diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 791143f53b..03a7619e61 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -127,6 +127,12 @@ impl HistoryEntry { self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) } + /// 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 89ccb1ae9c..b7ff421414 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -274,8 +274,10 @@ 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. panels::swatches::after_command(self, id, ¶ms, v); + panels::swatches::follow_drag(self); if id == "file.new" { self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 9803cb73b6..802568a10a 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -233,7 +233,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { app.run("select.none", json!({})).unwrap(); let document = app.session.active().unwrap().uid; let swatch = |name: &str, paint: Paint| { - let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { + document, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }; Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }) }; let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); @@ -329,7 +336,14 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + held: Default::default(), + }; let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; let local_target = add_target(&mut app); diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 587da09f84..56cdff25ac 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -52,6 +52,9 @@ pub struct SwatchRows { pub groups: bool, /// Whether the grabbed swatch's paint can travel as an unlinked process color. pub unlinked_process_color: bool, + /// The rows as the document held them when the drag started, which New Swatch and Delete + /// Swatch check before acting on them. + pub(crate) held: std::sync::Arc, } impl PanelDrag { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ab3c06f3b1..cdf512f078 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1136,7 +1136,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + held: Default::default(), + }; let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); drop_paint(&mut app, Well::Primary, &drag); @@ -1164,8 +1171,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = - SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }; let drag = PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }; if different_drawing { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index a179e07a53..5caf20c7b5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -41,6 +41,7 @@ mod libraries; #[cfg(test)] use actions::{deletable, delete, mergeable, new_swatch, selected_group}; pub(crate) use actions::{menu_rows, menu_states, run}; +pub(crate) use dnd::{HeldRows, follow_drag}; pub(crate) use libraries::{ DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, library_entries, limit_key, limit_name, load_library, open_library, other_library, user_library, window_menu, @@ -130,6 +131,9 @@ pub(crate) struct Model { kept: Option<(String, Option)>, /// The art and the active swatch the last pass saw ([`Model::focus`]). seen: Option<(Option, Option)>, + /// The rows of the last drag from the list (as it started) and what its last check found + /// ([`dnd::follow`]). + drag: Option<(Arc, HeldRows)>, } impl Model { @@ -388,6 +392,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { super::color_guide::choose_base(app, c); apply_click(app, ui, json!({"color": color_json(&c)})); } + // A drag whose rows were all replaced or removed since it started (or that started in another + // document) is not taken. + let held = match craft::ui::runtime::drag::active::(ui.ctx()).as_deref() { + Some(PanelDrag::Paint { rows: Some(r), .. }) => !dnd::follow(app, r).is_empty(), + _ => true, + }; // The model leaves the app while the browser borrows the document, and comes back before the events run. let mut model = std::mem::take(&mut app.ui.swatches_panel); let view = app.ui.swatches_view; @@ -410,9 +420,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let revision = (st.uid, st.revision); let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); let doc = Arc::clone(&st.doc); + let start = dnd::DragStart::of(st); let document = st.uid; let reverts = st.reverts; - let foot = Footer::of(app, &model); + let foot = Footer::of(app, &model, held); let shown_app: &VectorcraftApp = app; let search = model.show_find; let state = &mut model.state; @@ -425,10 +436,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .fill() .footer(|ui, _| footed = Some(foot.show(ui))) .show(ui, |ui, _| { - let dragged_doc = Arc::clone(&doc); + let start = start.clone(); let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&start, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), @@ -445,6 +456,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { }) .inner; app.ui.swatches_panel = model; + // The rows being dragged from the list are checked on every pass, so the footer's drop finds + // the ones replaced since the drag started. + if let Some(PanelDrag::Paint { rows: Some(r), .. }) = craft::ui::runtime::drag::active::(ui.ctx()).as_deref() { + dnd::follow(app, r); + } let shown = shown_keys(&data); if let Some(out) = out { if let Some((at, _, alt)) = out.used @@ -791,11 +807,14 @@ struct Footer { group: Option, libraries_open: bool, document: Option, + /// Whether a drag from the list still has rows the document holds unchanged ([`dnd::follow`]). + held: bool, } impl Footer { - /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it. - fn of(app: &VectorcraftApp, model: &Model) -> Self { + /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it, with + /// `held` from the drag check ([`Footer::held`]). + fn of(app: &VectorcraftApp, model: &Model, held: bool) -> Self { let sel = selected_in(app, model); let del = actions::deletable(app, &sel); let opts = actions::editable(app, &sel); @@ -804,6 +823,7 @@ impl Footer { kind: model.kind, libraries_open: library_panel::any_open::(&app.ui), document: app.session.active().map(|state| state.uid), + held, sel, del, opts, @@ -815,7 +835,8 @@ impl Footer { fn show(&self, ui: &mut Ui) -> FooterOutput { let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); let document = self.document; - let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let held = self.held; + let rows_drag = move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); let edit = if self.group.is_some() { FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) } else { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 6ff3420571..78ebf4a02d 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -1,8 +1,12 @@ -use super::{Document, Paint, PanelDrag, REGISTRATION, Value, VectorcraftApp, json, name_of, swatch_params}; +use std::sync::{Arc, Weak}; + +use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params}; use crate::panel_drag::SwatchRows; use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; +use vectorcraft_color::SwatchGroup; +use vectorcraft_engine::{DocState, History, HistoryEntry}; /// Swatches take paints, and take swatch rows or canvas art from the current document. pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool { @@ -50,9 +54,10 @@ impl Drop { } } -/// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own -/// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { +/// The drag a row of `key` starts in document `start`, moving rows `names`. Colour groups have no +/// paint of their own (the chip under the pointer draws Registration's mark for Registration). +pub(super) fn drag_of(start: &DragStart, key: &SwatchKey, names: Vec) -> PanelDrag { + let d = &start.doc; let name = name_of(key); let (paint, params, unlinked_process_color) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name), false), @@ -65,10 +70,197 @@ pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec (Paint::None, Value::Null, false), }; - let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)), unlinked_process_color }; + let held = Arc::new(start.rows(&names)); + let groups = matches!(key, SwatchKey::Group(_)); + let rows = SwatchRows { document: start.uid, grabbed: name.to_string(), names, groups, unlinked_process_color, held }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } +/// A row dragged from the list as it was when the drag started: its swatch or its colour group. +#[derive(Clone, PartialEq)] +enum HeldRow { + Swatch(Swatch), + Group(SwatchGroup), +} + +impl HeldRow { + /// Row `name` of `d`: its swatch, else the colour group of that name. + fn of(d: &Document, name: &str) -> Option { + match d.swatch(name) { + Some(w) => Some(HeldRow::Swatch(w.clone())), + None => d.swatch_groups.iter().find(|g| g.name == name).cloned().map(HeldRow::Group), + } + } + /// Whether `d` holds this row unchanged. + fn unchanged_in(&self, d: &Document) -> bool { + match self { + HeldRow::Swatch(w) => d.swatch(&w.name) == Some(w), + HeldRow::Group(g) => d.swatch_groups.iter().any(|x| x == g), + } + } +} + +/// 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)] +} + +/// A document as a drag from the list finds it: its `uid` and its count of File › Revert +/// ([`DocState::reverts`]), its state, its newest steps ([`steps`]) and the state undoing the newest +/// undo step gives back (that step's document). +#[derive(Clone)] +pub(super) struct DragStart { + uid: u64, + reverts: u64, + doc: Arc, + steps: [u64; 4], + back: Option>, +} + +impl DragStart { + pub(super) fn of(st: &DocState) -> Self { + let back = st.history.undo.last().map(|e| Arc::clone(&e.doc)); + DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back } + } + + /// Rows `names` as this document holds them. + fn rows(&self, names: &[String]) -> HeldRows { + let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect(); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(self.back.as_deref()).is_some_and(|(r, d)| r.unchanged_in(d))).collect(); + HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } + } +} + +/// The rows a drag from the list carries, in the order of its names, and the document (`uid`, and +/// its count of File › Revert) and the state 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)] +pub(crate) struct HeldRows { + uid: u64, + reverts: u64, + 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, +} + +impl PartialEq for HeldRows { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid + && self.reverts == other.reverts + && self.doc.ptr_eq(&other.doc) + && self.steps == other.steps + && self.rows == other.rows + && self.back == other.back + } +} + +impl std::fmt::Debug for HeldRows { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let held: Vec<(&str, bool)> = self.rows.iter().map(|(n, r)| (n.as_str(), r.is_some())).collect(); + f.debug_struct("HeldRows").field("uid", &self.uid).field("steps", &self.steps).field("held", &held).finish_non_exhaustive() + } +} + +/// `held` checked against every state document `st` passed through since it was 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 on every +/// pass and 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 checked(held: HeldRows, st: &DocState) -> HeldRows { + 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 (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) + } + 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: Vec<_> = 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 last = 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 { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back } +} + +/// The names of drag `r` that the active document has held unchanged since the drag started +/// ([`checked`]), in the drag's order. Empty when the drag started in another document, or before +/// File › Revert replaced the document. The panel keeps what it found for the drag, so the next +/// check starts from there. +pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + if st.uid != r.held.uid || st.reverts != r.held.reverts { + return vec![]; + } + let kept = &mut app.ui.swatches_panel.drag; + let from = match kept { + Some((start, now)) if Arc::ptr_eq(start, &r.held) => now.clone(), + _ => (*r.held).clone(), + }; + let now = checked(from, st); + let names = if now.rows.len() == r.names.len() { + r.names + .iter() + .zip(&now.rows) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc))) + .map(|(n, _)| n.clone()) + .collect() + } else { + vec![] + }; + *kept = Some((Arc::clone(&r.held), now)); + names +} + +/// Checks the rows being dragged from the list against the active document after a command ran +/// ([`follow`]), so that the commands after it cannot replace one unseen. +pub(crate) fn follow_drag(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if let Some(PanelDrag::Paint { rows: Some(r), .. }) = craft::ui::runtime::drag::active::(&ctx).as_deref() { + follow(app, r); + } +} + /// The row `at` names and whether the drop lands after it: onto a row it is that row; in a gap it is /// the row under the pointer, after it when the gap lies beyond its position in `shown`; a gap with /// no row under the pointer is the end of the list. @@ -123,13 +315,20 @@ pub(super) enum FooterTarget { /// Swatches or groups dragged from the list and released on a footer button (ap.AP8 `FooterDrop`): /// New Swatch duplicates the swatches among them, Delete Swatch asks to delete them as a click on -/// the button does. Other drags are left to their own targets. +/// the button does. Only rows the active document has held unchanged since the drag started count +/// ([`follow`]): a row deleted, edited or replaced under its name meanwhile, and every row of a drag +/// started in another document, is left alone. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; if !app.session.active().is_some_and(|state| state.uid == r.document) { return; } - let rows = footer_rows(app, r); + let held = follow(app, r); + if held.is_empty() { + return; + } + // Rows of the drag must be unchanged since it started; selected rows the drag does not hold come with it. + let rows: Vec = footer_rows(app, r).into_iter().filter(|n| !r.names.contains(n) || held.contains(n)).collect(); match target { FooterTarget::Delete => { let names = super::actions::deletable(app, &rows); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 617fb83a35..dd993bb69d 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -94,10 +94,10 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { dnd::on_dropped(app, &shown, &at, &drag, mods); } -/// The drag the row `name` starts, carrying rows `names`. +/// The drag the row `name` starts in the active document, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - let document = app.session.active().unwrap().uid; - dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) + let start = dnd::DragStart::of(app.session.active().expect("a document")); + dnd::drag_of(&start, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) } #[test] @@ -717,6 +717,184 @@ fn footer_drops_ignore_rows_from_another_document() { } } +/// The document and its undo step count. +fn doc_and_steps(app: &VectorcraftApp) -> (Document, usize) { + (doc(app), undo_steps(app)) +} + +/// Delete Swatch acts only on rows the document has held unchanged since the drag started: a swatch +/// deleted and made again under its name while it is dragged, a swatch the newest undo step made +/// that an undo takes back before one of that name is made again, and a swatch deleted and brought +/// back by an undo all ask nothing and are kept, also when the new swatch has the same color. A +/// swatch dragged while an undo takes back a step that left it alone is still deleted after +/// asking, and a drag started in another document deletes nothing. +#[test] +fn delete_swatch_skips_rows_replaced_during_the_drag() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + // Deleted and made again under its name, with the same color. + let drag = rows_drag(&app, "Orange", &["Orange"]); + let orange = doc(&app).swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let replaced = doc_and_steps(&app); + assert_eq!(replaced.0.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the new swatch of that name asks nothing"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch of that name is kept"); + // Made by the newest undo step, undone, and made again. + let glass = json!({"name": "Sea Glass", "color": "#00a99d"}); + app.run("swatch.new", glass.clone()).unwrap(); + let made = doc(&app).swatch("Sea Glass").cloned(); + let drag = rows_drag(&app, "Sea Glass", &["Sea Glass"]); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&app).swatch("Sea Glass").is_none(), "the undo takes Sea Glass away"); + app.session.execute("swatch.new", &glass).unwrap(); + let replaced = doc_and_steps(&app); + assert_eq!(replaced.0.swatch("Sea Glass").cloned(), made, "the new swatch is the same as the one undone"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the new swatch made after the undo asks nothing"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch made after the undo is kept"); + // Deleted and brought back by an undo. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.session.execute("swatch.delete", &json!({"names": ["Orange"]})).unwrap(); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_and_steps(&app), replaced, "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "a swatch brought back by an undo asks nothing"); + // An undo of a step that left the swatch alone. + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("edit.undo", json!({})).unwrap(); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(dialog_open(&app, key), "a swatch an undo left alone is deleted after asking"); + cancel(&mut app, key); + // Dragged from this document, dropped while another document with the same swatches is active. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = doc_and_steps(&app); + assert!(other.0.swatch("Orange").is_some(), "the other document has Orange"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the other document asks nothing"); + assert_eq!(doc_and_steps(&app), other, "the other document keeps Orange"); +} + +/// New Swatch duplicates only rows the document has held unchanged since the drag started: a +/// swatch deleted and made again under its name while it is dragged, a swatch the newest undo step +/// made that an undo takes back before one of that name is made again, and a swatch deleted and +/// brought back by an undo between two passes of the panel are not duplicated. A swatch that stays +/// unchanged is. +#[test] +fn new_swatch_skips_rows_replaced_during_the_drag() { + let mut app = app(); + // Deleted and made again under its name, with the same color. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let replaced = doc_and_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert!(open_dialogs(&app).is_empty(), "the new swatch of that name opens no dialog"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch of that name is not duplicated"); + // Made by the newest undo step (a batch), undone, and made again. + 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 drag = rows_drag(&app, "Sea Glass", &["Sea Glass"]); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("swatch.new", &glass).unwrap(); + let replaced = doc_and_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch made after the undo is not duplicated"); + // Deleted and brought back by an undo, then an edit that clears the redo steps, each seen by a + // pass of the panel. + let drag = rows_drag(&app, "Orange", &["Orange"]); + let PanelDrag::Paint { rows: Some(rows), .. } = &drag else { panic!("a rows drag") }; + for (id, params) in [ + ("swatch.delete", json!({"names": ["Orange"]})), + ("edit.undo", json!({})), + ("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})), + ] { + app.run(id, params).unwrap(); + dnd::follow(&mut app, rows); + } + let restored = doc_and_steps(&app); + assert!(restored.0.swatch("Orange").is_some(), "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is not duplicated"); + // A swatch that stays unchanged is duplicated. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("shape.rectangle", json!({"x": 90, "y": 0, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert!(doc(&app).swatch("Orange copy").is_some(), "an unchanged swatch is duplicated"); + assert_eq!(undo_steps(&app), undo + 1); +} + +/// A drag started before File › Revert replaced the document duplicates and deletes nothing, also +/// when the reverted document holds the same swatches. +#[test] +fn rows_dragged_before_a_revert_are_left_alone() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + let drag = rows_drag(&app, "Orange", &["Orange"]); + let at = app.session.active_index().expect("a document"); + let copy = doc(&app); + assert!(app.session.replace_document(at, copy)); + let reverted = doc_and_steps(&app); + assert!(reverted.0.swatch("Orange").is_some(), "the reverted document has Orange"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document's Orange is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the reverted document asks nothing"); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document keeps Orange"); +} + +/// The rows of a drag running in the drag session are checked after every command the app runs: +/// a swatch deleted and brought back by an undo, then an edit that clears the redo steps, all with +/// no pass of the panel in between, is neither duplicated by New Swatch nor deleted by Delete +/// Swatch. +#[test] +fn rows_dragged_in_the_session_are_checked_after_every_command() { + use craft::behavior::keyed; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::testing::Fixture; + + let mut app = app(); + let payload = rows_drag(&app, "Orange", &["Orange"]); + // A list row that starts the drag through the drag session, as a row of the panel does. + let mut fixture = Fixture::new(move |ui| { + let payload = payload.clone(); + let _ = List::::new("Drag source").drag_payload(move |_: &ListDrag| Some(payload.clone())).show_items( + ui, + &keyed(&[0u32], |key: &u32| *key), + &mut |_, _| ListRow::new("Dragged"), + ); + }); + fixture.room(vec2(240.0, 120.0)); + fixture.settle(); + app.ui_ctx = Some(fixture.ctx().clone()); + let from = fixture.by_label("Dragged").expect("the drag source").center(); + let key = crate::dialogs::confirm::KIND; + fixture.drag_at_pausing(from, vec2(0.0, 60.0), |f| { + let drag = craft::ui::runtime::drag::active::(f.ctx()).expect("the rows drag"); + for (id, params) in [ + ("swatch.delete", json!({"names": ["Orange"]})), + ("edit.undo", json!({})), + ("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})), + ] { + app.run(id, params).unwrap(); + } + let restored = doc_and_steps(&app); + assert!(restored.0.swatch("Orange").is_some(), "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "a swatch brought back by an undo asks nothing"); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is kept"); + }); +} + /// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that /// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch /// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection