Merge pull request #10132 from dotCooCoo/fix/speed-object-move-large-doc

Performance: an edit skips unchanged objects without reading them
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-29 18:21:16 -08:00
commit ff60b8078d
9 files changed
+84 -62

No files matched your search

+1 -9
View File
@@ -308,16 +308,8 @@ fn resolve_kids(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> Vec<(usize, Arc<Node>)> {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
let mut out = vec![];
for (i, c) in kids.iter().enumerate() {
let o = old.and_then(|old| match old.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
});
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
continue;
}
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
let mut c = c.clone();
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
out.push((i, c));
+1
View File
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::changed_nodes;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
+4
View File
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
use crate::text::TextObject;
mod attributes;
mod changed;
mod clip;
mod extras;
mod ids;
@@ -25,6 +26,9 @@ mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
#[cfg(test)]
pub(crate) use changed::COUNTERPART_LOOKUPS;
pub use changed::changed_nodes;
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+33
View File
@@ -0,0 +1,33 @@
use std::collections::HashMap;
use super::{Arc, Node, NodeId};
#[cfg(test)]
thread_local! {
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
/// node is new). A node that is the same node as the one at its position in `before` is skipped
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
after.iter().enumerate().filter_map(move |(i, a)| {
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
#[cfg(test)]
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
Some((i, a, b))
})
}
+34
View File
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
}
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
/// the same nodes in the same places are passed over by their pointers.
#[test]
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
let mut after = before.clone();
let mut edited = (*after[500]).clone();
edited.name = Some("edited".into());
after[500] = Arc::new(edited);
after.push(leaf(5000));
COUNTERPART_LOOKUPS.with(|c| c.set(0));
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
}
/// A node that moved to another place in the list is paired with itself by its id and left out
/// when it is the same node; a changed node that moved is paired with its old node, and a node
/// that is gone from the list gives nothing.
#[test]
fn changed_nodes_pairs_moved_nodes_by_id() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
let mut edited = (*before[0]).clone();
edited.locked = true;
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
assert_eq!(changed_nodes(&[], &after).count(), 3);
}
+2 -9
View File
@@ -14,7 +14,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
+3 -19
View File
@@ -5,7 +5,7 @@
use std::collections::HashMap;
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
use super::{
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
@@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
/// mask art holds such instances (`masked`).
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
masked.push(a.id);
}
@@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
out.push(a.id);
} else if let Some(children) = a.children() {
+3 -11
View File
@@ -25,12 +25,12 @@
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
//! the objects that move up the path after it; Expand).
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Rect;
use super::edit::{roots_of, selected_roots};
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
/// (`before`: the same list before the edit), outer ones first.
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if is_objects_on_path(a) {
out.push(a.id);
}
+3 -14
View File
@@ -6,12 +6,9 @@ use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
};
use serde_json::{Value, json};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
};
use std::{collections::BTreeMap, sync::Arc};
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
use vectorcraft_pathops as po;
use vectorcraft_tools::builder::{self as b, BuilderMap};
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
}
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().shaper.is_some() {
out.push(a.id);
}