diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 8a808b5f72..f8bc712117 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -103,20 +103,23 @@ impl Writer<'_> { || t.stacks_warichu() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; - let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; + // Every writer below draws this one layout of the type. + let db = vectorcraft_text::FontDb::global(); + let lay = vectorcraft_text::layout(db, t); + let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t, &lay) } else { w.text(n, t, &lay) }; let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()); // Live type with an inside or outside character stroke writes that stroke apart from the // text, in the group. let apart = !outlined && t.runs.iter().any(|r| aligned(&r.style)); if !painted && !inline && !apart { + #[cfg(test)] + DRAW_HANDED.with(|d| d.set(true)); return chars(self, n); } let id = self.id_attr(n); let a = self.attrs(&css::transparency(n)); self.line(&format!("")); self.depth += 1; - let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut all = lay.to_bezpath(); for (_, bar) in vectorcraft_text::decorations(&lay, db, t) { all.extend(bar.iter()); @@ -154,14 +157,22 @@ impl Writer<'_> { } /// Text as glyph outlines: one compound path per run, painted like the run (gradients span - /// the whole text), over its colour glyphs, as on the canvas. - fn text_outlines(&mut self, n: &Node, t: &TextObject) { + /// the whole text), over its colour glyphs, as on the canvas. `lay` is the layout of `t`. + fn text_outlines(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; + // Each run's glyphs, in layout order. + let mut run_glyphs = vec![Vec::new(); t.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } // Underline and strikethrough bars join their run's outlines; ruby glyphs are painted // with the run of the text they annotate. - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); for (run, outline) in lay .glyphs .iter() @@ -197,10 +208,10 @@ impl Writer<'_> { // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + for ((bp, run), glyphs) in runs.iter().zip(&t.runs).zip(&run_glyphs) { // Colour glyphs paint themselves, under their run's paint: bitmap glyphs (emoji) as // their images, COLR and SVG glyphs as their art. - for g in lay.glyphs.iter().filter(|g| g.run == i) { + for g in glyphs { if let Some((image, to_text)) = g.placed_image() { let m = self.matrix(self.xf * to_text); let href = self.blob_href(&image.blob); @@ -233,40 +244,42 @@ impl Writer<'_> { /// spacing come out as on the canvas. Centred and right-aligned lines are anchored /// (`text-anchor`) at their centre or right end, so they stay aligned in a viewer whose font /// differs; other lines are placed where each style run (and, justified, each word) starts. - fn text(&mut self, n: &Node, t: &TextObject) { + /// `lay` is the layout of `t`. + fn text(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { // Live SVG text is written in logical order from left-aligned pieces: bidirectional text // (and right-to-left paragraphs) keep their look as outlines until it is written with // `direction`/`unicode-bidi`. So do runs set Right to Left (Character Direction), whose // `direction="rtl"` would anchor their pieces at the right end. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut again = None; + let lay = handed(t, lay, &mut again); let rtl_runs = t.runs.iter().any(|r| r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft)); if lay.glyphs.iter().any(|g| g.rtl) || lay.lines.iter().any(|l| l.rtl) || rtl_runs { self.warn("bidirectional text is outlined to preserve shaping and visual order"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } if let TextKind::OnPath { path, start, end } = &t.kind { // A reader lays a ``'s glyphs straight: joined glyphs bent along the path // keep their look as outlines. if lay.glyphs.iter().any(|g| g.bend.is_some()) { self.warn("joined type bent along a path is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // `` has a start offset only: an end bracket, Align to Path and Spacing // keep their look as outlines. if end.is_some() || t.path_align != vectorcraft_doc::PathAlign::Baseline || t.path_spacing != 0.0 { self.warn("type on a path with an end bracket, Align to Path or Spacing is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A reader turns each `` glyph with the path, as Rainbow does: Skew, 3D // Ribbon, Stair Step and Gravity keep their look as outlines. if t.path_effect != vectorcraft_doc::PathEffect::Rainbow { self.warn("type on a path with an effect other than Rainbow is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // It cannot hang glyphs outside the start bracket either. - if hangs_on_path(t, &lay) { + if hangs_on_path(t, lay) { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // The space before the first character is written as its `dx`; one before a character // after a line break, which the `` writes as a space, keeps its look as outlines. @@ -279,39 +292,39 @@ impl Writer<'_> { }); if spaced_break { self.warn("type on a path with space before a character after a line break is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` places its characters one after the other: Insert Aki keeps its look as // outlines. if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) { self.warn("type on a path with Insert Aki is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Tsume does as well. if t.runs.iter().any(|r| r.style.tsume != 0.0) { self.warn("type on a path with Tsume is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Justification…'s Desired word and letter spacing and glyph scaling do too. if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) { self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { self.warn("type on a path with bullets or numbers is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). if !lay.repeat_marks.is_empty() { self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } - return self.text_on_path(n, t, path, *start); + return self.text_on_path(n, t, lay, path, *start); } - self.note_fonts(t, &lay); - let lines = text_lines(t, &lay, self.opts.fewer_tspans); + self.note_fonts(t, lay); + let lines = text_lines(t, lay, self.opts.fewer_tspans); // `drawn` holds the styles the layout draws the text in: Shrink Text to Fit scales its sizes, explicit leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -374,35 +387,36 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } - /// The inside and outside character strokes of live type `t`, over its text (which goes - /// without them, see [`Self::char_props`]): each such run's stroke on its glyph outlines, drawn - /// twice as wide and clipped or masked to its side as aligned path strokes are + /// The inside and outside character strokes of live type `t`, laid out as `lay`, over its text + /// (which goes without them, see [`Self::char_props`]): each such run's stroke on its glyph + /// outlines, drawn twice as wide and clipped or masked to its side as aligned path strokes are /// ([`Self::side_attr`]). The text stays live; only the stroke follows the outlines. - fn aligned_char_strokes(&mut self, t: &TextObject) { + fn aligned_char_strokes(&mut self, t: &TextObject, lay: &vectorcraft_text::TextLayout) { if !t.runs.iter().any(|r| aligned(&r.style)) { return; } + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); + // Each such run's glyph outlines and then its bars, in layout order. + let mut outlines = vec![BezPath::new(); t.runs.len()]; + for (run, outline) in lay.glyphs.iter().map(|g| (g.run, &g.outline)).chain(bars.iter().map(|(r, b)| (*r, b))) { + if let Some(bp) = outlines.get_mut(run).filter(|_| t.runs.get(run).is_some_and(|r| aligned(&r.style))) { + bp.extend(outline.iter()); + } + } // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, run) in t.runs.iter().enumerate().filter(|(_, r)| aligned(&r.style)) { - let mut bp = BezPath::new(); - for g in lay.glyphs.iter().filter(|g| g.run == i) { - bp.extend(g.outline.iter()); - } - for (_, bar) in bars.iter().filter(|(r, _)| *r == i) { - bp.extend(bar.iter()); - } + for (run, bp) in t.runs.iter().zip(&outlines).filter(|(r, _)| aligned(&r.style)) { if bp.elements().is_empty() { continue; } - let pd = PathData::from_bezpath(&bp); + let pd = PathData::from_bezpath(bp); let ap = vectorcraft_doc::Appearance { items: vec![AppearanceItem::Stroke(run.style.stroke_layer())], ..Default::default() }; let d = self.path_d(&pd, self.xf); self.shape(&Node::path(NodeId(u64::MAX), pd.clone(), ap), &d, None, &[&pd], FillRule::NonZero, Some(lay.bounds)); @@ -574,15 +588,16 @@ impl Writer<'_> { rules } - /// Type on a path: a `` along the path (a def). - fn text_on_path(&mut self, n: &Node, t: &TextObject, path: &PathData, start: f64) { + /// Type on a path, laid out as `lay`: a `` along the path (a def). + fn text_on_path(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout, path: &PathData, start: f64) { let id = self.id_attr(n); let pid = self.fresh_id("text-path"); let d = self.path_d(path, self.xf * t.xf); self.def(1, &format!("")); // The element's user space is the document's; gradients span the laid-out text. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - self.note_fonts(t, &lay); + let mut again = None; + let lay = handed(t, lay, &mut again); + self.note_fonts(t, lay); // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -626,7 +641,7 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } } @@ -635,6 +650,34 @@ fn aligned(st: &CharStyle) -> bool { st.has_stroke() && st.stroke_align != StrokeAlign::Center } +#[cfg(test)] +thread_local! { + /// Tests: each type writer lays `t` out again ([`handed`]) instead of drawing the layout it is + /// handed, so a test can compare the two. The first writer of type written without a group + /// still draws the layout it is handed ([`DRAW_HANDED`]), so each object is laid out where it + /// is drawn. + static LAY_OUT_AGAIN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the next type writer draws the layout it is handed, with [`LAY_OUT_AGAIN`] too. + static DRAW_HANDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The layout a type writer draws: `lay`, the layout of `t` it is handed. In tests that ask for it, +/// `t` laid out again, kept in `again`. +fn handed<'a>( + t: &TextObject, + lay: &'a vectorcraft_text::TextLayout, + again: &'a mut Option, +) -> &'a vectorcraft_text::TextLayout { + #[cfg(test)] + let lay = { + let draw_handed = DRAW_HANDED.with(|d| d.replace(false)); + if LAY_OUT_AGAIN.with(std::cell::Cell::get) && !draw_handed { &*again.insert(vectorcraft_text::layout(FontDb::global(), t)) } else { lay } + }; + #[cfg(not(test))] + let _ = (t, again); + lay +} + /// Does type on a path `t`, laid out as `lay`, hang glyphs outside its brackets? It does when /// Optical Margin Alignment or its first paragraph's Roman Hanging Punctuation is on and its /// glyphs sit elsewhere with both off. diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index 951817c2c5..6b2fcbfb1f 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -1,5 +1,7 @@ //! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid //! out again each time, which happens only when a reader sets the type differently from its layout. +//! The type writers draw one layout of the type ([`handed`]) and write what laying it out in each +//! writer writes. use super::*; use vectorcraft_doc::text::{Bullet, ParaList}; @@ -145,3 +147,202 @@ fn a_mixed_document_lays_out_again_only_the_japanese_type() { let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); assert_eq!(again, 1, "{svg}"); } + +/// Type `t`, with the object's own fills and strokes `items`, alone in a document. +fn doc_of(t: TextObject, items: Vec) -> Document { + let mut d = Document::new(300.0, 200.0); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// Type on a straight path across the page. +fn on_path(text: &str, st: CharStyle) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, st); + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t +} + +/// A character style with a stroke on side `align`. +fn stroked(align: StrokeAlign) -> CharStyle { + CharStyle { stroke: Paint::solid(vectorcraft_color::Color::rgb8(200, 0, 0)), stroke_width: 2.0, stroke_align: align, ..style() } +} + +fn red_fill() -> Vec { + vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))))] +} + +/// The type the writers handle differently, each with how many times its export lays the type +/// out: once, plus the layout of the copy that checks for hanging glyphs on a path; and how many +/// times with each writer laying the type out on its own ([`LAY_OUT_AGAIN`]). +fn writer_cases() -> Vec<(&'static str, Document, crate::ExportOptions, u64, u64)> { + let opts = crate::ExportOptions::default; + let outlined = || crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }; + let mut runs = point("Red "); + runs.runs.push(TextRun::new("green ", CharStyle { underline: true, ..stroked(StrokeAlign::Outside) })); + runs.runs.push(TextRun::new("blue", CharStyle { strikethrough: true, ..style() })); + let mut many = point(""); + many.runs = (0..200).map(|i| TextRun::new(if i % 7 == 6 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 5), ..style() })).collect(); + let mut rtl_run = point("abc"); + rtl_run.runs[0].style.char_direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + let mut skewed = on_path("Skewed", style()); + skewed.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut hanging = on_path("\u{201C}Quoted.\u{201D}", style()); + hanging.optical_margin = true; + let mut inside = point("Inside out"); + inside.runs.push(TextRun::new(" plain", style())); + inside.runs[0].style = CharStyle { underline: true, ..stroked(StrokeAlign::Inside) }; + let outside = TextObject::point(Point::new(20.0, 20.0), "Outside", stroked(StrokeAlign::Outside)); + vec![ + ("point type", doc_of(point("Plain type"), vec![]), opts(), 1, 1), + ("point type with a fill", doc_of(point("Filled type"), red_fill()), opts(), 1, 2), + ("type on a path", doc_of(on_path("Type on a path", style()), vec![]), opts(), 1, 2), + ("type on a path with a fill", doc_of(on_path("Filled path type", style()), red_fill()), opts(), 1, 3), + ("bidirectional type", doc_of(point("abc \u{5D0}\u{5D1}\u{5D2} def"), vec![]), opts(), 1, 2), + ("a run set right to left", doc_of(rtl_run, vec![]), opts(), 1, 2), + ("bidirectional type on a path", doc_of(on_path("abc \u{5D0}\u{5D1}\u{5D2}", style()), vec![]), opts(), 1, 2), + ("type on a path with Skew", doc_of(skewed, vec![]), opts(), 1, 2), + ("type on a path that may hang", doc_of(hanging, vec![]), opts(), 2, 3), + ("outside character stroke", doc_of(outside, vec![]), opts(), 1, 3), + ("inside character stroke", doc_of(inside, vec![]), opts(), 1, 3), + ("runs with a stroke and decorations", doc_of(runs.clone(), vec![]), opts(), 1, 3), + ("runs as outlines", doc_of(runs.clone(), vec![]), outlined(), 1, 1), + ("outside stroke on a path with a fill", doc_of(on_path("Stroked", stroked(StrokeAlign::Outside)), red_fill()), opts(), 1, 4), + ("inside stroke on a path", doc_of(on_path("Stroked", stroked(StrokeAlign::Inside)), vec![]), opts(), 1, 4), + ("many runs as outlines", doc_of(many.clone(), vec![]), outlined(), 1, 1), + ("many runs", doc_of(many, vec![]), opts(), 1, 1), + ] +} + +/// SVG export of `d` with each type writer laying the type out again (`again`) or drawing the +/// layout it is handed, and how many times the export laid type out. +fn export_counting(d: &Document, opts: &crate::ExportOptions, again: bool) -> (crate::Output, u64) { + LAY_OUT_AGAIN.with(|a| a.set(again)); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let out = crate::export_full(d, opts, None); + let laid = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + LAY_OUT_AGAIN.with(|a| a.set(false)); + (out, laid) +} + +#[test] +fn every_type_writer_draws_one_layout() { + for (name, d, opts, layouts, own_layouts) in writer_cases() { + let (out, laid) = export_counting(&d, &opts, false); + assert_eq!(laid, layouts, "{name}: {}", out.svg); + // The same file and warnings as each writer laying the type out on its own. + let (again, laid_again) = export_counting(&d, &opts, true); + assert_eq!(laid_again, own_layouts, "{name}"); + assert_eq!(out.svg, again.svg, "{name}"); + assert_eq!(out.warnings, again.warnings, "{name}"); + assert_eq!(out.setting_notes, again.setting_notes, "{name}"); + } +} + +/// The CPU time this thread has run, from Linux's scheduler statistics; wall time elsewhere. +fn thread_time(start: std::time::Instant) -> std::time::Duration { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .map_or_else(|| start.elapsed(), std::time::Duration::from_nanos) +} + +fn median(mut v: Vec) -> std::time::Duration { + v.sort(); + v[v.len() / 2] +} + +/// Timing, not a check: SVG export of a large document with each writer laying the type out again +/// and with one layout handed to them, alternating, seven runs each; and grouping the glyphs of +/// type with 1,000 runs by run, one filter per run against one pass. Run with +/// `cargo test --release -p vectorcraft-svg --lib svg_type_layout_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing"] +fn svg_type_layout_timing() { + let mut d = Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let add = |d: &mut Document, t: TextObject, items: Vec| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + let words: String = "Type set along a path for timing. ".chars().cycle().take(60).collect(); + for _ in 0..1000 { + add(&mut d, on_path(&words, style()), vec![]); + } + let hebrew = "abc \u{5D0}\u{5D1}\u{5D2}\u{5D3} def ".repeat(6); + for _ in 0..1000 { + add(&mut d, point(&hebrew.chars().take(80).collect::()), vec![]); + } + for _ in 0..300 { + add(&mut d, TextObject::point(Point::new(20.0, 20.0), "Stroked outside", stroked(StrokeAlign::Outside)), vec![]); + } + let mut runs = point(""); + runs.runs = (0..1000).map(|i| TextRun::new(if i % 9 == 8 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 3), ..style() })).collect(); + let mut outlined = Document::new(2000.0, 2000.0); + let ol = outlined.layers[0].id; + for _ in 0..300 { + let n = Node::new(outlined.alloc_id(), NodeKind::Text(Box::new(runs.clone()))); + outlined.insert(Some(ol), usize::MAX, n).unwrap(); + } + let docs = [ + ("1,000 on a path, 1,000 bidirectional, 300 outside strokes", &d, crate::ExportOptions::default()), + ("300 texts of 1,000 runs as outlines", &outlined, crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }), + ]; + for (name, doc, opts) in docs { + let (one, again) = (export_counting(doc, &opts, false), export_counting(doc, &opts, true)); + assert_eq!(one.0.svg, again.0.svg, "{name}"); + let (mut base, mut handed) = (vec![], vec![]); + for _ in 0..7 { + for (again, times) in [(true, &mut base), (false, &mut handed)] { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + let _ = export_counting(doc, &opts, again); + times.push(thread_time(start) - t0); + } + } + let (from, to, base_median, handed_median) = (again.1, one.1, median(base.clone()), median(handed.clone())); + println!( + "{name}: layouts {from} -> {to}; laid out again {base:?} (median {base_median:?}); one layout {handed:?} (median {handed_median:?})" + ); + } + // The glyphs of one 1,000-run text, grouped by run 300 times. + let lay = vectorcraft_text::layout(FontDb::global(), &runs); + let (mut filtered, mut bucketed) = (vec![], vec![]); + for _ in 0..7 { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + for i in 0..runs.runs.len() { + for g in lay.glyphs.iter().filter(|g| g.run == i) { + std::hint::black_box(g); + } + } + } + filtered.push(thread_time(start) - t0); + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + let mut run_glyphs = vec![Vec::new(); runs.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } + for g in run_glyphs.iter().flatten() { + std::hint::black_box(g); + } + } + bucketed.push(thread_time(start) - t0); + } + println!( + "grouping 300 texts of 1,000 runs: filter per run {filtered:?} (median {:?}); one pass {bucketed:?} (median {:?})", + median(filtered.clone()), + median(bucketed.clone()) + ); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..45bbff0c80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1973,6 +1973,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). + SVG export lays each type object out once and draws that layout in all of its writers (live text, type on a path, outlines, and inside or outside character strokes), and groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`).