mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 21:49:17 +00:00
Merge pull request #10039 from dotCooCoo/fix/speed-i13930-global-edit-preview
Global Edit: the preview after an edit compares only the changed objects again
This commit is contained in:
@@ -91,6 +91,8 @@
|
||||
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
|
||||
//! one out is not an undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
|
||||
@@ -214,8 +216,18 @@ struct Form {
|
||||
frame: Affine,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`Form::of`] reduced an object to its form on this thread.
|
||||
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) };
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
#[cfg(test)]
|
||||
FORMS_MADE.with(|c| c.set(c.get() + 1));
|
||||
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
|
||||
f.add(n, 0)?;
|
||||
let first = *f.points.first()?;
|
||||
@@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
),
|
||||
};
|
||||
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
|
||||
let in_scope = |n: &Node| {
|
||||
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
|
||||
let in_scope = |b: Option<Rect>| {
|
||||
let Some(b) = b else { return false };
|
||||
if !d.artboards.iter().any(|a| on(a.rect, b)) {
|
||||
return o.include_canvas;
|
||||
}
|
||||
@@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
};
|
||||
// A copy that lies the same way has the size of the selected object when their boxes are as
|
||||
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
|
||||
let same_size = |n: &Node, xf: Affine, turned: bool| {
|
||||
let same_size = |b: Option<Rect>, xf: Affine, turned: bool| {
|
||||
if turned {
|
||||
close(xf.determinant().abs().sqrt(), 1.0)
|
||||
} else {
|
||||
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
|
||||
matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height()))
|
||||
}
|
||||
};
|
||||
let mut out = vec![(*id, Affine::IDENTITY)];
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.forms.pass();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
@@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
_ => false,
|
||||
};
|
||||
// The object count first: it turns most objects down before their form is made.
|
||||
if n.children().map(Vec::len) == count
|
||||
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
|
||||
&& (!o.size || same_size(n, xf, turned))
|
||||
&& (!o.appearance || same_look(key, n))
|
||||
&& in_scope(n)
|
||||
{
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
if n.children().map(Vec::len) != count {
|
||||
return look_in;
|
||||
}
|
||||
let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None });
|
||||
if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) {
|
||||
let b = seen.bounds(n, &symbols);
|
||||
if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) {
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
look_in
|
||||
});
|
||||
cache.forms.end(pass, d);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to
|
||||
/// the next so that after an edit only the objects the edit replaced are measured again. A clone
|
||||
/// starts empty.
|
||||
#[derive(Default)]
|
||||
pub struct FormCache(std::cell::RefCell<FormCacheInner>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct FormCacheInner {
|
||||
forms: ByNode<Seen>,
|
||||
/// The outline of each highlighted object, or `None` when it has none and its box is shown.
|
||||
outlines: ByNode<Option<BezPath>>,
|
||||
}
|
||||
|
||||
/// An object as [`matches`] found it.
|
||||
struct Seen {
|
||||
/// Its form, or `None` when Global Edit doesn't support it.
|
||||
form: Option<Form>,
|
||||
/// Its geometric bounds, once measured; not kept for an object with symbol instances, whose
|
||||
/// bounds follow the symbols' art.
|
||||
bounds: Option<Option<Rect>>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option<Rect> {
|
||||
if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) {
|
||||
return n.geometric_bounds_with(symbols);
|
||||
}
|
||||
*self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols))
|
||||
}
|
||||
}
|
||||
|
||||
/// Values found for nodes of a document, by node address. The layers they were found in are held,
|
||||
/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so
|
||||
/// no other node can have that address while its entry is here.
|
||||
struct ByNode<T> {
|
||||
layers: Vec<Arc<Node>>,
|
||||
values: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Default for ByNode<T> {
|
||||
fn default() -> Self {
|
||||
Self { layers: vec![], values: ByAddress::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Values by node address.
|
||||
type ByAddress<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHasher>>;
|
||||
|
||||
/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low
|
||||
/// half (addresses are aligned, so their low bits are always the same).
|
||||
#[derive(Default)]
|
||||
struct AddressHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for AddressHasher {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_usize(&mut self, n: usize) {
|
||||
let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
|
||||
self.0 = x ^ (x >> 32);
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One walk of a document: the values it asks for, taken from the ones kept or found anew.
|
||||
struct Pass<T> {
|
||||
old: ByAddress<T>,
|
||||
new: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Pass<T> {
|
||||
fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T {
|
||||
let at = std::ptr::from_ref(n) as usize;
|
||||
let old = &mut self.old;
|
||||
self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ByNode<T> {
|
||||
fn pass(&mut self) -> Pass<T> {
|
||||
let old = std::mem::take(&mut self.values);
|
||||
Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old }
|
||||
}
|
||||
|
||||
/// Keep the values `pass` asked for, found in `d`.
|
||||
fn end(&mut self, pass: Pass<T>, d: &Document) {
|
||||
self.values = pass.new;
|
||||
self.layers.clone_from(&d.layers);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for FormCache {
|
||||
fn clone(&self) -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FormCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let c = self.0.borrow();
|
||||
f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.global_edit.is_some() {
|
||||
@@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines {
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
members
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.outlines.pass();
|
||||
let out = members
|
||||
.iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
|
||||
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
|
||||
return None;
|
||||
// One look-up of the object's place, then down through its layers and groups: none of
|
||||
// them may be selected, and the innermost layer gives the color.
|
||||
let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None);
|
||||
for i in st.doc.index_path(*id)? {
|
||||
let c: &Node = nodes.get(i)?;
|
||||
if st.selection.objects.contains(&c.id) {
|
||||
return None;
|
||||
}
|
||||
if c.is_layer() {
|
||||
layer = Some(c);
|
||||
}
|
||||
if let Some(ch) = c.children() {
|
||||
nodes = ch;
|
||||
}
|
||||
found = Some(c);
|
||||
}
|
||||
let path = match n.stroke_path() {
|
||||
Some(p) => p,
|
||||
let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?;
|
||||
let color = match layer.map(|l| &l.kind) {
|
||||
Some(NodeKind::Layer { color, .. }) => color.rgb(),
|
||||
_ => vectorcraft_doc::LAYER_COLORS[0].1,
|
||||
};
|
||||
let path = match pass.get(n, || {
|
||||
#[cfg(test)]
|
||||
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
|
||||
n.stroke_path()
|
||||
}) {
|
||||
Some(p) => p.clone(),
|
||||
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
|
||||
};
|
||||
Some((path, st.doc.layer_color(*id)))
|
||||
Some((path, color))
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
cache.outlines.end(pass, &st.doc);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -86,6 +86,9 @@ pub struct DocState {
|
||||
/// Whether Start Global Edit supports the one selected object
|
||||
/// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable.
|
||||
pub(crate) global_edit_support: cmd::globaledit::SupportCache,
|
||||
/// The forms Start Global Edit compared the selected object with
|
||||
/// ([`cmd::globaledit::FormCache`]). Not saved, not undoable.
|
||||
pub(crate) global_edit_forms: cmd::globaledit::FormCache,
|
||||
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
|
||||
pub(crate) symbol_edit_return: cmd::symboledit::Return,
|
||||
pub interaction: Option<Interaction>,
|
||||
@@ -481,6 +484,7 @@ impl DocState {
|
||||
global_edit: None,
|
||||
similar_outlines: Default::default(),
|
||||
global_edit_support: Default::default(),
|
||||
global_edit_forms: Default::default(),
|
||||
symbol_edit_return: Default::default(),
|
||||
interaction: None,
|
||||
undo_group: None,
|
||||
|
||||
@@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts
|
||||
assert!(highlights(&s).is_empty(), "two objects selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights};
|
||||
let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get));
|
||||
let since = |b: (usize, usize)| {
|
||||
let n = made();
|
||||
(n.0 - b.0, n.1 - b.1)
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
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.0, 10.0)).collect();
|
||||
sel(&mut s, &[key]);
|
||||
let before = made();
|
||||
assert_eq!(highlights(&s).len(), 39);
|
||||
assert_eq!(since(before), (40, 39), "the first preview measures each object");
|
||||
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");
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
sel(&mut s, &[copies[1]]);
|
||||
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
|
||||
sel(&mut s, &[copies[2]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
let before = made();
|
||||
let shown = highlights(&s);
|
||||
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
|
||||
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
|
||||
let moved = node(&s, copies[1]).stroke_path().unwrap();
|
||||
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
|
||||
let mut s = session();
|
||||
|
||||
Reference in New Issue
Block a user