PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Load Thai fallback fonts for native UI text (#2280)
Harrison O'Connor-Hoovere7df11d7703a
diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/cjk_fonts.rsindex 80df017a9..bbb1e14d0 100644--- a/crates/ui-egui/src/cjk_fonts.rs+++ b/crates/ui-egui/src/cjk_fonts.rs@@ -1,11 +1,12 @@-//! Lazy CJK fallback fonts for the UI.+//! Lazy CJK and Thai fallback fonts for the UI.//!//! The bundled Inter / JetBrains Mono have no Japanese, Chinese or Korean glyphs, and the OS//! fonts that do are large (Hiragino ~10 MB, Apple SD Gothic Neo 28 MB, PingFang 78 MB, Noto//! Sans CJK ~20 MB). Instead of reading them at startup, an egui plugin scans each frame's text//! for CJK characters no registered font covers, and registers the next system font for that//! character's script (`ctx.add_font`, active from the next frame, which it requests). Fonts are-//! appended at the lowest priority to every family, so Latin text keeps Inter.+//! appended at the lowest priority to every family, so Latin text keeps Inter. Thai has its own+//! candidate list and attempt state, independent of the locale-dependent CJK order.//!//! Script order follows the UI locale ([`photocraft_text::cjk::script_order`]): Kana prefers a//! Japanese font, Hangul a Korean one, Bopomofo a Traditional Chinese one, and Han the@@ -34,6 +35,8 @@ pub struct Sources {pub locale: fn() -> Option<String>,pub files: fn(CjkScript) -> Vec<FontFile>,pub last_resort: fn() -> Vec<FontFile>,+ /// Thai fonts, loaded only when a visible Thai character is missing.+ pub thai: fn() -> Vec<FontFile>,/// Embedded fonts tried before `files` for a script (craft-fonts' Japanese fonts).pub embedded: fn(CjkScript) -> Vec<&'static CraftFont>,}@@ -58,12 +61,13 @@ impl Sources {},files: cjk::font_files,last_resort: cjk::last_resort_files,+ thai: thai_font_files,embedded: craft_embedded,}}#[cfg(target_arch = "wasm32")]pub fn system() -> Self {- Self { locale: || None, files: |_| Vec::new(), last_resort: Vec::new, embedded: craft_embedded }+ Self { locale: || None, files: |_| Vec::new(), last_resort: Vec::new, thai: Vec::new, embedded: craft_embedded }}}@@ -75,6 +79,7 @@ pub struct CjkFallback {order: Option<[CjkScript; 4]>,tried: Vec<CjkScript>,last_resort_tried: bool,+ thai_tried: bool,loaded: Vec<PathBuf>,/// Fonts registered so far: (name, path, face index).pub registered: Vec<(String, PathBuf, u32)>,@@ -82,7 +87,16 @@ pub struct CjkFallback {impl CjkFallback {pub fn new(sources: Sources) -> Self {- Self { sources, defer_after_reset: false, order: None, tried: Vec::new(), last_resort_tried: false, loaded: Vec::new(), registered: Vec::new() }+ Self {+ sources,+ defer_after_reset: false,+ order: None,+ tried: Vec::new(),+ last_resort_tried: false,+ thai_tried: false,+ loaded: Vec::new(),+ registered: Vec::new(),+ }}/// Script order for the UI locale (resolved on first use, not at startup).@@ -122,6 +136,13 @@ impl CjkFallback {None}+ fn next_thai_font(&mut self) -> Option<(String, FontData)> {+ if std::mem::replace(&mut self.thai_tried, true) {+ return None;+ }+ self.load_first(&(self.sources.thai)())+ }+/// The first embedded (craft-fonts) font for `s`, registered from its static bytes.fn load_embedded(&mut self, s: CjkScript) -> Option<(String, FontData)> {let f = (self.sources.embedded)(s).into_iter().find(|f| !f.bytes.is_empty())?;@@ -159,14 +180,18 @@ impl CjkFallback {}}-/// First CJK character in the frame's text that the UI fonts can't draw.-fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape]) -> Option<char> {- fn collect(shape: &Shape, out: &mut Vec<char>) {+fn is_thai(c: char) -> bool {+ matches!(c, '\u{0e00}'..='\u{0e7f}')+}++/// First supported missing character for which a fallback has not yet been exhausted.+fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape], fallback: &CjkFallback) -> Option<char> {+ fn collect(shape: &Shape, out: &mut Vec<char>, cjk_pending: bool, thai_pending: bool) {match shape {Shape::Text(t) => {let text = &t.galley.job.text;if !text.is_ascii() {- for c in text.chars().filter(|c| cjk::classify(*c).is_some()) {+ for c in text.chars().filter(|c| (cjk_pending && cjk::classify(*c).is_some()) || (thai_pending && is_thai(*c))) {if out.len() >= 256 {return;}@@ -176,13 +201,13 @@ fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape]) -> O}}}- Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),+ Shape::Vec(v) => v.iter().for_each(|s| collect(s, out, cjk_pending, thai_pending)),_ => {}}}let mut chars = Vec::new();for s in shapes {- collect(&s.shape, &mut chars);+ collect(&s.shape, &mut chars, !fallback.exhausted(), !fallback.thai_tried);}if chars.is_empty() {return None;@@ -262,22 +287,22 @@ impl egui::Plugin for CjkFontPlugin {ctx.request_repaint();return;}- if self.0.exhausted() {+ if self.0.exhausted() && self.0.thai_tried {return;}- let Some(c) = missing_char(ctx, &output.shapes) else { return };- let Some(kind) = cjk::classify(c) else { return };- if let Some((name, data)) = self.0.next_font(kind) {+ let Some(c) = missing_char(ctx, &output.shapes, &self.0) else { return };+ let font = if is_thai(c) { self.0.next_thai_font() } else { cjk::classify(c).and_then(|kind| self.0.next_font(kind)) };+ if let Some((name, data)) = font {add_to_all_families(ctx, name, data);ctx.request_repaint();- } else if !self.0.exhausted() {+ } else if !self.0.exhausted() || !self.0.thai_tried {// Nothing readable for this script; try the next one on the next frame.ctx.request_repaint();}}}-/// Installs the lazy CJK fallback (system fonts; nothing on the web).+/// Installs the lazy CJK and Thai fallback (system fonts; nothing on the web).pub fn install(ctx: &egui::Context) {install_with(ctx, Sources::system());}@@ -298,6 +323,38 @@ pub fn install_with(ctx: &egui::Context, sources: Sources) {}}+/// Common native Thai fonts. Keep discovery lazy, as with the CJK candidates: no full+/// system font scan on the UI thread and no extra font files embedded in the web build.+#[cfg(not(target_arch = "wasm32"))]+fn thai_font_files() -> Vec<FontFile> {+ let f = |path: &str, family| FontFile { path: path.into(), family };+ if cfg!(target_os = "macos") {+ vec![f("/System/Library/Fonts/Supplemental/Thonburi.ttc", "Thonburi"), f("/System/Library/Fonts/Supplemental/SukhumvitSet.ttc", "Sukhumvit Set")]+ } else if cfg!(target_os = "windows") {+ let dir = std::env::var_os("WINDIR").map_or_else(|| PathBuf::from("C:\\Windows"), PathBuf::from).join("Fonts");+ [("Leelawui.ttf", "Leelawadee UI"), ("leelawad.ttf", "Leelawadee"), ("tahoma.ttf", "Tahoma")]+ .into_iter()+ .map(|(file, family)| FontFile { path: dir.join(file), family })+ .collect()+ } else {+ thai_unix_font_files()+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn thai_unix_font_files() -> Vec<FontFile> {+ // Fedora's static and variable packages, Debian/Ubuntu, then Arch/Noto installations.+ // Flatpak exposes the host's /usr/share/fonts as /run/host/fonts.+ ["google-noto/NotoSansThai-Regular.ttf", "google-noto-vf/NotoSansThai[wght].ttf", "truetype/noto/NotoSansThai-Regular.ttf", "noto/NotoSansThai-Regular.ttf"]+ .into_iter()+ .flat_map(|file| {+ ["/usr/share/fonts", "/run/host/fonts", "/usr/local/share/fonts"]+ .into_iter()+ .map(move |root| FontFile { path: std::path::Path::new(root).join(file), family: "Noto Sans Thai" })+ })+ .collect()+}+#[cfg(test)]#[cfg(not(target_arch = "wasm32"))]mod tests {@@ -379,6 +436,7 @@ mod tests {_ => vec![],},last_resort: || vec![fake("font.ttf")],+ thai: Vec::new,embedded: no_embedded,}}@@ -409,7 +467,7 @@ mod tests {("zh-Hant-TW", CjkScript::TraditionalChinese),("ko_KR", CjkScript::Korean),] {- let mut fb = CjkFallback::new(Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, embedded: no_embedded });+ let mut fb = CjkFallback::new(Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: no_embedded });fb.order = Some(cjk::script_order(Some(loc)));assert!(fb.next_font(CjkChar::Han).is_none());assert_eq!(fb.tried[0], first, "{loc}");@@ -427,6 +485,68 @@ mod tests {ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(12.0), &text.replace(' ', "")))}+ #[test]+ fn thai_candidates_include_fedora_static_variable_and_flatpak_fonts() {+ let files = thai_unix_font_files();+ for root in ["/usr/share/fonts", "/run/host/fonts"] {+ for file in ["google-noto/NotoSansThai-Regular.ttf", "google-noto-vf/NotoSansThai[wght].ttf"] {+ assert!(files.iter().any(|f| f.path == std::path::Path::new(root).join(file) && f.family == "Noto Sans Thai"));+ }+ }+ }++ #[test]+ fn thai_loading_is_lazy_once_per_install_and_independent_of_cjk() {+ let sources = Sources {+ locale: || Some("en".into()),+ files: |_| vec![],+ last_resort: Vec::new,+ thai: || vec![fake("missing.ttf"), fake("empty.ttf"), fake("font.ttf")],+ embedded: no_embedded,+ };+ let ctx = egui::Context::default();+ for _ in 0..2 {+ crate::theme::install_fonts_with(&ctx, sources.clone());+ assert!(render(&ctx, "Recent file.png"));+ ctx.with_plugin::<CjkFontPlugin, _>(|p| {+ assert!(!p.0.thai_tried, "Latin-only frames do not request Thai fonts");+ assert!(p.0.registered.is_empty());+ });+ // The stand-in does not draw Thai. An unavailable CJK glyph preceding Thai must+ // not prevent trying the Thai font, nor cause registration/repaint loops.+ assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png"));+ ctx.with_plugin::<CjkFontPlugin, _>(|p| {+ assert!(p.0.exhausted());+ assert!(p.0.thai_tried);+ assert_eq!(p.0.registered.len(), 1);+ });+ let fonts = ctx.fonts(|f| f.definitions().clone());+ assert_eq!(fonts.families[&FontFamily::Proportional].first().map(String::as_str), Some("Inter"));+ for stack in fonts.families.values() {+ assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 1);+ assert_eq!(stack.last().map(String::as_str), Some("system-cjk-0"));+ }+ }+ // Exhausting Thai first must likewise leave CJK available.+ let mut fallback = CjkFallback::new(fake_sources(|| Some("ko".into())));+ assert!(fallback.next_thai_font().is_none());+ assert!(fallback.next_font(CjkChar::Hangul).is_some());+ }++ #[test]+ fn system_fonts_cover_thai_recent_file_names() {+ // Like the CJK system-font test, run when this machine has the script's fonts.+ // The deterministic lazy-loading test above does not require installed fonts.+ let files = thai_font_files();+ if !files.iter().any(|f| f.path.is_file()) {+ eprintln!("skipping: no Thai system font");+ return;+ }+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png"), "Thai filename and combining marks still have missing glyphs");+ }+#[test]fn vertical_metrics_parse_and_reject_garbage() {let (asc, desc, gap) = vertical_metrics(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), 0).unwrap();@@ -449,7 +569,7 @@ mod tests {}#[test]- fn lazy_registration_triggers_only_for_cjk() {+ fn lazy_registration_triggers_only_for_supported_scripts() {let ctx = egui::Context::default();install_with(&ctx, fake_sources(|| Some("ko".into())));let _ = render(&ctx, "Layer 1 – café");@@ -467,7 +587,7 @@ mod tests {/// No system fonts at all: craft-fonts alone draws Japanese.fn craft_only(locale: fn() -> Option<String>) -> Sources {- Sources { locale, files: |_| vec![], last_resort: Vec::new, embedded: craft_embedded }+ Sources { locale, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: craft_embedded }}#[test]@@ -497,7 +617,7 @@ mod tests {// The pre-craft-fonts behaviour: no embedded fonts, no system fonts. Latin renders,// Japanese is tried (and stays missing) without panicking, and the loader exhausts.let ctx = egui::Context::default();- crate::theme::install_fonts_with(&ctx, Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, embedded: no_embedded });+ crate::theme::install_fonts_with(&ctx, Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: no_embedded });assert!(render(&ctx, "Layer 1 – café"));assert!(!render(&ctx, "日本語の文字"));let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count());diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rsindex d7f93ff23..83074d8c8 100644--- a/crates/ui-egui/src/theme.rs+++ b/crates/ui-egui/src/theme.rs@@ -532,7 +532,7 @@ pub fn install_fonts(ctx: &egui::Context) {install_fonts_with(ctx, crate::cjk_fonts::Sources::system());}-/// [`install_fonts`] with the CJK fallback fonts taken from `cjk` (tests swap the sources).+/// [`install_fonts`] with the CJK/Thai fallback fonts taken from `cjk` (tests swap the sources).pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) {let mut fonts = FontDefinitions::default();// The bundled fonts are inflated on first use (photocraft_text::fonts). Should one ever fail@@ -578,7 +578,7 @@ pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) {{ctx.add_plugin(UiFontSizePlugin { applied: size, defer_after_install: true });}- // Japanese / Chinese / Korean fallback fonts (craft-fonts' Japanese ones if built in, then+ // Japanese / Chinese / Korean / Thai fallback fonts (craft-fonts' Japanese ones if built in, then// the system's) are registered on demand (cjk_fonts.rs).crate::cjk_fonts::install_with(ctx, cjk);}