From 972e228f41b895d6b7e40dcbac981e65107111a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20Valentin=20N=C3=A9meth?= <61153253+attisvalentin@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:13:49 +0200 Subject: [PATCH 1/6] M4: text.rescanFonts and text.loadFont: fonts installed while the app runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The system fonts are indexed once per process, so a font installed while FigCraft (or `figcraft-cli mcp`) runs stayed missing until a restart. - text.rescanFonts walks the font folders again and offers the families installed since (loaded families keep their faces) → {added} - text.loadFont {path | data} adds a font file without installing it → {families} - both clear the layout cache so text lays out again in the new face Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/create.rs | 4 +-- crates/engine/src/cmd/text.rs | 30 ++++++++++++++++++ crates/engine/src/tests.rs | 19 ++++++++++++ crates/engine/src/textedit.rs | 3 +- crates/text/src/fontdb.rs | 54 +++++++++++++++++++++++++++++++++ crates/text/src/fontdb_tests.rs | 31 +++++++++++++++++++ crates/text/src/lib.rs | 2 +- docs/mcp.md | 4 ++- 8 files changed, 142 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 3a9f6d67..65c526e4 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -363,12 +363,12 @@ fn free_spot(s: &Session, w: f64, h: f64) -> Result<(f64, f64)> { } #[cfg(not(target_arch = "wasm32"))] -fn read_path(path: &str) -> Result> { +pub(super) fn read_path(path: &str) -> Result> { crate::file_access::read(path) } #[cfg(target_arch = "wasm32")] -fn read_path(path: &str) -> Result> { +pub(super) fn read_path(path: &str) -> Result> { Err(crate::EngineError::Other(format!("{path}: files can't be read in the browser"))) } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 3b861895..129c8ead 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -474,5 +474,35 @@ pub fn specs() -> Vec { }) } ), + spec!( + "text.rescanFonts", + "Rescan installed fonts", + "{} walks the system font folders again, for fonts installed while the app runs → {added: [families that were unknown]}", + false, + |_, _| Ok(json!({"added": figcraft_text::rescan_system_fonts()})) + ), + spec!( + "text.loadFont", + "Load font file", + "{path | data (base64)} adds a font file (.ttf, .otf, .ttc, .otc; every face of a collection) to this session's fonts without installing it → {families}", + false, + |_, p| { + let cmd = "text.loadFont"; + let bytes = if let Some(b64) = string(p, "data") { + use base64::Engine as _; + let b64 = b64.split_once(',').map(|(_, d)| d.to_string()).unwrap_or(b64); + base64::engine::general_purpose::STANDARD.decode(b64.trim()).map_err(|e| bad(cmd, format!("`data`: {e}")))? + } else if let Some(path) = string(p, "path") { + super::create::read_path(&path)? + } else { + return Err(bad(cmd, "pass `path` or `data` (base64)")); + }; + let families = figcraft_text::load_font_bytes(bytes); + if families.is_empty() { + return Err(bad(cmd, "not a font file")); + } + Ok(json!({"families": families})) + } + ), ] } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d8ebfc9e..7cfa320b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -434,6 +434,8 @@ fn every_command_survives_junk_params() { | "file.placeImage" | "image.place" | "file.revert" + // Takes no params and walks the font folders: one walk per junk is slow. + | "text.rescanFonts" ) { continue; } @@ -624,3 +626,20 @@ fn find_replace_changing_only_the_case_replaces_every_occurrence() { assert_eq!(s.doc().unwrap().node(t).unwrap().kind.text().unwrap().characters, "FigCraft and FigCraft, FigCraft"); assert_eq!(s.doc().unwrap().node(f).unwrap().name, "FigCraft / FigCraft"); } + +#[test] +fn fonts_load_from_files_and_rescans_report_new_families() { + let mut s = sess(); + assert!(s.execute("text.loadFont", &json!({})).is_err()); + assert!(s.execute("text.loadFont", &json!({"data": "bm90IGEgZm9udA=="})).is_err(), "not a font file"); + assert!(s.execute("text.loadFont", &json!({"data": "%%%"})).is_err()); + assert!(s.execute("text.loadFont", &json!({"path": "no-such-dir/x.ttf"})).is_err()); + if let Some(f) = figcraft_text::CRAFT_FONTS.first() { + use base64::Engine as _; + let data = base64::engine::general_purpose::STANDARD.encode(f.bytes); + let r = s.execute("text.loadFont", &json!({"data": data})).unwrap(); + assert_eq!(r["families"].as_array().map(Vec::len), Some(1)); + } + let r = s.execute("text.rescanFonts", &json!({})).unwrap(); + assert!(r["added"].is_array()); +} diff --git a/crates/engine/src/textedit.rs b/crates/engine/src/textedit.rs index 76b353a0..38d6a199 100644 --- a/crates/engine/src/textedit.rs +++ b/crates/engine/src/textedit.rs @@ -793,7 +793,8 @@ mod tests { json!({"variations": {"wght": "heavy", "toolong": 1}, "text": "\u{0}\u{7}", "cursor": 1e300}), json!({"variations": {"wght": 1e300, "opsz": -1e300}, "replace": "yes", "text": "日本語", "cursor": -1}), ]; - for spec in crate::cmd::all_commands().iter().filter(|c| c.id.starts_with("text.")) { + // `text.rescanFonts` takes no params and walks the font folders: one walk per junk is slow. + for spec in crate::cmd::all_commands().iter().filter(|c| c.id.starts_with("text.") && c.id != "text.rescanFonts") { for j in &junk { let (mut s, id) = setup("Hi there\nyou"); begin(&mut s, id, Some(2), false).unwrap(); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f9eda2c6..aa5777b5 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -670,6 +670,23 @@ impl FontDb { self.faces.len() } + /// Offer the families of a later walk of the font folders: new families become pending, and a + /// family not loaded yet takes the walk's files (styles installed since). Loaded families keep + /// their faces. Returns the display names of the families that were unknown. + fn merge_rescan(&mut self, found: BTreeMap)>) -> Vec { + let mut added = Vec::new(); + for (k, v) in found { + if self.families.contains_key(&k) { + continue; + } + if !self.pending.contains_key(&k) { + added.push(v.0.clone()); + } + self.pending.insert(k, v); + } + added + } + /// Index the system font directories (desktop only): family names are read now, faces loaded /// when first used. Safe to call more than once. pub fn scan_system(&mut self) { @@ -887,6 +904,43 @@ pub fn scan_system_fonts() { }); } +/// Walk the system font folders again, for fonts installed while the app runs (the first scan is +/// once per process). Returns the families that were unknown before. Before the first scan this +/// is that scan; a no-op on the web or with `FIGCRAFT_NO_SYSTEM_FONTS` set. +pub fn rescan_system_fonts() -> Vec { + #[cfg(not(target_arch = "wasm32"))] + if !system_fonts_opted_out() { + if SCANNED.get().is_none() { + let before: std::collections::BTreeSet = + raw_db().read().unwrap_or_else(std::sync::PoisonError::into_inner).families().into_iter().collect(); + scan_system_fonts(); + return family_names().into_iter().filter(|f| !before.contains(f)).collect(); + } + let mut found: BTreeMap)> = BTreeMap::new(); + for dir in system_font_dirs() { + scan_dir(&dir, 0, &mut found); + } + let added = raw_db().write().unwrap_or_else(std::sync::PoisonError::into_inner).merge_rescan(found); + if !added.is_empty() { + crate::clear_layout_cache(); + } + return added; + } + Vec::new() +} + +/// Load font file bytes (every face of a collection) into the global db, for a font that isn't +/// installed. Returns the families of the faces added (none: not a font file). +pub fn load_font_bytes(bytes: Vec) -> Vec { + let faces = db().write().unwrap_or_else(std::sync::PoisonError::into_inner).add_bytes(bytes); + if !faces.is_empty() { + crate::clear_layout_cache(); + } + let mut families: Vec = faces.iter().map(|f| f.family.clone()).collect(); + families.dedup(); + families +} + /// `FIGCRAFT_NO_SYSTEM_FONTS` is set (and not `0`): renders use only the embedded fonts. #[cfg(not(target_arch = "wasm32"))] fn system_fonts_opted_out() -> bool { diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 96ce7842..3574fdfb 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -217,3 +217,34 @@ fn user_font_dirs_preserve_non_utf8_paths() { assert_eq!(dirs[0].as_os_str().as_bytes(), b"/home/\xff/.fonts"); assert_eq!(dirs[1].as_os_str().as_bytes(), b"/data/\xfe/fonts"); } + +#[test] +fn a_rescan_offers_fonts_installed_since() { + let entry = |s: &str| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: s.into() }; + let mut db = pending(&["Regular"]); + let found = |fams: &[(&str, &[&str])]| -> BTreeMap)> { + fams.iter().map(|(f, styles)| (f.to_lowercase(), ((*f).to_string(), styles.iter().map(|s| entry(s)).collect()))).collect() + }; + // A new family is reported and offered; a pending one takes the walk's files (a new style). + let added = db.merge_rescan(found(&[("CJK UI", &["Regular", "Bold"]), ("Brand Sans", &["Regular"])])); + assert_eq!(added, ["Brand Sans"]); + assert!(db.has_family("brand sans")); + assert_eq!(left(&db), ["Regular", "Bold"]); + // A loaded family keeps its faces and isn't reported again. + db.families.insert("brand sans".into(), ("Brand Sans".into(), Vec::new())); + db.pending.remove("brand sans"); + assert!(db.merge_rescan(found(&[("Brand Sans", &["Regular"])])).is_empty()); + assert!(!db.pending.contains_key("brand sans")); +} + +#[test] +fn font_bytes_load_into_the_db() { + assert!(load_font_bytes(b"not a font".to_vec()).is_empty()); + assert!(load_font_bytes(Vec::new()).is_empty()); + // With the embedded fonts (absent on CI builds without craft-fonts): a file's family is added. + if let Some(f) = CRAFT_FONTS.first() { + let families = load_font_bytes(f.bytes.to_vec()); + assert_eq!(families.len(), 1); + assert!(families.iter().all(|f| has_family(f))); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 683350f6..e107593e 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -17,7 +17,7 @@ pub use breaks::grapheme_step; pub use color::{ColorBitmap, ColorInk, ColorLayer}; pub use fontdb::{ Axis, CRAFT_FONTS, Coords, Face, FontDb, NamedInstance, axis_label, db, face_with_char, family_names, family_styles, find_face, has_family, - installed_fonts_known, no_coords, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, + installed_fonts_known, load_font_bytes, no_coords, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, }; pub use layout::{Decoration, Glyph, Line, TextLayout, layout}; pub use onpath::OnPath; diff --git a/docs/mcp.md b/docs/mcp.md index c5ffe99f..787f0c82 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -234,7 +234,9 @@ Or in a project's `.mcp.json`: `text.setVariations {variations, replace?}` merges instead. `text.fonts {family, style?, axes: true}` lists a font's axes and named instances (named instances are also valid `fontStyle` values). `text.missingFonts` lists the families the document names that aren't installed - (`{families: [{family, layers}]}`); their text draws in a fallback font. + (`{families: [{family, layers}]}`); their text draws in a fallback font. Fonts are indexed once + per process: after installing one, `text.rescanFonts` picks it up (`{added: [families]}`), and + `text.loadFont {path | data (base64)}` adds a font file without installing it (`{families}`). OpenType features: `features {"liga": false, "tnum": true}`. Decorations: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationThickness` and `textDecorationOffset` (`auto`, px, or `"10%"` of the font size; the offset runs from the baseline From ba4c502ada1809c3a27a7795a312d0303528e0c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20Valentin=20N=C3=A9meth?= <61153253+attisvalentin@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:35:31 +0200 Subject: [PATCH 2/6] M4: text.refit: auto-sizing text measures its box again once its font is there MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A text box keeps the size it was measured at, so text laid out while its family was missing kept the fallback font's box after the font arrived (a hugging chip clipped its label). - text.refit {ids?} measures auto-sizing text again (whole document by default) → {refitted} - text.rescanFonts and text.loadFont refit the open document's text in the families they add, as one undo step Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/text.rs | 19 +++++--- crates/engine/src/fonts.rs | 77 +++++++++++++++++++++++++++----- crates/engine/src/fonts_tests.rs | 63 ++++++++++++++++++++++++++ docs/mcp.md | 3 ++ 4 files changed, 145 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 129c8ead..fbc41334 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -477,16 +477,20 @@ pub fn specs() -> Vec { spec!( "text.rescanFonts", "Rescan installed fonts", - "{} walks the system font folders again, for fonts installed while the app runs → {added: [families that were unknown]}", - false, - |_, _| Ok(json!({"added": figcraft_text::rescan_system_fonts()})) + "{} walks the system font folders again, for fonts installed while the app runs; the open document's auto-sizing text in those families fits them (text.refit) → {added: [families that were unknown], refitted: [ids]}", + true, + |s, _| { + let added = figcraft_text::rescan_system_fonts(); + let refitted = crate::fonts::refit_open(s, None, Some(&added)); + Ok(json!({"added": added, "refitted": refitted})) + } ), spec!( "text.loadFont", "Load font file", - "{path | data (base64)} adds a font file (.ttf, .otf, .ttc, .otc; every face of a collection) to this session's fonts without installing it → {families}", - false, - |_, p| { + "{path | data (base64)} adds a font file (.ttf, .otf, .ttc, .otc; every face of a collection) to this session's fonts without installing it; the open document's auto-sizing text in its families fits it (text.refit) → {families, refitted: [ids]}", + true, + |s, p| { let cmd = "text.loadFont"; let bytes = if let Some(b64) = string(p, "data") { use base64::Engine as _; @@ -501,7 +505,8 @@ pub fn specs() -> Vec { if families.is_empty() { return Err(bad(cmd, "not a font file")); } - Ok(json!({"families": families})) + let refitted = crate::fonts::refit_open(s, None, Some(&families)); + Ok(json!({"families": families, "refitted": refitted})) } ), ] diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index 3548124d..42cc8a56 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -1,13 +1,15 @@ //! Fonts a document names that this machine doesn't have (#752): text layers, their styled //! ranges, text styles and the string variables bound to a font family. Text in such a family -//! is drawn in a fallback font, so the user is told which ones are missing. +//! is drawn in a fallback font, so the user is told which ones are missing. Once such a font is +//! there, [`refit`] lets auto-sizing text measure its box in it again. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; -use figcraft_doc::{Document, NodeKind, StyleKind, VariableValue, Variables}; +use figcraft_doc::{Document, NodeId, NodeKind, StyleKind, VariableValue, Variables}; use serde_json::{Value, json}; use crate::cmd::CommandSpec; +use crate::params::{get, req_targets}; use crate::{Result, Session, spec}; /// A family the document names that no installed or built-in font provides. @@ -79,6 +81,52 @@ fn string_values(vars: &Variables, id: &str) -> Vec { out } +/// Auto-sizing text layers measure their boxes again: a box measured while its family was missing +/// (in a fallback font) follows the real face once that's installed or loaded. Only layers under +/// `under` (every layer: `None`) that use one of `families` (any family: `None`). Returns the +/// layers whose size changed. +pub fn refit(doc: &mut Document, under: Option<&[NodeId]>, families: Option<&[String]>) -> Vec { + let want: Option> = families.map(|f| f.iter().map(|x| x.trim().to_lowercase()).collect()); + let scope: Option> = under.map(|ids| ids.iter().flat_map(|i| doc.subtree(*i)).collect()); + let ids: Vec = doc + .nodes() + .filter(|n| scope.as_ref().is_none_or(|s| s.contains(&n.id))) + .filter(|n| { + let NodeKind::Text(t) = &n.kind else { return false }; + let uses = |w: &BTreeSet| { + w.contains(&t.style.font_family.trim().to_lowercase()) + || t.spans().iter().any(|(_, _, st)| w.contains(&st.font_family.trim().to_lowercase())) + }; + want.as_ref().is_none_or(uses) + && figcraft_text::auto_size(n).is_some_and(|(w, h)| (w - n.width).abs() > 1e-6 || (h - n.height).abs() > 1e-6) + }) + .map(|n| n.id) + .collect(); + if !ids.is_empty() { + let before = doc.clone(); + doc.mark_dirty(ids.iter().copied()); + crate::normalize(doc, &before); + } + ids +} + +/// [`refit`] in the open document, if there is one. +pub(crate) fn refit_open(s: &mut Session, under: Option<&[NodeId]>, families: Option<&[String]>) -> Vec { + match s.doc_mut() { + Ok(doc) => refit(doc, under, families), + Err(_) => Vec::new(), + } +} + +fn refit_text(s: &mut Session, p: &Value) -> Result { + let under = match get(p, "ids") { + Some(Value::Array(_)) => Some(req_targets("text.refit", s, p)?), + _ => None, + }; + s.doc()?; + Ok(json!({"refitted": refit_open(s, under.as_deref(), None)})) +} + fn missing_fonts(s: &mut Session, _: &Value) -> Result { let families: Vec = missing(s.doc()?).into_iter().map(|m| json!({"family": m.family, "layers": m.layers})).collect(); s.request_ui("dialog.missingFonts", json!({})); @@ -86,13 +134,22 @@ fn missing_fonts(s: &mut Session, _: &Value) -> Result { } pub fn specs() -> Vec { - vec![spec!( - "text.missingFonts", - "Missing fonts", - "{} fonts the open document names that aren't installed (text layers, styled ranges, text styles, font family variables); the app shows them → {families: [{family, layers}]}", - false, - missing_fonts - )] + vec![ + spec!( + "text.missingFonts", + "Missing fonts", + "{} fonts the open document names that aren't installed (text layers, styled ranges, text styles, font family variables); the app shows them → {families: [{family, layers}]}", + false, + missing_fonts + ), + spec!( + "text.refit", + "Fit text to fonts", + "{ids? (these layers and the text in them; default: the whole document)} auto-sizing text measures its box again, e.g. a box measured in a fallback font while its family was missing → {refitted: [ids whose size changed]}", + true, + refit_text + ), + ] } #[cfg(test)] diff --git a/crates/engine/src/fonts_tests.rs b/crates/engine/src/fonts_tests.rs index a6e2d213..c947773d 100644 --- a/crates/engine/src/fonts_tests.rs +++ b/crates/engine/src/fonts_tests.rs @@ -124,3 +124,66 @@ fn needs_an_open_document() { let mut s = Session::empty(); assert!(s.execute("text.missingFonts", &json!({})).is_err()); } + +/// Make `id`'s box stale, as if it was measured in another font: `dw` wider than its content. +fn stale(s: &mut Session, id: figcraft_doc::NodeId, dw: f64) -> f64 { + let doc = s.doc_mut().unwrap(); + let n = doc.get_mut(id).unwrap(); + let want = figcraft_text::auto_size(n).unwrap().0; + n.width = want + dw; + doc.take_dirty(); + want +} + +fn width(s: &Session, id: figcraft_doc::NodeId) -> f64 { + s.doc().unwrap().node(id).unwrap().width +} + +fn refitted(r: &Value) -> Vec { + r["refitted"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() +} + +#[test] +fn refit_measures_stale_text_boxes_again() { + let mut s = Session::new(); + let a = text(&mut s, "FigCraft Refit A"); + let b = text(&mut s, "FigCraft Refit B"); + let fixed = text(&mut s, "FigCraft Refit A"); + if let NodeKind::Text(t) = &mut s.doc_mut().unwrap().get_mut(fixed).unwrap().kind { + t.auto_resize = figcraft_doc::TextAutoResize::None; + } + s.execute("select.none", &json!({})).unwrap(); + let want_a = stale(&mut s, a, -30.0); + let want_b = stale(&mut s, b, 25.0); + s.doc_mut().unwrap().get_mut(fixed).unwrap().width = 7.0; + s.doc_mut().unwrap().take_dirty(); + // Only the families asked for. + let only_a = super::refit(s.doc_mut().unwrap(), None, Some(&["figcraft refit a".to_string()])); + assert_eq!(only_a, vec![a]); + assert_eq!(width(&s, a), want_a); + assert_eq!(width(&s, b), want_b + 25.0); + // Only the layers asked for, then everything; a fixed box keeps its size. + stale(&mut s, a, 12.0); + assert!(refitted(&s.execute("text.refit", &json!({"ids": [b]})).unwrap()) == vec![b.0]); + assert_eq!((width(&s, a), width(&s, b)), (want_a + 12.0, want_b)); + assert!(refitted(&s.execute("text.refit", &json!({})).unwrap()) == vec![a.0]); + assert_eq!(width(&s, a), want_a); + assert_eq!(width(&s, fixed), 7.0); + // Nothing stale: nothing changes. + assert!(refitted(&s.execute("text.refit", &json!({})).unwrap()).is_empty()); + assert!(s.execute("text.refit", &json!({"ids": ["nope"]})).is_err()); + assert!(Session::empty().execute("text.refit", &json!({})).is_err()); +} + +#[test] +fn refit_reaches_text_in_instances() { + let mut s = Session::new(); + let t = text(&mut s, "FigCraft Refit C"); + let comp = id_of(&s.execute("component.create", &json!({"ids": [t]})).unwrap()["id"]).unwrap(); + let inst = id_of(&s.execute("instance.create", &json!({"component": comp, "x": 300, "y": 0})).unwrap()["id"]).unwrap(); + let copy = s.doc().unwrap().node(inst).unwrap().children[0]; + let want = stale(&mut s, copy, -20.0); + let r = s.execute("text.refit", &json!({"ids": [inst]})).unwrap(); + assert_eq!(refitted(&r), vec![copy.0]); + assert_eq!(width(&s, copy), want); +} diff --git a/docs/mcp.md b/docs/mcp.md index 787f0c82..63ff7dd0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -237,6 +237,9 @@ Or in a project's `.mcp.json`: (`{families: [{family, layers}]}`); their text draws in a fallback font. Fonts are indexed once per process: after installing one, `text.rescanFonts` picks it up (`{added: [families]}`), and `text.loadFont {path | data (base64)}` adds a font file without installing it (`{families}`). + Text boxes keep the size they were measured at: both refit the open document's auto-sizing text + in the new families (`refitted: [ids]`), and `text.refit {ids?}` does it for any text, e.g. a + file saved while its fonts were missing. OpenType features: `features {"liga": false, "tnum": true}`. Decorations: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationThickness` and `textDecorationOffset` (`auto`, px, or `"10%"` of the font size; the offset runs from the baseline From 33c0f94cc8b5475d38c866a38fcbdc8eb774340f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20Valentin=20N=C3=A9meth?= <61153253+attisvalentin@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:46:20 +0200 Subject: [PATCH 3/6] M4: font review fixes: new styles of loaded families, ids checks, repeat loads - text.rescanFonts offers a loaded family the files it hasn't read (styles installed since) and refits every family that gained faces; `added` still lists only the families that were unknown - text.refit refuses an `ids` that isn't a list instead of refitting the whole document - text.loadFont with a file already loaded returns its families without keeping its bytes or adding its faces again - doc comments on the functions this change touches Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/create.rs | 2 + crates/engine/src/cmd/text.rs | 8 ++-- crates/engine/src/fonts.rs | 7 ++- crates/engine/src/fonts_tests.rs | 8 ++++ crates/engine/src/tests.rs | 2 + crates/engine/src/textedit.rs | 1 + crates/text/src/fontdb.rs | 80 +++++++++++++++++++++++--------- crates/text/src/fontdb_tests.rs | 27 ++++++++--- crates/text/src/lib.rs | 5 +- 9 files changed, 105 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 65c526e4..6ec7d4e5 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -362,11 +362,13 @@ fn free_spot(s: &Session, w: f64, h: f64) -> Result<(f64, f64)> { }) } +/// The bytes of the file at `path`, within the session's allowed file roots. #[cfg(not(target_arch = "wasm32"))] pub(super) fn read_path(path: &str) -> Result> { crate::file_access::read(path) } +/// The browser has no files to read: always an error. #[cfg(target_arch = "wasm32")] pub(super) fn read_path(path: &str) -> Result> { Err(crate::EngineError::Other(format!("{path}: files can't be read in the browser"))) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index fbc41334..0f0f003d 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -477,12 +477,12 @@ pub fn specs() -> Vec { spec!( "text.rescanFonts", "Rescan installed fonts", - "{} walks the system font folders again, for fonts installed while the app runs; the open document's auto-sizing text in those families fits them (text.refit) → {added: [families that were unknown], refitted: [ids]}", + "{} walks the system font folders again, for fonts installed while the app runs; the open document's auto-sizing text in the families that gained faces (new ones, or styles installed since) fits them (text.refit) → {added: [families that were unknown], refitted: [ids]}", true, |s, _| { - let added = figcraft_text::rescan_system_fonts(); - let refitted = crate::fonts::refit_open(s, None, Some(&added)); - Ok(json!({"added": added, "refitted": refitted})) + let rescan = figcraft_text::rescan_system_fonts(); + let refitted = crate::fonts::refit_open(s, None, Some(&rescan.changed)); + Ok(json!({"added": rescan.added, "refitted": refitted})) } ), spec!( diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index 42cc8a56..672d4f2c 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -118,10 +118,12 @@ pub(crate) fn refit_open(s: &mut Session, under: Option<&[NodeId]>, families: Op } } +/// `text.refit`: the layers `ids` names (an `ids` that isn't a list of layers is refused), else the +/// whole document. fn refit_text(s: &mut Session, p: &Value) -> Result { let under = match get(p, "ids") { - Some(Value::Array(_)) => Some(req_targets("text.refit", s, p)?), - _ => None, + None | Some(Value::Null) => None, + Some(_) => Some(req_targets("text.refit", s, p)?), }; s.doc()?; Ok(json!({"refitted": refit_open(s, under.as_deref(), None)})) @@ -133,6 +135,7 @@ fn missing_fonts(s: &mut Session, _: &Value) -> Result { Ok(json!({"families": families})) } +/// The font commands: `text.missingFonts` and `text.refit`. pub fn specs() -> Vec { vec![ spec!( diff --git a/crates/engine/src/fonts_tests.rs b/crates/engine/src/fonts_tests.rs index c947773d..463fb904 100644 --- a/crates/engine/src/fonts_tests.rs +++ b/crates/engine/src/fonts_tests.rs @@ -135,14 +135,17 @@ fn stale(s: &mut Session, id: figcraft_doc::NodeId, dw: f64) -> f64 { want } +/// The width of layer `id`. fn width(s: &Session, id: figcraft_doc::NodeId) -> f64 { s.doc().unwrap().node(id).unwrap().width } +/// The ids a refit reports. fn refitted(r: &Value) -> Vec { r["refitted"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() } +/// Stale boxes fit their text again, by family, by layer or everywhere; fixed boxes keep theirs. #[test] fn refit_measures_stale_text_boxes_again() { let mut s = Session::new(); @@ -172,9 +175,14 @@ fn refit_measures_stale_text_boxes_again() { // Nothing stale: nothing changes. assert!(refitted(&s.execute("text.refit", &json!({})).unwrap()).is_empty()); assert!(s.execute("text.refit", &json!({"ids": ["nope"]})).is_err()); + // An `ids` that isn't a list is refused, not taken as the whole document. + stale(&mut s, a, 9.0); + assert!(s.execute("text.refit", &json!({"ids": a.0.to_string()})).is_err()); + assert_eq!(width(&s, a), want_a + 9.0); assert!(Session::empty().execute("text.refit", &json!({})).is_err()); } +/// Text inside an instance is refitted too. #[test] fn refit_reaches_text_in_instances() { let mut s = Session::new(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7cfa320b..ad3b6aa3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -376,6 +376,7 @@ fn pointer_draw_move_resize() { assert_eq!(s.selection(), vec![r]); } +/// No command panics on junk parameters. #[test] fn every_command_survives_junk_params() { // A junk-parameter sweep: no command may panic (guard turns panics into Internal errors, @@ -627,6 +628,7 @@ fn find_replace_changing_only_the_case_replaces_every_occurrence() { assert_eq!(s.doc().unwrap().node(f).unwrap().name, "FigCraft / FigCraft"); } +/// `text.loadFont` refuses what isn't a font file; `text.rescanFonts` reports what it added. #[test] fn fonts_load_from_files_and_rescans_report_new_families() { let mut s = sess(); diff --git a/crates/engine/src/textedit.rs b/crates/engine/src/textedit.rs index 38d6a199..902ba149 100644 --- a/crates/engine/src/textedit.rs +++ b/crates/engine/src/textedit.rs @@ -782,6 +782,7 @@ mod tests { assert!(r.is_null() || r["axes"].is_array()); } + /// No text command panics on junk parameters while a text is being edited. #[test] fn text_commands_survive_junk_while_editing() { let junk = [ diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index aa5777b5..814d3a2f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -444,9 +444,22 @@ pub struct FontDb { families: BTreeMap)>, /// System faces known by name but not loaded (lower-case family → entries). pending: BTreeMap)>, + /// System faces read from disk (file, face index), so a rescan only offers new ones. + loaded_files: std::collections::BTreeSet<(std::path::PathBuf, u32)>, + /// Font files added as bytes (hash and length → families), so loading one again adds nothing. + loaded_bytes: std::collections::HashMap<(u64, usize), Vec>, system_scanned: bool, } +/// What a later walk of the font folders found ([`rescan_system_fonts`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Rescan { + /// Families that were unknown before. + pub added: Vec, + /// Every family that gained faces: the new ones and those with styles installed since. + pub changed: Vec, +} + static DB: OnceLock> = OnceLock::new(); /// Set by [`scan_system_fonts_on_demand`]. static ON_DEMAND: AtomicBool = AtomicBool::new(false); @@ -580,6 +593,7 @@ impl FontDb { }; if let Some(face) = Face::from_bytes(FontBytes::Shared(bytes), e.index, None, Some(&e.style)) { self.add(face); + self.loaded_files.insert((e.path, e.index)); } } } @@ -670,21 +684,33 @@ impl FontDb { self.faces.len() } - /// Offer the families of a later walk of the font folders: new families become pending, and a - /// family not loaded yet takes the walk's files (styles installed since). Loaded families keep - /// their faces. Returns the display names of the families that were unknown. - fn merge_rescan(&mut self, found: BTreeMap)>) -> Vec { - let mut added = Vec::new(); - for (k, v) in found { + /// Offer the families of a later walk of the font folders: new families become pending, a + /// family not loaded yet takes the walk's files, and a loaded family keeps its faces and gets + /// the files it hasn't read (styles installed since) as pending, read when it is next used. + fn merge_rescan(&mut self, found: BTreeMap)>) -> Rescan { + let mut out = Rescan::default(); + for (k, (display, entries)) in found { if self.families.contains_key(&k) { + let waiting = self.pending.get(&k).map(|(_, v)| v.clone()).unwrap_or_default(); + let new: Vec = entries + .into_iter() + .filter(|e| { + !self.loaded_files.contains(&(e.path.clone(), e.index)) && !waiting.iter().any(|w| w.path == e.path && w.index == e.index) + }) + .collect(); + if !new.is_empty() { + out.changed.push(display.clone()); + self.pending.entry(k).or_insert_with(|| (display, Vec::new())).1.extend(new); + } continue; } if !self.pending.contains_key(&k) { - added.push(v.0.clone()); + out.added.push(display.clone()); } - self.pending.insert(k, v); + out.changed.push(display.clone()); + self.pending.insert(k, (display, entries)); } - added + out } /// Index the system font directories (desktop only): family names are read now, faces loaded @@ -905,39 +931,51 @@ pub fn scan_system_fonts() { } /// Walk the system font folders again, for fonts installed while the app runs (the first scan is -/// once per process). Returns the families that were unknown before. Before the first scan this -/// is that scan; a no-op on the web or with `FIGCRAFT_NO_SYSTEM_FONTS` set. -pub fn rescan_system_fonts() -> Vec { +/// once per process): the families that were unknown before, and every family that gained faces. +/// Before the first scan this is that scan; a no-op on the web or with `FIGCRAFT_NO_SYSTEM_FONTS`. +pub fn rescan_system_fonts() -> Rescan { #[cfg(not(target_arch = "wasm32"))] if !system_fonts_opted_out() { if SCANNED.get().is_none() { let before: std::collections::BTreeSet = raw_db().read().unwrap_or_else(std::sync::PoisonError::into_inner).families().into_iter().collect(); scan_system_fonts(); - return family_names().into_iter().filter(|f| !before.contains(f)).collect(); + let added: Vec = family_names().into_iter().filter(|f| !before.contains(f)).collect(); + return Rescan { changed: added.clone(), added }; } let mut found: BTreeMap)> = BTreeMap::new(); for dir in system_font_dirs() { scan_dir(&dir, 0, &mut found); } - let added = raw_db().write().unwrap_or_else(std::sync::PoisonError::into_inner).merge_rescan(found); - if !added.is_empty() { + let rescan = raw_db().write().unwrap_or_else(std::sync::PoisonError::into_inner).merge_rescan(found); + if !rescan.changed.is_empty() { crate::clear_layout_cache(); } - return added; + return rescan; } - Vec::new() + Rescan::default() } /// Load font file bytes (every face of a collection) into the global db, for a font that isn't -/// installed. Returns the families of the faces added (none: not a font file). +/// installed. Returns the families of its faces (none: not a font file); the same file again +/// returns them without adding its faces twice. pub fn load_font_bytes(bytes: Vec) -> Vec { - let faces = db().write().unwrap_or_else(std::sync::PoisonError::into_inner).add_bytes(bytes); - if !faces.is_empty() { - crate::clear_layout_cache(); + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut h); + let key = (h.finish(), bytes.len()); + let mut db = db().write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(families) = db.loaded_bytes.get(&key) { + return families.clone(); } + let faces = db.add_bytes(bytes); let mut families: Vec = faces.iter().map(|f| f.family.clone()).collect(); families.dedup(); + if !families.is_empty() { + db.loaded_bytes.insert(key, families.clone()); + drop(db); + crate::clear_layout_cache(); + } families } diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 3574fdfb..f2456d28 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -218,6 +218,7 @@ fn user_font_dirs_preserve_non_utf8_paths() { assert_eq!(dirs[1].as_os_str().as_bytes(), b"/data/\xfe/fonts"); } +/// A rescan offers new families and the styles installed since, and never a file twice. #[test] fn a_rescan_offers_fonts_installed_since() { let entry = |s: &str| Pending { path: format!("no-such-dir/{s}.ttf").into(), index: 0, style: s.into() }; @@ -225,26 +226,40 @@ fn a_rescan_offers_fonts_installed_since() { let found = |fams: &[(&str, &[&str])]| -> BTreeMap)> { fams.iter().map(|(f, styles)| (f.to_lowercase(), ((*f).to_string(), styles.iter().map(|s| entry(s)).collect()))).collect() }; - // A new family is reported and offered; a pending one takes the walk's files (a new style). - let added = db.merge_rescan(found(&[("CJK UI", &["Regular", "Bold"]), ("Brand Sans", &["Regular"])])); - assert_eq!(added, ["Brand Sans"]); + // A new family is added; a pending one takes the walk's files (a new style); both changed. + let r = db.merge_rescan(found(&[("CJK UI", &["Regular", "Bold"]), ("Brand Sans", &["Regular"])])); + assert_eq!(r.added, ["Brand Sans"]); + assert_eq!(r.changed, ["Brand Sans", "CJK UI"]); assert!(db.has_family("brand sans")); assert_eq!(left(&db), ["Regular", "Bold"]); - // A loaded family keeps its faces and isn't reported again. + // A loaded family keeps its faces and gets only the files it hasn't read, once. db.families.insert("brand sans".into(), ("Brand Sans".into(), Vec::new())); db.pending.remove("brand sans"); - assert!(db.merge_rescan(found(&[("Brand Sans", &["Regular"])])).is_empty()); + db.loaded_files.insert(("no-such-dir/Regular.ttf".into(), 0)); + let same = db.merge_rescan(found(&[("Brand Sans", &["Regular"])])); + assert_eq!(same, Rescan::default()); assert!(!db.pending.contains_key("brand sans")); + let bold = db.merge_rescan(found(&[("Brand Sans", &["Regular", "Black"])])); + assert_eq!((bold.added.len(), bold.changed), (0, vec!["Brand Sans".to_string()])); + let waiting = |db: &FontDb| db.pending.get("brand sans").map(|(_, v)| v.iter().map(|e| e.style.clone()).collect::>()).unwrap_or_default(); + assert_eq!(waiting(&db), ["Black"]); + assert_eq!(db.merge_rescan(found(&[("Brand Sans", &["Regular", "Black"])])), Rescan::default()); + assert_eq!(waiting(&db), ["Black"]); } +/// Font file bytes add their faces once; junk adds nothing. #[test] fn font_bytes_load_into_the_db() { assert!(load_font_bytes(b"not a font".to_vec()).is_empty()); assert!(load_font_bytes(Vec::new()).is_empty()); - // With the embedded fonts (absent on CI builds without craft-fonts): a file's family is added. + // With the embedded fonts (absent on CI builds without craft-fonts): a file's family is added, + // and loading the same file again returns it without adding its faces twice. if let Some(f) = CRAFT_FONTS.first() { let families = load_font_bytes(f.bytes.to_vec()); assert_eq!(families.len(), 1); assert!(families.iter().all(|f| has_family(f))); + let faces = db().read().unwrap().face_count(); + assert_eq!(load_font_bytes(f.bytes.to_vec()), families); + assert_eq!(db().read().unwrap().face_count(), faces); } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index e107593e..667ab731 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -16,8 +16,9 @@ mod onpath; pub use breaks::grapheme_step; pub use color::{ColorBitmap, ColorInk, ColorLayer}; pub use fontdb::{ - Axis, CRAFT_FONTS, Coords, Face, FontDb, NamedInstance, axis_label, db, face_with_char, family_names, family_styles, find_face, has_family, - installed_fonts_known, load_font_bytes, no_coords, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, + Axis, CRAFT_FONTS, Coords, Face, FontDb, NamedInstance, Rescan, axis_label, db, face_with_char, family_names, family_styles, find_face, + has_family, installed_fonts_known, load_font_bytes, no_coords, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, + system_fonts_scanned, }; pub use layout::{Decoration, Glyph, Line, TextLayout, layout}; pub use onpath::OnPath; From 203ec13e03bd70ce696f9afabab48dd49172ce45 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 19 Oct 2026 23:43:40 +0700 Subject: [PATCH 4/6] #821: text.loadFont reads at most MAX_FONT_FILE (the font scan's 256 MiB cap) --- crates/engine/src/cmd/create.rs | 6 ++---- crates/engine/src/cmd/text.rs | 2 +- crates/text/src/fontdb.rs | 8 +++++++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 6ec7d4e5..3a9f6d67 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -362,15 +362,13 @@ fn free_spot(s: &Session, w: f64, h: f64) -> Result<(f64, f64)> { }) } -/// The bytes of the file at `path`, within the session's allowed file roots. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn read_path(path: &str) -> Result> { +fn read_path(path: &str) -> Result> { crate::file_access::read(path) } -/// The browser has no files to read: always an error. #[cfg(target_arch = "wasm32")] -pub(super) fn read_path(path: &str) -> Result> { +fn read_path(path: &str) -> Result> { Err(crate::EngineError::Other(format!("{path}: files can't be read in the browser"))) } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 0f0f003d..6e1f5c3d 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -497,7 +497,7 @@ pub fn specs() -> Vec { let b64 = b64.split_once(',').map(|(_, d)| d.to_string()).unwrap_or(b64); base64::engine::general_purpose::STANDARD.decode(b64.trim()).map_err(|e| bad(cmd, format!("`data`: {e}")))? } else if let Some(path) = string(p, "path") { - super::create::read_path(&path)? + super::file::read_capped(&path, figcraft_text::fontdb::MAX_FONT_FILE)? } else { return Err(bad(cmd, "pass `path` or `data` (base64)")); }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 814d3a2f..604f3eee 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -819,13 +819,19 @@ fn scan_dir(dir: &std::path::Path, depth: usize, out: &mut BTreeMap MAX_FONT_FILE { + continue; + } + let Some(bytes) = usize::try_from(meta.len()).ok().and_then(|l| index_bytes(&path, l)) else { continue }; for (index, family, style) in faces_in(&bytes) { out.entry(family.to_lowercase()).or_insert_with(|| (family.clone(), Vec::new())).1.push(Pending { path: path.clone(), index, style }); } } } +/// The largest font file read (CJK collections run to ~120 MB, Apple Color Emoji ~180 MB). +pub const MAX_FONT_FILE: u64 = 256 * 1024 * 1024; + /// The parts of a font file the scan reads: headers, table directories and `name` tables, at their /// offsets in a zeroed buffer of the file's length (reading whole files was most of the scan). fn index_bytes(path: &std::path::Path, len: usize) -> Option> { From 7126deaed001c6e03c25046a44c80c75e8233ec5 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 19 Oct 2026 23:43:40 +0700 Subject: [PATCH 5/6] #821: es and fi labels for text.rescanFonts, text.loadFont, text.refit --- crates/ui-egui/locales/es.toml | 3 +++ crates/ui-egui/locales/fi.toml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index b4c7c335..1af2f09f 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -2139,6 +2139,7 @@ status = "draft — needs native review" "text.listIndent" = "Aumentar sangría de la lista" "text.listOutdent" = "Reducir sangría de la lista" "text.listStyle" = "Estilo de lista" +"text.loadFont" = "Cargar archivo de fuente" "text.maxLines" = "Máximo de líneas" "text.missingFonts" = "Fuentes que faltan" "text.numberList" = "Lista numerada" @@ -2147,7 +2148,9 @@ status = "draft — needs native review" "text.paragraphSpacing" = "Espacio entre párrafos" "text.pathOptions" = "Opciones de texto en trazado" "text.preview" = "Previsualizar cambio de texto" +"text.refit" = "Ajustar texto a las fuentes" "text.removeFromPath" = "Quitar texto del trazado" +"text.rescanFonts" = "Volver a buscar fuentes instaladas" "text.set" = "Establecer texto" "text.setFeatures" = "Funciones OpenType" "text.setVariations" = "Ejes de fuente variable" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index db5d2579..2dff384b 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -2141,6 +2141,7 @@ status = "draft — needs native review" "text.listIndent" = "Sisennä luettelo" "text.listOutdent" = "Vähennä luettelon sisennystä" "text.listStyle" = "Luettelotyyli" +"text.loadFont" = "Lataa fonttitiedosto" "text.maxLines" = "Rivien enimmäismäärä" "text.missingFonts" = "Puuttuvat fontit" "text.numberList" = "Numeroitu luettelo" @@ -2149,7 +2150,9 @@ status = "draft — needs native review" "text.paragraphSpacing" = "Kappaleväli" "text.pathOptions" = "Tekstipolun asetukset" "text.preview" = "Esikatsele tekstimuutosta" +"text.refit" = "Sovita teksti fontteihin" "text.removeFromPath" = "Poista teksti polulta" +"text.rescanFonts" = "Etsi asennetut fontit uudelleen" "text.set" = "Aseta teksti" "text.setFeatures" = "OpenType-ominaisuudet" "text.setVariations" = "Muuttuvan fontin akselit" From 6325a323eecb26ddf2fdf738e34fbb9230a21b74 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 19 Oct 2026 23:43:41 +0700 Subject: [PATCH 6/6] #821: move the loadFont/rescanFonts test into fonts_tests --- crates/engine/src/fonts_tests.rs | 18 ++++++++++++++++++ crates/engine/src/tests.rs | 18 ------------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/fonts_tests.rs b/crates/engine/src/fonts_tests.rs index 463fb904..0fe6dcb3 100644 --- a/crates/engine/src/fonts_tests.rs +++ b/crates/engine/src/fonts_tests.rs @@ -195,3 +195,21 @@ fn refit_reaches_text_in_instances() { assert_eq!(refitted(&r), vec![copy.0]); assert_eq!(width(&s, copy), want); } + +/// `text.loadFont` refuses what isn't a font file; `text.rescanFonts` reports what it added. +#[test] +fn fonts_load_from_files_and_rescans_report_new_families() { + let mut s = Session::new(); + assert!(s.execute("text.loadFont", &json!({})).is_err()); + assert!(s.execute("text.loadFont", &json!({"data": "bm90IGEgZm9udA=="})).is_err(), "not a font file"); + assert!(s.execute("text.loadFont", &json!({"data": "%%%"})).is_err()); + assert!(s.execute("text.loadFont", &json!({"path": "no-such-dir/x.ttf"})).is_err()); + if let Some(f) = figcraft_text::CRAFT_FONTS.first() { + use base64::Engine as _; + let data = base64::engine::general_purpose::STANDARD.encode(f.bytes); + let r = s.execute("text.loadFont", &json!({"data": data})).unwrap(); + assert_eq!(r["families"].as_array().map(Vec::len), Some(1)); + } + let r = s.execute("text.rescanFonts", &json!({})).unwrap(); + assert!(r["added"].is_array()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ad3b6aa3..d6e2c9e0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -627,21 +627,3 @@ fn find_replace_changing_only_the_case_replaces_every_occurrence() { assert_eq!(s.doc().unwrap().node(t).unwrap().kind.text().unwrap().characters, "FigCraft and FigCraft, FigCraft"); assert_eq!(s.doc().unwrap().node(f).unwrap().name, "FigCraft / FigCraft"); } - -/// `text.loadFont` refuses what isn't a font file; `text.rescanFonts` reports what it added. -#[test] -fn fonts_load_from_files_and_rescans_report_new_families() { - let mut s = sess(); - assert!(s.execute("text.loadFont", &json!({})).is_err()); - assert!(s.execute("text.loadFont", &json!({"data": "bm90IGEgZm9udA=="})).is_err(), "not a font file"); - assert!(s.execute("text.loadFont", &json!({"data": "%%%"})).is_err()); - assert!(s.execute("text.loadFont", &json!({"path": "no-such-dir/x.ttf"})).is_err()); - if let Some(f) = figcraft_text::CRAFT_FONTS.first() { - use base64::Engine as _; - let data = base64::engine::general_purpose::STANDARD.encode(f.bytes); - let r = s.execute("text.loadFont", &json!({"data": data})).unwrap(); - assert_eq!(r["families"].as_array().map(Vec::len), Some(1)); - } - let r = s.execute("text.rescanFonts", &json!({})).unwrap(); - assert!(r["added"].is_array()); -}