diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cea1326c0c..e966971788 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,9 +156,13 @@ jobs: # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). CARGO_PROFILE_DEV_DEBUG: "0" - # The runner has no Japanese or Simplified Chinese system font, and egui 0.37 panics on a - # missing glyph: the localized UI tests need the same craft-fonts input the gate and FreeBSD - # build with (crates/text/build.rs). Same commit as the gate above and release.yml. + # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels + # with kittest's strict `MissingGlyphPolicy::Panic`. A hosted Windows image has no + # guaranteed Japanese or Simplified Chinese system font, and egui 0.37 panics on a + # missing glyph; the app's lazy system fallback runs after layout, too late for the + # first headless frame. Use the same pinned central fonts as Linux and release, so every + # language is drawn by a real embedded face rather than skipping. Same commit as the gate + # above and release.yml. CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts CRAFT_FONTS_REQUIRED: "1" steps: diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3b..8f1aa5ad52 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -16,6 +16,9 @@ concurrency: jobs: sonarcloud: - # Tracked at @main so org-wide CI improvements propagate without PR churn. + # Track shared CI improvements on main. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + with: + timeout-minutes: 120 + fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 68547951ef..2c06a488fd 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; /// The binary, without the variables `mcp` and `serve` fall back to: a test that wants one sets it. fn bin() -> Command { - let mut cmd = Command::new(env!("CARGO_BIN_EXE_photocraft-cli")); + let mut cmd = Command::new(crate::binary()); for var in ENV_VARS { cmd.env_remove(var); } diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs index 60cea6f74b..65092cdee4 100644 --- a/apps/photocraft-cli/tests/it/main.rs +++ b/apps/photocraft-cli/tests/it/main.rs @@ -3,3 +3,8 @@ mod cli; mod man_and_completions; mod orientation; + +/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. +fn binary() -> std::ffi::OsString { + std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into()) +} diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index 3895df367a..8e8da558c7 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima use serde_json::Value; fn bin() -> Command { - Command::new(env!("CARGO_BIN_EXE_photocraft-cli")) + Command::new(crate::binary()) } fn tmp(name: &str) -> PathBuf { diff --git a/apps/photocraft/tests/it/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs index d9afc64194..a0d8377638 100644 --- a/apps/photocraft/tests/it/command_line_usage.rs +++ b/apps/photocraft/tests/it/command_line_usage.rs @@ -34,7 +34,7 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run { let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("photocraft-usage-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft")); + let mut cmd = std::process::Command::new(crate::binary()); for var in VARS { cmd.env_remove(var); } diff --git a/apps/photocraft/tests/it/control_exit_code.rs b/apps/photocraft/tests/it/control_exit_code.rs index 9494dbb43f..4be624c5d2 100644 --- a/apps/photocraft/tests/it/control_exit_code.rs +++ b/apps/photocraft/tests/it/control_exit_code.rs @@ -28,7 +28,7 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run { let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft")) + let output = std::process::Command::new(crate::binary()) .args(args) .env("PHOTOCRAFT_CONFIG_DIR", &dir) // Isolate from the host environment so the test is reproducible. diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs index b5ece12621..73bea9196a 100644 --- a/apps/photocraft/tests/it/main.rs +++ b/apps/photocraft/tests/it/main.rs @@ -3,3 +3,8 @@ mod command_line_usage; mod control_exit_code; mod startup_without_display; + +/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. +fn binary() -> std::ffi::OsString { + std::env::var_os("NEXTEST_BIN_EXE_photocraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft").into()) +} diff --git a/apps/photocraft/tests/it/startup_without_display.rs b/apps/photocraft/tests/it/startup_without_display.rs index 5ffb5783a9..b0faf77d5b 100644 --- a/apps/photocraft/tests/it/startup_without_display.rs +++ b/apps/photocraft/tests/it/startup_without_display.rs @@ -30,7 +30,7 @@ fn missing_display_preserves_existing_gpu_crash_evidence() { } fn launch_without_display(dir: &std::path::Path) -> String { - let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft")) + let output = std::process::Command::new(crate::binary()) .env("PHOTOCRAFT_CONFIG_DIR", dir) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index ab59c440b4..af788d60de 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -423,6 +423,29 @@ mod shapes { } } + #[test] + fn artistic_text_reads_its_characters_runs_and_anchor() { + let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("Hi".into()))]); + let run = F::Obj(tag(b"Item"), vec![]); + let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]); + let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)]; + let text = F::Def( + 100, + vec![tag(b"TxtA")], + vec![ + (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])), + (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])), + ], + ); + let document = read(vec![text], 100); + let Kind::Text(t) = &document.spreads[0].nodes[0].kind else { panic!("expected text") }; + assert_eq!(t.runs.len(), 1); + assert_eq!(t.runs[0].text, "Hi"); + assert_eq!(t.align, crate::model::Align::Left); + assert_eq!(t.anchor, Point { x: 0.0, y: 0.0 }); + assert!(t.frame.is_none()); + } + #[test] fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() { let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100); diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index bfad07217f..eb52cda436 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -4,7 +4,7 @@ use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect}; use crate::paint::{self, Paint}; -use crate::stream::{ObjId, Value}; +use crate::stream::{ObjId, Stream, Value}; /// Characters read per text node (stories are split into blocks; this caps hostile ones). const MAX_CHARS: usize = 1 << 20; @@ -21,26 +21,7 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { let mut placeholders = false; for block in s.objs(story, b"Blok") { let glyphs = s.obj(block, b"Glyp")?; - let chars: Vec = match s.str(glyphs, b"Utf8") { - Some(t) => t.chars().collect(), - None => { - // Inline objects (page numbers, anchors) each take one index before the segment text. - let mut v = Vec::new(); - // One past the allowance is enough to trip the check below; shared segments - // repeated by reference must not expand beyond it first. - let room = MAX_CHARS.saturating_sub(total).saturating_add(1); - for seg in s.objs(glyphs, b"Mixd") { - if v.len() >= room { - break; - } - let inline = s.objs(seg, b"Glys").len(); - v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len()))); - placeholders |= inline > 0; - v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len()))); - } - v - } - }; + let chars = block_chars(s, glyphs, total, &mut placeholders); total = total.checked_add(chars.len())?; if total > MAX_CHARS { r.warn("text longer than a million characters (truncated)"); @@ -84,6 +65,32 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world }) } +/// The characters of one text block. A block without a UTF-8 string is a list of segments: each +/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once +/// `total` plus these characters would pass the cap. +fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec { + // One past the allowance is enough to trip the check in `read`; both arms stop there. + let room = MAX_CHARS.saturating_sub(total).saturating_add(1); + match s.str(glyphs, b"Utf8") { + Some(t) => t.chars().take(room).collect(), + None => { + // Inline objects (page numbers, anchors) each take one index before the segment text. + let mut v = Vec::new(); + // Shared segments repeated by reference must not expand beyond the allowance first. + for seg in s.objs(glyphs, b"Mixd") { + if v.len() >= room { + break; + } + let inline = s.objs(seg, b"Glys").len(); + v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len()))); + *placeholders |= inline > 0; + v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len()))); + } + v + } + } +} + fn slot(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option) -> Option { match v? { Value::Array(a) => a.get(i).and_then(f), diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index eb7cc17be0..cac8fb158a 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -6,7 +6,7 @@ //! `layer.layerStyle.*`. use photocraft_color::{BlendMode, ColorMode, SampleType}; -use photocraft_doc::{Document, Effect, Layer, Size}; +use photocraft_doc::{Document, Effect, Layer, Pattern, Size}; use photocraft_geom::Rect; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -170,19 +170,12 @@ fn targets(s: &Session, p: &Value) -> Vec { crate::layer_multi_cmds::selected(s) } -fn apply(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "style.presets.apply"; - let style = find_style(s, p, CMD)?.clone(); - let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); - let ids = targets(s, p); - if ids.is_empty() { - return Err(bad(CMD, "no target layers")); - } - // Pattern overlays name their pattern; resolve to library patterns copied into the document. +/// Resolves each effect's pattern, plus the patterns that strokes and bevels name, copied from the library. +fn resolve_style_effects(s: &Session, fx_list: &[Effect]) -> Result<(Vec, Vec)> { let mut effects = Vec::new(); let mut pats = Vec::new(); - for fx in style.effects { - let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?; + for fx in fx_list { + let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx.clone())?; effects.push(fx); pats.extend(pat); } @@ -192,6 +185,46 @@ fn apply(s: &mut Session, p: &Value) -> Result { pats.push(pat); } } + Ok((effects, pats)) +} + +/// Writes a preset onto one layer: replaces its effects, or appends to them when `add`. +fn apply_to_layer(l: &mut Layer, style: &StylePreset, effects: &[Effect], add: bool) { + if add { + l.effects.items.extend(effects.iter().cloned()); + } else { + l.effects.items = effects.to_vec(); + l.effects.psd_raw = None; + } + l.effects.psd_raw = None; + l.effects.enabled = true; + // Adding keeps the layer's blending unless the preset carries some: a blend mode, or + // an Opacity saved on its own (`style.presets.new` with `includeBlending: false`). + if !add || style.blend.is_some() || style.opacity.is_some() { + if let Some(b) = style.blend { + l.blend = b; + } + if let Some(f) = style.fill_opacity { + l.fill_opacity = f; + } else if !add { + l.fill_opacity = 1.0; + } + if let Some(o) = style.opacity { + l.opacity = o; + } + } +} + +fn apply(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "style.presets.apply"; + let style = find_style(s, p, CMD)?.clone(); + let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); + let ids = targets(s, p); + if ids.is_empty() { + return Err(bad(CMD, "no target layers")); + } + // Pattern overlays name their pattern; resolve to library patterns copied into the document. + let (effects, pats) = resolve_style_effects(s, &style.effects)?; let label = format!("Apply Style: {}", style.name); s.edit(&label, |doc, _| { for pat in &pats { @@ -204,29 +237,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { // Styles can't sit on the Background: Photoshop turns it into a normal layer first. crate::extra_cmds::background_to_layer(doc, *id); let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - if add { - l.effects.items.extend(effects.iter().cloned()); - } else { - l.effects.items = effects.clone(); - l.effects.psd_raw = None; - } - l.effects.psd_raw = None; - l.effects.enabled = true; - // Adding keeps the layer's blending unless the preset carries some: a blend mode, or - // an Opacity saved on its own (`style.presets.new` with `includeBlending: false`). - if !add || style.blend.is_some() || style.opacity.is_some() { - if let Some(b) = style.blend { - l.blend = b; - } - if let Some(f) = style.fill_opacity { - l.fill_opacity = f; - } else if !add { - l.fill_opacity = 1.0; - } - if let Some(o) = style.opacity { - l.opacity = o; - } - } + apply_to_layer(l, &style, &effects, add); } Ok(()) })?; diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index cbbd746195..0ca3c36b98 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -1047,6 +1047,12 @@ pub struct Warp { pub values: Vec, } +/// Relative to the magnitude so the fit's rounding at large origins isn't rejected. +fn point_fits(expected: [f64; 2], actual: [f64; 2]) -> bool { + let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6); + !((actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1])) +} + impl Warp { /// No warp over `bounds`. pub fn none(bounds: [f64; 4]) -> Warp { @@ -1080,36 +1086,53 @@ impl Warp { WarpStyle::None => true, WarpStyle::Custom | WarpStyle::Cylinder => match &self.mesh { None => true, - Some(m) => { - if !m.is_valid() { - return false; - } - let nx = m.nx(); - let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1); - for pj in 0..pr { - for j in 0..4 { - let v = m.vs[pj] + (m.vs[pj + 1] - m.vs[pj]) * j as f64 / 3.0; - for pi in 0..pc { - for i in 0..4 { - let u = m.us[pi] + (m.us[pi + 1] - m.us[pi]) * i as f64 / 3.0; - let expected = self.box_point(u, v); - let actual = m.points[(3 * pj + j) * nx + 3 * pi + i]; - // Relative to the magnitude so the fit's rounding at large origins isn't rejected. - let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6); - if (actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1]) { - return false; - } - } - } - } - } - true - } + Some(m) => self.mesh_is_box_fit(m), }, _ => self.style_warp().is_none(), } } + /// True when every control point of `m` sits where the box's own grid puts it. + fn mesh_is_box_fit(&self, m: &BezierMesh) -> bool { + if !m.is_valid() { + return false; + } + let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1); + for pj in 0..pr { + for j in 0..4 { + if !self.mesh_row_is_box_fit(m, pj, j, pc) { + return false; + } + } + } + true + } + + /// One sample row (`j` within patch row `pj`) of [`Self::mesh_is_box_fit`]. + fn mesh_row_is_box_fit(&self, m: &BezierMesh, pj: usize, j: usize, pc: usize) -> bool { + let nx = m.nx(); + let (Some(&v0), Some(&v1)) = (m.vs.get(pj), m.vs.get(pj + 1)) else { + return false; + }; + let v = v0 + (v1 - v0) * j as f64 / 3.0; + for pi in 0..pc { + let (Some(&u0), Some(&u1)) = (m.us.get(pi), m.us.get(pi + 1)) else { + return false; + }; + for i in 0..4 { + let u = u0 + (u1 - u0) * i as f64 / 3.0; + let expected = self.box_point(u, v); + let Some(&actual) = m.points.get((3 * pj + j) * nx + 3 * pi + i) else { + return false; + }; + if !point_fits(expected, actual) { + return false; + } + } + } + true + } + fn box_point(&self, s: f64, t: f64) -> [f64; 2] { let b = self.bounds; [b[0] + s * (b[2] - b[0]), b[1] + t * (b[3] - b[1])] diff --git a/crates/text/src/cjk.rs b/crates/text/src/cjk.rs index c0e632d983..ab1c7d8992 100644 --- a/crates/text/src/cjk.rs +++ b/crates/text/src/cjk.rs @@ -53,28 +53,48 @@ pub fn classify(c: char) -> Option { }) } -/// Script order for a locale tag such as `ja_JP.UTF-8`, `zh-Hant-TW`, `zh_CN` or `ko-KR`. -/// Non-CJK (or unknown) locales get Simplified Chinese first, so Japanese forms only win -/// for shared Han when the locale is Japanese. -pub fn script_order(locale: Option<&str>) -> [CjkScript; 4] { +/// A locale tag reduced to what [`script_order`] and [`locale_script`] compare: +/// lowercase, `_` as `-`, without an encoding or modifier suffix. +fn normalized_locale(locale: Option<&str>) -> String { + locale.unwrap_or("").split(['.', '@']).next().unwrap_or("").to_ascii_lowercase().replace('_', "-") +} + +/// The CJK script a locale explicitly asks for, or `None` for a non-CJK (or unknown) locale. +/// +/// [`script_order`] also gives non-CJK locales a default order (Simplified Chinese first). The +/// craft-font manifest, however, lists its Japanese faces before Noto Sans CJK SC, so the eager +/// provider keeps that Japanese-first baseline for Han unless the user's locale names another +/// script. This helper distinguishes a non-CJK/unknown effective locale (use the baseline +/// manifest order) from "zh-Hans/zh-Hant/ja/ko, use this script". +pub fn locale_script(locale: Option<&str>) -> Option { use CjkScript::*; - let tag = locale.unwrap_or("").split(['.', '@']).next().unwrap_or("").to_ascii_lowercase().replace('_', "-"); + let tag = normalized_locale(locale); let mut parts = tag.split('-'); let lang = parts.next().unwrap_or(""); let rest: Vec<&str> = parts.collect(); match lang { - "ja" => [Japanese, SimplifiedChinese, TraditionalChinese, Korean], - "ko" => [Korean, TraditionalChinese, SimplifiedChinese, Japanese], + "ja" => Some(Japanese), + "ko" => Some(Korean), "zh" | "yue" => { let hant = rest.iter().any(|p| matches!(*p, "hant" | "tw" | "hk" | "mo")); let hans = rest.iter().any(|p| matches!(*p, "hans" | "cn" | "sg")); - if (hant || lang == "yue") && !hans { - [TraditionalChinese, SimplifiedChinese, Japanese, Korean] - } else { - [SimplifiedChinese, TraditionalChinese, Japanese, Korean] - } + if (hant || lang == "yue") && !hans { Some(TraditionalChinese) } else { Some(SimplifiedChinese) } } - _ => [SimplifiedChinese, TraditionalChinese, Japanese, Korean], + _ => None, + } +} + +/// Script order for a locale tag such as `ja_JP.UTF-8`, `zh-Hant-TW`, `zh_CN` or `ko-KR`. +/// Non-CJK (or unknown) locales get Simplified Chinese first for system fonts, so Japanese +/// forms only win for shared Han when the locale is Japanese (craft faces keep the manifest's +/// Japanese-first order through [`locale_script`]). +pub fn script_order(locale: Option<&str>) -> [CjkScript; 4] { + use CjkScript::*; + match locale_script(locale) { + Some(Japanese) => [Japanese, SimplifiedChinese, TraditionalChinese, Korean], + Some(Korean) => [Korean, TraditionalChinese, SimplifiedChinese, Japanese], + Some(TraditionalChinese) => [TraditionalChinese, SimplifiedChinese, Japanese, Korean], + Some(SimplifiedChinese) | None => [SimplifiedChinese, TraditionalChinese, Japanese, Korean], } } @@ -330,7 +350,10 @@ fn fontconfig_match(script: CjkScript) -> Option { fn fontconfig_font_covers_sample(bytes: &[u8], family: &str, script: CjkScript) -> bool { use skrifa::MetadataProvider; - let index = face_index_for_family(bytes, family); + let Some(index) = face_index_for_family_checked(bytes, family) else { return false }; + if !font_face_is_readable(bytes, index) { + return false; + } let Ok(font) = skrifa::FontRef::from_index(bytes, index) else { return false }; let sample = match script { CjkScript::Japanese => "レイヤー図", @@ -509,51 +532,121 @@ pub fn mac_pingfang() -> Option { None } -/// Maximum collection faces and cumulative `name` records inspected by [`face_index_for_family`]. +/// Maximum collection faces and cumulative `name` records inspected by +/// [`face_index_for_family_checked`]. const MAX_COLLECTION_FACES: usize = 256; const MAX_NAME_RECORDS: usize = 8192; -/// Face index in a font file (or collection) whose family name is `family`; 0 when `family` is -/// empty or no face matches. Never panics on malformed data. -pub fn face_index_for_family(bytes: &[u8], family: &str) -> u32 { - use skrifa::{ - MetadataProvider, - raw::{FileRef, types::Tag}, - string::StringId, - }; - if family.is_empty() { - return 0; - } - let Ok(FileRef::Collection(c)) = FileRef::new(bytes) else { return 0 }; - let mut seen_faces = std::collections::HashSet::new(); - let mut seen_names = std::collections::HashSet::new(); - let mut budget = MAX_NAME_RECORDS; - for (i, f) in c.iter().take(MAX_COLLECTION_FACES).enumerate() { - if let Some(off_bytes) = bytes.get(12 + i * 4..12 + (i + 1) * 4) - && let Ok(arr) = <[u8; 4]>::try_from(off_bytes) - && !seen_faces.insert(u32::from_be_bytes(arr)) - { - continue; - } - let Ok(f) = f else { continue }; - if let Some(rec) = f.table_directory.table_records().iter().find(|r| r.tag() == Tag::new(b"name")) - && !seen_names.insert((rec.offset(), rec.length())) - { - continue; - } - for id in [StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME] { - for s in f.localized_strings(id) { - let Some(rem) = budget.checked_sub(1) else { - return 0; - }; - budget = rem; - if s.chars().eq(family.chars()) { - return i as u32; - } +/// Whether `font` has a family record exactly equal to `family`, charging each inspected record +/// to `budget` so malformed fonts cannot make this scan unbounded. +fn family_name_matches(font: &skrifa::FontRef<'_>, family: &str, budget: &mut usize) -> bool { + use skrifa::{MetadataProvider, string::StringId}; + + for id in [StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME] { + for s in font.localized_strings(id) { + let Some(rem) = budget.checked_sub(1) else { + return false; + }; + *budget = rem; + if s.chars().eq(family.chars()) { + return true; } } } - 0 + false +} + +/// Whether every table in the selected face of `bytes` really is present in the file. +/// +/// `FontRef` reads tables lazily: a face whose `cmap` and `name` are valid can still point another +/// table outside the file. Coverage checks only read `cmap`, so callers that register a selected +/// collection face (by family index, coverage result or face 0) must check this first; epaint +/// panics when it installs a configured face the parser cannot read. +fn face_tables_are_readable(font: &skrifa::raw::FontRef<'_>) -> bool { + let directory = font.table_directory(); + let records = directory.table_records(); + !records.is_empty() && records.len() == usize::from(directory.num_tables()) && records.iter().all(|record| font.table_data(record.tag()).is_some()) +} + +/// Whether face `index` of a font file or collection has a complete, in-bounds table directory. +/// +/// This is the selected-index counterpart of [`font_file_is_readable`]. A readable collection may +/// still contain a malformed face at `index`; the face's `cmap` and `name` can work while another +/// table points outside the file. Returns `false` for an out-of-range index or malformed data. +/// Never panics. +pub fn font_face_is_readable(bytes: &[u8], index: u32) -> bool { + skrifa::raw::FontRef::from_index(bytes, index).is_ok_and(|font| face_tables_are_readable(&font)) +} + +/// Whether `bytes` is a font file or font collection that the text engine's parser can read. +/// +/// This uses the same `skrifa` parser the text engine lays out and rasterizes with, instead of a +/// hand-written table-directory check with invented face/table caps. A readable non-font or +/// truncated file returns `false`; valid SFNT, OTF and TTC data returns `true`. For a collection, +/// at least one face must have a complete table directory. That does **not** make every face +/// readable: a face selected by family name, coverage or the empty-family face-0 contract must be +/// checked with [`font_face_is_readable`], because its `cmap` and `name` can work while another +/// table points out of bounds. +pub fn font_file_is_readable(bytes: &[u8]) -> bool { + use skrifa::raw::FileRef; + + match FileRef::new(bytes) { + Ok(FileRef::Font(font)) => face_tables_are_readable(&font), + Ok(FileRef::Collection(faces)) => faces.iter().any(|face| face.is_ok_and(|font| face_tables_are_readable(&font))), + Err(_) => false, + } +} + +/// Face index in a font file (or collection) whose family name is `family`. +/// +/// An empty `family` is the explicit "face 0" contract. A single-face file must actually carry +/// the requested family name; a collection must contain a face with it. `None` when the family is +/// missing, the data is malformed or the name budget is exhausted. The returned index has a +/// matching `name`, but its other tables are not validated: use [`font_face_is_readable`] before +/// registering it. Never panics. +pub fn face_index_for_family_checked(bytes: &[u8], family: &str) -> Option { + use skrifa::raw::{FileRef, types::Tag}; + + if family.is_empty() { + return Some(0); + } + let mut budget = MAX_NAME_RECORDS; + match FileRef::new(bytes).ok()? { + FileRef::Font(font) => family_name_matches(&font, family, &mut budget).then_some(0), + FileRef::Collection(c) => { + let mut seen_faces = std::collections::HashSet::new(); + let mut seen_names = std::collections::HashSet::new(); + for (i, f) in c.iter().take(MAX_COLLECTION_FACES).enumerate() { + if let Some(off_bytes) = bytes.get(12 + i * 4..12 + (i + 1) * 4) + && let Ok(arr) = <[u8; 4]>::try_from(off_bytes) + && !seen_faces.insert(u32::from_be_bytes(arr)) + { + continue; + } + let Ok(f) = f else { continue }; + if let Some(rec) = f.table_directory.table_records().iter().find(|r| r.tag() == Tag::new(b"name")) + && !seen_names.insert((rec.offset(), rec.length())) + { + continue; + } + if family_name_matches(&f, family, &mut budget) { + return u32::try_from(i).ok(); + } + if budget == 0 { + return None; + } + } + None + } + } +} + +/// Face index in a font file (or collection) whose family name is `family`; 0 when `family` is +/// empty or no face matches. Kept for callers that prefer the historical face-0 fallback; new +/// system-font selection should use [`face_index_for_family_checked`], verify the selected face +/// with [`font_face_is_readable`], and then verify coverage. Never panics on malformed data. +pub fn face_index_for_family(bytes: &[u8], family: &str) -> u32 { + face_index_for_family_checked(bytes, family).unwrap_or(0) } #[cfg(test)] @@ -561,6 +654,19 @@ mod tests { use super::*; use CjkScript::*; + #[test] + fn explicit_locale_scripts_are_distinct_from_the_non_cjk_default() { + assert_eq!(locale_script(Some("ja_JP.UTF-8")), Some(Japanese)); + assert_eq!(locale_script(Some("ko-KR")), Some(Korean)); + assert_eq!(locale_script(Some("zh-Hans-CN")), Some(SimplifiedChinese)); + assert_eq!(locale_script(Some("zh_CN")), Some(SimplifiedChinese)); + assert_eq!(locale_script(Some("zh-Hant-TW")), Some(TraditionalChinese)); + assert_eq!(locale_script(Some("yue-HK")), Some(TraditionalChinese)); + for unknown in [None, Some(""), Some("en_US.UTF-8"), Some("C"), Some("de"), Some("!!@@")] { + assert_eq!(locale_script(unknown), None, "{unknown:?}"); + } + } + #[test] fn locale_orders() { assert_eq!(script_order(Some("ja_JP.UTF-8"))[0], Japanese); @@ -656,6 +762,118 @@ mod tests { } } + /// A two-face TrueType collection built at runtime from the repository's OFL-licensed + /// Inter and JetBrains Mono files. Each face directory is rewritten with offsets relative to + /// the collection, so no font fixture is committed. + fn two_face_ttc(first: &[u8], second: &[u8]) -> Vec { + let font_count = 2usize; + let tables = |font: &[u8]| u16::from_be_bytes([font[4], font[5]]) as usize; + let dir_lengths = [12 + 16 * tables(first), 12 + 16 * tables(second)]; + let mut dir_offsets = Vec::with_capacity(font_count); + let mut cursor = 12 + 4 * font_count; + for length in dir_lengths { + dir_offsets.push(cursor); + cursor += length; + } + let data_start = cursor.next_multiple_of(4); + let mut bases = Vec::with_capacity(font_count); + let mut total = data_start; + for font in [first, second] { + bases.push(total); + total += font.len().next_multiple_of(4); + } + let mut out = vec![0u8; total]; + out[..4].copy_from_slice(b"ttcf"); + out[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes()); + out[8..12].copy_from_slice(&u32::try_from(font_count).expect("two faces").to_be_bytes()); + for (i, offset) in dir_offsets.iter().enumerate() { + let at = 12 + i * 4; + out[at..at + 4].copy_from_slice(&u32::try_from(*offset).expect("collection fits").to_be_bytes()); + } + for (i, font) in [first, second].into_iter().enumerate() { + let dir = dir_offsets[i]; + let base = bases[i]; + out[dir..dir + font.len().min(12)].copy_from_slice(&font[..font.len().min(12)]); + for record in 0..tables(font) { + let src = 12 + 16 * record; + let dst = dir + 12 + 16 * record; + out[dst..dst + 8].copy_from_slice(&font[src..src + 8]); + let table_offset = u32::from_be_bytes(font[src + 8..src + 12].try_into().expect("four bytes")); + let collection_offset = u32::try_from(base).expect("collection fits") + table_offset; + out[dst + 8..dst + 12].copy_from_slice(&collection_offset.to_be_bytes()); + out[dst + 12..dst + 16].copy_from_slice(&font[src + 12..src + 16]); + } + out[base..base + font.len()].copy_from_slice(font); + } + out + } + + #[test] + fn checked_face_lookup_uses_the_requested_collection_family_and_exact_coverage() { + use crate::scripts::face_covers; + + let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"); + let ttc = two_face_ttc(inter, jetbrains); + + assert_eq!(face_index_for_family_checked(&ttc, "Inter"), Some(0)); + assert_eq!(face_index_for_family_checked(&ttc, "JetBrains Mono"), Some(1)); + assert_eq!(face_index_for_family_checked(&ttc, "Noto Sans CJK TC"), None); + assert_eq!(face_index_for_family(&ttc, "JetBrains Mono"), 1, "the old wrapper keeps its face-0 fallback only on a miss"); + assert_eq!(face_index_for_family_checked(inter, "Inter"), Some(0)); + assert_eq!(face_index_for_family_checked(inter, "JetBrains Mono"), None, "a single-face file must carry the requested family"); + assert_eq!(face_index_for_family_checked(inter, ""), Some(0), "empty family is the explicit face-0 contract"); + assert_eq!(face_index_for_family_checked(b"", "Inter"), None); + + // Both faces cover A. JetBrains Mono does not cover Latin Small Letter B with Stroke, + // while Inter does, so a first-covering-face lookup cannot satisfy this pair. + assert!(face_covers(&ttc, 0, 'A')); + assert!(face_covers(&ttc, 1, 'A')); + assert!(face_covers(&ttc, 0, 'ƀ')); + assert!(!face_covers(&ttc, 1, 'ƀ')); + assert!(!face_covers(&ttc, 1, '日')); + assert!(!face_covers(&ttc, 2, 'A'), "out-of-range face index"); + } + + #[test] + fn font_file_validation_uses_the_layout_parser() { + let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"); + assert!(font_file_is_readable(inter)); + assert!(font_file_is_readable(&two_face_ttc(inter, jetbrains))); + assert!(!font_file_is_readable(b"this is not a font")); + assert!(!font_file_is_readable(&inter[..20])); + let mut missing_table = inter.to_vec(); + // The first directory record begins at 12; its offset occupies bytes 20..24. + missing_table[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(!font_file_is_readable(&missing_table), "a complete directory cannot point outside the file"); + } + + /// A readable collection can contain a malformed non-selected face, so the file-level check + /// must not stand in for validating the face a caller selects. The selected face keeps a valid + /// `cmap` (coverage succeeds) and `name` (family lookup succeeds) while another table points + /// past the end of the file. + #[test] + fn selected_face_validation_rejects_a_malformed_face_in_a_readable_collection() { + use crate::scripts::face_covers; + + let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"); + let mut malformed = jetbrains.to_vec(); + let tables = u16::from_be_bytes([malformed[4], malformed[5]]) as usize; + let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| malformed.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table"); + malformed[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes()); + let ttc = two_face_ttc(inter, &malformed); + + assert!(font_file_is_readable(&ttc), "face 0 remains a readable face"); + assert_eq!(face_index_for_family_checked(&ttc, "JetBrains Mono"), Some(1), "the malformed face's name still resolves"); + assert!(face_covers(&ttc, 1, 'A'), "the malformed face's cmap still covers A"); + assert!(!font_face_is_readable(&ttc, 1), "its glyf table lies outside the collection"); + assert!(font_face_is_readable(&ttc, 0), "positive control: the good face stays readable"); + assert!(!font_face_is_readable(&ttc, 2), "out-of-range face"); + assert!(font_face_is_readable(&two_face_ttc(inter, jetbrains), 1), "positive control: a valid selected face passes"); + } + #[test] fn face_index_handles_bad_data() { assert_eq!(face_index_for_family(b"", "PingFang SC"), 0); diff --git a/crates/text/src/scripts.rs b/crates/text/src/scripts.rs index b6e0aae74f..54120f609b 100644 --- a/crates/text/src/scripts.rs +++ b/crates/text/src/scripts.rs @@ -280,6 +280,15 @@ pub fn covering_face(bytes: &[u8], c: char) -> Option { } } +/// Whether face `index` of `bytes` (a font or collection) maps `c` in its character map. +/// `false` for an out-of-range face or data that doesn't parse. Never panics. +pub fn face_covers(bytes: &[u8], index: u32, c: char) -> bool { + use skrifa::MetadataProvider; + + let Ok(font) = skrifa::FontRef::from_index(bytes, index) else { return false }; + font.charmap().map(c).is_some() +} + #[cfg(test)] mod tests { use super::*; @@ -351,6 +360,10 @@ mod tests { 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); } + assert!(face_covers(inter, 0, 'A')); + assert!(!face_covers(inter, 0, 'ส')); + assert!(!face_covers(inter, 1, 'A'), "a single-face file has no face 1"); + assert!(!face_covers(b"", 0, 'A')); } /// With the real system fonts, each script that has a candidate installed has one that diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rs index 3af0e2ac3a..3aa6e9c0c2 100644 --- a/crates/ui-egui/src/artboard_ui.rs +++ b/crates/ui-egui/src/artboard_ui.rs @@ -145,25 +145,26 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { edit = Some(json!({"layer": layer.id.0, "preset": preset})); } }); - // The visible label and the accessible name differ for X and Y ("X" alone does not say - // position), so the name comes from the call site. + // W/H use a short visible label but the full word as the accessible name (a screen reader + // says "Width", not "W"); X/Y already name their axis, so their name comes from the call site + // too. let num = |ui: &mut egui::Ui, label: &str, name: &str, v: &mut f32, range: std::ops::RangeInclusive| -> bool { ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim).size(12.0)); - crate::widgets::value_field(ui, v, range, "px", 64.0).accessible_name(tl!(name)).changed() + crate::widgets::value_field(ui, v, range, "px", 64.0).accessible_name(name).changed() }; let r = a.rect; ui.horizontal(|ui| { let (mut w, mut h) = (r.width() as f32, r.height() as f32); - let cw = num(ui, "W", "Width", &mut w, 1.0..=300_000.0); - let ch = num(ui, "H", "Height", &mut h, 1.0..=300_000.0); + let cw = num(ui, "W", tl!("Width"), &mut w, 1.0..=300_000.0); + let ch = num(ui, "H", tl!("Height"), &mut h, 1.0..=300_000.0); if cw || ch { edit = Some(json!({"layer": layer.id.0, "width": w.round(), "height": h.round(), "coalesce": key("wh")})); } }); ui.horizontal(|ui| { let (mut x, mut y) = (r.x0 as f32, r.y0 as f32); - let cx = num(ui, "X", "X", &mut x, -300_000.0..=300_000.0); - let cy = num(ui, "Y", "Y", &mut y, -300_000.0..=300_000.0); + let cx = num(ui, "X", tl!("X"), &mut x, -300_000.0..=300_000.0); + let cy = num(ui, "Y", tl!("Y"), &mut y, -300_000.0..=300_000.0); if cx || cy { edit = Some(json!({"layer": layer.id.0, "x": x.round(), "y": y.round(), "coalesce": key("xy")})); } @@ -446,4 +447,23 @@ mod tests { app.ui.layer_comp_selected = Some(999); assert_eq!(crate::comps_ui::target(&app), Some(b)); } + + #[test] + fn property_fields_are_named_for_their_axis() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let (mut app, _) = app(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap(); + let id = app.session.active().unwrap().doc.artboards()[0].0; + let layer = app.session.active().unwrap().doc.layer(id).unwrap().clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(520.0, 420.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(move |ui, app: &mut PhotocraftApp| properties(app, ui, &layer), app); + h.run_steps(2); + let labels: Vec = h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect(); + assert_eq!(labels, ["Width", "Height", "X", "Y"].map(String::from).to_vec(), "the fields announce their own axis in layout order"); + } } diff --git a/crates/ui-egui/src/background_redraw.rs b/crates/ui-egui/src/background_redraw.rs index 53ab20f73f..8b13c01eab 100644 --- a/crates/ui-egui/src/background_redraw.rs +++ b/crates/ui-egui/src/background_redraw.rs @@ -16,6 +16,8 @@ //! uploads those blocks instead of compositing every layer again. use std::collections::VecDeque; +#[cfg(test)] +use std::sync::atomic::AtomicU64; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, TryRecvError}; use std::sync::{Arc, Weak}; @@ -43,6 +45,55 @@ const KEEP: usize = 2; /// [`GpuCanvas::refresh`] kind of a redraw served from a [`Kept`] composite. pub(crate) const KEPT: &str = "kept"; +/// Tests hold the redraw worker before it draws a batch, so an edit lands while blocks are still +/// to come. A real run never waits: a fast machine draws a test document before its next frame, +/// leaving nothing drawn "before" the edit. +#[cfg(test)] +static HOLD: AtomicBool = AtomicBool::new(false); + +/// Identity of the next spawned redraw worker: lets a test tell the worker it watched from a +/// replacement that [`restart`] spawns after an edit. +#[cfg(test)] +static NEXT_WORKER_GENERATION: AtomicU64 = AtomicU64::new(1); + +/// Hold the redraw worker until the guard drops. +#[cfg(test)] +pub(crate) fn hold_redraws() -> HoldRedraws { + HOLD.store(true, Ordering::SeqCst); + HoldRedraws +} + +/// Wait until worker `generation` of document `doc`'s [`Redraw`] has reached its pre-batch +/// [`HOLD`]. A replacement worker has another generation, so an edit only lands while the worker +/// the test watched still has its blocks to draw. Returns `false` after `timeout`. +#[cfg(test)] +pub(crate) fn wait_for_held_redraw(app: &PhotocraftApp, doc: DocId, generation: u64, timeout: std::time::Duration) -> bool { + let deadline = std::time::Instant::now() + timeout; + loop { + if let Some(r) = app.redraws.get(&doc) + && r.worker_generation == generation + && r.reached_hold.load(Ordering::SeqCst) + { + return true; + } + if std::time::Instant::now() >= deadline { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// Releases [`hold_redraws`], including while a test unwinds. +#[cfg(test)] +pub(crate) struct HoldRedraws; + +#[cfg(test)] +impl Drop for HoldRedraws { + fn drop(&mut self) { + HOLD.store(false, Ordering::SeqCst); + } +} + /// One finished block, as texels of the canvas texture. struct Piece { block: usize, @@ -70,6 +121,11 @@ pub(crate) struct Redraw { collected_bytes: u64, /// Bytes the kept composites may hold: what Memory Usage leaves beside the document. cap: u64, + /// Set when this worker first reaches the test [`HOLD`], and this worker's generation. + #[cfg(test)] + reached_hold: Arc, + #[cfg(test)] + worker_generation: u64, } impl Redraw { @@ -423,11 +479,22 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, s: Spawn) { let left = todo.len(); let (tx, rx) = std::sync::mpsc::sync_channel(BATCH); let stop = Arc::new(AtomicBool::new(false)); + #[cfg(test)] + let reached_hold = Arc::new(AtomicBool::new(false)); + #[cfg(test)] + let worker_generation = NEXT_WORKER_GENERATION.fetch_add(1, Ordering::SeqCst); + #[cfg(test)] + let worker_hold = reached_hold.clone(); let work = (blocks.clone(), stop.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("canvas-redraw".into()).spawn(move || { let (blocks, stop, ctx) = work; // A panic stops the redraw: the receiver sees the worker gone and drops it. - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx))); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + #[cfg(test)] + draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx, &worker_hold); + #[cfg(not(test))] + draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx); + })); ctx.request_repaint(); }); if let Err(e) = spawned { @@ -452,40 +519,14 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, s: Spawn) { collected, collected_bytes, cap, + #[cfg(test)] + reached_hold, + #[cfg(test)] + worker_generation, }, ); } -/// A test can hold the worker after a batch: a real worker's speed is not reproducible, and the -/// edit-during-a-redraw test needs the redraw to be certainly still running. -#[cfg(test)] -pub(crate) mod test_hold { - use std::sync::atomic::{AtomicBool, Ordering}; - - static HELD: AtomicBool = AtomicBool::new(false); - - /// Holds every redraw worker after its next batch until this guard drops. - pub(crate) struct Hold; - - pub(crate) fn hold() -> Hold { - HELD.store(true, Ordering::SeqCst); - Hold - } - - impl Drop for Hold { - fn drop(&mut self) { - HELD.store(false, Ordering::SeqCst); - } - } - - /// Called by the worker between batches while a test holds it. - pub(crate) fn wait() { - while HELD.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_millis(2)); - } - } -} - /// The worker: composite `todo`'s blocks of `doc` in batches and hand each over, until done or /// stopped. #[allow(clippy::too_many_arguments)] @@ -498,8 +539,17 @@ fn draw( stop: &AtomicBool, tx: &SyncSender, ctx: &egui::Context, + #[cfg(test)] reached_hold: &AtomicBool, ) { for batch in todo.chunks(BATCH) { + // A test may hold the worker here; a cancelled redraw must still exit, not wait for release. + #[cfg(test)] + while HOLD.load(Ordering::SeqCst) && !stop.load(Ordering::Relaxed) { + // This worker, identified by its own acknowledgement, reached the hold: a replacement + // spawned after the edit starts with another one and can't satisfy the test's wait. + reached_hold.store(true, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(1)); + } if stop.load(Ordering::Relaxed) { return; } @@ -517,8 +567,6 @@ fn draw( } ctx.request_repaint(); } - #[cfg(test)] - test_hold::wait(); } } diff --git a/crates/ui-egui/src/background_redraw_tests.rs b/crates/ui-egui/src/background_redraw_tests.rs index 08152b82e8..114a150eb1 100644 --- a/crates/ui-egui/src/background_redraw_tests.rs +++ b/crates/ui-egui/src/background_redraw_tests.rs @@ -210,13 +210,20 @@ fn a_full_cpu_refresh_draws_in_the_background_with_the_synchronous_pixels() { fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; - // Hold the worker after its first batch: how fast it composites is not reproducible (a fast - // machine finished all 4×3 blocks before the edit's frame on FreeBSD), and the test needs the - // redraw to still be running when the edit lands. The hold is released before `settle`. - let hold = test_hold::hold(); + // Hold the worker before its first batch and wait until this very worker acknowledges that + // hold: when the fill lands, all 12 blocks of this 4×3 document are still to draw by it. + // Without the hold a fast machine finishes them before the next frame, so the edit never + // races the worker and this test only checked a completed redraw; without the per-worker + // acknowledgement an edit could beat the worker to the hold, and its restarted replacement + // would satisfy the checks. + let held = hold_redraws(); let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); g.harness.step(); - assert!(g.harness.state().redraws.contains_key(&doc)); + let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation; + assert!( + wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)), + "the redraw worker never reached the pre-batch hold; an edit would race an unstarted redraw" + ); // A corner, drawn last (farthest from the view's centre), changes on a layer of its own while // the redraw runs: a small edit, drawn at once. g.harness.state_mut().run("layer.new.layer", json!({})).expect("layer"); @@ -226,8 +233,12 @@ fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() { g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); g.harness.step(); assert_eq!(g.harness.state().perf.last_refresh, "rect", "the fill's damage was drawn synchronously"); - assert!(g.harness.state().redraws.contains_key(&doc), "the redraw goes on"); - drop(hold); + // Still running with blocks to draw, and drawing the edited document, not the state before it. + let current = g.harness.state().session.active().expect("document").doc.clone(); + let r = g.harness.state().redraws.get(&doc).expect("the redraw goes on"); + assert!(r.pending.iter().any(|p| *p), "blocks are still to draw"); + assert!(Arc::ptr_eq(&r.doc, ¤t) || *r.doc == *current, "the blocks left draw the edit"); + drop(held); settle(&mut g); assert_matches_synchronous(&mut g, doc); } diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/caf_ui.rs index 04bd6e05f5..aaa7978e23 100644 --- a/crates/ui-egui/src/caf_ui.rs +++ b/crates/ui-egui/src/caf_ui.rs @@ -1647,6 +1647,31 @@ mod tests { app.distort.caf.as_ref().unwrap() } + #[test] + fn settings_dropdowns_are_named_for_their_visible_labels() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 900.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, app: &mut PhotocraftApp| show(app, ui.ctx()), app); + h.run_steps(2); + // The Indicates dropdown lives inside a collapsed "Sampling Area Overlay" header. + h.get_by_role_and_label(Role::DisclosureTriangle, "Sampling Area Overlay").click(); + h.run_steps(3); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + for label in ["Indicates", "Color Adaptation", "Rotation Adaptation", "Output To"] { + assert!(labels.iter().any(|have| have == label), "{label} names its dropdown: {labels:?}"); + } + for wrong in ["Contents:", "Color", "Rotation", "Source"] { + assert!(!labels.iter().any(|have| have == wrong), "{wrong} names no control here: {labels:?}"); + } + } + /// Photoshop opens the workspace with the Sampling Brush subtracting at a tenth of the /// window's side, Auto sampling, output to a new layer. #[test] diff --git a/crates/ui-egui/src/cam_preview.rs b/crates/ui-egui/src/cam_preview.rs index 45f6c5f1ed..68cd29f02c 100644 --- a/crates/ui-egui/src/cam_preview.rs +++ b/crates/ui-egui/src/cam_preview.rs @@ -29,6 +29,9 @@ struct Running { key: String, ctx: JobCtx, rx: Receiver>, + /// Test-only notification sent after this worker publishes its real result. + #[cfg(test)] + finished: Receiver<()>, /// The full-resolution job that follows a coarse one. refine: Option, /// This job refines a coarse preview already shown: its failure leaves that one shown. @@ -179,13 +182,25 @@ fn spawn(job: ContentAwarePreview, key: String, refining: bool) -> Option BASE && showing(&app)); assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30), "the preview shows the move"); let doc = app.session.active().unwrap().doc.clone(); @@ -270,32 +277,37 @@ mod tests { tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m); tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 30.0 }, m); assert!(crate::cam_transform::active(&app)); - let (mut now, mut shown) = (0.0, step(&mut app, 0.0)); - for _ in 0..800 { - if shown.is_some() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - now += 10.0; - shown = step(&mut app, now); - } - let (preview, _) = shown.expect("the box shows the result"); + let mut now = 0.0; + let (preview, _) = wait_for(&mut app, &mut now, 0).expect("the box shows the result"); assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30)); // Cancelling the box drops the preview. crate::cam_transform::cancel(&mut app); assert!(step(&mut app, now + 1.0).is_none() && app.cam_preview.is_none()); } - /// Step until the canvas shows a preview with a key past `after`, or give up after a while. + /// Wait for the specific worker to publish its result, then let the normal non-blocking + /// `step` path consume it. Coverage instrumentation can make a solve much slower than a + /// fixed polling loop; the watchdog bounds a stuck worker without setting its expected speed. fn wait_for(app: &mut PhotocraftApp, now: &mut f64, after: u64) -> Option<(Arc, u64)> { - for _ in 0..6000 { - if let Some(shown) = step(app, *now).filter(|s| s.1 > after) { - return Some(shown); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); + loop { + let shown = step(app, *now); + if shown.as_ref().is_some_and(|s| s.1 > after) { + return shown; + } + let p = app.cam_preview.as_ref()?; + if let Some(running) = &p.running { + let remaining = deadline.checked_duration_since(std::time::Instant::now())?; + running.finished.recv_timeout(remaining).ok()?; + } else if shown.is_some() || p.failed.as_deref() == Some(p.key.as_str()) { + return None; + } else if *now < p.since + DEBOUNCE_MS { + // Advance the simulated debounce clock without sleeping in real time. + *now = p.since + DEBOUNCE_MS; + } else { + return None; } - std::thread::sleep(std::time::Duration::from_millis(10)); - *now += 10.0; } - None } #[test] diff --git a/crates/ui-egui/src/channel_options_ui_tests.rs b/crates/ui-egui/src/channel_options_ui_tests.rs index 210a4ff0e3..9a9a93394c 100644 --- a/crates/ui-egui/src/channel_options_ui_tests.rs +++ b/crates/ui-egui/src/channel_options_ui_tests.rs @@ -145,6 +145,30 @@ fn dialog_body_renders_for_alpha_spot_and_quick_mask() { } } +#[test] +fn value_fields_are_named_for_the_visible_solidity_or_opacity_caption() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let labels = |f: Map, body: fn(&mut egui::Ui, &mut Map)| -> Vec { + let mut h = Harness::builder() + .with_size(egui::vec2(520.0, 300.0)) + .with_context_setup(|ctx| crate::PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(&body, f); + h.run_steps(2); + h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect() + }; + + let app = app(); + let mut f = fields(&app, &json!(0)).unwrap(); + f.insert("indicates".into(), json!("spot")); + assert_eq!(labels(f.clone(), body), ["Solidity:"]); + f.insert("indicates".into(), json!("masked")); + assert_eq!(labels(f, body), ["Opacity:"]); + assert_eq!(labels(new_spot_fields(&app).unwrap(), new_spot_body), ["Solidity:"]); +} + #[test] fn new_spot_channel_dialog_creates_the_ink_from_the_selection_and_remembers_it() { let mut app = app(); diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/cjk_fonts.rs index 6d3279d1ea..7dfefbb640 100644 --- a/crates/ui-egui/src/cjk_fonts.rs +++ b/crates/ui-egui/src/cjk_fonts.rs @@ -13,18 +13,32 @@ //! 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 -//! locale's script (Japanese forms only for a Japanese locale). At most one font is read per -//! frame, each file at most once, and once every script has been tried the scan stops. +//! Script order follows the effective UI locale ([`photocraft_text::cjk::script_order`]): Kana +//! prefers a Japanese font, Hangul a Korean one, Bopomofo a Traditional Chinese one, and Han the +//! locale's script. The effective locale is the translated UI language when it names +//! ja/ko/zh-Hans/zh-Hant; otherwise it is the OS locale. An English UI on a Japanese, Korean or +//! Chinese OS therefore follows that OS script, not the English baseline. The craft manifest +//! lists Shippori Mincho and BIZ UDPGothic before Noto Sans CJK SC, so a non-CJK/unknown +//! effective locale keeps the migration baseline's first covering face for shared Han and kana +//! (Shippori Mincho Regular); Hangul intentionally uses the Korean face (NanumGothic) instead, +//! because [`CjkChar::preferred`] always prefers Korean, even though the old linear stack would +//! have picked the broad Simplified Chinese face. An explicit zh-Hans/zh-Hant/ja/ko preference +//! selects its own form and keeps the UI-first face for its script (BIZ UDPGothic for Japanese). +//! The lazy loader reads at most one font per frame, each file at most once, and once every +//! script has been tried the scan stops. //! //! Builds made with the optional craft-fonts input (`CRAFT_FONTS_DIR`, -//! [`photocraft_text::craft_fonts`]) carry Japanese fonts (BIZ UDPGothic first): they are tried -//! before the system Japanese fonts, in the Japanese slot of the same locale order. Without -//! craft-fonts (and on the web, which never embeds them) nothing changes. +//! [`photocraft_text::craft_fonts`]) carry Japanese, Chinese, Korean and other faces. A +//! per-character [`FontProvider`] serves them, and the system font a locale defers to, in the +//! first frame; the lazy loader remains the later fallback. The provider has no lifetime read +//! cap. It retains at most [`MAX_SYSTEM_CACHE_BYTES`] of unique font-file blobs, charging a +//! collection (TTC) once however many faces it selects; a face that cannot be retained is +//! returned transiently for the current request, so a later Fontconfig candidate is never +//! skipped merely because earlier characters read other fonts. +//! Without craft-fonts (and on the web, which never embeds them) nothing changes. use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; -use egui::{FontData, FontFamily, FontId, Shape}; +use egui::{FallbackRequest, FontData, FontFamily, FontId, FontProvider, Shape}; use photocraft_text::cjk::{self, CjkChar, CjkScript, FontFile}; use photocraft_text::craft_fonts::{self, CraftFont}; use photocraft_text::scripts::{self, Script}; @@ -32,8 +46,18 @@ 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). +/// At most this many candidate files are read for one non-CJK script by the lazy loader. const MAX_SCRIPT_READS: usize = 6; +/// Upper bound on the unique font-file blobs the eager provider retains in its own cache. +/// Structurally invalid candidates are not retained at all. A readable file is charged once, +/// whatever number of faces the provider selects from a collection; it is evicted before the +/// budget is exceeded. A file that cannot be retained is still used for the current request and +/// returned transiently to egui (which may own that installed face independently). There is +/// deliberately no lifetime read cap: a valid Fontconfig match appended after many +/// absent/non-covering static paths (or after earlier characters) must still be reached. +const MAX_SYSTEM_CACHE_BYTES: usize = 128 << 20; +/// Remembered face names are tiny but still bounded independently of the blob budget. +const MAX_SYSTEM_FACE_NAMES: usize = 1024; /// Name prefix of the registered fallback fonts. pub const FONT_PREFIX: &str = "system-cjk"; @@ -43,42 +67,519 @@ pub struct Sources { pub locale: fn() -> Option, pub files: fn(CjkScript) -> Vec, pub last_resort: fn() -> Vec, + /// Whether the background Fontconfig CJK lookup is still running. The provider must not fall + /// through to a lower-priority script (for example Simplified Chinese for a Hant character) + /// while the preferred script may still gain a system face. Injectable so tests (and the web + /// build) never depend on timing. + pub pending: fn() -> bool, /// 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, /// The face of a font file whose character map has the character (`None`: not this file). pub covers: fn(&[u8], char) -> Option, - /// Embedded fonts tried before `files` for a script (craft-fonts' Japanese fonts). - pub embedded: fn(CjkScript) -> Vec<&'static CraftFont>, - /// Register every craft-fonts face up front, so a headless frame can shape CJK and other - /// scripts before the lazy loader gets a second pass (tests panic on a missing glyph). + /// Embedded craft faces declaring an ISO 15924 script, in the script's own order. The + /// provider and lazy loader both use this injection (tests can therefore pin craft-font + /// selection without depending on the build input). + pub embedded: fn(&'static str) -> Vec<&'static CraftFont>, + /// Install the per-character craft-font provider, so a headless first frame can shape CJK + /// and other scripts before the lazy loader gets a second pass (tests panic on a missing + /// glyph). It selects a face for the character's script instead of putting a broad face into + /// the family stack up front for every later character. pub eager_craft_fonts: bool, } -/// craft-fonts' Japanese fonts for the Japanese script, UI face first (empty without craft-fonts). +/// Craft fonts declaring `iso`, Regular first and (for Japanese) the UI face first; empty +/// without craft-fonts. This is the explicit-locale order; a non-CJK/unknown effective locale +/// uses the raw manifest order through [`craft_face_manifest`] instead. +/// +/// The lazy loader tries these before system files for a script, so its fallback order stays +/// `preferred script, then the locale order` even for a character the provider left to it. +pub fn craft_embedded_iso(iso: &'static str) -> Vec<&'static CraftFont> { + craft_faces(iso).into_iter().map(|(_, f)| f).collect() +} + +/// Craft fonts for a CJK script; a convenience wrapper for callers that already hold the enum. pub fn craft_embedded(script: CjkScript) -> Vec<&'static CraftFont> { - if script == CjkScript::Japanese { craft_fonts::japanese_for_ui() } else { Vec::new() } + craft_embedded_iso(cjk_iso(script)) } /// No embedded fonts (tests that pin the system-font behaviour). -pub fn no_embedded(_: CjkScript) -> Vec<&'static CraftFont> { +pub fn no_embedded(_: &'static str) -> Vec<&'static CraftFont> { Vec::new() } +/// Craft fonts chosen per character, the way the lazy loader chooses them for one missing glyph. +/// +/// A single linear font stack cannot express the per-script preference: a broad Noto Sans CJK SC +/// face covers kana and Hangul too, so putting it in the stack would make it win there over the +/// Japanese or Korean face. A [`FontProvider`] is asked per missing character instead, and this +/// one returns the face for that character's script. When the preferred script has no craft face +/// (e.g. Traditional Chinese), it asks the system font for that script first, and only falls +/// through the locale order (so a Simplified Chinese face comes last) when the system has none. +/// +/// egui still resolves a character from an already discovered broad face before asking a +/// provider again; a mixed-script run whose first character discovered SC can therefore serve a +/// later kana/Hangul character from SC. Removing that last ambiguity needs script-aware fallback +/// in epaint (or per-script text runs); this provider fixes the eager-stack case. +struct CraftFontProvider { + locale: fn() -> Option, + files: fn(CjkScript) -> Vec, + last_resort: fn() -> Vec, + pending: fn() -> bool, + scripts: fn(Script) -> Vec, + covers: fn(&[u8], char) -> Option, + embedded: fn(&'static str) -> Vec<&'static CraftFont>, + /// Interface > UI Font Size multiplier for the discovered faces (see `theme::ui_font_scale`). + scale: std::sync::Arc, + /// System files, faces and failed lookups read for characters no craft face covers. + system: std::sync::Mutex, + /// I/O for a candidate path; `read_font` in production, injectable by tests. + reader: fn(&std::path::Path) -> Option>, +} + +/// A readable, structurally valid font file retained as one shared blob, no matter how many +/// faces of it the provider selects. The blob is charged to the byte budget once. +struct CachedFile { + path: PathBuf, + data: FontData, + bytes: usize, +} + +struct SystemCache { + /// Unique retained font blobs, oldest first; evicted when the byte budget is exceeded. + /// A collection's faces share this one entry, so a TTC is not charged per face. + files: Vec, + /// Paths whose read failed (missing, empty, oversized, unreadable): never retry them for + /// each missing character. + failed_reads: std::collections::HashSet, + /// Paths that were readable but structurally not a font (truncated download, unrelated + /// file): negative-cached separately from an I/O failure and from a non-covering face. + invalid_fonts: std::collections::HashSet, + /// Names of faces handed to egui, reusing their name across characters. These carry no font + /// bytes (the blob stays in `files` while retained) and are capped by + /// [`MAX_SYSTEM_FACE_NAMES`]. + faces: Vec, + /// `face_index_for_family_checked` results, including family misses, so a collection's + /// `name`/directory tables are not parsed again for every character. + family_indices: Vec<(PathBuf, String, Option)>, + /// Bytes of the unique blobs in `files`. A selected face adds no bytes: egui's installed copy + /// may outlive the provider's reference, but the provider charges and bounds only its own + /// retained blob. + retained_bytes: usize, + /// Budget for `retained_bytes`; injectable (small) in tests. + max_bytes: usize, + /// Next face name; monotonic so names are never reused for a different face. + next_face_name: usize, + /// Successful I/O reads. Diagnostics/tests only: there is deliberately no lifetime cap. + #[cfg_attr(not(test), allow(dead_code))] + reads: usize, +} + +impl Default for SystemCache { + fn default() -> Self { + Self { + files: Vec::new(), + failed_reads: std::collections::HashSet::new(), + invalid_fonts: std::collections::HashSet::new(), + faces: Vec::new(), + family_indices: Vec::new(), + retained_bytes: 0, + max_bytes: MAX_SYSTEM_CACHE_BYTES, + next_face_name: 0, + reads: 0, + } + } +} + +impl SystemCache { + /// Evict the oldest blobs until `extra` more bytes fit. Returns `false` when even an empty + /// cache cannot hold `extra`; in that case nothing is evicted, because a request that must be + /// transient should not discard useful cached candidates. Face names are not pinned blobs: + /// egui may keep an installed copy, but the provider's own byte cache stays bounded. + fn make_room(&mut self, extra: usize) -> bool { + if extra > self.max_bytes { + return false; + } + while self.retained_bytes.saturating_add(extra) > self.max_bytes { + let Some(file) = self.files.first() else { return false }; + let bytes = file.bytes; + self.files.remove(0); + self.retained_bytes = self.retained_bytes.saturating_sub(bytes); + } + true + } + + /// Remember a face name without retaining font bytes. Names are capped; forgetting an old + /// name only means egui may install a face under a new name later. + fn remember_face(&mut self, path: PathBuf, index: u32, name: String) { + if self.faces.len() >= MAX_SYSTEM_FACE_NAMES { + self.faces.remove(0); + } + self.faces.push(SystemFace { path, index, name }); + } +} + +struct SystemFace { + path: PathBuf, + index: u32, + name: String, +} + +impl CraftFontProvider { + fn new(sources: &Sources, scale: f32) -> Self { + Self { + locale: sources.locale, + files: sources.files, + last_resort: sources.last_resort, + pending: sources.pending, + scripts: sources.scripts, + covers: sources.covers, + embedded: sources.embedded, + scale: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(scale.to_bits())), + system: std::sync::Mutex::new(SystemCache::default()), + reader: read_font, + } + } + + fn scale(&self) -> f32 { + f32::from_bits(self.scale.load(std::sync::atomic::Ordering::Relaxed)) + } + + fn set_scale(&self, scale: f32) { + self.scale.store(scale.to_bits(), std::sync::atomic::Ordering::Relaxed); + } + + /// The bytes of `path`, read at most once while its blob is retained and shared even when a + /// later request wants a different face of the same collection. + /// + /// The whole check/read/insert runs under the cache lock, so concurrent layout threads share + /// one read per path and a success can never be shadowed by another thread's stale failure. + /// Missing/unreadable paths and readable non-font bytes are negative-cached separately. + fn system_source(&self, path: &std::path::Path) -> Option { + let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if cache.failed_reads.contains(path) || cache.invalid_fonts.contains(path) { + return None; + } + if let Some(file) = cache.files.iter().find(|file| file.path.as_path() == path) { + return Some(FontData::from_blob(file.data.font.clone(), 0)); + } + let Some(bytes) = (self.reader)(path) else { + cache.failed_reads.insert(path.to_path_buf()); + return None; + }; + cache.reads = cache.reads.saturating_add(1); + if !cjk::font_file_is_readable(&bytes) { + // A readable non-font is an invalid candidate, not a valid face that merely lacks + // this character: remember that separately and never retain its bytes. + cache.invalid_fonts.insert(path.to_path_buf()); + return None; + } + let size = bytes.len(); + let data = FontData::from_owned(bytes); + let source = FontData::from_blob(data.font.clone(), 0); + if cache.make_room(size) { + cache.retained_bytes = cache.retained_bytes.saturating_add(size); + cache.files.push(CachedFile { path: path.to_path_buf(), data, bytes: size }); + } + // If this file alone exceeds the budget, the bytes are still used for this request but + // not retained. egui may keep the installed face; the provider's own cache stays bounded. + Some(source) + } + + /// The (cached) face index whose family name is `family`; `None` is cached as a family miss. + fn checked_face_index(&self, path: &std::path::Path, family: &str, bytes: &[u8]) -> Option { + { + let cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((_, _, index)) = cache.family_indices.iter().find(|(cached, name, _)| cached.as_path() == path && name.as_str() == family) { + return *index; + } + } + let index = cjk::face_index_for_family_checked(bytes, family); + let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !cache.family_indices.iter().any(|(cached, name, _)| cached.as_path() == path && name.as_str() == family) { + cache.family_indices.push((path.to_path_buf(), family.to_owned(), index)); + } + index + } + + /// Register one face of an already-read system file, reusing its name but applying the + /// current UI scale on every return (a cache must never bake the scale in). + /// + /// A face never adds a second charge for its collection's blob. If the blob was not retained + /// (it alone exceeds the budget, or another thread evicted it first), this still returns a + /// complete transient `FontInsert`: egui installs and owns that copy, while the provider's + /// own cache remains within `max_bytes`. + fn system_insert_face(&self, path: PathBuf, index: u32, source: FontData) -> FontInsert { + let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let name = match cache.faces.iter().find(|f| f.path == path && f.index == index) { + Some(face) => face.name.clone(), + None => { + let name = format!("craft-system-{}", cache.next_face_name); + cache.next_face_name = cache.next_face_name.saturating_add(1); + cache.remember_face(path, index, name.clone()); + name + } + }; + let mut data = FontData::from_blob(source.font, index); + apply_font_tweaks(&mut data); + font_insert(name, data, self.scale()) + } + + /// The first system face for `script` (or any last-resort face) whose requested family really + /// covers `c`. + /// + /// The lazy loader reads these after the first frame; the provider needs the same source for + /// the first frame, before a headless layout with `MissingGlyphPolicy::Panic` can finish. + /// A non-empty family is resolved by name first, then checked against that exact face: never + /// use the first face of a collection that happens to cover `c`. + fn system_insert_files(&self, files: Vec, c: char) -> Option { + for file in files { + let Some(source) = self.system_source(&file.path) else { continue }; + let index = if file.family.is_empty() { + 0 + } else { + let Some(index) = self.checked_face_index(&file.path, &file.family, source.bytes()) else { continue }; + index + }; + // A readable collection can still hold a malformed selected face whose `cmap` and + // `name` work; do not hand that index to epaint, which panics when it installs a + // configured face it cannot parse. + if !cjk::font_face_is_readable(source.bytes(), index) { + continue; + } + if !scripts::face_covers(source.bytes(), index, c) { + continue; + } + return Some(self.system_insert_face(file.path, index, source)); + } + None + } + + /// The first non-CJK candidate path that maps `c`; these files have no requested family, so + /// the same character-map rule as the lazy loader applies. + fn system_insert_paths(&self, files: Vec, c: char) -> Option { + for path in files { + let Some(source) = self.system_source(&path) else { continue }; + let Some(index) = (self.covers)(source.bytes(), c) else { continue }; + if !cjk::font_face_is_readable(source.bytes(), index) { + continue; + } + return Some(self.system_insert_face(path, index, source)); + } + None + } +} + +impl FontProvider for CraftFontProvider { + fn font_for(&self, request: &FallbackRequest<'_>) -> Option { + let c = request.cluster.chars().next()?; + let locale = (self.locale)(); + let order = cjk::script_order(locale.as_deref()); + // The migration baseline appended every craft face to the family stack in manifest + // order, so a non-CJK/unknown effective locale drew shared Han/kana with the first + // manifest face that covered the character (Shippori Mincho Regular). An explicit + // ja/ko/zh preference is a new choice and keeps the UI-first order for its script. + // `locale` already resolves an English UI on a CJK OS to that OS locale, so this + // baseline does not apply there. + let manifest_baseline = cjk::locale_script(locale.as_deref()).is_none(); + let craft = |iso: &'static str| { + if manifest_baseline { craft_face_manifest(self.embedded, iso, c) } else { craft_face_for(self.embedded, iso, c) } + }; + if let Some(kind) = cjk::classify(c) { + // Han follows the locale's script. For a non-CJK/unknown effective locale, try the + // manifest's Japanese faces first (exactly as the baseline stack did) before the + // SC-first system order. + if kind == cjk::CjkChar::Han + && manifest_baseline + && let Some((index, face)) = craft_face_manifest(self.embedded, "Jpan", c) + { + return Some(craft_insert(index, face, self.scale())); + } + // The same order as `CjkFallback::next_font`: the character's preferred script first, + // then the locale order; craft faces and system files per script. A Traditional + // Chinese locale therefore checks its system Hant font before any Simplified craft + // face, and only falls through when the system has no Hant face either. + // + // While fontconfig is still looking for the preferred script's face, do not cache a + // lower-priority face (SC for a Hant character): egui keeps that wrong choice for the + // installed font chain. Returning `None` lets the next layout retry after the scan. + let mut scripts = vec![kind.preferred(&order)]; + scripts.extend(order); + let mut tried: Vec = Vec::new(); + for script in scripts { + if tried.contains(&script) { + continue; + } + tried.push(script); + if let Some((index, face)) = craft(cjk_iso(script)) { + return Some(craft_insert(index, face, self.scale())); + } + if let Some(insert) = self.system_insert_files((self.files)(script), c) { + return Some(insert); + } + if (self.pending)() { + return None; + } + } + return self.system_insert_files((self.last_resort)(), c); + } + let Some(script) = scripts::classify(c) else { + return craft("Zsym").map(|(index, face)| craft_insert(index, face, self.scale())); + }; + if let Some((index, face)) = craft(script_iso(script)) { + return Some(craft_insert(index, face, self.scale())); + } + if let Some(insert) = self.system_insert_paths((self.scripts)(script), c) { + return Some(insert); + } + // The lazy loader's last-resort list is broad (Arial Unicode, Droid Sans Fallback): it is + // the same final source for non-CJK scripts when no script-specific file is installed. + self.system_insert_files((self.last_resort)(), c) + } +} + +/// Whether `face` really maps `c` in the face [`craft_insert`] would install. +/// +/// `craft_insert` builds `FontData::from_static(face.bytes)`, whose default face index is 0, so +/// testing any face of a collection would select a face whose glyphs egui never uses. Test face +/// 0 here, exactly like the lazy loader's `load_embedded_faces`. +fn craft_face_installs_coverage(face: &CraftFont, c: char) -> bool { + !face.bytes.is_empty() && cjk::font_face_is_readable(face.bytes, 0) && scripts::face_covers(face.bytes, 0, c) +} + +/// The best injected craft face declaring `iso` that really covers `c` in the face +/// [`craft_insert`] installs. +fn craft_face_for(embedded: fn(&'static str) -> Vec<&'static CraftFont>, iso: &'static str, c: char) -> Option<(usize, &'static CraftFont)> { + embedded(iso).into_iter().find_map(|face| { + let index = craft_index(face)?; + craft_face_installs_coverage(face, c).then_some((index, face)) + }) +} + +/// The injected craft face the migration baseline would have used first: the earliest manifest +/// face declaring `iso` that really covers `c` in the face [`craft_insert`] installs. (The +/// baseline appended the whole manifest in order; for Japanese that is Shippori Mincho Regular, +/// not the UI-first BIZ UDPGothic.) +fn craft_face_manifest(embedded: fn(&'static str) -> Vec<&'static CraftFont>, iso: &'static str, c: char) -> Option<(usize, &'static CraftFont)> { + let mut faces = embedded(iso); + // Stable: faces outside the global table (test doubles) keep their injected order. + faces.sort_by_key(|face| craft_index(face).unwrap_or(usize::MAX)); + faces.into_iter().find_map(|face| { + let index = craft_index(face)?; + craft_face_installs_coverage(face, c).then_some((index, face)) + }) +} + +fn cjk_iso(script: CjkScript) -> &'static str { + match script { + CjkScript::Japanese => "Jpan", + CjkScript::SimplifiedChinese => "Hans", + CjkScript::TraditionalChinese => "Hant", + CjkScript::Korean => "Kore", + } +} + +fn script_iso(script: Script) -> &'static str { + use Script::*; + match script { + Thai => "Thai", + Lao => "Laoo", + Khmer => "Khmr", + Myanmar => "Mymr", + Tibetan => "Tibt", + Arabic => "Arab", + Hebrew => "Hebr", + Armenian => "Armn", + Georgian => "Geor", + Ethiopic => "Ethi", + Devanagari => "Deva", + Bengali => "Beng", + Gurmukhi => "Guru", + Gujarati => "Gujr", + Oriya => "Orya", + Tamil => "Taml", + Telugu => "Telu", + Kannada => "Knda", + Malayalam => "Mlym", + Sinhala => "Sinh", + } +} + +/// The manifest index of a craft face (the name suffix of its `FontInsert`). +fn craft_index(face: &CraftFont) -> Option { + craft_fonts::CRAFT_FONTS.iter().position(|candidate| std::ptr::eq(candidate, face)) +} + +/// Craft faces declaring `iso`, Regular first, with the Japanese UI face ahead of the other +/// Japanese faces (the explicit-locale choice; a non-CJK/unknown effective locale keeps the +/// manifest order). +fn craft_faces(iso: &str) -> Vec<(usize, &'static CraftFont)> { + let mut faces: Vec<(usize, &'static CraftFont)> = + craft_fonts::CRAFT_FONTS.iter().enumerate().filter(|(_, f)| !f.bytes.is_empty() && f.scripts.contains(&iso)).collect(); + faces.sort_by_key(|(_, f)| (f.family != craft_fonts::UI_JAPANESE_FAMILY, f.style != "Regular")); + faces +} + +/// Baseline and variable-weight tweaks shared by craft and system fallbacks. +fn apply_font_tweaks(data: &mut FontData) { + let offset = vertical_metrics(data.bytes(), data.index) + .zip(vertical_metrics(photocraft_text::fonts::INTER_REGULAR.as_slice(), 0)) + .map(|(face, primary)| baseline_offset(face, primary)); + let weight = regular_weight(data.bytes(), data.index); + if let Some(offset) = offset { + data.tweak.y_offset_factor = offset; + } + if let Some(weight) = weight { + data.tweak.coords = egui::epaint::text::VariationCoords::new([(b"wght", weight)]); + } +} + +fn font_insert(name: String, mut data: FontData, scale: f32) -> FontInsert { + data.tweak.scale = scale; + let families: Vec = + [FontFamily::Proportional, FontFamily::Monospace].into_iter().map(|family| InsertFontFamily { family, priority: FontPriority::Lowest }).collect(); + FontInsert::new(&name, data, families) +} + +/// One craft face as an egui font, with the same baseline/weight tweaks as a lazy fallback and the +/// current UI font-size multiplier. Added to both UI families: a discovered face is appended to +/// each family that asks for it, and a headless frame may use either. `FontData::from_static` +/// leaves the face index at its default 0; the coverage helpers above test that same face. +fn craft_insert(index: usize, face: &'static CraftFont, scale: f32) -> FontInsert { + let mut data = FontData::from_static(face.bytes); + apply_font_tweaks(&mut data); + font_insert(format!("craft-font-{index}"), data, scale) +} + +fn craft_provider_id() -> egui::Id { + egui::Id::unique("photocraft-craft-font-provider") +} + +/// The effective locale for CJK choice: an explicitly translated UI language +/// (ja/ko/zh-Hans/zh-Hant) wins; otherwise the OS locale, when known. +/// +/// An English UI on a Japanese, Korean or Chinese OS therefore uses that OS script, not the +/// migration baseline's manifest-first face. The baseline applies only when the effective locale +/// is non-CJK or unknown. +fn effective_locale(ui_code: &str, os_locale: Option<&str>) -> Option { + match ui_code { + "ja" | "ko" | "zh-hans" | "zh-hant" => Some(ui_code.to_owned()), + _ => os_locale.map(str::to_owned), + } +} + impl Sources { #[cfg(not(target_arch = "wasm32"))] pub fn system() -> Self { cjk::start_fontconfig_cjk_scan(); Self { - locale: || match crate::i18n::current().code() { - code @ ("ja" | "ko" | "zh-hans" | "zh-hant") => Some(code.to_string()), - _ => cjk::ui_locale().map(str::to_string), - }, + locale: || effective_locale(crate::i18n::current().code(), cjk::ui_locale()), files: cjk::font_files, last_resort: cjk::last_resort_files, + pending: cjk::fontconfig_cjk_scan_pending, scripts: scripts::system_candidates, covers: scripts::covering_face, - embedded: craft_embedded, + embedded: craft_embedded_iso, eager_craft_fonts: true, } } @@ -88,9 +589,10 @@ impl Sources { locale: || None, files: |_| Vec::new(), last_resort: Vec::new, + pending: || false, scripts: |_| Vec::new(), covers: scripts::covering_face, - embedded: craft_embedded, + embedded: craft_embedded_iso, // The web build embeds no craft fonts; keep its font stack as it was. eager_craft_fonts: false, } @@ -98,15 +600,20 @@ impl Sources { } /// Headless test frame pumps do not wait for `request_repaint_after`, so let the optional -/// Fontconfig worker finish before asserting on installed system fonts. -#[cfg(all(test, target_os = "linux"))] -pub(crate) fn wait_for_fontconfig_cjk_scan() { +/// Fontconfig worker finish before asserting on installed system fonts. `pub` (rather than +/// `pub(crate)`) so strict-policy integration tests can use the same wait as the unit tests. +/// +/// Returns whether the scan finished; it never panics in production. Test callers assert the +/// result (and choose their own message). +#[cfg(target_os = "linux")] +#[doc(hidden)] +pub fn wait_for_fontconfig_cjk_scan() -> bool { cjk::start_fontconfig_cjk_scan(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); while cjk::fontconfig_cjk_scan_pending() && std::time::Instant::now() < deadline { std::thread::sleep(std::time::Duration::from_millis(10)); } - assert!(!cjk::fontconfig_cjk_scan_pending(), "Fontconfig CJK lookup did not finish within 10 seconds"); + !cjk::fontconfig_cjk_scan_pending() } /// The lazy loader's state: which scripts were tried and which files were read. @@ -148,23 +655,38 @@ impl CjkFallback { self.tried.len() >= 4 && self.last_resort_tried } - /// The next font to register for a character of kind `kind` that no current font covers: - /// the first readable file of the first untried script (the character's preferred script, - /// then the locale order), then the last-resort fonts. `None` when nothing is left. - pub fn next_font(&mut self, kind: CjkChar) -> Option<(String, FontData)> { + /// The next font to register for `c` (kind `kind`) that no current font covers: the first + /// readable file of the first untried script (the character's preferred script, then the + /// locale order), then the last-resort fonts. For a non-CJK/unknown effective locale the + /// craft faces for shared Han and kana follow the manifest's own order (Shippori Mincho + /// before BIZ UDPGothic), exactly like the migration baseline's family stack; Hangul keeps + /// the Korean face. `None` when nothing is left or while the preferred script's Fontconfig + /// lookup is still pending. + pub fn next_font(&mut self, c: char, kind: CjkChar) -> Option<(String, FontData)> { + // The craft manifest lists Shippori Mincho first. A non-CJK effective locale keeps that + // baseline choice for Han and kana; an explicit zh-Hans/zh-Hant/ja/ko preference keeps the + // script's UI-first order. + let manifest_baseline = cjk::locale_script((self.sources.locale)().as_deref()).is_none(); + if kind == CjkChar::Han + && manifest_baseline + && let Some(f) = self.load_embedded_manifest(CjkScript::Japanese, c) + { + return Some(f); + } let order = self.order(); let scripts: Vec = std::iter::once(kind.preferred(&order)).chain(order).collect(); for s in scripts { if self.tried.contains(&s) { continue; } - if let Some(f) = self.load_embedded(s) { + let embedded = if manifest_baseline { self.load_embedded_manifest(s, c) } else { self.load_embedded(s, c) }; + if let Some(f) = embedded { self.tried.push(s); return Some(f); } - let fontconfig_pending = cjk::fontconfig_cjk_scan_pending(); + let fontconfig_pending = (self.sources.pending)(); let files = (self.sources.files)(s); - if let Some(f) = self.load_first(&files) { + if let Some(f) = self.load_first(&files, c) { self.tried.push(s); return Some(f); } @@ -176,7 +698,7 @@ impl CjkFallback { if !self.last_resort_tried { self.last_resort_tried = true; let files = (self.sources.last_resort)(); - return self.load_first(&files); + return self.load_first(&files, c); } None } @@ -203,7 +725,13 @@ impl CjkFallback { } let Some(bytes) = read_font(&path) else { continue }; reads += 1; + if !cjk::font_file_is_readable(&bytes) { + continue; + } let Some(index) = (self.sources.covers)(&bytes, c) else { continue }; + if !cjk::font_face_is_readable(&bytes, index) { + 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()); @@ -216,9 +744,23 @@ impl CjkFallback { None } - /// 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())?; + /// The first embedded (craft-fonts) face for `s` in the UI-first order (explicit locale). + fn load_embedded(&mut self, s: CjkScript, c: char) -> Option<(String, FontData)> { + let faces = (self.sources.embedded)(cjk_iso(s)); + self.load_embedded_faces(faces, c) + } + + /// The first embedded face for `s` in the migration baseline's manifest order + /// (non-CJK/unknown effective locale): Shippori Mincho Regular before BIZ UDPGothic. + fn load_embedded_manifest(&mut self, s: CjkScript, c: char) -> Option<(String, FontData)> { + let mut faces = (self.sources.embedded)(cjk_iso(s)); + faces.sort_by_key(|face| craft_index(face).unwrap_or(usize::MAX)); + self.load_embedded_faces(faces, c) + } + + /// The first of `faces` that really covers `c`, registered from its static bytes. + fn load_embedded_faces(&mut self, faces: Vec<&'static CraftFont>, c: char) -> Option<(String, FontData)> { + let f = faces.into_iter().find(|f| !f.bytes.is_empty() && cjk::font_face_is_readable(f.bytes, 0) && scripts::face_covers(f.bytes, 0, c))?; let path = PathBuf::from(format!("craft-fonts/{} {}", f.family, f.style)); if self.loaded.contains(&path) { return None; @@ -230,13 +772,35 @@ impl CjkFallback { Some((name, FontData::from_static(f.bytes))) } - fn load_first(&mut self, files: &[FontFile]) -> Option<(String, FontData)> { + /// The first file whose requested collection face (or face 0 for an empty family) really + /// covers `c`. A family miss skips the file rather than using whichever face happens to cover + /// the character. + fn load_first(&mut self, files: &[FontFile], c: char) -> Option<(String, FontData)> { for f in files { if self.loaded.contains(&f.path) { continue; } let Some(bytes) = read_font(&f.path) else { continue }; - let index = cjk::face_index_for_family(&bytes, &f.family); + // Register only what the text engine can actually parse. A readable collection may + // still have a selected face whose `cmap` is valid while another table points outside + // the file; `font_face_is_readable` below rejects such a face before registration. + if !cjk::font_file_is_readable(&bytes) { + continue; + } + let index = if f.family.is_empty() { + 0 + } else { + let Some(index) = cjk::face_index_for_family_checked(&bytes, &f.family) else { continue }; + index + }; + // `face_covers` only reads `cmap`; validate the selected face's whole table directory + // before `ctx.add_font` may install (and panic on) a face another table makes unreadable. + if !cjk::font_face_is_readable(&bytes, index) { + continue; + } + if !scripts::face_covers(&bytes, index, c) { + continue; + } self.loaded.push(f.path.clone()); let name = format!("{FONT_PREFIX}-{}", self.registered.len()); log::info!("UI font fallback: registered {} (face {index}) as {name}", f.path.display()); @@ -393,13 +957,13 @@ impl egui::Plugin for CjkFontPlugin { } let Some(c) = missing_char(ctx, &output.shapes, &self.0) else { return }; let font = match cjk::classify(c) { - Some(kind) => self.0.next_font(kind), + Some(kind) => self.0.next_font(c, 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 cjk::classify(c).is_some() && cjk::fontconfig_cjk_scan_pending() { + } else if cjk::classify(c).is_some() && (self.0.sources.pending)() { ctx.request_repaint_after(std::time::Duration::from_millis(50)); } else if !self.0.exhausted() || !self.0.scripts_exhausted() { // Nothing readable for this script; try the next one on the next frame. @@ -427,11 +991,32 @@ pub fn install_with(ctx: &egui::Context, sources: Sources) { { ctx.add_plugin(CjkFontPlugin(fallback)); } + // The provider resolves a craft face for each missing character in the first frame, before the + // lazy loader's next-pass system fallback. Without it a headless frame panics on CJK text. + if sources.eager_craft_fonts && !craft_fonts::CRAFT_FONTS.is_empty() { + let provider = std::sync::Arc::new(CraftFontProvider::new(&sources, crate::theme::ui_font_scale(ctx))); + let as_provider: std::sync::Arc = provider.clone(); + ctx.data_mut(|d| d.insert_temp(craft_provider_id(), provider)); + ctx.set_font_providers(vec![as_provider]); + } +} + +/// Keep provider-discovered craft faces in step with Interface > UI Font Size. The size plugin +/// calls this after `ctx.set_fonts` with the rescaled stack. A face discovered while the old stack +/// was still active stays at the old scale for the rest of that pass; recreating `Fonts` for the +/// next pass drops the discovered faces (they are not part of `FontDefinitions`) and the provider +/// rediscovers them at its new scale. +pub(crate) fn set_craft_font_scale(ctx: &egui::Context, scale: f32) { + let Some(provider) = ctx.data(|d| d.get_temp::>(craft_provider_id())) else { return }; + provider.set_scale(scale); + let as_provider: std::sync::Arc = provider; + ctx.set_font_providers(vec![as_provider]); } #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; + use egui::FontProvider; use std::sync::Mutex; #[test] @@ -459,6 +1044,89 @@ mod tests { } } + /// A face discovered by [`CraftFontProvider`] during a pass that also changes Interface > UI + /// Font Size must use the scale of the definitions active in that pass. The size plugin moves + /// the provider to the new scale only after `ctx.set_fonts` queued the rescaled definitions; + /// updating the provider in `set_ui_font_size` would put the new scale on a face laid out + /// with the old stack. + #[test] + fn discovered_faces_use_the_scale_of_the_definitions_they_were_laid_out_with() { + use photocraft_engine::prefs::UiFontSize; + fn thai_reader(_: &std::path::Path) -> Option> { + Some(synthetic_font(&[(0x0E01, 0x0E5B)])) + } + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, craft_only(|| None)); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + let mut provider = CraftFontProvider::new( + &Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: |script| if script == Script::Thai { vec![PathBuf::from("synthetic-thai.ttf")] } else { Vec::new() }, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }, + 1.0, + ); + provider.reader = thai_reader; + let provider = std::sync::Arc::new(provider); + ctx.data_mut(|d| d.insert_temp(craft_provider_id(), provider.clone())); + let as_provider: std::sync::Arc = provider.clone(); + ctx.set_font_providers(vec![as_provider]); + + // The scale of the configured Inter face (part of `FontDefinitions`) and of the face the + // provider discovered for Thai. + let inter_scale = |ctx: &egui::Context| -> Option { ctx.fonts(|f| f.definitions().font_data.get("Inter").map(|data| data.tweak.scale)) }; + let thai_scale = |ctx: &egui::Context| -> Option { + ctx.fonts(|f| f.discovered_fonts().iter().find(|insert| insert.name.starts_with("craft-system-")).map(|insert| insert.data.tweak.scale)) + }; + // A frame that checks the state during the change pass, before laying out Thai (the + // character that makes the provider discover a face). + let frame = |check: &dyn Fn(&egui::Context)| { + ctx.run_ui(Default::default(), |ui| { + check(&ctx); + ui.label("ก"); + }) + .textures_delta + .clear(); + }; + // Small (the install default) is active. Walk Small -> Large -> Small, repeat Large + // (the same size must leave both the definitions and the provider alone, not accumulate) + // and back to Small. + assert_eq!(provider.scale(), 1.0); + for (size, want, same_size) in [ + (UiFontSize::Large, 16.0 / 12.0, false), + (UiFontSize::Small, 1.0, false), + (UiFontSize::Large, 16.0 / 12.0, false), + (UiFontSize::Large, 16.0 / 12.0, true), + (UiFontSize::Small, 1.0, false), + ] { + let old = provider.scale(); + let inter_before = inter_scale(&ctx); + crate::theme::set_ui_font_size(&ctx, size); + assert_eq!(provider.scale(), old, "the provider follows the definitions still active in this pass"); + frame(&|ctx: &egui::Context| { + assert_eq!(inter_scale(ctx), inter_before, "the configured Inter keeps its old scale during the change pass"); + assert_eq!(provider.scale(), old, "the provider does not move before the pass ends"); + }); + assert_eq!(provider.scale(), want, "the provider follows the rescaled definitions"); + if same_size { + assert_eq!(inter_scale(&ctx), inter_before, "a same-size request leaves the stack alone"); + } + assert_eq!(thai_scale(&ctx), Some(old), "the pass laid the discovered face out with the old definitions"); + // The queued definitions with the new scale are active now, and a new pass drops the + // discovered face and rediscovers it at the provider's new scale. + frame(&|ctx: &egui::Context| { + assert_eq!(inter_scale(ctx), Some(want), "the rescaled stack is active in the next pass"); + assert_eq!(provider.scale(), want); + }); + assert_eq!(thai_scale(&ctx), Some(want), "the next pass rediscovers the face at the provider's scale"); + } + } + /// A font holding only an `fvar` table with the given axes (tag, min, default, max), as a /// single face or as face 1 of a two-face collection. fn fvar_font(axes: &[(&[u8; 4], f32, f32, f32)], collection: bool) -> Vec { @@ -521,6 +1189,16 @@ mod tests { assert_eq!(fonts.font_data.get("test-static").map(|d| d.tweak.coords.clone()), Some(Default::default())); } + /// A corrupt or non-font blob has no `hhea`, `head` or `fvar` table: the fallback tweaks + /// must leave it untouched rather than deriving a baseline or weight from garbage. + #[test] + fn font_tweaks_ignore_bytes_without_metrics_or_weight_axes() { + let mut data = FontData::from_static(b""); + apply_font_tweaks(&mut data); + assert_eq!(data.tweak.y_offset_factor, 0.0); + assert_eq!(data.tweak.coords, Default::default()); + } + static DIR: Mutex> = Mutex::new(None); #[test] @@ -555,6 +1233,15 @@ mod tests { 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(); + std::fs::write(dir.join("korean.ttf"), synthetic_font(&[(0xCE74, 0xCE74)])).unwrap(); + std::fs::write(dir.join("tamil.ttf"), synthetic_font(&[(0x0B80, 0x0BFF)])).unwrap(); + std::fs::write(dir.join("ethiopic.ttf"), synthetic_font(&[(0x1200, 0x137F)])).unwrap(); + std::fs::write(dir.join("hant.ttf"), synthetic_font(&[(0x9F8D, 0x9F8D)])).unwrap(); + std::fs::write( + dir.join("families.ttc"), + two_face_ttc(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf")), + ) + .unwrap(); dir }) .clone() @@ -564,16 +1251,92 @@ mod tests { FontFile { path: fake_dir().join(name), family: String::new() } } + #[test] + fn font_reads_skip_missing_empty_oversized_and_non_file_candidates() { + let dir = fake_dir(); + assert!(read_font(&dir.join("missing-read-test.ttf")).is_none(), "a missing path is skipped"); + assert!(read_font(&dir).is_none(), "a directory is not a font file"); + assert!(read_font(&dir.join("empty.ttf")).is_none(), "an empty file is skipped"); + + let oversized = dir.join("oversized-read-test.ttf"); + let file = std::fs::File::create(&oversized).expect("create a sparse oversized test file"); + file.set_len(MAX_FONT_BYTES + 1).expect("set the sparse file size"); + drop(file); + assert!(read_font(&oversized).is_none(), "an oversized file is not read"); + std::fs::remove_file(&oversized).expect("remove the sparse test file"); + + let valid = dir.join("font.ttf"); + assert_eq!(read_font(&valid).expect("the valid font is read").as_slice(), std::fs::read(&valid).expect("test font bytes").as_slice()); + } + + fn provider_corrupt_thai_candidates(script: Script) -> Vec { + if script == Script::Thai { + vec![ + fake_dir().join("provider-missing-thai.ttf"), + fake_dir().join("provider-corrupt-thai.ttf"), + fake_dir().join("provider-corrupt-selected-thai.ttc"), + fake_dir().join("font.ttf"), + fake_dir().join("thai.ttf"), + ] + } else { + Vec::new() + } + } + + fn provider_missing_thai_candidate(script: Script) -> Vec { + if script == Script::Thai { vec![fake_dir().join("provider-only-missing-thai.ttf")] } else { Vec::new() } + } + + /// The provider's non-CJK script route must reject a structurally invalid file, a readable + /// collection whose selected covering face is unreadable, and a missing file, then use the + /// next real candidate. The rejected and missing paths stay negative-cached. + #[test] + fn provider_skips_missing_and_corrupt_script_candidates_before_registering() { + let malformed = fake_dir().join("provider-corrupt-thai.ttf"); + let collection = fake_dir().join("provider-corrupt-selected-thai.ttc"); + std::fs::write(&malformed, font_with_out_of_bounds_table()).expect("write the malformed test font"); + std::fs::write(&collection, two_face_ttc(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), &font_with_out_of_bounds_table())) + .expect("write the malformed selected-face collection"); + + let sources = Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: provider_corrupt_thai_candidates, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + let insert = provided_insert(&provider, 'ก').expect("the valid Thai candidate is reached"); + assert_eq!(insert.data.index, 0); + assert_eq!(insert.data.bytes(), std::fs::read(fake_dir().join("thai.ttf")).expect("Thai test font").as_slice()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.failed_reads.contains(&fake_dir().join("provider-missing-thai.ttf")), "the missing file is remembered"); + assert!(cache.invalid_fonts.contains(&malformed), "the readable non-font is remembered as invalid"); + assert!(cache.files.iter().any(|file| file.path == collection), "the readable collection is retained for its other faces"); + drop(cache); + + let missing_only = Sources { scripts: provider_missing_thai_candidate, ..sources }; + let provider = CraftFontProvider::new(&missing_only, 1.0); + assert!(provided(&provider, 'ก').is_none(), "no readable script candidate leaves the character missing"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.failed_reads.len(), 1); + assert_eq!(cache.reads, 0); + } + fn fake_sources(locale: fn() -> Option) -> Sources { Sources { locale, - // Korean has a readable "font", Japanese only broken files, Chinese none. + // Korean has a readable Hangul font, Japanese only broken files, Chinese none. files: |s| match s { - CjkScript::Korean => vec![fake("missing.ttc"), fake("empty.ttf"), fake("font.ttf")], + CjkScript::Korean => vec![fake("missing.ttc"), fake("empty.ttf"), fake("korean.ttf")], CjkScript::Japanese => vec![fake("empty.ttf")], _ => vec![], }, last_resort: || vec![fake("font.ttf")], + pending: || false, scripts: |_| Vec::new(), covers: scripts::covering_face, embedded: no_embedded, @@ -586,17 +1349,19 @@ mod tests { let mut fb = CjkFallback::new(fake_sources(|| Some("en_US".into()))); assert!(!fb.exhausted()); // Hangul: Korean first; missing and empty files are skipped. - let (name, data) = fb.next_font(CjkChar::Hangul).expect("korean font"); + let (name, data) = fb.next_font('카', CjkChar::Hangul).expect("korean font"); assert!(name.starts_with(FONT_PREFIX)); assert_eq!(data.index, 0); assert_eq!(fb.tried, vec![CjkScript::Korean]); - // Han on an English locale: SC, TC, JA have nothing readable, and the last-resort file was - // already loaded, so nothing new; everything is now tried. - assert!(fb.next_font(CjkChar::Han).is_none()); + // Han on an English locale: system fallback keeps the locale order (SC first); the + // Japanese-first craft-manifest baseline is a separate provider/lazy-craft path. + // SC, TC, JA have nothing readable here, and the last-resort file was already loaded, + // so nothing new; everything is now tried. + assert!(fb.next_font('日', CjkChar::Han).is_none()); assert!(fb.exhausted()); assert_eq!(fb.tried, vec![CjkScript::Korean, CjkScript::SimplifiedChinese, CjkScript::TraditionalChinese, CjkScript::Japanese]); assert_eq!(fb.registered.len(), 1, "a file is read at most once"); - assert!(fb.next_font(CjkChar::Kana).is_none()); + assert!(fb.next_font('あ', CjkChar::Kana).is_none()); } #[test] @@ -611,13 +1376,14 @@ mod tests { locale: || None, files: |_| vec![], last_resort: Vec::new, + pending: || false, scripts: |_| Vec::new(), covers: scripts::covering_face, embedded: no_embedded, eager_craft_fonts: false, }); fb.order = Some(cjk::script_order(Some(loc))); - assert!(fb.next_font(CjkChar::Han).is_none()); + assert!(fb.next_font('日', CjkChar::Han).is_none()); assert_eq!(fb.tried[0], first, "{loc}"); } } @@ -633,6 +1399,52 @@ mod tests { ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(12.0), &text.replace(' ', ""))) } + /// A two-face TrueType collection built at runtime from the repository's OFL-licensed + /// Inter and JetBrains Mono files. Each face directory is rewritten with offsets relative to + /// the collection, so no font fixture is committed. + fn two_face_ttc(first: &[u8], second: &[u8]) -> Vec { + let font_count = 2usize; + let tables = |font: &[u8]| u16::from_be_bytes([font[4], font[5]]) as usize; + let dir_lengths = [12 + 16 * tables(first), 12 + 16 * tables(second)]; + let mut dir_offsets = Vec::with_capacity(font_count); + let mut cursor = 12 + 4 * font_count; + for length in dir_lengths { + dir_offsets.push(cursor); + cursor += length; + } + let data_start = cursor.next_multiple_of(4); + let mut bases = Vec::with_capacity(font_count); + let mut total = data_start; + for font in [first, second] { + bases.push(total); + total += font.len().next_multiple_of(4); + } + let mut out = vec![0u8; total]; + out[..4].copy_from_slice(b"ttcf"); + out[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes()); + out[8..12].copy_from_slice(&u32::try_from(font_count).expect("two faces").to_be_bytes()); + for (i, offset) in dir_offsets.iter().enumerate() { + let at = 12 + i * 4; + out[at..at + 4].copy_from_slice(&u32::try_from(*offset).expect("collection fits").to_be_bytes()); + } + for (i, font) in [first, second].into_iter().enumerate() { + let dir = dir_offsets[i]; + let base = bases[i]; + out[dir..dir + 12].copy_from_slice(&font[..12]); + for record in 0..tables(font) { + let src = 12 + 16 * record; + let dst = dir + 12 + 16 * record; + out[dst..dst + 8].copy_from_slice(&font[src..src + 8]); + let table_offset = u32::from_be_bytes(font[src + 8..src + 12].try_into().expect("four bytes")); + let collection_offset = u32::try_from(base).expect("collection fits") + table_offset; + out[dst + 8..dst + 12].copy_from_slice(&collection_offset.to_be_bytes()); + out[dst + 12..dst + 16].copy_from_slice(&font[src + 12..src + 16]); + } + out[base..base + font.len()].copy_from_slice(font); + } + out + } + /// 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 { @@ -725,6 +1537,7 @@ mod tests { locale: || Some("en".into()), files: |_| vec![], last_resort: Vec::new, + pending: || false, scripts: |s| { let f = |name: &str| fake_dir().join(name); match s { @@ -790,7 +1603,7 @@ mod tests { 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()); + assert!(fallback.next_font('카', CjkChar::Hangul).is_some()); } #[test] @@ -856,7 +1669,7 @@ mod tests { let _ = render(&ctx, "Layer 1 – café"); let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count()); assert_eq!(n, 0, "Latin text loads nothing"); - // Hangul isn't in the stand-in font, but the Korean candidate must have been registered. + // The Korean candidate covers the first missing Hangul character and is registered. let _ = render(&ctx, "카드 배경"); let fonts = ctx.fonts(|f| f.definitions().clone()); let name = format!("{FONT_PREFIX}-0"); @@ -866,34 +1679,153 @@ mod tests { } } - /// No system fonts at all: craft-fonts alone draws Japanese. + /// Craft fonts available through the first-frame provider, as the desktop shell does. + fn eager_sources(locale: fn() -> Option) -> Sources { + Sources { + locale, + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: true, + } + } + + /// No system fonts at all: craft-fonts alone draws CJK through the lazy loader. fn craft_only(locale: fn() -> Option) -> Sources { Sources { locale, files: |_| vec![], last_resort: Vec::new, + pending: || false, scripts: |_| Vec::new(), covers: scripts::covering_face, - embedded: craft_embedded, + embedded: craft_embedded_iso, eager_craft_fonts: false, } } + /// The migration baseline's first craft face covering `c`: the first non-empty face in + /// manifest order (what the old family stack appended first), not the UI-first sort. + fn baseline_face(c: char) -> Option<&'static CraftFont> { + craft_fonts::CRAFT_FONTS.iter().find(|f| !f.bytes.is_empty() && scripts::face_covers(f.bytes, 0, c)) + } + + /// A test-only craft face backed by a collection built with [`two_face_ttc`]: face 0 maps + /// Thai only, face 1 maps 龍. `craft_insert` would install face 0, so the craft coverage + /// helpers must not accept it for 龍 even though a later face covers the character. + fn ttc_craft_face() -> &'static CraftFont { + static FACE: std::sync::OnceLock = std::sync::OnceLock::new(); + FACE.get_or_init(|| { + let bytes: &'static [u8] = Box::leak(two_face_ttc(&synthetic_font(&[(0x0E01, 0x0E5B)]), &synthetic_font(&[(0x9F8D, 0x9F8D)])).into_boxed_slice()); + CraftFont { family: "Synthetic Collection", style: "Regular", scripts: &["Hans"], bytes } + }) + } + + /// The craft helpers must test face 0, the face `FontData::from_static` installs. The old + /// any-face coverage check returned the face for a character only a later collection face + /// maps, which then drew tofu in the installed face 0. #[test] - fn craft_fonts_render_japanese_without_system_fonts() { + fn craft_face_coverage_matches_the_face_craft_insert_installs() { + let face = ttc_craft_face(); + // Precondition: an any-face check really accepts 龍 (face 1), so this regression would + // fail if the helpers went back to `scripts::covering_face`. + assert_eq!(scripts::covering_face(face.bytes, '龍'), Some(1), "face 1 maps 龍"); + assert!(!scripts::face_covers(face.bytes, 0, '龍'), "the installed face 0 does not map 龍"); + assert!(!craft_face_installs_coverage(face, '龍'), "face 0 lacks the glyph; craft_insert installs face 0"); + assert!(craft_face_installs_coverage(face, 'ก'), "face 0 maps Thai"); + } + + static EMPTY_CRAFT_FACE: CraftFont = CraftFont { family: "Empty", style: "Regular", scripts: &["Zsym"], bytes: &[] }; + + fn only_empty_craft_face(_: &'static str) -> Vec<&'static CraftFont> { + vec![&EMPTY_CRAFT_FACE] + } + + /// A craft entry without bytes, or a face injected only by a test that is absent from the + /// global manifest, has no installable face index: selection must return `None`, not a face + /// name egui cannot resolve. + #[test] + fn craft_face_selection_ignores_empty_and_unindexed_faces() { + assert!(!craft_face_installs_coverage(&EMPTY_CRAFT_FACE, '☃')); + assert!(craft_face_for(only_empty_craft_face, "Zsym", '☃').is_none()); + assert!(craft_face_manifest(only_empty_craft_face, "Zsym", '☃').is_none()); + } + + /// Every script the lazy fallback can see has a valid ISO 15924 tag, so its injected craft + /// faces and the CJK scripts are selected by the same tags the manifest declares. + #[test] + fn fallback_scripts_map_to_iso_15924_tags() { + assert_eq!(cjk_iso(CjkScript::Japanese), "Jpan"); + assert_eq!(cjk_iso(CjkScript::SimplifiedChinese), "Hans"); + assert_eq!(cjk_iso(CjkScript::TraditionalChinese), "Hant"); + assert_eq!(cjk_iso(CjkScript::Korean), "Kore"); + let expected = [ + (Script::Thai, "Thai"), + (Script::Lao, "Laoo"), + (Script::Khmer, "Khmr"), + (Script::Myanmar, "Mymr"), + (Script::Tibetan, "Tibt"), + (Script::Arabic, "Arab"), + (Script::Hebrew, "Hebr"), + (Script::Armenian, "Armn"), + (Script::Georgian, "Geor"), + (Script::Ethiopic, "Ethi"), + (Script::Devanagari, "Deva"), + (Script::Bengali, "Beng"), + (Script::Gurmukhi, "Guru"), + (Script::Gujarati, "Gujr"), + (Script::Oriya, "Orya"), + (Script::Tamil, "Taml"), + (Script::Telugu, "Telu"), + (Script::Kannada, "Knda"), + (Script::Malayalam, "Mlym"), + (Script::Sinhala, "Sinh"), + ]; + assert_eq!(expected.len(), Script::ALL.len(), "the test lists every fallback script"); + for (script, iso) in expected { + assert_eq!(script_iso(script), iso, "{script:?}"); + } + assert_eq!(craft_embedded(CjkScript::Japanese).len(), craft_embedded_iso("Jpan").len()); + } + + /// No system fonts at all: craft-fonts alone draws CJK, in the locale's script order. + #[test] + fn craft_fonts_render_cjk_without_system_fonts() { let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); return; }; - // An English locale tries Chinese first (none here), then Japanese: the craft font. - for locale in [(|| Some("en_US".into())) as fn() -> Option, || Some("ja_JP".into()), || None] { + let Some(chinese) = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && f.style == "Regular") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + // The craft manifest's Japanese faces come before Noto Sans CJK SC and the baseline + // appended them in manifest order, so a non-CJK/unknown effective locale keeps Shippori + // Mincho (the first covering face). An explicit locale keeps its own UI-first script face. + let Some(baseline) = baseline_face('日') else { + eprintln!("skipping: the craft-fonts manifest has no face covering 日"); + return; + }; + for (locale, expected) in [ + ((|| Some("en_US".into())) as fn() -> Option, baseline), + ((|| Some("ja_JP".into())) as fn() -> Option, ui_font), + ((|| Some("zh-CN".into())) as fn() -> Option, chinese), + ((|| None) as fn() -> Option, baseline), + ] { let ctx = egui::Context::default(); crate::theme::install_fonts_with(&ctx, craft_only(locale)); assert!(render(&ctx, "日本語の文字"), "tofu in 日本語の文字"); assert!(render(&ctx, "レイヤー 1"), "tofu in kana"); let fonts = ctx.fonts(|f| f.definitions().clone()); let name = format!("{FONT_PREFIX}-0"); - assert!(fonts.font_data.get(&name).is_some_and(|d| std::ptr::eq(d.bytes().as_ptr(), ui_font.bytes.as_ptr())), "BIZ UDPGothic Regular first"); + assert!( + fonts.font_data.get(&name).is_some_and(|d| std::ptr::eq(d.bytes().as_ptr(), expected.bytes.as_ptr())), + "{} first by locale: {name}", + expected.family + ); for (fam, stack) in &fonts.families { assert_eq!(stack.last(), Some(&name), "{fam:?}: appended last so Latin keeps Inter"); assert!(stack.first().is_some_and(|f| f != &name), "{fam:?}"); @@ -901,6 +1833,1059 @@ mod tests { } } + fn provided_insert(provider: &CraftFontProvider, c: char) -> Option { + let mut buf = [0u8; 4]; + let cluster = c.encode_utf8(&mut buf); + provider.font_for(&FallbackRequest { cluster, family: &FontFamily::Proportional }) + } + + fn provided(provider: &CraftFontProvider, c: char) -> Option { + provided_insert(provider, c).map(|insert| insert.name) + } + + fn test_sources(locale: fn() -> Option) -> Sources { + Sources { + locale, + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + } + } + + fn test_provider(locale: fn() -> Option) -> CraftFontProvider { + CraftFontProvider::new(&test_sources(locale), 1.0) + } + + #[test] + fn effective_locale_prefers_the_translated_ui_then_the_os_locale() { + assert_eq!(effective_locale("ja", Some("en_US.UTF-8")), Some("ja".into())); + assert_eq!(effective_locale("zh-hant", Some("ja_JP.UTF-8")), Some("zh-hant".into())); + assert_eq!(effective_locale("en", Some("ja_JP.UTF-8")), Some("ja_JP.UTF-8".into()), "English UI on a Japanese OS uses the OS locale"); + assert_eq!(effective_locale("de", Some("ko_KR")), Some("ko_KR".into())); + assert_eq!(effective_locale("en", None), None, "no UI preference and no OS locale stays unknown"); + } + + fn no_script_files(_: Script) -> Vec { + Vec::new() + } + + fn no_files(_: CjkScript) -> Vec { + Vec::new() + } + + /// A stand-in system Traditional Chinese file, so the system-before-SC-craft ordering is + /// testable without depending on the host's fonts. Its content is the SC craft face (which + /// covers the sample Han character). + fn hant_system_file() -> Option { + static FILE: std::sync::OnceLock> = std::sync::OnceLock::new(); + let face = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && !f.bytes.is_empty())?; + FILE.get_or_init(|| { + let path = std::env::temp_dir().join(format!("photocraft-hant-{}.otf", std::process::id())); + std::fs::write(&path, face.bytes).ok().map(|()| path) + }) + .clone() + } + + fn hant_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese { + hant_system_file().map(|path| vec![FontFile { path, family: String::new() }]).unwrap_or_default() + } else { + Vec::new() + } + } + + #[test] + fn craft_font_provider_keeps_the_baseline_face_for_unknown_locales() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, sc)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { + eprintln!("skipping: the craft-fonts manifest has no Korean face"); + return; + }; + let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { + eprintln!("skipping: the craft-fonts manifest has no Arabic face"); + return; + }; + let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { + eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); + return; + }; + let Some(baseline_han) = baseline_face('日') else { + eprintln!("skipping: the craft-fonts manifest has no face covering 日"); + return; + }; + let Some(baseline_kana) = baseline_face('あ') else { + eprintln!("skipping: the craft-fonts manifest has no face covering あ"); + return; + }; + let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); + let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); + let baseline_han_name = format!("craft-font-{baseline_han_index}"); + let baseline_kana_name = format!("craft-font-{baseline_kana_index}"); + let ui_name = format!("craft-font-{ui_index}"); + let sc_name = format!("craft-font-{sc_index}"); + let korean_name = format!("craft-font-{korean_index}"); + let arabic_name = format!("craft-font-{arabic_index}"); + let devanagari_name = format!("craft-font-{devanagari_index}"); + + let ja = test_provider((|| Some("ja_JP".into())) as fn() -> Option); + assert_eq!(provided(&ja, 'あ').as_deref(), Some(ui_name.as_str()), "explicit ja keeps the Japanese UI face"); + assert_eq!(provided(&ja, '日').as_deref(), Some(ui_name.as_str()), "Han follows an explicit Japanese locale"); + + let en = test_provider((|| Some("en_US".into())) as fn() -> Option); + assert_eq!( + provided(&en, 'あ').as_deref(), + Some(baseline_kana_name.as_str()), + "kana in a non-CJK effective locale keeps the manifest's first covering face" + ); + assert_eq!(provided(&en, '한').as_deref(), Some(korean_name.as_str()), "Hangul in a non-CJK effective locale stays on the Korean face"); + assert_eq!( + provided(&en, '日').as_deref(), + Some(baseline_han_name.as_str()), + "Han in a non-CJK effective locale keeps the manifest's first covering face" + ); + let unknown = test_provider((|| None) as fn() -> Option); + assert_eq!(provided(&unknown, '日').as_deref(), Some(baseline_han_name.as_str()), "an unknown effective locale has the same baseline face"); + let english_on_japanese_os = test_provider((|| effective_locale("en", Some("ja_JP"))) as fn() -> Option); + assert_eq!( + provided(&english_on_japanese_os, '日').as_deref(), + Some(ui_name.as_str()), + "English UI on a Japanese OS follows the OS locale; the manifest baseline is not universal for English UI" + ); + assert_eq!(provided(&en, 'م').as_deref(), Some(arabic_name.as_str()), "Arabic uses its own craft face"); + assert_eq!(provided(&en, 'न').as_deref(), Some(devanagari_name.as_str()), "Devanagari uses its own craft face"); + + let hans = test_provider((|| Some("zh-CN".into())) as fn() -> Option); + assert_eq!(provided(&hans, '日').as_deref(), Some(sc_name.as_str())); + assert_eq!(provided(&hans, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Chinese UI keeps the Japanese face"); + + let hant = test_provider((|| Some("zh-Hant-TW".into())) as fn() -> Option); + assert_eq!(provided(&hant, '龍').as_deref(), Some(sc_name.as_str()), "with no system Hant face, the locale order falls through to SC"); + assert_eq!(provided(&hant, '\u{3105}').as_deref(), Some(sc_name.as_str()), "Bopomofo follows the same locale-order fallback"); + assert_eq!(provided(&hant, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Hant UI keeps the Japanese face"); + + // A system Hant file, when present, is read before the Simplified Chinese craft fallback. + if hant_system_file().is_some() { + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: hant_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + }; + let hant = CraftFontProvider::new(&sources, 1.0); + let got = provided(&hant, '龍').expect("the system Hant face"); + assert!(got.starts_with("craft-system-"), "the system Hant face comes before the SC craft fallback: {got}"); + assert_ne!(got, sc_name, "the SC craft face must not pre-empt a system Hant face"); + } + + let ko = test_provider((|| Some("ko_KR".into())) as fn() -> Option); + assert_eq!(provided(&ko, '한').as_deref(), Some(korean_name.as_str())); + assert_eq!(provided(&ko, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Korean UI keeps the Japanese face"); + assert_ne!(sc.family, ui_font.family); + } + + static PENDING_LAST_RESORT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static PENDING_CRAFT_SC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static PENDING_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static STRICT_PENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + + fn pending_last_resort() -> bool { + PENDING_LAST_RESORT.load(std::sync::atomic::Ordering::Relaxed) + } + + fn pending_craft_sc() -> bool { + PENDING_CRAFT_SC.load(std::sync::atomic::Ordering::Relaxed) + } + + fn pending_ready() -> bool { + !PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) + } + + fn strict_pending() -> bool { + STRICT_PENDING.load(std::sync::atomic::Ordering::Relaxed) + } + + fn ready_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese && PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) { vec![fake("hant.ttf")] } else { Vec::new() } + } + + fn ready_hant_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese { vec![fake("hant.ttf")] } else { Vec::new() } + } + + #[test] + fn provider_uses_the_requested_collection_family_and_its_exact_coverage() { + let path = fake_dir().join("families.ttc"); + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; + + let insert = provider.system_insert_files(file("JetBrains Mono"), 'A').expect("face 1 covers A"); + assert_eq!(insert.data.index, 1, "the requested family selects face 1, not the first covering face 0"); + assert!( + provider.system_insert_files(file("JetBrains Mono"), 'ƀ').is_none(), + "JetBrains Mono does not cover the character; face 0 of Inter must not be used" + ); + + let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; + let insert = provider.system_insert_files(empty_family, 'ƀ').expect("an empty family is face 0"); + assert_eq!(insert.data.index, 0); + } + + #[test] + fn cached_system_face_returns_the_current_scale() { + let path = fake_dir().join("families.ttc"); + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let file = || vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }]; + + let first = provider.system_insert_files(file(), 'A').expect("face 1 covers A"); + assert_eq!(first.data.index, 1); + assert_eq!(first.data.tweak.scale, 1.0); + provider.set_scale(4.0 / 3.0); + let second = provider.system_insert_files(file(), 'A').expect("cached face"); + assert_eq!(second.data.index, 1); + assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a cached face must not bake in the old UI scale"); + } + + #[test] + fn provider_honours_the_injected_embedded_faces() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + if craft_index(ui_font).is_none() { + return; + } + let Some(baseline) = baseline_face('あ') else { return }; + let baseline_name = format!("craft-font-{}", craft_index(baseline).expect("a manifest face has an index")); + let with_craft = test_provider((|| Some("en_US".into())) as fn() -> Option); + assert_eq!(provided(&with_craft, 'あ').as_deref(), Some(baseline_name.as_str())); + + let no_craft = Sources { embedded: no_embedded, ..test_sources((|| Some("en_US".into())) as fn() -> Option) }; + let provider = CraftFontProvider::new(&no_craft, 1.0); + assert!(provided(&provider, 'あ').is_none(), "the provider must use Sources::embedded, not the global craft table"); + } + + #[test] + fn provider_reaches_a_fontconfig_match_after_six_missing_candidates() { + let mut files: Vec = + (0..MAX_SCRIPT_READS).map(|i| FontFile { path: fake_dir().join(format!("missing-{i}.ttf")), family: String::new() }).collect(); + files.push(fake("hant.ttf")); + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let insert = provider.system_insert_files(files, '龍').expect("the seventh (Fontconfig) candidate must be reachable"); + assert!(insert.name.starts_with("craft-system-")); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 1, "only the real file counts as a read; absent paths do not"); + assert_eq!(cache.failed_reads.len(), MAX_SCRIPT_READS); + } + + #[test] + fn provider_caches_failed_reads_and_face_lookups_across_characters() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let missing = fake("missing-cache.ttf"); + assert!(provider.system_insert_files(vec![missing.clone()], '日').is_none()); + assert!(provider.system_insert_files(vec![missing.clone()], '本').is_none()); + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.failed_reads.len(), 1, "a missing path is remembered"); + assert_eq!(cache.reads, 0, "a missing path performs no font read"); + } + + // Inter is readable but does not cover either Han character: its bytes are read once. + let inter = fake("font.ttf"); + assert!(provider.system_insert_files(vec![inter.clone()], '日').is_none()); + assert!(provider.system_insert_files(vec![inter.clone()], '本').is_none()); + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 1, "the second character reuses the cached bytes"); + assert_eq!(cache.files.len(), 1); + } + + // A collection's family lookup is parsed once even when it misses every character. + let path = fake_dir().join("families.ttc"); + let file = vec![FontFile { path, family: "Noto Sans CJK TC".into() }]; + assert!(provider.system_insert_files(file.clone(), '日').is_none()); + assert!(provider.system_insert_files(file, '本').is_none()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.family_indices.len(), 1, "a family miss is cached"); + assert_eq!(cache.family_indices[0].2, None); + } + + static TTC_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + + fn counted_ttc_read(path: &std::path::Path) -> Option> { + TTC_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::fs::read(path).ok() + } + + /// A collection's two faces share one blob: selecting both faces reads the file once and + /// charges its bytes once, not once per face. + #[test] + fn provider_charges_a_ttc_blob_once_for_multiple_selected_faces() { + let path = fake_dir().join("families.ttc"); + let size = std::fs::metadata(&path).expect("test collection").len() as usize; + let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + provider.reader = counted_ttc_read; + TTC_READS.store(0, std::sync::atomic::Ordering::Relaxed); + let first = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "Inter".into() }], 'A').expect("face 0 covers A"); + let second = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }], 'A').expect("face 1 covers A"); + assert_eq!((first.data.index, second.data.index), (0, 1)); + assert!(std::sync::Arc::ptr_eq(&first.data.font, &second.data.font), "both faces share the collection's blob"); + assert_eq!(TTC_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "the collection is read once"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.files.len(), 1, "one retained blob serves both faces"); + assert_eq!(cache.retained_bytes, size, "the TTC blob is charged once"); + assert_eq!(cache.faces.len(), 2, "both selected faces keep their own name"); + } + + /// Selecting a second face under a one-blob budget evicts the earlier blob from the + /// provider, but the earlier `FontInsert` remains valid because it owns its shared blob. + #[test] + fn provider_evicts_an_earlier_selected_blob_under_budget_pressure() { + let first_path = fake("font.ttf").path; + let bytes = std::fs::read(&first_path).expect("test font"); + let size = bytes.len(); + let second_path = fake_dir().join("budget-selected-second.ttf"); + std::fs::write(&second_path, &bytes).expect("write a second test font"); + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size; + } + let first = provider.system_insert_files(vec![FontFile { path: first_path.clone(), family: String::new() }], 'A').expect("the first selected face"); + let second = provider.system_insert_files(vec![FontFile { path: second_path.clone(), family: String::new() }], 'A').expect("the second selected face"); + assert_ne!(first.name, second.name); + assert_eq!(first.data.bytes(), bytes.as_slice(), "evicting the provider's blob does not invalidate egui's copy"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.files.len(), 1, "only one blob fits"); + assert_eq!(cache.files[0].path, second_path, "the newest selected blob is retained"); + assert_eq!(cache.retained_bytes, size, "the provider cache stays within its one-blob budget"); + assert_eq!(cache.faces.len(), 2, "the earlier face name remains reusable metadata, not bytes"); + } + + /// A selected face whose blob does not fit the budget is still returned complete for this + /// request. egui may keep it, but the provider retains neither its bytes nor a second copy. + #[test] + fn provider_returns_a_transient_valid_face_when_the_blob_cannot_be_retained() { + let path = fake("font.ttf").path; + let size = std::fs::metadata(&path).expect("test font").len() as usize; + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size.saturating_sub(1); + } + let insert = provider + .system_insert_files(vec![FontFile { path: path.clone(), family: String::new() }], 'A') + .expect("the over-budget face is returned transiently"); + assert_eq!(insert.data.index, 0); + assert_eq!(insert.data.bytes().len(), size, "the transient face carries the whole valid font"); + assert_eq!(insert.data.bytes(), std::fs::read(&path).expect("test font bytes").as_slice()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.retained_bytes, 0, "an over-budget face retains no provider bytes"); + assert!(cache.files.is_empty(), "the over-budget blob is not retained"); + assert!(cache.retained_bytes <= cache.max_bytes, "the provider cache stays within its budget"); + assert_eq!(cache.reads, 1); + } + + /// A valid font file whose character map does not include the requested character is still a + /// valid font: its bytes are cached within the budget and it is not marked invalid. + #[test] + fn provider_cache_evicts_retained_bytes_within_the_budget() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + let size = bytes.len(); + assert!(size > 0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size.saturating_mul(2); + } + let mut paths = Vec::new(); + for i in 0..5 { + let path = fake_dir().join(format!("budget-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + paths.push(path); + } + for path in &paths { + let file = vec![FontFile { path: path.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none(), "the Thai-only face does not cover 日"); + } + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.retained_bytes <= cache.max_bytes, "retained {} > budget {}", cache.retained_bytes, cache.max_bytes); + assert!(cache.files.len() <= 2, "only two files fit the budget"); + assert!(cache.files.iter().any(|file| file.path == paths[4]), "the newest retained file stays"); + assert!(!cache.files.iter().any(|file| file.path == paths[0]), "the oldest retained file was evicted"); + assert_eq!(cache.reads, 5, "each distinct file was read once"); + assert!(cache.invalid_fonts.is_empty(), "a non-covering face is not an invalid font"); + } + + /// A later covering candidate (such as the Fontconfig match appended last) is reached even + /// when a tiny budget evicts every retained candidate before it. + #[test] + fn provider_reaches_a_later_covering_candidate_under_budget_pressure() { + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = bytes.len(); + } + let mut files = Vec::new(); + for i in 0..12 { + let path = fake_dir().join(format!("budget-later-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + files.push(FontFile { path, family: String::new() }); + } + let covering = fake("hant.ttf").path; + files.push(FontFile { path: covering.clone(), family: String::new() }); + let insert = provider.system_insert_files(files, '龍').expect("the later covering candidate must be reached"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.faces.iter().any(|face| face.path == covering), "the covering file became a selected face"); + assert!(cache.reads >= 13, "all retained candidates plus the matching file were read"); + } + + /// The old lifetime read cap could exhaust before a Fontconfig match appended after many + /// earlier characters. Reads are no longer globally capped; only retained bytes are bounded. + #[test] + fn provider_has_no_lifetime_read_cap_for_the_final_fontconfig_candidate() { + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = bytes.len(); + } + for i in 0..130 { + let path = fake_dir().join(format!("lifetime-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + let file = vec![FontFile { path, family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none()); + } + let covering = fake("hant.ttf").path; + let insert = provider + .system_insert_files(vec![FontFile { path: covering, family: String::new() }], '龍') + .expect("the final candidate must still be read after 130 successful reads"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 131, "130 non-covering reads plus the final candidate"); + } + + static CONCURRENT_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + + fn counted_slow_read(path: &std::path::Path) -> Option> { + CONCURRENT_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::read(path).ok() + } + + /// Layout may ask the provider from several threads. The check/read/insert is serialised, so + /// the same path is read once and every caller sees the same success. + #[test] + fn provider_serialises_concurrent_reads_of_the_same_path() { + let path = fake("font.ttf").path; + let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + provider.reader = counted_slow_read; + CONCURRENT_READS.store(0, std::sync::atomic::Ordering::Relaxed); + let provider = std::sync::Arc::new(provider); + let mut handles = Vec::new(); + for _ in 0..8 { + let provider = std::sync::Arc::clone(&provider); + let path = path.clone(); + handles.push(std::thread::spawn(move || { + let file = vec![FontFile { path, family: String::new() }]; + provider.system_insert_files(file, 'A').is_some() + })); + } + for handle in handles { + assert!(handle.join().expect("layout thread"), "every caller must get the Inter face"); + } + assert_eq!(CONCURRENT_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "one read per path even under concurrency"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.faces.len(), 1, "one selected face is shared"); + } + + /// A readable non-font is negative-cached as invalid (read/parsed once) and never conflated + /// with a valid font that simply does not cover the requested character. + #[test] + fn provider_negative_caches_invalid_fonts_separately_from_noncovering_faces() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let invalid = fake("not-a-font-cache.ttf").path; + std::fs::write(&invalid, b"this is not a font").expect("write invalid bytes"); + let truncated = fake("truncated-font-cache.ttf").path; + std::fs::write(&truncated, &include_bytes!("../../../assets/fonts/Inter-Regular.ttf")[..20]).expect("write truncated font"); + for path in [&invalid, &truncated] { + for c in ['日', '本'] { + let file = vec![FontFile { path: path.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, c).is_none()); + } + } + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.invalid_fonts.len(), 2, "both invalid paths are remembered"); + assert_eq!(cache.reads, 2, "invalid bytes are read and examined once each"); + assert!(cache.files.is_empty(), "invalid bytes are never retained as a font"); + assert!(cache.failed_reads.is_empty(), "an invalid font is not an I/O failure"); + } + let inter = fake("font.ttf").path; + let file = vec![FontFile { path: inter.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none(), "Inter does not cover 日"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.files.iter().any(|file| file.path == inter), "a valid non-covering font is cached"); + assert!(!cache.invalid_fonts.contains(&inter), "a non-covering face is not an invalid font"); + drop(cache); + let file = vec![FontFile { path: inter, family: String::new() }]; + let insert = provider.system_insert_files(file, 'A').expect("the cached valid font still covers A"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + } + + #[test] + fn pending_scan_recovers_through_real_layout_and_the_lazy_reload() { + PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); + let ctx = egui::Context::default(); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: ready_files, + last_resort: Vec::new, + pending: pending_ready, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + let frame = |ctx: &egui::Context| { + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + }; + frame(&ctx); + assert!(!ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the pending first frame has no Hant face"); + + PENDING_READY.store(true, std::sync::atomic::Ordering::Relaxed); + for _ in 0..4 { + frame(&ctx); + } + assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the lazy loader's add_font reload recovers after the scan"); + let registered = ctx.fonts(|f| f.definitions().font_data.keys().filter(|name| name.starts_with(FONT_PREFIX)).count()); + assert_eq!(registered, 1, "exactly the Hant file was installed"); + PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn strict_policy_first_frame_after_the_scan_is_accepted() { + if craft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: the eager provider is only installed with craft-fonts"); + return; + } + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: ready_hant_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍'))); + } + + /// A strict first frame while Fontconfig is still pending cannot be recovered by the lazy + /// loader: epaint panics during layout before `output_hook` can call `add_font`. The real app + /// uses `MissingGlyphPolicy::Tofu` (brief tofu, then the reload above); strict integration + /// tests such as `camera_raw_localization` must wait for the scan first. This test records + /// that limitation instead of claiming a pending strict startup is accepted. + #[test] + #[should_panic(expected = "No glyph for")] + fn pending_strict_policy_startup_is_not_fake_acceptance() { + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: no_files, + last_resort: Vec::new, + pending: strict_pending, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + let _ = ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }); + } + + #[test] + fn language_change_reloads_eager_faces_through_the_app_context() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let ui_name = format!("craft-font-{ui_index}"); + let sc_name = format!("craft-font-{sc_index}"); + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let ctx = egui::Context::default(); + crate::i18n::sync_context(&ctx, "ja"); + for _ in 0..2 { + ctx.run_ui(Default::default(), |ui| { + ui.label("日"); + }) + .textures_delta + .clear(); + } + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name == ui_name), "ja discovers {ui_name}: {discovered:?}"); + + crate::i18n::sync_context(&ctx, "zh-hans"); + for _ in 0..2 { + ctx.run_ui(Default::default(), |ui| { + ui.label("日"); + }) + .textures_delta + .clear(); + } + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name == sc_name), "zh-hans discovers {sc_name}: {discovered:?}"); + assert!(!discovered.iter().any(|insert| insert.name == ui_name), "the language reload clears the old Japanese face: {discovered:?}"); + }); + } + + /// A valid synthetic font whose `glyf` table record extends past the end of the file. Its + /// `cmap` still parses and maps Thai, so a coverage-only check accepts it, but the text + /// engine cannot read every declared table. + fn font_with_out_of_bounds_table() -> Vec { + let mut font = synthetic_font(&[(0x0E01, 0x0E5B)]); + let tables = u16::from_be_bytes([font[4], font[5]]) as usize; + for i in 0..tables { + let rec = 12 + 16 * i; + if font.get(rec..rec + 4) == Some(&b"glyf"[..]) { + font[rec + 12..rec + 16].copy_from_slice(&u32::MAX.to_be_bytes()); + return font; + } + } + panic!("synthetic font has no glyf table"); + } + + /// A readable collection whose selected family face has an out-of-bounds `glyf` table. Face 0 + /// stays readable, and face 1's `cmap`/`name` still work, so a file-level check plus coverage + /// accepts it even though the face cannot be installed safely. + fn collection_with_out_of_bounds_selected_face() -> Vec { + let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let mut jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); + let tables = u16::from_be_bytes([jetbrains[4], jetbrains[5]]) as usize; + let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| jetbrains.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table"); + jetbrains[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes()); + two_face_ttc(inter, &jetbrains) + } + + /// A truncated/out-of-bounds table can keep a valid `cmap`, so `load_first` must validate + /// the file before registering it, and must still reach the next, valid candidate. + #[test] + fn lazy_loader_rejects_a_font_with_an_out_of_bounds_table_and_uses_the_next_candidate() { + let malformed = fake_dir().join("out-of-bounds-thai.ttf"); + std::fs::write(&malformed, font_with_out_of_bounds_table()).unwrap(); + let valid = fake_dir().join("thai.ttf"); + let files = vec![FontFile { path: malformed.clone(), family: String::new() }, FontFile { path: valid.clone(), family: String::new() }]; + let bytes = std::fs::read(&malformed).unwrap(); + assert!(scripts::face_covers(&bytes, 0, 'ก'), "the malformed file's cmap still maps the character"); + assert!(!cjk::font_file_is_readable(&bytes), "an out-of-bounds table makes the file unreadable"); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (_, data) = fallback.load_first(&files, 'ก').expect("the valid fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the malformed file is skipped, not registered"); + assert_eq!(data.index, 0); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); + + // The non-CJK script route must enforce the same validation before registration. + let mut sources = test_sources(|| Some("en".into())); + sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttf"), fake_dir().join("thai.ttf")]; + let mut fallback = CjkFallback::new(sources); + let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the script route also skips the malformed file"); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); + + // A readable collection with an unreadable covering face must also skip that face: the + // coverage route selects face 1 by its valid cmap, not the readable face 0. + let collection = fake_dir().join("out-of-bounds-thai.ttc"); + let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let collection_bytes = two_face_ttc(inter, &font_with_out_of_bounds_table()); + std::fs::write(&collection, &collection_bytes).unwrap(); + assert!(cjk::font_file_is_readable(&collection_bytes), "face 0 keeps the collection readable"); + assert_eq!(scripts::covering_face(&collection_bytes, 'ก'), Some(1), "coverage selects the malformed face"); + assert!(!cjk::font_face_is_readable(&collection_bytes, 1)); + let mut sources = test_sources(|| Some("en".into())); + sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttc"), fake_dir().join("thai.ttf")]; + let mut fallback = CjkFallback::new(sources); + let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the coverage route skips the malformed selected face"); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); + } + + /// A readable collection may contain one bad face. The selected face (by family name) can + /// keep a valid `cmap` and `name` while another table points outside the file, so checking the + /// file or coverage alone would register a face epaint cannot safely install. Both the lazy + /// loader and the eager provider must skip that face and continue to the valid candidate. + #[test] + fn malformed_selected_collection_face_falls_back_before_lazy_and_provider_registration() { + let path = fake_dir().join("out-of-bounds-selected.ttc"); + let bytes = collection_with_out_of_bounds_selected_face(); + std::fs::write(&path, &bytes).expect("write the synthetic collection"); + assert!(cjk::font_file_is_readable(&bytes), "face 0 keeps the collection readable"); + assert_eq!(cjk::face_index_for_family_checked(&bytes, "JetBrains Mono"), Some(1), "the selected face's name resolves"); + assert!(scripts::face_covers(&bytes, 1, 'A'), "the selected face's cmap covers the character"); + assert!(!cjk::font_face_is_readable(&bytes, 1), "the selected face's glyf table is out of bounds"); + + let valid = fake("font.ttf"); + let candidates = vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }, FontFile { path: valid.path.clone(), family: String::new() }]; + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (name, data) = fallback.load_first(&candidates, 'A').expect("the valid alternative is reached"); + assert_eq!(data.index, 0, "the lazy loader registers the valid face 0, not the malformed selected face"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid.path, "the malformed collection is not registered"); + + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let insert = provider.system_insert_files(candidates, 'A').expect("the provider reaches the valid alternative"); + assert_eq!(insert.data.index, 0, "the provider does not hand the malformed selected face to epaint"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + + // Installing the selected font under the strict policy must not panic: only the valid + // fallback reaches egui's family builder. + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + crate::theme::install_fonts(&ctx); + // The lazy loader runs after a frame; initialize the font view before matching that path. + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + add_to_all_families(&ctx, name, data); + ctx.run_ui(Default::default(), |ui| { + ui.label("A"); + }) + .textures_delta + .clear(); + } + + #[test] + fn lazy_loader_uses_the_requested_collection_family_and_checks_coverage() { + let path = fake_dir().join("families.ttc"); + let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (_, data) = fallback.load_first(&file("JetBrains Mono"), 'A').expect("face 1 covers A"); + assert_eq!(data.index, 1); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + assert!(fallback.load_first(&file("JetBrains Mono"), 'ƀ').is_none(), "coverage is checked on the requested face"); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; + let (_, data) = fallback.load_first(&empty_family, 'ƀ').expect("empty family is face 0"); + assert_eq!(data.index, 0); + } + + fn always_thai_candidate(_: Script) -> Vec { + vec![fake_dir().join("thai.ttf")] + } + + /// A path already registered through either route is not read or registered a second time. + #[test] + fn lazy_loader_registers_each_loaded_font_once() { + let valid = fake("font.ttf"); + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let files = vec![valid.clone()]; + fallback.load_first(&files, 'A').expect("the font covers Latin A"); + assert!(fallback.load_first(&files, 'A').is_none(), "a second request for the loaded file registers nothing"); + assert_eq!(fallback.registered.len(), 1); + + let sources = Sources { scripts: always_thai_candidate, ..test_sources(|| Some("en".into())) }; + let mut fallback = CjkFallback::new(sources); + fallback.loaded.push(fake_dir().join("thai.ttf")); + assert!(fallback.next_script_font('ก').is_none(), "the script route skips a file the other route already loaded"); + assert!(fallback.registered.is_empty()); + assert_eq!(fallback.scripts_tried, vec![Script::Thai], "the script is still marked tried only once"); + } + + /// A craft face is registered once: a later request for the same embedded file must not add + /// another font with a new name and a duplicate blob. + #[test] + fn lazy_loader_registers_an_embedded_craft_face_once() { + if baseline_face('あ').is_none() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + } + let mut fallback = CjkFallback::new(craft_only(|| Some("en".into()))); + fallback.load_embedded(CjkScript::Japanese, 'あ').expect("the manifest covers kana"); + assert!(fallback.load_embedded(CjkScript::Japanese, 'あ').is_none(), "the same embedded face is not registered twice"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.loaded.len(), 1); + } + + #[test] + fn provider_uses_system_script_candidates_and_last_resort_for_non_cjk() { + let sources = Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: || vec![FontFile { path: fake_dir().join("ethiopic.ttf"), family: String::new() }], + pending: || false, + scripts: |s| match s { + Script::Tamil => vec![fake_dir().join("tamil.ttf")], + _ => Vec::new(), + }, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + let tamil = provided(&provider, 'த').expect("Tamil system candidate"); + assert!(tamil.starts_with("craft-system-"), "{tamil}"); + let ethiopic = provided(&provider, 'ሀ').expect("last-resort face"); + assert!(ethiopic.starts_with("craft-system-"), "{ethiopic}"); + } + + static PROVIDER_SCRIPT_CALLS: Mutex> = Mutex::new(Vec::new()); + + fn recorded_provider_files(script: CjkScript) -> Vec { + PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(script); + Vec::new() + } + + /// A Hangul character's preferred script is the locale order's first script, so the provider + /// builds a list with Korean twice. It must still ask for Korean's files once, then try each + /// remaining script once, not restart the preferred script after a miss. + #[test] + fn provider_tries_each_script_once_when_the_preferred_script_repeats_the_order() { + PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear(); + let sources = Sources { + locale: || Some("ko_KR".into()), + files: recorded_provider_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '한').is_none(), "the test source has no Hangul face"); + let calls = PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + assert_eq!(calls, vec![CjkScript::Korean, CjkScript::TraditionalChinese, CjkScript::SimplifiedChinese, CjkScript::Japanese]); + } + + /// An unclassified symbol (not CJK, not one of the non-CJK scripts) only has the optional + /// craft `Zsym` face. Without one the provider must return missing rather than read unrelated + /// system fonts, and an empty cluster is likewise no request at all. + #[test] + fn provider_missing_symbol_and_empty_cluster_do_not_touch_system_fonts() { + let sources = Sources { embedded: no_embedded, ..test_sources(|| Some("en".into())) }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provider.font_for(&FallbackRequest { cluster: "", family: &FontFamily::Proportional }).is_none()); + assert!(provided(&provider, '☃').is_none(), "no injected Zsym craft face covers the symbol"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 0, "a symbol is not a CJK or script fallback request"); + assert!(cache.failed_reads.is_empty() && cache.invalid_fonts.is_empty()); + } + + #[test] + fn provider_applies_the_current_scale_to_craft_faces() { + if baseline_face('あ').is_none() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + } + let provider = test_provider(|| Some("en".into())); + let first = provided_insert(&provider, 'あ').expect("the craft manifest covers kana"); + assert_eq!(first.data.tweak.scale, 1.0); + assert!(first.families.iter().any(|f| f.family == FontFamily::Proportional)); + assert!(first.families.iter().any(|f| f.family == FontFamily::Monospace)); + provider.set_scale(4.0 / 3.0); + let second = provided_insert(&provider, 'あ').expect("the craft face is resolved again at the current scale"); + assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a craft face must not bake in the scale of an earlier pass"); + } + + /// Face-name metadata is capped independently of the retained-blob budget: forgetting the + /// oldest name only makes egui install that face under a later name, it never drops bytes + /// from a file that still fits. + #[test] + fn system_face_names_are_bounded_independently_of_font_blobs() { + let mut cache = SystemCache::default(); + for i in 0..MAX_SYSTEM_FACE_NAMES + 4 { + cache.remember_face(PathBuf::from(format!("face-{i}.ttf")), i as u32, format!("craft-system-{i}")); + } + assert_eq!(cache.faces.len(), MAX_SYSTEM_FACE_NAMES); + assert_eq!(cache.faces.first().map(|face| face.name.as_str()), Some("craft-system-4"), "the oldest names are evicted first"); + assert_eq!(cache.faces.last().map(|face| face.name.as_str()), Some("craft-system-1027")); + assert!(cache.files.is_empty() && cache.retained_bytes == 0, "face names do not retain or charge font bytes"); + } + + #[test] + fn pending_fontconfig_defers_the_last_resort_instead_of_returning_none_forever() { + PENDING_LAST_RESORT.store(true, std::sync::atomic::Ordering::Relaxed); + let sources = Sources { + locale: || Some("zh-Hant-TW".into()), + files: no_files, + last_resort: || vec![FontFile { path: fake_dir().join("hant.ttf"), family: String::new() }], + pending: pending_last_resort, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '龍').is_none(), "pending Hant scan must not fall through to a last resort"); + PENDING_LAST_RESORT.store(false, std::sync::atomic::Ordering::Relaxed); + let got = provided(&provider, '龍').expect("after the scan the last resort is usable"); + assert!(got.starts_with("craft-system-"), "{got}"); + } + + #[test] + fn pending_fontconfig_does_not_cache_the_lower_priority_sc_craft_face_for_hant() { + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + PENDING_CRAFT_SC.store(true, std::sync::atomic::Ordering::Relaxed); + let sources = Sources { + locale: || Some("zh-Hant-TW".into()), + files: no_files, + last_resort: Vec::new, + pending: pending_craft_sc, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '龍').is_none(), "a pending Hant scan must not return (and cache) the lower-priority SC craft face"); + PENDING_CRAFT_SC.store(false, std::sync::atomic::Ordering::Relaxed); + let expected = format!("craft-font-{sc_index}"); + assert_eq!(provided(&provider, '龍').as_deref(), Some(expected.as_str())); + } + + #[test] + fn every_craft_face_is_available_to_both_ui_families() { + let mut checked = 0; + for (i, face) in craft_fonts::CRAFT_FONTS.iter().enumerate() { + if face.bytes.is_empty() { + continue; + } + let insert = craft_insert(i, face, 1.0); + assert_eq!(insert.name, format!("craft-font-{i}")); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{} is missing from Proportional", face.family); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{} is missing from Monospace", face.family); + checked += 1; + } + if checked == 0 { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + } + } + + #[test] + fn the_craft_provider_shapes_the_first_headless_frame_in_both_families() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { + eprintln!("skipping: the craft-fonts manifest has no Korean face"); + return; + }; + let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { + eprintln!("skipping: the craft-fonts manifest has no Arabic face"); + return; + }; + let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { + eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); + return; + }; + let Some(baseline_kana) = baseline_face('か') else { return }; + let Some(baseline_han) = baseline_face('日') else { return }; + let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); + let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); + for (locale, text, expected) in [ + ((|| Some("ja_JP".into())) as fn() -> Option, "かな", ui_index), + ((|| Some("en_US".into())) as fn() -> Option, "かな", baseline_kana_index), + ((|| Some("en_US".into())) as fn() -> Option, "日本", baseline_han_index), + ((|| None) as fn() -> Option, "日本", baseline_han_index), + ((|| Some("en_US".into())) as fn() -> Option, "한", korean_index), + ((|| Some("en_US".into())) as fn() -> Option, "مرحبا", arabic_index), + ((|| Some("en_US".into())) as fn() -> Option, "नमस्ते", devanagari_index), + ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "かな", ui_index), + ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "龍", sc_index), + ((|| Some("zh-CN".into())) as fn() -> Option, "中文", sc_index), + ] { + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, eager_sources(locale)); + ctx.run_ui(Default::default(), |ui| { + ui.label(text); + ui.label(egui::RichText::new(text).monospace()); + }) + .textures_delta + .clear(); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&FontId::monospace(12.0), text)), "{text} is missing from Monospace"); + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!( + discovered.iter().any(|insert| insert.name == format!("craft-font-{expected}")), + "{text}: expected craft-font-{expected}, discovered {discovered:?}" + ); + for insert in &discovered { + assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{insert:?}"); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{insert:?}"); + } + } + // A Traditional Chinese locale has no Hant craft face. A system Hant file, when present, + // must be read before the Simplified Chinese craft fallback. + if hant_system_file().is_some() { + let mut sources = eager_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option); + sources.files = hant_files; + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, sources); + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name.starts_with("craft-system-")), "the system Hant face draws the first frame: {discovered:?}"); + assert!( + !discovered.iter().any(|insert| insert.name == format!("craft-font-{sc_index}")), + "the Simplified Chinese face must not pre-empt the Hant system font: {discovered:?}" + ); + } + } + #[test] fn ui_works_without_craft_fonts() { // The pre-craft-fonts behaviour: no embedded fonts, no system fonts. Latin renders, @@ -912,6 +2897,7 @@ mod tests { locale: || None, files: |_| vec![], last_resort: Vec::new, + pending: || false, scripts: |_| Vec::new(), covers: scripts::covering_face, embedded: no_embedded, @@ -932,7 +2918,7 @@ mod tests { #[test] fn system_fonts_cover_cjk_samples() { #[cfg(target_os = "linux")] - wait_for_fontconfig_cjk_scan(); + assert!(wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds"); let available = |s: CjkScript| cjk::font_files(s).iter().any(|f| f.path.is_file()); let samples = [ ("图层", CjkScript::SimplifiedChinese), diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 81639fa8d2..10332ced7c 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -188,7 +188,7 @@ fn cjk_font_order_follows_the_selected_language() { fn korean_glyphs_remain_available_after_repeated_language_switches() { use photocraft_text::cjk::{self, CjkChar, CjkScript}; #[cfg(target_os = "linux")] - crate::cjk_fonts::wait_for_fontconfig_cjk_scan(); + assert!(crate::cjk_fonts::wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds"); if !cjk::font_files(CjkScript::Korean).iter().any(|font| font.path.is_file()) { eprintln!("skipping: no installed Korean font"); return; diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/layer_props_ui.rs index 778cb8f6cd..62f84ecc8a 100644 --- a/crates/ui-egui/src/layer_props_ui.rs +++ b/crates/ui-egui/src/layer_props_ui.rs @@ -34,8 +34,6 @@ pub fn transform_params(layer: u64, b: [f64; 4], w: Option, h: Option, Some(json!({"layer": layer, "rect": b, "quad": quad})) } -/// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own -/// label and the one stacked with it in the same column ("W" over "X"), which share a centre. /// The smallest W/H change, in px, that counts as an edit. A pixel frame is whole pixels: under /// half a pixel is noise. A shape's path is fractional and is scaled to exactly the typed size, /// so anything past the field's own rounding (half its last shown decimal) is an edit: 400.25 px @@ -48,6 +46,8 @@ fn edit_tolerance(layer: &Layer, u: LenUnit, extent: f64) -> f32 { } } +/// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own +/// label and the one stacked with it in the same column ("W" over "X"), which share a centre. /// `len` is the unit shown and its 100% extent (for percent); `name` is the field's accessible name. // The explicit accessible name accompanies the existing numeric-field parameters. #[expect(clippy::too_many_arguments)] diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 68ebf5bd97..1c7fbddb1e 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -2763,6 +2763,28 @@ mod tests { assert_eq!(h.state()["memoryUsageMb"], 50000); } + #[test] + fn graphics_dropdowns_are_named_for_their_settings() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let obj = json!({"gpuBackend": "auto", "gpuAdapter": ""}).as_object().unwrap().clone(); + let mut h = Harness::builder() + .with_size(vec2(700.0, 500.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, obj| gpu_status_rows(ui, None, None, obj), obj); + h.run_steps(2); + h.get_by_label("Advanced").click(); + h.run_steps(2); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + assert!(labels.iter().any(|label| label == "GPU Backend"), "{labels:?}"); + if cfg!(target_os = "linux") { + assert!(labels.iter().any(|label| label == "GPU adapter"), "{labels:?}"); + } + assert!(!labels.iter().any(|label| label == "Graphics"), "the section title names neither control: {labels:?}"); + } + #[test] fn colour_preferences_take_a_typed_hex_value() { // #668: the canvas colour (and every colour preference) showed its hex but couldn't take one. diff --git a/crates/ui-egui/src/shape_dialog.rs b/crates/ui-egui/src/shape_dialog.rs index 9a8e075d6d..1b2634a330 100644 --- a/crates/ui-egui/src/shape_dialog.rs +++ b/crates/ui-egui/src/shape_dialog.rs @@ -202,6 +202,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) } let mut linked = f.get("linkRadii").and_then(Value::as_bool).unwrap_or(true); let mut changed = None; + // `radii` is [top-left, top-right, bottom-right, bottom-left]. ui.horizontal(|ui| { label(ui, tl!("Radius:")); ui.vertical(|ui| { diff --git a/crates/ui-egui/src/shape_dialog_tests.rs b/crates/ui-egui/src/shape_dialog_tests.rs index d9e61c8830..7af252f087 100644 --- a/crates/ui-egui/src/shape_dialog_tests.rs +++ b/crates/ui-egui/src/shape_dialog_tests.rs @@ -141,6 +141,30 @@ fn click_slop_scales_with_zoom() { assert!(is_click([10.0, 10.0], &[], 0.0)); } +#[test] +fn radius_fields_are_named_for_their_corners() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app(); + let id = open(&mut app, Tool::Rectangle, [10.0, 20.0]).unwrap(); + let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + let mut h = Harness::builder().with_size(egui::vec2(520.0, 520.0)).build_ui_state(move |ui, fields| body(&app, ui, fields), fields); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + let labels: Vec = h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect(); + // The visible rows are [top-left, top-right], [bottom-left, bottom-right]; the field for each + // radius index must carry its own corner name (a permutation would still pass a set check). + let corners: Vec<&str> = labels.iter().map(String::as_str).filter(|label| !matches!(*label, "Width:" | "Height:")).collect(); + assert_eq!( + corners, + vec!["Top Left Radius:", "Top Right Radius:", "Bottom Left Radius:", "Bottom Right Radius:"], + "radius fields name their corner in layout order: {labels:?}" + ); + assert!(!labels.iter().any(|label| label == "Radius:"), "the generic name would leave the corners indistinguishable"); +} + /// #4205: the click slop is in screen points, so on a 2x (HiDPI) display at 100 % a 2 pt jitter /// (4 device px = 4 document px) is still a click that opens Create Rectangle, not a tiny shape. #[test] diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index cdeacbbbee..a969dfcb7d 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -536,6 +536,24 @@ mod tests { assert!(app.ui.dialogs.iter().any(|x| x.id == id), "reset leaves the dialog open"); } + #[test] + fn canvas_extension_dropdown_is_named_for_its_setting() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 100, "height": 50})).unwrap(); + let mut h = + Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.canvasSize").unwrap(); + h.run_steps(3); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + assert!(labels.iter().any(|label| label == "Canvas extension color:"), "{labels:?}"); + assert!(!labels.iter().any(|label| label == "Size"), "the dialog's Size label names a different field: {labels:?}"); + } + /// #6019: on an Indexed Color document the dialog opens on, and offers only, Automatic and Nearest Neighbor. #[test] fn indexed_color_resamples_with_nearest_neighbor_only() { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index aa35282e72..b2620ced01 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -873,28 +873,11 @@ pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) { fonts.families.entry(FontFamily::Monospace).or_default().insert(0, mono); } // The optional craft-fonts input carries Japanese, Simplified Chinese, Korean, Arabic, Thai and - // other faces. Register them up front: the lazy loader cannot react before the first frame - // shapes (and a headless frame panics on a missing glyph rather than drawing tofu). - if cjk.eager_craft_fonts { - // The UI Japanese face comes first, as in the lazy loader (`japanese_for_ui`): egui uses - // the first family member that covers a glyph, and the manifest lists Shippori Mincho - // before BIZ UDPGothic, so manifest order alone would draw Japanese UI in serif glyphs - // and shared Han characters in Japanese forms. - let craft = photocraft_text::craft_fonts::CRAFT_FONTS; - let ui_first: Vec = - photocraft_text::craft_fonts::japanese_for_ui().iter().filter_map(|f| craft.iter().position(|c| std::ptr::eq(c, *f))).collect(); - let order = ui_first.iter().copied().chain((0..craft.len()).filter(|i| !ui_first.contains(i))); - for i in order { - let f = &craft[i]; - if f.bytes.is_empty() { - continue; - } - let name = format!("craft-font-{i}"); - fonts.font_data.insert(name.clone(), Arc::new(FontData::from_static(f.bytes))); - fonts.families.entry(FontFamily::Proportional).or_default().push(name.clone()); - fonts.families.entry(FontFamily::Monospace).or_default().push(name); - } - } + // other faces. They are not registered into this static stack: `cjk_fonts` installs a + // per-character font provider for them, so a broad Simplified Chinese face is not put in the + // family stack ahead of the Japanese or Korean face, and a locale without a Traditional Chinese + // craft face leaves Han to the system font. (A single linear per-family chain still decides a + // glyph once a broad face is discovered; see `cjk_fonts`.) // Named weights fall back to the default stack for missing glyphs. let fallback: Vec = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); for (fam, primary) in [("medium", medium), ("semibold", semibold)] { @@ -938,6 +921,11 @@ fn ui_font_size(ctx: &egui::Context) -> UiFontSize { ctx.data(|d| d.get_temp::(ui_fonts_id())).unwrap_or_default() } +/// The Interface > UI Font Size multiplier for the current context (including the default Small). +pub(crate) fn ui_font_scale(ctx: &egui::Context) -> f32 { + font_scale(ui_font_size(ctx)) +} + fn font_scale(size: UiFontSize) -> f32 { match size { UiFontSize::Tiny => 10.0 / 12.0, @@ -999,6 +987,10 @@ impl egui::Plugin for UiFontSizePlugin { Arc::make_mut(data).tweak.scale = original * font_scale(size); } ctx.set_fonts(fonts); + // The provider must use the scale of the definitions that were active while this pass + // laid out text. A face it discovers during the pass is inserted at that old scale; after + // `set_fonts` the rescaled definitions take effect and the provider follows them. + crate::cjk_fonts::set_craft_font_scale(ctx, font_scale(size)); self.applied = size; ctx.request_repaint(); } diff --git a/crates/ui-egui/tests/it/camera_raw_localization.rs b/crates/ui-egui/tests/it/camera_raw_localization.rs index ef42396364..7d91567591 100644 --- a/crates/ui-egui/tests/it/camera_raw_localization.rs +++ b/crates/ui-egui/tests/it/camera_raw_localization.rs @@ -6,14 +6,11 @@ use serde_json::json; #[test] fn all_registered_languages_render_camera_raw_and_switch_without_resetting_view_or_filter() { - // Required central-font acceptance must not pass only because the host supplies Hindi. - if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() { - let faces: Vec<_> = photocraft_text::craft_fonts::CRAFT_FONTS.iter().filter(|f| f.family == "Noto Sans Devanagari").collect(); - assert_eq!(faces.len(), 1, "the central default manifest supplies one Devanagari face"); - assert_eq!(faces[0].style, "Regular"); - assert_eq!(faces[0].scripts, ["Deva"]); - assert!(!faces[0].bytes.is_empty()); - } + // On Linux some scripts arrive through the background Fontconfig lookup. Kittest's strict + // missing-glyph policy must not race that scan: wait for it exactly as the i18n live tests do. + #[cfg(target_os = "linux")] + assert!(photocraft_ui_egui::cjk_fonts::wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds"); + assert_required_camera_raw_fonts(); let _gpu = photocraft_testkit::gpu_lock(); for lang in i18n::Lang::all() { let gpu = std::env::var_os("PHOTOCRAFT_LOCALE_SNAPSHOTS").is_some(); @@ -116,3 +113,21 @@ fn all_registered_languages_render_camera_raw_and_switch_without_resetting_view_ assert_eq!(after["histogram"], before["histogram"]); } } + +/// Check central font fixtures independently of the language-switching UI assertions. +fn assert_required_camera_raw_fonts() { + // Required central-font acceptance must not pass only because the host supplies Hindi, + // or because a Windows runner happens to have Japanese fonts: every non-Latin script this + // test renders comes from a real face in the central manifest. The all-language loop then + // checks the actual translated labels under egui_kittest's strict missing-glyph policy. + if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() { + for (family, script) in [("BIZ UDPGothic", "Jpan"), ("Noto Sans CJK SC", "Hans"), ("NanumGothic", "Kore"), ("Noto Sans Devanagari", "Deva")] { + let faces: Vec<_> = photocraft_text::craft_fonts::CRAFT_FONTS + .iter() + .filter(|f| f.family == family && f.style == "Regular" && f.scripts.contains(&script)) + .collect(); + assert_eq!(faces.len(), 1, "the central default manifest supplies one {family} {script} Regular face"); + assert!(!faces[0].bytes.is_empty(), "{family} {script} has an empty face"); + } + } +} diff --git a/docs/development.md b/docs/development.md index 4cb7161ab0..1a39c103e7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -112,7 +112,7 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo test --workspace # runs the Japa - **UI:** the Japanese fonts (BIZ UDPGothic Regular first) are the first Japanese fallback in the lazy CJK loader (`crates/ui-egui/src/cjk_fonts.rs`), ahead of the system Japanese fonts and in the same locale script order, appended last to every egui family with the usual baseline alignment. - **Type tool:** the text engine registers them in `FontDb::new` (so also with no system fonts) and puts them first in the Japanese slot of the locale-ordered fallback list: BIZ UDPGothic for sans runs, Shippori Mincho / BIZ UDMincho for serif runs. - **Web:** the wasm32 build never embeds craft-fonts, even with `CRAFT_FONTS_DIR` set: measured on 2026-10-06, the UI face alone took the release wasm from 24.19 MB to 28.87 MB, over the 24 MiB gate in `packaging/web/package.sh`. Instead it loads fonts served next to it, on demand: `fonts/manifest.txt` beside `index.html`, in craft-fonts' manifest format (`crates/text/src/served.rs`; hosting: `packaging/web/README.md` › Fonts). `PHOTOCRAFT_WEB_FONTS_DIR="$PWD/../craft-fonts" packaging/web/package.sh` puts craft-fonts there. Served families are in the font menus and are fetched when picked or when a document's text needs them; they aren't in the script fallback list yet, so Japanese text set in a Latin font still needs a Japanese font picked (#1615). -- Tests that need the fonts skip with a message when `CRAFT_FONTS` is empty; CI's Linux gate builds with `CRAFT_FONTS_DIR` set and `CRAFT_FONTS_REQUIRED=1`, so they run there. Desktop releases check out craft-fonts at the commit pinned in `.github/workflows/release.yml` (`CRAFT_FONTS_REF`; ci.yml pins the same commit) and ship each font's `OFL.txt` as `OFL-.txt`. +- Tests that need the fonts skip with a message when `CRAFT_FONTS` is empty; CI's Linux gate and Windows test legs build with `CRAFT_FONTS_DIR` set and `CRAFT_FONTS_REQUIRED=1`, so they run there. Desktop releases check out craft-fonts at the commit pinned in `.github/workflows/release.yml` (`CRAFT_FONTS_REF`; ci.yml pins the same commit) and ship each font's `OFL.txt` as `OFL-.txt`. ## One instance per user