From 828f43447d19a46e0906d2e03421ae47591da4d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:15:20 -0800 Subject: [PATCH 1/7] Undo: a command run during a tool drag is its own undo step A command run from a panel, a menu or an automation client while a tool drag was open ran inside the drag. With Real-time Drawing on, the drag's next move put the document back to where the drag began and dropped the command's edit, and Escape dropped it too. With Real-time Drawing off, the release lost what the drag drew or moved. Such a command now runs on the document without the drag's preview and records its own undo step and journal entry. The drag then continues from the command's result: with Real-time Drawing on, its preview is applied again at once. The release records the drag's step after the command's, Undo takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes does not change what it moves, and the fill and stroke proxies keep showing those objects' paints. Objects the command deletes, hides or locks are left out of the drag. A change the command makes to the current layer or to the new-art paints stays when the drag ends or is canceled. When the command deletes the art being dragged, the drag records no step. A warning or an error from the preview applied again goes to the command's result. Commands that already kept the drag as a step first still do (Undo, Redo, command.batch, swatch.renameGroup, edit.newDocumentFromState and the others that call settle_interaction). Typing in progress is still kept as a step of its own first. A command run during a Quick Pen press, object.transform with copy during an Alt-drag, and a command run during a dialog's or a panel's preview still run inside the interaction. Docs: docs/mcp.md (undo / redo row), docs/target-app-parity.md. --- crates/engine/src/cmd/edit.rs | 5 +- crates/engine/src/cmd/swatch.rs | 2 +- crates/engine/src/interaction.rs | 59 +++ crates/engine/src/lib.rs | 5 +- crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/edit.rs | 174 +++++++ crates/engine/src/session/execute.rs | 7 +- crates/engine/src/tests.rs | 1 + .../engine/src/tests/interaction_commands.rs | 485 ++++++++++++++++++ crates/engine/src/tooling.rs | 15 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/drag_commands.rs | 48 ++ docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 14 files changed, 800 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/tests/interaction_commands.rs create mode 100644 crates/ui-egui/src/tests/drag_commands.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a20a6c47e4..fc31c86349 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -695,6 +695,7 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result { /// goes to the running command's result or the tool's status messages, as the tool's own commit /// reports it ([`Session::note_settled_warning`]). pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { + s.put_back_interaction(); let typing = typing_in_progress(s); match s.unapplied_interaction_preview().filter(|_| !s.previewing) { Some((cmd, p)) => match s.preview(&cmd, &p) { @@ -894,8 +895,10 @@ fn clear_history(s: &mut Session, _: &Value) -> Result { fn new_document_from_state(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.newDocumentFromState"; let created = date_param(p, "created", C)?; + // The row as the panel lists it now, with a drag in progress on show: keeping it below + // changes the rows. + s.put_back_interaction(); let st = s.doc()?; - // The row as the panel lists it now: keeping an edit in progress below changes the rows. let chosen = match super::index_opt(p, "index", C)? { None => None, Some(row) => { diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 511352b9a5..8137e561cf 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1252,7 +1252,7 @@ fn swatch_rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("a swatch or color group named `{name}` already exists"))); } // A drag still in progress is a step of its own, so canceling or undoing it leaves the rename. - if !s.previewing && s.batch_stash.is_none() && s.in_interaction() { + if !s.previewing && s.batch_stash.is_none() && (s.in_interaction() || s.holds_interaction()) { super::settle_interaction(s)?; } s.edit("Color Group Options", |d, _| { diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 06cc86859e..a06c160897 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -8,6 +8,10 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub preview: Option<(String, Value)>, + /// The active tool began it (a drag): a command from outside the tool runs as a step of its + /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an + /// interaction runs its commands inside it. + pub(crate) tool: bool, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, /// An accepted batch preview uses these final paints after changing the document color mode. @@ -35,6 +39,61 @@ pub struct Interaction { pub(crate) move_box: std::sync::OnceLock>, } +/// An interaction that a command from outside the tool set aside while it runs +/// ([`crate::Session::outside_interaction`]). +#[derive(Debug)] +pub(crate) struct HeldInteraction { + /// The [`crate::DocState::uid`] of the interaction's document. + pub(crate) uid: u64, + pub(crate) interaction: Interaction, + /// The document and the selection on show when the command began, when a preview had changed + /// them from the interaction's snapshot. + pub(crate) shown: Option<(Arc, Selection)>, + /// The document's current layer, highlighted Layers panel rows, highlighted variable and + /// isolation when the command began; a cancel puts back the ones it changed as it left them. + pub(crate) state: ViewState, + /// The new-art paints when the command began: a change the command makes to them stays when + /// the interaction's next preview or a cancel puts back the paints it began with. + pub(crate) paint: vectorcraft_tools::PaintDefaults, +} + +/// The per-document state an interaction puts back when it is canceled, besides the document and +/// the selection. +#[derive(Debug, PartialEq)] +pub(crate) struct ViewState { + pub(crate) active_layer: Option, + pub(crate) layer_rows: Vec, + pub(crate) variables_highlight: Option, + pub(crate) isolation: Option, +} + +impl ViewState { + pub(crate) fn of(st: &crate::DocState) -> Self { + ViewState { + active_layer: st.active_layer, + layer_rows: st.layer_rows.clone(), + variables_highlight: st.variables_highlight.clone(), + isolation: st.isolation, + } + } + + /// Give `it` the parts of `now` that differ from `self`, the state before a command. + pub(crate) fn rebase(&self, now: ViewState, it: &mut Interaction) { + if now.active_layer != self.active_layer { + it.active_layer = now.active_layer; + } + if now.layer_rows != self.layer_rows { + it.layer_rows = now.layer_rows; + } + if now.variables_highlight != self.variables_highlight { + it.variables_highlight = now.variables_highlight; + } + if now.isolation != self.isolation { + it.isolation = now.isolation; + } + } +} + /// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]). #[derive(Clone, Debug, PartialEq)] pub enum LastTransform { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..472ae9c8f8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -320,6 +320,9 @@ pub struct Session { /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). settled_warnings: Option>, + /// The interaction a command from outside the tool set aside while it runs + /// ([`Session::outside_interaction`]). + held_interaction: Option, /// While [`Session::preview`] runs its command: its edits are the interaction's own. previewing: bool, /// The images Remove Background decoded during the interaction's preview steps, emptied when @@ -438,7 +441,7 @@ pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; -pub(crate) use interaction::PreviewCopies; +pub(crate) use interaction::{HeldInteraction, PreviewCopies}; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..8e43a8ce34 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -137,6 +137,7 @@ impl Session { recovery: Default::default(), in_tool_actions: false, settled_warnings: None, + held_interaction: None, previewing: false, decoded_images: Default::default(), envelope_defaults: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index e2ba1715b9..5930c8d9c0 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -260,6 +260,163 @@ impl Session { (r, settled) } + /// Run `f`, the top-level command `id` with `params` from outside the tool (a panel, a menu + /// item, an automation client), with the active document's tool drag set aside: the command + /// runs on the document the drag started from and records its own undo step and journal entry. + /// The drag then starts from what the command left, and its preview is applied again, so the + /// next preview, the commit and a cancel keep the command's edit, and Undo takes back the drag's + /// step before the command's. While the command runs, [`Session::in_interaction`] is false, so + /// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with + /// no drag in progress. + /// + /// The interaction stays as it is, and the command runs inside it, for an interaction a dialog + /// or a panel began (it builds its preview from commands), for typing in progress + /// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside + /// it ends the path it draws), and for a copy made with `object.transform` during a drag that + /// copies (it copies the document as the drag's move left it). A command that settles, + /// commits or cancels the interaction, or that hands the active tool actions to apply, gets it + /// back first ([`Session::put_back_interaction`]), as it found it. + pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result) -> Result { + if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID { + return f(self); + } + let Some(st) = self.active_mut() else { return f(self) }; + let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) }; + // A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies. + let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true)); + if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) { + return f(self); + } + let Some(interaction) = st.interaction.take() else { return f(self) }; + // The document and selection on show, when a preview changed them. + let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection; + let shown = previewed.then(|| (st.doc.clone(), st.selection.clone())); + if previewed { + st.doc = interaction.doc.clone(); + st.selection.clone_from(&interaction.selection); + st.revision += 1; + cmd::globaledit::follow_history(st); + } + let (uid, state) = (st.uid, crate::interaction::ViewState::of(st)); + let paint = self.paint.clone(); + self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint }); + if previewed { + self.sync_front_profiles(); + } + let r = f(self); + self.put_back_interaction(); + r + } + + /// Put back the interaction [`Session::outside_interaction`] set aside. When the command left + /// the document and the selection as it found them, the preview on show before it is on show + /// again. Otherwise the interaction starts from the document the command left and from its + /// own selection, without the objects the command removed, hid or locked, and the preview that Real-time + /// Drawing showed is applied to it again. The warning or the error of that preview goes to + /// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the + /// interaction with nothing to commit. An interaction whose document the command closed ends, + /// and a document the command left an interaction of its own on keeps that one. + pub(crate) fn put_back_interaction(&mut self) { + let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return }; + // A selection command loaded the paints of the selection it made into the fill and stroke + // proxies. The drag goes on with its own selection, so they show its paints again. + if self.paint != paint + && let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none()) + { + let own = drag_selection(&it.selection, &st.doc); + if st.selection != own { + let made = std::mem::replace(&mut st.selection, own); + self.inherit_new_art(); + self.load_selection_paints(); + if let Some(st) = self.active_mut() { + st.selection = made; + } + } + } + // A change the command made to the new-art paints stays when the next preview or a cancel + // puts back the paints the interaction began with (the Live Paint Bucket's colors); the + // parts it left alone keep the interaction's. + let (now, start) = (&self.paint, &mut it.paint); + if now.fill != paint.fill { + start.fill.clone_from(&now.fill); + } + if now.stroke != paint.stroke { + start.stroke.clone_from(&now.stroke); + } + if now.stroke_width != paint.stroke_width { + start.stroke_width = now.stroke_width; + } + if now.appearance != paint.appearance { + start.appearance.clone_from(&now.appearance); + } + if now.opacity != paint.opacity { + start.opacity = now.opacity; + } + if now.blend != paint.blend { + start.blend = now.blend; + } + if now.style != paint.style { + start.style.clone_from(&now.style); + } + if now.inherited != paint.inherited { + start.inherited = now.inherited; + } + let active = self.active().is_some_and(|d| d.uid == uid); + let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; + if st.interaction.is_some() { + return; + } + // A change the command made to the current layer, the highlighted rows or variable, or + // isolation stays when the interaction is canceled. + state.rebase(crate::interaction::ViewState::of(st), &mut it); + let previewed = shown.is_some(); + if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection { + if let Some((doc, selection)) = shown { + st.doc = doc; + st.selection = selection; + st.revision += 1; + cmd::globaledit::follow_history(st); + } + st.interaction = Some(it); + if previewed { + self.sync_front_profiles(); + } + return; + } + it.doc = st.doc.clone(); + // The drag acts on the objects it began with: a selection the command made (a paste, a + // duplicate, Select All) does not change what the drag moves. + it.selection = Arc::new(drag_selection(&it.selection, &st.doc)); + it.copies = None; + it.move_box = std::sync::OnceLock::new(); + // With Real-time Drawing off the preview waits for the commit, as it did before the command. + let again = it.preview.clone().filter(|_| previewed && active); + // Without a preview to apply, the drag's own selection is on show, as a preview would leave + // it before it acts. + if again.is_none() && st.selection != *it.selection { + st.selection.clone_from(&it.selection); + st.revision += 1; + } + st.interaction = Some(it); + self.clear_deferred_overlay_cache(); + if let Some((cmd, p)) = again { + match self.preview(&cmd, &p) { + Ok(v) => { + if let Some(w) = v.get("warning").and_then(Value::as_str) { + self.note_settled_warning(w); + } + } + Err(e) => self.note_settled_warning(&e.to_string()), + } + } + } + + /// While a command from outside the tool runs: the interaction it set aside + /// ([`Session::outside_interaction`]). + pub(crate) fn holds_interaction(&self) -> bool { + self.held_interaction.is_some() + } + /// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings /// of the preview that keeping typing in progress applied, for its status bar. pub fn begin_interaction_warned(&mut self, label: &str) -> Result> { @@ -284,6 +441,8 @@ impl Session { if label != "Typing" && cmd::typing_in_progress(self) { cmd::settle_interaction(self)?; } + // A command from outside the tool that begins an interaction during a drag joins the drag's. + self.put_back_interaction(); // An edit the tool computes on another thread (a Shape Builder merge) is applied first too, // so the snapshot the interaction previews from and goes back to holds it. if !self.in_interaction() { @@ -300,6 +459,7 @@ impl Session { doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, + tool: false, paint, preview_paint: None, color_mode_paints: None, @@ -318,6 +478,7 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { + self.put_back_interaction(); if self.script_running() { return Err(EngineError::Busy); } @@ -392,6 +553,7 @@ impl Session { pub fn commit_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); self.decoded_images.empty(); + self.put_back_interaction(); if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } @@ -481,6 +643,7 @@ impl Session { } pub fn cancel_interaction(&mut self) -> Result<()> { + self.put_back_interaction(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; @@ -512,3 +675,14 @@ impl Session { self.active().is_some_and(|d| d.interaction.is_some()) } } + +/// The selection a drag began with, without the objects that a command run during it removed, +/// hid or locked in `doc`. +fn drag_selection(began: &Selection, doc: &Document) -> Selection { + let mut selection = began.clone(); + selection.prune(doc); + let editable = doc.editable(); + let held: Vec<_> = selection.objects.iter().copied().filter(|&id| !editable(id)).collect(); + selection.remove_all(held); + selection +} diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..ac987a83be 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -75,10 +75,15 @@ impl Session { self.finish_tool_edit_later()?; } let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id)); + // A command from outside the tool, while the tool's drag is in progress, is a step of its + // own before the drag's ([`Session::outside_interaction`]). + let outside = spec.journal && !self.previewing && !self.in_tool_actions; // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept // before Undo) reports its warning in the command's result. let r = if self.depth == 0 { - let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params)); + let (r, settled) = self.collect_settled_warnings(|s| { + if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) } + }); r.map(|v| with_settled_warnings(v, &settled)) } else { self.execute_spec(spec, id, params) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..de919c224a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -87,6 +87,7 @@ mod history_document; mod history_mem; mod ids_without_selection; mod inline; +mod interaction_commands; mod interactivity; mod interpolate_handles; mod intertwine; diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs new file mode 100644 index 0000000000..e18b0db56d --- /dev/null +++ b/crates/engine/src/tests/interaction_commands.rs @@ -0,0 +1,485 @@ +//! A command run from outside the tool (a panel, a menu item, an automation client) while a tool's drag is +//! in progress is a step of its own, before the drag's: the drag's next preview, its release and +//! Escape keep the command's edit, and the release still draws what the drag drew, with Real-time +//! Drawing on and off. + +use serde_json::json; +use vectorcraft_geom::Rect; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +/// The view the gestures run in: page coordinates, with Smart Guides off so nothing snaps. +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +/// Feed the pointer event `(kind, x, y)` to the active tool. +fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) { + s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap(); +} + +/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding one 20 × 20 pt rectangle +/// (returned), nothing selected, and the Rectangle tool chosen. +fn session(real_time: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("rectangle", view()).unwrap(); + (s, other) +} + +fn visible(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).expect("the object is in the document").visible +} + +/// The objects of the document's first layer. +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len) +} + +/// The commands journaled from entry `start` on. +fn journaled(s: &Session, start: usize) -> Vec { + s.journal.iter().skip(start).map(|(id, _)| id.clone()).collect() +} + +#[test] +fn a_command_during_a_drag_is_a_step_of_its_own_before_the_drag() { + for real_time in [true, false] { + let (mut s, other) = session(real_time); + let (steps, start) = (s.doc().unwrap().history.undo.len(), s.journal.len()); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert!(!visible(&s, other), "real time {real_time}: the command hides the object at once"); + pointer(&mut s, PointerKind::Drag, 200.0, 180.0); + assert!(!visible(&s, other), "real time {real_time}: the drag's next preview keeps the command's edit"); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + assert!(!visible(&s, other), "real time {real_time}: the release keeps the command's edit"); + assert_eq!(objects(&s), 2, "real time {real_time}: the release draws the rectangle"); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_ne!(drawn, other); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[drawn], false), Some(Rect::new(100.0, 100.0, 200.0, 180.0)), "real time {real_time}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the command and the drag are a step each"); + assert_eq!(journaled(&s, start), ["object.hide", "shape.rectangle"], "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 1, "real time {real_time}: Undo takes back the drawn rectangle"); + assert!(!visible(&s, other), "real time {real_time}: and leaves the command's edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}: the next Undo takes back the command's edit"); + } +} + +#[test] +fn escape_after_a_command_during_a_drag_keeps_the_command() { + for real_time in [true, false] { + let (mut s, other) = session(real_time); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert!(!visible(&s, other), "real time {real_time}: Escape takes back only the drag"); + assert_eq!(objects(&s), 1, "real time {real_time}: nothing is drawn"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}"); + } +} + +/// Every object of the first layer but `other`, as the document has it. +fn others(s: &Session, other: NodeId) -> Vec { + let d = &s.doc().unwrap().doc; + d.layers[0].children().map_or_else(Vec::new, |c| c.iter().filter(|n| n.id != other).map(|n| (**n).clone()).collect()) +} + +/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding a 40 × 40 pt square at +/// (100, 100) and a 20 × 20 pt one at (10, 10) → the session, the larger square (selected) and the +/// smaller one. +fn two_squares(real_time: bool) -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); + let target = s.doc().unwrap().selection.objects[0]; + (s, target, other) +} + +/// A press at the first point of `pts`, drags to the others and a release at the last, with +/// `mid` run after the first drag. +fn drag_with(s: &mut Session, pts: &[(f64, f64)], mid: impl FnOnce(&mut Session)) { + let (&(x0, y0), rest) = pts.split_first().expect("a press"); + pointer(s, PointerKind::Down, x0, y0); + let mut mid = Some(mid); + for &(x, y) in rest { + pointer(s, PointerKind::Drag, x, y); + if let Some(f) = mid.take() { + f(s); + } + } + let &(x, y) = pts.last().expect("a release"); + pointer(s, PointerKind::Up, x, y); +} + +/// Is `id` filled red? +fn red(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill_paint().color()).is_some_and(|c| c.to_hex() == "#ff0000") +} + +/// The Selection tool's move, the Scale and Rotate tools and the Pen, each with a command that +/// fills another object red during the drag: the release keeps both, as two undo steps, and Undo +/// takes back the drag first. +#[test] +fn the_move_scale_rotate_and_pen_drags_keep_a_command_run_during_them() { + let drags: [(&str, &[(f64, f64)]); 4] = [ + ("selection", &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)]), + ("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]), + ("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]), + ("pen", &[(300.0, 300.0), (320.0, 300.0), (350.0, 320.0)]), + ]; + for (tool, pts) in drags { + for real_time in [true, false] { + let at = format!("{tool}, real time {real_time}"); + let (mut s, _, other) = two_squares(real_time); + if tool == "pen" { + s.execute("select.none", &json!({})).unwrap(); + } + s.select_tool(tool, view()).unwrap(); + let (before, steps) = (others(&s, other), s.doc().unwrap().history.undo.len()); + drag_with(&mut s, pts, |s| { + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#ff0000"})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert!(red(&s, other), "{at}: the release keeps the command's edit"); + assert_ne!(others(&s, other), before, "{at}: the release keeps the drag's edit"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(others(&s, other), before, "{at}: Undo takes back the drag"); + assert!(red(&s, other), "{at}: and leaves the command's edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!red(&s, other), "{at}: the next Undo takes back the command's edit"); + } + } +} + +/// A command that changes the object being moved: the move applies to the changed object. +#[test] +fn a_move_drag_moves_the_object_as_a_command_during_it_changed_it() { + for real_time in [true, false] { + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let fill = |s: &Session| s.doc().unwrap().doc.node(target).unwrap().appearance.fill_paint().color().map(|c| c.to_hex()); + let was = fill(&s); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + }); + let moved = s.doc().unwrap().doc.bounds_of(&[target], false); + assert_eq!(moved, Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}: the fill is a step of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s), was, "real time {real_time}"); + } +} + +/// A command that deletes the object being moved: the drag goes on and ends without an edit of +/// its own, on release and on Escape, and the deletion stays. +#[test] +fn a_move_drag_of_an_object_a_command_deleted_ends_without_an_edit() { + for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] { + let at = format!("real time {real_time}, Escape {escape}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap(); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}"); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays"); + assert_eq!(others(&s, other), [], "{at}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}"); + } +} + +/// A command that hides or locks the object being moved: the object stays where it was and +/// unselected, and the drag ends without an edit of its own. +#[test] +fn a_move_drag_of_an_object_a_command_hid_or_locked_leaves_it_alone() { + for command in ["object.hide", "object.lock"] { + for real_time in [true, false] { + let at = format!("{command}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute(command, &json!({"ids": [target.0]})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: not moved"); + assert!(!s.doc().unwrap().selection.objects.contains(&target), "{at}: not selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step"); + } + } +} + +/// The commands that end a drag first still do: Undo during a drag keeps the drag as a step and +/// takes it back, and `command.batch` and `swatch.renameGroup` keep it as a step before their own. +#[test] +fn undo_and_a_batch_during_a_drag_still_keep_the_drag_first() { + for real_time in [true, false] { + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + + let (mut s, target, other2) = two_squares(real_time); + assert_eq!(other, other2); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("command.batch", &json!({"commands": [{"command": "object.hide", "params": {"ids": [other.0]}}]})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}: the batch keeps the drag first"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}: Undo takes back the batch first"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + + // A color group renamed during the drag keeps the drag as a step before the rename. + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("swatch.renameGroup", &json!({"group": "Brights", "name": "Vivid"})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}: the rename keeps the drag first"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == "Brights"), "real time {real_time}: Undo takes back the rename"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + } +} + +/// A copy made with `object.transform` during an Alt-drag runs inside the drag, with Real-time +/// Drawing on and off: the release records one step that holds both. +#[test] +fn a_copy_during_an_alt_drag_is_part_of_the_drag() { + for real_time in [true, false] { + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let alt = Mods { alt: true, ..Mods::default() }; + for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 170.0, 150.0)] { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(alt), view()).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(alt), view()).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}: one step for the drag and the copy"); + + // With Alt let go during the drag, the drag moves again, and the copy is a step of its own. + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0).with_mods(alt), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 140.0).with_mods(alt), view()).unwrap(); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap(); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the copy and the move"); + } +} + +/// A command that changes only the current layer during a drag keeps its change through Escape. +#[test] +fn escape_keeps_a_current_layer_set_during_a_drag() { + for real_time in [true, false] { + let (mut s, _) = session(real_time); + let first = s.doc().unwrap().active_layer; + let second = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let first = first.expect("a current layer"); + s.execute("layer.setCurrent", &json!({"id": first.0})).unwrap(); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("layer.setCurrent", &json!({"id": second.0})).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert_eq!(s.doc().unwrap().active_layer, Some(second), "real time {real_time}"); + } +} + +/// With Real-time Drawing on, the drag's preview is on show again right after the command. +#[test] +fn the_drag_preview_shows_again_after_the_command() { + let (mut s, other) = session(true); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + assert_eq!(objects(&s), 2, "the preview draws the rectangle"); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert_eq!(objects(&s), 2, "the preview is on show after the command"); + s.execute("object.showAll", &json!({})).unwrap(); + assert_eq!(objects(&s), 2, "and after a second one"); + assert!(visible(&s, other)); + assert!(s.in_interaction()); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert_eq!(objects(&s), 2); + assert!(visible(&s, other)); +} + +/// A command that changes the selection during a move drag (Select All, Deselect, a duplicate) +/// leaves the drag moving the object it began with. +#[test] +fn a_selection_made_during_a_move_drag_leaves_the_drag_moving_its_object() { + for command in ["select.all", "select.none", "edit.duplicate"] { + for real_time in [true, false] { + let at = format!("{command}, real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute(command, &json!({})).unwrap(); + }); + let d = &s.doc().unwrap().doc; + assert_eq!(d.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "{at}: the drag moves its object"); + assert_eq!(d.bounds_of(&[other], false), Some(Rect::new(10.0, 10.0, 30.0, 30.0)), "{at}: and nothing else"); + if command == "edit.duplicate" { + let copies = others(&s, other).into_iter().filter(|n| n.id != target).map(|n| n.id).collect::>(); + assert_eq!(copies.len(), 1, "{at}"); + assert_eq!(d.bounds_of(&copies, false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: the copy stays where it was made"); + } + } + } +} + +/// A command that selects another object during a move drag: the drag's object stays selected, +/// and the fill and stroke proxies keep showing its paints. +#[test] +fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.select_tool("selection", view()).unwrap(); + let fill = |s: &Session| s.paint.fill.color().map(|c| c.to_hex()); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}"); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the command"); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the release"); + } +} + +/// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the +/// object they act on during the drag: the drag ends without an edit of its own and the deletion +/// stays. +#[test] +fn a_scale_rotate_or_pen_drag_of_an_object_a_command_deleted_ends_without_an_edit() { + let drags: [(&str, &[(f64, f64)]); 3] = [ + ("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]), + ("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]), + ("pen", &[(350.0, 350.0), (370.0, 360.0), (380.0, 380.0)]), + ]; + for (tool, pts) in drags { + for real_time in [true, false] { + let at = format!("{tool}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.select_tool(tool, view()).unwrap(); + let target = if tool == "pen" { + s.execute("select.none", &json!({})).unwrap(); + for (x, y) in [(300.0, 300.0), (350.0, 300.0)] { + pointer(&mut s, PointerKind::Down, x, y); + pointer(&mut s, PointerKind::Up, x, y); + } + s.doc().unwrap().selection.objects[0] + } else { + target + }; + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, pts, |s| { + s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "{at}: Undo brings the object back as it was"); + } + } +} + +/// With the Live Paint Bucket's Selection tool (Cmd+drag), a fill chosen during the drag stays the +/// new-art fill after the release and after Escape, though the drag puts back the bucket's colors +/// it began with. +#[test] +fn a_fill_chosen_during_a_bucket_drag_stays() { + for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] { + let at = format!("real time {real_time}, Escape {escape}"); + let (mut s, _, _) = two_squares(real_time); + s.select_tool("livePaintBucket", view()).unwrap(); + let cmd = Mods { cmd: true, ..Mods::default() }; + for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 140.0, 130.0)] { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(cmd), view()).unwrap(); + } + assert!(s.in_interaction(), "{at}: the lent Selection tool drags the square"); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": []})).unwrap(); + let green = s.paint.fill.clone(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0).with_mods(cmd), view()).unwrap(); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(cmd), view()).unwrap(); + assert_eq!(s.paint.fill, green, "{at}"); + } +} + +/// A command run during a Quick Pen press still runs inside the press, so it records no undo +/// step of its own while the press is held. +#[test] +fn a_command_during_a_quick_pen_press_runs_inside_it() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = session(real_time); + s.select_tool(vectorcraft_tools::quickpen::ID, view()).unwrap(); + pointer(&mut s, PointerKind::Down, 50.0, 50.0); + pointer(&mut s, PointerKind::Up, 50.0, 50.0); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 120.0); + assert!(s.in_interaction(), "{at}: the press drags a piece"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert!(s.in_interaction(), "{at}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press"); + } +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f3d615ac8d..6c0f83439e 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1611,6 +1611,10 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { + // The tool acts on its own interaction, which a command from outside it may have set aside. + if !acts.is_empty() { + self.put_back_interaction(); + } let outer = std::mem::replace(&mut self.in_tool_actions, true); let outer_bucket = self.back_to_bucket; // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. @@ -1636,7 +1640,16 @@ impl Session { let mut ui = vec![]; for a in acts { match a { - Action::Begin(label) => self.begin_interaction(&label)?, + Action::Begin(label) => { + // The snapshot of the interaction open before, which the tool's drag then joins. + let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc)); + self.begin_interaction(&label)?; + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) + && open != Some(std::sync::Arc::as_ptr(&it.doc)) + { + it.tool = true; + } + } Action::Preview(cmd, p) => { // Performance › Real-time Drawing and Editing (#394): off, remember the latest // params and apply them once on Commit instead of every move. A ruler guide diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..30e5648f23 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -8,6 +8,7 @@ mod cut; mod distortkeys; mod docsetup; mod document_drag; +mod drag_commands; pub(super) mod folder; mod font_menu; mod fonts; diff --git a/crates/ui-egui/src/tests/drag_commands.rs b/crates/ui-egui/src/tests/drag_commands.rs new file mode 100644 index 0000000000..8879c3e25c --- /dev/null +++ b/crates/ui-egui/src/tests/drag_commands.rs @@ -0,0 +1,48 @@ +//! A command sent through the control channel (`engine.execute`, which MCP's `run_command` sends) +//! or run as a menu item while a tool's drag is in progress is a step of its own, before the drag's. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; + +/// Send a control request → its reply. +fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (request, _) = crate::control::ControlRequest::new(method, params); + let crate::control::Outcome::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("{method}: not done") }; + reply +} + +#[test] +fn a_command_from_the_control_channel_or_a_menu_during_a_drag_is_a_step_of_its_own() { + for through_control in [true, false] { + let at = format!("control channel {through_control}"); + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + let objects = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len); + let hidden = |app: &VectorcraftApp| !app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(other)).unwrap().visible; + let steps = app.session.doc().unwrap().history.undo.len(); + let down = json!({"events": [{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 150, "y": 150}]}); + assert_eq!(control(&mut app, &ctx, "ui.pointer", down)["ok"], true, "{at}"); + if through_control { + let r = control(&mut app, &ctx, "engine.execute", json!({"command": "object.hide", "params": {"ids": [other]}})); + assert_eq!(r["ok"], true, "{at}: {r}"); + } else { + app.run("object.hide", json!({"ids": [other]})).unwrap(); + } + let up = json!({"events": [{"kind": "drag", "x": 200, "y": 180}, {"kind": "up", "x": 200, "y": 180}]}); + assert_eq!(control(&mut app, &ctx, "ui.pointer", up)["ok"], true, "{at}"); + assert!(hidden(&app), "{at}: the drag keeps the command's edit"); + assert_eq!(objects(&app), 2, "{at}: the drag draws its rectangle"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 2, "{at}: a step each"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(objects(&app), 1, "{at}: Undo takes back the drag first"); + assert!(hidden(&app), "{at}"); + app.run("edit.undo", json!({})).unwrap(); + assert!(!hidden(&app), "{at}: then the command"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..0759644cc3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -758,7 +758,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..e3968f2379 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -763,6 +763,7 @@ since 2026-10-01. - **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. - **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`. +- **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. - **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`. - **Ctrl/Cmd-click and Shift-click on Layers panel target circles (#8639):** the target circles follow the same modifier rules as the row names, as the help page describes for selecting objects in the Layers panel: Shift for adjacent objects, Ctrl or Command for non-adjacent ones ([Move objects to different layers](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/move-objects-to-different-layers.html)). Ctrl/Cmd-click adds the item (a layer: its art) to the selection or takes it out, which Shift-click did before (#913); Shift-click selects the art of every row from the last circle clicked (else the targeted row) to this one, and Shift+Ctrl/Cmd-click adds it (`layer.target {range, add?}`). Hidden or locked art and art outside the isolated group in the range is left out, and nothing stays targeted. Regression tests: `clicking_a_target_circle_targets_the_layer` and `shift_clicking_a_target_circle_selects_a_range_of_rows` in `crates/ui-egui/src/panels/layers/tests.rs`. From 782715d46771fa709faf13f7ec917ba7e8a4dd4f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:52:58 -0800 Subject: [PATCH 2/7] Undo: a drag after a command replays on its own objects When a command run during a tool drag deletes, hides or locks an object that the drag's preview names in its ids, the preview applied again leaves that object out, so the drag still edits the others. A preview left naming no object records no step. When the command changes the selection, the journal also records the drag's own selection after the command (select.set, with its anchors, segments, guides and key, or its slices, target, symbol part or Objects on Path member), so replaying the journal moves the objects the drag moved. A targeted object keeps its guides and key, and a path with every anchor selected keeps them selected as anchors. The current layer and the highlighted Layers panel rows are left as the drag left them. --- crates/engine/src/session/edit.rs | 137 +++++++++- .../engine/src/tests/interaction_commands.rs | 258 ++++++++++++++++++ 2 files changed, 394 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 5930c8d9c0..cbf9bf4931 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -383,10 +383,19 @@ impl Session { } return; } - it.doc = st.doc.clone(); + let began = std::mem::replace(&mut it.doc, st.doc.clone()); // The drag acts on the objects it began with: a selection the command made (a paste, a // duplicate, Select All) does not change what the drag moves. it.selection = Arc::new(drag_selection(&it.selection, &st.doc)); + // The journal holds the selection the command left. The drag's own selection is journaled + // after it, so the drag and the commands after it replay on the objects they act on. + let reselect = (active && st.selection != *it.selection) + .then(|| selection_steps(&it.selection, &st.selection, &st.doc, st.active_layer, &st.highlighted_rows())); + // The objects the drag's preview names leave out those the command removed, hid or locked. + // A preview left naming none has nothing to apply, and the drag records no step. + if it.preview.as_mut().is_some_and(|(_, p)| !drag_targets(p, &began, &st.doc)) { + it.preview = None; + } it.copies = None; it.move_box = std::sync::OnceLock::new(); // With Real-time Drawing off the preview waits for the commit, as it did before the command. @@ -398,6 +407,13 @@ impl Session { st.revision += 1; } st.interaction = Some(it); + if let Some(steps) = reselect { + let (from, grouped) = (self.journal.len(), self.undo_group_docs()); + for step in steps { + self.journal.push(step); + } + self.journal_in_undo_groups(Some(uid), &grouped, from); + } self.clear_deferred_overlay_cache(); if let Some((cmd, p)) = again { match self.preview(&cmd, &p) { @@ -686,3 +702,122 @@ fn drag_selection(began: &Selection, doc: &Document) -> Selection { selection.remove_all(held); selection } + +/// Take out of the `ids` of a drag's preview `params` the objects that a command run during the +/// drag removed from `doc`, or hid or locked there while they were editable in `began` → false +/// when the preview named objects and none of them is left. +fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool { + let Some(ids) = params.get_mut("ids").and_then(Value::as_array_mut) else { return true }; + if ids.is_empty() { + return true; + } + let (was, now) = (began.editable(), doc.editable()); + ids.retain(|v| v.as_u64().map(vectorcraft_doc::NodeId).is_none_or(|id| doc.node(id).is_some() && (now(id) || !was(id)))); + !ids.is_empty() +} + +/// The journal entries that select `selection` again in `doc` after `made`, the selection a +/// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]). +/// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer` +/// current again, as the drag leaves it, and `layer.highlight` gives back the highlighted rows. +fn selection_steps( + selection: &Selection, + made: &Selection, + doc: &Document, + layer: Option, + rows: &[vectorcraft_doc::NodeId], +) -> Vec<(String, Value)> { + let mut steps = object_steps(selection, doc); + // `layer.target` on a layer makes it current; any other change to the selected objects makes + // the layer of the last selected object current. + let targeted = steps.first().is_some_and(|(id, _)| id == "layer.target"); + let selects = match selection.target.filter(|t| targeted && doc.node(*t).is_some_and(|n| n.is_layer())) { + Some(t) => Some(t), + None if selection.objects != made.objects => { + selection.objects.last().and_then(|id| doc.layer_containing(*id)).filter(|l| doc.is_editable(*l)) + } + None => None, + }; + if let Some(layer) = layer.filter(|l| selects.is_some_and(|s| s != *l)) { + steps.push(("layer.setCurrent".into(), serde_json::json!({ "id": layer.0 }))); + // `layer.setCurrent` highlights the layer's row. `layer.highlight` sets the rows the command + // left instead; it keeps `layer` current while the last of them is on `layer`, or none is left. + if rows != [layer] && rows.last().is_none_or(|r| doc.layer_containing(*r) == Some(layer)) { + let ids: Vec = rows.iter().map(|r| r.0).collect(); + steps.push(("layer.highlight".into(), serde_json::json!({ "ids": ids, "mode": "set" }))); + } + } + steps +} + +/// The journal entries that select `selection` in `doc`: the selections made on their own (its +/// slices with `object.slice.select`, its target with `layer.target`, its symbol part with +/// `symbol.instance.selectPart`, its Objects on Path member with +/// `object.objectsOnPath.selectMember`), or its objects in their order (`select.set`), the anchors +/// left out on paths that are not selected whole (`select.anchorsMany`), the anchors of paths with +/// every anchor selected (`select.anchors`) and its segments (`select.segments`); after its objects +/// or its target, its ruler guides (`guide.select`) and its key object, key guide or key anchor +/// (`select.key`). +fn object_steps(selection: &Selection, doc: &Document) -> Vec<(String, Value)> { + use serde_json::json; + if !selection.slices.is_empty() { + let slices: Vec = selection.slices.iter().map(|id| id.0).collect(); + return vec![("object.slice.select".into(), json!({ "slices": slices }))]; + } + // A target is selected again only while targeting it selects the same objects: when a command + // added art to a targeted layer, `select.set` selects the drag's objects. + let targets = |t: vectorcraft_doc::NodeId| match doc.node(t) { + Some(n) if n.is_layer() => n.layer_art(true) == selection.objects, + _ => selection.objects == [t], + }; + let json_refs = |refs: &mut dyn Iterator| Value::Array(refs.map(|&(a, b)| json!([a, b])).collect()); + // A targeted object keeps the ruler guides and the key selected beside it. + let mut steps = if let Some(t) = selection.target.filter(|&t| targets(t)) { + vec![("layer.target".to_string(), json!({ "id": t.0 }))] + } else if let Some(part) = &selection.symbol_part { + return vec![("symbol.instance.selectPart".into(), json!({ "id": part.instance.0, "path": part.path }))]; + } else if let Some(member) = selection.on_path_member { + return vec![("object.objectsOnPath.selectMember".into(), json!({ "member": member.0 }))]; + } else { + let ids: Vec = selection.objects.iter().map(|id| id.0).collect(); + let mut steps = vec![("select.set".to_string(), json!({ "ids": ids }))]; + // `select.set` selects each path whole: subtracting the anchors that are not selected leaves + // the ones that are, and keeps the order of the objects. A path with every anchor selected + // as anchors gets them back with `select.anchors`, which keeps them all as anchors. + let mut every = Vec::new(); + let partial: Vec = selection + .objects + .iter() + .filter_map(|id| { + let refs = selection.anchors.get(id)?; + let path = doc.node(*id)?.path_data()?; + let out: Vec<(usize, usize)> = path.anchors().map(|(s, i, _)| (s, i)).filter(|r| !refs.contains(r)).collect(); + if out.is_empty() { + every.push(("select.anchors".to_string(), json!({ "id": id.0, "anchors": json_refs(&mut refs.iter()), "mode": "add" }))); + return None; + } + Some(json!({ "id": id.0, "anchors": json_refs(&mut out.iter()) })) + }) + .collect(); + if !partial.is_empty() { + steps.push(("select.anchorsMany".into(), json!({ "items": partial, "mode": "subtract" }))); + } + steps.extend(every); + for (id, refs) in &selection.segments { + steps.push(("select.segments".into(), json!({ "id": id.0, "segments": json_refs(&mut refs.iter()), "mode": "add" }))); + } + steps + }; + if !selection.guides.is_empty() { + let indexes = cmd::guide_indexes(doc, &selection.guides); + steps.push(("guide.select".into(), json!({ "indexes": indexes, "toggle": true }))); + } + if let Some((id, (s, i))) = selection.key_anchor { + steps.push(("select.key".into(), json!({ "id": id.0, "anchor": [s, i] }))); + } else if let Some(g) = selection.key_guide.and_then(|g| cmd::guide_indexes(doc, &[g]).first().copied()) { + steps.push(("select.key".into(), json!({ "guide": g }))); + } else if let Some(key) = selection.key { + steps.push(("select.key".into(), json!({ "id": key.0 }))); + } + steps +} diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index e18b0db56d..71e23f6382 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -400,6 +400,264 @@ fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() { } } +/// Replay the journal of `s` from `start` on `replayed`. +fn replay_from(s: &Session, start: usize, replayed: &mut Session) { + for (id, p) in s.journal.iter().skip(start) { + replayed.replay(id, p).unwrap(); + } +} + +/// The journal of a move drag with a selection command run during it replays as the drag went: +/// the drag moves its own object, not the one the command selected. +#[test] +fn a_move_drag_after_a_selection_command_replays_on_its_own_object() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let bounds = |s: &Session| { + let d = &s.doc().unwrap().doc; + (d.bounds_of(&[target], false), d.bounds_of(&[other], false)) + }; + assert_eq!(bounds(&s), (Some(Rect::new(150.0, 130.0, 190.0, 170.0)), Some(Rect::new(10.0, 10.0, 30.0, 30.0))), "{at}"); + let (mut replayed, _, _) = two_squares(real_time); + replay_from(&s, start, &mut replayed); + assert_eq!(bounds(&replayed), bounds(&s), "{at}: {:?}", journaled(&s, start)); + assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}"); + assert_eq!(replayed.doc().unwrap().active_layer, s.doc().unwrap().active_layer, "{at}"); + } +} + +/// A square on a second layer selected with a ruler guide, and a square on the first layer → +/// the session (with Real-time Drawing `real_time`) and the square on the first layer. +fn square_and_guide(real_time: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("layer.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); + let target = s.doc().unwrap().selection.objects[0]; + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + (s, other) +} + +/// The journal of a move drag of a square and a ruler guide, with a command during it that +/// selects an object on another layer, replays with the drag's selection, guide included, with +/// the layer the command made current and with the Layers panel rows the command left highlighted. +#[test] +fn a_move_drag_of_a_guide_after_a_selection_command_replays_its_selection_and_layer() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = square_and_guide(real_time); + s.select_tool("selection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let (mut replayed, _) = square_and_guide(real_time); + replay_from(&s, start, &mut replayed); + let state = |s: &mut Session| { + let d = s.doc().unwrap(); + let state = ( + d.selection.objects.clone(), + d.selection.guides.clone(), + d.active_layer, + d.highlighted_rows(), + d.doc.bounds_of(&d.selection.objects, false), + ); + (state, s.execute("guide.list", &json!({})).unwrap()) + }; + assert_eq!(state(&mut replayed), state(&mut s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted square, with a command during it that selects another +/// square, replays with the square targeted, as the drag leaves it. +#[test] +fn a_move_drag_of_a_targeted_object_after_a_selection_command_replays_its_target() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("layer.target", &json!({"id": target.0})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, other) + }; + let (mut s, other) = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let (mut replayed, _) = setup(); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.selection.target, d.doc.bounds_of(&d.selection.objects, false)) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted square and a ruler guide, with a command during it +/// that selects another square, replays with the square targeted and the guide selected. +#[test] +fn a_move_drag_of_a_targeted_object_and_a_guide_after_a_selection_command_replays_both() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + s.execute("layer.target", &json!({"id": target.0})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, target, other) + }; + let (mut s, target, other) = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let state = |s: &mut Session| { + let d = s.doc().unwrap(); + let state = (d.selection.objects.clone(), d.selection.target, d.selection.guides.clone(), d.doc.bounds_of(&d.selection.objects, false)); + (state, s.execute("guide.list", &json!({})).unwrap()) + }; + let live = state(&mut s); + assert_eq!((live.0.1, live.0.2.len()), (Some(target), 1), "{at}: the drag leaves the square targeted and the guide selected"); + let (mut replayed, _, _) = setup(); + replay_from(&s, start, &mut replayed); + assert_eq!(state(&mut replayed), live, "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a path with every anchor selected as anchor points, with a +/// command during it that selects another square, replays with those anchors selected. +#[test] +fn a_move_drag_of_every_anchor_of_a_path_after_a_selection_command_replays_its_anchors() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": target.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, target, other) + }; + let (mut s, target, other) = setup(); + let every = s.doc().unwrap().selection.anchors.get(&target).cloned(); + assert!(every.as_ref().is_some_and(|a| a.len() > 1), "{at}: {every:?}"); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.selection.anchors.clone(), d.doc.bounds_of(&d.selection.objects, false)) + }; + assert_eq!(state(&s).1.get(&target), every.as_ref(), "{at}: the drag leaves every anchor selected as anchors"); + let (mut replayed, _, _) = setup(); + replay_from(&s, start, &mut replayed); + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted layer's art, with a duplicate made on that layer +/// during it, replays with the drag moving its own objects, not the duplicates. +#[test] +fn a_move_drag_of_a_targeted_layer_after_a_duplicate_replays_its_objects() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, _, _) = two_squares(real_time); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + s.select_tool("selection", view()).unwrap(); + s + }; + let mut s = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("edit.duplicate", &json!({})).unwrap(); + }); + let mut replayed = setup(); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.doc.bounds_of(&d.selection.objects, false), objects(s)) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// A selected user slice and a square → the session (with Real-time Drawing `real_time`), the +/// slice and the square. +fn slice_and_square(real_time: bool) -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + let slice = s.execute("object.slice.create", &json!({"x": 200, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap(); + (s, NodeId(slice), other) +} + +/// The journal of a Slice Selection drag, with a command during it that selects an object, +/// replays with the slice selected, as the drag leaves it. +#[test] +fn a_slice_drag_after_a_selection_command_replays_its_slice_selection() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, slice, other) = slice_and_square(real_time); + s.select_tool("sliceSelection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(220.0, 220.0), (230.0, 230.0), (240.0, 240.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + assert_eq!(s.doc().unwrap().selection.slices, [slice], "{at}"); + let (mut replayed, _, _) = slice_and_square(real_time); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let sel = &s.doc().unwrap().selection; + (sel.objects.clone(), sel.slices.clone()) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// A Warp stroke over two selected squares, with a command that deletes one of them during the +/// stroke: the release still warps the other square, and the stroke's journal entry names it. +#[test] +fn a_warp_stroke_over_an_object_a_command_deleted_still_warps_the_others() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("warp", view()).unwrap(); + let before = s.doc().unwrap().doc.node(target).cloned(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 135.0, 125.0); + let r = s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap(); + assert!(r.get("warning").is_none(), "{at}: {r}"); + pointer(&mut s, PointerKind::Up, 135.0, 125.0); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(other).is_none(), "{at}: the deletion stays"); + assert_ne!(s.doc().unwrap().doc.node(target).cloned(), before, "{at}: the release warps the other square"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the deletion and the stroke are a step each"); + let (id, p) = s.journal.last().unwrap(); + assert_eq!((id.as_str(), &p["ids"]), ("object.liquify", &json!([target.0])), "{at}"); + } +} + /// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the /// object they act on during the drag: the drag ends without an edit of its own and the deletion /// stays. From 232b3de397d166060f1e82e314dbb1af8c12d2be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:17:18 -0800 Subject: [PATCH 3/7] Tests: drag command test uses craft::automation's request and reply types After the craft UI framework move, `control` no longer exports `ControlRequest` or `Outcome`; `control::handle` takes a `craft::automation::ControlRequest` and returns a `Reply`. --- crates/ui-egui/src/tests/drag_commands.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tests/drag_commands.rs b/crates/ui-egui/src/tests/drag_commands.rs index 8879c3e25c..1c087bb5ec 100644 --- a/crates/ui-egui/src/tests/drag_commands.rs +++ b/crates/ui-egui/src/tests/drag_commands.rs @@ -8,8 +8,8 @@ use crate::VectorcraftApp; /// Send a control request → its reply. fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { - let (request, _) = crate::control::ControlRequest::new(method, params); - let crate::control::Outcome::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("{method}: not done") }; + let (request, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("{method}: not done") }; reply } From 7a37e282d93b056ad6062030a56cf73e19327114 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 12:50:43 -0800 Subject: [PATCH 4/7] Undo: putting back a drag's paints names every PaintDefaults field put_back_interaction compares the new-art paints field by field. It now destructures PaintDefaults without `..`, so a field added to the struct does not compile until it is handled there. --- crates/engine/src/session/edit.rs | 38 ++++++++++++++++--------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 464c92b09e..a70850f44d 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -362,31 +362,33 @@ impl Session { } // A change the command made to the new-art paints stays when the next preview or a cancel // puts back the paints the interaction began with (the Live Paint Bucket's colors); the - // parts it left alone keep the interaction's. - let (now, start) = (&self.paint, &mut it.paint); - if now.fill != paint.fill { - start.fill.clone_from(&now.fill); + // parts it left alone keep the interaction's. The pattern lists every field, so a field + // added to `PaintDefaults` does not compile until it is handled here. + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; + let start = &mut it.paint; + if *fill != paint.fill { + start.fill.clone_from(fill); } - if now.stroke != paint.stroke { - start.stroke.clone_from(&now.stroke); + if *stroke != paint.stroke { + start.stroke.clone_from(stroke); } - if now.stroke_width != paint.stroke_width { - start.stroke_width = now.stroke_width; + if *stroke_width != paint.stroke_width { + start.stroke_width = *stroke_width; } - if now.appearance != paint.appearance { - start.appearance.clone_from(&now.appearance); + if *appearance != paint.appearance { + start.appearance.clone_from(appearance); } - if now.opacity != paint.opacity { - start.opacity = now.opacity; + if *opacity != paint.opacity { + start.opacity = *opacity; } - if now.blend != paint.blend { - start.blend = now.blend; + if *blend != paint.blend { + start.blend = *blend; } - if now.style != paint.style { - start.style.clone_from(&now.style); + if *style != paint.style { + start.style.clone_from(style); } - if now.inherited != paint.inherited { - start.inherited = now.inherited; + if *inherited != paint.inherited { + start.inherited = *inherited; } let active = self.active().is_some_and(|d| d.uid == uid); let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; From ea602fcd00e0fe826fb0c980fe699b55b7601197 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 13:54:07 -0800 Subject: [PATCH 5/7] Undo: Find Objects with select during a drag is a step of its own document.find with `select: true` is journaled, so during a tool drag it now runs outside the drag like other journaled commands. It finds and selects only objects outside the drag's preview, as its replay before the drag does. --- crates/engine/src/session/execute.rs | 6 +++-- .../engine/src/tests/interaction_commands.rs | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 0ba94dffa2..f87d37691f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -100,8 +100,10 @@ impl Session { } let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id)); // A command from outside the tool, while the tool's drag is in progress, is a step of its - // own before the drag's ([`Session::outside_interaction`]). - let outside = spec.journal && !self.previewing && !self.in_tool_actions; + // own before the drag's ([`Session::outside_interaction`]). Find Objects with `select` is + // journaled (`Session::journal_query`), so it is one too. + let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true); + let outside = (spec.journal || find_selects) && !self.previewing && !self.in_tool_actions; // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept // before Undo) reports its warning in the command's result. let r = if self.depth == 0 { diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index 71e23f6382..5234ea52ac 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -432,6 +432,30 @@ fn a_move_drag_after_a_selection_command_replays_on_its_own_object() { } } +/// Find Objects with `select` during a drag is a step of its own, as it is journaled: it finds and +/// selects only the objects outside the drag's preview, as its replay before the drag does. +#[test] +fn find_objects_with_select_during_a_drag_skips_the_drag_preview() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = session(real_time); + let start = s.journal.len(); + let find = json!({"intersects": [0, 0, 400, 400], "select": true}); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + let r = s.execute("document.find", &find).unwrap(); + assert_eq!(r["total"], 1, "{at}: {r}"); + assert_eq!(r["matches"][0]["id"], other.0, "{at}: {r}"); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + assert_eq!(objects(&s), 2, "{at}: the release draws the rectangle"); + assert_eq!(journaled(&s, start), ["document.find", "shape.rectangle"], "{at}"); + let (mut replayed, _) = session(real_time); + replay_from(&s, start, &mut replayed); + assert_eq!(objects(&replayed), 2, "{at}"); + assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}"); + } +} + /// A square on a second layer selected with a ruler guide, and a square on the first layer → /// the session (with Real-time Drawing `real_time`) and the square on the first layer. fn square_and_guide(real_time: bool) -> (Session, NodeId) { From dd37e3c14bf92f10d893088251b889f52e56c30a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:20:37 -0800 Subject: [PATCH 6/7] Tests: Find Objects during a drag journals the drag's own selection After Find Objects with `select` runs during a drag, the drag's own selection is journaled before its release, so the expected journal is document.find, select.set, shape.rectangle. --- crates/engine/src/tests/interaction_commands.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index 5234ea52ac..1c24f26440 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -448,7 +448,8 @@ fn find_objects_with_select_during_a_drag_skips_the_drag_preview() { assert_eq!(r["matches"][0]["id"], other.0, "{at}: {r}"); pointer(&mut s, PointerKind::Up, 200.0, 180.0); assert_eq!(objects(&s), 2, "{at}: the release draws the rectangle"); - assert_eq!(journaled(&s, start), ["document.find", "shape.rectangle"], "{at}"); + // The drag's own selection is journaled after the find, so the release replays on it. + assert_eq!(journaled(&s, start), ["document.find", "select.set", "shape.rectangle"], "{at}"); let (mut replayed, _) = session(real_time); replay_from(&s, start, &mut replayed); assert_eq!(objects(&replayed), 2, "{at}"); From c1859a1f1e31f8977a586d6d7268cd7add81cb51 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:18:32 -0800 Subject: [PATCH 7/7] Undo: an anchor drag ends when a command renumbers its path A command run during a Direct Selection drag of anchors or segments, such as Add Anchor Point or Reverse Path Direction, can number the path's anchors anew. The drag kept its old anchor numbers and then moved a different point. When the command changes a path that holds the drag's selected anchors or segments in more than a move of the whole path, the drag now ends without a step of its own, and the command's edit stays. A command that only moves the path leaves the drag going on the same anchor. --- crates/engine/src/session/edit.rs | 41 ++++++++++++- .../engine/src/tests/interaction_commands.rs | 61 +++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index a70850f44d..cc7af44898 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -342,7 +342,9 @@ impl Session { /// Drawing showed is applied to it again. The warning or the error of that preview goes to /// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the /// interaction with nothing to commit. An interaction whose document the command closed ends, - /// and a document the command left an interaction of its own on keeps that one. + /// and so does one with anchors or segments selected on a path the command changed in more + /// than a move. A document + /// the command left an interaction of its own on keeps that one. pub(crate) fn put_back_interaction(&mut self) { let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return }; // A selection command loaded the paints of the selection it made into the fill and stroke @@ -412,6 +414,13 @@ impl Session { } return; } + // The drag's anchors and segments are numbered in the paths it began on. When the command + // changed one of those paths in more than a move, the numbers can name other points, and + // the drag ends without a step. + if renumbered(&it.selection, &it.doc, &st.doc) { + self.clear_deferred_overlay_cache(); + return; + } let began = std::mem::replace(&mut it.doc, st.doc.clone()); // The drag acts on the objects it began with: a selection the command made (a paste, a // duplicate, Select All) does not change what the drag moves. @@ -773,6 +782,36 @@ fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool { !ids.is_empty() } +/// Whether a path with anchors or segments in `selection` is other in `doc` than in `began`, the +/// document a drag began from, in more than a move: its anchors added, removed, put in another +/// order (Reverse Path Direction) or reshaped, or a subpath opened or closed. A path the command +/// moved as a whole keeps its numbers. +fn renumbered(selection: &Selection, began: &Document, doc: &Document) -> bool { + fn path(d: &Document, id: vectorcraft_doc::NodeId) -> Option<&[vectorcraft_geom::SubPath]> { + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.as_slice()) + } + selection.anchors.keys().chain(selection.segments.keys()).any(|&id| match (path(began, id), path(doc, id)) { + (Some(was), Some(now)) => !moved_whole(was, now), + (was, now) => was.is_some() != now.is_some(), + }) +} + +/// Whether the subpaths `now` are the subpaths `was` moved by one offset: the same number of each, +/// each opened or closed as before, every anchor of the same kind, and every anchor and handle +/// offset alike. +fn moved_whole(was: &[vectorcraft_geom::SubPath], now: &[vectorcraft_geom::SubPath]) -> bool { + if was.len() != now.len() || was.iter().zip(now).any(|(a, b)| a.closed != b.closed || a.anchors.len() != b.anchors.len()) { + return false; + } + let mut pairs = was.iter().zip(now).flat_map(|(a, b)| a.anchors.iter().zip(b.anchors.iter())); + let Some((a0, b0)) = pairs.next() else { return true }; + let (dx, dy) = (b0.p.x - a0.p.x, b0.p.y - a0.p.y); + let alike = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| { + (b.x - a.x - dx).abs() <= vectorcraft_geom::EPS && (b.y - a.y - dy).abs() <= vectorcraft_geom::EPS + }; + std::iter::once((a0, b0)).chain(pairs).all(|(a, b)| a.kind == b.kind && alike(a.p, b.p) && alike(a.h_in, b.h_in) && alike(a.h_out, b.h_out)) +} + /// The journal entries that select `selection` again in `doc` after `made`, the selection a /// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]). /// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer` diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index 1c24f26440..d0d12cce94 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -722,6 +722,67 @@ fn a_scale_rotate_or_pen_drag_of_an_object_a_command_deleted_ends_without_an_edi } } +/// A Direct Selection drag of an anchor, with a command during it that numbers the path's anchors +/// anew (Add Anchor Point before the dragged one, Reverse Path Direction): the command's edit +/// stays, the drag ends without an edit of its own and moves no other anchor of the path. +#[test] +fn an_anchor_drag_after_a_command_renumbers_its_anchors_moves_no_other_anchor() { + let commands = [("path.insertAnchor", json!({"segment": 0, "t": 0.5}), 1), ("path.reverse", json!({}), 0)]; + for ((id, params, added), real_time) in commands.iter().flat_map(|c| [(c, true), (c, false)]) { + let at = format!("{id}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("directSelection", view()).unwrap(); + let points = |s: &Session| -> Vec<(f64, f64)> { + let doc = &s.doc().unwrap().doc; + let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path"); + path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect() + }; + let before = points(&s); + let &(x, y) = before.last().expect("the square has anchors"); + let steps = s.doc().unwrap().history.undo.len(); + let mut params = params.clone(); + params["id"] = json!(target.0); + drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| { + s.execute(id, ¶ms).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + let after = points(&s); + assert_eq!(after.len(), before.len() + added, "{at}: the command's edit stays"); + assert!(before.iter().all(|p| after.contains(p)), "{at}: no anchor of the square moved: {before:?} → {after:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step"); + } +} + +/// A Direct Selection drag of an anchor, with a command during it that moves the path: the drag +/// goes on and moves the same anchor of the moved path. +#[test] +fn an_anchor_drag_after_a_command_moves_its_path_moves_the_same_anchor() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("directSelection", view()).unwrap(); + let points = |s: &Session| -> Vec<(f64, f64)> { + let doc = &s.doc().unwrap().doc; + let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path"); + path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect() + }; + let before = points(&s); + let &(x, y) = before.last().expect("the square has anchors"); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| { + s.execute("object.move", &json!({"ids": [target.0], "dx": 0, "dy": 50})).unwrap(); + }); + let after = points(&s); + let last = before.len() - 1; + let moved: Vec<(f64, f64)> = + before.iter().enumerate().map(|(i, &(px, py))| if i == last { (px + 30.0, py + 70.0) } else { (px, py + 50.0) }).collect(); + assert_eq!(after, moved, "{at}: the drag moves the same anchor of the moved square"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the move and the drag are a step each"); + } +} + /// With the Live Paint Bucket's Selection tool (Cmd+drag), a fill chosen during the drag stays the /// new-art fill after the release and after Escape, though the drag puts back the bucket's colors /// it began with.