diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 1a15e44aa3..c86bd4c792 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -192,7 +192,11 @@ fn apply_transform_moving_guides( if copy { vec![] } else { ids } } else { let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; - s.edit(label, |d, sel| { + // A move of whole objects, not of copies (which `reindex` covers): the document before it, + // and the moved objects as the transform left them, for [`moved_by`] to check after the edit. + let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?; + let mut held: Vec<(NodeId, Arc)> = vec![]; + let targets = s.edit(label, |d, sel| { let mut targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the // loop below transforms only the copies. @@ -229,6 +233,10 @@ fn apply_transform_moving_guides( transform_node(n, xf, sc, objects); } } + // Holding them makes any later change to them copy them first, which `moved_by` sees. + if from.is_some() { + held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect(); + } if objects { for id in &targets { super::pixelgrid::keep_compound_aligned(d, *id, sc); @@ -248,7 +256,10 @@ fn apply_transform_moving_guides( targets.extend(d.transform_ruler_guides(sel, xf)); } Ok(targets) - })? + })?; + let st = s.doc_mut()?; + st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5]))); + targets }; let st = s.doc_mut()?; if st.interaction.is_none() { @@ -266,6 +277,47 @@ fn apply_transform_moving_guides( Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) } +/// The node at index path `path` of `d`, shared. +fn node_arc(d: &Document, path: &[usize]) -> Option> { + let (first, rest) = path.split_first()?; + let mut cur = d.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur.clone()) +} + +/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved +/// objects as the transform left them (`held`). `None` unless every moved object is still that +/// node, none is a member of a blend (whose spine follows its members), and every object the +/// selection shows, the key object and the key anchor's object included, is a moved object or +/// inside one. A pass after the transform that changes a moved object, such as the one that snaps +/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it +/// first, so it is no longer that node. +fn moved_by(from: &Arc, st: &crate::DocState, held: &[(NodeId, Arc)], by: Vec2) -> Option { + let d = &st.doc; + let unchanged = |(id, n): &(NodeId, Arc)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n))); + if held.is_empty() || !held.iter().all(unchanged) { + return None; + } + let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. })); + if held.iter().any(|(id, _)| in_blend(*id)) { + return None; + } + let mut moved = std::collections::HashSet::new(); + for (_, n) in held { + n.walk(&mut |c| { + moved.insert(c.id); + }); + } + let sel = &st.selection; + let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id)); + if !shown.all(|id| moved.contains(&id)) { + return None; + } + Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() }) +} + /// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction /// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot /// back first). These are the copies the interaction keeps when they were made of that snapshot for diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index e1bb6df83a..39be553eb6 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -203,6 +203,24 @@ pub struct DocState { /// The selected objects as [`crate::Session::select`] last checked them or the proxies last /// read them, with the document they were checked in ([`SelectionRecord`]). Not saved. pub(crate) selection_record: Option, + /// The last move of the selected objects that changed nothing else they show ([`Moved`]). + /// Not saved. + pub moved: Option, +} + +/// A move of whole objects that took document `from` to document `to`: each object the selection +/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and +/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine +/// they follow, no pass after the edit). A view that drew the selection of `from` can +/// move what it drew by `by` instead of building it again. It holds the documents as +/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches. +#[derive(Clone, Debug)] +pub struct Moved { + pub from: std::sync::Weak, + pub to: std::sync::Weak, + pub by: vectorcraft_geom::Vec2, + /// The selection the move was made with, which is also the selection after it. + pub selection: Selection, } /// A selection of objects alone ([`objects_only`]) with the document it was checked or read in: @@ -522,6 +540,7 @@ impl DocState { measured_in_own: None, inline_resolved: None, selection_record: None, + moved: None, } } /// The [`SelectionRecord`] of the selection now: `None` when the document or the selected diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 48964aad0c..3e132c5f9e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -507,7 +507,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; -pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView}; +pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9e3cf2371e..89f74fd03d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -118,6 +118,7 @@ mod livecorners; mod maskview; pub(super) mod menucmds; mod mesh_picks; +mod moved; mod nativefile; mod newart; mod newdoc; diff --git a/crates/engine/src/tests/moved.rs b/crates/engine/src/tests/moved.rs new file mode 100644 index 0000000000..1b70d4acf8 --- /dev/null +++ b/crates/engine/src/tests/moved.rs @@ -0,0 +1,127 @@ +//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far +//! it went, and only when every object the selection shows is the one before it, moved that far. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::Vec2; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn doc(s: &Session) -> Arc { + s.doc().unwrap().doc.clone() +} + +/// The move [`DocState::moved`] names, when it took `from` to the document now. +fn moved_from(s: &Session, from: &Arc) -> Option { + let st = s.doc().unwrap(); + let m = st.moved.as_ref()?; + (m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by) +} + +// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the +// document the drag began with. +#[test] +fn a_move_of_whole_objects_names_the_documents_and_the_distance() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a, b]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap(); + assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move"); + let before = doc(&s); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge"); + + let start = doc(&s); + s.begin_interaction("Move").unwrap(); + for dx in [3.0, 7.5] { + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap(); + assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}"); + } +} + +// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move +// of part of what the selection shows name no move. +#[test] +fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a, b]); + let cases = [ + ("object.move", json!({"dx": 12, "dy": 0, "copy": true})), + ("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})), + ("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})), + ("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})), + ("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})), + ]; + for (cmd, p) in cases { + select(&mut s, &[a, b]); + let before = doc(&s); + s.execute(cmd, &p).unwrap(); + assert_eq!(moved_from(&s, &before), None, "{cmd} {p}"); + } +} + +// The key object is shown too: a move that leaves it where it was names no move. +#[test] +fn a_key_object_left_where_it_was_names_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0)); + select(&mut s, &[a]); + s.active_mut().unwrap().selection.key = Some(b); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None); +} + +// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel +// grid snaps after the edit: neither is the object before the move moved by its distance. +#[test] +fn objects_that_snap_to_the_pixel_grid_name_no_move() { + let mut s = session(); + let a = rect(&mut s, 20.0); + select(&mut s, &[a]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path"); + + let mut s = session(); + let art = rect(&mut s, 20.0); + let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap(); + select(&mut s, &[id_of(&made)]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid"); +} + +// A member of a blend moved on its own changes the blend's spine. +#[test] +fn a_member_of_a_blend_names_no_move() { + let mut s = session(); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0)); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap(); + select(&mut s, &[a]); + let before = doc(&s); + s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap(); + assert_eq!(moved_from(&s, &before), None); +} diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index e0ac7e7aee..dd2b85fcca 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::collections::hash_map::{DefaultHasher, Entry}; use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Weak}; use craft::behavior::Input; use craft::behavior::Metrics; @@ -18,9 +19,9 @@ use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline}; use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, NodeId, NodeKind}; use vectorcraft_engine::{DocState, Prefs, ViewInfo}; -use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; +use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point, Vec2}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; @@ -632,9 +633,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect); } let key = marks_key(app, st, tool, tool_points); + let view = view_key(app, st, tool, tool_points); let marks = match app.canvas.selection_marks.take() { Some(kept) if kept.key == key => kept, - _ => SelectionMarks::build(app, st, tool, tool_points, key), + Some(kept) if kept.view == view && kept.selection == st.selection => { + kept.follow(st, key).unwrap_or_else(|| SelectionMarks::build(app, st, tool, tool_points, (key, view))) + } + _ => SelectionMarks::build(app, st, tool, tool_points, (key, view)), }; for o in &marks.outlines { let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision); @@ -663,29 +668,99 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } /// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with -/// nothing changed walks no selected object. +/// nothing changed walks no selected object. They are also kept while the document and the selection stay the same +/// under another revision, and moved with the selection when a move ([`vectorcraft_engine::Moved`]) took the document +/// they show to the one now. pub(crate) struct SelectionMarks { key: u64, + /// [`view_key`] of the state they were made for. + view: u64, + /// The selection they show. + selection: vectorcraft_doc::Selection, + /// The document they show. + doc: Weak, + /// A document they show moved by a distance: the one they were built for and no distance, or the document the + /// last move they followed started from and its distance. Each step of a drag starts from the document the drag + /// began with ([`SelectionMarks::follow`]). + from: (Weak, Vec2), outlines: Vec, anchors: Anchors, dots: Dots, } impl SelectionMarks { - fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self { + fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, (key, view): (u64, u64)) -> Self { #[cfg(test)] tests::MARKS_BUILT.with(|built| built.set(built.get() + 1)); - Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) } + let doc = Arc::downgrade(&st.doc); + Self { + key, + view, + selection: st.selection.clone(), + from: (doc.clone(), Vec2::ZERO), + doc, + outlines: outlines(app, st), + anchors: anchors(app, st, tool, tool_points), + dots: dots(app, st), + } + } + + /// The marks of `st`, whose [`marks_key`] is `key`, from these marks of the same selection and view: these marks + /// when `st` shows the same document, these marks moved by `st`'s move when it took the document they show, or the + /// document of [`SelectionMarks::from`], to the one `st` shows, else `None`. + fn follow(mut self, st: &DocState, key: u64) -> Option { + let now = Arc::as_ptr(&st.doc); + if self.doc.as_ptr() != now { + let moved = st.moved.as_ref().filter(|m| m.to.as_ptr() == now && m.selection == st.selection)?; + let by = if moved.from.ptr_eq(&self.doc) { + moved.by + } else if moved.from.ptr_eq(&self.from.0) { + moved.by - self.from.1 + } else { + return None; + }; + self.translate(by); + self.from = (moved.from.clone(), moved.by); + self.doc = moved.to.clone(); + } + self.key = key; + Some(self) + } + + /// Moves every mark by `by`. + fn translate(&mut self, by: Vec2) { + let shift = vectorcraft_geom::Affine::translate(by); + for o in &mut self.outlines { + o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift)); + o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array()); + } + for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { + knot.anchor += by; + knot.in_ctrl += by; + knot.out_ctrl += by; + } + let dots = &mut self.dots; + for (at, _) in dots.origins.iter_mut().chain(&mut dots.centers).chain(&mut dots.key_anchor) { + *at += by; + } } } -/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the -/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the -/// Selection & Anchor Display preferences. +/// What the selection's marks are built from: the document and its selection (its uid and revision), and what +/// [`view_key`] hashes. fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 { + let mut h = DefaultHasher::new(); + (st.revision, view_key(app, st, tool, tool_points)).hash(&mut h); + h.finish() +} + +/// What the selection's marks are built from besides the document's content and the selection: the document (its +/// uid), the parts the view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, +/// and the Selection & Anchor Display preferences. +fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 { let mut h = DefaultHasher::new(); let hides = ViewHides::of(app); - (st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h); + (st.uid, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h); let prefs = &app.session.prefs; (prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h); h.finish() diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 672b07094a..e413a5655c 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -918,3 +918,75 @@ fn the_canvas_builds_the_selection_marks_once_per_change() { app.select_tool("directSelection"); assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once"); } + +/// Every point of the outlines, the anchors and their handles, and the dots, in order. +fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec { + let mut out = vec![]; + for path in outlines.iter().flat_map(|o| o.paths.iter().chain(&o.key)) { + for el in path.elements() { + match *el { + PathEl::MoveTo(a) | PathEl::LineTo(a) => out.push(a), + PathEl::QuadTo(a, b) => out.extend([a, b]), + PathEl::CurveTo(a, b, c) => out.extend([a, b, c]), + PathEl::ClosePath => {} + } + } + } + for knot in anchors.paths.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) { + out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]); + } + out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at)); + out +} + +/// Whether the marks the canvas keeps are, to rounding, the ones the builders give for the state now. +fn kept_marks_are_current(app: &VectorcraftApp) -> bool { + let kept = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); + let st = app.session.active().unwrap(); + let now = points_of(&outlines(app, st), &anchors(app, st, app.session.tool_id(), false), &dots(app, st)); + let was = points_of(&kept.outlines, &kept.anchors, &kept.dots); + now.len() == was.len() && now.iter().zip(&was).all(|(a, b)| (*a - *b).hypot() < 1e-9) +} + +// Whole-app frames keep the selection's marks through a new revision of the same document and selection, and move +// them with a move of the selection instead of building them: a move command, each step of a drag, and the drag's end +// build nothing and keep the marks of the state now. A scale and an undo still build them once. +#[test] +fn a_move_of_the_selection_moves_its_marks_without_building_them() { + let (mut app, _) = scene(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MARKS_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }); + } + MARKS_BUILT.with(std::cell::Cell::get) - before + }; + frames(&mut app, 3); + let layer = app.session.active().unwrap().doc.layers[0].id; + let revision = app.session.active().unwrap().revision; + app.run("layer.setCurrent", json!({"id": layer.0})).unwrap(); + assert_ne!(app.session.active().unwrap().revision, revision, "a new revision"); + assert_eq!(frames(&mut app, 3), 0, "a new revision of the same document and selection"); + app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap(); + assert_eq!(frames(&mut app, 3), 0, "a move command"); + assert!(kept_marks_are_current(&app), "after a move command"); + + app.session.begin_interaction("Move").unwrap(); + for dx in [3.0, 7.5, -2.0] { + app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 4], "copy": false})).unwrap(); + assert_eq!(frames(&mut app, 2), 0, "a drag's step by {dx}"); + assert!(kept_marks_are_current(&app), "after a drag's step by {dx}"); + } + app.session.commit_interaction().unwrap(); + assert_eq!(frames(&mut app, 2), 0, "the drag's end"); + assert!(kept_marks_are_current(&app), "after the drag"); + + app.run("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})).unwrap(); + assert_eq!(frames(&mut app, 3), 1, "a scale"); + assert!(kept_marks_are_current(&app), "after a scale"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frames(&mut app, 3), 1, "an undo"); + assert!(kept_marks_are_current(&app), "after an undo"); +}