diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index dc26c78550..7ba6fda3dd 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,8 +1,13 @@ +use std::sync::{Arc, Weak}; + +use vectorcraft_color::SwatchGroup; +use vectorcraft_engine::DocState; + use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; use super::{ - Kind, LibraryKind, PanelDrag, Response, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, - widgets, + Document, Kind, LibraryKind, PanelDrag, Response, Swatch, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, + set_pstate, widgets, }; /// The selected swatches and groups that can be deleted: every color group in the document and @@ -117,9 +122,81 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { /// The panel state key of the document (`uid`) the swatches being dragged from the list belong to. pub(super) const DRAG_DOC: &str = "swatch-drag-doc"; +/// The panel state key of the rows being dragged from the list ([`HeldRows`]). +const DRAG_ROWS: &str = "swatch-drag-rows"; + +/// A row dragged from the list as it was when the drag started: its swatch or its color group. +#[derive(Clone, PartialEq)] +enum HeldRow { + Swatch(Swatch), + Group(SwatchGroup), +} + +impl HeldRow { + /// Row `name` of `d`: its swatch, else the color 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 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. +#[derive(Clone, Default)] +struct HeldRows { + doc: Weak, + rows: Vec<(String, Option)>, +} + +/// Records the document and the rows a drag from the list started with this frame, so that New +/// Swatch and Delete Swatch act only on rows that stay unchanged until it is dropped. +pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { + let st = app.session.active(); + 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::default(), + }; + set_pstate(ctx, DRAG_ROWS, held); +} + +/// 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. +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)) { + 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; + } + } + held.doc = Arc::downgrade(&st.doc); + set_pstate(ctx, DRAG_ROWS, held.clone()); + held +} + /// 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. Empty for any other -/// drag, and for a drag started in another document. +/// 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. fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let d = &st.doc; @@ -127,16 +204,25 @@ fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { } /// The names of the swatches or color groups of the active document being dragged from the list, -/// in panel order. Empty for any other drag, and for a drag started in another document. +/// in panel order, that the document has held unchanged since the drag started ([`held_rows`]). +/// Empty for any other drag, and for a drag started in another document. fn dragged_rows(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; if pstate::>(ctx, DRAG_DOC) != Some(st.uid) { return vec![]; } - match egui::DragAndDrop::payload::(ctx).as_deref() { - Some(PanelDrag::Paint { rows: Some(r), .. }) => r.names.clone(), - _ => vec![], + let drag = egui::DragAndDrop::payload::(ctx); + let Some(PanelDrag::Paint { rows: Some(r), .. }) = drag.as_deref() else { return vec![] }; + let held = held_rows(st, ctx); + if held.rows.len() != r.names.len() { + return vec![]; } + r.names + .iter() + .zip(&held.rows) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc))) + .map(|(n, _)| n.clone()) + .collect() } /// Swatches or color groups (`names`) dragged onto Delete Swatch (`button`): the button is @@ -157,8 +243,8 @@ fn drop_on_delete(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: V } /// The swatches of the active document being dragged from the list that New Swatch can duplicate, -/// in panel order: the dragged rows ([`dragged_rows`]) that are swatches still in the document, -/// other than None and Registration. +/// in panel order: the dragged rows ([`dragged_rows`]) that are swatches still in the document +/// unchanged, other than None and Registration. fn dragged_swatches(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; dragged_rows(app, ctx).into_iter().filter(|n| st.doc.swatch(n).is_some_and(|w| !w.is_reserved())).collect() diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index 944a245b9e..4ec269d5dd 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -1,4 +1,4 @@ -use super::actions::{DRAG_DOC, bottom, edit_group}; +use super::actions::{bottom, drag_started, edit_group}; use super::dnd::{TileEvents, apply_drop, click_selection, highlighted, selection, tile_input, zone_input}; use super::tiles::{ draw_folder, draw_registration, folder_tile, global_mark, list_icons, list_row, list_row_name, pattern_thumb, tile_grid, tile_id, @@ -133,7 +133,7 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { None => {} } if ev.started { - set_pstate(ui.ctx(), DRAG_DOC, app.session.active().map(|st| st.uid)); + drag_started(app, ui.ctx()); } if let Some(drop) = ev.drop { apply_drop(app, drop); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a3e7120c7a..58e767817c 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -788,7 +788,8 @@ 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. +/// 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. #[test] fn delete_swatch_ignores_other_drags() { let mut app = app(); @@ -848,6 +849,23 @@ fn delete_swatch_ignores_other_drags() { assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some() && undo_steps(&app) == undo_new, "the other document keeps Orange"); assert!(app.session.set_active(0)); unchanged(&app, "the first document"); + // A swatch deleted while it is dragged, and a new swatch made under its name before the drop. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.0); + let from = tile_center(&ctx, "Orange"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 5.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 5.2); + assert!(egui::DragAndDrop::payload::(&ctx).is_some(), "Orange is dragged"); + let orange = app.session.doc().unwrap().doc.swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 5.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 5.4); + assert!(!outlined(&held, trash), "the new swatch of that name is not outlined"); + 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"); } /// Swatches dragged from the list onto New Swatch are duplicated without a dialog, in thumbnail @@ -920,7 +938,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. A secondary button released while a swatch is +/// 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 /// held over the button ends the drag without duplicating, and a click still opens New Swatch. #[test] fn new_swatch_ignores_other_drags() { @@ -977,6 +996,25 @@ fn new_swatch_ignores_other_drags() { frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 4.5); assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (gone, undo_gone), "a deleted swatch is not duplicated"); app.run("edit.undo", json!({})).unwrap(); + // A swatch deleted while it is dragged, and a new swatch made under its name before the drop. + hold_orange(&mut app, 4.6); + let orange = app.session.doc().unwrap().doc.swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 4.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 4.9); + assert!(!outlined(&held, new), "the new swatch of that name is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 4.95); + assert!(app.ui.dialog.is_none(), "the new swatch of that name opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced, undo_replaced), + "the new swatch of that name is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); // A swatch dragged from this document while another document with the same swatches becomes // active. hold_orange(&mut app, 5.0);