From 0225e4d2a5acd5f331d439bef85bb7247f921cf6 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Wed, 21 Oct 2026 09:17:02 -0400 Subject: [PATCH] Startup: the first frame no longer waits for the system CJK/Hangul/Thai font search; SOLIDCRAFT_PROFILE_STARTUP prints startup steps (#4283) Co-authored-by: Claude Sonnet 5.5 --- apps/solidcraft/src/main.rs | 20 ++++++- crates/ui-egui/src/fonts.rs | 104 ++++++++++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 15 +++++- 3 files changed, 131 insertions(+), 8 deletions(-) diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 5b22a549b..b05116240 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -32,6 +32,15 @@ mod startup; use solidcraft_engine::{Session, io}; use solidcraft_ui_egui::{Services, SolveApp}; +/// `SOLIDCRAFT_PROFILE_STARTUP=1` prints the time since launch at each startup step. +fn mark(step: &str) { + static START: std::sync::OnceLock<(std::time::Instant, bool)> = std::sync::OnceLock::new(); + let (start, on) = START.get_or_init(|| (std::time::Instant::now(), solidcraft_engine::geom::env::var_os("PROFILE_STARTUP").is_some())); + if *on { + eprintln!("startup {:>6.0} ms {step}", start.elapsed().as_secs_f64() * 1000.0); + } +} + struct App { solve: SolveApp, /// The settings folder whose start marker the first frame clears (`startup::started`). @@ -46,6 +55,7 @@ impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { if self.frames < 2 { self.frames += 1; + mark(if self.frames == 1 { "first frame begins" } else { "second frame begins (first presented)" }); // A second frame right away, which means the first was presented: the app is up. ctx.request_repaint(); if self.frames == 2 { @@ -477,6 +487,7 @@ fn app_viewport() -> Result { const APP_ID: &str = solidcraft_engine::io::APP_ID; fn main() -> eframe::Result { + mark("main"); adopt_legacy_settings(); let mut safe_mode = startup::env_on(std::env::var(startup::SAFE_MODE_ENV).ok().as_deref()); let mut control_port: Option = solidcraft_engine::geom::env::var("CONTROL_PORT").and_then(|p| p.parse().ok()); @@ -587,13 +598,17 @@ fn main() -> eframe::Result { let created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let created_in_app = created.clone(); let starting = settings.clone(); + mark("run_native"); let result = eframe::run_native( "SolidCraft", options, Box::new(move |cc| { created_in_app.store(true, std::sync::atomic::Ordering::SeqCst); solidcraft_engine::crash::phase("app setup"); - solidcraft_ui_egui::fonts::setup_fonts(&cc.egui_ctx); + mark("window and device ready"); + solidcraft_ui_egui::fonts::setup_bundled_fonts(&cc.egui_ctx); + solidcraft_ui_egui::fonts::load_system_fonts_in_background(&cc.egui_ctx); + mark("fonts"); let mut app = SolveApp::new(Session::default(), services(cc)); app.apply_off_thread = Some(solidcraft_ui_egui::dialogs::APPLY_AT_ONCE); app.custom_titlebar = CUSTOM_TITLEBAR; @@ -611,6 +626,7 @@ fn main() -> eframe::Result { if let Some(p) = cc.storage.and_then(|s| solidcraft_ui_egui::prefs::stored(|k| s.get_string(k))).filter(|_| !safe_mode) { app.load_prefs(&p); } + mark("app state and prefs"); if let Some(rs) = &cc.wgpu_render_state { eprintln!("SolidCraft graphics: {:?}, MSAA {}x (requested {}x)", rs.adapter.get_info().backend, rs.msaa_samples, samples); solidcraft_engine::crash::phase("viewport pipelines (shader compile)"); @@ -628,6 +644,7 @@ fn main() -> eframe::Result { info.backend, info.name, info.driver, rs.msaa_samples )); } + mark("viewport pipelines"); if let Some(port) = control_port { let rx = control_server::start(port, cc.egui_ctx.clone()); app = app.with_control(rx); @@ -680,6 +697,7 @@ fn main() -> eframe::Result { } #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] let space_mouse = space_mouse::SpaceMouse::start(&cc.egui_ctx); + mark("app created"); solidcraft_engine::crash::phase("first frame"); Ok(Box::new(App { solve: app, diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 205927b9d..afc032bd4 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -97,7 +97,7 @@ fn install(ctx: &egui::Context, fonts: FontDefinitions) { } /// Install only the bundled definitions (also used by the offscreen scenario shell). -pub(crate) fn setup_bundled_fonts(ctx: &egui::Context) { +pub fn setup_bundled_fonts(ctx: &egui::Context) { install(ctx, base_font_definitions()); } @@ -659,10 +659,75 @@ pub fn fallback_order(language: &str) -> [&'static str; 4] { /// when one is chosen (see [`ui_font`]). #[cfg(not(target_arch = "wasm32"))] pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { - let cjk = find_system_cjk_font(); - let chinese = find_system_chinese_font().filter(|bytes| cjk.as_ref() != Some(bytes)); - let hangul = HANGUL_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); - let thai = THAI_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); + install_fonts(ctx, language, ui_font, Some(system_fallbacks())); +} + +/// The system fallback faces, searched for once and kept: reading them takes long on a system +/// with large CJK fonts, so the app starts that search on a thread and draws its first frame +/// with the bundled faces (see [`load_system_fonts_in_background`]). +#[cfg(not(target_arch = "wasm32"))] +struct SystemFonts { + cjk: Option>, + chinese: Option>, + hangul: Option>, + thai: Option>, +} + +#[cfg(not(target_arch = "wasm32"))] +static SYSTEM_FONTS: std::sync::OnceLock = std::sync::OnceLock::new(); + +#[cfg(not(target_arch = "wasm32"))] +fn system_fallbacks() -> &'static SystemFonts { + SYSTEM_FONTS.get_or_init(|| { + let cjk = find_system_cjk_font(); + let chinese = find_system_chinese_font().filter(|bytes| cjk.as_ref() != Some(bytes)); + let hangul = HANGUL_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); + let thai = THAI_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path))); + SystemFonts { cjk, chinese, hangul, thai } + }) +} + +/// Whether the system fallback faces have been searched for. +#[cfg(not(target_arch = "wasm32"))] +pub fn system_fonts_ready() -> bool { + SYSTEM_FONTS.get().is_some() +} + +/// Search for the system fallback faces on a thread and repaint when they are found. +#[cfg(not(target_arch = "wasm32"))] +pub fn load_system_fonts_in_background(ctx: &egui::Context) { + static STARTED: std::sync::Once = std::sync::Once::new(); + if SYSTEM_FONTS.get().is_some() { + return; + } + let mut first = false; + STARTED.call_once(|| first = true); + if !first { + return; + } + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("system-fonts".into()).spawn(move || { + system_fallbacks(); + ctx.request_repaint(); + }); + // Without a thread the first frame waits for them, as it always did. + if spawned.is_err() { + system_fallbacks(); + } +} + +/// [`setup_fonts_for`] with the system fallbacks that are there already, never waiting for the search. +#[cfg(not(target_arch = "wasm32"))] +pub fn setup_fonts_without_waiting(ctx: &egui::Context, language: &str, ui_font: &str) { + install_fonts(ctx, language, ui_font, SYSTEM_FONTS.get()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn install_fonts(ctx: &egui::Context, language: &str, ui_font: &str, system: Option<&SystemFonts>) { + let (cjk, chinese, hangul, thai) = match system { + Some(f) => (f.cjk.clone(), f.chinese.clone(), f.hangul.clone(), f.thai.clone()), + None => (None, None, None, None), + }; let mut fonts = base_font_definitions(); if let Some(font) = self::ui_font(ui_font) { fonts = with_ui_font(fonts, font); @@ -769,6 +834,19 @@ fn find_chinese_font_in(dirs: &[std::path::PathBuf]) -> Option> { /// Web installs the bundled faces synchronously; Japanese is fetched by the shell on demand. /// Preserve that downloaded face when preferences change later in the session. +#[cfg(target_arch = "wasm32")] +pub fn load_system_fonts_in_background(_ctx: &egui::Context) {} + +#[cfg(target_arch = "wasm32")] +pub fn system_fonts_ready() -> bool { + true +} + +#[cfg(target_arch = "wasm32")] +pub fn setup_fonts_without_waiting(ctx: &egui::Context, language: &str, ui_font: &str) { + setup_fonts_for(ctx, language, ui_font); +} + #[cfg(target_arch = "wasm32")] pub fn setup_fonts_for(ctx: &egui::Context, language: &str, ui_font: &str) { let previous = ctx.data(|d| d.get_temp::(installed_fonts_id())); @@ -812,6 +890,22 @@ pub(crate) fn test_context() -> egui::Context { mod tests { use super::*; + /// The system faces are searched for on a thread; installing fonts before they are found does + /// not wait for the search and still gives the bundled faces. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn system_fonts_load_in_the_background_and_installing_does_not_wait() { + let ctx = egui::Context::default(); + setup_fonts_without_waiting(&ctx, "en", ""); + assert!(ctx.data(|d| d.get_temp::(installed_fonts_id())).is_some()); + load_system_fonts_in_background(&ctx); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !system_fonts_ready() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(system_fonts_ready()); + } + /// Whether a face of the Proportional family has `c`. Checked in the font data: /// `Fonts::has_glyph` misses a glyph in the face that also gives the replacement glyph. fn proportional_draws(fonts: &egui::FontDefinitions, c: char) -> bool { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b8c657e56..54d7f776f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -504,6 +504,8 @@ pub struct SolveApp { applied_fonts_language: String, /// The interface font the fonts were last set up with (`Prefs::ui_font`). applied_ui_font: String, + /// The fonts installed include the system's fallback faces. + applied_system_fonts: bool, } impl SolveApp { @@ -605,6 +607,7 @@ impl SolveApp { docs: documents::Documents::default(), applied_fonts_language: "en".into(), applied_ui_font: String::new(), + applied_system_fonts: false, } } @@ -1502,10 +1505,18 @@ impl SolveApp { pub fn ui(&mut self, ui: &mut egui::Ui) { expression_complete::begin_frame(ui.ctx()); let t0 = now_ms(); - if self.preferences.language != self.applied_fonts_language || self.preferences.ui_font != self.applied_ui_font { + // The first frames draw with the bundled faces while the system's CJK, Hangul and Thai + // faces are read on a thread; the fonts are installed again once they are there. + crate::fonts::load_system_fonts_in_background(ui.ctx()); + let system_fonts = crate::fonts::system_fonts_ready(); + if self.preferences.language != self.applied_fonts_language + || self.preferences.ui_font != self.applied_ui_font + || (system_fonts && !self.applied_system_fonts) + { self.applied_fonts_language.clone_from(&self.preferences.language); self.applied_ui_font.clone_from(&self.preferences.ui_font); - crate::fonts::setup_fonts_for(ui.ctx(), &self.preferences.language, &self.preferences.ui_font); + self.applied_system_fonts = system_fonts; + crate::fonts::setup_fonts_without_waiting(ui.ctx(), &self.preferences.language, &self.preferences.ui_font); } let _language = crate::i18n::scope(&self.preferences.language); let mut report_input = None;