From 24e0208d314622564e56729e253b8b848f5115ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:08:24 -0800 Subject: [PATCH 1/2] Type: inline graphics are checked again only in the layer trees an edit changed After an edit of a document with symbols, the refresh of inline graphics walked every node of every layer. It now keeps the document the last refresh left resolved, with the symbol bounds it measured, and checks only the layer trees that are not the same nodes as that document's, as long as the symbols, graph designs, pattern tiles and foreign data (which holds the symbols' natural sizes and 9-slice guides) are the same and each measured symbol still measures the same. Otherwise the full pass runs, as before. Visit order is unchanged, so the document and the ids of the texts laid out again equal the full pass's. --- crates/doc/src/inline.rs | 228 ++++++++++++++++++++++++++-- crates/doc/src/lib.rs | 2 +- crates/engine/src/cmd/inline.rs | 31 +++- crates/engine/src/doc_state.rs | 5 + crates/engine/src/session/edit.rs | 9 +- crates/engine/src/tests/inline.rs | 239 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 7 files changed, 497 insertions(+), 18 deletions(-) diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc, + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc]>, + kids: &[Arc], + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> Vec<(usize, Arc)> { + let mut by_id: Option>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 11711b3f1d..cbb783efdd 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -31,7 +31,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index d2df2ada51..cb516465ff 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::text::INLINE_MAX_SCALE; -use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; +use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; use super::brushsym::current_symbol; @@ -25,12 +25,33 @@ pub fn specs() -> Vec { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9cbdfb6827..f6f383fe5b 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -136,6 +136,10 @@ pub struct DocState { /// same document comes to the front, its type set in them is not measured again. While this /// reference lasts, its allocation holds no other document. Not saved. pub(crate) measured_in_own: Option<(std::sync::Weak, std::collections::HashSet)>, + /// The document as the last edit's refresh of inline graphics left it, and what that refresh + /// measured: the next refresh checks only the layer trees that differ from it + /// ([`cmd::inline::refresh`]). Not saved. + pub(crate) inline_resolved: Option, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -355,6 +359,7 @@ impl DocState { plugin_effects: Default::default(), art_to_fit: Default::default(), measured_in_own: None, + inline_resolved: None, } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4f47b325b9..4e840c9364 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -53,7 +53,8 @@ impl Session { let mut symbol_synced = if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) }; // Inline graphics in text follow their symbols. - cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); + let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc)); + let mut resolved = measured.map(|m| (st.doc.clone(), m)); // The document the passes below start from, for the symbol to follow what they // change on its editing layer. let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone()); @@ -86,7 +87,10 @@ impl Session { let new = art(&st.doc); if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) { let resynced = st.doc.clone(); - cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc)); + let last = resolved.as_ref().or(st.inline_resolved.as_ref()); + if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) { + resolved = Some((st.doc.clone(), m)); + } if !st.doc.text_threads.is_empty() { cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc)); } @@ -100,6 +104,7 @@ impl Session { if !st.doc.variables.bindings.is_empty() { Arc::make_mut(&mut st.doc).prune_variable_bindings(); } + st.inline_resolved = resolved; if let Err(e) = symbol_synced { Err(e) } else if st.doc.too_deep(Some(&before)) { diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 71caf14bf8..e491aefc34 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -504,6 +504,245 @@ fn saved_documents_keep_inline_graphics() { assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds); } +/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns +/// the ids of each group's rectangles. +fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec> { + s.edit("Rectangles", |d, _| { + let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut ids = vec![]; + let mut made = vec![]; + for g in 0..groups { + let kids: Vec> = (0..each) + .map(|i| { + let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone())) + }) + .collect(); + ids.push(kids.iter().map(|k| k.id).collect()); + made.push(Arc::new(Node::group(d.alloc_id(), kids))); + } + match Arc::make_mut(&mut d.layers[0]).children_mut() { + Some(kids) => kids.extend(made), + None => panic!("the first layer holds art"), + } + Ok(ids) + }) + .unwrap() +} + +/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on +/// `fast`; checks that both leave the same document and that each refresh returned the same changed +/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees. +fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec { + let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut())); + take(); + cmd::inline::FULL_PASS.set(true); + step(full); + cmd::inline::FULL_PASS.set(false); + let want = take(); + step(fast); + let got = take(); + assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc); + let ids = |passes: &[(bool, Vec)]| passes.iter().map(|(_, ids)| ids.clone()).collect::>(); + assert_eq!(ids(&got), ids(&want)); + assert!(want.iter().all(|(partial, _)| !partial)); + got.iter().map(|(partial, _)| *partial).collect() +} + +/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and +/// the document and the changed texts are those of the full pass; a change to a symbol's art, its +/// natural size or anything else a symbol is measured with checks them all. +#[test] +fn refreshing_only_changed_trees_matches_the_full_pass() { + let setup = |s: &mut Session| { + circle_symbol(s, "Tap", 10.0); + circle_symbol(s, "Dot", 6.0); + let groups = rect_groups(s, 20, 10); + let id = text(s, "Tap here"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap(); + // Type showing Dot inline becomes the opacity mask of a rectangle. + let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone(); + let mask = text(s, "Dot"); + s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap(); + (groups, id) + }; + let (mut full, mut fast) = (session(), session()); + let (groups, id) = setup(&mut full); + assert_eq!(setup(&mut fast), (groups.clone(), id)); + let rect = groups[3][4].0; + let len = obj(&fast, id).plain_text().len(); + let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p); + let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p); + + // A rectangle beside 19 unchanged groups moves. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Type with an inline graphic is edited, gets a second one, and loses it again. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap(); + s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap(); + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Dot's art is redefined: the type in the opacity mask follows it. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot")); + assert!(passes.contains(&false), "{passes:?}"); + // Tap's natural size changes, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.edit("Size", |d, _| { + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] })); + Ok(()) + }) + .unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap")); + assert!(b.is_some() && b == want, "{b:?} {want:?}"); + // 9-slice guides for Tap, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + // Symbol editing mode, entered and left, a rectangle moved inside it. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + }); + // Undo and redo, then edits after them. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap(); + }); + // Fonts scanned again, then another move. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.rescanFonts", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap(); + }); +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the +/// wall clock. +fn time_ms(f: impl FnOnce()) -> f64 { + let d = match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + }; + d.as_secs_f64() * 1000.0 +} + +/// The median, fastest and slowest of `runs`, as text. +fn spread(runs: &mut [f64]) -> String { + runs.sort_by(f64::total_cmp); + format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1]) +} + +/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with +/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100 +/// groups, with three symbols and one line of type showing one of them inline: the refresh alone, +/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going +/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on +/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn inline_refresh_perf() { + const RUNS: usize = 7; + eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)"); + for n in [5_000, 50_000, 200_000] { + let mut s = session(); + for name in ["A", "B", "C"] { + circle_symbol(&mut s, name, 10.0); + } + let groups = rect_groups(&mut s, 100, n / 100); + let id = text(&mut s, "Type"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap(); + let rect = groups[50][7]; + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + // The refresh alone, after the same move made on a copy of the resolved document. + let resolved = s.doc().unwrap().inline_resolved.clone().unwrap(); + let before = resolved.0.clone(); + // The rectangle and the group and layer above it become new nodes, as a move makes them. + let mut after = (*before).clone(); + assert!(after.node_mut(rect).is_some()); + // Each run times EACH refreshes, or EACH commands, and gives the time of one. + const EACH: usize = 20; + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..RUNS { + let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]); + let mut go_full = || { + cmd::inline::FULL_PASS.set(true); + full.push( + time_ms(|| { + for d in &mut a { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + cmd::inline::FULL_PASS.set(false); + }; + let mut go_partial = || { + partial.push( + time_ms(|| { + for d in &mut b { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + }; + if run % 2 == 0 { + go_full(); + go_partial(); + } else { + go_partial(); + go_full(); + } + assert_eq!(a, b); + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial)); + // The whole command, moving the rectangle back and forth. + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..2 * RUNS { + let take_full = (run / 2) % 2 == run % 2; + cmd::inline::FULL_PASS.set(take_full); + let ms = time_ms(|| { + for i in 0..EACH { + let dx = if i % 2 == 0 { -1 } else { 1 }; + s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap(); + } + }) / EACH as f64; + cmd::inline::FULL_PASS.set(false); + if take_full { full.push(ms) } else { partial.push(ms) } + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial)); + cmd::inline::PASSES.with(|p| p.borrow_mut().clear()); + } +} + #[test] fn create_outlines_turns_inline_graphics_into_symbol_instances() { let mut s = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..e0ea3b31fa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1506,6 +1506,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Inline graphics in symbol art follow their symbols:** when a symbol changes, type with an inline graphic of it is laid out again wherever the type is: in the layers, in the art of other symbols, graph designs and pattern tiles, and in opacity masks. A symbol's type is laid out before the type that shows that symbol inline, so a symbol whose art holds an inline graphic, its instances and the inline graphics that show it take its new size. Opening and reverting a document and Refresh Font List resolve them in the same order. An inline graphic of a symbol whose art shows that symbol inline, directly or through other symbols, is an empty slot. This is VectorCraft's own rule. Tests: `inline_graphics_in_symbol_art_follow_their_symbol`, `inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol`, `symbols_are_resolved_after_the_symbols_they_show_inline`, `a_symbol_that_shows_itself_inline_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`. - **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. +- **Inline graphics after an edit, in large documents:** after an edit, a document with symbols checks its type's inline graphics again only in the layer trees that differ from the document the last check left, as long as the symbols, graph designs, pattern tiles and the symbols' natural sizes and 9-slice guides are unchanged and each symbol the type shows measures as before; otherwise every tree is checked, as before. The document and the texts laid out again are the same either way. Measured in one process (thread CPU time, median of 7 runs, 100 groups, three symbols, one inline graphic, one rectangle moved): the check went from 1.0 ms to under 0.05 ms at 50,000 rectangles and from 5.7 ms to under 0.05 ms at 200,000, and a whole `object.move` from 1.55 ms to 0.7 ms and from 11.9 ms to 6.2 ms; the rest of an edit still walks the document. Tests: `refreshing_only_changed_trees_matches_the_full_pass` in `crates/engine/src/tests/inline.rs`; `a_pass_after_an_edit_checks_only_the_trees_the_edit_changed`, `changed_symbols_or_symbol_sizes_take_the_full_pass` in `crates/doc/src/inline.rs`; timings: `inline_refresh_perf` (ignored). - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`. From 92020b43bc17788ca5e26762d0a22eb67c22bc57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:31:34 -0800 Subject: [PATCH 2/2] Rerun CI