diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 763325f90e..fb7e38bd0f 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -137,6 +137,15 @@ fn text_hash(s: &str) -> u64 { /// The edited text's layout, keyed by [`vectorcraft_text::layout_inputs`] and the text. type CachedLayout = ((u64, TextObject), Arc); +/// The layouts of the frames other than the edited one that the overlays draw (the ports of the +/// selected area type and type on a path, the other frames of a selected story), by frame, each +/// kept with the layout inputs and the text it was made from ([`TypeTool::frame_layout`]). +type FrameLayouts = std::collections::HashMap; + +/// The most other frames' layouts [`TypeTool::frames`] keeps: every port drawn ([`PORTS_MAX`]) +/// and a long story's frames. The frames an overlays call draws past it are laid out on each call. +const FRAME_LAYOUTS_MAX: usize = 2_048; + /// Process-global Type-tool edit-session counter: the IME target's replacement epoch. /// /// A per-tool counter restarts at zero when the tool is recreated (a document switch, File › @@ -220,6 +229,9 @@ pub struct TypeTool { /// The state at the start of each `command.batch` still running, innermost last. batches: Vec, cache: Mutex>, + /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call + /// keeps only the frames it draws. + frames: Mutex, } struct BeforePress { @@ -296,6 +308,28 @@ impl TypeTool { l } + /// Layout of `t`, frame `id`, for an overlays call that draws a frame other than the edited + /// one: the layout kept in `now` or `was` for `id` when it was made from the layout inputs + /// `fonts` and the same text, otherwise a new one. It is kept in `now` either way while `now` + /// holds fewer than [`FRAME_LAYOUTS_MAX`]. + fn frame_layout(now: &mut FrameLayouts, was: &mut FrameLayouts, fonts: u64, id: NodeId, t: &TextObject) -> Arc { + if let Some(((g, k), l)) = now.get(&id) + && *g == fonts + && k == t + { + return l.clone(); + } + let kept = match was.remove(&id) { + Some(((g, k), l)) if g == fonts && &k == t => ((g, k), l), + _ => ((fonts, t.clone()), Arc::new(vectorcraft_text::layout(FontDb::global(), t))), + }; + let l = kept.1.clone(); + if now.len() < FRAME_LAYOUTS_MAX { + now.insert(id, kept); + } + l + } + /// The edited text used to find word and paragraph boundaries for selection: the typing session's /// runs, or the document's current text when there is no live session or it has gone stale. fn plain(&self, cx: &ToolContext) -> String { diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 94063166bc..89a24cc3bf 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1636,10 +1636,276 @@ fn the_edited_types_ports_follow_the_limit_too() { tool.start_editing(id, 0); let boxes = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [255, 255, 255, 255], .. })).count(); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 2 * PORTS_MAX, "at the limit, the edited one's included"); + assert_eq!(kept_frames(&tool), PORTS_MAX - 1, "the other frames' layouts are kept"); let copy = d.alloc_id(); d.insert(Some(l), 1, Node::new(copy, node.kind.clone())).unwrap(); sel.add(copy); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 0, "past it, not even the edited one's"); + assert_eq!(kept_frames(&tool), 0, "no ports drawn, no layouts kept"); +} + +/// How many other frames' layouts the Type tool keeps between overlays calls. +fn kept_frames(tool: &TypeTool) -> usize { + tool.frames.lock().unwrap().len() +} + +/// The value `f` returns, and how many layouts this thread started while it ran. +fn counted(f: impl FnOnce() -> T) -> (T, u64) { + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let v = f(); + (v, vectorcraft_text::test_fonts::layouts_on_this_thread() - before) +} + +/// A document with area type frames of `texts` (each 120 × 40 pt, one under the other) and their ids. +fn area_frames(texts: &[&str]) -> (Document, Vec) { + let mut d = Document::new(500.0, 2000.0); + let l = d.layers[0].id; + let mut ids = Vec::new(); + for (i, s) in texts.iter().enumerate() { + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(50.0, 50.0 + 60.0 * i as f64), s, CharStyle::default()); + t.kind = area_kind(120.0, 40.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + ids.push(id); + } + (d, ids) +} + +/// Area type in a `w` × `h` pt frame. +fn area_kind(w: f64, h: f64) -> TextKind { + TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, w, h).to_path(0.1)) } +} + +fn text_mut(d: &mut Document, id: NodeId) -> &mut TextObject { + match &mut d.node_mut(id).unwrap().kind { + NodeKind::Text(t) => t, + _ => panic!("not text"), + } +} + +const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hundred and twenty by forty points."; + +/// The Type tools draw the ports of several different selected frames, with and without one of +/// them being edited, without laying any of them out again on the next frame, and draw the same +/// overlays as a tool that lays every frame out afresh. +#[test] +fn type_overlays_keep_the_selected_frames_layouts() { + let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let c = cx(&d, &sel, &p); + let mut probe = Vec::new(); + push_port(&mut probe, Point::ZERO, PortState::Overflow, [0, 0, 0], 1.0); + let Some(Overlay::Line { color: red, .. }) = probe.last().cloned() else { panic!("the red plus is drawn with lines") }; + let red_plus = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == red)).count(); + for editing in [None, Some(ids[0])] { + let mut tool = TypeTool::new("areaType"); + if let Some(id) = editing { + tool.start_editing(id, 0); + } + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0, "{editing:?}: the first frame lays the frames out"); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "{editing:?}: the next frame lays none out again"); + assert_eq!(first, second, "{editing:?}"); + let mut fresh = TypeTool::new("areaType"); + if let Some(id) = editing { + fresh.start_editing(id, 0); + } + assert_eq!(second, fresh.overlays(&c), "{editing:?}: what laying out afresh draws"); + assert!(red_plus(&second) > 0, "{editing:?}: the overflowing frame's out port shows its red plus"); + } +} + +/// After Select All in threaded text, the story's other frames are highlighted without laying them +/// out again on the next frame. +#[test] +fn type_overlays_keep_a_selected_storys_layouts() { + let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + assert_eq!(tool.story_others(&c).len(), 3); + let highlights = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [60, 120, 255, 90], .. })).count(); + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "the story's other frames are not laid out again"); + assert_eq!(first, second); + let mut fresh = TypeTool::new("areaType"); + fresh.start_editing(ids[0], 0); + fresh.set_option("selectAll", &story); + assert_eq!(second, fresh.overlays(&c), "what laying out afresh draws"); + assert!(highlights(&second) >= 4, "every frame's text is highlighted: {}", highlights(&second)); +} + +/// A kept layout is used only while its frame's text object is unchanged: editing the text, +/// changing the frame and undoing both lay out just the frames that changed, a frame that is no +/// longer drawn is dropped, and choosing another tool drops them all. +#[test] +fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let mut tool = TypeTool::new("areaType"); + let fresh = |d: &Document, sel: &Selection| TypeTool::new("areaType").overlays(&cx(d, sel, &p)); + tool.overlays(&cx(&d, &sel, &p)); + let start = d.clone(); + // Edit the text of one frame. + text_mut(&mut d, ids[1]).runs[0].text = OVERFLOWS.into(); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the edited frame"); + assert_eq!(o, fresh(&d, &sel)); + // Make another frame tall enough for its text. + text_mut(&mut d, ids[3]).kind = area_kind(120.0, 400.0); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the changed frame"); + assert_eq!(o, fresh(&d, &sel)); + // Undo puts both back. + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 2, "the two frames undo changed"); + assert_eq!(o, fresh(&start, &sel)); + // A smaller selection keeps only its frames; the others are laid out again when selected again. + let mut one = Selection::default(); + one.set([ids[0]]); + assert_eq!(counted(|| tool.overlays(&cx(&start, &one, &p))).1, 0); + assert_eq!(kept_frames(&tool), 1); + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 3); + assert_eq!(o, fresh(&start, &sel)); + tool.deactivate(&cx(&start, &sel, &p)); + assert_eq!(kept_frames(&tool), 0, "another tool chosen"); +} + +/// A story of more frames than [`FRAME_LAYOUTS_MAX`] keeps that many layouts, lays the rest out on +/// each call, and draws what laying every frame out afresh draws. +#[test] +fn type_overlays_keep_at_most_frame_layouts_max() { + let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; + let (mut d, ids) = area_frames(&texts); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + let first = tool.overlays(&c); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 2, "the two other frames past the limit"); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + assert_eq!(first, second); +} + +#[test] +fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + // Other tests can load system fonts; this assertion needs its own process-wide database. + #[cfg(not(target_arch = "wasm32"))] + if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "text::tests::frame_layouts_follow_fonts_and_hyphenation_exceptions", "--nocapture", "--test-threads=1"]) + .env("VECTORCRAFT_FONT_CACHE_TEST_CHILD", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated font cache test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let (mut d, ids) = area_frames(&["One", "Two", "Three ", "four"]); + d.text_threads.push(vec![ids[2], ids[3]]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0], ids[1], ids[2]]); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[2], 0); + tool.set_option("selectAll", &json!({ "story": [ids[2].0, ids[3].0] })); + tool.overlays(&c); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + // Two selected frames, the story's other frame and the edited one. + let font = vectorcraft_text::test_fonts::variable_font().unwrap(); + assert!(FontDb::global().add_font(font) > 0, "the test font is new to this process"); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "a font added after the layouts refreshes them"); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + vectorcraft_text::set_hyphenation_exceptions(&vectorcraft_text::hyphenation_exceptions()); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "new hyphenation exceptions refresh them"); +} + +/// Times the Type tool's overlays on 200 selected area type frames of about 400 characters, one of +/// them edited, and on a 5-frame story after Select All, laying every frame out on each call as the +/// tool did before it kept their layouts (base) against keeping them (kept). Run with +/// `cargo test --release -p vectorcraft-tools --lib type_overlays_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing, run by hand"] +fn type_overlays_timing() { + use std::time::Instant; + let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); + let texts: Vec = (0..200).map(|i| format!("{i} {words}")).collect(); + let (mut d, ids) = area_frames(&texts.iter().map(String::as_str).collect::>()); + for id in &ids { + text_mut(&mut d, *id).kind = area_kind(200.0, 200.0); + } + let story: Vec = ids[..5].to_vec(); + d.text_threads.push(story.clone()); + let p = paint(); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut first = Selection::default(); + first.set([ids[0]]); + // Before, the selected frames' layouts replaced the edited one's single kept layout; with only + // the edited frame selected, it stayed. + let cases = [("200 selected frames, one edited", &all, None, true), ("5-frame story, Select All", &first, Some(story), false)]; + for (name, sel, story, evicted) in cases { + let c = cx(&d, sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + if let Some(s) = &story { + tool.set_option("selectAll", &json!({ "story": s.iter().map(|id| id.0).collect::>() })); + } + let expected = tool.overlays(&c); + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + let (_, before) = counted(|| tool.overlays(&c)); + let (_, after) = counted(|| tool.overlays(&c)); + println!("{name}: {before} layouts per call before, {after} after"); + let calls = 20; + let (mut base, mut kept) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..calls { + // Before: the other frames were laid out on every call. + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + assert_eq!(tool.overlays(&c), expected); + } + base.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + let start = Instant::now(); + for _ in 0..calls { + assert_eq!(tool.overlays(&c), expected); + } + kept.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{name}: base runs {base:.3?} ms per call, kept runs {kept:.3?} ms per call"); + println!("{name}: median base {:.3} ms, kept {:.3} ms per call", median(&mut base), median(&mut kept)); + } } /// Type on a path has its in port just before its start bracket and its out port just past its diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index 4ab193a9f0..2945777610 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -472,6 +472,7 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.prev_tool = None; + self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } /// Editing ends when a command takes the text out of the selection (Deselect, another object @@ -652,13 +653,17 @@ impl Tool for TypeTool { o.push(Overlay::Measure { p: d, text: cx.size_label(size.width, size.height) }); } } + // The other frames this call draws keep their layouts for the next call; the rest are dropped. + let fonts = vectorcraft_text::layout_inputs(); + let mut now = self.frames.lock().unwrap_or_else(|e| e.into_inner()); + let mut was = std::mem::take(&mut *now); // The ports of selected area type and type on a path, as many as show ([`PORTS_MAX`]), the // edited one's included. let shown = ports_shown(cx.doc, &cx.selection.objects); if shown { for id in cx.selection.objects.iter().filter(|id| Some(**id) != self.editing) { if let Some(t) = ported(cx.doc, *id) { - let lay = self.layout(t); + let lay = Self::frame_layout(&mut now, &mut was, fonts, *id, t); ports(cx, *id, t, lay.overflow, &mut o); } } @@ -707,7 +712,7 @@ impl Tool for TypeTool { if self.preedit.is_none() { for f in self.story_others(cx) { let Some(other) = Self::text(cx, f) else { continue }; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + let lay = Self::frame_layout(&mut now, &mut was, fonts, f, other); for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 192fbf36a3..52ce2ee750 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2252,6 +2252,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A subpath keeps its anchors in chunks of up to 256 anchors, and the versions of a path share the chunks they have not changed. Editing one anchor copies only the chunk that holds it, so its undo step keeps that chunk instead of a copy of every anchor; adding or deleting an anchor copies the chunk it is in and rebuilds the subpath's table of chunks. When the renderer looks for the anchors that moved, it compares only the chunks the edit copied. Moving one anchor of a selected open path of 10,000 or 200,000 anchors (`path.moveAnchor`, `path.setHandle`, `path.moveAnchors` or a nudge) keeps at most 48 KiB in the undo step and in the redo step, where it kept a copy of every anchor at 56 bytes each (counted in the engine's tests). Files are written and read as before, each subpath's anchors as one list. Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. + With a Type tool active, the in and out ports of the selected area type and type on a path, and the highlight of a selected story's other frames after Select All, use each frame's layout from the last frame instead of laying the frame out again. A frame is laid out again when its text object changes, or when the fonts or the hyphenation exceptions change. With 200 selected area type frames of about 400 characters, one of them being edited, the Type tool's overlays take 0.27 ms per frame instead of 121 ms; with a 5-frame story selected they take 0.016 ms instead of 2.0 ms (release build on Linux, medians of seven runs, measured while other builds were running). A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429).