mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 04:51:52 +00:00
Merge pull request #8472 from dotCooCoo/perf/ai-save-font-record-once
.ai save: resolve each run's font once per font
This commit is contained in:
@@ -11394,6 +11394,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::<u64>().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<u64>; 2] = [vec![], vec![]];
|
||||
let mut resolves = [0, 0];
|
||||
let mut outputs: [Vec<u8>; 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<String> = 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)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! [`crate::ai_editing`] for the form). Each style is read back before it is written
|
||||
//! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic
|
||||
//! style, with the object's own gradient): one that reads back differently is not written, and the
|
||||
//! object is written as its drawn look alone. Each style text is parsed once per save ([`Parsed`]).
|
||||
//! object is written as its drawn look alone. Style texts are kept parsed for the save, up to a
|
||||
//! limit ([`Parsed`]).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
@@ -172,15 +173,27 @@ pub(in crate::ai_editing) struct Styles {
|
||||
next_anon: u64,
|
||||
/// How many objects were written with the graphic style they are linked to.
|
||||
pub(super) links_written: usize,
|
||||
/// Every style text checked so far, as the reader parses it.
|
||||
/// The style texts checked so far, as the reader parses them.
|
||||
pub(super) parsed: Parsed,
|
||||
}
|
||||
|
||||
/// Style texts as the reader parses them ([`crate::import::parse_art_style`]), each parsed once
|
||||
/// however many styles and objects are checked with it; a text the reader doesn't parse is kept
|
||||
/// as `None`.
|
||||
/// The most style texts [`Parsed`] keeps parsed in one save.
|
||||
const MAX_PARSED: usize = 4096;
|
||||
/// The most bytes of style text [`Parsed`] keeps parsed in one save.
|
||||
const MAX_PARSED_BYTES: usize = 8 << 20;
|
||||
|
||||
/// Style texts as the reader parses them ([`crate::import::parse_art_style`]). The first
|
||||
/// [`MAX_PARSED`] texts, up to [`MAX_PARSED_BYTES`] bytes in all, are each parsed once however many
|
||||
/// styles and objects are checked with them; a text the reader doesn't parse is kept as `None`.
|
||||
/// Past that, only the last text checked is kept, and each other text is parsed again when checked.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Parsed(HashMap<String, Option<crate::import::ParsedStyle>>);
|
||||
pub(super) struct Parsed {
|
||||
kept: HashMap<String, Option<crate::import::ParsedStyle>>,
|
||||
/// The bytes of the texts in `kept`.
|
||||
bytes: usize,
|
||||
/// The last text checked that `kept` doesn't hold, with its parse.
|
||||
last: Option<(String, Option<crate::import::ParsedStyle>)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
@@ -192,14 +205,21 @@ impl Parsed {
|
||||
/// Style text `text` as the reader parses it (`None` when it doesn't).
|
||||
pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> {
|
||||
#[cfg(test)]
|
||||
if REPARSE.get() {
|
||||
self.0.remove(text);
|
||||
let reparse = REPARSE.get();
|
||||
#[cfg(not(test))]
|
||||
let reparse = false;
|
||||
if !reparse && self.kept.contains_key(text) {
|
||||
return self.kept.get(text).and_then(Option::as_ref);
|
||||
}
|
||||
if !self.0.contains_key(text) {
|
||||
if reparse || self.last.as_ref().is_none_or(|(last, _)| last != text) {
|
||||
let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x");
|
||||
self.0.insert(text.to_owned(), parsed);
|
||||
if !reparse && self.kept.len() < MAX_PARSED && self.bytes.saturating_add(text.len()) <= MAX_PARSED_BYTES {
|
||||
self.bytes += text.len();
|
||||
return self.kept.entry(text.to_owned()).or_insert(parsed).as_ref();
|
||||
}
|
||||
self.last = Some((text.to_owned(), parsed));
|
||||
}
|
||||
self.0.get(text).and_then(Option::as_ref)
|
||||
self.last.as_ref().and_then(|(_, parsed)| parsed.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1071,3 +1091,52 @@ pub(super) fn near(a: &Value, b: &Value) -> bool {
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A style text after its name: a stroke `width` pt wide.
|
||||
fn stroke_style(width: usize) -> String {
|
||||
format!(
|
||||
"/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\
|
||||
; /Dict ;\n /Part ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// `text` parsed on its own, as the reader parses it.
|
||||
fn fresh(text: &str) -> String {
|
||||
format!("{:?}", crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"))
|
||||
}
|
||||
|
||||
/// A save that checks more distinct style texts than [`Parsed`] keeps, stroke styles and texts
|
||||
/// that aren't styles, keeps at most [`MAX_PARSED`] texts and [`MAX_PARSED_BYTES`] bytes, and each
|
||||
/// check still gives the text's own parse, kept or not, the first time and again.
|
||||
#[test]
|
||||
fn parsed_styles_kept_in_a_save_stay_within_the_limits() {
|
||||
let mut parsed = Parsed::default();
|
||||
for i in 0..MAX_PARSED + 100 {
|
||||
let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") };
|
||||
let got = format!("{:?}", parsed.get(&text).cloned());
|
||||
assert_eq!(got, fresh(&text), "{i}");
|
||||
assert_eq!(format!("{:?}", parsed.get(&text).cloned()), got, "{i}");
|
||||
assert!(parsed.kept.len() <= MAX_PARSED && parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} texts", parsed.kept.len());
|
||||
}
|
||||
assert_eq!(parsed.kept.len(), MAX_PARSED);
|
||||
for i in [0, 1, MAX_PARSED - 1, MAX_PARSED, MAX_PARSED + 98, MAX_PARSED + 99] {
|
||||
let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") };
|
||||
assert_eq!(format!("{:?}", parsed.get(&text).cloned()), fresh(&text), "{i}");
|
||||
}
|
||||
|
||||
let mut parsed = Parsed::default();
|
||||
let long = |i: usize| format!("{i} {}", "x".repeat(1 << 20));
|
||||
for i in 0..MAX_PARSED_BYTES / (1 << 20) + 4 {
|
||||
assert_eq!(format!("{:?}", parsed.get(&long(i)).cloned()), fresh(&long(i)), "{i}");
|
||||
assert!(parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} bytes", parsed.bytes);
|
||||
assert_eq!(parsed.bytes, parsed.kept.keys().map(String::len).sum::<usize>());
|
||||
}
|
||||
assert!(parsed.kept.len() < MAX_PARSED_BYTES / (1 << 20));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String>,
|
||||
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<FontKey, Resolved>);
|
||||
|
||||
#[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<bool> = 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<usize> = 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<T>(&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<bool> {
|
||||
@@ -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
|
||||
}
|
||||
};
|
||||
@@ -1157,7 +1243,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<usize> = texts.iter().map(|t| self.frame(t, canvas, scale)).collect();
|
||||
let story = self.story(&whole, &frames, scale);
|
||||
if !self.fits(mark) {
|
||||
@@ -1352,3 +1438,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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user