Type: scan system fonts off the UI thread (#3021) (#3030)

* Type: scan system fonts off the UI thread (#3021)

The first `photocraft_text::shared()` call scans every installed font, and
nothing made that call before the Type tool's options bar drew its font
menu, so the scan ran inside a UI frame (over 60 s on some Macs, #2518).

- photocraft-text: `warm_shared()` starts the scan on a background thread;
  `try_shared()` returns the engine without blocking (None while the scan
  runs, started there if nobody warmed it; built in place on the web, in
  tests, if the thread can't start or the worker died). `shared()` keeps
  its blocking behaviour for engine commands.
- The desktop app warms the fonts at start-up.
- Font menus that draw every frame (options bar, Character, Glyphs and the
  Character/Paragraph Styles family menus) show a disabled "Loading fonts…"
  box and repaint until the scan is done. "Loading fonts…" is in all 16
  catalogs.

Complements #2644 (CoreText discovery on macOS): this changes where the
scan runs, not how fonts are discovered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Type: axis sliders wait for the background font scan too

#2996 (landed on main) added axis_sliders, which called the blocking
photocraft_text::shared() every frame; use try_shared() so the Character
section doesn't stall while the scan runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-11 16:25:57 -04:00
1 parent 3e45d769fa
commit 7aba2bd305
21 files changed
+199 -22

No files matched your search

+2
View File
@@ -155,6 +155,8 @@ fn main() -> eframe::Result {
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
crash_guard::install_hook();
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
photocraft_ui_egui::type_tool::warm_fonts();
let mut control_port: Option<u16> = None;
let mut control_arg_errors: Vec<String> = Vec::new();
if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
+123 -6
View File
@@ -137,14 +137,131 @@ impl TextEngine {
}
}
static SHARED: warm::Warm<std::sync::Mutex<TextEngine>> = warm::Warm::new();
/// Whether [`shared`] scans the installed fonts (native builds, outside tests, unless
/// `PHOTOCRAFT_NO_SYSTEM_FONTS` is set). Without the scan it is cheap to build.
fn uses_system_fonts() -> bool {
cfg!(not(target_arch = "wasm32")) && !cfg!(test) && std::env::var_os("PHOTOCRAFT_NO_SYSTEM_FONTS").is_none()
}
fn new_shared() -> std::sync::Mutex<TextEngine> {
std::sync::Mutex::new(if uses_system_fonts() { TextEngine::with_system_fonts() } else { TextEngine::new() })
}
/// A process-wide engine for callers without their own (bundled fonts only on the web; bundled
/// plus system fonts elsewhere). Locking is cheap relative to layout.
/// plus system fonts elsewhere). Locking is cheap relative to layout. The first call scans the
/// installed fonts and blocks until that is done (or until [`warm_shared`]'s scan finishes), so
/// code that runs every UI frame uses [`try_shared`] instead.
pub fn shared() -> &'static std::sync::Mutex<TextEngine> {
static ENGINE: std::sync::OnceLock<std::sync::Mutex<TextEngine>> = std::sync::OnceLock::new();
ENGINE.get_or_init(|| {
let use_system = cfg!(not(target_arch = "wasm32")) && !cfg!(test) && std::env::var_os("PHOTOCRAFT_NO_SYSTEM_FONTS").is_none();
std::sync::Mutex::new(if use_system { TextEngine::with_system_fonts() } else { TextEngine::new() })
})
SHARED.get_or_init(new_shared)
}
/// [`shared`] without blocking: `None` while the system font scan is still running on its
/// background thread (started here if [`warm_shared`] has not started it yet). Without system
/// fonts (web, tests) the engine is cheap and this always returns it.
pub fn try_shared() -> Option<&'static std::sync::Mutex<TextEngine>> {
SHARED.try_get(new_shared, uses_system_fonts())
}
/// Starts building [`shared`] (the system font scan) on a background thread, so the Type tool's
/// font menus don't stall the UI when they first draw. Call once at startup; calling again does
/// nothing.
pub fn warm_shared() {
let _ = try_shared();
}
mod warm {
use std::sync::{Mutex, OnceLock, PoisonError};
use std::thread::JoinHandle;
/// A lazily built value whose (slow) construction can run on a background thread.
pub(crate) struct Warm<T: 'static> {
cell: OnceLock<T>,
scan: Mutex<Option<JoinHandle<()>>>,
}
impl<T: Send + Sync + 'static> Warm<T> {
pub(crate) const fn new() -> Self {
Self { cell: OnceLock::new(), scan: Mutex::new(None) }
}
/// The value, building it on this thread (or waiting for the background build).
pub(crate) fn get_or_init(&'static self, init: fn() -> T) -> &'static T {
self.cell.get_or_init(init)
}
/// The value if it is built. With `background`, the first call starts building it on a
/// worker thread and returns `None` until that finishes; otherwise (or when no thread can
/// be started, or the worker died) it is built here.
pub(crate) fn try_get(&'static self, init: fn() -> T, background: bool) -> Option<&'static T> {
if let Some(v) = self.cell.get() {
return Some(v);
}
if !background {
return Some(self.get_or_init(init));
}
let mut scan = self.scan.lock().unwrap_or_else(PoisonError::into_inner);
match scan.as_ref() {
Some(worker) if !worker.is_finished() => None,
// Finished: the value is set, or the worker panicked and this thread retries.
Some(_) => {
drop(scan);
Some(self.get_or_init(init))
}
None => match std::thread::Builder::new().name("photocraft-font-scan".into()).spawn(move || {
self.get_or_init(init);
}) {
Ok(worker) => {
*scan = Some(worker);
self.cell.get()
}
Err(_) => {
drop(scan);
Some(self.get_or_init(init))
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::Warm;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
static OPEN: AtomicBool = AtomicBool::new(false);
/// A slow build: waits until the test opens the gate (at most 2 s).
fn slow() -> u32 {
let start = Instant::now();
while !OPEN.load(Ordering::SeqCst) && start.elapsed() < Duration::from_secs(2) {
std::thread::sleep(Duration::from_millis(1));
}
7
}
#[test]
fn try_get_does_not_block_while_the_background_build_runs() {
static W: Warm<u32> = Warm::new();
let start = Instant::now();
assert_eq!(W.try_get(slow, true), None, "the first call starts the build and returns at once");
assert_eq!(W.try_get(slow, true), None, "still building");
assert!(start.elapsed() < Duration::from_secs(1), "try_get blocked for {:?}", start.elapsed());
OPEN.store(true, Ordering::SeqCst);
let deadline = Instant::now() + Duration::from_secs(10);
let v = loop {
if let Some(v) = W.try_get(slow, true) {
break *v;
}
assert!(Instant::now() < deadline, "the background build never finished");
std::thread::sleep(Duration::from_millis(1));
};
assert_eq!(v, 7);
assert_eq!(W.get_or_init(slow), &7);
}
}
}
#[cfg(test)]
+1
View File
@@ -2575,6 +2575,7 @@ cameraData Lens Objektiv
Snap to Origin Přichytit k počátku
Search settings… Hledat nastavení…
No matching settings Žádná odpovídající nastavení
Loading fonts… Načítání písem…
# Select and Mask view modes (#1754)
Onion Skin Cibulová slupka
Marching Ants Pochodující mravenci
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -2606,6 +2606,7 @@ cameraData Lens Objektiv
Snap to Origin An Ursprung ausrichten
Search settings… Einstellungen durchsuchen…
No matching settings Keine passenden Einstellungen
Loading fonts… Schriften werden geladen…
# Select and Mask view modes (#1754)
Onion Skin Zwiebelschicht
Marching Ants Laufende Ameisen
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3666,6 +3666,7 @@ cameraData Lens Φακός
Snap to Origin Προσκόλληση στην αρχή
Search settings… Αναζήτηση ρυθμίσεων…
No matching settings Δεν βρέθηκαν ρυθμίσεις
Loading fonts… Φόρτωση γραμματοσειρών…
# Select and Mask view modes (#1754)
Onion Skin Φλούδα κρεμμυδιού
Marching Ants Κινούμενο περίγραμμα
Can't render this file because it contains an unexpected character in line 1000 and column 18.
+1
View File
@@ -2647,6 +2647,7 @@ cameraData Lens Objetivo
Snap to Origin Ajustar a origen
Search settings… Buscar ajustes…
No matching settings No hay ajustes que coincidan
Loading fonts… Cargando fuentes…
# Select and Mask view modes (#1754)
Onion Skin Papel cebolla
Marching Ants Hormigas en marcha
Can't render this file because it contains an unexpected character in line 4 and column 47.
+1
View File
@@ -2984,6 +2984,7 @@ cameraData Lens Objectif
Snap to Origin Aligner sur l'origine
Search settings… Rechercher des réglages…
No matching settings Aucun réglage correspondant
Loading fonts… Chargement des polices…
# Select and Mask view modes (#1754)
Onion Skin Pelure d'oignon
Marching Ants Fourmis en marche
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -2971,6 +2971,7 @@ cameraData Lens Lensa
Snap to Origin Jepret ke Titik Asal
Search settings… Cari pengaturan…
No matching settings Tidak ada pengaturan yang cocok
Loading fonts… Memuat font…
# Select and Mask view modes (#1754)
Onion Skin Kulit Bawang
Marching Ants Semut Berbaris
Can't render this file because it contains an unexpected character in line 4 and column 47.
+1
View File
@@ -2638,6 +2638,7 @@ cameraData Lens Obiettivo
Snap to Origin Aggancia all'origine
Search settings… Cerca impostazioni…
No matching settings Nessuna impostazione corrispondente
Loading fonts… Caricamento font…
# Select and Mask view modes (#1754)
Onion Skin Velina
Marching Ants Formiche in marcia
Can't render this file because it contains an unexpected character in line 2586 and column 53.
+1
View File
@@ -3580,6 +3580,7 @@ cameraData Lens レンズ
Snap to Origin 原点にスナップ
Search settings… 設定を検索…
No matching settings 一致する設定はありません
Loading fonts… フォントを読み込み中…
# Select and Mask view modes (#1754)
Onion Skin オニオンスキン
Marching Ants 点線の境界
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3149,6 +3149,7 @@ cameraData Lens 렌즈
Snap to Origin 원점에 스냅
Search settings… 설정 검색…
No matching settings 일치하는 설정 없음
Loading fonts… 글꼴 불러오는 중…
# Select and Mask view modes (#1754)
Onion Skin 어니언 스킨
Marching Ants 점선 윤곽
Can't render this file because it contains an unexpected character in line 3095 and column 53.
+1
View File
@@ -3725,6 +3725,7 @@ cameraData Lens Lens
Search settings… Instellingen zoeken…
No matching settings Geen overeenkomende instellingen
PhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer
Loading fonts… Lettertypen laden…
# Select and Mask view modes (#1754)
Onion Skin Uienschil
Marching Ants Mierenmars
Can't render this file because it contains an unexpected character in line 8 and column 34.
+1
View File
@@ -3582,6 +3582,7 @@ cameraData Lens Obiektyw
Snap to Origin Przyciągnij do początku
Search settings… Szukaj ustawień…
No matching settings Brak pasujących ustawień
Loading fonts… Wczytywanie czcionek…
# Select and Mask view modes (#1754)
Onion Skin Skórka cebuli
Marching Ants Maszerujące mrówki
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -2989,6 +2989,7 @@ cameraData Lens Lente
Snap to Origin Ajustar à origem
Search settings… Pesquisar configurações…
No matching settings Nenhuma configuração encontrada
Loading fonts… Carregando fontes…
# Select and Mask view modes (#1754)
Onion Skin Papel vegetal
Marching Ants Formigas marchando
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -2907,6 +2907,7 @@ cameraData Lens Объектив
Rasterize Layer Style Растрировать стиль слоя
Search settings… Поиск настроек…
No matching settings Нет подходящих настроек
Loading fonts… Загрузка шрифтов…
# Select and Mask view modes (#1754)
Onion Skin Калька
Marching Ants Бегущие муравьи
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3656,6 +3656,7 @@ cameraData Lens Об'єктив
Search settings… Пошук налаштувань…
No matching settings Немає відповідних налаштувань
PhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана
Loading fonts… Завантаження шрифтів…
# Select and Mask view modes (#1754)
Onion Skin Калька
Marching Ants Мурашки
Can't render this file because it contains an unexpected character in line 1356 and column 18.
+1
View File
@@ -2576,6 +2576,7 @@ cameraData Lens 镜头
Snap to Origin 贴紧原点
Search settings… 搜索设置…
No matching settings 没有匹配的设置
Loading fonts… 正在加载字体…
# Select and Mask view modes (#1754)
Onion Skin 洋葱皮
Marching Ants 蚂蚁线
Can't render this file because it contains an unexpected character in line 2528 and column 53.
+1
View File
@@ -2546,6 +2546,7 @@ cameraData Lens 鏡頭
Snap to Origin 靠齊原點
Search settings… 搜尋設定…
No matching settings 沒有符合的設定
Loading fonts… 正在載入字體…
# Select and Mask view modes (#1754)
Onion Skin 洋蔥皮
Marching Ants 螞蟻線
Can't render this file because it contains an unexpected character in line 6 and column 47.
@@ -158,6 +158,8 @@ fn every_theme_shows_the_type_options() {
// text", so there was no font, style or size control while typing.
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
// The font menus show "Loading fonts…" until the font scan is done (#3021): wait for it.
let _ = photocraft_text::shared();
for theme in crate::theme::ThemeKind::ALL {
let (mut app, _, _) = app();
app.ui.tool = Tool::Type;
+7
View File
@@ -509,6 +509,9 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s
/// Searchable family combo box.
fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String, preview: photocraft_engine::prefs::FontPreview) -> bool {
if !crate::type_tool::fonts_ready(ui, 140.0) {
return false;
}
let mut shown = if current.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { current.clone() };
let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview);
if changed {
@@ -594,6 +597,10 @@ pub fn insert_glyph(app: &mut PhotocraftApp, g: &str) -> bool {
}
pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// Every glyph cell needs the font database: wait for the font scan without blocking.
if !crate::type_tool::fonts_ready(ui, 260.0) {
return;
}
let t = Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
let (family, style) = glyph_font(app);
+49 -16
View File
@@ -1074,8 +1074,10 @@ fn axis_label(tag: &str) -> String {
/// One slider row per variable-font axis of the style's font, below the font style (#2985).
fn axis_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::text::CharStyle) {
// Drawn every frame: no sliders until the background font scan is done (#3021).
let Some(engine) = photocraft_text::try_shared() else { return };
let axes = {
let faces = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner).fonts.faces(&c.font_family);
let faces = engine.lock().unwrap_or_else(PoisonError::into_inner).fonts.faces(&c.font_family);
slider_axes(&faces, c.italic)
};
let t = crate::theme::Tokens::get(ui.ctx());
@@ -1105,8 +1107,11 @@ fn axis_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::
/// PSD text can identify a face only by its PostScript name. Show its real subfamily too.
pub(crate) fn selected_style(style: &photocraft_doc::text::CharStyle) -> String {
if let Some(ps) = &style.postscript_name {
let faces = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(&style.font_family);
// Drawn every frame: while the font scan runs, the stored style name stands in.
if let Some(ps) = &style.postscript_name
&& let Some(engine) = photocraft_text::try_shared()
{
let faces = engine.lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(&style.font_family);
if let Some(face) = faces.into_iter().find(|f| f.postscript_name.as_ref() == Some(ps)) {
return face.style;
}
@@ -1121,6 +1126,26 @@ pub fn style_label(style: &str) -> String {
style.split(' ').map(|w| crate::i18n::tr_ctx(crate::i18n::current(), "fontWeight", w)).collect::<Vec<_>>().join(" ")
}
/// Starts scanning the installed fonts on a background thread (desktop start-up), so choosing
/// the Type tool doesn't stall the UI while they are read (#3021). Does nothing on the web.
pub fn warm_fonts() {
photocraft_text::warm_shared();
}
/// Whether the font database is ready. The installed fonts are scanned on a background thread
/// from launch (`photocraft_text::warm_shared`); until that finishes, font menus draw this
/// disabled "Loading fonts…" box `width` wide instead of blocking the UI, and a repaint picks the
/// menus up once the scan is done.
pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool {
if photocraft_text::try_shared().is_some() {
return true;
}
let label = tl!("Loading fonts…").to_string();
ui.add_enabled_ui(false, |ui| crate::widgets::dropdown(ui, "fonts-loading", &mut label.clone(), &[(label.clone(), label.as_str())], width));
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
false
}
/// Searchable font-family combo box.
fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview) -> bool {
family_picker_in(ui, "type-font", current, width, &families(), preview)
@@ -1404,18 +1429,21 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.ui.status_error = true;
}
}
if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview) {
app.ui.tool_options.type_font = fam.clone();
let st = styles(&fam);
style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };
app.ui.tool_options.type_style = style.clone();
apply(app, ui.ctx(), json!({"font": fam}));
}
let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect();
let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();
if crate::widgets::dropdown(ui, "type-style", &mut style, &opts_ref, 110.0) {
app.ui.tool_options.type_style = style.clone();
apply(app, ui.ctx(), json!({"fontStyle": style}));
// Font family and style menus (one placeholder in their place while the fonts load).
if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) {
if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview) {
app.ui.tool_options.type_font = fam.clone();
let st = styles(&fam);
style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };
app.ui.tool_options.type_style = style.clone();
apply(app, ui.ctx(), json!({"font": fam}));
}
let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect();
let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();
if crate::widgets::dropdown(ui, "type-style", &mut style, &opts_ref, 110.0) {
app.ui.tool_options.type_style = style.clone();
apply(app, ui.ctx(), json!({"fontStyle": style}));
}
}
let (r, _) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover());
crate::icons::paint(ui, r, "type", 13.0, t.icon);
@@ -1715,13 +1743,18 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa
let full = ui.available_width();
let w = field_width(full, 2, LABEL_W);
let mut fam = c.font_family.clone();
let mut ready = true;
row(ui, &mut |ui| {
if font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview) {
ready = fonts_ready(ui, full);
if ready && font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview) {
app.ui.tool_options.type_font = fam.clone();
apply(app, ui.ctx(), json!({"font": fam}));
}
});
row(ui, &mut |ui| {
if !ready {
return;
}
let mut style = selected_style(&c);
let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect();
let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();