diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..0655c675dd 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -339,6 +339,7 @@ impl Document { /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { + crate::id_index::note_path_lookup(); // The cached path, while the node there still has the id ([`id_index`]). let cached = self.index.get(); match cached.as_ref().and_then(|m| m.get(&id)) { diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index ed89f6ead4..149a8e488b 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,16 @@ impl Paths { pub(crate) fn len(&self) -> usize { self.ids.len() } + /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` + /// when it isn't in the table. + pub(crate) fn entry(&self, id: &NodeId) -> Option> { + self.ids.get(id).copied() + } + /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its + /// siblings. + pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { + self.at.get(e as usize).copied() + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() { TREE_WALKS.set(TREE_WALKS.get().saturating_add(1)); } +thread_local! { + /// [`path_lookups`] of this thread. + static PATH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that +/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included. +pub fn path_lookups() -> u64 { + PATH_LOOKUPS.get() +} + +/// Adds one to [`path_lookups`]. +pub(crate) fn note_path_lookup() { + PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree). #[derive(Default)] pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7f26dc9a50..2a2bbb78ee 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -21,7 +21,7 @@ pub mod graph; mod halftone_radii; pub mod hit; mod id_index; -pub use id_index::tree_walks; +pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; @@ -48,6 +48,8 @@ pub mod marks; mod mem; pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; +mod nearest; +pub use nearest::NearestFinder; pub mod node; pub mod objects_on_path; pub mod orient; diff --git a/crates/doc/src/nearest.rs b/crates/doc/src/nearest.rs new file mode 100644 index 0000000000..0adc6269f9 --- /dev/null +++ b/crates/doc/src/nearest.rs @@ -0,0 +1,90 @@ +//! The nearest node of a kind at or above each of many objects, found along one index path per +//! object. + +use std::sync::Arc; + +use crate::id_index::Paths; +use crate::{Document, Node, NodeId}; + +/// Finds, for one object after another, the nearest node that passes a test: the object itself, +/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`]. +/// +/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that +/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache +/// places the object and each id on its path where they are, a lookup reads that one path; an id +/// the cache does not place there (one that appears more than once, or a cache older than the +/// tree) is looked up with [`Document::node`]. +pub struct NearestFinder<'a> { + doc: &'a Document, + cache: Option>, + /// The cache entries from the top-level layer down to the object. + entries: Vec, + /// The nodes at those entries. + nodes: Vec<&'a Node>, +} + +impl Document { + /// A [`NearestFinder`] for this document. + pub fn nearest_finder(&self) -> NearestFinder<'_> { + NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] } + } +} + +impl<'a> NearestFinder<'a> { + /// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred` + /// holds; `None` when `id` is not in the tree or no node on its path passes. + pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> { + let doc = self.doc; + let ids: Vec = if self.cached_path(id) { + let cache = self.cache.as_deref()?; + // The depth of the first id from the object up that the cache does not place there. + let mut unplaced = None; + for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() { + if cache.entry(&node.id) != Some(Some(e)) { + unplaced = Some(k); + break; + } + if pred(node) { + return Some(node); + } + } + let k = unplaced?; + self.nodes[..=k].iter().map(|n| n.id).collect() + } else { + doc.ancestry(id).unwrap_or_default() + }; + let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n))); + // Those lookups may have built the cache again. + self.cache = doc.index.get(); + found + } + + /// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for + /// it or the path no longer leads to it. + fn cached_path(&mut self, id: NodeId) -> bool { + self.entries.clear(); + self.nodes.clear(); + let Some(cache) = self.cache.as_deref() else { return false }; + let Some(Some(mut e)) = cache.entry(&id) else { return false }; + loop { + let Some((parent, _)) = cache.place(e) else { return false }; + self.entries.push(e); + if parent == u32::MAX { + break; + } + // A parent's entry is made before its children's, so the walk up ends. + if parent >= e { + return false; + } + e = parent; + } + self.entries.reverse(); + let mut siblings: &'a [Arc] = &self.doc.layers; + for &e in &self.entries { + let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false }; + self.nodes.push(&**n); + siblings = n.children().map_or(&[], |c| c.as_slice()); + } + self.nodes.last().is_some_and(|n| n.id == id) + } +} diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..863c7979cd 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -282,3 +282,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } + +/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node` +/// for each id finds it. +fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> { + d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node) +} + +/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone +/// each, so both start from the same cache. +fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) { + type Pred = fn(&Node) -> bool; + let preds: [(&str, Pred); 5] = [ + ("group", |n| matches!(n.kind, NodeKind::Group { .. })), + ("layer", |n| n.is_layer()), + ("any", |_| true), + ("none", |_| false), + ("id divisible by 3", |n| n.id.0 % 3 == 0), + ]; + for (name, pred) in preds { + let (a, b) = (d.clone(), d.clone()); + let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect(); + let mut find = b.nearest_finder(); + let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect(); + assert_eq!(got, want, "{what}: {name}"); + } +} + +#[test] +fn nearest_finder_matches_the_ancestry_walk() { + for seed in 1..30 { + let (mut d, ids) = tree(seed); + nearest_agrees(&d, &ids, "no cache"); + d.node(ids[0]); + nearest_agrees(&d, &ids, "cached"); + // Every path in the first layer shifts: the cache is stale there. + let extra = d.alloc_id(); + let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, leaf); + } + nearest_agrees(&d, &ids, "a stale cache"); + // A group with the id of a node in the last layer, earlier in tree order than it, put in + // after the cache was built. + d.drop_lookup_cache(); + d.node(ids[0]); + let last = d.layers.len() - 1; + let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id); + if let Some(dup) = dup + && let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() + { + ch.insert(0, Arc::new(Node::group(dup, vec![]))); + } + nearest_agrees(&d, &ids, "a duplicate put in after the cache was built"); + d.drop_lookup_cache(); + nearest_agrees(&d, &ids, "a duplicate, cached afresh"); + } +} + +/// An id on the path that an earlier node of another kind also has: the earlier node is the one +/// tested, as `node` gives it. +#[test] +fn nearest_finder_tests_the_first_node_with_a_repeated_id() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())); + d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap(); + d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + // A group that has the path's id, after the path in tree order. + d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap(); + let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. }); + for cached in [false, true] { + d.drop_lookup_cache(); + if cached { + d.node(layer); + } + let mut find = d.nearest_finder(); + assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}"); + assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path"); + assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree"); + } +} + +/// With the cache built, finding the nearest group of every object of a large tree looks no id up +/// and walks the tree no time. +#[test] +fn nearest_finder_reads_one_path_per_object() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut leaves = vec![]; + for g in 0..2_000 { + let kids: Vec> = (0..3) + .map(|_| { + let id = d.alloc_id(); + leaves.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let gid = d.alloc_id(); + d.insert(Some(layer), g, Node::group(gid, kids)).unwrap(); + } + d.drop_lookup_cache(); + d.node(layer); + let (lookups, walks) = (path_lookups(), tree_walks()); + let mut find = d.nearest_finder(); + let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count(); + assert_eq!(found, leaves.len()); + assert_eq!(path_lookups() - lookups, 0, "lookups by id"); + assert_eq!(tree_walks() - walks, 0, "walks of the tree"); +} diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 618865cede..1d23d07792 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -29,6 +29,8 @@ mod commands; mod common; mod envelope; mod mesh; +#[cfg(test)] +mod selected_tests; pub(crate) use blend::expand_blends; pub use commands::specs; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 5334311789..a2cb0e3f91 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result { } /// Is any selected blend one made without a spine? -fn any_without_spine(s: &Session) -> bool { - let Ok(st) = s.doc() else { return false }; - selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +pub(super) fn any_without_spine(s: &Session) -> bool { + super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine)) } pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/live/common.rs b/crates/engine/src/cmd/live/common.rs index cfa3f32076..661d574b58 100644 --- a/crates/engine/src/cmd/live/common.rs +++ b/crates/engine/src/cmd/live/common.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::mesh::whole; use super::{ Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value, @@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); let ordered = sel.in_paint_order(&st.doc); + let given: HashSet = ordered.iter().copied().collect(); // Drop ids nested inside other given ids. return Ok(ordered .iter() .copied() .filter(|id| { let anc = st.doc.ancestry(*id).unwrap_or_default(); - !anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a)) + !anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a)) }) .collect()); } @@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { /// dynamic symbol instance's art is selected. pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec { let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut find = st.doc.nearest_finder(); + let mut seen = HashSet::new(); let mut out = vec![]; for id in &st.selection.objects { - for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { - if st.doc.node(a).is_some_and(pred) { - if !out.contains(&a) { - out.push(a); - } - break; - } + if let Some(n) = find.nearest(*id, pred) + && seen.insert(n.id) + { + out.push(n.id); } } out } +/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the +/// first one that does. +pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); + st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test)) +} + pub(super) fn is_blend(n: &Node) -> bool { matches!(n.kind, NodeKind::Blend { .. }) } @@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool { pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) } + if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) } } pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) } + if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) } } pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) } + if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) } } /// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was. diff --git a/crates/engine/src/cmd/live/selected_tests.rs b/crates/engine/src/cmd/live/selected_tests.rs new file mode 100644 index 0000000000..b1250e2560 --- /dev/null +++ b/crates/engine/src/cmd/live/selected_tests.rs @@ -0,0 +1,324 @@ +//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones +//! the lookup of every ancestor by id found: the same ids in the same order, the same availability +//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart}; + +use super::Session; +use super::blend::any_without_spine; +use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of}; + +/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from +/// the object up, repeats dropped by a scan of the list. +fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut out = vec![]; + for id in &st.selection.objects { + for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { + if st.doc.node(a).is_some_and(pred) { + if !out.contains(&a) { + out.push(a); + } + break; + } + } + } + out +} + +/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`]. +fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> { + super::has_selection(s)?; + crate::cmd::edit::no_symbol_part(s)?; + if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) } +} + +/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`]. +fn without_spine_by_ids(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + +/// Every check on the current selection gives what the lookups by id gave. +fn agree(s: &Session, what: &str) { + type Has = fn(&Session) -> std::result::Result<(), String>; + for (name, pred, has, msg) in [ + ("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"), + ("envelope", is_envelope, has_envelope, "select an envelope"), + ("mesh", is_mesh, has_mesh, "select a gradient mesh"), + ] { + let want = selected_of_by_ids(s, pred); + assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s"); + assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}"); + assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}"); + } + assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine"); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId { + select(s, ids); + id_of(&s.execute(cmd, &p).unwrap()) +} + +/// Every node id under the layers, parents before children (as Direct Selection can pick them). +fn all_ids(s: &Session) -> Vec { + fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + out.push(n.id); + if let Some(ch) = n.children() { + walk(ch, out); + } + } + } + let mut out = vec![]; + for l in &s.doc().unwrap().doc.layers { + walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out); + } + out +} + +/// The active document, to change in place. +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// Set the selection's objects as given, stale and repeated ids included. +fn set_objects(s: &mut Session, ids: Vec) { + s.doc_mut().unwrap().selection.objects = ids; +} + +/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine. +/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key +/// of `a`. +fn document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let r: Vec = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect(); + let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({})); + let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({})); + let g = run(&mut s, "object.group", &[a, r[4]], json!({})); + let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({})); + let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50})); + select(&mut s, &[r[7]]); + s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap(); + if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) { + spec.no_spine = true; + } + (s, [a, b, c, g, e, r[0]]) +} + +#[test] +fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() { + let (mut s, [a, b, c, g, e, inner_key]) = document(); + s.execute("select.all", &json!({})).unwrap(); + agree(&s, "select all"); + let all = all_ids(&s); + let keys: Vec = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect(); + set_objects(&mut s, keys.clone()); + agree(&s, "keys, as Direct Selection picks them"); + set_objects(&mut s, all.iter().rev().copied().collect()); + agree(&s, "every node, children first"); + set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]); + agree(&s, "repeated and stale ids, in first-seen order"); + assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order"); + set_objects(&mut s, vec![NodeId(999_999)]); + agree(&s, "only a stale id"); + set_objects(&mut s, vec![]); + agree(&s, "nothing"); + // A blend in another blend's key group: the inner one. + set_objects(&mut s, vec![inner_key]); + agree(&s, "a key of a blend nested in another's key group"); + assert_eq!(selected_of(&s, is_blend), vec![a]); + // An object of a dynamic symbol instance's art: nothing. + set_objects(&mut s, all.clone()); + s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] }); + agree(&s, "a symbol part"); + assert!(selected_of(&s, is_blend).is_empty()); +} + +/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's +/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is +/// built again. +#[test] +fn a_repeated_id_counts_as_its_first_node() { + let (mut s, [a, _, c, _, _, inner_key]) = document(); + let all = all_ids(&s); + s.doc().unwrap().doc.node(a); + let doc = doc_mut(&mut s); + if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() { + ch.insert(0, std::sync::Arc::new(Node::group(a, vec![]))); + } + set_objects(&mut s, all.clone()); + agree(&s, "a repeated id, the cache older than the tree"); + s.doc().unwrap().doc.drop_lookup_cache(); + agree(&s, "a repeated id, no cache"); + s.doc().unwrap().doc.node(a); + agree(&s, "a repeated id, cached afresh"); + set_objects(&mut s, vec![inner_key]); + assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts"); +} + +/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and +/// the checks stop at the first selected object that has one. +#[test] +fn selected_blends_take_no_lookups_by_id() { + let mut s = session(); + let mut keys = vec![]; + for i in 0..300 { + let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0)); + run(&mut s, "object.blend.make", &[x, y], json!({})); + keys.extend([x, y]); + } + for i in 0..1_000 { + rect(&mut s, i as f64); + } + s.execute("select.all", &json!({})).unwrap(); + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(keys[0]); + let before = vectorcraft_doc::path_lookups(); + assert_eq!(selected_of(&s, is_blend).len(), 300); + assert!(!any_selected_of(&s, is_mesh, |_| true)); + set_objects(&mut s, keys.clone()); + assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys"); + assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id"); + // The first key is in a blend: the check tests that key and its blend only. + static TESTED: AtomicUsize = AtomicUsize::new(0); + fn counted(n: &Node) -> bool { + TESTED.fetch_add(1, Ordering::Relaxed); + is_blend(n) + } + assert!(any_selected_of(&s, counted, |_| true)); + assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested"); +} + +/// `n` and everything under it with new ids. +fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node { + let mut n = n.clone(); + n.id = d.alloc_id(); + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + *c = std::sync::Arc::new(renumber(d, c)); + } + } + n +} + +/// This thread's CPU time in nanoseconds, where the system reports it (Linux). +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it, +/// otherwise in wall-clock time. +fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 { + let (cpu, wall) = (cpu_ns(), std::time::Instant::now()); + for _ in 0..calls { + f(); + } + let ms = match (cpu, cpu_ns()) { + (Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1e3, + }; + ms / f64::from(calls) +} + +/// The medians of 7 runs of `a` and of `b`, the runs taking turns. +fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) { + let (mut ta, mut tb) = (vec![], vec![]); + for _ in 0..7 { + ta.push(ms_per_call(calls, a)); + tb.push(ms_per_call(calls, b)); + } + ta.sort_by(f64::total_cmp); + tb.sort_by(f64::total_cmp); + (ta[3], tb[3]) +} + +/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers, +/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with +/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn timing_of_the_selected_blend_checks() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0)); + let square = rect(&mut s, 120.0); + let blend = run(&mut s, "object.blend.make", &[a, b], json!({})); + let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50})); + let doc = doc_mut(&mut s); + let templates: Vec = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect(); + let mut layers = vec![]; + for l in 0..10 { + let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0)); + let mut kids = vec![]; + for _ in 0..10_000 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[0]))); + } + for i in 0..200 { + let b = renumber(doc, &templates[1]); + let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b }; + kids.push(std::sync::Arc::new(b)); + } + for _ in 0..20 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[2]))); + } + if let Some(ch) = layer.children_mut() { + *ch = kids; + } + layers.push(std::sync::Arc::new(layer)); + } + doc.layers = layers; + s.execute("select.all", &json!({})).unwrap(); + let first = s.doc().unwrap().selection.objects[0]; + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(first); + println!("{} objects selected", s.doc().unwrap().selection.objects.len()); + type Check = fn(&Session) -> bool; + let checks: [(&str, Check, Check); 5] = [ + ("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()), + ("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()), + ("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()), + ( + "selected blends (object.blend.info and the Blend commands)", + |s| !selected_of_by_ids(s, is_blend).is_empty(), + |s| !selected_of(s, is_blend).is_empty(), + ), + ("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine), + ]; + assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend)); + println!("| Check | Lookups by id (ms) | One path (ms) |"); + println!("|---|---:|---:|"); + for (name, by_ids, one_path) in checks { + assert_eq!(by_ids(&s), one_path(&s), "{name}"); + let (old, new) = medians( + 15, + &|| { + std::hint::black_box(by_ids(&s)); + }, + &|| { + std::hint::black_box(one_path(&s)); + }, + ); + println!("| {name} | {old:.3} | {new:.3} |"); + } +} diff --git a/crates/ui-egui/src/panels/blend.rs b/crates/ui-egui/src/panels/blend.rs index ebc182d238..9991e0b37a 100644 --- a/crates/ui-egui/src/panels/blend.rs +++ b/crates/ui-egui/src/panels/blend.rs @@ -55,13 +55,10 @@ fn available(app: &VectorcraftApp, cmd: &str) -> bool { /// Selection counts as its blend. fn selects_blend_without_spine(app: &VectorcraftApp) -> bool { let Some(st) = app.session.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); st.selection.objects.iter().any(|id| { - let ancestry = st.doc.ancestry(*id).unwrap_or_default(); - let blend = ancestry.iter().rev().find_map(|a| match st.doc.node(*a).map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => Some(spec.no_spine), - _ => None, - }); - blend == Some(true) + let blend = find.nearest(*id, |n| matches!(n.kind, NodeKind::Blend { .. })); + matches!(blend.map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine) }) } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..0724e29575 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1721,6 +1721,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. + The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Detach is in its own entry below. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`.