From 698ec93090fc1aa23cf53f8870d4ab69641ebfb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 13:37:08 -0800 Subject: [PATCH] Select: removing objects one at a time checks and reads only the removed ones Taking objects out of a selection (select.toggle, which Shift-click, the Layers panel and a script's selected = false run) checked the whole selection again, walking the tree once it held more than an eighth of the document, and read every selected object's paints for the fill and stroke proxies. Deselecting N objects one at a time took O(N^2) lookups. Session::select now checks only the objects that follow the objects it already checked, kept in their order, so a removal needs no checks. The selection's paints keep counts (the first fill, stroke and weight met, how many match it, and how many there are), so the objects that leave are taken out of them and the objects that join are read. The paints are read again when every value matching the first one is gone and others are left, or when that takes fewer lookups. --- crates/engine/src/cmd/newart.rs | 6 +- crates/engine/src/cmd/paint.rs | 146 ++++++++++++++++++++----- crates/engine/src/doc_state.rs | 49 +++++++-- crates/engine/src/session/edit.rs | 16 +-- crates/engine/src/tests/large_edits.rs | 27 +++++ crates/engine/src/tests/newart.rs | 37 +++++++ 6 files changed, 237 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ffea03187d..f43221120c 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -286,9 +286,9 @@ impl Session { return; } let read = self.read_selection_paints(); - let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed)); + let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed(), p.stroke_mixed())); let (fill, stroke) = self.proxy_paints(); - let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed); + let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed()); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. if !fill_mixed && !self.tool_paints(false) { @@ -323,7 +323,7 @@ impl Session { Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) }); } let paints = st.selection_paints()?.clone(); - (!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints) + (!paints.in_live_paint() && self.fill_mesh_points().is_empty()).then_some(paints) } } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 25ca3a60ca..65faaad09b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -396,20 +396,62 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' /// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or /// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a /// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with -/// [`SelectionPaints::add`]. +/// [`SelectionPaints::add`], and the objects taken out of it with [`SelectionPaints::remove`]. #[derive(Clone, Debug, Default)] pub(crate) struct SelectionPaints { - fill: Option, - pub(crate) fill_mixed: bool, - stroke: Option, - pub(crate) stroke_mixed: bool, - weight: Option, - pub(crate) weight_mixed: bool, - /// An object is a face or edge of a Live Paint group, or lies inside one + fill: Tally, + stroke: Tally, + weight: Tally, + /// The objects that are a face or edge of a Live Paint group, or lie inside one /// ([`live_paint_covered`]). - pub(crate) in_live_paint: bool, - /// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]). - pub(crate) may_hold_mesh: bool, + in_live_paint: usize, + /// The objects that are a gradient mesh or a container ([`Session::fill_mesh_points`]). + may_hold_mesh: usize, +} + +/// The first value met, how many of the values met are the same as it, and how many were met. +#[derive(Clone, Debug)] +struct Tally { + first: Option, + same: usize, + all: usize, +} + +impl Default for Tally { + fn default() -> Self { + Self { first: None, same: 0, all: 0 } + } +} + +impl Tally { + fn add(&mut self, value: T, same: impl Fn(&T, &T) -> bool) { + self.all += 1; + match &self.first { + Some(f) if same(f, &value) => self.same += 1, + Some(_) => {} + None => (self.first, self.same) = (Some(value), 1), + } + } + /// Take out a value met before. → false when the values left must be met again to know which + /// differ: every value the same as the first one is gone, and others are left. + fn remove(&mut self, value: &T, same: impl Fn(&T, &T) -> bool) -> bool { + let Some(f) = &self.first else { return false }; + if self.all == 0 { + return false; + } + self.all -= 1; + if same(f, value) { + self.same = self.same.saturating_sub(1); + } + if self.same == 0 { + self.first = None; + return self.all == 0; + } + true + } + fn mixed(&self) -> bool { + self.same < self.all + } } impl SelectionPaints { @@ -420,31 +462,76 @@ impl SelectionPaints { p } - /// Read objects `ids` of `doc` too. + /// Do the fills differ? + pub(crate) fn fill_mixed(&self) -> bool { + self.fill.mixed() + } + + /// Do the strokes differ? + pub(crate) fn stroke_mixed(&self) -> bool { + self.stroke.mixed() + } + + /// Do the stroke weights differ? + pub(crate) fn weight_mixed(&self) -> bool { + self.weight.mixed() + } + + /// Is an object a face or edge of a Live Paint group, or inside one? + pub(crate) fn in_live_paint(&self) -> bool { + self.in_live_paint > 0 + } + + /// Is an object a gradient mesh or a container? + pub(crate) fn may_hold_mesh(&self) -> bool { + self.may_hold_mesh > 0 + } + + /// Read objects `ids` of `doc` too: ids that are not read yet, each named once. pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) { - fn meet(first: &mut Option, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) { - match first { - Some(f) => *mixed |= !same(f, &value), - None => *first = Some(value), + self.each(doc, ids, true); + } + + /// Take out objects `ids` of `doc`, read before in the same document: ids that are read, each + /// named once. → false when the objects left must be read again ([`Tally::remove`]); the + /// paints are then wrong. + pub(crate) fn remove(&mut self, doc: &Document, ids: &[NodeId]) -> bool { + self.each(doc, ids, false) + } + + /// [`Self::add`] (`add`) or [`Self::remove`]. + fn each(&mut self, doc: &Document, ids: &[NodeId], add: bool) -> bool { + let mut ok = true; + let mut meet = |tally: &mut Tally, value: Paint| { + if add { + tally.add(value, same_in_proxy); + } else { + ok &= tally.remove(&value, same_in_proxy); } - } - // As in `proxy_mixed_with`: every node with an added id, in tree order. + }; + // As in `proxy_mixed_with`: every node with one of the ids, in tree order. let (mut fills, mut strokes) = (vec![], vec![]); for n in doc.nodes_in_order(ids.iter().copied()) { painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } for n in fills { - meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy); + meet(&mut self.fill, proxy_paint(n, false, None)); } for n in strokes { - meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy); + meet(&mut self.stroke, proxy_paint(n, true, None)); } - // As in `stroke_mixed`: the node each added id names. - for id in ids { + // As in `stroke_mixed`: the node each id names. + let step = |count: &mut usize, yes: bool| { + if yes { + *count = if add { *count + 1 } else { count.saturating_sub(1) }; + } + }; + let mut seen = std::collections::HashSet::new(); + for id in ids.iter().filter(|id| seen.insert(**id)) { let Some(n) = doc.node(*id) else { continue }; - self.in_live_paint |= in_live_paint(doc, *id); - self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container(); + step(&mut self.in_live_paint, in_live_paint(doc, *id)); + step(&mut self.may_hold_mesh, matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); let mut nodes = vec![]; painted(n, true, true, &mut nodes); for n in nodes { @@ -453,10 +540,15 @@ impl SelectionPaints { _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; for w in widths { - meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b); + if add { + self.weight.add(w, |a, b| a == b); + } else { + ok &= self.weight.remove(&w, |a, b| a == b); + } } } } + ok } } @@ -1273,7 +1365,7 @@ impl DocState { /// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group. pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet { - if self.selection_paints().is_some_and(|p| !p.in_live_paint) { + if self.selection_paints().is_some_and(|p| !p.in_live_paint()) { return std::collections::HashSet::new(); } live_paint_covered(&self.doc, ids) @@ -1525,7 +1617,7 @@ impl Session { // Only gradient meshes have points to pick: a selection with no mesh and no container that // could hold one skips reading the tool's options. let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); - let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh); + let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh()); if st.selection.symbol_part.is_some() || none_may() { return vec![]; } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9a17cb9c56..5d02e43d6b 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -191,6 +191,33 @@ pub(crate) fn objects_only(sel: &Selection) -> bool { && sel.on_path_member.is_none() } +/// How `after` starts with objects of `before` kept in their order: → how many objects of `after` +/// do, and the objects of `before` that are not among them, in order. +pub(crate) fn kept_from(before: &[NodeId], after: &[NodeId]) -> (usize, Vec) { + let (mut at, mut kept, mut removed) = (0, 0, Vec::new()); + for id in after { + let Some(i) = before[at..].iter().position(|b| b == id) else { break }; + removed.extend_from_slice(&before[at..at + i]); + at += i + 1; + kept += 1; + } + removed.extend_from_slice(&before[at..]); + (kept, removed) +} + +/// The objects of `ids` that are not in `of`, each named once, in order. +fn left_out(ids: &[NodeId], of: &[NodeId]) -> Vec { + if ids.is_empty() { + return vec![]; + } + let mut out: std::collections::HashSet = ids.iter().copied().collect(); + for id in of { + out.remove(id); + } + let mut seen = std::collections::HashSet::new(); + ids.iter().copied().filter(|id| out.contains(id) && seen.insert(*id)).collect() +} + /// What the commands scripts ran did to an open document since the person last opened or saved it /// ([`DocState::by_script`]). #[derive(Clone, Debug)] @@ -467,8 +494,10 @@ impl DocState { self.selection_record().and_then(|r| r.paints.as_ref()) } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with - /// Lock Guides `guides_locked`. `record` is the record of the selection before: when the - /// selected objects start with its objects, the added objects are read into its paints. + /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same + /// document: the objects that leave the selection are taken out of its paints and the objects + /// that join it are read into them, unless that reads more objects than reading the selection + /// again would, or the paints left can't be told apart without reading them again. pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { if !objects_only(&self.selection) { self.selection_record = None; @@ -476,16 +505,22 @@ impl DocState { } let objects = &self.selection.objects; self.selection_record = Some(match record { - Some(mut r) if objects.starts_with(&r.objects) => { - let added = &objects[r.objects.len()..]; + Some(mut r) => { if let Some(p) = &mut r.paints { - p.add(&self.doc, added); + let (kept, removed) = kept_from(&r.objects, objects); + let gone = left_out(&removed, objects); + let joined = left_out(&objects[kept..], &r.objects); + if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) { + r.paints = None; + } else { + p.add(&self.doc, &joined); + } } - r.objects.extend_from_slice(added); + r.objects.clone_from(objects); r.settled = Some(guides_locked); r } - _ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, + None => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, }); } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index e723be129b..cb12a01930 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -2,7 +2,7 @@ use super::{ Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane, objects_in_range, }; -use crate::doc_state::objects_only; +use crate::doc_state::{kept_from, objects_only}; impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one @@ -236,17 +236,19 @@ impl Session { let new_art = st.selection.new_art.clone(); let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; f(&st.doc, &mut st.selection); - let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before); - // Objects added to objects this checked in the same document, with Lock Guides as it was - // then and no art on a locked artboard to protect, are checked alone, by the rules `prune` - // and `deselect_hidden` apply to an object. + // Objects this checked in the same document, kept in their order, with Lock Guides as it + // was then and no art on a locked artboard to protect, need no check again: only the + // objects after them are checked, by the rules `prune` and `deselect_hidden` apply to an + // object. let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked)) + && objects_only(&st.selection) && st.selection.new_art.is_empty() && st.doc.new_art.get().is_empty() && !st.doc.artboards.iter().any(|a| a.locked); - if added && settled { + if settled { let doc = &st.doc; - let tail = st.selection.objects.split_off(before.len()); + let (kept, _) = kept_from(&before, &st.selection.objects); + let tail = st.selection.objects.split_off(kept); st.selection.objects.extend(tail.into_iter().filter(|id| { doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. }))) })); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 81d6b3bc65..b3ca69fbc7 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -721,3 +721,30 @@ fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() { assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); } + +/// `select.toggle` run once for each of `n` selected objects, in the order they were selected, +/// until none is selected → the walks of the tree and the lookups by id it took. +fn remove_one_at_a_time(n: usize) -> (u64, u64) { + let mut s = session(n, square); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + for id in &ids { + s.execute("select.toggle", &json!({"id": id.0})).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty()); + (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups) +} + +/// Deselecting objects one at a time checks and reads only the object each `select.toggle` takes +/// out: twice as many objects take about twice as many lookups, and the tree is not walked for +/// each one. +#[test] +fn deselecting_objects_one_at_a_time_looks_up_only_the_removed_objects() { + let (walks, lookups) = remove_one_at_a_time(1_000); + let (more_walks, more_lookups) = remove_one_at_a_time(2_000); + assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); + assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); +} diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index b139ee5927..0c6cc8dfdc 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -233,6 +233,43 @@ fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() { assert_eq!(s.paint.fill, blue, "a, b and c are all blue now"); } +fn toggle(s: &mut Session, id: NodeId) { + run(s, "select.toggle", json!({"id": id.0})); +} + +/// Objects taken out one at a time leave the others to be compared: a fill and weight the objects +/// left share loads, one they don't stays as it was. +#[test] +fn objects_taken_out_one_at_a_time_load_only_the_paints_the_objects_left_share() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#00ffff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0); + let d = painted(&mut s, 320.0, "#ff0000", "#00ff00", 5.0); + let red = node(&s, a).appearance.fill_paint(); + select(&mut s, &[a, b, c, d]); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + toggle(&mut s, c); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 5.0), "a, b and d share the weight, not the fill"); + s.paint.stroke_width = 0.5; + toggle(&mut s, b); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and d share both"); +} + +/// Taking out every object with the fill met first leaves the other objects' fills to compare. +#[test] +fn taking_out_the_objects_with_the_first_fill_compares_the_fills_left() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#0000ff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0); + let blue = node(&s, b).appearance.fill_paint(); + select(&mut s, &[a, b, c]); + s.paint.fill = Paint::None; + toggle(&mut s, a); + assert_eq!(s.paint.fill, blue, "b and c are both blue"); +} + #[test] fn art_without_paint_leaves_the_proxies_as_they_were() { let mut s = session();