diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..51c38e8e09 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -109,6 +109,12 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// A number no other step takes ([`History::step`]). Undo and Redo make the step they move + /// with a new number, and so does an edit merged into the newest step. + pub fn serial(&self) -> u64 { + self.serial + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..b52addfe41 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -275,9 +275,11 @@ impl VectorcraftApp { } // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); - // A renamed color group stays selected in the Swatches panel. + // A renamed color group stays selected in the Swatches panel, and the rows dragged + // from its list are checked against what the command left. if let Some(ctx) = self.ui_ctx.clone() { panels::swatches::after_command(&ctx, id, ¶ms, v); + panels::swatches::follow_drag(self, &ctx); } if id == "file.new" { self.status(""); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 41b42bfd60..0f6c0b1fe5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -30,6 +30,7 @@ mod dnd; mod libraries; mod tiles; +pub(crate) use actions::follow_drag; pub use actions::menu; #[cfg(test)] use actions::{deletable, delete, mergeable, new_swatch, selected_group}; diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 7ba6fda3dd..5572e4f778 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_color::SwatchGroup; -use vectorcraft_engine::DocState; +use vectorcraft_engine::{DocState, History, HistoryEntry}; use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; @@ -149,14 +149,37 @@ impl HeldRow { } } -/// The rows being dragged from the list, in the order of the drag's names, and the document they -/// were last checked against. A row is `None` once a state of the document since the drag started -/// did not hold it unchanged: deleted, edited, or deleted and made again under its name, also with -/// the same paint. +/// The rows being dragged from the list, in the order of the drag's names, and the document and +/// undo history they were last checked against. A row is `None` once a state of the document since +/// the drag started did not hold it unchanged: deleted, edited, or deleted and made again under its +/// name, also with the same paint. #[derive(Clone, Default)] struct HeldRows { doc: Weak, + /// The newest undo step of the document and the one under it, and the next redo step and the + /// one under it ([`steps`]). + steps: [u64; 4], rows: Vec<(String, Option)>, + /// For each row, whether the document undoing the newest step gives back (that step's + /// document) holds it unchanged. + back: Vec, +} + +/// The newest undo step of `st` and the one under it, and the next redo step and the one under it +/// ([`HistoryEntry::serial`]), 0 for none. +fn steps(st: &DocState) -> [u64; 4] { + let serial = |list: &[HistoryEntry], back: usize| list.len().checked_sub(back).and_then(|i| list.get(i)).map_or(0, HistoryEntry::serial); + let h = &st.history; + [serial(&h.undo, 1), serial(&h.undo, 2), serial(&h.redo, 1), serial(&h.redo, 2)] +} + +impl HeldRows { + /// `rows`, checked against document `st` as it is now. + fn at(st: &DocState, rows: Vec<(String, Option)>) -> Self { + let last = st.history.undo.last(); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect(); + HeldRows { doc: Arc::downgrade(&st.doc), steps: steps(st), rows, back } + } } /// Records the document and the rows a drag from the list started with this frame, so that New @@ -166,7 +189,7 @@ pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { set_pstate(ctx, DRAG_DOC, st.map(|st| st.uid)); let held = match (st, egui::DragAndDrop::payload::(ctx).as_deref()) { (Some(st), Some(PanelDrag::Paint { rows: Some(r), .. })) => { - HeldRows { doc: Arc::downgrade(&st.doc), rows: r.names.iter().map(|n| (n.clone(), HeldRow::of(&st.doc, n))).collect() } + HeldRows::at(st, r.names.iter().map(|n| (n.clone(), HeldRow::of(&st.doc, n))).collect()) } _ => HeldRows::default(), }; @@ -174,26 +197,65 @@ pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { } /// The dragged rows ([`HeldRows`]) checked against every state document `st` passed through since -/// they were last checked: the states its undo steps kept since then, and the current one. When -/// the last checked state is not among them (an undo, or steps dropped past the history's limits), -/// only the current state is checked. +/// they were last checked, and the current one. Those states are the ones the redo steps made +/// since then keep (the states an undo left), and: +/// - While the newest undo step of then is still in the history, the states the undo steps made +/// since then keep. +/// - After an undo of that step, or an edit merged into it, the state before that step and the +/// states the undo steps made since then keep. +/// +/// Otherwise (more than one step undone, or steps dropped past the history's limits) the states in +/// between are not known, and every row is left out of the drop. The panel checks the rows after +/// every command the app runs ([`follow_drag`]), so only the steps of one command go unseen. One +/// undo step is one change: the states between the commands of a `command.batch` are not kept, and +/// a row the batch leaves as it found it stays in the drop. fn held_rows(st: &DocState, ctx: &egui::Context) -> HeldRows { - let mut held: HeldRows = pstate(ctx, DRAG_ROWS); - if std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)) { + let held: HeldRows = pstate(ctx, DRAG_ROWS); + let now = steps(st); + let same = std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)); + if same && held.steps == now { return held; } - let since = st.history.undo.iter().rposition(|e| std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&e.doc))); - let between = since.and_then(|i| st.history.undo.get(i + 1..)).unwrap_or_default(); - for (_, row) in &mut held.rows { - if row.as_ref().is_some_and(|r| !(between.iter().all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc))) { - *row = None; + let (undo, redo) = (&st.history.undo, &st.history.redo); + // Where the steps made after the step with `serial` start in `list`: 0 for none. + let after = |list: &[HistoryEntry], serial: u64| { + if serial == 0 { Some(0) } else { list.iter().rposition(|e| e.serial() == serial).map(|i| i + 1) } + }; + let [newest, below, next, further] = held.steps; + // The redo steps made since: above the next redo step of then, or above the one under it once a + // redo took that step. + let left = redo.get(after(redo, next).or_else(|| after(redo, further)).unwrap_or(0)..).unwrap_or_default(); + // The states in between, and whether they start with the state an undo of the newest step gave back. + let (between, undone) = match after(undo, newest) { + // With no step before it, the first step keeps the last checked state, unless steps were + // dropped past the history's limits, which leave at least that many steps. + Some(0) => { + let kept = same + || undo.len() < st.history.limit.min(History::MIN_STEPS) + || undo.first().is_none_or(|e| std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&e.doc))); + (kept.then_some(undo.as_slice()), false) } - } - held.doc = Arc::downgrade(&st.doc); + Some(i) => (undo.get(i..), false), + None => (after(undo, below).and_then(|i| undo.get(i..)), true), + }; + let unchanged = |r: &HeldRow, b: &[HistoryEntry]| b.iter().chain(left).all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc); + let rows = held + .rows + .into_iter() + .zip(held.back) + .map(|((name, row), back)| (name, row.filter(|r| (back || !undone) && between.is_some_and(|b| unchanged(r, b))))) + .collect(); + let held = HeldRows::at(st, rows); set_pstate(ctx, DRAG_ROWS, held.clone()); held } +/// Checks the rows being dragged from the list against the active document after a command ran +/// ([`held_rows`]), so that the commands after it cannot replace one unseen. +pub(crate) fn follow_drag(app: &VectorcraftApp, ctx: &egui::Context) { + dragged_rows(app, ctx); +} + /// The swatches and color groups of the active document being dragged from the list that Delete /// Swatch can delete: neither None nor Registration, and still in the document unchanged. Empty for /// any other drag, and for a drag started in another document. diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 58e767817c..81b4096bd5 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -788,8 +788,9 @@ fn swatches_dropped_on_delete_swatch_are_deleted_after_asking() { /// Delete Swatch takes only swatches dragged from the active document's list: a paint dragged from /// elsewhere, art, and a swatch dragged from another document whose name the active document also /// has delete nothing, ask nothing and are not outlined. A secondary button released while a swatch -/// is held over the button ends the drag without asking, and a swatch deleted while it is dragged -/// leaves alone a new swatch made under its name. +/// is held over the button ends the drag without asking, and a swatch deleted or undone while it is +/// dragged leaves alone a new swatch made under its name, and the swatch an undo brings back. A +/// swatch dragged while an undo takes back a step that left it alone is still deleted. #[test] fn delete_swatch_ignores_other_drags() { let mut app = app(); @@ -866,6 +867,50 @@ fn delete_swatch_ignores_other_drags() { frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 5.5); assert_eq!(dialog_message(&app), None, "the new swatch of that name asks nothing"); assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (replaced, undo_replaced), "the new swatch of that name is kept"); + // A swatch the newest undo step made, undone while it is dragged, and a new swatch made under + // its name before the drop, both inside one command (run on the session, so the panel does + // not check the rows between them). + let hold_orange = |app: &mut VectorcraftApp, time: f64| { + frame_out(app, &ctx, vec![], Modifiers::NONE, time); + let from = tile_center(&ctx, "Orange"); + frame_out(app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, time + 0.1); + frame_out(app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, time + 0.2); + let drag = egui::DragAndDrop::payload::(&ctx); + assert!(matches!(drag.as_deref(), Some(PanelDrag::Paint { rows: Some(r), .. }) if r.names == ["Orange"]), "Orange is dragged"); + }; + hold_orange(&mut app, 6.0); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("swatch.new", &json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.4); + assert!(!outlined(&held, trash), "the new swatch made after the undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 6.5); + assert_eq!(dialog_message(&app), None, "the new swatch made after the undo asks nothing"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced.clone(), undo_replaced), + "the new swatch made after the undo is kept" + ); + // A swatch deleted while it is dragged and brought back by an undo, inside one command. + hold_orange(&mut app, 6.6); + app.session.execute("swatch.delete", &json!({"names": ["Orange"]})).unwrap(); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.clone(), replaced, "the undo brings Orange back"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.9); + assert!(!outlined(&held, trash), "a swatch brought back by an undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 6.95); + assert_eq!(dialog_message(&app), None, "a swatch brought back by an undo asks nothing"); + // A swatch dragged while an undo takes back a step that left it alone is still deleted. + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + hold_orange(&mut app, 7.0); + app.session.execute("edit.undo", &json!({})).unwrap(); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 7.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 7.4); + assert!(outlined(&held, trash), "a swatch an undo left alone is outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 7.5); + assert!(dialog_message(&app).is_some(), "a swatch an undo left alone is deleted after asking"); } /// Swatches dragged from the list onto New Swatch are duplicated without a dialog, in thumbnail @@ -939,7 +984,8 @@ fn swatches_dropped_on_new_swatch_are_duplicated() { /// New Swatch duplicates only swatches dragged from the active document's list that are still in /// it: a paint dragged from elsewhere, art, a swatch dragged from another document, and a swatch /// deleted while it is dragged duplicate nothing, nor does a new swatch made under the name of a -/// swatch deleted while it is dragged. A secondary button released while a swatch is +/// swatch deleted or undone while it is dragged, or the swatch an undo brings back after deleting it +/// while it is dragged. A secondary button released while a swatch is /// held over the button ends the drag without duplicating, and a click still opens New Swatch. #[test] fn new_swatch_ignores_other_drags() { @@ -1028,14 +1074,69 @@ fn new_swatch_ignores_other_drags() { assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (other, undo_new), "the other document duplicates nothing"); assert!(app.session.set_active(0)); unchanged(&app, "the first document"); + // A swatch the newest undo step made, undone while it is dragged, and a new swatch made under + // its name before the drop, both inside one command (run on the session, so the panel does + // not check the rows between them). + let glass = json!({"name": "Sea Glass", "color": "#00a99d"}); + let steps = json!([{"command": "swatch.new", "params": glass}, {"command": "swatch.move", "params": {"name": "Sea Glass", "to": 2}}]); + app.run("command.batch", json!({"label": "New Swatch", "commands": steps})).unwrap(); + let made = app.session.doc().unwrap().doc.swatch("Sea Glass").cloned(); + assert!(made.is_some(), "Sea Glass is made"); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.6); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.65); + let from = tile_center(&ctx, "Sea Glass"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 5.7); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 5.8); + let drag = egui::DragAndDrop::payload::(&ctx); + assert!(matches!(drag.as_deref(), Some(PanelDrag::Paint { rows: Some(r), .. }) if r.names == ["Sea Glass"]), "Sea Glass is dragged"); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch("Sea Glass").is_none(), "the undo takes Sea Glass away"); + app.session.execute("swatch.new", &glass).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Sea Glass").cloned(), made, "the new swatch is the same as the one undone"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 5.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 5.9); + assert!(!outlined(&held, new), "the new swatch made after the undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 5.95); + assert!(app.ui.dialog.is_none(), "the new swatch made after the undo opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced, undo_replaced), + "the new swatch made after the undo is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + unchanged(&app, "after the undo case"); + // A swatch deleted while it is dragged and brought back by an undo, then an edit that clears + // the redo steps, each a command of its own before the panel is drawn again. The app checks the + // rows after each command it runs with the window's context. + app.ui_ctx = Some(ctx.clone()); + hold_orange(&mut app, 6.0); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + let (restored, undo_restored) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert!(restored.swatch("Orange").is_some(), "the undo brings Orange back"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 6.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 6.4); + assert!(!outlined(&held, new), "a swatch brought back by an undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 6.5); + assert!(app.ui.dialog.is_none(), "a swatch brought back by an undo opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (restored, undo_restored), + "a swatch brought back by an undo is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + app.ui_ctx = None; + unchanged(&app, "after the restored case"); // A click still opens New Swatch. - frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 6.0); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 7.0); let click = vec![ Event::PointerMoved(new.center()), press(new.center(), PointerButton::Primary, true), press(new.center(), PointerButton::Primary, false), ]; - frame_out(&mut app, &ctx, click, Modifiers::NONE, 6.1); + frame_out(&mut app, &ctx, click, Modifiers::NONE, 7.1); assert!(app.ui.dialog.is_some(), "a click opens the New Swatch dialog"); }