Merge pull request #10143 from dotCooCoo/fix/speed-global-edit-preview-member-list

Global Edit: moving the selected object keeps the preview without walking the document
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-30 01:06:42 -08:00
commit 2e330bef17
2 files changed
+359 -10

No files matched your search

+157 -9
View File
@@ -267,6 +267,8 @@ thread_local! {
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many objects [`matches`] looked at on this thread.
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Form {
@@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.forms.pass();
super::select::walk_selectable(d, st.isolation, |n| {
#[cfg(test)]
OBJECTS_WALKED.with(|c| c.set(c.get() + 1));
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
}
@@ -1075,34 +1079,178 @@ pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
out
}
/// [`similar`]'s outlines as of a document revision and the options they were found with.
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
/// [`similar`]'s outlines as of a document revision, with what they were found from.
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
/// [`similar`]'s outlines and what they were found from.
#[derive(Clone, Debug)]
pub struct Similar {
revision: u64,
options: Options,
/// The document, the one selected object and the isolated object they were found with.
doc: Arc<Document>,
key: NodeId,
isolation: Option<NodeId>,
out: Arc<Highlights>,
}
/// Before Global Edit starts: with one supported object selected, the outlines of the other
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
/// progress, or when fewer than two objects would be taken. Kept per document revision and
/// options, as finding them walks the whole document.
/// options, as finding them walks the whole document. After an edit that replaced only the
/// selected object, and left what the others are compared with as it was (a move), the outlines
/// found before are kept without a walk.
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
// Global Edit is refused while an object of a dynamic symbol instance's art is selected.
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() {
return NO_HIGHLIGHTS.clone();
}
let o = &s.global_edit_options;
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
&& *rev == st.revision
&& opts == o
let key = st.selection.objects[0];
if let Some(c) = &mut *st.similar_outlines.borrow_mut()
&& c.options == *o
&& c.key == key
&& c.isolation == st.isolation
&& (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key))
{
return out.clone();
c.revision = st.revision;
c.doc = st.doc.clone();
return c.out.clone();
}
let out = Highlights::new(match matches(s, o) {
Ok(m) if m.len() >= 2 => outlines(st, &m),
_ => vec![],
});
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
*st.similar_outlines.borrow_mut() =
Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() });
out
}
/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both?
/// True when the layers differ only in `key` and in the layers and groups that hold it (the same
/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the
/// rest of the document is the same. A group that holds `key` is never like it (its form holds
/// `key`'s and more), so the walk looks into it before and after alike.
fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool {
let mut found = None;
let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| {
a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art)
};
// Everything else in the document (artboards, symbol settings, editing modes) as it was: the
// symbols' art is compared on its own, as one copy when no edit changed it.
let rest = |d: &Document| {
let mut d = d.clone();
d.layers.clear();
d.symbols.clear();
d
};
if then.symbols.len() != now.symbols.len()
|| !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b))
|| rest(then) != rest(now)
|| !changed_only(&then.layers, &now.layers, key, &mut found)
{
return false;
}
found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes()))
}
/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way
/// to it? `found` takes the two versions of `key` when it changed.
fn changed_only<'a>(then: &'a [Arc<Node>], now: &'a [Arc<Node>], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool {
if then.len() != now.len() {
return false;
}
then.iter().zip(now).all(|(a, b)| {
if Arc::ptr_eq(a, b) {
return true;
}
if a.id != b.id {
return false;
}
if a.id == key {
return found.replace((a, b)).is_none();
}
match (holder_children(a), holder_children(b)) {
(Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found),
_ => false,
}
})
}
/// The objects in a layer or a group.
fn holder_children(n: &Node) -> Option<&[Arc<Node>]> {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children),
_ => None,
}
}
/// Are two versions of a layer or a group the same apart from the objects in them?
fn same_holder(a: &Node, b: &Node) -> bool {
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
let kinds = match (kind, &b.kind) {
(
NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images },
NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di },
) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di,
(NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c,
_ => false,
};
kinds
&& *id == b.id
&& *name == b.name
&& *visible == b.visible
&& *locked == b.locked
&& *opacity == b.opacity
&& *blend == b.blend
&& *isolate == b.isolate
&& *knockout == b.knockout
&& *knockout_shape == b.knockout_shape
&& *appearance == b.appearance
&& *bbox_angle == b.bbox_angle
&& *extras == b.extras
}
/// How far apart two versions of the selected object's form may lie, in its unit box, and how much
/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a
/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in
/// its unit box by a transform that includes the move), well within this.
const KEPT: f64 = 1e-12;
/// Are two versions of the selected object compared with the other objects in the same way by
/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective
/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in
/// them?
fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0);
fn same_look(a: &Node, b: &Node) -> bool {
fill_of(a) == fill_of(b)
&& stroke_of(a) == stroke_of(b)
&& match (a.children(), b.children()) {
(Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)),
(x, y) => x.is_none() && y.is_none(),
}
}
if !(supported(a) && supported(b)) {
return false;
}
let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false };
let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs());
let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) {
(Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()),
(x, y) => x.is_none() && y.is_none(),
};
f.tag == g.tag
&& f.symbols == g.symbols
&& f.points.len() == g.points.len()
&& f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT)
&& fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y))
&& sizes
&& same_look(a, b)
}
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
/// selected object, in their layer's color.
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
+202 -1
View File
@@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged");
sel(&mut s, &[copies[0]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
sel(&mut s, &[copies[1]]);
@@ -156,6 +156,207 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
}
#[test]
fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
// The outlines `highlights` gives, and how many objects it looked at for them.
let shown = |s: &Session| {
let before = walked();
let out = highlights(s);
(out, walked() - before)
};
// The outlines in each layer color.
let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::<Vec<_>>();
// The outlines a walk finds, the options set again so that nothing is kept.
let fresh = |s: &mut Session| {
let size = s.global_edit_options.size;
s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap();
highlights(s);
s.execute("select.globalEditOptions", &json!({"size": size})).unwrap();
let before = walked();
let out = highlights(s);
assert!(walked() > before, "a walk");
paths(&out)
};
let mut s = session();
let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3);
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect();
sel(&mut s, &[key]);
let (first, n) = shown(&s);
assert_eq!(first.len(), 39);
assert!(n >= 40, "the first preview walks every object");
// The move rounds the form in its unit box differently; the same objects are like it.
s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap();
let (out, n) = shown(&s);
assert_eq!(n, 0, "a move of the selected object alone compares the others as before");
assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked");
assert_eq!(paths(&out), fresh(&mut s));
// Another object moved: it is shown where it is now.
sel(&mut s, &[copies[0]]);
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
sel(&mut s, &[key]);
let (out, n) = shown(&s);
assert!(n > 0, "another object changed");
let moved = node(&s, copies[0]).stroke_path().unwrap();
assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
assert_eq!(paths(&out), fresh(&mut s));
// The selected object took another shape: none of the squares is like it.
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
// With Size, a larger copy of the selected square is another size.
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
// With Appearance, another fill on the selected square leaves the others out.
s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap();
assert_eq!(shown(&s).0.len(), 39);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "the others have another fill now");
s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap();
// Reflected, the selected kite keeps its size but is no longer like its copy.
let lone = kite(&mut s, 0.0, 500.0, 1.0);
kite(&mut s, 200.0, 500.0, 1.0);
sel(&mut s, &[lone]);
assert_eq!(shown(&s).0.len(), 1);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let (out, n) = shown(&s);
assert!(n > 0 && out.is_empty(), "a reflected copy is not like it");
}
#[test]
fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 3);
s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [key]);
assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out");
}
#[test]
fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
rect(&mut s, 1100.0, 100.0, 10.0, 10.0);
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out");
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now");
}
#[test]
fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap();
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
sel(&mut s, &[key]);
assert!(highlights(&s).is_empty(), "the other instance is on the canvas");
// The symbol's art drawn 400 pt to the left: the other instance lies on the artboard.
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
let art = std::sync::Arc::make_mut(&mut d.symbols[0].art);
art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default());
st.revision += 1;
assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now");
}
#[test]
fn a_symbol_instance_put_in_perspective_has_another_size() {
use crate::cmd::globaledit::highlights;
let mut s = session();
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
sel(&mut s, &[key]);
assert_eq!(highlights(&s).len(), 1);
let size = |s: &Session| bounds(s, key).size();
let was = size(&s);
s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap();
sel(&mut s, &[key]);
assert_ne!(size(&s), was, "the projection changes the instance's size");
assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had");
}
#[test]
fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() {
use crate::cmd::globaledit::highlights;
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap();
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1);
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art");
sel(&mut s, &[inst]);
assert_eq!(highlights(&s).len(), 1, "the whole instance again");
}
#[test]
fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() {
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
let mut s = session();
let group = |s: &mut Session, ids: &[NodeId]| {
sel(s, ids);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
};
// A group of two squares inside an outer group with a third square, and a copy of both: the
// copy's inner group is like the selected inner group.
let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)];
let inner = group(&mut s, &a);
let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let outer = group(&mut s, &[inner, third]);
let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)];
let inner_copy = group(&mut s, &b);
let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0);
group(&mut s, &[inner_copy, third_copy]);
sel(&mut s, &[inner]);
let first = highlights(&s);
assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one");
assert!(!first.is_empty());
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = walked();
assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first));
assert_eq!(walked(), before, "the outer group changed with the selected group only");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same");
assert!(walked() > before);
}
#[test]
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
let mut s = session();