From dd810ea4bb25d596e63bf6e9eb719cf05d1e30bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:30:14 -0800 Subject: [PATCH] .ai save: resolve each run's font once per font Saving a .ai file resolves the font of every run of type twice: once for its font record and once to check that the font comes back as itself. Each resolution looks the face up, reads its axes and name table, and scans the loaded faces by PostScript name, so a document with tens of thousands of runs in a few fonts repeated the same lookups for every run. The text document now keeps what each style's font fields (family, style, version and Variable Font settings, each setting by the bits of its value) resolve to for the whole save, and reuses it while the font database's generation is unchanged. A font added or loaded during the save resolves it again. The font set is still searched and filled as before, so its order, indices and rollback are unchanged. The output is unchanged. - Tests: a save resolves as many fonts for one row of type as for four; the program, header, warnings and private data are the same as with every run's font resolved again (many fonts, threaded type, envelopes of type, and type taken back when an envelope is written as its art); each resolved record and check equals the uncached one for static and variable fonts, settings outside the axis range, not a number, +0 and -0, and a missing family, and a value resolved before the font database changed is resolved again. An ignored test times the save of 10,000 point type objects in three runs over four fonts. --- crates/eps/src/ai_editing/tests.rs | 186 ++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 4 +- crates/eps/src/ai_editing/writer/texts.rs | 155 +++++++++++++++++- 3 files changed, 336 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3ddc8636c8..aa08b3e6b6 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -11170,6 +11170,192 @@ fn variable_font_instances_name_their_design_space() { ); } +/// Style 12 pt black in family `family` and style `style`, with the Variable Font settings `axes`. +fn font_style(family: &str, style: &str, axes: &[(&str, f64)]) -> vectorcraft_doc::CharStyle { + vectorcraft_doc::CharStyle { + font_family: family.into(), + font_style: style.into(), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..style_of(12.0) + } +} + +/// A document of `k` rows 30 pt apart, each with point type in three runs (Source Sans 3 Regular +/// and Bold, and the variable test font's Bold at a weight of 650), point type in four (Inter +/// Medium, the variable test font's Bold at 500 and at a weight that differs from 500 by less than +/// the font record's precision, and a family that isn't installed), and area type threaded through +/// two frames in Bold and the variable test font's Regular. +fn fonted_document(k: usize) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let (regular, bold) = (style_of(12.0), font_style("Source Sans 3", "Bold", &[])); + let mut doc = Document::new(400.0, 30.0 * k as f64 + 30.0); + let layer = doc.layers[0].id; + for i in 0..k { + let y = 20.0 + 30.0 * i as f64; + let mut three = TextObject::point(Point::new(10.0, y), "", regular.clone()); + three.runs = vec![ + TextRun::new("One ", regular.clone()), + TextRun::new("two ", bold.clone()), + TextRun::new("three", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)])), + ]; + let mut four = TextObject::point(Point::new(100.0, y), "", regular.clone()); + four.runs = vec![ + TextRun::new("four ", font_style("Inter", "Medium", &[])), + TextRun::new("five ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.0)])), + TextRun::new("six ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.000_001)])), + TextRun::new("seven", font_style("No Such Family", "Bold", &[])), + ]; + let mut first = TextObject::point(Point::ZERO, "", bold.clone()); + first.runs = vec![TextRun::new("eight nine ", bold.clone()), TextRun::new("ten", font_style(VARIABLE_FAMILY, "Regular", &[]))]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(250.0, y - 10.0, 315.0, y + 10.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("", bold.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(325.0, y - 10.0, 390.0, y + 10.0)) }; + let nodes = [text_node(&mut doc, three), text_node(&mut doc, four), text_node(&mut doc, first), text_node(&mut doc, second)]; + doc.text_threads.push(vec![nodes[2].id, nodes[3].id]); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + doc +} + +/// A save resolves the font of each style once, however many runs are set in it: as many fonts are +/// resolved (font records and checks that a font comes back) for one row of type as for four. Two +/// weights of a variable font that the font record writes as one number are one font written. +#[test] +fn a_save_resolves_each_font_once() { + // How many fonts a save of `doc` resolves, in a save during which the font database didn't change. + let resolves = |doc: &Document| { + let db = vectorcraft_text::FontDb::global(); + for _ in 0..20 { + let before = db.generation(); + writer::FONT_RESOLVES.set(0); + export_ai_editing(doc, &opts()).unwrap(); + if db.generation() == before { + return writer::FONT_RESOLVES.get(); + } + } + panic!("the font database changed during every save"); + }; + let one = resolves(&fonted_document(1)); + let doc = fonted_document(4); + let four = resolves(&doc); + assert!(one > 0); + assert_eq!(four, one, "fonts resolved with one row of type and with four"); + let td = text_document(&program(&doc)); + // 650 × 65536 and 500 × 65536. + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 42598400 ]").count(), 1, "{td}"); + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 32768000 ]").count(), 1, "{td}"); + assert_eq!(td.matches("/CoolTypeFont").count(), 8, "seven fonts and the hidden characters' font: {td}"); +} + +/// A save that resolves each style's font once writes the same program, header, warnings and private +/// data as one that resolves the font of every run again: with type in many fonts, threaded type, +/// type in envelopes, and type taken out again when an envelope is written as its art. +#[test] +fn a_save_writes_the_same_with_each_font_resolved_once() { + use vectorcraft_doc::live::EnvelopeKind; + let save = |doc: &Document, each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + let mut docs = vec![sample(), typed(), fonted_document(3)]; + for (_, kind) in live_envelope_kinds() { + for editing in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind.clone(), editing); + docs.push(alone(envelope)); + } + } + for doc in &docs { + let (once, again) = (save(doc, false), save(doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } + // An envelope of type one object short of room: it is written as its art, and its story and fonts + // are taken out again. + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind, false); + let doc = alone(envelope); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let within = |each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.warnings) + }; + let (once, again) = (within(false), within(true)); + assert!(once.1.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", once.1); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); +} + +/// The CPU time of saving a document of 10,000 point type objects, each in three runs drawn in turn +/// from four fonts (Source Sans 3 Regular and Bold, Inter Medium, and the variable test font's Bold +/// at a weight of 650), with each style's font resolved once and with the font of every run +/// resolved again: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture font_resolve_time`. +#[test] +#[ignore = "timing; run by hand"] +fn font_resolve_time() { + use vectorcraft_doc::{TextObject, TextRun}; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let fonts = [ + style_of(12.0), + font_style("Source Sans 3", "Bold", &[]), + font_style("Inter", "Medium", &[]), + font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)]), + ]; + let mut doc = Document::new(2000.0, 2000.0); + let layer = doc.layers[0].id; + for i in 0..10_000usize { + let (x, y) = ((i % 100) as f64 * 20.0, (i / 100) as f64 * 20.0 + 10.0); + let mut t = TextObject::point(vectorcraft_geom::Point::new(x, y), "", fonts[0].clone()); + t.runs = (0..3).map(|r| TextRun::new(["ab ", "cd ", "ef"][r], fonts[(i + r) % fonts.len()].clone())).collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + // A first save loads the faces the document names. + export_ai_editing(&doc, &opts()).unwrap(); + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut resolves = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, each_run) in [(0, true), (1, false)] { + writer::RESOLVE_EACH_RUN.set(each_run); + writer::FONT_RESOLVES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + resolves[k] = writer::FONT_RESOLVES.get(); + outputs[k] = out.program; + } + } + writer::RESOLVE_EACH_RUN.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "resolved for every run"), (1, "resolved once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} fonts resolved, runs {}", times[k][3] as f64 / 1e6, resolves[k], ms.join(" ")); + } +} + fn style_of(size: f64) -> vectorcraft_doc::CharStyle { style(size, Color::BLACK) } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 39c3157350..a5a592118c 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -50,7 +50,7 @@ pub(super) use paints::{ #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] -pub(super) use texts::TYPE_ATTRIBUTES; +pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; @@ -1604,7 +1604,7 @@ impl<'a> Writer<'a> { let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { - self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) + self.texts.add(t, self.canvas).map(|story| ((story, 0), self.texts.loses(t))) }; let Some(((story, frame), lost)) = placed else { // The text document can't hold it: the outlines count their own objects. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index e9d2dcf38c..226e90b4d2 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -445,8 +445,9 @@ fn held_aki(v: f64) -> f64 { if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } } -/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? -pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { +/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the +/// fonts already resolved. +fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; // A run's style as the text document holds it: every other attribute at its default. A color @@ -484,7 +485,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { ..CharStyle::default() } }; - let run_lost = |s: &CharStyle| { + let mut run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. let unstroked = CharStyle::default(); @@ -501,7 +502,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); - s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) + s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of // its direction (Auto) without a direction of its own, it comes back aligned left, which @@ -669,6 +670,84 @@ fn font_kept(st: &CharStyle) -> bool { && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } +/// The font fields of a style, as [`ResolvedFonts`] keeps what they resolve to: the family, style +/// and version, and each Variable Font setting as the bits of its value, so two settings that +/// differ are two keys even where they are written as one number. +#[derive(PartialEq, Eq, Hash)] +struct FontKey { + family: String, + style: String, + version: Option, + axes: Vec<(String, u64)>, +} + +impl FontKey { + fn of(st: &CharStyle) -> Self { + FontKey { + family: st.font_family.clone(), + style: st.font_style.clone(), + version: st.font_version.clone(), + axes: st.font_axes.iter().map(|(tag, v)| (tag.clone(), v.to_bits())).collect(), + } + } +} + +/// What one style's font fields resolved to, each with the font database's generation +/// ([`vectorcraft_text::FontDb::generation`]) when it was resolved. +#[derive(Default)] +struct Resolved { + /// Its font record ([`font_name`]). + record: Option<(u64, FontRecord)>, + /// Whether its font comes back as itself ([`font_kept`]). + kept: Option<(u64, bool)>, +} + +/// The fonts of the styles written so far, each resolved once for the whole save. A value is used +/// again only while the font database's generation is the one it was resolved in: fonts added or +/// loaded since then resolve it again. +#[derive(Default)] +struct ResolvedFonts(HashMap); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`ResolvedFonts`] keeps nothing: every run's font is resolved again. + pub(in crate::ai_editing) static RESOLVE_EACH_RUN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`ResolvedFonts`] has resolved a font record or checked a font on this thread. + pub(in crate::ai_editing) static FONT_RESOLVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl ResolvedFonts { + /// The value `slot` holds for the font of style `st` when it was resolved in the font + /// database's current generation, else `resolve(st)`, kept for later runs. + fn get(&mut self, st: &CharStyle, slot: fn(&mut Resolved) -> &mut Option<(u64, T)>, resolve: fn(&CharStyle) -> T) -> &T { + let now = vectorcraft_text::FontDb::global().generation(); + let held = slot(self.0.entry(FontKey::of(st)).or_default()); + #[cfg(test)] + if RESOLVE_EACH_RUN.get() { + *held = None; + } + if held.as_ref().is_some_and(|(generation, _)| *generation != now) { + *held = None; + } + let (_, value) = held.get_or_insert_with(|| { + #[cfg(test)] + FONT_RESOLVES.set(FONT_RESOLVES.get() + 1); + (now, resolve(st)) + }); + value + } + + /// The font record of style `st` ([`font_name`]). + fn record(&mut self, st: &CharStyle) -> &FontRecord { + self.get(st, |r| &mut r.record, font_name) + } + + /// Whether the font of style `st` comes back as itself ([`font_kept`]). + fn kept(&mut self, st: &CharStyle) -> bool { + *self.get(st, |r| &mut r.kept, font_kept) + } +} + /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo /// and their presentation forms) or a strong left-to-right one (`Some(false)`: any other letter). fn strong_direction(c: char) -> Option { @@ -761,6 +840,8 @@ pub(in crate::ai_editing) struct TextDoc { /// reader counts in them. doc_bytes: usize, doc_values: usize, + /// The fonts of the styles written so far, as they resolve. + resolved: ResolvedFonts, } impl TextDoc { @@ -768,9 +849,14 @@ impl TextDoc { self.stories.is_empty() } + /// Has type `t` attributes the text document leaves out ([`loses`])? + pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { + loses(t, &mut self.resolved) + } + /// The index of the font of `st` in the font set. fn font(&mut self, st: &CharStyle) -> i64 { - let font = font_name(st); + let font = self.resolved.record(st); // Two installed versions of one font are two fonts, so each keeps its own `/5`. let same = |f: &FontRecord| { f.name == font.name && f.version == font.version && f.design.iter().map(|v| fixed(*v)).eq(font.design.iter().map(|v| fixed(*v))) @@ -778,7 +864,7 @@ impl TextDoc { let i = match self.fonts.iter().position(same) { Some(i) => i, None => { - self.fonts.push(font); + self.fonts.push(font.clone()); self.fonts.len() - 1 } }; @@ -1156,7 +1242,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1351,3 +1437,58 @@ pub(in crate::ai_editing) fn stub(s: &mut String, story: usize, frame: usize, t: } s.push_str("2 /TextAntialiasing ,\n;\n"); } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style's font resolved through [`ResolvedFonts`], the first time and again, is the font + /// record and the check [`font_name`] and [`font_kept`] give for it: static and variable fonts, + /// a version of their own, Variable Font settings within and outside the axis's range, not a + /// number, +0 and -0, an axis the font doesn't have, and a family that isn't installed. A font + /// resolved before the font database last changed is resolved again. + #[test] + fn resolved_fonts_are_the_fonts_resolved_for_each_run() { + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let font = |family: &str, style: &str, version: Option<&str>, axes: &[(&str, f64)]| CharStyle { + font_family: family.into(), + font_style: style.into(), + font_version: version.map(str::to_owned), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..CharStyle::default() + }; + let styles = [ + CharStyle::default(), + font("Source Sans 3", "Bold", None, &[]), + font("Inter", "Medium", None, &[]), + font(VARIABLE_FAMILY, "Regular", None, &[]), + font(VARIABLE_FAMILY, "Bold", Some("Version 1.000"), &[]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 650.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 900.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", f64::NAN)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", -0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wdth", 80.0), ("wght", 500.0)]), + font("No Such Family", "Bold", None, &[]), + font("No Such Family", "", Some("2.0"), &[]), + ]; + let mut fonts = ResolvedFonts::default(); + for round in ["first", "again"] { + for st in &styles { + assert_eq!(fonts.record(st), &font_name(st), "{round}: {st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{round}: {st:?}"); + } + } + assert_eq!(fonts.0.len(), styles.len(), "each style's font fields are a key of their own"); + // What was resolved before the font database last changed is resolved again. + let stale = vectorcraft_text::FontDb::global().generation().wrapping_sub(1); + let wrong = FontRecord { name: "Wrong".into(), truetype: false, design: vec![], version: String::new() }; + for st in &styles { + let held = fonts.0.entry(FontKey::of(st)).or_default(); + (held.record, held.kept) = (Some((stale, wrong.clone())), Some((stale, !font_kept(st)))); + assert_eq!(fonts.record(st), &font_name(st), "{st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{st:?}"); + } + } +}