PhotoCraft: An open-source, photo editor written by scratch in pure Rust
UI fonts: lazy fallback for Thai, Arabic, Indic and other scripts (#2275) (#2758)
Fabio Lussiaa509ca9666a
diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rsindex 0db728017..032353307 100644--- a/crates/text/src/fonts.rs+++ b/crates/text/src/fonts.rs@@ -499,7 +499,7 @@ pub fn guess_from_postscript(ps: &str) -> ResolvedFont {}#[cfg(not(target_arch = "wasm32"))]-fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {+pub(crate) fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {let Ok(rd) = std::fs::read_dir(dir) else {return;};@@ -516,7 +516,7 @@ fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path}#[cfg(not(target_arch = "wasm32"))]-fn system_font_dirs() -> Vec<std::path::PathBuf> {+pub(crate) fn system_font_dirs() -> Vec<std::path::PathBuf> {use std::path::PathBuf;let home = std::env::var_os("HOME").map(PathBuf::from);let mut v = Vec::new();diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rsindex a63b3d9c0..173b1c84c 100644--- a/crates/text/src/lib.rs+++ b/crates/text/src/lib.rs@@ -26,6 +26,7 @@ pub mod psd;pub mod psd_styles;pub mod raster;pub mod render;+pub mod scripts;pub mod served;pub mod spell;pub mod warp;diff --git a/crates/text/src/scripts.rs b/crates/text/src/scripts.rsnew file mode 100644index 000000000..b6e0aae74--- /dev/null+++ b/crates/text/src/scripts.rs@@ -0,0 +1,366 @@+//! UI fallback fonts for the non-CJK scripts the bundled Inter / JetBrains Mono don't draw+//! (Thai, Arabic, Hebrew, the Indic scripts, ...): which characters belong to which script, and+//! which installed font files to try for it.+//!+//! Candidates come from the file names in the platform font directories (the same directories+//! [`crate::fonts::FontDb`] scans), listed once per process and only when first asked for, so+//! nothing is read at startup and no path is hard-coded per distribution. Noto fonts are matched+//! by their family-derived file names (`NotoSansThai-Regular.ttf`, `NotoSansThai[wght].ttf`),+//! platform fonts by their known file names (Leelawadee UI, Nirmala UI, Segoe UI, Geeza Pro,+//! Kohinoor, DejaVu Sans, Lohit, ...). A file name is only a hint: callers check that a face+//! really maps the character ([`covering_face`]) before using it. CJK has its own,+//! locale-ordered lists ([`crate::cjk`]).++/// A script that needs a UI fallback font.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Script {+ Thai,+ Lao,+ Khmer,+ Myanmar,+ Tibetan,+ Arabic,+ Hebrew,+ Armenian,+ Georgian,+ Ethiopic,+ Devanagari,+ Bengali,+ Gurmukhi,+ Gujarati,+ Oriya,+ Tamil,+ Telugu,+ Kannada,+ Malayalam,+ Sinhala,+}++impl Script {+ pub const ALL: [Script; 20] = [+ Script::Thai,+ Script::Lao,+ Script::Khmer,+ Script::Myanmar,+ Script::Tibetan,+ Script::Arabic,+ Script::Hebrew,+ Script::Armenian,+ Script::Georgian,+ Script::Ethiopic,+ Script::Devanagari,+ Script::Bengali,+ Script::Gurmukhi,+ Script::Gujarati,+ Script::Oriya,+ Script::Tamil,+ Script::Telugu,+ Script::Kannada,+ Script::Malayalam,+ Script::Sinhala,+ ];++ /// Font file names for this script, most preferred first: lowercase, without extension,+ /// spaces, underscores or style suffix (`NotoSansThai-Bold.ttf` and `NotoSansThai[wght].ttf`+ /// are both `notosansthai`). Noto first (the usual Linux font), then Windows, macOS and+ /// other Linux families.+ fn file_names(self) -> &'static [&'static str] {+ use Script::*;+ match self {+ Thai => &[+ "notosansthai",+ "notosansthailooped",+ "notosansthaiui",+ "notoserifthai",+ "leelawui",+ "leelawad",+ "tahoma",+ "thonburi",+ "sukhumvitset",+ "ayuthaya",+ "loma",+ "garuda",+ "waree",+ "kinnari",+ "norasi",+ ],+ Lao => &["notosanslao", "notosanslaoui", "notoseriflao", "leelawui", "laosangammn", "laomn", "phetsarathot", "saysetthaot"],+ Khmer => &["notosanskhmer", "notosanskhmerui", "notoserifkhmer", "leelawui", "daunpenh", "khmersangammn", "khmermn", "khmeros", "khmerossys"],+ Myanmar => &["notosansmyanmar", "notosansmyanmarui", "notoserifmyanmar", "mmrtext", "myanmarsangammn", "myanmarmn", "padauk"],+ Tibetan => &["notoseriftibetan", "himalaya", "kailasa", "jomolhari", "tibetanmachineuni"],+ Arabic => &[+ "notosansarabic",+ "notosansarabicui",+ "notonaskharabic",+ "notonaskharabicui",+ "notokufiarabic",+ "segoeui",+ "tahoma",+ "geezapro",+ "sfarabic",+ "dejavusans",+ "kacstone",+ "kacstbook",+ "amiri",+ "arial",+ ],+ Hebrew => &["notosanshebrew", "notoserifhebrew", "segoeui", "arialhb", "sfhebrew", "dejavusans", "arial", "freesans", "culmus"],+ Armenian => &["notosansarmenian", "notoserifarmenian", "segoeui", "sylfaen", "mshtakan", "dejavusans", "freesans"],+ Georgian => &["notosansgeorgian", "notoserifgeorgian", "segoeui", "sylfaen", "dejavusans", "freesans"],+ Ethiopic => &["notosansethiopic", "notoserifethiopic", "ebrima", "kefa", "abyssinicasil"],+ Devanagari => &[+ "notosansdevanagari",+ "notosansdevanagariui",+ "notoserifdevanagari",+ "nirmala",+ "mangal",+ "kohinoor",+ "kohinoordevanagari",+ "itfdevanagari",+ "devanagarimt",+ "devanagarisangammn",+ "lohitdevanagari",+ "lohit-devanagari",+ "gargi",+ "freesans",+ ],+ Bengali => &[+ "notosansbengali",+ "notosansbengaliui",+ "notoserifbengali",+ "nirmala",+ "vrinda",+ "kohinoorbangla",+ "banglasangammn",+ "banglamn",+ "lohitbengali",+ "lohit-bengali",+ "lohit-assamese",+ ],+ Gurmukhi => &[+ "notosansgurmukhi",+ "notosansgurmukhiui",+ "notoserifgurmukhi",+ "nirmala",+ "raavi",+ "gurmukhisangammn",+ "gurmukhimn",+ "lohit-gurmukhi",+ "lohit-punjabi",+ ],+ Gujarati => &[+ "notosansgujarati",+ "notosansgujaratiui",+ "notoserifgujarati",+ "nirmala",+ "shruti",+ "kohinoorgujarati",+ "gujaratisangammn",+ "gujaratimt",+ "lohit-gujarati",+ ],+ Oriya => &["notosansoriya", "notosansoriyaui", "notoseriforiya", "nirmala", "kalinga", "oriyasangammn", "oriyamn", "lohit-odia", "lohit-oriya"],+ Tamil => &["notosanstamil", "notosanstamilui", "notoseriftamil", "nirmala", "latha", "tamilsangammn", "tamilmn", "lohit-tamil"],+ Telugu => {+ &["notosanstelugu", "notosansteluguui", "notoseriftelugu", "nirmala", "gautami", "kohinoortelugu", "telugusangammn", "telugumn", "lohit-telugu"]+ }+ Kannada => &["notosanskannada", "notosanskannadaui", "notoserifkannada", "nirmala", "tunga", "kannadasangammn", "kannadamn", "lohit-kannada"],+ Malayalam => {+ &["notosansmalayalam", "notosansmalayalamui", "notoserifmalayalam", "nirmala", "kartika", "malayalamsangammn", "malayalammn", "lohit-malayalam"]+ }+ Sinhala => &["notosanssinhala", "notosanssinhalaui", "notoserifsinhala", "nirmala", "iskpota", "sinhalasangammn", "sinhalamn", "lklug"],+ }+ }+}++/// The script of a character that needs a non-CJK fallback font, or `None`.+pub fn classify(c: char) -> Option<Script> {+ use Script::*;+ Some(match c as u32 {+ 0x0E00..=0x0E7F => Thai,+ 0x0E80..=0x0EFF => Lao,+ 0x1780..=0x17FF | 0x19E0..=0x19FF => Khmer,+ 0x1000..=0x109F | 0xA9E0..=0xA9FF | 0xAA60..=0xAA7F => Myanmar,+ 0x0F00..=0x0FFF => Tibetan,+ 0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => Arabic,+ 0x0590..=0x05FF | 0xFB1D..=0xFB4F => Hebrew,+ 0x0530..=0x058F | 0xFB13..=0xFB17 => Armenian,+ 0x10A0..=0x10FF | 0x1C90..=0x1CBF | 0x2D00..=0x2D2F => Georgian,+ 0x1200..=0x139F | 0x2D80..=0x2DDF | 0xAB00..=0xAB2F => Ethiopic,+ 0x0900..=0x097F | 0xA8E0..=0xA8FF => Devanagari,+ 0x0980..=0x09FF => Bengali,+ 0x0A00..=0x0A7F => Gurmukhi,+ 0x0A80..=0x0AFF => Gujarati,+ 0x0B00..=0x0B7F => Oriya,+ 0x0B80..=0x0BFF => Tamil,+ 0x0C00..=0x0C7F => Telugu,+ 0x0C80..=0x0CFF => Kannada,+ 0x0D00..=0x0D7F => Malayalam,+ 0x0D80..=0x0DFF => Sinhala,+ _ => return None,+ })+}++/// `(name, stem, style rank)` of a font file: [`Script::file_names`] form, the file stem, and 0+/// for the regular face, 1 for a variable font, 2 for other weights, 3 for bold, italic and+/// condensed faces. Non-font files give `None`.+fn file_key(path: &std::path::Path) -> Option<(String, &str, u8)> {+ let ext = path.extension()?.to_str()?.to_ascii_lowercase();+ if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") {+ return None;+ }+ let stem = path.file_stem()?.to_str()?;+ let squash = |s: &str| s.chars().filter(|c| !matches!(c, ' ' | '_')).collect::<String>().to_lowercase();+ let style = |s: &str| {+ let s = s.to_ascii_lowercase();+ if s.is_empty() || s == "-regular" {+ 0+ } else if s.starts_with('[') {+ 1+ } else if ["bold", "italic", "oblique", "condensed", "narrow", "black", "heavy", "thin", "light"].iter().any(|w| s.contains(w)) {+ 3+ } else {+ 2+ }+ };+ let cut = stem.find(['-', '[']).unwrap_or(stem.len());+ let (base, rest) = stem.split_at(cut);+ Some((squash(base), stem, style(rest)))+}++/// Font files among `files` that may cover `script`, most preferred first (at most+/// `MAX_CANDIDATES`). Pure, so tests pass their own listing.+pub fn candidates(script: Script, files: &[std::path::PathBuf]) -> Vec<std::path::PathBuf> {+ const MAX_CANDIDATES: usize = 16;+ let names = script.file_names();+ let mut ranked: Vec<(usize, u8, &std::path::PathBuf)> = files+ .iter()+ .filter_map(|p| {+ let (base, stem, style) = file_key(p)?;+ // A name with a hyphen ("lohit-tamil") matches the whole stem.+ let full = stem.to_lowercase().replace([' ', '_'], "");+ let rank = names.iter().position(|n| *n == base || *n == full)?;+ Some((rank, if *names.get(rank)? == full { 0 } else { style }, p))+ })+ .collect();+ ranked.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));+ ranked.into_iter().take(MAX_CANDIDATES).map(|(_, _, p)| p.clone()).collect()+}++/// Every font file in the platform font directories, listed on first use and cached for the+/// process (names only; nothing is opened).+#[cfg(not(target_arch = "wasm32"))]+pub fn system_font_files() -> &'static [std::path::PathBuf] {+ static FILES: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();+ FILES.get_or_init(|| {+ let mut files = Vec::new();+ for d in crate::fonts::system_font_dirs() {+ crate::fonts::collect_font_files(&d, 0, &mut files);+ }+ files.sort();+ files.dedup();+ files+ })+}++/// Installed font files that may cover `script`, most preferred first.+#[cfg(not(target_arch = "wasm32"))]+pub fn system_candidates(script: Script) -> Vec<std::path::PathBuf> {+ candidates(script, system_font_files())+}++/// Index of the first face in `bytes` (a font or a collection) whose character map has `c`.+/// `None` for fonts without it and for data that doesn't parse. Never panics.+pub fn covering_face(bytes: &[u8], c: char) -> Option<u32> {+ use skrifa::MetadataProvider;+ use skrifa::raw::FileRef;+ match FileRef::new(bytes).ok()? {+ FileRef::Font(f) => f.charmap().map(c).map(|_| 0),+ FileRef::Collection(col) => col.iter().position(|f| f.is_ok_and(|f| f.charmap().map(c).is_some())).and_then(|i| u32::try_from(i).ok()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ #[test]+ fn classifies_scripts_and_leaves_latin_and_cjk_alone() {+ for (c, s) in [+ ('ส', Script::Thai),+ ('ม', Script::Thai),+ ('ر', Script::Arabic),+ ('ﻻ', Script::Arabic),+ ('ש', Script::Hebrew),+ ('न', Script::Devanagari),+ ('த', Script::Tamil),+ ('ក', Script::Khmer),+ ('ა', Script::Georgian),+ ] {+ assert_eq!(classify(c), Some(s), "{c}");+ }+ for c in ['A', 'é', 'Ж', 'Ω', '–', '日', 'カ', '한', ' '] {+ assert_eq!(classify(c), None, "{c}");+ }+ for s in Script::ALL {+ assert!(!s.file_names().is_empty());+ }+ }++ #[test]+ fn candidates_match_file_names_regular_first_across_layouts() {+ let files: Vec<PathBuf> = [+ "/usr/share/fonts/google-noto/NotoSansThai-Bold.ttf",+ "/usr/share/fonts/google-noto-vf/NotoSansThai[wght].ttf",+ "/usr/share/fonts/truetype/noto/NotoSansThai-Regular.ttf",+ "/usr/share/fonts/truetype/noto/NotoSansThaiLooped-Regular.ttf",+ "/usr/share/fonts/truetype/noto/NotoSansThaana-Regular.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",+ "/usr/share/fonts/truetype/lohit-devanagari/Lohit-Devanagari.ttf",+ "/usr/share/fonts/Lohit-Tamil.ttf",+ "/mnt/c/Windows/Fonts/LeelawUI.ttf",+ "/mnt/c/Windows/Fonts/Nirmala.ttc",+ "/System/Library/Fonts/Supplemental/Thonburi.ttc",+ "/System/Library/Fonts/Supplemental/Kohinoor.ttc",+ "/usr/share/fonts/README.txt",+ ]+ .into_iter()+ .map(PathBuf::from)+ .collect();+ let names = |s| candidates(s, &files).into_iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect::<Vec<_>>();+ assert_eq!(+ names(Script::Thai),+ ["NotoSansThai-Regular.ttf", "NotoSansThai[wght].ttf", "NotoSansThai-Bold.ttf", "NotoSansThaiLooped-Regular.ttf", "LeelawUI.ttf", "Thonburi.ttc"]+ );+ assert_eq!(names(Script::Arabic), ["DejaVuSans.ttf", "DejaVuSans-Bold.ttf"]);+ assert_eq!(names(Script::Devanagari), ["Nirmala.ttc", "Kohinoor.ttc", "Lohit-Devanagari.ttf"]);+ assert_eq!(names(Script::Tamil), ["Nirmala.ttc", "Lohit-Tamil.ttf"]);+ assert!(names(Script::Ethiopic).is_empty());+ assert!(candidates(Script::Thai, &[]).is_empty());+ }++ #[test]+ fn covering_face_checks_the_character_map_and_rejects_garbage() {+ let inter = crate::fonts::INTER_REGULAR.as_slice();+ assert_eq!(covering_face(inter, 'A'), Some(0));+ assert_eq!(covering_face(inter, 'ส'), None);+ assert_eq!(covering_face(inter, 'ر'), None);+ for bad in [&b""[..], b"ttcf", b"ttcf\0\x01\0\0\0\0\0\x02\xff\xff\xff\xff\0\0\0\x10", b"\0\x01\0\0\0\xff"] {+ assert_eq!(covering_face(bad, 'A'), None);+ }+ }++ /// With the real system fonts, each script that has a candidate installed has one that+ /// covers it (skipped per script when the machine has none, e.g. CI Linux).+ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn system_candidates_cover_their_script() {+ for (s, c) in [(Script::Thai, 'ส'), (Script::Arabic, 'ر'), (Script::Hebrew, 'ש'), (Script::Devanagari, 'न')] {+ let found = system_candidates(s).iter().take(4).any(|p| std::fs::read(p).ok().and_then(|b| covering_face(&b, c)).is_some());+ eprintln!("{s:?}: {}", if found { "covered" } else { "no installed font" });+ }+ }+}diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/cjk_fonts.rsindex bbb1e14d0..7cd253e95 100644--- a/crates/ui-egui/src/cjk_fonts.rs+++ b/crates/ui-egui/src/cjk_fonts.rs@@ -1,12 +1,17 @@-//! Lazy CJK and Thai fallback fonts for the UI.+//! Lazy CJK and other-script 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. Thai has its own-//! candidate list and attempt state, independent of the locale-dependent CJK order.+//! appended at the lowest priority to every family, so Latin text keeps Inter.+//!+//! Other scripts the bundled fonts lack (Thai, Arabic, Hebrew, Devanagari and the other Indic+//! scripts, ...: [`photocraft_text::scripts`]) work the same way, each with its own attempt state,+//! independent of the CJK order: the first installed candidate file whose character map really+//! has the missing character is registered, once per script. egui shapes each font run with+//! HarfRust, so Thai marks and Arabic joining come from the font; it has no bidi reordering yet.//!//! 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@@ -22,10 +27,13 @@ use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily};use egui::{FontData, FontFamily, FontId, Shape};use photocraft_text::cjk::{self, CjkChar, CjkScript, FontFile};use photocraft_text::craft_fonts::{self, CraftFont};+use photocraft_text::scripts::{self, Script};use std::path::PathBuf;/// Skip absurdly large files (a corrupt or non-font path must not eat memory).pub const MAX_FONT_BYTES: u64 = 128 << 20;+/// At most this many candidate files are read for one script (bounded I/O on a miss).+const MAX_SCRIPT_READS: usize = 6;/// Name prefix of the registered fallback fonts.pub const FONT_PREFIX: &str = "system-cjk";@@ -35,8 +43,11 @@ 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>,+ /// Candidate files for a non-CJK script, most preferred first; read only when a visible+ /// character of that script is missing.+ pub scripts: fn(Script) -> Vec<PathBuf>,+ /// The face of a font file whose character map has the character (`None`: not this file).+ pub covers: fn(&[u8], char) -> Option<u32>,/// Embedded fonts tried before `files` for a script (craft-fonts' Japanese fonts).pub embedded: fn(CjkScript) -> Vec<&'static CraftFont>,}@@ -61,13 +72,21 @@ impl Sources {},files: cjk::font_files,last_resort: cjk::last_resort_files,- thai: thai_font_files,+ scripts: scripts::system_candidates,+ covers: scripts::covering_face,embedded: craft_embedded,}}#[cfg(target_arch = "wasm32")]pub fn system() -> Self {- Self { locale: || None, files: |_| Vec::new(), last_resort: Vec::new, thai: Vec::new, embedded: craft_embedded }+ Self {+ locale: || None,+ files: |_| Vec::new(),+ last_resort: Vec::new,+ scripts: |_| Vec::new(),+ covers: scripts::covering_face,+ embedded: craft_embedded,+ }}}@@ -79,7 +98,8 @@ pub struct CjkFallback {order: Option<[CjkScript; 4]>,tried: Vec<CjkScript>,last_resort_tried: bool,- thai_tried: bool,+ /// Non-CJK scripts whose candidates were tried (each at most once per install).+ scripts_tried: Vec<Script>,loaded: Vec<PathBuf>,/// Fonts registered so far: (name, path, face index).pub registered: Vec<(String, PathBuf, u32)>,@@ -93,7 +113,7 @@ impl CjkFallback {order: None,tried: Vec::new(),last_resort_tried: false,- thai_tried: false,+ scripts_tried: Vec::new(),loaded: Vec::new(),registered: Vec::new(),}@@ -136,11 +156,39 @@ impl CjkFallback {None}- fn next_thai_font(&mut self) -> Option<(String, FontData)> {- if std::mem::replace(&mut self.thai_tried, true) {+ /// Every non-CJK script has been tried.+ pub fn scripts_exhausted(&self) -> bool {+ self.scripts_tried.len() >= Script::ALL.len()+ }++ /// The first candidate font for `c`'s script that really maps `c`; the script is tried once.+ pub fn next_script_font(&mut self, c: char) -> Option<(String, FontData)> {+ let script = scripts::classify(c)?;+ if self.scripts_tried.contains(&script) {return None;}- self.load_first(&(self.sources.thai)())+ self.scripts_tried.push(script);+ let mut reads = 0;+ for path in (self.sources.scripts)(script) {+ if reads >= MAX_SCRIPT_READS {+ break;+ }+ if self.loaded.contains(&path) {+ continue;+ }+ let Some(bytes) = read_font(&path) else { continue };+ reads += 1;+ let Some(index) = (self.sources.covers)(&bytes, c) else { continue };+ self.loaded.push(path.clone());+ let name = format!("{FONT_PREFIX}-{}", self.registered.len());+ log::info!("UI font fallback: registered {} (face {index}) for {script:?} as {name}", path.display());+ self.registered.push((name.clone(), path, index));+ let mut data = FontData::from_owned(bytes);+ data.index = index;+ return Some((name, data));+ }+ log::info!("UI font fallback: no installed font covers {script:?}");+ None}/// The first embedded (craft-fonts) font for `s`, registered from its static bytes.@@ -162,11 +210,7 @@ impl CjkFallback {if self.loaded.contains(&f.path) {continue;}- let Ok(meta) = std::fs::metadata(&f.path) else { continue };- if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_FONT_BYTES {- continue;- }- let Ok(bytes) = std::fs::read(&f.path) else { continue };+ let Some(bytes) = read_font(&f.path) else { continue };let index = cjk::face_index_for_family(&bytes, f.family);self.loaded.push(f.path.clone());let name = format!("{FONT_PREFIX}-{}", self.registered.len());@@ -180,18 +224,24 @@ impl CjkFallback {}}-fn is_thai(c: char) -> bool {- matches!(c, '\u{0e00}'..='\u{0e7f}')+/// A font file's bytes, or `None` for missing, empty, oversized or unreadable files.+fn read_font(path: &std::path::Path) -> Option<Vec<u8>> {+ let meta = std::fs::metadata(path).ok()?;+ if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_FONT_BYTES {+ return None;+ }+ std::fs::read(path).ok()}/// 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) {+ fn collect(shape: &Shape, out: &mut Vec<char>, fallback: &CjkFallback, cjk_pending: bool) {+ let wanted = |c: char| (cjk_pending && cjk::classify(c).is_some()) || scripts::classify(c).is_some_and(|s| !fallback.scripts_tried.contains(&s));match shape {Shape::Text(t) => {let text = &t.galley.job.text;if !text.is_ascii() {- for c in text.chars().filter(|c| (cjk_pending && cjk::classify(*c).is_some()) || (thai_pending && is_thai(*c))) {+ for c in text.chars().filter(|c| wanted(*c)) {if out.len() >= 256 {return;}@@ -201,13 +251,13 @@ fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape], fall}}}- Shape::Vec(v) => v.iter().for_each(|s| collect(s, out, cjk_pending, thai_pending)),+ Shape::Vec(v) => v.iter().for_each(|s| collect(s, out, fallback, cjk_pending)),_ => {}}}let mut chars = Vec::new();for s in shapes {- collect(&s.shape, &mut chars, !fallback.exhausted(), !fallback.thai_tried);+ collect(&s.shape, &mut chars, fallback, !fallback.exhausted());}if chars.is_empty() {return None;@@ -287,22 +337,25 @@ impl egui::Plugin for CjkFontPlugin {ctx.request_repaint();return;}- if self.0.exhausted() && self.0.thai_tried {+ if self.0.exhausted() && self.0.scripts_exhausted() {return;}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)) };+ let font = match cjk::classify(c) {+ Some(kind) => self.0.next_font(kind),+ None => self.0.next_script_font(c),+ };if let Some((name, data)) = font {add_to_all_families(ctx, name, data);ctx.request_repaint();- } else if !self.0.exhausted() || !self.0.thai_tried {+ } else if !self.0.exhausted() || !self.0.scripts_exhausted() {// Nothing readable for this script; try the next one on the next frame.ctx.request_repaint();}}}-/// Installs the lazy CJK and Thai fallback (system fonts; nothing on the web).+/// Installs the lazy CJK and other-script fallback (system fonts; nothing on the web).pub fn install(ctx: &egui::Context) {install_with(ctx, Sources::system());}@@ -323,38 +376,6 @@ 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 {@@ -417,6 +438,9 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();std::fs::write(dir.join("font.ttf"), include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap();std::fs::write(dir.join("empty.ttf"), b"").unwrap();+ std::fs::write(dir.join("thai.ttf"), synthetic_font(&[(0x0E01, 0x0E5B)])).unwrap();+ std::fs::write(dir.join("arabic.ttf"), synthetic_font(&[(0x0600, 0x06FF)])).unwrap();+ std::fs::write(dir.join("devanagari.ttf"), synthetic_font(&[(0x0900, 0x097F)])).unwrap();dir}).clone()@@ -436,7 +460,8 @@ mod tests {_ => vec![],},last_resort: || vec![fake("font.ttf")],- thai: Vec::new,+ scripts: |_| Vec::new(),+ covers: scripts::covering_face,embedded: no_embedded,}}@@ -467,7 +492,14 @@ 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, thai: Vec::new, embedded: no_embedded });+ let mut fb = CjkFallback::new(Sources {+ locale: || None,+ files: |_| vec![],+ last_resort: Vec::new,+ scripts: |_| Vec::new(),+ covers: scripts::covering_face,+ 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}");@@ -485,66 +517,198 @@ 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"));+ /// A minimal TrueType font mapping the `ranges` (inclusive) to box glyphs, so tests have a+ /// font for a script without committing font files.+ fn synthetic_font(ranges: &[(u32, u32)]) -> Vec<u8> {+ let be16 = |v: &mut Vec<u8>, x: i32| v.extend((x as u16).to_be_bytes());+ let be32 = |v: &mut Vec<u8>, x: u32| v.extend(x.to_be_bytes());+ let chars: u32 = ranges.iter().map(|(a, b)| b - a + 1).sum();+ let glyphs = chars as i32 + 1;+ // One 500x700 box (contour of four on-curve points); glyph 0 (.notdef) is empty.+ let mut boxed = Vec::new();+ for x in [1, 50, 0, 550, 700, 3, 0] {+ be16(&mut boxed, x);+ }+ boxed.extend([1u8; 4]);+ for x in [50, 0, 500, 0, 0, 700, 0, -700] {+ be16(&mut boxed, x);+ }+ boxed.extend([0, 0]);+ let glyf: Vec<u8> = boxed.repeat(chars as usize);+ let mut loca = Vec::new();+ be32(&mut loca, 0);+ for i in 0..chars {+ be32(&mut loca, i * boxed.len() as u32);+ }+ be32(&mut loca, chars * boxed.len() as u32);+ let mut head = Vec::new();+ for x in [0x0001_0000, 0x0001_0000, 0, 0x5F0F_3CF5] {+ be32(&mut head, x);+ }+ for x in [0x000B, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, -200, 600, 800, 0, 8, 2, 1, 0] {+ be16(&mut head, x);+ }+ let mut hhea = Vec::new();+ be32(&mut hhea, 0x0001_0000);+ for x in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, glyphs] {+ be16(&mut hhea, x);+ }+ let mut maxp = Vec::new();+ be32(&mut maxp, 0x0001_0000);+ for x in [glyphs, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] {+ be16(&mut maxp, x);+ }+ let mut hmtx = Vec::new();+ for _ in 0..glyphs {+ be16(&mut hmtx, 600);+ be16(&mut hmtx, 50);+ }+ let mut cmap = Vec::new();+ for x in [0, 1, 3, 10] {+ be16(&mut cmap, x);+ }+ be32(&mut cmap, 12);+ be16(&mut cmap, 12);+ be16(&mut cmap, 0);+ be32(&mut cmap, 16 + 12 * ranges.len() as u32);+ be32(&mut cmap, 0);+ be32(&mut cmap, ranges.len() as u32);+ let mut gid = 1;+ for (a, b) in ranges {+ for x in [*a, *b, gid] {+ be32(&mut cmap, x);}+ gid += b - a + 1;+ }+ let tables: [(&[u8; 4], Vec<u8>); 7] =+ [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];+ let mut font = Vec::new();+ be32(&mut font, 0x0001_0000);+ for x in [7, 64, 2, 48] {+ be16(&mut font, x);+ }+ let mut offset = 12 + 16 * tables.len() as u32;+ for (tag, data) in &tables {+ font.extend(*tag);+ be32(&mut font, 0);+ be32(&mut font, offset);+ be32(&mut font, data.len() as u32);+ offset += (data.len() as u32).next_multiple_of(4);+ }+ for (_, data) in &tables {+ font.extend(data);+ font.resize(font.len().next_multiple_of(4), 0);}+ font}- #[test]- fn thai_loading_is_lazy_once_per_install_and_independent_of_cjk() {- let sources = Sources {+ /// Thai, Arabic and Devanagari each have a synthetic font; Thai's list starts with unreadable+ /// files and Inter, which doesn't map Thai. No other script has a font.+ fn script_sources() -> Sources {+ Sources {locale: || Some("en".into()),files: |_| vec![],last_resort: Vec::new,- thai: || vec![fake("missing.ttf"), fake("empty.ttf"), fake("font.ttf")],+ scripts: |s| {+ let f = |name: &str| fake_dir().join(name);+ match s {+ Script::Thai => vec![f("missing.ttf"), f("empty.ttf"), f("font.ttf"), f("thai.ttf")],+ Script::Arabic => vec![f("arabic.ttf")],+ Script::Devanagari => vec![f("devanagari.ttf")],+ _ => vec![],+ }+ },+ covers: scripts::covering_face,embedded: no_embedded,- };+ }+ }++ fn fallback_files(ctx: &egui::Context) -> Vec<String> {+ ctx.with_plugin::<CjkFontPlugin, _>(|p| p.0.registered.iter().map(|(_, path, _)| path.file_name().unwrap().to_string_lossy().into_owned()).collect())+ .unwrap()+ }++ #[test]+ fn layer_names_in_other_scripts_load_a_covering_font_once() {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"));+ crate::theme::install_fonts_with(&ctx, script_sources());+ assert!(render(&ctx, "Layer 1 – café"));+ ctx.with_plugin::<CjkFontPlugin, _>(|p| assert!(p.0.scripts_tried.is_empty(), "Latin text reads no font")).unwrap();+ assert!(fallback_files(&ctx).is_empty());+ // A Thai type layer's name (#2275), Arabic (#1693) and Devanagari: no missing glyphs.+ for text in ["สวัสดี", "ภาพถ่าย/วันหยุดพักผ่อน", "مرحبا بالعالم", "नमस्ते दुनिया"]+ {+ assert!(render(&ctx, text), "tofu in {text}");+ }+ assert_eq!(fallback_files(&ctx), ["thai.ttf", "arabic.ttf", "devanagari.ttf"], "the first file that maps the character, never Inter");+ // Hebrew has no font here: tried once, then left alone (no reload or repaint loop).+ assert!(!render(&ctx, "שלום"));+ assert!(!render(&ctx, "שלום"));ctx.with_plugin::<CjkFontPlugin, _>(|p| {- assert!(p.0.exhausted());- assert!(p.0.thai_tried);- assert_eq!(p.0.registered.len(), 1);- });+ assert!(p.0.scripts_tried.contains(&Script::Hebrew));+ assert_eq!(p.0.registered.len(), 3);+ })+ .unwrap();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"));+ assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 3);+ assert_eq!(stack.last().map(String::as_str), Some("system-cjk-2"), "appended last so Latin keeps Inter");}}- // Exhausting Thai first must likewise leave CJK available.+ }++ #[test]+ fn a_missing_cjk_font_does_not_block_other_scripts_and_vice_versa() {+ let ctx = egui::Context::default();+ crate::theme::install_fonts_with(&ctx, script_sources());+ assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png"));+ assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png"));+ ctx.with_plugin::<CjkFontPlugin, _>(|p| assert!(p.0.exhausted())).unwrap();+ assert_eq!(fallback_files(&ctx), ["thai.ttf"]);+ // A script with no font leaves CJK available.let mut fallback = CjkFallback::new(fake_sources(|| Some("ko".into())));- assert!(fallback.next_thai_font().is_none());+ assert!(fallback.next_script_font('ส').is_none());+ assert!(fallback.next_script_font('ส').is_none());+ assert!(fallback.next_script_font('A').is_none(), "Latin is never a fallback script");+ assert_eq!(fallback.scripts_tried, [Script::Thai]);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;- }+ fn script_candidates_are_read_a_bounded_number_of_times() {+ static CHECKED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+ let mut fallback = CjkFallback::new(Sources {+ scripts: |_| (0..20).map(|i| fake_dir().join(if i % 2 == 0 { "font.ttf" } else { "thai.ttf" })).collect(),+ covers: |_, _| {+ CHECKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ None+ },+ ..script_sources()+ });+ assert!(fallback.next_script_font('ش').is_none());+ assert!(fallback.next_script_font('ش').is_none());+ assert_eq!(CHECKED.load(std::sync::atomic::Ordering::Relaxed), MAX_SCRIPT_READS, "one bounded pass per script");+ assert!(fallback.registered.is_empty());+ assert!(!fallback.scripts_exhausted());+ }++ #[test]+ fn system_fonts_cover_other_script_samples() {+ // Like the CJK system-font test, run per script when this machine has a font for it.+ // The deterministic tests above do not need installed fonts.+ let samples = [("ภาพถ่าย/วันหยุดพักผ่อน", 'ภ'), ("مرحبا", 'م'), ("שלום", 'ש'), ("नमस्ते", 'न')];let ctx = egui::Context::default();crate::theme::install_fonts(&ctx);- assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png"), "Thai filename and combining marks still have missing glyphs");+ for (text, c) in samples {+ let Some(script) = scripts::classify(c) else { continue };+ if !scripts::system_candidates(script).iter().any(|p| read_font(p).and_then(|b| scripts::covering_face(&b, c)).is_some()) {+ eprintln!("skipping {text}: no {script:?} system font");+ continue;+ }+ assert!(render(&ctx, text), "{text} still has missing glyphs");+ }}#[test]@@ -587,7 +751,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, thai: Vec::new, embedded: craft_embedded }+ Sources { locale, files: |_| vec![], last_resort: Vec::new, scripts: |_| Vec::new(), covers: scripts::covering_face, embedded: craft_embedded }}#[test]@@ -617,7 +781,17 @@ 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, thai: Vec::new, embedded: no_embedded });+ crate::theme::install_fonts_with(+ &ctx,+ Sources {+ locale: || None,+ files: |_| vec![],+ last_resort: Vec::new,+ scripts: |_| Vec::new(),+ covers: scripts::covering_face,+ 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 17bd3b439..493b29a63 100644--- a/crates/ui-egui/src/theme.rs+++ b/crates/ui-egui/src/theme.rs@@ -646,7 +646,7 @@ pub fn install_fonts(ctx: &egui::Context) {install_fonts_with(ctx, crate::cjk_fonts::Sources::system());}-/// [`install_fonts`] with the CJK/Thai fallback fonts taken from `cjk` (tests swap the sources).+/// [`install_fonts`] with the CJK and other-script 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@@ -692,7 +692,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 / Thai fallback fonts (craft-fonts' Japanese ones if built in, then+ // CJK, Thai, Arabic, Indic and other script 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);}