diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1be4f47bec..8ed73725c8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -723,19 +723,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e657eba7db..af6d0c6b40 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -213,6 +213,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty +/// third layer `e`. +#[derive(Clone, Copy)] +struct Column { + layer: NodeId, + sub: NodeId, + a: NodeId, + g: NodeId, + b: NodeId, + c: NodeId, + o: NodeId, + e: NodeId, +} + +fn column_start() -> (Session, Column) { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let other = id(&run(&mut s, "layer.new", json!({}))); + let o = rect(&mut s, 200.0); + let e = id(&run(&mut s, "layer.new", json!({}))); + run(&mut s, "select.none", json!({})); + let top: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}"); + (s, Column { layer, sub, a, g, b, c, o, e }) +} + +type Prep = dyn Fn(&mut Session, Column); + +/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the +/// same selection, reply, current layer, highlighted rows and revision as removing or adding each +/// id of `art` one at a time. Returns the session the click ran in. +fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec) -> (Session, Column) { + let (mut new, t) = column_start(); + prep(&mut new, t); + let row = row(t); + let before = new.doc().unwrap().selection.clone(); + let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true})); + let (mut old, t) = column_start(); + prep(&mut old, t); + let ids = art(t); + let st = old.doc().unwrap(); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + old.select(|_, sel| { + for i in &ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } + }) + .unwrap(); + old.doc_mut().unwrap().layer_rows = rows; + let (n, o) = (new.doc().unwrap(), old.doc().unwrap()); + assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}"); + assert_eq!(ids_sel(&reply), o.selection.objects); + assert_eq!(n.active_layer, o.active_layer); + assert_eq!(n.highlighted_rows(), o.highlighted_rows()); + assert_eq!(n.revision, o.revision); + assert_eq!(undos(&new), undos(&old)); + (new, t) +} + +#[test] +fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() { + // `o` outside the layer is selected first and is the key object and the target; `a` is + // selected by one anchor, which is the key anchor. + let partly: &Prep = &|s, t| { + run(s, "layer.setCurrent", json!({"id": t.sub.0})); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects = vec![t.o, t.a]; + sel.anchors.insert(t.a, [(0, 1)].into()); + sel.key = Some(t.o); + sel.key_anchor = Some((t.a, (0, 1))); + sel.target = Some(t.o); + }; + let layer_art = |t: Column| vec![t.c, t.a, t.g]; + // Some of the layer's art is selected: the rest is added after what was selected. + let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]); + assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked"); + assert!(sel.target.is_none()); + // All of it is selected, `a` as the key object: it is removed, with its anchors, key and key + // anchor. + let all: &Prep = &|s, t| { + partly(s, t); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects.extend([t.c, t.g]); + sel.key = Some(t.a); + }; + let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o]); + assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none()); + // An object row, a group row and an empty layer's row. + shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]); + shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]); + shift_column_matches_each_id(partly, |t| t.e, |_| vec![]); + // A locked sublayer's row, and rows outside and inside the isolated group. + let locked: &Prep = &|s, t| { + partly(s, t); + run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true})); + }; + shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]); + let isolated: &Prep = &|s, t| { + partly(s, t); + s.doc_mut().unwrap().isolation = Some(t.g); + }; + shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]); + shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]); +} + fn ids_sel(v: &Value) -> Vec { v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2d890f781e..925d3248f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -703,6 +703,7 @@ since 2026-10-01. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. +- **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`.