diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 8ddaa0b775..5acbe66de4 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -78,19 +78,51 @@ pub fn runs_in_background(command: &str) -> Option<(&'static str, &'static str)> IN_BACKGROUND.iter().find(|(c, ..)| *c == command).map(|(c, name, _)| (*c, *name)) } +/// Background exports that render map, layout, report, or scene text with installed fonts. +fn uses_fonts(command: &str) -> bool { + matches!(command, "share.exportMap" | "layout.export" | "report.export" | "map.exportOrbit" | "map.exportBlock") +} + +#[cfg(test)] +thread_local! { + static TEST_CJK_SCAN_PENDING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +fn cjk_scan_pending() -> bool { + #[cfg(test)] + if TEST_CJK_SCAN_PENDING.get() { + return true; + } + rustgis_render::fonts::cjk_roots_pending() +} + /// `command`'s export written here: it says what it wrote. pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult { let &(_, name, start) = IN_BACKGROUND.iter().find(|(c, ..)| *c == command).ok_or_else(|| format!("{command} isn't an export"))?; + if uses_fonts(command) && cjk_scan_pending() { + return Err("CJK font folder scan is still running; try exporting again in a moment".into()); + } let owner = s.continuation()?; owner.check()?; let current = owner.clone(); let still = std::sync::Arc::new(move || current.check().is_ok()); // The probe keeps authority checks at file commit even when the user cannot cancel this run. let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() }; - let wrote = crate::render::rustgis_tiles::cache::with_still(still, || { + let (mut wrote, pending_cjk) = crate::render::rustgis_tiles::cache::with_still(still, || { let work = start(s, p)?; - written_under(name, &control, work) + if uses_fonts(command) { + let (res, hit) = rustgis_render::fonts::track_pending_cjk(|| written_under(name, &control, work)); + Ok::<_, String>((res?, hit)) + } else { + Ok((written_under(name, &control, work)?, false)) + } })?; + if pending_cjk { + wrote.diagnostics.push(( + rustgis_data::diagnostics::Severity::Warning, + "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing.".into(), + )); + } s.check_continuation(&owner) .map_err(|why| completion_with_notes(command, wrote.written_path.as_deref(), &wrote.completion_notes(), why))?; said(s, wrote) @@ -375,16 +407,27 @@ impl ExportRun { /// Writes the file, or stages it if installing it needs the live session. `control` stops the /// work and counts its progress (see [`rustgis_analysis::control`]). A cancelled export leaves /// no file, or the one there before. + /// + /// On Linux, font-drawing exports wait for any in-flight background CJK font-folder scan off + /// the UI thread so exported files do not omit CJK glyphs; that one-time bounded scan + /// (`MAX_DIRS = 2_000`, `MAX_FILES = 20_000`) does not observe `control` Cancel while waiting. pub fn run(self, control: &std::sync::Arc) -> Result { let inputs = self.started.capture_inputs.then(rustgis_data::provenance::Capture::start); let ExportRun { name, work, started } = self; + let command = started.command; let owner = started.owner; owner.check()?; let current = owner.clone(); let still = std::sync::Arc::new(move || current.check().is_ok()); // A bug in a writer must not take the app down. let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - crate::render::rustgis_tiles::cache::with_still(still, || written_under(name, control, work)) + crate::render::rustgis_tiles::cache::with_still(still, || { + if uses_fonts(command) { + rustgis_render::fonts::with_blocking_cjk_scan(|| written_under(name, control, work)) + } else { + written_under(name, control, work) + } + }) })) .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))) .map(|w| Wrote { owner: Some(owner), crs_used: rustgis_data::raster::crs::take_used(), ..w }); @@ -521,4 +564,27 @@ mod tests { }); assert!(written_under("Export Raster", &control, work).err().unwrap().contains("was cancelled")); } + + #[test] + fn write_here_rejects_font_exports_while_cjk_scan_is_pending() { + struct PendingGuard; + impl Drop for PendingGuard { + fn drop(&mut self) { + TEST_CJK_SCAN_PENDING.set(false); + } + } + + let mut s = Session::new(crate::Project::default()); + TEST_CJK_SCAN_PENDING.set(true); + let _guard = PendingGuard; + + // Font-drawing synchronous exports fail fast rather than blocking the UI thread or writing missing glyphs. + let err = write_here(&mut s, &serde_json::json!({"path": "out.png"}), "share.exportMap").unwrap_err(); + assert!(err.contains("CJK font folder scan is still running"), "{err}"); + + // Non-font exports (e.g. tables) are unaffected by a pending CJK scan and proceed to normal validation. + let table_err = + write_here(&mut s, &serde_json::json!({"layer": "NoSuchLayer", "path": "out.csv"}), "share.exportTable").unwrap_err(); + assert!(!table_err.contains("CJK font folder scan"), "{table_err}"); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 07a6d66ec1..8eb1bc8431 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1901,6 +1901,12 @@ impl Session { // A command may change a map's projection, or add layers to it. if s.depth == 0 { s.note_shown_systems(); + if !ui_owns_cjk_scan_notice() + && let Some(summary) = take_cjk_scan_summary_for_session() + && let Some(msg) = summary.notice() + { + s.notify(msg, false); + } } // Native sessions without a drawing loop recover their own failed overviews. // Named callers and sealed completions do not initiate unrelated maintenance. @@ -4325,3 +4331,42 @@ impl Session { self.project.gp_history.push(record); } } + +/// Process-wide ownership of the one-shot CJK font-folder scan summary. Set by a UI front end so +/// neither the live session nor any temporary `Session::new` copy consumes the summary inside +/// [`Session::run`] before the UI can translate and emit it. +static UI_OWNS_CJK_SCAN_NOTICE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Marks this process as having a UI front end that takes and translates the one-shot CJK +/// font-folder scan summary itself, leaving it untouched in [`Session::run`]. +pub fn claim_ui_cjk_scan_notice() { + UI_OWNS_CJK_SCAN_NOTICE.store(true, std::sync::atomic::Ordering::Release); +} + +/// Whether a UI front end owns taking and translating the process-wide CJK scan summary. +pub fn ui_owns_cjk_scan_notice() -> bool { + #[cfg(test)] + if let Some(overridden) = TEST_UI_OWNS_CJK_SCAN_NOTICE.get() { + return overridden; + } + UI_OWNS_CJK_SCAN_NOTICE.load(std::sync::atomic::Ordering::Acquire) +} + +#[cfg(test)] +thread_local! { + /// Thread-local override for [`take_cjk_scan_summary_for_session`] so tests can exercise + /// `Session::run`'s CJK scan notice wiring in parallel without mutating the global font cache. + static TEST_CJK_SCAN_SUMMARY: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; + /// Thread-local override for [`ui_owns_cjk_scan_notice`] so parallel unit tests can cover + /// headless sessions even after another test claims UI ownership. + static TEST_UI_OWNS_CJK_SCAN_NOTICE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +fn take_cjk_scan_summary_for_session() -> Option { + #[cfg(test)] + if let Some(summary) = TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| slot.as_mut().map(Option::take)) { + return summary; + } + rustgis_render::fonts::take_cjk_scan_summary() +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7f04e0c3c7..1c5bb974b0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -63093,3 +63093,90 @@ fn a_transparency_reads_back_without_float_noise() { assert_eq!(crate::cmd::project::percent(33.3), json!(33.3)); assert_eq!(crate::cmd::project::percent(0.0), json!(0.0)); } + +/// Headless sessions emit the CJK font-folder scan notice once through `Session::run` when a +/// fallback scan was lossy, stay silent when clean, and leave the summary untouched across every +/// `Session::new` copy once a UI shell claims process-wide ownership for translation. +#[test] +fn headless_session_run_emits_cjk_scan_notice_only_when_lossy() { + use rustgis_render::fonts::CjkRootScanSummary; + + struct SummaryGuard; + impl SummaryGuard { + fn set(summary: Option) -> Self { + crate::TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| *slot = Some(summary)); + Self + } + } + impl Drop for SummaryGuard { + fn drop(&mut self) { + crate::TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| *slot = None); + } + } + + struct UiNoticeGuard; + impl UiNoticeGuard { + fn set(value: bool) -> Self { + crate::TEST_UI_OWNS_CJK_SCAN_NOTICE.set(Some(value)); + Self + } + } + impl Drop for UiNoticeGuard { + fn drop(&mut self) { + crate::TEST_UI_OWNS_CJK_SCAN_NOTICE.set(None); + } + } + + let lossy = CjkRootScanSummary { + truncated_dirs: 2, + unreadable_dirs: 1, + entry_errors: 0, + thread_spawn_failed: false, + sample_path: Some(std::path::PathBuf::from("/run/host/fonts")), + }; + + // Lossy summary on a headless session emits one English notice and consumes it; clean/absent stay silent. + { + let _ui_guard = UiNoticeGuard::set(false); + assert!(!crate::ui_owns_cjk_scan_notice()); + let mut headless = Session::new(Project::default()); + { + let _guard = SummaryGuard::set(Some(lossy.clone())); + let mark = headless.notice_mark(); + headless.run("connection.list", &Value::Null).unwrap(); + let notices = headless.notices_since(mark); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(!notices[0].error); + assert!(notices[0].text.contains("CJK font folder search stopped early"), "{}", notices[0].text); + assert!(notices[0].text.contains("2 folder(s) reached the scan limit"), "{}", notices[0].text); + assert!(notices[0].text.contains("1 unreadable folder(s)"), "{}", notices[0].text); + assert!(notices[0].text.contains("/run/host/fonts"), "{}", notices[0].text); + + // One-shot: a subsequent command emits nothing. + let mark2 = headless.notice_mark(); + headless.run("connection.list", &Value::Null).unwrap(); + assert!(headless.notices_since(mark2).is_empty(), "{:?}", headless.notices_since(mark2)); + } + + for clean in [Some(CjkRootScanSummary::default()), None] { + let _guard = SummaryGuard::set(clean); + let mark = headless.notice_mark(); + headless.run("connection.list", &Value::Null).unwrap(); + assert!(headless.notices_since(mark).is_empty(), "clean scan must stay silent: {:?}", headless.notices_since(mark)); + } + } + + // Once a UI front end claims process-wide ownership, even a separate temporary Session::new + // copy leaves the summary untouched inside Session::run so ui-egui can translate it. + crate::claim_ui_cjk_scan_notice(); + assert!(crate::ui_owns_cjk_scan_notice()); + let mut copy = Session::new(Project::default()); + { + let _guard = SummaryGuard::set(Some(lossy)); + let mark = copy.notice_mark(); + copy.run("connection.list", &Value::Null).unwrap(); + assert!(copy.notices_since(mark).is_empty(), "{:?}", copy.notices_since(mark)); + let still_pending = crate::TEST_CJK_SCAN_SUMMARY.with_borrow(|slot| slot.as_ref().and_then(Option::as_ref).is_some()); + assert!(still_pending, "copy session must not consume the CJK scan summary once UI owns it"); + } +} diff --git a/crates/render/src/families.rs b/crates/render/src/families.rs index ac93af5a67..4848693aac 100644 --- a/crates/render/src/families.rs +++ b/crates/render/src/families.rs @@ -82,6 +82,7 @@ pub fn warm_up() { if WARMING.swap(true, Ordering::Relaxed) { return; } + crate::fonts::enable_async_cjk_scan(); #[cfg(not(target_arch = "wasm32"))] if std::thread::Builder::new() .name("font-index".into()) @@ -201,9 +202,14 @@ fn font_dirs() -> Vec { } else if cfg!(target_os = "android") { // Android's app home has no system fonts; manufacturer faces can live on /product. dirs.extend(crate::fonts::ANDROID_FONT_DIRS.iter().map(PathBuf::from)); + } else if cfg!(target_os = "linux") { + dirs.extend(crate::fonts::linux_font_roots_with( + std::env::var_os("XDG_DATA_HOME").as_deref(), + home.as_deref().map(Path::as_os_str), + )); } else { dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(PathBuf::from)); - match std::env::var_os("XDG_DATA_HOME") { + match std::env::var_os("XDG_DATA_HOME").filter(|v| crate::fonts::is_posix_absolute(v)) { Some(d) => dirs.push(PathBuf::from(d).join("fonts")), None => dirs.extend(home.iter().map(|h| h.join(".local").join("share").join("fonts"))), } @@ -518,4 +524,28 @@ mod tests { let table = [0u8, 0, 0, 1, 0, 18, 0, 3, 0, 1, 4, 9, 0, 1, 0xff, 0xff, 0, 0]; assert_eq!(name(&table, 1), None); } + + #[test] + fn linux_font_roots_include_flatpak_host_and_xdg_roots() { + use std::ffi::OsStr; + + let dirs = crate::fonts::linux_font_roots_with(Some(OsStr::new("/xdg/data")), Some(OsStr::new("/home/alice"))); + assert_eq!( + dirs, + vec![ + PathBuf::from("/usr/share/fonts"), + PathBuf::from("/usr/local/share/fonts"), + PathBuf::from("/run/host/fonts"), + PathBuf::from("/run/host/local-fonts"), + PathBuf::from("/run/host/user-fonts"), + PathBuf::from("/xdg/data/fonts"), + PathBuf::from("/home/alice/.fonts"), + ] + ); + let fallback = crate::fonts::linux_font_roots_with(None, Some(OsStr::new("/home/alice"))); + assert!(fallback.contains(&PathBuf::from("/home/alice/.local/share/fonts"))); + + let deduped = crate::fonts::linux_font_roots_with(Some(OsStr::new("/usr/share")), Some(OsStr::new("/home/alice"))); + assert_eq!(deduped.iter().filter(|p| *p == &PathBuf::from("/usr/share/fonts")).count(), 1); + } } diff --git a/crates/render/src/fonts.rs b/crates/render/src/fonts.rs index fb011ceb41..49ccb90333 100644 --- a/crates/render/src/fonts.rs +++ b/crates/render/src/fonts.rs @@ -36,9 +36,42 @@ pub struct UiFonts { } /// Reads a regular font within its budget, including a file that grows after metadata is read. +/// Uses a nonblocking open on Linux and macOS so a named pipe swapped into a candidate path can +/// never block font discovery waiting for a writer. fn read_bounded(path: impl AsRef, limit: u64) -> Option> { use std::io::Read; - let file = std::fs::File::open(path).ok()?; + let path = path.as_ref(); + let pre_meta = std::fs::metadata(path).ok()?; + if !pre_meta.is_file() || pre_meta.len() > limit { + return None; + } + let mut open = std::fs::OpenOptions::new(); + open.read(true); + #[cfg(all( + target_os = "linux", + any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "x86", + target_arch = "arm", + target_arch = "riscv64", + target_arch = "powerpc64", + target_arch = "s390x", + target_arch = "loongarch64" + ) + ))] + { + use std::os::unix::fs::OpenOptionsExt; + // Linux asm-generic `O_NONBLOCK` (`0o4000`). + open.custom_flags(0o4000); + } + #[cfg(target_os = "macos")] + { + use std::os::unix::fs::OpenOptionsExt; + // macOS/BSD `O_NONBLOCK` (`0x0004`). + open.custom_flags(0x0004); + } + let file = open.open(path).ok()?; let meta = file.metadata().ok()?; if !meta.is_file() || meta.len() > limit { return None; @@ -48,12 +81,16 @@ fn read_bounded(path: impl AsRef, limit: u64) -> Option (bytes.len() as u64 <= limit).then_some(bytes) } -fn read(path: &str) -> Option> { +fn read_path(path: &std::path::Path) -> Option> { let bytes = read_bounded(path, MAX_FONT_BYTES as u64)?; ab_glyph::FontRef::try_from_slice(&bytes).ok()?; Some(bytes) } +fn read(path: &str) -> Option> { + read_path(std::path::Path::new(path)) +} + /// The weight the semibold face is drawn at where it is a variable font (#591): macOS's system /// font is one file for every weight, drawn at its default 400 unless told otherwise. 600 is /// semibold, as the static faces used elsewhere (Segoe UI Semibold, Inter SemiBold) are; a face @@ -96,6 +133,17 @@ pub fn ui_fonts() -> &'static UiFonts { return UiFonts { regular, semibold, source: (*r).to_string() }; } } + for root in extra_linux_roots(&linux_font_roots()) { + for (r, b) in CANDIDATES { + if let (Some(r_rel), Some(b_rel)) = (r.strip_prefix(LINUX_SYSTEM_FONTS), b.strip_prefix(LINUX_SYSTEM_FONTS)) { + let r_path = root.join(r_rel); + if let Some(regular) = read_path(&r_path) { + let semibold = read_path(&root.join(b_rel)).unwrap_or_else(|| regular.clone()); + return UiFonts { regular, semibold, source: r_path.display().to_string() }; + } + } + } + } } let b = epaint_default_fonts::UBUNTU_LIGHT.to_vec(); UiFonts { regular: b.clone(), semibold: b, source: "built-in".into() } @@ -220,40 +268,148 @@ pub fn serif_fonts() -> Option<&'static SerifFonts> { if std::env::var_os("RUSTGIS_BUILTIN_FONTS").is_some() { return None; } + let roots = linux_font_roots(); let family = |[r, b, i, bi]: &[&str; 4]| { let regular = read(r)?; Some(SerifFonts { regular, bold: read(b), italic: read(i), bold_italic: read(bi), variable: false, source: (*r).to_string() }) }; - SERIF_CANDIDATES.iter().find_map(family).or_else(|| variable_noto_serif(&FONT_ROOTS)).or_else(|| SERIF_LAST.iter().find_map(family)) + let find_fixed = |list: &[[&str; 4]]| { + list.iter().find_map(family).or_else(|| { + extra_linux_roots(&roots).find_map(|root| { + list.iter().find_map(|[r, b, i, bi]| { + let join = |p: &str| p.strip_prefix(LINUX_SYSTEM_FONTS).map(|rel| root.join(rel)); + let r_path = join(r)?; + let regular = read_path(&r_path)?; + Some(SerifFonts { + regular, + bold: join(b).as_deref().and_then(read_path), + italic: join(i).as_deref().and_then(read_path), + bold_italic: join(bi).as_deref().and_then(read_path), + variable: false, + source: r_path.display().to_string(), + }) + }) + }) + }) + }; + // Search by family tier (system paths before extra Linux roots within each tier): + // 1) static preferred serifs (`SERIF_CANDIDATES`: Georgia, Times New Roman, static Noto Serif), + // 2) variable Noto Serif across all roots (`serif_font_roots`), + // 3) fallback serifs (`SERIF_LAST`: DejaVu Serif, Liberation Serif). + find_fixed(SERIF_CANDIDATES).or_else(|| variable_noto_serif(&serif_font_roots(&roots))).or_else(|| find_fixed(SERIF_LAST)) }) .as_ref() } -/// The folders under which distributions put each font package's own folder. -const FONT_ROOTS: [&str; 3] = ["/usr/share/fonts", "/usr/share/fonts/truetype", "/usr/share/fonts/opentype"]; +/// System font directory whose relative paths are expanded across Linux, Flatpak host, and XDG roots. +const LINUX_SYSTEM_FONTS: &str = "/usr/share/fonts/"; + +/// Flatpak runtime mounts exposing the host system, local, and user font directories (#2313). +const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"]; + +fn push_unique_root(out: &mut Vec, path: std::path::PathBuf) { + if !path.as_os_str().is_empty() && !out.contains(&path) { + out.push(path); + } +} + +/// POSIX absolute path check used for `XDG_DATA_HOME` (required by the XDG Base Directory spec) +/// and `HOME`, working consistently even when Linux root logic is unit-tested on Windows. +pub(crate) fn is_posix_absolute(path: &std::ffi::OsStr) -> bool { + path.as_encoded_bytes().starts_with(b"/") +} + +/// Linux font roots in search order: system, local, Flatpak host mounts, and XDG/user directories. +/// Shared with `crate::families::font_dirs` on Linux. +pub(crate) fn linux_font_roots_with(xdg_data_home: Option<&std::ffi::OsStr>, home: Option<&std::ffi::OsStr>) -> Vec { + let mut roots = Vec::new(); + for dir in ["/usr/share/fonts", "/usr/local/share/fonts"] { + push_unique_root(&mut roots, std::path::PathBuf::from(dir)); + } + for dir in FLATPAK_FONT_DIRS { + push_unique_root(&mut roots, std::path::PathBuf::from(dir)); + } + if let Some(xdg) = xdg_data_home.filter(|v| is_posix_absolute(v)) { + push_unique_root(&mut roots, std::path::PathBuf::from(xdg).join("fonts")); + } else if let Some(h) = home.filter(|v| is_posix_absolute(v)) { + push_unique_root(&mut roots, std::path::PathBuf::from(h).join(".local").join("share").join("fonts")); + } + if let Some(h) = home.filter(|v| is_posix_absolute(v)) { + push_unique_root(&mut roots, std::path::PathBuf::from(h).join(".fonts")); + } + roots +} + +fn linux_font_roots() -> Vec { + if !cfg!(target_os = "linux") { + return Vec::new(); + } + linux_font_roots_with(std::env::var_os("XDG_DATA_HOME").as_deref(), std::env::var_os("HOME").as_deref()) +} + +fn extra_linux_roots(roots: &[std::path::PathBuf]) -> impl Iterator { + roots.iter().filter(|r| *r != std::path::Path::new("/usr/share/fonts")) +} + +/// The folders under each root where distributions put each font package's own folder. +/// Always includes `/usr/share/fonts` first so non-Linux Unix systems (e.g. FreeBSD) keep +/// the original system `FONT_ROOTS` search for variable Noto Serif when Linux-only Flatpak/XDG +/// roots are gated off. +fn serif_font_roots(roots: &[std::path::PathBuf]) -> Vec { + let mut base = vec![std::path::PathBuf::from("/usr/share/fonts")]; + for root in roots { + push_unique_root(&mut base, root.clone()); + } + let mut out = Vec::new(); + for root in base { + out.push(root.clone()); + out.push(root.join("truetype")); + out.push(root.join("opentype")); + } + out +} /// Noto Serif as recent distributions ship it: a variable font (`NotoSerif[wdth,wght].ttf`, or -/// `[wght]`), with its italic beside it, in a package folder under one of `roots` ([`FONT_ROOTS`]). -/// Found by its name's start, whatever axes it lists; its bold is the same file (kept once), -/// drawn at the bold weight. -fn variable_noto_serif(roots: &[&str]) -> Option { +/// `[wght]`), with its italic beside it, in a package folder under one of `roots` +/// ([`serif_font_roots`]). Found by its name's start, whatever axes it lists; its bold is the +/// same file (kept once), drawn at the bold weight. +fn variable_noto_serif>(roots: &[P]) -> Option { + // Shared budgets across all roots so adding Flatpak/XDG roots keeps worst-case UI-thread + // directory work bounded near the original 3-root × 1,000-folder limit. + const MAX_DIRS: usize = 3_000; + const MAX_ENTRIES_PER_DIR: usize = 10_000; + const MAX_TOTAL_ENTRIES: usize = 100_000; let named = |files: &[std::path::PathBuf], stem: &str| { files.iter().find(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(stem) && n.ends_with(".ttf"))).cloned() }; + let mut entries_remaining = MAX_TOTAL_ENTRIES; // Folders and files in name order, so the same one is picked on every machine whatever order // the system lists them in; loose files don't count against the folders taken. - let listed = |dir: &std::path::Path| { + let listed = |dir: &std::path::Path, entries_remaining: &mut usize| -> Vec { + let limit = (*entries_remaining).min(MAX_ENTRIES_PER_DIR); + if limit == 0 { + return Vec::new(); + } let mut paths: Vec = - std::fs::read_dir(dir).map(|e| e.flatten().take(10_000).map(|e| e.path()).collect()).unwrap_or_default(); + std::fs::read_dir(dir).map(|e| e.flatten().take(limit).map(|e| e.path()).collect()).unwrap_or_default(); + *entries_remaining = entries_remaining.saturating_sub(paths.len()); paths.sort(); paths }; + let mut dirs_visited = 0usize; for root in roots { - for dir in listed(std::path::Path::new(root)).into_iter().filter(|p| p.is_dir()).take(1000) { - let files = listed(&dir); + if dirs_visited >= MAX_DIRS || entries_remaining == 0 { + break; + } + for dir in listed(root.as_ref(), &mut entries_remaining).into_iter().filter(|p| p.is_dir()) { + if dirs_visited >= MAX_DIRS || entries_remaining == 0 { + break; + } + dirs_visited += 1; + let files = listed(&dir, &mut entries_remaining); let Some(r) = named(&files, "NotoSerif[") else { continue }; - let Some(regular) = r.to_str().and_then(read) else { continue }; - let italic = named(&files, "NotoSerif-Italic[").and_then(|p| p.to_str().and_then(read)); + let Some(regular) = read_path(&r) else { continue }; + let italic = named(&files, "NotoSerif-Italic[").as_deref().and_then(read_path); let source = r.display().to_string(); return Some(SerifFonts { regular, bold: None, italic, bold_italic: None, variable: true, source }); } @@ -348,8 +504,8 @@ fn apple_cjk_named_files(region: CjkRegion) -> &'static [(&'static str, &'static } /// `file` in each of the Apple font folders, in order. -fn in_apple_dirs(files: &[(&str, T)]) -> impl Iterator { - APPLE_FONT_DIRS.iter().flat_map(move |dir| files.iter().map(move |(file, x)| (format!("{dir}/{file}"), *x))) +fn in_apple_dirs(files: &[(&str, T)]) -> impl Iterator { + APPLE_FONT_DIRS.iter().flat_map(move |dir| files.iter().map(move |(file, x)| (std::path::PathBuf::from(dir).join(file), *x))) } /// Android's system and manufacturer font folders. Shared with the family index, so labels @@ -369,26 +525,577 @@ fn android_cjk_files(region: CjkRegion) -> [(&'static str, u32); 3] { } /// Every installed CJK font candidate for `region`, in order of preference: (path, face index). -/// Windows first, then Apple's (macOS, iOS), Linux's and Android's. -fn cjk_paths(region: CjkRegion) -> Vec<(String, u32)> { +/// Windows first, then Apple's (macOS, iOS), Linux's (system, Flatpak host, XDG) and Android's. +fn cjk_paths(region: CjkRegion) -> Vec<(std::path::PathBuf, u32)> { + cjk_paths_with(region, &linux_font_roots()) +} + +fn cjk_paths_with(region: CjkRegion, roots: &[std::path::PathBuf]) -> Vec<(std::path::PathBuf, u32)> { let listed = cjk_candidates(region); let (windows, rest) = listed.split_at(listed.iter().take_while(|(p, _)| p.starts_with("C:\\")).count()); + let linux_extra = extra_linux_roots(roots) + .flat_map(|root| rest.iter().filter_map(move |(p, i)| p.strip_prefix(LINUX_SYSTEM_FONTS).map(|rel| (root.join(rel), *i)))); windows .iter() - .map(|(p, i)| (p.to_string(), *i)) + .map(|(p, i)| (std::path::PathBuf::from(p), *i)) .chain(in_apple_dirs(apple_cjk_files(region))) - .chain(rest.iter().map(|(p, i)| (p.to_string(), *i))) - .chain(ANDROID_FONT_DIRS.iter().flat_map(|dir| android_cjk_files(region).map(|(file, i)| (format!("{dir}/{file}"), i)))) + .chain(rest.iter().map(|(p, i)| (std::path::PathBuf::from(p), *i))) + .chain(linux_extra) + .chain( + ANDROID_FONT_DIRS + .iter() + .flat_map(|dir| android_cjk_files(region).map(|(file, i)| (std::path::PathBuf::from(dir).join(file), i))), + ) .collect() } +const ALL_CJK_REGIONS: [CjkRegion; 4] = + [CjkRegion::SimplifiedChinese, CjkRegion::TraditionalChinese, CjkRegion::Japanese, CjkRegion::Korean]; + +/// Deduplicated Linux CJK font filenames and face indices in preference order. +fn cjk_linux_filenames(region: CjkRegion) -> Vec<(&'static str, u32)> { + let mut out: Vec<(&'static str, u32)> = Vec::new(); + for &(path, index) in cjk_candidates(region) { + if path.starts_with(LINUX_SYSTEM_FONTS) + && let Some(name) = path.rsplit('/').next() + && !out.iter().any(|&(n, i)| n == name && i == index) + { + out.push((name, index)); + } + } + out +} + +/// Union of Linux CJK filenames across all four regions so a single bounded scan serves every region. +fn all_cjk_linux_filenames() -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for region in ALL_CJK_REGIONS { + for (name, _) in cjk_linux_filenames(region) { + if !out.contains(&name) { + out.push(name); + } + } + } + out +} + +/// Diagnostics from the bounded Linux CJK font-folder fallback scan, recording any unreadable +/// directories, directory-entry errors, or folders truncated/skipped at the scan limits. +/// Clean (`is_clean()`) when every existing folder under the scanned roots was walked in full. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CjkRootScanSummary { + /// Directories whose `read_dir` failed for a reason other than `NotFound`. + pub unreadable_dirs: usize, + /// Directory entries that returned an I/O error during iteration. + pub entry_errors: usize, + /// Directories truncated or skipped because a depth, directory, file, or entry cap was hit. + pub truncated_dirs: usize, + /// Whether the OS refused to spawn the background scan thread in an async UI session. + pub thread_spawn_failed: bool, + /// First affected path, so notices say where skipping or errors happened. + pub sample_path: Option, +} + +impl CjkRootScanSummary { + /// Whether every existing folder under the scanned roots was walked completely without errors. + pub fn is_clean(&self) -> bool { + self.unreadable_dirs == 0 && self.entry_errors == 0 && self.truncated_dirs == 0 && !self.thread_spawn_failed + } + + /// Human-readable notice naming what was skipped or unreadable, how much, and where, + /// or `None` when the scan completed cleanly. + pub fn notice(&self) -> Option { + if self.is_clean() { + return None; + } + let mut parts = Vec::new(); + if self.thread_spawn_failed { + parts.push("background scan thread could not start".to_string()); + } + if self.truncated_dirs > 0 { + parts.push(format!("{} folder(s) reached the scan limit", self.truncated_dirs)); + } + if self.unreadable_dirs > 0 { + parts.push(format!("{} unreadable folder(s)", self.unreadable_dirs)); + } + if self.entry_errors > 0 { + parts.push(format!("{} directory entry error(s)", self.entry_errors)); + } + let where_text = self.sample_path.as_deref().map(|p| format!(" (e.g. {})", p.display())).unwrap_or_default(); + Some(format!("CJK font folder search stopped early: {}{where_text}; some installed CJK fonts may not be found.", parts.join(", "))) + } +} + +struct CjkRootIndex { + files: std::collections::HashMap<&'static str, Vec>, + summary: CjkRootScanSummary, +} + +/// Shared bounded BFS under Linux `roots` indexing known CJK font filenames across all four regions +/// (`MAX_DEPTH = 6`, `MAX_DIRS = 2_000`, `MAX_FILES = 20_000`). +/// +/// In desktop UI sessions (`crate::families::warm_up` enables async fallback), this scan starts +/// lazily on a background `"cjk-font-scan"` thread only if a CJK lookup misses every fixed path; +/// `cjk_font` returns `None` without blocking while the walk runs and the UI retries once +/// [`cjk_roots_ready`] flips true. Both that background walk and synchronous CLI/Python/headless +/// runs execute once per process as a bounded non-cancellable step. +/// +/// Out of scope for #2313: Arabic, Bengali, Lao, and symbol faces remain on their fixed paths +/// (`script_paths`) without nested directory fallback search. +fn scan_cjk_roots(roots: &[std::path::PathBuf]) -> CjkRootIndex { + const MAX_DEPTH: usize = 6; + const MAX_DIRS: usize = 2_000; + const MAX_FILES: usize = 20_000; + scan_cjk_roots_bounded(roots, MAX_DEPTH, MAX_DIRS, MAX_FILES) +} + +fn scan_cjk_roots_bounded(roots: &[std::path::PathBuf], max_depth: usize, max_dirs: usize, max_files: usize) -> CjkRootIndex { + // Bound the entries read from read_dir across the whole scan, so an oversized directory cannot + // grow the buffers without limit. Which entries survive the cut follows the filesystem's + // listing order, not the sorted order. + let max_entries = max_files.saturating_add(max_dirs); + + let targets = all_cjk_linux_filenames(); + let mut files: std::collections::HashMap<&'static str, Vec> = std::collections::HashMap::new(); + let mut summary = CjkRootScanSummary::default(); + if targets.is_empty() || roots.is_empty() { + return CjkRootIndex { files, summary }; + } + + // Canonical directory -> (shallowest depth visited, direct subdirectory names discovered on + // first visit). Revisiting at a strictly shallower depth re-enqueues only cached subdirectories + // without re-reading the directory or double-counting against the directory/entry/file caps. + let mut seen: std::collections::HashMap)> = std::collections::HashMap::new(); + let mut skipped_dirs: Vec = Vec::new(); + let mut dirs_visited = 0usize; + let mut files_seen = 0usize; + let mut entries_seen = 0usize; + + for root in roots { + if dirs_visited >= max_dirs || files_seen >= max_files || entries_seen >= max_entries { + // Not `exists()`: it also hides errors other than NotFound, which must count as skipped. + if !matches!(std::fs::metadata(root), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound) { + skipped_dirs.push(root.clone()); + } + continue; + } + let mut queue = std::collections::VecDeque::from([(root.clone(), 0usize)]); + let mut queued_depth: std::collections::HashMap = std::collections::HashMap::new(); + while let Some((dir, depth)) = queue.pop_front() { + if depth > max_depth || dirs_visited >= max_dirs || files_seen >= max_files || entries_seen >= max_entries { + skipped_dirs.push(dir); + skipped_dirs.extend(queue.drain(..).map(|(p, _)| p)); + break; + } + let canonical = std::fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone()); + // Revisit only when reached at a strictly shallower depth so deep symlinks cannot shadow shallow paths. + if let Some((prev_depth, child_subdirs)) = seen.get_mut(&canonical) { + if *prev_depth <= depth { + continue; + } + *prev_depth = depth; + let names = child_subdirs.clone(); + queued_depth.entry(canonical).and_modify(|d| *d = (*d).min(depth)).or_insert(depth); + for name in names { + let child = dir.join(name); + let next_depth = depth + 1; + if next_depth > max_depth { + skipped_dirs.push(child); + continue; + } + let child_canonical = std::fs::canonicalize(&child).unwrap_or_else(|_| child.clone()); + if seen.get(&child_canonical).is_some_and(|&(prev, _)| prev <= next_depth) + || queued_depth.get(&child_canonical).is_some_and(|&prev| prev <= next_depth) + { + continue; + } + // Revisited descendants already in `seen` do not consume `dirs_visited`, so cap + // the revisit queue by `max_dirs` rather than the remaining first-visit budget. + if queue.len() < max_dirs { + queued_depth.insert(child_canonical, next_depth); + queue.push_back((child, next_depth)); + } else { + skipped_dirs.push(child); + } + } + continue; + } + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(err) => { + if err.kind() != std::io::ErrorKind::NotFound { + summary.unreadable_dirs += 1; + summary.sample_path.get_or_insert_with(|| dir.clone()); + } + continue; + } + }; + queued_depth.entry(canonical.clone()).and_modify(|d| *d = (*d).min(depth)).or_insert(depth); + dirs_visited += 1; + + let mut children = Vec::new(); + let mut entry_cap_hit = false; + for entry in entries { + match entry { + Ok(e) => { + if entries_seen >= max_entries { + entry_cap_hit = true; + break; + } + entries_seen += 1; + children.push(e.path()); + } + Err(_) => { + summary.entry_errors += 1; + summary.sample_path.get_or_insert_with(|| dir.clone()); + } + } + } + children.sort(); + + let mut child_subdirs = Vec::new(); + let mut dir_truncated = entry_cap_hit; + let mut iter = children.into_iter(); + while let Some(path) = iter.next() { + match std::fs::metadata(&path) { + Ok(meta) if meta.is_dir() => { + if let Some(name) = path.file_name() { + child_subdirs.push(name.to_os_string()); + } + let next_depth = depth + 1; + if next_depth > max_depth { + skipped_dirs.push(path); + continue; + } + let child_canonical = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); + if seen.get(&child_canonical).is_some_and(|&(prev, _)| prev <= next_depth) + || queued_depth.get(&child_canonical).is_some_and(|&prev| prev <= next_depth) + { + continue; + } + if queue.len() < max_dirs.saturating_sub(dirs_visited) { + queued_depth.insert(child_canonical, next_depth); + queue.push_back((path, next_depth)); + } else { + skipped_dirs.push(path); + } + } + Ok(meta) if meta.is_file() => { + if files_seen >= max_files { + dir_truncated = true; + for remaining in iter { + match std::fs::metadata(&remaining) { + Ok(meta) if meta.is_dir() => skipped_dirs.push(remaining), + Ok(_) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => { + summary.entry_errors += 1; + summary.sample_path.get_or_insert(remaining); + } + } + } + break; + } + files_seen += 1; + if let Some(name) = path.file_name().and_then(|n| n.to_str()) + && let Some(&target_name) = targets.iter().find(|&&t| t == name) + { + let bucket = files.entry(target_name).or_default(); + if !bucket.contains(&path) { + bucket.push(path); + } + } + } + Ok(_) => {} + Err(err) => { + if err.kind() != std::io::ErrorKind::NotFound { + summary.entry_errors += 1; + summary.sample_path.get_or_insert(path); + } + } + } + } + seen.insert(canonical, (depth, child_subdirs)); + if dir_truncated { + summary.truncated_dirs += 1; + summary.sample_path.get_or_insert_with(|| dir.clone()); + } + } + } + + // Count only skipped directories that were not subsequently visited through a shallower path. + let mut skipped_seen: std::collections::HashSet = std::collections::HashSet::new(); + for path in skipped_dirs { + let canonical = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); + if !seen.contains_key(&canonical) && skipped_seen.insert(canonical) { + summary.truncated_dirs += 1; + summary.sample_path.get_or_insert(path); + } + } + + CjkRootIndex { files, summary } +} + +struct CjkScanState { + async_enabled: std::sync::atomic::AtomicBool, + started: std::sync::atomic::AtomicBool, + done: std::sync::atomic::AtomicBool, + notice_needed: std::sync::atomic::AtomicBool, + notice_taken: std::sync::atomic::AtomicBool, + index: OnceLock, + fixed: [OnceLock, u32)>>; 4], + fallback: [OnceLock, u32)>>; 4], +} + +enum CjkResolveResult { + Pending, + Resolved(Option<&'static (Vec, u32)>), +} + +impl CjkScanState { + const fn new() -> Self { + Self { + async_enabled: std::sync::atomic::AtomicBool::new(false), + started: std::sync::atomic::AtomicBool::new(false), + done: std::sync::atomic::AtomicBool::new(false), + notice_needed: std::sync::atomic::AtomicBool::new(false), + notice_taken: std::sync::atomic::AtomicBool::new(false), + index: OnceLock::new(), + fixed: [OnceLock::new(), OnceLock::new(), OnceLock::new(), OnceLock::new()], + fallback: [OnceLock::new(), OnceLock::new(), OnceLock::new(), OnceLock::new()], + } + } + + fn slot(region: CjkRegion) -> usize { + match region { + CjkRegion::SimplifiedChinese => 0, + CjkRegion::Japanese => 1, + CjkRegion::Korean => 2, + CjkRegion::TraditionalChinese => 3, + } + } + + fn enable_async(&self) { + self.async_enabled.store(true, std::sync::atomic::Ordering::Release); + } + + fn is_pending(&self) -> bool { + self.started.load(std::sync::atomic::Ordering::Acquire) && !self.done.load(std::sync::atomic::Ordering::Acquire) + } + + fn is_ready(&self) -> bool { + self.done.load(std::sync::atomic::Ordering::Acquire) + } + + fn take_summary(&self) -> Option { + if !self.notice_needed.load(std::sync::atomic::Ordering::Acquire) { + return None; + } + if self.notice_taken.swap(true, std::sync::atomic::Ordering::AcqRel) { + return None; + } + self.index.get().filter(|idx| !idx.summary.is_clean()).map(|idx| idx.summary.clone()) + } + + fn publish_done(&self) { + use std::sync::atomic::Ordering; + // Publish `done` before advancing `FONT_GENERATION` so any reader observing the new + // generation resolves against the completed scan (and disk cache) rather than `Pending`. + if !self.done.swap(true, Ordering::AcqRel) { + FONT_GENERATION.fetch_add(1, Ordering::Release); + } + } + + #[cfg(any(not(target_arch = "wasm32"), test))] + fn record_spawn_refused(&self) { + let _ = self.index.set(CjkRootIndex { + files: std::collections::HashMap::new(), + summary: CjkRootScanSummary { thread_spawn_failed: true, ..Default::default() }, + }); + self.notice_needed.store(true, std::sync::atomic::Ordering::Release); + self.publish_done(); + } + + /// Starts the bounded Linux CJK folder walk on a background thread once. Returns `true` + /// while the scan is running off-thread so UI callers return `None` without blocking. + /// If the OS refuses to spawn the thread, records a diagnostic summary and marks the scan done + /// without running the folder walk on the UI thread. + fn start_async_scan(&'static self, scan: impl Fn() -> CjkRootIndex + Clone + Send + 'static) -> bool { + use std::sync::atomic::Ordering; + if self.done.load(Ordering::Acquire) || self.index.get().is_some() { + return false; + } + if self.started.swap(true, Ordering::AcqRel) { + return !self.done.load(Ordering::Acquire) && self.index.get().is_none(); + } + #[cfg(not(target_arch = "wasm32"))] + { + struct FinishOnDrop(&'static CjkScanState); + impl Drop for FinishOnDrop { + fn drop(&mut self) { + self.0.publish_done(); + } + } + if std::thread::Builder::new() + .name("cjk-font-scan".into()) + .spawn(move || { + let _done = FinishOnDrop(self); + let index = self.index.get_or_init(scan); + if !index.summary.is_clean() { + self.notice_needed.store(true, Ordering::Release); + } + }) + .is_ok() + { + return true; + } + self.record_spawn_refused(); + false + } + #[cfg(target_arch = "wasm32")] + { + let _ = scan; + let _ = self.index.set(CjkRootIndex { files: std::collections::HashMap::new(), summary: CjkRootScanSummary::default() }); + self.publish_done(); + false + } + } + + fn resolve_region( + &'static self, + region: CjkRegion, + find_fixed: impl FnOnce(CjkRegion) -> Option<(Vec, u32)>, + use_root_scan: bool, + scan: impl Fn() -> CjkRootIndex + Clone + Send + 'static, + find_cached: impl FnOnce(CjkRegion) -> Option<(Vec, u32)>, + ) -> CjkResolveResult { + let slot = Self::slot(region); + let Some(fixed_slot) = self.fixed.get(slot) else { + return CjkResolveResult::Resolved(None); + }; + if let Some(found) = fixed_slot.get_or_init(|| find_fixed(region)).as_ref() { + return CjkResolveResult::Resolved(Some(found)); + } + if use_root_scan + && !BLOCKING_CJK_SCAN.get() + && self.async_enabled.load(std::sync::atomic::Ordering::Acquire) + && self.start_async_scan(scan.clone()) + { + PENDING_CJK_HIT.set(true); + return CjkResolveResult::Pending; + } + let Some(fallback_slot) = self.fallback.get(slot) else { + return CjkResolveResult::Resolved(None); + }; + let found = fallback_slot + .get_or_init(|| { + let scanned = if use_root_scan { + let index = self.index.get_or_init(scan); + if !index.summary.is_clean() { + self.notice_needed.store(true, std::sync::atomic::Ordering::Release); + } + if self.async_enabled.load(std::sync::atomic::Ordering::Acquire) { + self.publish_done(); + } + find_cjk_in_index(&index.files, region).map(|(_, bytes, index)| (bytes, index)) + } else { + None + }; + scanned.or_else(|| find_cached(region)) + }) + .as_ref(); + CjkResolveResult::Resolved(found) + } +} + +thread_local! { + /// Set by background export workers ([`with_blocking_cjk_scan`]) so exports wait for any + /// in-flight Linux CJK folder scan rather than omitting glyphs. + static BLOCKING_CJK_SCAN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Set when [`CjkScanState::resolve_region`] returns `Pending` on this thread, so a + /// synchronous non-blocking export can warn if a CJK lookup was still waiting on the scan. + static PENDING_CJK_HIT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with blocking Linux CJK folder resolution on the current thread. Intended for +/// background export workers (off the UI thread) so exports wait for an in-flight scan and can +/// use discovered or disk-cached faces instead of returning `Pending`. +pub fn with_blocking_cjk_scan(f: impl FnOnce() -> T) -> T { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + BLOCKING_CJK_SCAN.set(self.0); + } + } + let prev = BLOCKING_CJK_SCAN.replace(true); + let _reset = Reset(prev); + f() +} + +/// Runs `f` and reports whether any CJK lookup on this thread returned `Pending` while an async +/// Linux CJK folder scan was running, so synchronous callers never silently emit missing glyphs. +pub fn track_pending_cjk(f: impl FnOnce() -> T) -> (T, bool) { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + PENDING_CJK_HIT.set(self.0 || PENDING_CJK_HIT.get()); + } + } + let prev = PENDING_CJK_HIT.replace(false); + let _reset = Reset(prev); + let out = f(); + let hit = PENDING_CJK_HIT.get(); + (out, hit) +} + +static CJK_SCAN: CjkScanState = CjkScanState::new(); + +/// Enables non-blocking background CJK folder scanning for UI sessions (`crate::families::warm_up`). +/// Does not start a scan eagerly; a thread is spawned only if a CJK lookup misses fixed paths. +pub(crate) fn enable_async_cjk_scan() { + CJK_SCAN.enable_async(); +} + +/// Whether the background Linux CJK folder fallback scan is currently running off the UI thread. +pub fn cjk_roots_pending() -> bool { + CJK_SCAN.is_pending() +} + +/// Whether a background Linux CJK folder fallback scan has finished and its index is ready. +pub fn cjk_roots_ready() -> bool { + CJK_SCAN.is_ready() +} + +/// Returns truncation or directory-read diagnostics once if a CJK font lookup actually fell back +/// to the bounded recursive scan and encountered limits or errors. Never starts a scan itself. +pub fn take_cjk_scan_summary() -> Option { + CJK_SCAN.take_summary() +} + +/// Selects the first usable CJK font from a scanned root index in `region`'s preference order. +fn find_cjk_in_index( + indexed_files: &std::collections::HashMap<&'static str, Vec>, + region: CjkRegion, +) -> Option<(std::path::PathBuf, Vec, u32)> { + for (target_name, index) in cjk_linux_filenames(region) { + if let Some(paths) = indexed_files.get(target_name) { + for path in paths { + if let Some(bytes) = read_cjk_path(path).filter(|b| draws_cjk(b, index, region)) { + return Some((path.clone(), bytes, index)); + } + } + } + } + None +} + /// Installed CJK collections whose face is found by family name, not by index: (path, family). -fn cjk_named_candidates(region: CjkRegion) -> Vec<(String, &'static str)> { +fn cjk_named_candidates(region: CjkRegion) -> Vec<(std::path::PathBuf, &'static str)> { in_apple_dirs(apple_cjk_named_files(region)).collect() } /// A CJK font file's bytes. CJK collections are large; accept up to 128 MiB. -fn read_cjk(path: &str) -> Option> { +fn read_cjk_path(path: &std::path::Path) -> Option> { read_bounded(path, 128 << 20) } @@ -406,36 +1113,38 @@ fn regular_face(bytes: &[u8], family: &str) -> Option { }) } -/// An installed CJK font for `region` (bytes and face index), found once. `None` on the web or -/// when nothing suitable is installed. Traditional Chinese falls back to the Simplified face, -/// which has the Traditional characters in mainland China's glyph forms. +fn find_fixed_cjk(region: CjkRegion) -> Option<(Vec, u32)> { + cjk_paths(region) + .iter() + .find_map(|(path, index)| read_cjk_path(path).filter(|b| draws_cjk(b, *index, region)).map(|b| (b, *index))) + .or_else(|| { + cjk_named_candidates(region).iter().find_map(|(path, family)| { + let bytes = read_cjk_path(path)?; + let index = regular_face(&bytes, family).filter(|i| draws_cjk(&bytes, *i, region))?; + Some((bytes, index)) + }) + }) +} + +/// An installed CJK font for `region` (bytes and face index), found once. `None` on the web, +/// while an async Linux folder fallback scan is in flight, or when nothing suitable is installed. +/// Traditional Chinese falls back to the Simplified face, which has the Traditional characters in +/// mainland China's glyph forms. pub fn cjk_font(region: CjkRegion) -> Option<&'static (Vec, u32)> { if std::env::var_os("RUSTGIS_BUILTIN_FONTS").is_some() { return None; } - static FOUND: [OnceLock, u32)>>; 4] = [OnceLock::new(), OnceLock::new(), OnceLock::new(), OnceLock::new()]; - let slot = match region { - CjkRegion::SimplifiedChinese => &FOUND[0], - CjkRegion::Japanese => &FOUND[1], - CjkRegion::Korean => &FOUND[2], - CjkRegion::TraditionalChinese => &FOUND[3], - }; - let found = slot.get_or_init(|| { - let indexed = - cjk_paths(region).iter().find_map(|(path, index)| read_cjk(path).filter(|b| draws_cjk(b, *index, region)).map(|b| (b, *index))); - indexed - .or_else(|| { - cjk_named_candidates(region).iter().find_map(|(path, family)| { - let bytes = read_cjk(path)?; - let index = regular_face(&bytes, family).filter(|i| draws_cjk(&bytes, *i, region))?; - Some((bytes, index)) - }) - }) - .or_else(|| cached_script_font(ScriptFont::Cjk(region))) - }); + let found = CJK_SCAN.resolve_region( + region, + find_fixed_cjk, + cfg!(target_os = "linux"), + || scan_cjk_roots(&linux_font_roots()), + |r| cached_script_font(ScriptFont::Cjk(r)), + ); match (found, region) { - (None, CjkRegion::TraditionalChinese) => cjk_font(CjkRegion::SimplifiedChinese), - (found, _) => found.as_ref(), + (CjkResolveResult::Pending, _) => None, + (CjkResolveResult::Resolved(None), CjkRegion::TraditionalChinese) => cjk_font(CjkRegion::SimplifiedChinese), + (CjkResolveResult::Resolved(found), _) => found, } } @@ -714,16 +1423,23 @@ fn covers_lao(bytes: &[u8], index: u32) -> bool { outlines(bytes, index, &['\u{0E81}', '\u{0E82}', '\u{0EB2}', '\u{0EC8}']) } -/// The existing script candidates in every Apple font folder (iOS uses subfolders), and -/// Android system candidates in manufacturer folders too. Keep the listed paths first. -fn script_paths(candidates: &[&str]) -> Vec { - let mut paths: Vec = candidates.iter().map(|p| (*p).to_string()).collect(); +/// The existing script candidates in every Apple font folder (iOS uses subfolders), +/// Android system candidates in manufacturer folders, and Linux Flatpak/XDG font roots. +/// Keep the listed paths first. +fn script_paths(candidates: &[&str]) -> Vec { + script_paths_with(candidates, &linux_font_roots()) +} + +fn script_paths_with(candidates: &[&str], roots: &[std::path::PathBuf]) -> Vec { + let mut paths: Vec = candidates.iter().map(std::path::PathBuf::from).collect(); for path in candidates { if let Some(file) = path.strip_prefix("/System/Library/Fonts/Supplemental/").or_else(|| path.strip_prefix("/System/Library/Fonts/")) { paths.extend(in_apple_dirs(&[(file, ())]).map(|(p, _)| p)); } else if let Some(file) = path.strip_prefix("/system/fonts/") { - paths.extend(ANDROID_FONT_DIRS.iter().map(|dir| format!("{dir}/{file}"))); + paths.extend(ANDROID_FONT_DIRS.iter().map(|dir| std::path::PathBuf::from(dir).join(file))); + } else if let Some(rel) = path.strip_prefix(LINUX_SYSTEM_FONTS) { + paths.extend(extra_linux_roots(roots).map(|root| root.join(rel))); } } paths @@ -1084,16 +1800,18 @@ mod tests { /// not just the desktop paths listed for the same faces. #[test] fn script_faces_follow_mobile_font_folders() { + use std::path::PathBuf; + for candidates in [super::BENGALI_CANDIDATES, super::ARABIC_CANDIDATES, super::LAO_CANDIDATES, super::SYMBOL_CANDIDATES] { let paths = super::script_paths(candidates); - assert!(paths.iter().any(|p| p.starts_with("/System/Library/Fonts/Core/")), "{candidates:?}"); + assert!(paths.iter().any(|p| p.starts_with("/System/Library/Fonts/Core")), "{candidates:?}"); } for (candidates, file) in [(super::BENGALI_CANDIDATES, "NotoSansBengali-VF.ttf"), (super::LAO_CANDIDATES, "NotoSansLao-Regular.ttf")] { let paths = super::script_paths(candidates); - assert!(paths.contains(&format!("/system/fonts/{file}"))); - assert!(paths.contains(&format!("/product/fonts/{file}"))); + assert!(paths.contains(&PathBuf::from(format!("/system/fonts/{file}")))); + assert!(paths.contains(&PathBuf::from(format!("/product/fonts/{file}")))); } } @@ -1118,29 +1836,31 @@ mod tests { /// faces are still tried first. #[test] fn every_cjk_region_names_a_face_on_each_platform() { + use std::path::{Path, PathBuf}; + use super::{CjkRegion, cjk_named_candidates, cjk_paths}; for region in [CjkRegion::SimplifiedChinese, CjkRegion::TraditionalChinese, CjkRegion::Japanese, CjkRegion::Korean] { - let paths: Vec = + let paths: Vec = cjk_paths(region).into_iter().map(|(p, _)| p).chain(cjk_named_candidates(region).into_iter().map(|(p, _)| p)).collect(); - let in_dir = |dir: &str| paths.iter().any(|p| p.rsplit_once('/').is_some_and(|(d, _)| d == dir)); + let in_dir = |dir: &str| paths.iter().any(|p| p.parent() == Some(Path::new(dir))); assert!(in_dir("/System/Library/Fonts"), "{region:?}: no macOS face"); assert!(in_dir("/System/Library/Fonts/Core"), "{region:?}: no iOS face"); assert!(in_dir("/system/fonts"), "{region:?}: no Android face"); - assert!(paths.first().is_some_and(|p| p.starts_with("C:\\")), "{region:?}: Windows first"); + assert!(paths.first().is_some_and(|p| p.to_string_lossy().starts_with("C:\\")), "{region:?}: Windows first"); } for (region, index) in [(CjkRegion::Japanese, 0), (CjkRegion::Korean, 1), (CjkRegion::SimplifiedChinese, 2), (CjkRegion::TraditionalChinese, 3)] { let paths = cjk_paths(region); for dir in super::ANDROID_FONT_DIRS { - assert!(paths.contains(&(format!("{dir}/NotoSansCJK-Regular.ttc"), index)), "{region:?}"); - assert!(paths.contains(&(format!("{dir}/DroidSansFallback.ttf"), 0)), "{region:?}: legacy face"); + assert!(paths.contains(&(PathBuf::from(dir).join("NotoSansCJK-Regular.ttc"), index)), "{region:?}"); + assert!(paths.contains(&(PathBuf::from(dir).join("DroidSansFallback.ttf"), 0)), "{region:?}: legacy face"); } } let korean = cjk_paths(CjkRegion::Korean); - assert!(korean.iter().any(|(p, i)| p == "/System/Library/Fonts/Core/AppleSDGothicNeo.ttc" && *i == 0)); + assert!(korean.iter().any(|(p, i)| p == &PathBuf::from("/System/Library/Fonts/Core/AppleSDGothicNeo.ttc") && *i == 0)); let japanese = cjk_paths(CjkRegion::Japanese); - assert!(japanese.iter().any(|(p, _)| p == "/System/Library/Fonts/Core/HiraginoKakuGothic.ttc")); + assert!(japanese.iter().any(|(p, _)| p == &PathBuf::from("/System/Library/Fonts/Core/HiraginoKakuGothic.ttc"))); } /// A CJK candidate is taken only when it outlines its region's script: not a face without @@ -1153,9 +1873,12 @@ mod tests { assert!(!draws_cjk(b"not a font", 0, region), "{region:?}"); } // Noto Sans CJK draws them all, where it is installed. - for (p, i) in super::cjk_paths(CjkRegion::Korean).iter().filter(|(p, _)| p.ends_with("NotoSansCJK-Regular.ttc")) { + for (p, i) in super::cjk_paths(CjkRegion::Korean) + .iter() + .filter(|(p, _)| p.file_name().and_then(|n| n.to_str()) == Some("NotoSansCJK-Regular.ttc")) + { if let Ok(b) = std::fs::read(p) { - assert!(draws_cjk(&b, *i, CjkRegion::Korean), "{p}"); + assert!(draws_cjk(&b, *i, CjkRegion::Korean), "{}", p.display()); } } } @@ -1214,4 +1937,485 @@ mod tests { } } } + + #[test] + fn flatpak_and_xdg_roots_are_included_in_cjk_and_script_paths() { + use std::ffi::OsStr; + use std::path::PathBuf; + + let roots_xdg = super::linux_font_roots_with(Some(OsStr::new("/custom/xdg")), Some(OsStr::new("/custom/home"))); + for expected in [ + "/usr/share/fonts", + "/usr/local/share/fonts", + "/run/host/fonts", + "/run/host/local-fonts", + "/run/host/user-fonts", + "/custom/xdg/fonts", + "/custom/home/.fonts", + ] { + assert!(roots_xdg.contains(&PathBuf::from(expected)), "missing {expected} in {roots_xdg:?}"); + } + + let roots_home = super::linux_font_roots_with(None, Some(OsStr::new("/custom/home"))); + assert!(roots_home.contains(&PathBuf::from("/custom/home/.local/share/fonts")), "{roots_home:?}"); + + // Per XDG Base Directory spec, relative XDG_DATA_HOME is ignored and falls back to $HOME/.local/share. + let roots_rel = super::linux_font_roots_with(Some(OsStr::new("relative/xdg")), Some(OsStr::new("/custom/home"))); + assert!(!roots_rel.contains(&PathBuf::from("relative/xdg/fonts")), "{roots_rel:?}"); + assert!(roots_rel.contains(&PathBuf::from("/custom/home/.local/share/fonts")), "{roots_rel:?}"); + + for (region, index) in [ + (super::CjkRegion::Japanese, 0), + (super::CjkRegion::Korean, 1), + (super::CjkRegion::SimplifiedChinese, 2), + (super::CjkRegion::TraditionalChinese, 3), + ] { + let paths = super::cjk_paths_with(region, &roots_xdg); + for root in ["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts", "/custom/xdg/fonts", "/custom/home/.fonts"] { + let expected = PathBuf::from(root).join("opentype/noto/NotoSansCJK-Regular.ttc"); + assert!(paths.contains(&(expected.clone(), index)), "{region:?}: missing {}", expected.display()); + } + } + + let arabic_paths = super::script_paths_with(super::ARABIC_CANDIDATES, &roots_xdg); + for root in ["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts", "/custom/xdg/fonts"] { + let expected = PathBuf::from(root).join("truetype/dejavu/DejaVuSans.ttf"); + assert!(arabic_paths.contains(&expected), "missing {} in {arabic_paths:?}", expected.display()); + } + + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + + let raw_xdg = OsStr::from_bytes(b"/custom/\xff/xdg"); + let raw_roots = super::linux_font_roots_with(Some(raw_xdg), None); + let raw_cjk = super::cjk_paths_with(super::CjkRegion::SimplifiedChinese, &raw_roots); + let raw_script = super::script_paths_with(super::ARABIC_CANDIDATES, &raw_roots); + let expected_cjk = PathBuf::from(OsStr::from_bytes(b"/custom/\xff/xdg/fonts/opentype/noto/NotoSansCJK-Regular.ttc")); + let expected_script = PathBuf::from(OsStr::from_bytes(b"/custom/\xff/xdg/fonts/truetype/dejavu/DejaVuSans.ttf")); + assert!(raw_cjk.contains(&(expected_cjk, 2))); + assert!(raw_script.contains(&expected_script)); + } + } + + #[test] + fn find_cjk_in_roots_discovers_nested_distribution_subfolders_in_preference_order() { + let dir = tempfile::tempdir().unwrap(); + let valid_font = include_bytes!("../testdata/test-fallback.otf"); + + // Higher-priority filename that is corrupt/unusable must be skipped. + let corrupt_dir = dir.path().join("other"); + std::fs::create_dir_all(&corrupt_dir).unwrap(); + std::fs::write(corrupt_dir.join("NotoSansCJK-Regular.ttc"), b"not a font").unwrap(); + + // Lower-priority valid fallback. + let wqy_dir = dir.path().join("alt"); + std::fs::create_dir_all(&wqy_dir).unwrap(); + let wqy_path = wqy_dir.join("wqy-microhei.ttc"); + std::fs::write(&wqy_path, valid_font).unwrap(); + + // Preferred NotoSansSC-Regular.otf placed inside a non-standard nested subfolder. + let nested_dir = dir.path().join("distro-cjk").join("sub"); + std::fs::create_dir_all(&nested_dir).unwrap(); + let sc_path = nested_dir.join("NotoSansSC-Regular.otf"); + std::fs::write(&sc_path, valid_font).unwrap(); + + // Another region's font present in the same tree is indexed in the same scan. + let jp_path = nested_dir.join("NotoSansJP-Regular.otf"); + std::fs::write(&jp_path, valid_font).unwrap(); + + let missing_index = super::scan_cjk_roots(&[dir.path().join("missing")]); + assert!(missing_index.summary.is_clean(), "missing optional roots should not emit a notice"); + assert!(missing_index.summary.notice().is_none()); + assert!(super::find_cjk_in_index(&missing_index.files, super::CjkRegion::SimplifiedChinese).is_none()); + + let index = super::scan_cjk_roots(&[dir.path().to_path_buf()]); + assert!(index.summary.is_clean()); + assert!(index.summary.notice().is_none()); + let (chosen_path, found_bytes, found_face) = + super::find_cjk_in_index(&index.files, super::CjkRegion::SimplifiedChinese).expect("should discover nested SC font"); + assert_eq!(chosen_path, sc_path); + assert_eq!(found_bytes, valid_font); + assert_eq!(found_face, 0); + + let (chosen_jp, _, jp_face) = + super::find_cjk_in_index(&index.files, super::CjkRegion::Japanese).expect("single scan should also index Japanese font"); + assert_eq!(chosen_jp, jp_path); + assert_eq!(jp_face, 0); + + // Remove NotoSansSC-Regular.otf -> falls back to wqy-microhei.ttc. + std::fs::remove_file(&sc_path).unwrap(); + let fallback_index = super::scan_cjk_roots(&[dir.path().to_path_buf()]); + let (fallback_path, fallback_bytes, fallback_face) = + super::find_cjk_in_index(&fallback_index.files, super::CjkRegion::SimplifiedChinese) + .expect("should fall back to wqy-microhei.ttc"); + assert_eq!(fallback_path, wqy_path); + assert_eq!(fallback_bytes, valid_font); + assert_eq!(fallback_face, 0); + + // Corrupt-only directory returns None. + std::fs::remove_file(&wqy_path).unwrap(); + let corrupt_index = super::scan_cjk_roots(&[dir.path().to_path_buf()]); + assert!(super::find_cjk_in_index(&corrupt_index.files, super::CjkRegion::SimplifiedChinese).is_none()); + } + + #[test] + fn serif_font_roots_keeps_system_roots_when_linux_roots_are_empty() { + use std::path::PathBuf; + + assert_eq!( + super::serif_font_roots(&[]), + vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/share/fonts/truetype"), PathBuf::from("/usr/share/fonts/opentype")] + ); + + let with_extra = super::serif_font_roots(&[PathBuf::from("/usr/share/fonts"), PathBuf::from("/run/host/fonts")]); + assert_eq!( + with_extra, + vec![ + PathBuf::from("/usr/share/fonts"), + PathBuf::from("/usr/share/fonts/truetype"), + PathBuf::from("/usr/share/fonts/opentype"), + PathBuf::from("/run/host/fonts"), + PathBuf::from("/run/host/fonts/truetype"), + PathBuf::from("/run/host/fonts/opentype"), + ] + ); + } + + #[test] + fn scan_cjk_roots_reports_truncation_and_is_silent_when_clean() { + let dir = tempfile::tempdir().unwrap(); + let sub_a = dir.path().join("a"); + let sub_b = dir.path().join("b"); + std::fs::create_dir_all(&sub_a).unwrap(); + std::fs::create_dir_all(&sub_b).unwrap(); + std::fs::write(sub_a.join("f1.ttf"), b"x").unwrap(); + std::fs::write(sub_a.join("f2.ttf"), b"x").unwrap(); + std::fs::write(sub_b.join("f3.ttf"), b"x").unwrap(); + + // Clean scan within limits produces no notice. + let clean = super::scan_cjk_roots_bounded(&[dir.path().to_path_buf()], 6, 10, 10); + assert!(clean.summary.is_clean(), "{:?}", clean.summary); + assert!(clean.summary.notice().is_none()); + + // Capping files below the directory's file count reports truncation with count and path. + let capped_files = super::scan_cjk_roots_bounded(&[dir.path().to_path_buf()], 6, 10, 1); + assert!(!capped_files.summary.is_clean()); + assert!(capped_files.summary.truncated_dirs >= 1, "{:?}", capped_files.summary); + let notice = capped_files.summary.notice().expect("truncated scan should produce a notice"); + assert!(notice.contains("reached the scan limit"), "{notice}"); + assert!(capped_files.summary.sample_path.is_some()); + + // Subfolders sorted after the file that hits max_files are also counted as skipped. + let behind_dir = tempfile::tempdir().unwrap(); + std::fs::write(behind_dir.path().join("a1.ttf"), b"x").unwrap(); + std::fs::write(behind_dir.path().join("a2.ttf"), b"x").unwrap(); + std::fs::create_dir_all(behind_dir.path().join("z1")).unwrap(); + std::fs::create_dir_all(behind_dir.path().join("z2")).unwrap(); + let capped_behind = super::scan_cjk_roots_bounded(&[behind_dir.path().to_path_buf()], 6, 10, 1); + assert_eq!(capped_behind.summary.truncated_dirs, 3, "{:?}", capped_behind.summary); + + // Capping depth below the subfolders reports skipped folders. + let capped_depth = super::scan_cjk_roots_bounded(&[dir.path().to_path_buf()], 0, 10, 10); + assert_eq!(capped_depth.summary.truncated_dirs, 2, "{:?}", capped_depth.summary); + assert!(capped_depth.summary.notice().is_some()); + + // Unreadable and entry-error counts appear in notice text. + let err_summary = super::CjkRootScanSummary { + unreadable_dirs: 2, + entry_errors: 3, + truncated_dirs: 0, + thread_spawn_failed: false, + sample_path: Some(dir.path().to_path_buf()), + }; + let err_notice = err_summary.notice().expect("errors should produce a notice"); + assert!(err_notice.contains("2 unreadable folder(s)"), "{err_notice}"); + assert!(err_notice.contains("3 directory entry error(s)"), "{err_notice}"); + } + + #[cfg(unix)] + #[test] + fn scan_cjk_roots_revisits_canonical_directory_when_reached_shallower() { + let dir = tempfile::tempdir().unwrap(); + let valid_font = include_bytes!("../testdata/test-fallback.otf"); + + let target = dir.path().join("target"); + let sub = target.join("sub"); + std::fs::create_dir_all(&sub).unwrap(); + let expected = sub.join("NotoSansSC-Regular.otf"); + std::fs::write(&expected, valid_font).unwrap(); + + // Sits at depth 6 under deep_root, so sub sits at depth 7 (> MAX_DEPTH) through the symlink. + let deep_parent = dir.path().join("deep").join("a").join("b").join("c").join("d").join("e"); + std::fs::create_dir_all(&deep_parent).unwrap(); + std::os::unix::fs::symlink(&target, deep_parent.join("link")).unwrap(); + + let deep_only = super::scan_cjk_roots(&[dir.path().join("deep")]); + assert!(super::find_cjk_in_index(&deep_only.files, super::CjkRegion::SimplifiedChinese).is_none()); + assert_eq!(deep_only.summary.truncated_dirs, 1, "sub at depth 7 should be reported as skipped"); + + // Visiting target again as a shallower root revisits it and discovers sub/NotoSansSC-Regular.otf. + let revisited = super::scan_cjk_roots(&[dir.path().join("deep"), target.clone()]); + assert!(revisited.summary.is_clean(), "revisited sub should not count as skipped: {:?}", revisited.summary); + let (chosen, _, _) = + super::find_cjk_in_index(&revisited.files, super::CjkRegion::SimplifiedChinese).expect("shallower root should revisit target"); + assert_eq!(chosen, expected); + } + + #[cfg(unix)] + #[test] + fn scan_cjk_roots_revisit_does_not_double_count_caps_or_entry_errors() { + let dir = tempfile::tempdir().unwrap(); + let valid_font = include_bytes!("../testdata/test-fallback.otf"); + + let target = dir.path().join("target"); + let sub = target.join("sub"); + std::fs::create_dir_all(&sub).unwrap(); + std::fs::write(target.join("other.ttf"), b"x").unwrap(); + let expected = sub.join("NotoSansSC-Regular.otf"); + std::fs::write(&expected, valid_font).unwrap(); + + let deep = dir.path().join("deep"); + std::fs::create_dir_all(&deep).unwrap(); + std::os::unix::fs::symlink(&target, deep.join("link")).unwrap(); + + // Exact unique totals across [deep, target]: 3 directories (deep, target, sub) and 2 files + // (other.ttf, NotoSansSC-Regular.otf). Under max_depth = 1, target is first visited at + // depth 1 through deep/link (leaving sub at depth 2) and revisited at depth 0 as the + // second root. Revisiting must not re-spend directory, file, or entry budgets. + let tight = super::scan_cjk_roots_bounded(&[deep.clone(), target.clone()], 1, 3, 2); + assert!(tight.summary.is_clean(), "revisit must not double-count scan caps: {:?}", tight.summary); + assert!(tight.summary.notice().is_none()); + let (chosen, _, _) = + super::find_cjk_in_index(&tight.files, super::CjkRegion::SimplifiedChinese).expect("sub must still fit within tight caps"); + assert_eq!(chosen, expected); + + // Metadata errors inside target must likewise be counted once, not duplicated on revisit. + let loop_a = target.join("loop-a"); + let loop_b = target.join("loop-b"); + std::os::unix::fs::symlink(&loop_b, &loop_a).unwrap(); + std::os::unix::fs::symlink(&loop_a, &loop_b).unwrap(); + let with_loop = super::scan_cjk_roots_bounded(&[deep, target], 1, 10, 10); + assert_eq!(with_loop.summary.entry_errors, 2, "entry errors must not double-count on revisit: {:?}", with_loop.summary); + assert_eq!(with_loop.summary.truncated_dirs, 0, "{:?}", with_loop.summary); + let (chosen_with_loop, _, _) = super::find_cjk_in_index(&with_loop.files, super::CjkRegion::SimplifiedChinese) + .expect("nested CJK font still found alongside symlink loop"); + assert_eq!(chosen_with_loop, expected); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn cjk_scan_state_stays_non_blocking_while_async_scan_runs_and_retries_when_ready() { + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + + let dir = tempfile::tempdir().unwrap(); + let nested = dir.path().join("distro").join("sub"); + std::fs::create_dir_all(&nested).unwrap(); + let valid_font = include_bytes!("../testdata/test-fallback.otf"); + std::fs::write(nested.join("NotoSansSC-Regular.otf"), valid_font).unwrap(); + + // 1) Fixed-path hit never starts the background scan, even with async enabled. + static FIXED_STATE: super::CjkScanState = super::CjkScanState::new(); + FIXED_STATE.enable_async(); + let fixed_res = FIXED_STATE.resolve_region( + super::CjkRegion::SimplifiedChinese, + |_| Some((valid_font.to_vec(), 0)), + true, + || super::scan_cjk_roots(&[]), + |_| None, + ); + assert!(matches!(fixed_res, super::CjkResolveResult::Resolved(Some(_)))); + assert!(!FIXED_STATE.is_pending()); + assert!(!FIXED_STATE.is_ready(), "fixed-path hit must not start the folder walk"); + + // 2) Async UI mode: a fixed-path miss spawns a background scan and returns Pending without + // blocking; a blocking export worker waits for the scan and resolves immediately, and UI + // retries succeed once the background scan completes and bumps FONT_GENERATION. + static ASYNC_STATE: super::CjkScanState = super::CjkScanState::new(); + ASYNC_STATE.enable_async(); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let entered = Arc::new(Mutex::new(Some(entered_tx))); + let release = Arc::new(Mutex::new(Some(release_rx))); + let scan_root = dir.path().to_path_buf(); + let gen_before = super::font_generation(); + + let first = ASYNC_STATE.resolve_region( + super::CjkRegion::SimplifiedChinese, + |_| None, + true, + move || { + if let Some(tx) = entered.lock().unwrap().take() { + let _ = tx.send(()); + } + if let Some(rx) = release.lock().unwrap().take() { + let _ = rx.recv_timeout(Duration::from_secs(5)); + } + super::scan_cjk_roots(std::slice::from_ref(&scan_root)) + }, + |_| None, + ); + assert!(matches!(first, super::CjkResolveResult::Pending), "UI caller must not block while scanning"); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("background scan thread started"); + assert!(ASYNC_STATE.is_pending()); + assert!(!ASYNC_STATE.is_ready()); + + // Subsequent UI calls while still scanning stay non-blocking and do not poison cache. + let second = + ASYNC_STATE.resolve_region(super::CjkRegion::SimplifiedChinese, |_| None, true, || super::scan_cjk_roots(&[]), |_| None); + assert!(matches!(second, super::CjkResolveResult::Pending)); + + // A background export worker using `with_blocking_cjk_scan` waits for the scan and gets + // the discovered face rather than `Pending`. + let (export_tx, export_rx) = mpsc::channel(); + let export_handle = std::thread::Builder::new() + .name("test-cjk-export".into()) + .spawn(move || { + let res = super::with_blocking_cjk_scan(|| { + ASYNC_STATE.resolve_region(super::CjkRegion::SimplifiedChinese, |_| None, true, || super::scan_cjk_roots(&[]), |_| None) + }); + let _ = + export_tx.send(matches!(res, super::CjkResolveResult::Resolved(Some((bytes, 0))) if bytes.as_slice() == valid_font)); + }) + .unwrap(); + + release_tx.send(()).unwrap(); + assert!(export_rx.recv_timeout(Duration::from_secs(5)).unwrap(), "export worker must resolve discovered CJK font"); + export_handle.join().unwrap(); + + let deadline = Instant::now() + Duration::from_secs(5); + while !ASYNC_STATE.is_ready() || super::font_generation() == gen_before { + assert!(Instant::now() < deadline, "timed out waiting for async scan completion"); + std::thread::yield_now(); + } + assert!(!ASYNC_STATE.is_pending()); + assert!(super::font_generation() > gen_before, "completing scan must bump font generation"); + + let (retried, hit_pending_after) = super::track_pending_cjk(|| { + ASYNC_STATE.resolve_region(super::CjkRegion::SimplifiedChinese, |_| None, true, || super::scan_cjk_roots(&[]), |_| None) + }); + assert!(!hit_pending_after, "resolved CJK lookup must not report pending"); + match retried { + super::CjkResolveResult::Resolved(Some((bytes, idx))) => { + assert_eq!(bytes.as_slice(), valid_font); + assert_eq!(*idx, 0); + } + _ => panic!("retry after background scan completes must return discovered CJK font"), + } + assert!(ASYNC_STATE.take_summary().is_none(), "clean scan emits no notice"); + + // 3) Empty async scan still bumps FONT_GENERATION so disk-cache fallback unblocks metrics. + static EMPTY_ASYNC_STATE: super::CjkScanState = super::CjkScanState::new(); + EMPTY_ASYNC_STATE.enable_async(); + let empty_gen = super::font_generation(); + let (empty_first, hit_pending) = super::track_pending_cjk(|| { + EMPTY_ASYNC_STATE.resolve_region( + super::CjkRegion::SimplifiedChinese, + |_| None, + true, + || super::scan_cjk_roots(&[]), + |_| Some((valid_font.to_vec(), 0)), + ) + }); + assert!(matches!(empty_first, super::CjkResolveResult::Pending)); + assert!(hit_pending, "pending async scan lookup must signal track_pending_cjk"); + let empty_deadline = Instant::now() + Duration::from_secs(5); + while !EMPTY_ASYNC_STATE.is_ready() || super::font_generation() == empty_gen { + assert!(Instant::now() < empty_deadline, "timed out waiting for empty async scan"); + std::thread::yield_now(); + } + assert!(EMPTY_ASYNC_STATE.is_ready()); + assert!(super::font_generation() > empty_gen, "empty async scan must still bump font generation"); + let cached_fallback = EMPTY_ASYNC_STATE.resolve_region( + super::CjkRegion::SimplifiedChinese, + |_| None, + true, + || super::scan_cjk_roots(&[]), + |_| Some((valid_font.to_vec(), 0)), + ); + assert!(matches!(cached_fallback, super::CjkResolveResult::Resolved(Some(_)))); + + // 4) Refused scan thread records a non-clean notice without running the walk inline. + static REFUSED_STATE: super::CjkScanState = super::CjkScanState::new(); + REFUSED_STATE.enable_async(); + REFUSED_STATE.record_spawn_refused(); + assert!(REFUSED_STATE.is_ready()); + assert!(!REFUSED_STATE.is_pending()); + let refused_summary = REFUSED_STATE.take_summary().expect("spawn refusal must produce a notice"); + assert!(refused_summary.thread_spawn_failed); + assert!(refused_summary.notice().is_some_and(|n| n.contains("background scan thread could not start"))); + + // 5) Sync headless/CLI mode (async not enabled): resolves synchronously on the first call. + static SYNC_STATE: super::CjkScanState = super::CjkScanState::new(); + let sync_root = dir.path().to_path_buf(); + let sync_res = SYNC_STATE.resolve_region( + super::CjkRegion::SimplifiedChinese, + |_| None, + true, + move || super::scan_cjk_roots(std::slice::from_ref(&sync_root)), + |_| None, + ); + match sync_res { + super::CjkResolveResult::Resolved(Some((bytes, idx))) => { + assert_eq!(bytes.as_slice(), valid_font); + assert_eq!(*idx, 0); + } + _ => panic!("sync mode must discover nested CJK font immediately"), + } + } + + #[cfg(unix)] + #[test] + fn scan_cjk_roots_deduplicates_self_link_and_skips_named_pipes() { + let dir = tempfile::tempdir().unwrap(); + let valid_font = include_bytes!("../testdata/test-fallback.otf"); + + // Self-referencing symlink sorted before `z` must not consume the remaining directory slot. + std::os::unix::fs::symlink(dir.path(), dir.path().join("a-link")).unwrap(); + let z_dir = dir.path().join("z"); + std::fs::create_dir_all(&z_dir).unwrap(); + let expected = z_dir.join("NotoSansSC-Regular.otf"); + std::fs::write(&expected, valid_font).unwrap(); + + let tight = super::scan_cjk_roots_bounded(&[dir.path().to_path_buf()], 6, 2, 10); + assert!(tight.summary.is_clean(), "self-link alias must not exhaust dir cap: {:?}", tight.summary); + let (chosen, _, _) = + super::find_cjk_in_index(&tight.files, super::CjkRegion::SimplifiedChinese).expect("z should use the second directory slot"); + assert_eq!(chosen, expected); + + // Named pipe (FIFO) with a matching CJK font filename must be skipped and never block open. + let fifo_dir = tempfile::tempdir().unwrap(); + let fifo_path = fifo_dir.path().join("NotoSansSC-Regular.otf"); + let mkfifo = std::process::Command::new("mkfifo").arg(&fifo_path).status().expect("mkfifo available on unix"); + assert!(mkfifo.success(), "mkfifo failed"); + let fifo_scan = super::scan_cjk_roots(&[fifo_dir.path().to_path_buf()]); + assert!(fifo_scan.summary.is_clean(), "{:?}", fifo_scan.summary); + assert!(fifo_scan.files.is_empty(), "special files must not be indexed: {:?}", fifo_scan.files); + assert!(super::read_bounded(&fifo_path, super::MAX_FONT_BYTES as u64).is_none(), "read_bounded must reject FIFOs without blocking"); + } + + #[cfg(unix)] + #[test] + fn scan_cjk_roots_reports_metadata_error_on_symlink_loop() { + // Symlink loops produce a non-NotFound metadata error (ELOOP) regardless of user privileges. + let loop_dir = tempfile::tempdir().unwrap(); + let loop_a = loop_dir.path().join("loop-a"); + let loop_b = loop_dir.path().join("loop-b"); + std::os::unix::fs::symlink(&loop_b, &loop_a).unwrap(); + std::os::unix::fs::symlink(&loop_a, &loop_b).unwrap(); + let loop_scan = super::scan_cjk_roots(&[loop_dir.path().to_path_buf()]); + assert!(!loop_scan.summary.is_clean(), "{:?}", loop_scan.summary); + assert_eq!(loop_scan.summary.entry_errors, 2, "{:?}", loop_scan.summary); + assert_eq!(loop_scan.summary.sample_path.as_deref(), Some(loop_a.as_path())); + + // When scan caps are already exhausted, a later root whose metadata fails with a non-NotFound + // error is still counted as skipped rather than silently dropped like NotFound. + let first_root = tempfile::tempdir().unwrap(); + std::fs::write(first_root.path().join("a.ttf"), b"x").unwrap(); + let missing_root = first_root.path().join("does-not-exist"); + let capped = super::scan_cjk_roots_bounded(&[first_root.path().to_path_buf(), missing_root, loop_a.clone()], 6, 10, 1); + assert_eq!(capped.summary.truncated_dirs, 1, "{:?}", capped.summary); + assert_eq!(capped.summary.sample_path.as_deref(), Some(loop_a.as_path())); + } } diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index f7ae98b085..aeb83443ae 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -174,7 +174,13 @@ fn installed_cjk(region: CjkRegion) -> Option<&'static FontRef<'static>> { if none_installed { None } else { - FACES.get(cjk_slot(region))?.get_or_init(|| crate::fonts::cjk_font(region).and_then(parse_cjk)).as_ref() + // Once a face is parsed it is cached. Until then a temporary `None` (the Linux CJK root + // scan running in the background) is not cached, so the lookup runs again on the next call. + if let Some(face) = FACES.get(cjk_slot(region)).and_then(OnceLock::get) { + return face.as_ref(); + } + let data = crate::fonts::cjk_font(region)?; + FACES.get(cjk_slot(region))?.get_or_init(|| parse_cjk(data)).as_ref() } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 403d4daad5..924c54d762 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1613,6 +1613,16 @@ pub struct RustGisApp { /// Coverage of the last chosen catalog in the active font stack. Cleared when fonts change /// or a language is picked again, so checking thousands of letters is never a per-frame loop. language_coverage: Option<(i18n::Lang, bool)>, + /// Bounded CJK font-scan summary held until the selected interface language is active (or + /// known to lack font coverage), so the notice is translated into the active UI language. + pending_cjk_scan_notice: Option, + /// Whether the UI has already reconciled a completed background Linux CJK folder scan. + cjk_roots_applied: bool, + /// Whether `add_cjk_fallback` missed while an async Linux CJK folder scan was in flight and + /// should retry once that scan finishes. + cjk_fallback_deferred: bool, + #[cfg(test)] + test_cjk_roots_state: Option<(bool, bool)>, /// The project path last seen, so a change (whoever opened or saved it) updates Last Project. seen_project: Option, } @@ -1789,6 +1799,7 @@ impl RustGisApp { // This front end has the Download Datum Grids setting, so a note about a missing grid can // point to it. s.offers_grid_downloads = true; + rustgis_engine::claim_ui_cjk_scan_notice(); if s.active_layer.is_none() { s.active_layer = s.map().layers.first().map(|l| l.id); } @@ -1889,6 +1900,11 @@ impl RustGisApp { label_fonts_indexed: false, shown_lang: i18n::Lang::EN, language_coverage: None, + pending_cjk_scan_notice: None, + cjk_roots_applied: rustgis_engine::render::fonts::cjk_roots_ready(), + cjk_fallback_deferred: false, + #[cfg(test)] + test_cjk_roots_state: None, seen_project: None, autosave: Default::default(), save_prompt: Default::default(), @@ -2118,6 +2134,13 @@ impl RustGisApp { } let name = format!("script-{region:?}"); let have = self.extra_fonts.iter().any(|(_, _, r)| *r == Some(region)); + if !have + && !self.fonts_failed.contains(&name) + && matches!(region, rustgis_engine::render::fonts::ScriptFont::Cjk(_)) + && self.cjk_scan_in_flight() + { + return false; + } if !have && self.fonts_requested.contains(&name) && !self.fonts_failed.contains(&name) @@ -2177,21 +2200,98 @@ impl RustGisApp { covered } + fn cjk_roots_pending(&self) -> bool { + #[cfg(test)] + if let Some((pending, _)) = self.test_cjk_roots_state { + return pending; + } + rustgis_engine::render::fonts::cjk_roots_pending() + } + + fn cjk_roots_ready(&self) -> bool { + #[cfg(test)] + if let Some((_, ready)) = self.test_cjk_roots_state { + return ready; + } + rustgis_engine::render::fonts::cjk_roots_ready() + } + + fn cjk_scan_in_flight(&self) -> bool { + self.cjk_roots_pending() || (!self.cjk_roots_applied && self.cjk_roots_ready()) + } + /// On the desktop, an installed CJK face as a last-resort fallback, so CJK text (language names /// in the picker, place names in data) renders whatever the interface language. The bytes are - /// borrowed from the font cache, not copied. - fn add_cjk_fallback(&mut self) { + /// borrowed from the font cache, not copied. Returns `true` when a face was newly added. + fn add_cjk_fallback(&mut self) -> bool { use rustgis_engine::render::fonts::{CjkRegion, cjk_font}; if self.extra_fonts.iter().any(|(n, _, _)| n == "cjk-fallback") { - return; + return false; } let found = [CjkRegion::SimplifiedChinese, CjkRegion::Japanese, CjkRegion::Korean].into_iter().find_map(cjk_font); if let Some((bytes, index)) = found { let face = theme::installed_face(bytes, *index, true); self.extra_fonts.push(("cjk-fallback".into(), std::sync::Arc::new(face), None)); + return true; + } + if self.cjk_scan_in_flight() { + self.cjk_fallback_deferred = true; + } + false + } + + /// Captures any CJK font-folder scan diagnostic summary after font lookups run and emits a + /// translated notice once the selected interface language is active (or confirmed unavailable). + fn flush_cjk_scan_notice(&mut self) { + if self.pending_cjk_scan_notice.is_none() { + self.pending_cjk_scan_notice = rustgis_engine::render::fonts::take_cjk_scan_summary(); + } + let chosen = self.chosen_lang(); + let settled = self.shown_lang == chosen || self.language_coverage == Some((chosen, false)); + if !settled { + return; + } + let Some(summary) = self.pending_cjk_scan_notice.take() else { return }; + let prev = i18n::current(); + i18n::set_current(self.shown_lang); + let msg = Self::format_cjk_scan_notice(&summary); + i18n::set_current(prev); + if let Some(msg) = msg { + self.session.notify(msg, false); } } + fn format_cjk_scan_notice(summary: &rustgis_engine::render::fonts::CjkRootScanSummary) -> Option { + if summary.is_clean() { + return None; + } + let mut parts = Vec::new(); + if summary.thread_spawn_failed { + parts.push(i18n::t_raw("background scan thread could not start").to_string()); + } + if summary.truncated_dirs > 0 { + parts.push(i18n::fmt_raw("{count} folder(s) reached the scan limit", &[("count", &summary.truncated_dirs.to_string())])); + } + if summary.unreadable_dirs > 0 { + parts.push(i18n::fmt_raw("{count} unreadable folder(s)", &[("count", &summary.unreadable_dirs.to_string())])); + } + if summary.entry_errors > 0 { + parts.push(i18n::fmt_raw("{count} directory entry error(s)", &[("count", &summary.entry_errors.to_string())])); + } + let details = parts.join(", "); + let msg = match summary.sample_path.as_deref() { + Some(path) => i18n::fmt( + "CJK font folder search stopped early: {details} (e.g. {path}); some installed CJK fonts may not be found.", + &[("details", &details), ("path", &path.display().to_string())], + ), + None => i18n::fmt( + "CJK font folder search stopped early: {details}; some installed CJK fonts may not be found.", + &[("details", &details)], + ), + }; + Some(msg) + } + /// On the desktop, an installed symbol face as a last-resort fallback, so marks the interface /// faces lack (Segoe UI has no "✓") don't draw as boxes. The bytes are borrowed from the font /// cache, not copied. @@ -2229,7 +2329,7 @@ impl RustGisApp { /// Makes sure the current language's script has a font: an installed face on the desktop, a /// download on the web. fn ensure_script_font(&mut self) { - use rustgis_engine::render::fonts::{script_font, script_font_url}; + use rustgis_engine::render::fonts::{ScriptFont, script_font, script_font_url}; // Switching between script languages reorders the faces already loaded. if self.current_region() != self.installed_region { self.fonts_dirty = true; @@ -2240,12 +2340,19 @@ impl RustGisApp { { return; } - self.fonts_requested.push(name.clone()); if let Some((bytes, index)) = script_font(region) { - let face = theme::installed_face(bytes, *index, matches!(region, rustgis_engine::render::fonts::ScriptFont::Cjk(_))); + self.fonts_requested.push(name.clone()); + let face = theme::installed_face(bytes, *index, matches!(region, ScriptFont::Cjk(_))); self.extra_fonts.push((name, std::sync::Arc::new(face), Some(region))); self.fonts_dirty = true; - } else if let (Some(fetch), Some(url)) = (&self.services.fetch_font, script_font_url(region)) { + return; + } + if matches!(region, ScriptFont::Cjk(_)) && self.cjk_scan_in_flight() { + // Linux CJK folder scan is running off the UI thread; retry once it finishes. + return; + } + self.fonts_requested.push(name); + if let (Some(fetch), Some(url)) = (&self.services.fetch_font, script_font_url(region)) { fetch(url); } else { log::warn!("no {region:?} font installed; text in that script may not display"); @@ -2340,9 +2447,10 @@ impl RustGisApp { /// CJK font installed). fn ensure_data_cjk_font(&mut self, ctx: &egui::Context) { use rustgis_engine::render::fonts::{CjkRegion, CjkScript, ScriptFont, script_font_url, take_missing_cjk}; - if self.fonts_dirty || self.fonts_pending { + if self.fonts_dirty || self.fonts_pending || self.cjk_scan_in_flight() { return; } + let fetching = self.services.fetch_font.is_some(); let samples = rustgis_engine::render::fonts::peek_missing_text(); let missing: Vec<_> = take_missing_cjk() .into_iter() @@ -2356,7 +2464,6 @@ impl RustGisApp { return; } let han = if missing.contains(&CjkScript::Han) { self.han_region() } else { CjkRegion::SimplifiedChinese }; - let fetching = self.services.fetch_font.is_some(); if !fetching { for script in missing { if self.cjk_scripts_handled.contains(&script) { @@ -7296,6 +7403,18 @@ impl RustGisApp { } None })); + // Reconcile a completed off-thread Linux CJK folder scan before requesting script fonts. + if !self.cjk_roots_applied && self.cjk_roots_ready() { + self.cjk_roots_applied = true; + if self.cjk_fallback_deferred { + self.cjk_fallback_deferred = false; + if self.add_cjk_fallback() { + self.fonts_dirty = true; + } + } + self.map.invalidate(); + self.layout.redraw(); + } self.ensure_script_font(); self.ensure_data_cjk_font(ctx); self.ensure_other_script_fonts(ctx); @@ -7479,6 +7598,11 @@ impl RustGisApp { theme::install_fonts(ctx, &self.extra_fonts, self.installed_region); self.fonts_pending = true; } + if self.cjk_roots_pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } else if !self.cjk_roots_applied && self.cjk_roots_ready() { + ctx.request_repaint(); + } // Switch the drawn language once its font can draw it; until then keep the previous one. let chosen = self.chosen_lang(); if self.shown_lang != chosen { @@ -7489,6 +7613,7 @@ impl RustGisApp { ctx.request_repaint(); } } + self.flush_cjk_scan_notice(); self.refresh_themes(ctx); if self.ui.dark_follows_system && let Some(system) = ctx.system_theme() @@ -7632,8 +7757,16 @@ impl RustGisApp { autosave::tick(self, &ctx); } // Missing text first drawn this frame needs a next logic pass even without input. - // Handled requests wait for their result instead of keeping an idle window repainting. - if rustgis_engine::render::fonts::peek_missing_cjk().iter().any(|s| !self.cjk_scripts_handled.contains(s)) + // Handled requests (or CJK misses waiting on an in-flight Linux folder scan) wait for + // their result instead of keeping an idle window repainting every frame; if a scan + // started (or completed) during `ui`, schedule the poll or immediate reconciliation. + if self.cjk_roots_pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } else if !self.cjk_roots_applied && self.cjk_roots_ready() { + ctx.request_repaint(); + } + if (!self.cjk_scan_in_flight() + && rustgis_engine::render::fonts::peek_missing_cjk().iter().any(|s| !self.cjk_scripts_handled.contains(s))) || rustgis_engine::render::fonts::peek_missing_text() .iter() .any(|(s, _)| !matches!(s, rustgis_engine::render::fonts::ScriptFont::Cjk(_)) && !self.other_scripts_handled.contains(s)) @@ -8159,12 +8292,166 @@ mod language_coverage_tests { frame(&mut app, &ctx); assert_eq!(app.lang(), i18n::Lang::EN, "a valid font with no Persian must not activate Persian"); } + + #[test] + fn cjk_scan_notice_waits_for_selected_language_before_emitting() { + use rustgis_engine::render::fonts::CjkRootScanSummary; + + let mut app = RustGisApp::with_sample(); + assert!(rustgis_engine::ui_owns_cjk_scan_notice(), "UI shell claims process-wide ownership of the CJK scan notice"); + app.run("ui.language", json!({"code": "de"})).unwrap(); + app.pending_cjk_scan_notice = Some(CjkRootScanSummary { + truncated_dirs: 2, + unreadable_dirs: 0, + entry_errors: 1, + thread_spawn_failed: false, + sample_path: Some(std::path::PathBuf::from("/run/host/fonts")), + }); + let ctx = egui::Context::default(); + let mark = app.session.notice_mark(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.label("Host text before RustGIS"); + app.logic(ui.ctx()); + }); + output.textures_delta.clear(); + assert_eq!(app.lang(), i18n::Lang::EN); + assert!(app.pending_cjk_scan_notice.is_some(), "retain summary until shown_lang switches"); + assert!( + !app.session.notices_since(mark).iter().any(|n| n.text.contains("/run/host/fonts")), + "must not emit scan notice before shown_lang settles" + ); + + frame(&mut app, &ctx); + assert_eq!(app.lang().code(), "de"); + assert!(app.pending_cjk_scan_notice.is_none()); + let matching: Vec<_> = app.session.notices_since(mark).iter().filter(|n| n.text.contains("/run/host/fonts")).collect(); + assert_eq!(matching.len(), 1, "{matching:?}"); + + // If the chosen language cannot be drawn, flush the pending notice once coverage fails. + let (mut missing_app, missing_ctx) = without_script_font("ja"); + missing_app.pending_cjk_scan_notice = Some(CjkRootScanSummary { + truncated_dirs: 0, + unreadable_dirs: 1, + entry_errors: 0, + thread_spawn_failed: false, + sample_path: Some(std::path::PathBuf::from("/run/host/user-fonts")), + }); + let missing_mark = missing_app.session.notice_mark(); + frame(&mut missing_app, &missing_ctx); + assert_eq!(missing_app.lang(), i18n::Lang::EN); + assert!(missing_app.pending_cjk_scan_notice.is_none(), "summary must flush once chosen language fails coverage"); + assert!( + missing_app.session.notices_since(missing_mark).iter().any(|n| n.text.contains("/run/host/user-fonts")), + "{:?}", + missing_app.session.notices_since(missing_mark) + ); + } + + #[test] + fn cjk_language_waits_for_async_cjk_root_scan_before_reporting_unavailable() { + #[cfg(not(target_arch = "wasm32"))] + if crate::isolate_account_test("language_coverage_tests::cjk_language_waits_for_async_cjk_root_scan_before_reporting_unavailable") { + return; + } + let (mut app, ctx) = without_script_font("ja"); + // Keep `fonts_requested` populated so host macOS/Windows fonts are not pulled in, while + // clearing `fonts_failed` so `can_draw` behaves as an in-flight Linux CJK scan. + app.fonts_failed.clear(); + app.cjk_roots_applied = false; + app.test_cjk_roots_state = Some((true, false)); + let mark = app.session.notice_mark(); + + frame(&mut app, &ctx); + assert_eq!(app.lang(), i18n::Lang::EN); + assert!(app.language_coverage.is_none(), "must not cache failure while CJK root scan is pending"); + assert!(!app.cjk_roots_applied); + assert!( + !app.session.notices_since(mark).iter().any(|n| n.text.contains("can't display")), + "must not emit missing-font notice before CJK root scan finishes: {:?}", + app.session.notices_since(mark) + ); + + // Once the background scan finishes with no Japanese font found, coverage is evaluated + // and the unavailability notice is emitted once. + app.test_cjk_roots_state = Some((false, true)); + frame(&mut app, &ctx); + assert!(app.cjk_roots_applied); + assert_eq!(app.lang(), i18n::Lang::EN); + assert_eq!(app.language_coverage, Some((app.chosen_lang(), false))); + let unavailable: Vec<_> = app.session.notices_since(mark).iter().filter(|n| n.text.contains("can't display")).collect(); + assert_eq!(unavailable.len(), 1, "{unavailable:?}"); + + // While a scan is pending, data-CJK downloads are also deferred even when fetch_font is set. + let (mut dl_app, dl_ctx) = without_script_font("en"); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = asked.clone(); + dl_app.services.fetch_font = Some(Box::new(move |url| sink.lock().unwrap().push(url.to_string()))); + dl_app.cjk_roots_applied = false; + dl_app.test_cjk_roots_state = Some((true, false)); + rustgis_engine::render::fonts::note_missing_cjk('か'); + let mut output = dl_ctx.run_ui(egui::RawInput::default(), |ui| dl_app.ensure_data_cjk_font(ui.ctx())); + output.textures_delta.clear(); + assert!(asked.lock().unwrap().is_empty(), "must not start font download while CJK folder scan is in flight"); + + // A scan started during `ui` (after `logic` already ran) must still schedule a delayed + // repaint poll without busy-spinning, and completing during `ui` must wake immediately. + let immediate = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let delayed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (imm_sink, del_sink) = (immediate.clone(), delayed.clone()); + dl_ctx.set_repaint_observer(move |req| { + if req.delay.is_zero() { + imm_sink.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } else if req.delay <= std::time::Duration::from_millis(50) { + del_sink.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + }); + dl_app.fonts_frames = 2; + dl_app.label_fonts_indexed = true; + dl_app.chrome = Some(|_, _| {}); + dl_app.test_cjk_roots_state = Some((false, false)); + let _ = rustgis_engine::render::fonts::take_missing_cjk(); + let raw_input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 240.0))), + ..Default::default() + }; + for _ in 0..8 { + let mut output = dl_ctx.run_ui(raw_input.clone(), |ui| { + dl_app.logic(ui.ctx()); + dl_app.ui(ui); + }); + output.textures_delta.clear(); + } + dl_app.cjk_roots_applied = false; + dl_app.test_cjk_roots_state = Some((true, false)); + rustgis_engine::render::fonts::note_missing_cjk('か'); + let mut output = dl_ctx.run_ui(raw_input.clone(), |ui| { + immediate.store(0, std::sync::atomic::Ordering::SeqCst); + delayed.store(0, std::sync::atomic::Ordering::SeqCst); + dl_app.ui(ui); + }); + output.textures_delta.clear(); + assert_eq!(immediate.load(std::sync::atomic::Ordering::SeqCst), 0, "in-flight scan must not busy-spin immediate repaints"); + assert!(delayed.load(std::sync::atomic::Ordering::SeqCst) > 0, "in-flight scan must schedule a delayed poll at end of ui"); + + dl_app.test_cjk_roots_state = Some((false, true)); + let mut output = dl_ctx.run_ui(raw_input, |ui| { + immediate.store(0, std::sync::atomic::Ordering::SeqCst); + dl_app.ui(ui); + }); + output.textures_delta.clear(); + assert!(immediate.load(std::sync::atomic::Ordering::SeqCst) > 0, "completed scan during ui must wake immediately"); + + // Drain missing CJK bit cleanly so other tests start clean. + let _ = rustgis_engine::render::fonts::take_missing_cjk(); + } } #[cfg(test)] mod cjk_download_tests { /// Initializes the font stack before a poll can recheck actual missing characters. fn poll_cjk(app: &mut super::RustGisApp) { + // Download tests emulate a browser/environment with no Linux CJK folder scan in flight. + app.test_cjk_roots_state = Some((false, false)); let ctx = egui::Context::default(); let mut output = ctx.run_ui(egui::RawInput::default(), |ui| app.ensure_data_cjk_font(ui.ctx())); output.textures_delta.clear();