diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index c94ee35c33..2d77776662 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,7 +1,7 @@ use super::error::{EngineError, Result}; use super::history::{History, HistoryEntry}; use super::interaction::{Interaction, LastTransform, UndoGroup}; -use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access}; +use super::{Arc, Document, NodeId, NodeKind, Paint, Selection, Value, cmd, file_access}; /// A document's window as the desktop app shows it ([`crate::Session::window_views`]). #[derive(Clone, Copy, Debug, PartialEq)] @@ -41,6 +41,9 @@ impl WindowView { } } +/// How many canceled interactions [`DocState::was_canceled`] remembers. +const CANCELED_INTERACTIONS_KEPT: usize = 32; + /// Per-document editing state. #[derive(Clone, Debug)] pub struct DocState { @@ -124,6 +127,11 @@ pub struct DocState { /// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects /// across that boundary. pub history_restores: u64, + /// `Weak`s to the selection snapshots of canceled interactions ([`crate::Session::cancel_interaction`]) that + /// something else held a `Weak` to, also when their previews changed only the tool's paints and left the document + /// in place, each with the new-art fill and stroke the interaction began with. [`DocState::was_canceled`] tells + /// whether an interaction is among them. A commit adds nothing. It is not saved. + canceled_interactions: Vec<(std::sync::Weak, Paint, Paint)>, /// Advances when a canceled interaction, Exit Symbol Editing Mode taking /// back the entering step, Discard Empty Type taking back the step that made the text, or a command /// that panicked puts back an older document snapshot. A canceled plug-in run advances it @@ -569,6 +577,7 @@ impl DocState { activated: 0, reverts: 0, history_restores: 0, + canceled_interactions: Vec::new(), rollbacks: 0, opened_as_tab: true, mask_view: None, @@ -823,9 +832,28 @@ impl DocState { self.history.clear_redo(); self.history.trim(); } + /// Whether the interaction whose selection snapshot `selection` points to was canceled. Only an interaction + /// whose snapshot something held a `Weak` to when a later interaction was canceled is still known. + pub fn was_canceled(&self, selection: &std::sync::Weak) -> bool { + self.canceled_paints(selection).is_some() + } + /// The new-art fill and stroke the canceled interaction whose selection snapshot `selection` points to began + /// with, or `None` when that interaction is not known to be canceled ([`DocState::was_canceled`]). + pub fn canceled_paints(&self, selection: &std::sync::Weak) -> Option<(&Paint, &Paint)> { + self.canceled_interactions.iter().find(|(s, ..)| s.as_ptr() == selection.as_ptr()).map(|(_, fill, stroke)| (fill, stroke)) + } /// End the interaction in progress, undoing what it changed. pub(crate) fn undo_interaction(&mut self) { if let Some(it) = self.interaction.take() { + // Only a snapshot something holds a `Weak` to can be asked about. The record keeps a `Weak` too, so the + // selection still moves back without a copy. Once the selection moves out, a `Weak` cannot tell whether + // anything else still holds one, so only the most recent records are kept. + if Arc::weak_count(&it.selection) > 0 { + if self.canceled_interactions.len() >= CANCELED_INTERACTIONS_KEPT { + self.canceled_interactions.remove(0); + } + self.canceled_interactions.push((Arc::downgrade(&it.selection), it.paint.fill.clone(), it.paint.stroke.clone())); + } if !Arc::ptr_eq(&self.doc, &it.doc) { self.rollbacks += 1; } diff --git a/crates/ui-egui/src/edits.rs b/crates/ui-egui/src/edits.rs index ac5fc8e80a..2699a0c2e3 100644 --- a/crates/ui-egui/src/edits.rs +++ b/crates/ui-egui/src/edits.rs @@ -217,8 +217,10 @@ fn cancel_scope(app: &mut VectorcraftApp, open: OpenScope, reason: CancelReason) /// Ends the undo scopes of the gestures whose component went away while they ran /// (`FrameOutput::removed_gestures`), whose `Cancel` never comes: what they applied stays, as one -/// step, as a removed preview keeps what it showed. +/// step, as a removed preview keeps what it showed. The Gradient panel's Location field stops tracking the stop of a +/// removed gesture. pub(crate) fn end_removed(app: &mut VectorcraftApp, removed: &[GestureId]) { + crate::panels::gradient::end_removed_location_scrub(app, removed); for id in removed { if let Some(open) = app.edit_scopes.remove(id) { app.session.end_undo_scope(open.scope, false); diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index f1511b2309..e185a8def5 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -25,7 +25,9 @@ //! gradient behind the active proxy, keeping its placement (`gradient.presets.*`). Hide Presets in //! the panel menu leaves the row out. -use craft::behavior::{ColumnWidth, EditEvent, IconId, Mixed}; +use std::sync::{Arc, Weak}; + +use craft::behavior::{CancelReason, ColumnWidth, EditEvent, EditEvents, GestureId, IconId, Mixed}; use craft::color_ui::gradient::stops::AltDrop; use craft::color_ui::ui::DropperButton; use craft::color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, StopDrop, StopRef, StopRow, StopRows, StopRules}; @@ -33,7 +35,7 @@ use craft::theme::Srgba; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented, Swatch}; -use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Politeness, Props as _, Show as _, ShowContainer as _, Trigger, announce}; use craft::ui::display::{Divider, Icon, Shade, Text}; use craft::ui::layout::CellAlign; use craft::ui::layout_components::{Grid, Row, Stack}; @@ -51,7 +53,7 @@ use egui::{Pos2, Ui}; use serde_json::{Value, json}; use vectorcraft_color::gradient::{MAX_REPEATS, MIN_STOPS, insert_stop, move_stop, remove_stop, set_midpoint}; use vectorcraft_color::{Color, Freeform, FreeformMode, Gradient, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; -use vectorcraft_doc::StrokeGradientMode; +use vectorcraft_doc::{Document, Selection, StrokeGradientMode}; use vectorcraft_engine::StopOwner; use vectorcraft_tools::params::stops_json; @@ -60,7 +62,7 @@ use super::{Live, active_paint, live_run, part_hidden, set_part_hidden}; use crate::VectorcraftApp; // PLAN: assumed color-w18's `dialogs::gradient_stop::{open_at(app, index, at: Anchor), Anchor::Screen(Pos2)}` (co.A5). use crate::dialogs::gradient_stop::{self, Anchor}; -use crate::edits::{EditPath, apply_edits}; +use crate::edits::{EditPath, apply_edits, apply_event}; // PLAN: assumed widgets-w13's `paint_preview::{paint_face(&GradientPaint) -> FacePaint, paint_rect(&ContentPainterCx, Rect, &Paint)}` (wg.S6). use crate::paint_preview::{paint_face, rect_face}; // PLAN: assumed widgets-w13's `panel_drag::PanelDrag` with `Paint { params, .. }` and `color(&self) -> Option` (wg.S7). @@ -102,6 +104,359 @@ pub struct GradientUi { /// `paint.editGradient` sorts the stops, so the gradient shown mid-gesture is the last preview /// re-sorted: the editor's tags name stops of this one. pub(crate) begun: Option>, + /// The Location field's open gesture on the selected stop (a scrub or steps), from its `Begin` until its + /// `Commit` or `Cancel`, or until the end of another edit's preview it joined. When its recorded interaction is + /// no longer open, the record stays retired to discard the gesture's remaining events. + pub(crate) location_scrub: Option, + /// A Location gesture's stop was lost and the selection cleared outside a panel pass; the next pass announces it. + pub(crate) location_lost: bool, + /// A Location gesture's stop was lost in another edit's preview it joined and the selection was cleared: the stop + /// selected when it began, selected again if that preview is canceled or undone. + pub(crate) location_restore: Option, +} + +/// The selection a Location gesture cleared in a joined preview, and the preview whose rollback restores it. +#[derive(Clone, Debug)] +pub(crate) struct LocationRestore { + owner: StopOwner, + from: usize, + /// The stop at `from` when the gesture began; another stop at that index is not selected. + stop: GradientStop, + interaction: LocationInteraction, +} + +/// A Location gesture on a stop. The stop stays selected by its index when the gesture began, while every value the +/// gesture gives moves the stop at `at`, so the stop passes its neighbors as a typed location does and the neighbors +/// keep their locations. The recorded index identifies the stop only while the whole stop list is unchanged; +/// a changed list must contain exactly one stop equal to the recorded stop. A retired gesture only tracks +/// its identity so its remaining events can be discarded. +#[derive(Clone, Debug)] +pub(crate) struct LocationScrub { + /// The gesture whose values move the stop at `at`, as do outside values while its preview is live. + id: GestureId, + /// Whether the gesture's remaining events must be discarded because its interaction ended or its stop was lost. + retired: bool, + /// The gradient the gesture began on ([`vectorcraft_engine::Session::gradient_owner`]). + owner: StopOwner, + /// The interaction the gesture's preview runs in, recorded after its first write; `None` until then. + interaction: Option, + /// Whether the gesture opened the interaction that received its first write. + opened: bool, + /// The selected stop's index when the gesture began, the selected stop until the gesture ends. + from: usize, + /// The selected stop when the first Location gesture in the same preview began, which a canceled joined preview + /// selects again; `None` when that index was past the end of the stops. + origin: Option, + /// The moved stop's index when the gesture began. It differs from `from` when the gesture began inside a preview + /// an earlier gesture joined, where the field shows that gesture's moved stop. + start: usize, + /// The stop's index in the stops the gesture shows now. + at: usize, + /// The stop stored at `at` after the gesture's last write, or when it began. + stop: GradientStop, + /// The whole stop list when the gesture began. + began: Vec, + /// The whole stop list after the gesture's last write, or when it began. + stops: Vec, + /// The earlier gesture's `start` and `began` when this gesture took over its interaction, used to settle the + /// selection until this gesture writes. + inherited: Option<(usize, Vec)>, +} + +/// The preview's document revision, starting and written documents, and selection snapshot unique to its interaction. +#[derive(Clone, Debug)] +struct LocationInteraction { + document: (u64, u64), + selection: Weak, + started: Weak, + wrote: Weak, +} + +/// Whether the active document's interaction is the one the Location gesture's preview runs in. +fn owns_location_interaction(s: &LocationScrub, app: &VectorcraftApp) -> bool { + s.interaction.as_ref().is_some_and(|owner| is_open_interaction(owner, app)) +} + +/// Whether the active document's interaction is `owner`. +fn is_open_interaction(owner: &LocationInteraction, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|state| { + (state.uid, state.reverts) == owner.document + && state.interaction.as_ref().is_some_and(|interaction| owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) +} + +/// Whether ending the tracked Location gesture may select its moved stop: it is not retired, and it has written no +/// preview yet or its preview is still the open interaction. +fn location_scrub_may_select(app: &VectorcraftApp) -> bool { + app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| !s.retired && (s.interaction.is_none() || owns_location_interaction(s, app))) +} + +/// Selects the moved stop, or clears the selection if it cannot be identified, and drops the Location gesture's +/// tracking when its gesture is among `removed`. When its recorded interaction is no longer open, only a uniquely +/// identified moved stop replaces its starting selection. A retired gesture leaves selection unchanged. A preview the +/// gesture opened and still owns is committed, as a removed preview keeps what it showed. A gesture that joined another +/// edit's preview still open keeps its tracking and the selection while its moved stop is found. +pub(crate) fn end_removed_location_scrub(app: &mut VectorcraftApp, removed: &[GestureId]) { + if app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| removed.contains(&s.id)) { + // A gesture that joined another edit's preview still open keeps its tracking and the selection while its moved + // stop is found, so the selection follows that preview's commit or cancel; a lost stop clears the selection. + let joined = + location_scrub_may_select(app) && app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| s.interaction.is_some() && !s.opened); + if joined && let Some(s) = scrub_of(app) { + if current(app).is_some_and(|g| scrub_at(s, &g.gradient.stops).is_some()) { + return; + } + clear_joined_location_stop(app); + } else if location_scrub_may_select(app) { + if app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| s.opened && owns_location_interaction(s, app)) { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + } + select_location_scrub_stop(app); + } else { + let stops = current(app).map(|g| g.gradient.stops).unwrap_or_default(); + settle_lost_location_scrub(app, &stops); + } + app.ui.gradient_panel.location_scrub = None; + } +} + +/// Selects the tracked Location gesture's moved stop in the gradient currently shown, or clears the selection +/// if the stop cannot be uniquely identified. Leaves the selection unchanged when no gesture tracks the current owner. +fn select_location_scrub_stop(app: &mut VectorcraftApp) { + let Some(s) = scrub_of(app) else { return }; + let at = current(app).and_then(|g| scrub_at(s, &g.gradient.stops)); + if app.session.selected_stop() != at { + select_stop(app, at); + } +} + +/// Selects the uniquely identified moved stop when a non-retired Location gesture's recorded interaction is no longer +/// open and its starting stop is still selected on the same owner. A missing or ambiguous stop in a kept preview +/// clears the selection. An undone or canceled preview leaves selection unchanged, as do restored starting stops unless +/// the gesture began on another stop than the selected one, which is then selected when it is unique. +/// [`rolled_back`] tells a canceled or undone preview. +/// Returns true when the selection was cleared. +fn settle_lost_location_scrub(app: &mut VectorcraftApp, stops: &[GradientStop]) -> bool { + let Some(s) = scrub_of(app).filter(|s| s.interaction.is_some() && !owns_location_interaction(s, app)) else { return false }; + let Some(interaction) = &s.interaction else { return false }; + if app.session.active().is_none() { + return false; + } + if rolled_back(interaction, app) { + // A canceled preview of the tool's paints is not tied to a document, so a later edit may have changed the + // restored stops. A selected stop that differs from the one at its index when the canceled interaction began + // clears the selection. + let paints_only = interaction.started.as_ptr() == interaction.wrote.as_ptr(); + let restored = app.session.active().and_then(|state| state.canceled_paints(&interaction.selection)).is_some_and(|(fill, stroke)| { + matches!(if app.session.fill_active { fill } else { stroke }, Paint::Gradient(g) if g.gradient.stops.get(s.from) == stops.get(s.from)) + }); + if !paints_only || restored { + return false; + } + select_stop(app, None); + let lost = app.session.selected_stop().is_none(); + app.ui.gradient_panel.location_lost |= lost; + return lost; + } + let at = scrub_at(s, stops); + // Restored starting stops, or the unchanged starting stop back at its starting index, mean the move was rolled + // back before a later edit. A gesture begun on another index than the selected one selects the restored stop, or + // clears the selection when the starting or the changed list holds that stop more than once. + // Any other missing stop clears the selection rather than leave another stop selected. + // A gesture that has not written yet settles with the starting state it took over from the earlier gesture. + let (start, began) = s.inherited.as_ref().map_or((s.start, s.began.as_slice()), |(start, began)| (*start, began.as_slice())); + if stops == began || (at.is_none() && stops.get(start) == began.get(start)) { + if start == s.from { + return false; + } + let once = |list: &[GradientStop]| list.iter().filter(|stop| Some(*stop) == began.get(start)).count() == 1; + let unique = stops == began || (once(began) && once(stops)); + let pick = unique.then_some(start); + select_stop(app, pick); + let lost = pick.is_none() && app.session.selected_stop().is_none(); + app.ui.gradient_panel.location_lost |= lost; + return lost; + } + select_stop(app, at); + let lost = at.is_none() && app.session.selected_stop().is_none(); + app.ui.gradient_panel.location_lost |= lost; + lost +} + +/// Whether the ended `interaction` was canceled or undone. When the gesture's write replaced the document, a preview +/// is canceled when the document, or the start of the interaction open now, is the one the interaction started from. +/// When the write left the document in place (a preview of the tool's paints), the preview is canceled when its +/// interaction is among those the document canceled. Only a replaced document can be undone. +fn rolled_back(interaction: &LocationInteraction, app: &VectorcraftApp) -> bool { + let Some(state) = app.session.active() else { return false }; + let replaced_document = interaction.started.as_ptr() != interaction.wrote.as_ptr(); + let canceled = if replaced_document { + interaction.started.as_ptr() == Arc::as_ptr(&state.doc) + || state.interaction.as_ref().is_some_and(|open| interaction.started.as_ptr() == Arc::as_ptr(&open.doc)) + } else { + state.was_canceled(&interaction.selection) + }; + let undone = replaced_document && state.history.redo.iter().any(|entry| interaction.wrote.as_ptr() == Arc::as_ptr(&entry.doc)); + canceled || undone +} + +/// Clears the selection when a Location gesture's stop is lost in another edit's preview it joined, which stays open. +/// The next panel pass reports the loss, and the stop the gesture began on is selected again if that preview is +/// canceled or undone. +fn clear_joined_location_stop(app: &mut VectorcraftApp) { + let restore = scrub_of(app) + .and_then(|s| Some(LocationRestore { owner: s.owner, from: s.from, stop: s.origin.clone()?, interaction: s.interaction.clone()? })); + select_stop(app, None); + if app.session.selected_stop().is_none() { + app.ui.gradient_panel.location_lost = true; + if restore.is_some() { + app.ui.gradient_panel.location_restore = restore; + } + } +} + +/// Once the preview a lost Location gesture joined has ended, selects the stop the gesture began on again if that +/// preview was canceled or undone, neither a stop nor a midpoint is selected, the same gradient is shown and that stop +/// is back at its index. A preview still open keeps the record. Returns true when the stop was selected again. +fn settle_location_restore(app: &mut VectorcraftApp) -> bool { + let Some(r) = app.ui.gradient_panel.location_restore.as_ref() else { return false }; + if is_open_interaction(&r.interaction, app) { + return false; + } + let stops = current(app).map(|g| g.gradient.stops).unwrap_or_default(); + let restore = rolled_back(&r.interaction, app) + && app.session.selected_stop().is_none() + && selected_mid(app, stops.len()).is_none() + && app.session.gradient_owner() == r.owner + && stops.get(r.from) == Some(&r.stop); + let from = r.from; + app.ui.gradient_panel.location_restore = None; + if restore { + select_stop(app, Some(from)); + } + restore && app.session.selected_stop() == Some(from) +} + +/// Settles lost and restored Location selections for this panel pass and announces each change. +fn announce_location_changes(app: &mut VectorcraftApp, ui: &Ui) { + let restored = settle_location_restore(app); + if end_lost_location_scrub(app) { + announce(ui.ctx(), tl!("The stop was changed by another edit. No stop is selected."), Politeness::Polite); + } else if restored { + announce(ui.ctx(), tl!("Another edit was canceled. The stop is selected again."), Politeness::Polite); + } +} + +/// Ends tracking of a non-retired Location gesture whose `event` belongs to it but must not write: its recorded +/// interaction is no longer open, or the gradient it began on is no longer shown. In the first case the gesture +/// settles its selection and retires. In the second case a preview the gesture opened and still owns ends on `Commit` +/// or `Cancel`. Returns true when `event` is to be discarded. +fn end_stale_location_scrub(app: &mut VectorcraftApp, event: &EditEvent>, stops: &[GradientStop]) -> bool { + let owner = app.session.gradient_owner(); + let Some(s) = app.ui.gradient_panel.location_scrub.as_ref().filter(|s| !s.retired && event.id() == Some(s.id)) else { return false }; + if s.interaction.is_some() && !owns_location_interaction(s, app) { + settle_lost_location_scrub(app, stops); + if let Some(s) = app.ui.gradient_panel.location_scrub.as_mut() { + s.retired = true; + } + return true; + } + if s.owner == owner { + return false; + } + let ends = matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. }); + if ends && s.opened && s.interaction.is_some() { + if matches!(event, EditEvent::Commit { .. }) { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + } else { + apply_event(app, event, &EditPath::Preview, &mut |_: &mut VectorcraftApp, _: &Option, _| {}); + } + } + true +} + +/// Retires tracking when the Location gesture has written a preview and that interaction is no longer open, selecting +/// its uniquely identified moved stop if its starting stop is still selected on the same owner, and leaving every +/// interaction unchanged. An already retired gesture is left alone. In its recorded interaction, a stop no longer +/// found in the current gradient clears the selection and discards the gesture's later events. The preview is +/// committed only if the gesture opened the interaction that received its first write; a joined interaction stays open. +/// Returns true when the stop is lost and no stop is selected, now or since the last call. No current gradient +/// leaves tracking unchanged. +fn end_lost_location_scrub(app: &mut VectorcraftApp) -> bool { + settle_location_restore(app); + let lost = end_lost_location_scrub_now(app); + let pending = std::mem::take(&mut app.ui.gradient_panel.location_lost); + (pending && app.session.selected_stop().is_none()) || lost +} + +/// [`end_lost_location_scrub`] for the current pass alone. +fn end_lost_location_scrub_now(app: &mut VectorcraftApp) -> bool { + let Some(s) = app.ui.gradient_panel.location_scrub.as_ref().filter(|s| !s.retired && s.interaction.is_some()) else { return false }; + let Some(g) = current(app) else { return false }; + let stops = &g.gradient.stops; + if !owns_location_interaction(s, app) { + let lost = settle_lost_location_scrub(app, stops); + if let Some(s) = app.ui.gradient_panel.location_scrub.as_mut() { + s.retired = true; + } + return lost; + } + if !scrub_of(app).is_some_and(|s| scrub_at(s, stops).is_none()) { + return false; + } + if s.opened { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + select_stop(app, None); + } else { + clear_joined_location_stop(app); + } + if let Some(s) = app.ui.gradient_panel.location_scrub.as_mut() { + s.retired = true; + } + app.session.selected_stop().is_none() +} + +/// The index in `stops` of the stop the gesture moves: `at` while the whole list equals the recorded list, +/// otherwise the only stop equal to the recorded stop. No match, multiple matches, or a recorded list that held +/// more than one stop equal to the recorded stop returns `None`. +fn scrub_at(s: &LocationScrub, stops: &[GradientStop]) -> Option { + let matches = |stop: &GradientStop| *stop == s.stop; + if stops == s.stops { + return Some(s.at); + } + if s.stops.iter().filter(|stop| matches(stop)).count() > 1 { + return None; + } + let mut found = stops.iter().enumerate().filter(|(_, stop)| matches(stop)).map(|(i, _)| i); + let at = found.next()?; + found.next().is_none().then_some(at) +} + +/// The non-retired Location gesture on the selected stop, on the gradient the active proxy shows. +fn scrub_of(app: &VectorcraftApp) -> Option<&LocationScrub> { + let sel = app.session.selected_stop(); + let owner = app.session.gradient_owner(); + app.ui.gradient_panel.location_scrub.as_ref().filter(|s| !s.retired && sel == Some(s.from) && s.owner == owner) +} + +/// The stop the panel shows as selected among `stops`: while a Location gesture's preview is the open interaction +/// (or the gesture has written none yet during an open interaction), the moved stop's index, or `None` if it cannot be +/// uniquely identified. Otherwise, the selected stop's index when it is in bounds. +fn shown_stop(app: &VectorcraftApp, stops: &[GradientStop]) -> Option { + let live = |s: &&LocationScrub| app.session.in_interaction() && (s.interaction.is_none() || owns_location_interaction(s, app)); + if let Some(s) = scrub_of(app).filter(live) { + return scrub_at(s, stops); + } + app.session.selected_stop().filter(|i| *i < stops.len()) } /// Select stop `i` (the session's selected stop, shared with the Gradient tool's annotator, the @@ -343,6 +698,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let points = is_grad && edits_points(app, &g); if hidden { if !points { + if is_grad { + announce_location_changes(app, ui); + } stops_editor(app, ui, &g, is_grad); } return; @@ -374,6 +732,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { // their fields. if freeform { draw_row(app, ui, shown_points(&g).mode); + if is_grad { + announce_location_changes(app, ui); + } stops_editor(app, ui, &g, is_grad); host_fields(app, ui, &g.gradient, is_grad); return; @@ -398,6 +759,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { aspect_field(app, ui, &g, placed); }); }); + if is_grad { + announce_location_changes(app, ui); + } stops_editor(app, ui, &g, is_grad); host_fields(app, ui, &g.gradient, is_grad); // Dither applies to gradient fills only: off and dimmed behind the Stroke proxy. @@ -692,10 +1056,12 @@ fn fill_box(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: b /// diamond's midpoint instead), and Delete Stop, which never goes below two stops. fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { let stops = &g.stops; - let sel = app.session.selected_stop().filter(|i| *i < stops.len() && is_grad); + let selected = app.session.selected_stop().filter(|_| is_grad); let mid = selected_mid(app, stops.len()).filter(|_| is_grad); - let stop = sel.and_then(|i| stops.get(i)); - if let (Some(i), Some(s)) = (sel, stop) { + // While a Location gesture moves the selected stop, the row shows and edits that stop where the preview has put it. + let shown_at = shown_stop(app, stops).filter(|_| selected.is_some()); + let stop = shown_at.and_then(|i| stops.get(i)); + if let (Some(i), Some(s)) = (shown_at, stop) { Row::new().show(ui, |ui, _| { Text::new(tl!("Color:")).shade(Shade::Muted).show(ui); let chip = Swatch::new(tl!("Edit the stop"), srgba(&s.color, 1.0)).tooltip(tl!("Edit the stop")).show(ui); @@ -711,6 +1077,9 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo let armed = app.session.tool_id() == "eyedropper"; let dropper = DropperButton::new(tl!("Eyedropper: click the art to sample the stop's colour"), Bind::given(armed)).show(ui); if dropper.request.is_some() { + if app.session.selected_stop() != Some(i) { + select_stop(app, Some(i)); + } stop_eyedropper(app); } }); @@ -724,11 +1093,11 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))) .range(0.0..=100.0) .unit("%") - .enabled(sel.is_some()) - .edit_target((target, sel)) + .enabled(shown_at.is_some()) + .edit_target((target, selected)) .show(ui); apply_number(app, &opacity.edit, |app, v, phase| { - let Some(i) = sel else { return }; + let Some(i) = shown_at else { return }; let mut v2 = stops.clone(); if let Some(s) = v2.get_mut(i) { s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; @@ -746,23 +1115,15 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo let location = NumberField::new(tl!("Location"), Bind::given(Some(loc))) .range(0.0..=100.0) .unit("%") - .enabled(sel.is_some() || mid.is_some()) - .edit_target((target, sel, mid)) + .enabled(shown_at.is_some() || mid.is_some()) + .edit_target((target, selected, mid)) .show(ui); - apply_number(app, &location.edit, |app, v, phase| { - let v = (v / 100.0) as f32; - if let Some(m) = mid { - set_stops(app, &set_midpoint(stops, m, v), None, phase); - } else if let Some(i) = sel { - let (v2, ni) = move_stop(stops, i, v); - set_stops(app, &v2, Some(ni), phase); - } - }); + apply_location(app, &location.edit.events, is_grad); }); - let can_del = sel.is_some() && stops.len() > MIN_STOPS; + let can_del = shown_at.is_some() && stops.len() > MIN_STOPS; let delete = IconButton::new(IconId::new("trash-2")).label(tl!("Delete Stop")).tooltip(tl!("Delete Stop")).enabled(can_del).show(ui); if delete.clicked() - && let Some(i) = sel + && let Some(i) = shown_at && let Some(v) = remove_stop(stops, i) { let next = i.min(v.len().saturating_sub(1)); @@ -771,6 +1132,172 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo }); } +/// Apply the Location field's `events` in order to the gradient behind the active proxy: the selected stop's +/// location, or the selected diamond's midpoint. Each event reads the stops and the selection that the events before +/// it left. A gesture's values move the stop it began on wherever its preview has put it, so the stop passes its +/// neighbors as a typed value does; a value outside a gesture moves the stop shown in the field. The moved stop stays +/// selected when identified; ending a gesture that owns its open preview clears the selection if its stop cannot be +/// identified. Ending a gesture whose recorded interaction is no longer open leaves the selection unchanged; +/// a gesture with no recorded interaction can still select its stop. +/// A gesture that joined another edit's preview leaves that preview open when it ends, and its tracking stays until +/// that preview ends so the selection follows its commit or cancel; when its stop is lost there, the selection is +/// cleared and selected again if that preview is canceled. A gesture that begins while a tracked gesture's stop cannot +/// be identified moves nothing. Events belonging to a retired +/// gesture, to a gesture whose recorded interaction is no longer open, or to a gesture begun on a gradient no longer +/// shown are discarded, and its tracking ends on `Commit` or `Cancel`. +fn apply_location(app: &mut VectorcraftApp, events: &EditEvents>, is_grad: bool) { + for event in events.iter() { + if app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| s.retired && event.id() == Some(s.id)) { + if matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. }) { + app.ui.gradient_panel.location_scrub = None; + } + continue; + } + let stops = current(app).filter(|_| is_grad).map(|g| g.gradient.stops).unwrap_or_default(); + if end_stale_location_scrub(app, event, &stops) { + if matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. }) { + app.ui.gradient_panel.location_scrub = None; + } + continue; + } + let sel = app.session.selected_stop().filter(|i| *i < stops.len()); + let mid = selected_mid(app, stops.len()).filter(|_| is_grad); + let gesture = match event { + EditEvent::Begin { id, .. } => { + let owner = app.session.gradient_owner(); + // Inside a preview an earlier gesture joined, the field shows that gesture's moved stop, which may sit + // at another index than the selected one, or past the end of stops another edit removed: the new + // gesture moves the stop shown. + let shown = shown_stop(app, &stops).filter(|i| *i < stops.len()); + let live = + app.session.in_interaction() && scrub_of(app).is_some_and(|s| s.interaction.is_none() || owns_location_interaction(s, app)); + if live && shown.is_none() { + // Another edit changed the tracked stop since the last panel pass: the stop cannot be identified, + // so the loss check settles the selection and this gesture's events move nothing. + end_lost_location_scrub_now(app); + if let Some(s) = app.ui.gradient_panel.location_scrub.as_mut() { + s.id = *id; + s.retired = true; + } + continue; + } + let target = shown.or(sel); + // A gesture begun in a preview an earlier live gesture wrote into keeps that gesture's starting stop. + let origin = match scrub_of(app).filter(|_| live) { + Some(s) => s.origin.clone(), + None => sel.map(|i| stops[i].clone()), + }; + // It also keeps that gesture's interaction, so the owner's commit or cancel before this gesture writes + // still settles the selection on the stop shown. + let (interaction, opened, inherited) = scrub_of(app).filter(|s| live && s.interaction.is_some()).map_or((None, false, None), |s| { + (s.interaction.clone(), s.opened, Some(s.inherited.clone().unwrap_or_else(|| (s.start, s.began.clone())))) + }); + app.ui.gradient_panel.location_scrub = + app.session.selected_stop().filter(|_| mid.is_none()).zip(target).map(|(i, at)| LocationScrub { + id: *id, + retired: false, + owner, + interaction, + opened, + from: i, + origin, + start: at, + at, + stop: stops[at].clone(), + began: stops.clone(), + stops, + inherited, + }); + continue; + } + _ => scrub_of(app) + .filter(|s| event.id() == Some(s.id) || (matches!(event, EditEvent::Set { .. }) && app.session.in_interaction())) + .map(|s| scrub_at(s, &stops)), + }; + let was_in_interaction = app.session.in_interaction(); + let can_select_scrub_stop = location_scrub_may_select(app); + // A gesture that joined another edit's preview writes into it but leaves it open for its owner. + let joined = gesture.is_some() && scrub_of(app).is_some_and(|s| s.interaction.is_some() && !s.opened); + // Only a preview the gesture opened and still owns is the gesture's to commit when its stop is lost. + let opened = gesture.is_some() && scrub_of(app).is_some_and(|s| s.opened && owns_location_interaction(s, app)); + // Its Cancel does not end the preview, which belongs to the edit that opened it; the gesture's writes stay in + // that preview until its owner commits or cancels it. + let joined_cancel = joined && matches!(event, EditEvent::Cancel { .. }); + let mut apply = |app: &mut VectorcraftApp, value: &Option, phase: Live| { + let phase = if joined { Live::Dragging } else { phase }; + if gesture == Some(None) { + if matches!(event, EditEvent::Commit { .. } | EditEvent::Set { .. }) { + if joined { + clear_joined_location_stop(app); + return; + } + if opened { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + } + if can_select_scrub_stop { + select_location_scrub_stop(app); + } + } + return; + } + let Some(v) = *value else { return }; + let v = (v / 100.0) as f32; + if let Some(m) = mid { + set_stops(app, &set_midpoint(&stops, m, v), None, phase); + } else if let Some(i) = gesture.flatten().or(sel) { + let (v2, ni) = move_stop(&stops, i, v); + let before = + app.session.active().and_then(|state| state.interaction.as_ref()).map(|interaction| Arc::downgrade(&interaction.selection)); + set_stops(app, &v2, Some(ni), phase); + if gesture.is_some() + && let Some(stops) = current(app).map(|g| g.gradient.stops) + && let Some(stop) = stops.get(ni).cloned() + && let Some(s) = app.ui.gradient_panel.location_scrub.as_mut() + { + s.at = ni; + s.stop = stop; + s.stops = stops; + s.inherited = None; + s.interaction = app.session.active().and_then(|state| { + let interaction = state.interaction.as_ref()?; + if s.interaction.is_none() { + s.opened = before.as_ref().is_none_or(|selection| selection.as_ptr() != Arc::as_ptr(&interaction.selection)); + } + Some(LocationInteraction { + document: (state.uid, state.reverts), + selection: Arc::downgrade(&interaction.selection), + started: Arc::downgrade(&interaction.doc), + wrote: Arc::downgrade(&state.doc), + }) + }); + } + } + }; + if !joined_cancel { + apply_event(app, event, &EditPath::Preview, &mut apply); + } else if gesture == Some(None) && app.session.selected_stop().is_some() { + clear_joined_location_stop(app); + } + if let EditEvent::Cancel { reason, .. } = event + && was_in_interaction + && gesture.is_some() + && !joined_cancel + && can_select_scrub_stop + && (reason.document_moved() || *reason == CancelReason::Removed) + { + select_location_scrub_stop(app); + } + // A joined preview's owner can still commit or cancel it, so tracking stays to settle the selection then. + let keeps_tracking = joined && gesture.flatten().is_some() && !matches!(event, EditEvent::Update { .. }); + if matches!(event, EditEvent::Commit { .. } | EditEvent::Cancel { .. } | EditEvent::Set { .. }) && !keeps_tracking { + app.ui.gradient_panel.location_scrub = None; + } + } +} + /// The editor's stops of `g`: each stop's tag is its index in `g` plus one, which [`app_stops`] /// reads back; the opacity is the colour's alpha. fn editor_stops(g: &GradientPaint) -> GradientStops { @@ -821,7 +1348,7 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra }; let selected = match selected_mid(app, stops.len()) { Some(m) => Some(StopRef::Midpoint(StopRow::Color, m)), - None => app.session.selected_stop().filter(|i| *i < stops.len()).map(StopRef::Color), + None => shown_stop(app, stops).map(StopRef::Color), }; let mut shared = selected; let out = GradientEditor::new(tl!("Gradient"), Bind::given(editor_stops(g))) diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 0fe5d38823..222d8f96d8 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -1,6 +1,7 @@ use std::cell::{RefCell, RefMut}; use std::rc::Rc; +use craft::ui::testing::focus::AccessActionKind; use craft::ui::testing::{Fixture, Target}; use egui::{Key, Modifiers, Pos2, pos2, vec2}; use vectorcraft_doc::NodeId; @@ -535,6 +536,1749 @@ fn an_unfinished_value_does_not_reach_a_wider_selection_or_another_symbol_part() assert_eq!(rig.text("Angle"), angle, "Angle shows the other part's angle"); } +/// White, three grays and black: stops at 0, 40, 50, 60 and 100 %. +fn five_stops() -> Value { + json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#c0c0c0"}, + {"offset": 0.5, "color": "#808080"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]) +} + +/// White, two grays and black: stops at 0, 40, 60 and 100 %. +fn four_stops() -> Value { + json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]) +} + +/// The fill's stops as (percent, hex) pairs, and the selected stop. +fn stops_and_selection(app: &VectorcraftApp) -> (Vec<(f64, String)>, Option) { + let stops = fill(app).gradient.stops.iter().map(|s| (percent(s.offset), s.color.to_hex())).collect(); + (stops, app.session.selected_stop()) +} + +/// The panel over a rectangle filled with `stops`, stop `select` selected. +fn rig_with_stop(stops: &Value, select: usize) -> Rig { + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("gradient.selectStop", json!({"index": select})).unwrap(); + Rig::new(app) +} + +/// A scrub of Location, or a location typed with Enter, moves only the selected stop, past one or two neighbors in +/// either direction: the neighbors keep their locations, the stop stays selected, and the scrub is one undo step. +#[test] +fn scrubbing_location_past_neighbors_moves_only_the_selected_stop() { + // (stops, the stop moved, points dragged, where it ends in percent) + let cases = [(four_stops(), 1, 40.0, "80"), (four_stops(), 2, -40.0, "20"), (five_stops(), 1, 40.0, "80"), (five_stops(), 3, -40.0, "20")]; + for (stops, from, by, typed) in cases { + let mut rig = rig_with_stop(&stops, from); + let before = stops_and_selection(&rig.app()); + let mut expected = before.0.clone(); + let moved = expected.remove(from); + let to: f64 = typed.parse().unwrap(); + let at = expected.iter().position(|(p, _)| *p > to).unwrap_or(expected.len()); + expected.insert(at, (to, moved.1)); + let expected = (expected, Some(at)); + + let undo = rig.app().session.doc().unwrap().history.undo.len(); + let field = rig.at("Location"); + rig.drag(field, field + vec2(by, 0.0)); + assert_eq!(stops_and_selection(&rig.app()), expected, "a scrub of stop {from} by {by}"); + assert_eq!(rig.app().session.doc().unwrap().history.undo.len(), undo + 1, "the scrub of stop {from} is one undo step"); + rig.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(stops_and_selection(&rig.app()).0, before.0, "undo puts the stops of stop {from}'s scrub back"); + + let mut typing = rig_with_stop(&stops, from); + typing.type_into("Location", typed); + assert_eq!(stops_and_selection(&typing.app()), expected, "typing {typed} for stop {from}"); + } +} + +/// A Location value outside a gesture (an arrow step) moves the stop from the stops shown, even when a gesture on the +/// same stop was left without an end. +#[test] +fn a_location_step_moves_the_stop_from_the_stops_shown() { + let mut rig = rig_with_stop(&four_stops(), 1); + let field = rig.target("Location"); + rig.fixture.click(&field).settle(); + let owner = rig.app().session.gradient_owner(); + let stops = fill(&rig.app()).gradient.stops; + let stop = stops[2].clone(); + rig.app().ui.gradient_panel.location_scrub = Some(LocationScrub { + id: GestureId::default(), + retired: false, + owner, + interaction: None, + opened: true, + from: 1, + origin: stops.get(1).cloned(), + start: 2, + at: 2, + stop, + began: stops.clone(), + stops, + inherited: None, + }); + rig.fixture.key(Key::ArrowUp, Modifiers::NONE).settle(); + let expected = vec![(0.0, "#ffffff".to_owned()), (41.0, "#808080".to_owned()), (60.0, "#404040".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&rig.app()), (expected, Some(1)), "the step moves stop 1 of the stops shown"); +} + +/// The Location field's events for a gesture: its begin from `from` percent and its updates to `values`. +fn location_gesture(from: f64, values: &[f64]) -> EditEvents> { + let id = GestureId::default(); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(from)), "Location".into(), None)); + for v in values { + events.push(EditEvent::update(id, Some(*v))); + } + events +} + +/// The gradient behind the stroke proxy as (percent, hex) pairs. +fn stroke_stops(app: &VectorcraftApp) -> Vec<(f64, String)> { + let Paint::Gradient(g) = crate::panels::current_paints(app).1 else { panic!("a gradient stroke") }; + g.gradient.stops.iter().map(|s| (percent(s.offset), s.color.to_hex())).collect() +} + +/// A gesture that ends in the same pass as a step that follows it (a wheel scrub, then an arrow key): the step moves +/// the stop the gesture moved, from where the gesture left it. +#[test] +fn a_step_after_a_location_gesture_in_one_pass_moves_the_same_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + let mut ends = EditEvents::new(); + ends.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + ends.push(EditEvent::set(Mixed::Same(Some(80.0)), Some(81.0), "Location".into(), None)); + apply_location(&mut app, &ends, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (81.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "the step moves the stop the gesture moved"); +} + +/// A step during a Location gesture's live preview moves the stop shown in the field past its neighbor. +#[test] +fn a_step_during_a_location_gesture_moves_the_same_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + assert!(app.session.in_interaction(), "the gesture's preview is live"); + let mut step = EditEvents::new(); + step.push(EditEvent::set(Mixed::Same(Some(80.0)), Some(81.0), "Location".into(), None)); + apply_location(&mut app, &step, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (81.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "the step moves the stop shown in Location"); +} + +/// A Location gesture finds its stop after another edit adds a stop before it. +#[test] +fn a_location_gesture_finds_its_stop_after_another_edit_adds_one() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + let added = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#ff0000"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": added})).unwrap(); + let mut update = EditEvents::new(); + update.push(EditEvent::update(GestureId::default(), Some(90.0))); + apply_location(&mut app, &update, true); + let expected = vec![ + (0.0, "#ffffff".to_owned()), + (20.0, "#ff0000".to_owned()), + (60.0, "#404040".to_owned()), + (90.0, "#808080".to_owned()), + (100.0, "#000000".to_owned()), + ]; + assert_eq!(stops_and_selection(&app), (expected, Some(1)), "the gesture's stop moves and its neighbor stays at 60%"); +} + +/// A Location gesture finds its stop when removing earlier stops puts its original index outside the list. +#[test] +fn a_location_gesture_finds_its_stop_after_another_edit_removes_earlier_stops() { + let mut app = app(json!({"gradient": {"stops": five_stops()}})); + app.run("gradient.selectStop", json!({"index": 3})).unwrap(); + apply_location(&mut app, &location_gesture(60.0, &[20.0]), true); + let remaining = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": remaining})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(3), "the selected index is outside the remaining stops"); + let mut update = EditEvents::new(); + update.push(EditEvent::update(GestureId::default(), Some(30.0))); + apply_location(&mut app, &update, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (30.0, "#404040".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the gesture's stop moves and the endpoints stay in place"); +} + +/// A Location gesture moves no stop when another edit recolors its stop, and its commit closes the preview and +/// leaves no stop selected. +#[test] +fn a_location_gesture_moves_nothing_when_its_stop_is_gone() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": recolored, "angle": 30})).unwrap(); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#ff0000".to_owned()), (100.0, "#000000".to_owned())]; + let mut update = EditEvents::new(); + update.push(EditEvent::update(GestureId::default(), Some(90.0))); + apply_location(&mut app, &update, true); + assert_eq!(stops_and_selection(&app), (expected.clone(), Some(1)), "the update leaves every stop in place"); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(90.0))); + apply_location(&mut app, &end, true); + assert_eq!(stops_and_selection(&app), (expected, None), "the commit leaves every stop in place and selects no stop"); + assert_eq!(fill(&app).angle, 30.0, "the commit keeps the preview's angle"); + assert!(!app.session.in_interaction(), "the commit closes the preview"); +} + +/// A Location gesture distinguishes stops with the same color and offset by their opacity. +#[test] +fn a_location_gesture_moves_only_its_own_stop_among_stops_of_its_color() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let added = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#ff0000"}, + {"offset": 0.8, "color": "#808080", "opacity": 0.5}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 0.95, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": added})).unwrap(); + let expected = vec![ + (0.0, "#ffffff".to_owned()), + (20.0, "#ff0000".to_owned()), + (80.0, "#808080".to_owned()), + (80.0, "#808080".to_owned()), + (95.0, "#404040".to_owned()), + (100.0, "#000000".to_owned()), + ]; + assert_eq!(stops_and_selection(&app), (expected, Some(1)), "the preview places both gray stops after the added red stop"); + let opacities = |app: &VectorcraftApp| fill(app).gradient.stops.iter().map(|s| s.opacity).collect::>(); + assert_eq!(opacities(&app), vec![1.0, 1.0, 0.5, 1.0, 1.0, 1.0], "the half-opaque stop takes the recorded index 2"); + let mut update = EditEvents::new(); + update.push(EditEvent::update(GestureId::default(), Some(90.0))); + apply_location(&mut app, &update, true); + let expected = vec![ + (0.0, "#ffffff".to_owned()), + (20.0, "#ff0000".to_owned()), + (80.0, "#808080".to_owned()), + (90.0, "#808080".to_owned()), + (95.0, "#404040".to_owned()), + (100.0, "#000000".to_owned()), + ]; + assert_eq!(stops_and_selection(&app), (expected, Some(1)), "only the fully opaque gray stop moves to 90%"); + assert_eq!(opacities(&app), vec![1.0, 1.0, 0.5, 1.0, 1.0, 1.0], "the gray stop at 80% stays half opaque"); +} + +/// A Location gesture moves no stop when a changed list puts another identical stop at its recorded index. +#[test] +fn a_location_gesture_moves_nothing_when_identical_stops_are_ambiguous() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 0.8, "color": "#404040"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("gradient.selectStop", json!({"index": 3})).unwrap(); + apply_location(&mut app, &location_gesture(80.0, &[80.0]), true); + let added = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#ff0000"}, + {"offset": 0.4, "color": "#0000ff"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 0.8, "color": "#404040"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": added})).unwrap(); + let before = fill(&app).gradient.stops; + let mut update = EditEvents::new(); + update.push(EditEvent::update(GestureId::default(), Some(90.0))); + apply_location(&mut app, &update, true); + assert_eq!(fill(&app).gradient.stops, before, "the gesture moves no stop when the identical stops make its match ambiguous"); +} + +/// A Location gesture keeps a change made to another stop while it runs: it moves only its own stop. +#[test] +fn a_location_gesture_keeps_a_neighbor_changed_while_it_runs() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#ff0000"}, + {"offset": 0.7, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": recolored})).unwrap(); + let mut end = EditEvents::new(); + end.push(EditEvent::update(GestureId::default(), Some(80.0))); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#ff0000".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "the recolored neighbor stays"); +} + +/// The Color chip opens the stop a Location scrub is moving, even when it is activated before the scrub ends. +#[test] +fn the_color_chip_opens_the_stop_a_location_scrub_moves() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + let chip = rig.target("Edit the stop"); + rig.fixture.access(AccessActionKind::Click, &chip).settle(); + assert_eq!(rig.app().session.selected_stop(), Some(2), "the chip selects the moved stop for its popover"); +} + +/// The eyedropper selects the stop a Location scrub is moving before sampling its color. +#[test] +fn the_eyedropper_samples_into_the_stop_a_location_scrub_moves() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + let dropper = rig.target("Eyedropper: click the art to sample the stop's colour"); + rig.fixture.access(AccessActionKind::Click, &dropper).settle(); + assert_eq!(rig.app().session.selected_stop(), Some(2), "the eyedropper selects the moved stop for sampling"); +} + +/// A Location gesture begun on the fill's stop does not write the fill's stops into the stroke when the stroke's stop +/// of the same index is selected before the gesture ends. +#[test] +fn a_location_gesture_keeps_to_the_gradient_it_began_on() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + let stroke = json!([ + {"offset": 0, "color": "#ff0000"}, + {"offset": 0.3, "color": "#00ff00"}, + {"offset": 0.7, "color": "#0000ff"}, + {"offset": 1, "color": "#ffff00"}, + ]); + app.run("paint.setStroke", json!({"gradient": {"stops": stroke}})).unwrap(); + app.session.fill_active = true; + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.session.fill_active = false; + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(30.0)), Some(80.0))); + apply_location(&mut app, &end, true); + let expected = vec![(0.0, "#ff0000".to_owned()), (30.0, "#00ff00".to_owned()), (70.0, "#0000ff".to_owned()), (100.0, "#ffff00".to_owned())]; + assert_eq!(stroke_stops(&app), expected, "the fill gesture's Commit leaves the stroke's stops unchanged"); +} + +/// Removing a Location gesture whose preview it opened commits that preview with the moved stop. +#[test] +fn a_removed_location_gesture_commits_the_preview_it_opened() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + assert!(app.session.in_interaction(), "the Location gesture opens a preview"); + crate::edits::end_removed(&mut app, &[GestureId::default()]); + assert!(!app.session.in_interaction(), "removing the gesture ends the preview it opened"); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "the removed preview keeps the moved stop, selected"); +} + +/// A Location scrub that begins inside another edit's preview and loses its stop before its first write leaves that +/// preview open on its Commit. +#[test] +fn a_location_commit_before_its_first_write_leaves_another_edits_preview_open() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#ff0000"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + assert!(app.session.in_interaction(), "the Commit leaves the other edit's preview open"); + app.session.cancel_interaction().unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); +} + +#[test] +fn a_removed_location_gesture_leaves_no_tracking() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + assert!(app.ui.gradient_panel.location_scrub.is_some(), "the Location gesture tracks its stop"); + crate::edits::end_removed(&mut app, &[GestureId::default()]); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "the removed Location gesture leaves no tracking"); + assert_eq!(app.session.selected_stop(), Some(2), "the moved #808080 stop stays selected after the Location gesture is removed"); +} + +/// Removing a Location gesture after its preview is rolled back keeps the restored stop selected. +#[test] +fn a_removed_location_gesture_after_rollback_keeps_the_original_stop_selected() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.session.cancel_interaction().unwrap(); + crate::edits::end_removed(&mut app, &[GestureId::default()]); + let stops = fill(&app).gradient.stops; + assert_eq!(percent(stops[1].offset), 40.0, "the original stop returns to 40 percent"); + assert_eq!(percent(stops[2].offset), 60.0, "the neighbor stays at 60 percent"); + assert_eq!(app.session.selected_stop(), Some(1), "removing the gesture keeps the restored stop selected"); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "the removed Location gesture leaves no tracking"); +} + +/// A Location gesture canceled because its field went away keeps its preview and selects the stop it moved. +#[test] +fn a_removed_location_cancel_keeps_the_moved_stop_selected() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Removed, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), Some(2), "the moved #808080 stop stays selected after a Removed cancel"); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "a Removed cancel clears the Location gesture tracking"); +} + +/// A Location cancel after its preview is restored keeps the original stop selected among identical stops. +#[test] +fn a_location_cancel_after_restoring_the_preview_keeps_the_original_stop_selected() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + app.session.cancel_interaction().unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "canceling the interaction restores the original stops"); + assert!(!app.session.in_interaction(), "the preview ends before the field receives its Cancel event"); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::UndoDuringGesture, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), Some(1), "the Cancel keeps stop 1 selected instead of the identical stop at 80%"); +} + +/// A Location gesture canceled with Escape puts the stops and the selection back. +#[test] +fn an_escape_location_cancel_restores_the_stops_and_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), Some(1), "an Escape cancel leaves the original stop selected"); + assert_eq!(fill(&app).gradient.stops, before, "an Escape cancel restores the original stops"); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "an Escape cancel clears the Location gesture tracking"); +} + +/// While a Location scrub has moved the selected stop past a neighbor, the panel shows that stop: Location gives its +/// location and the slider marks it, not the neighbor that took its place in the list. +#[test] +fn a_location_scrub_shows_the_stop_it_moves() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + let stops = fill(&rig.app()).gradient.stops; + let moved = stops.iter().position(|s| s.color.to_hex() == "#808080"); + assert_eq!(moved, Some(2), "the preview has the stop past its neighbor: {stops:?}"); + assert_eq!(rig.number("Location"), Some(80.0), "Location shows the stop being moved"); + let marked = |name: &str| rig.fixture.tree().selected_of(rig.target(name).node) == Some(true); + assert_eq!((marked("Color stop 2 of 4"), marked("Color stop 3 of 4")), (false, true), "the slider marks the stop being moved"); + rig.fixture.release_at(at + vec2(40.0, 0.0)); + assert_eq!(rig.app().session.selected_stop(), Some(2), "the stop stays selected after the release"); +} + +/// A Location scrub keeps showing its stop when another edit removes earlier stops. +#[test] +fn a_location_scrub_shows_its_stop_after_another_edit_removes_earlier_stops() { + let mut rig = rig_with_stop(&five_stops(), 3); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(-40.0, 0.0)); + let remaining = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": remaining})).unwrap(); + rig.fixture.frame(vec![]); + assert_eq!(rig.number("Location"), Some(20.0), "Location shows the moved stop"); + assert!(!rig.disabled("Location"), "Location stays enabled for the moved stop"); + rig.fixture.release_at(at + vec2(-40.0, 0.0)); + assert_eq!(rig.app().session.selected_stop(), Some(1), "the stop stays selected after the release"); +} + +/// A Location scrub shows no selected stop when another edit changes the moved stop's color. +#[test] +fn a_location_scrub_shows_no_stop_after_another_edit_changes_its_color() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + rig.fixture.frame(vec![]); + assert!(rig.disabled("Delete Stop"), "Delete Stop is disabled when the moved stop cannot be identified"); + assert!( + (1..=4).all(|i| rig.fixture.tree().selected_of(rig.target(&format!("Color stop {i} of 4")).node) != Some(true)), + "the slider marks no color stop when the moved stop cannot be identified" + ); + rig.fixture.release_at(at + vec2(40.0, 0.0)); +} + +/// A Location scrub whose moved stop another edit recolors ends at the next frame: the preview's stops stay, no stop +/// is selected, and the rest of the drag moves nothing. +#[test] +fn a_location_scrub_whose_stop_is_recolored_ends_with_no_stop_selected() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + rig.fixture.frame(vec![]); + assert!(!rig.app().session.in_interaction(), "the frame closes the preview of the gesture whose stop is lost"); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#ff0000".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&rig.app()), (expected.clone(), None), "the other edit stays and no stop is selected"); + rig.fixture.release_at(at + vec2(80.0, 0.0)); + assert_eq!(stops_and_selection(&rig.app()), (expected, None), "the rest of the drag moves no stop"); + assert!(rig.disabled("Delete Stop"), "Delete Stop is disabled with no stop selected"); +} + +/// Losing the moved stop announces the cleared selection in that frame and retires the scrub. +#[test] +fn a_location_scrub_announces_when_its_stop_is_recolored() { + let mut rig = rig_with_stop(&four_stops(), 1); + let at = rig.at("Location"); + rig.fixture.drag_hold_at(at, vec2(40.0, 0.0)); + assert!(rig.app().session.in_interaction(), "the scrub keeps its preview open"); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + rig.fixture.frame(vec![]); + assert_eq!(rig.app().session.selected_stop(), None, "the lost stop clears the selection"); + let message = tl!("The stop was changed by another edit. No stop is selected."); + let announces = |rig: &Rig| { + let tree = rig.fixture.tree(); + tree.keys().into_iter().any(|key| tree.role_of(key) == Some(craft::ui::contract::Role::STATUS) && tree.name_of(key) == Some(message)) + }; + assert!(announces(&rig), "the cleared selection is announced in the frame where the stop is lost"); + // The status node keeps an announcement for a quarter second after its frame. + rig.fixture.advance(0.5).frame(vec![]); + assert!(!announces(&rig), "a later frame does not announce it again"); + rig.fixture.release_at(at + vec2(80.0, 0.0)); +} + +/// A Location gesture whose interaction ended leaves another edit's preview open when its stop is lost, and stops +/// tracking its stop. Its remaining events leave that preview and selection unchanged. +#[test] +fn a_location_gesture_whose_interaction_ended_leaves_another_preview_open() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.session.cancel_interaction().unwrap(); + app.begin_interaction("Other edit").unwrap(); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#ff0000"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let stops = fill(&app).gradient.stops; + let other_selection = app.session.active().unwrap().interaction.as_ref().unwrap().selection.clone(); + end_lost_location_scrub(&mut app); + assert!(app.session.in_interaction(), "the other edit's preview stays open after the gesture's stop is lost"); + assert!(app.ui.gradient_panel.location_scrub.as_ref().is_some_and(|s| s.retired), "the gesture retires after its interaction ends"); + assert_eq!(app.session.selected_stop(), Some(1), "the selection stays as it was"); + for event in [EditEvent::update(GestureId::default(), Some(90.0)), EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(90.0))] { + let mut events = EditEvents::new(); + events.push(event); + apply_location(&mut app, &events, true); + assert_eq!(fill(&app).gradient.stops, stops, "the retired gesture's event preserves the other edit's previewed stops"); + assert!(app.session.in_interaction(), "the retired gesture's event leaves the other interaction open"); + assert!( + app.session.active().unwrap().interaction.as_ref().is_some_and(|interaction| Arc::ptr_eq(&interaction.selection, &other_selection)), + "the retired gesture's event preserves the other interaction" + ); + assert_eq!(app.session.selected_stop(), Some(1), "the retired gesture's event leaves the selection unchanged"); + } + assert!(app.ui.gradient_panel.location_scrub.is_none(), "the retired gesture's Commit drops its tracking"); +} + +/// Clearing history during a Location gesture keeps its preview and selects the moved stop. +#[test] +fn a_location_gesture_committed_by_clear_history_keeps_the_moved_stop_selected() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.run("edit.clearHistory", json!({})).unwrap(); + assert!(!app.session.in_interaction(), "clearing history commits the Location preview"); + end_lost_location_scrub(&mut app); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the committed stops keep #808080 at 80 percent and its neighbor at 60 percent"); + assert_eq!(app.session.selected_stop(), Some(2), "the moved #808080 stop stays selected after clearing history"); +} + +/// Clearing history during a Location gesture on the default fill selects the moved stop without changing the document. +#[test] +fn a_default_location_gesture_committed_by_clear_history_keeps_the_moved_stop_selected() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "no artwork is selected"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let document = app.session.active().unwrap().doc.clone(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + assert!(Arc::ptr_eq(&document, &app.session.active().unwrap().doc), "the default fill scrub keeps the same document"); + app.run("edit.clearHistory", json!({})).unwrap(); + assert!(!app.session.in_interaction(), "clearing history commits the Location preview"); + end_lost_location_scrub(&mut app); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the default fill keeps the committed stops"); + assert_eq!(app.session.selected_stop(), Some(2), "the moved stop stays selected after clearing history"); +} + +/// Removing a Location gesture after clearing history keeps its committed stop selected. +#[test] +fn a_removed_location_gesture_after_clear_history_keeps_the_moved_stop_selected() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.run("edit.clearHistory", json!({})).unwrap(); + crate::edits::end_removed(&mut app, &[GestureId::default()]); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "removing the gesture keeps the committed #808080 stop selected at 80 percent"); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "the removed Location gesture leaves no tracking"); +} + +/// Clearing history after another edit recolors a neighbor keeps the uniquely identified moved stop selected. +#[test] +fn a_location_gesture_committed_by_clear_history_keeps_its_stop_selected_after_a_neighbor_is_recolored() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#ff0000"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": recolored})).unwrap(); + app.run("edit.clearHistory", json!({})).unwrap(); + end_lost_location_scrub(&mut app); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#ff0000".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app), (expected, Some(2)), "the recolored neighbor stays and the moved #808080 stop is selected"); +} + +/// After clearing history commits a Location scrub, the first frame marks and shows the moved stop. +#[test] +fn a_location_scrub_committed_by_clear_history_shows_the_same_stop_in_the_ramp_and_fields() { + let mut rig = rig_with_stop(&four_stops(), 1); + apply_location(&mut rig.app(), &location_gesture(40.0, &[70.0, 80.0]), true); + rig.app().run("edit.clearHistory", json!({})).unwrap(); + rig.fixture.frame(vec![]); + assert_eq!(rig.number("Location"), Some(80.0), "the fields show the committed stop at 80 percent"); + let marked = |name: &str| rig.fixture.tree().selected_of(rig.target(name).node) == Some(true); + assert_eq!( + (marked("Color stop 2 of 4"), marked("Color stop 3 of 4")), + (false, true), + "the ramp marks the same moved stop the fields show in the first frame after clearing history" + ); +} + +/// Restoring a Location preview keeps the original stop selected when the moved stop matched a neighbor. +#[test] +fn a_rolled_back_location_scrub_keeps_the_original_stop_selected() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + apply_location(&mut app, &location_gesture(40.0, &[60.0]), true); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "the original four stops stay restored"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop stays selected instead of its identical neighbor"); +} + +/// Undoing a Location scrub and an endpoint recolor keeps the original stop selected. +#[test] +fn a_location_scrub_undone_with_an_earlier_recolor_keeps_the_original_stop_selected() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": stops}})); + let before = fill(&app).gradient.stops; + let recolored = json!([ + {"offset": 0, "color": "#ff0000"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + edit(&mut app, json!({"stops": recolored}), Live::Released); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[60.0]), true); + app.session.commit_interaction().unwrap(); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "both undos restore the original four stops with a white endpoint"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1), "the original 40 percent stop is selected before settlement"); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(1), "settlement keeps the original stop selected instead of its identical 60 percent neighbor"); +} + +/// Canceling a Location scrub and an endpoint recolor keeps the original stop selected. +#[test] +fn a_location_scrub_canceled_with_an_earlier_recolor_keeps_the_original_stop_selected() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": stops}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + let recolored = json!([ + {"offset": 0, "color": "#ff0000"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.begin_interaction("Endpoint recolor").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": recolored})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[60.0]), true); + app.session.cancel_interaction().unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "canceling restores the original four stops with a white endpoint"); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(1), "settlement keeps the original stop selected instead of its identical 60 percent neighbor"); +} + +/// A Location scrub settles against the reversed gradient's current stop order. +#[test] +fn a_location_scrub_settles_against_the_reversed_stop_order() { + let mut app = app(json!({"gradient": {"stops": five_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[50.0]), true); + app.session.commit_interaction().unwrap(); + edit(&mut app, json!({"reverse": true}), Live::Released); + assert!(!app.session.in_interaction(), "no preview is open after the reversal"); + end_lost_location_scrub(&mut app); + let stops = fill(&app).gradient.stops; + let selected = &stops[app.session.selected_stop().unwrap()]; + assert_eq!(selected.color.to_hex(), "#c0c0c0", "the moved gray stop stays selected in the reversed list"); + assert_eq!(percent(selected.offset), 50.0, "the selected stop is at its reversed location"); +} + +/// A Location gesture whose stop disappears discards its late Cancel without ending another preview. +#[test] +fn a_location_scrub_whose_stop_disappears_leaves_another_preview_open_on_cancel() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + end_lost_location_scrub(&mut app); + assert!(!app.session.in_interaction(), "losing the moved stop commits its preview"); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + let stops = fill(&app).gradient.stops; + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::UndoDuringGesture, None)); + apply_location(&mut app, &cancel, true); + assert!(app.session.in_interaction(), "the old gesture's Cancel leaves the other preview open"); + assert_eq!(fill(&app).gradient.stops, stops, "the other preview keeps its stops"); + assert!(app.ui.gradient_panel.location_scrub.is_none(), "the old gesture's Cancel drops its tracking"); +} + +/// Losing a Location scrub's stop commits the preview it opened after a Typing interaction. +#[test] +fn a_location_scrub_whose_stop_disappears_commits_its_preview_after_typing() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Typing").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + assert!(app.session.in_interaction(), "the Typing preview is open before the gesture"); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + assert_eq!(app.session.active().unwrap().interaction.as_ref().unwrap().label, "Gradient", "the scrub replaces the Typing interaction"); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let stops = fill(&app).gradient.stops; + end_lost_location_scrub(&mut app); + assert!(!app.session.in_interaction(), "losing the moved stop commits the preview the scrub opened"); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + assert_eq!(fill(&app).gradient.stops, stops, "committing keeps the recolored stops"); +} + +/// Losing a Location scrub's stop leaves the interaction it joined open for its owner to cancel. +#[test] +fn a_location_scrub_whose_stop_disappears_leaves_its_joined_preview_open() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + end_lost_location_scrub(&mut app); + assert!(app.session.in_interaction(), "losing the moved stop leaves the other edit's preview open"); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + app.session.cancel_interaction().unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); +} + +/// A Location scrub's Commit with its stop lost leaves the interaction it joined open for its owner to cancel. +#[test] +fn a_location_commit_with_a_lost_stop_leaves_its_joined_preview_open() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + assert!(app.session.in_interaction(), "the Commit leaves the other edit's preview open"); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + app.session.cancel_interaction().unwrap(); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); +} + +/// Releases a Location scrub of stop 1 to 80% inside another edit's preview, and returns the app and the stops from +/// before that preview. +fn released_into_a_joined_preview() -> (VectorcraftApp, Vec) { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + (app, before) +} + +/// Releasing a Location scrub that joined another edit's preview shows its moved stop and leaves that preview open; +/// canceling that preview keeps the original stop selected. +#[test] +fn a_location_release_leaves_its_joined_preview_open() { + let (mut app, before) = released_into_a_joined_preview(); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (80.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the release moves the stop"); + assert_eq!(shown_stop(&app, &fill(&app).gradient.stops), Some(2), "the panel shows the moved stop"); + assert!(app.session.in_interaction(), "the release leaves the other edit's preview open"); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop stays selected"); +} + +/// Committing the preview a released Location scrub joined selects the moved stop. +#[test] +fn a_committed_joined_preview_selects_the_released_location_stop() { + let (mut app, _) = released_into_a_joined_preview(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(2), "the moved stop is selected"); +} + +/// A second Location scrub inside the preview a released scrub joined moves the stop the field shows. +#[test] +fn a_second_location_scrub_in_a_joined_preview_moves_the_shown_stop() { + let (mut app, _) = released_into_a_joined_preview(); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(90.0))); + apply_location(&mut app, &end, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (60.0, "#404040".to_owned()), (90.0, "#808080".to_owned()), (100.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the moved stop moves again and its neighbor stays"); +} + +/// When the owner of a joined preview recolors the stop a second Location scrub moved and commits, the selection is +/// cleared rather than left on the unchanged neighbor at the selected index. +#[test] +fn a_second_location_scrubs_stop_recolored_in_its_joined_preview_clears_the_selection() { + let (mut app, _) = released_into_a_joined_preview(); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(90.0))); + apply_location(&mut app, &end, true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.9, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "the #404040 neighbor is not left selected"); +} + +/// When the owner of a joined preview puts the stop a second Location scrub moved back where that scrub began, edits +/// the neighbor and commits, the restored stop is selected rather than the neighbor at the selected index. +#[test] +fn a_second_location_scrubs_stop_restored_in_its_joined_preview_is_selected() { + let (mut app, _) = released_into_a_joined_preview(); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(90.0))); + apply_location(&mut app, &end, true); + let restored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#505050"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": restored})).unwrap(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(2), "the restored #808080 stop at 80 percent is selected"); +} + +/// When the owner of a joined preview restores the stop a second Location scrub moved twice over, the restored stop +/// cannot be identified and the selection is cleared. +#[test] +fn a_second_location_scrubs_stop_restored_twice_in_its_joined_preview_clears_the_selection() { + let (mut app, _) = released_into_a_joined_preview(); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(90.0))); + apply_location(&mut app, &end, true); + let restored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": restored})).unwrap(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "neither #808080 stop at 80 percent is selected"); +} + +/// When a second Location scrub begins on one of two identical stops in a joined preview and its stop is recolored +/// there, the unchanged twin is not selected in its place. +#[test] +fn a_second_location_scrub_begun_on_one_of_two_identical_stops_does_not_select_the_twin() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + let twins = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": twins})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(50.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(50.0))); + apply_location(&mut app, &end, true); + let recolored: Vec = fill(&app) + .gradient + .stops + .iter() + .map(|s| { + let color = if percent(s.offset) == 50.0 { "#ff0000".to_owned() } else { s.color.to_hex() }; + json!({"offset": s.offset, "color": color}) + }) + .collect(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": recolored})).unwrap(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "the unchanged #808080 twin at 80 percent is not selected"); +} + +/// A canceled Location preview followed by a recolor of the restored stop cannot be told from a kept preview whose +/// stop was lost, so the selection is cleared and the loss reported rather than another stop left selected. +#[test] +fn a_canceled_location_preview_then_a_recolor_of_its_stop_clears_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.session.cancel_interaction().unwrap(); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#ff00ff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.run("paint.editGradient", json!({"stroke": false, "stops": recolored})).unwrap(); + assert!(end_lost_location_scrub(&mut app), "the loss is reported"); + assert_eq!(app.session.selected_stop(), None, "no stop is selected"); +} + +/// A kept Location preview whose moved stop is lost clears the selection even when another stop now sits at the +/// starting stop's location. +#[test] +fn a_kept_location_preview_with_a_neighbor_at_the_starting_location_clears_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + app.session.commit_interaction().unwrap(); + assert!(end_lost_location_scrub(&mut app), "the loss is reported"); + assert_eq!(app.session.selected_stop(), None, "the neighbor is not left selected"); +} + +/// A Location scrub that landed on an identical stop moves nothing after another edit removes one of the pair. +#[test] +fn a_location_scrub_on_an_identical_pair_moves_nothing_after_one_is_removed() { + let pair = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = app(json!({"gradient": {"stops": pair}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let removed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.8, "color": "#808080"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": removed})).unwrap(); + let stops = fill(&app).gradient.stops; + let mut more = EditEvents::new(); + more.push(EditEvent::update(GestureId::default(), Some(90.0))); + apply_location(&mut app, &more, true); + assert_eq!(fill(&app).gradient.stops, stops, "the surviving stop does not move"); +} + +/// A Location scrub's Cancel with its stop lost in the preview it joined clears the selection, reports the loss and +/// leaves that preview open. +#[test] +fn a_location_cancel_with_a_lost_stop_in_a_joined_preview_clears_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert!(app.session.in_interaction(), "the other edit's preview stays open"); + assert_eq!(app.session.selected_stop(), None, "no stop is selected"); + assert!(end_lost_location_scrub(&mut app), "the next pass reports the loss"); +} + +/// A Location scrub's Cancel leaves the preview it joined open for the edit that opened it, and canceling that +/// preview keeps the original stop selected. +#[test] +fn a_location_cancel_leaves_its_joined_preview_open() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert!(app.session.in_interaction(), "the other edit's preview stays open"); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop stays selected"); +} + +/// Stops of [`four_stops`] after a Location scrub to 80 percent, with the moved #808080 stop recolored. +fn moved_and_recolored() -> Value { + json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]) +} + +/// A Location scrub's Commit with its stop lost in the preview it joined reports the loss in the next pass. +#[test] +fn a_location_commit_with_a_lost_stop_in_a_joined_preview_reports_the_loss() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + apply_location(&mut app, &end, true); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + assert!(end_lost_location_scrub(&mut app), "the next pass reports the loss"); +} + +/// When the owner of a joined preview cancels it after a Location scrub's stop was lost there, the original stop is +/// selected again; when the owner commits it, the selection stays cleared. +#[test] +fn a_rolled_back_joined_preview_restores_the_stop_a_lost_location_scrub_began_on() { + for (end, owner_cancels) in [("cancel", true), ("commit", true), ("cancel", false), ("commit", false)] { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + let mut events = EditEvents::new(); + if end == "cancel" { + events.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + } else { + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + } + apply_location(&mut app, &events, true); + assert_eq!(app.session.selected_stop(), None, "the gesture's {end} clears the selection"); + if owner_cancels { + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "after the gesture's {end}, the original stop is selected again"); + } else { + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "after the gesture's {end}, the committed lost stop stays unselected"); + } + } +} + +/// With the Live Paint Bucket active, the joined preview edits the tool's fill and leaves the document in place: +/// canceling it still selects the stop a lost Location scrub began on, and committing it keeps the selection cleared. +#[test] +fn a_rolled_back_bucket_preview_restores_the_stop_a_lost_location_scrub_began_on() { + for owner_cancels in [true, false] { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + let doc = Arc::clone(&app.session.active().unwrap().doc); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + assert!(Arc::ptr_eq(&doc, &app.session.active().unwrap().doc), "the preview edits the tool's fill, not the document"); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + if owner_cancels { + app.session.cancel_interaction().unwrap(); + app.begin_interaction("Later edit").unwrap(); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop is selected again after a later canceled edit"); + } else { + app.session.commit_interaction().unwrap(); + app.begin_interaction("Later edit").unwrap(); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "a later canceled edit does not restore the committed lost stop"); + } + } +} + +/// With the Live Paint Bucket active, an edit that removes the original stop after the joined preview is canceled and +/// before the panel settles clears the selection rather than leave its neighbor selected. +#[test] +fn a_canceled_bucket_preview_then_a_removed_stop_clears_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut events = EditEvents::new(); + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + events.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(80.0)), "Location".into(), None)); + apply_location(&mut app, &events, true); + app.session.cancel_interaction().unwrap(); + let removed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.run("paint.editGradient", json!({"stroke": false, "stops": removed})).unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "the 60 percent neighbor is not left selected"); +} + +/// With the Live Paint Bucket active, a second Location scrub that moves the stop back before the joined preview is +/// canceled keeps the original stop selected. +#[test] +fn a_canceled_bucket_preview_after_a_second_scrub_moved_the_stop_back_keeps_the_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let mut events = EditEvents::new(); + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + events.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(GestureId::new(1), Some(40.0))); + apply_location(&mut app, &events, true); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original 40 percent stop stays selected"); +} + +/// A Location scrub of an object's fill that ends back on its starting location keeps the stop selected when the +/// joined preview is canceled, while the new-art fill is a plain color. +#[test] +fn a_canceled_joined_preview_after_a_scrub_back_to_the_start_keeps_the_objects_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 40.0]), true); + let mut events = EditEvents::new(); + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(40.0))); + events.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(40.0)), "Location".into(), None)); + apply_location(&mut app, &events, true); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling keeps the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the 40 percent stop stays selected"); +} + +/// With the Live Paint Bucket active, an edit that recolors only a neighbor after the joined preview is canceled keeps +/// the original stop selected. +#[test] +fn a_canceled_bucket_preview_then_a_recolored_neighbor_keeps_the_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut events = EditEvents::new(); + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + events.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(80.0)), "Location".into(), None)); + apply_location(&mut app, &events, true); + app.session.cancel_interaction().unwrap(); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.run("paint.editGradient", json!({"stroke": false, "stops": recolored})).unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(1), "the unchanged 40 percent stop stays selected"); +} + +/// With the Live Paint Bucket active, a joined preview that moved the stop before a Location scrub moved it back keeps +/// the original stop selected when it is canceled. +#[test] +fn a_canceled_bucket_preview_that_moved_the_stop_first_keeps_the_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + let moved = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.5, "color": "#808080"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved})).unwrap(); + apply_location(&mut app, &location_gesture(50.0, &[40.0]), true); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original 40 percent stop stays selected"); +} + +/// A second Location scrub begun after a released one in a joined preview keeps the first one's settlement when the +/// owner ends that preview before the second scrub writes: a commit selects the moved stop, now at index 2, and a +/// cancel keeps the original stop at index 1, for the object's fill and for the Live Paint Bucket's. +#[test] +fn a_joined_preview_ended_before_a_second_scrub_writes_settles_the_first_scrubs_stop() { + for (bucket, owner_cancels) in [(false, false), (false, true), (true, false), (true, true)] { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + if bucket { + app.select_tool("livePaintBucket"); + app.run("paint.setFill", json!({"gradient": {"stops": four_stops()}})).unwrap(); + } + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = fill(&app).gradient.stops; + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + let mut events = EditEvents::new(); + events.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(40.0)), Some(80.0))); + events.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(80.0)), "Location".into(), None)); + apply_location(&mut app, &events, true); + if owner_cancels { + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "bucket {bucket}: canceling restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "bucket {bucket}: the original 40 percent stop stays selected"); + } else { + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops[2].color.to_hex(), "#808080", "bucket {bucket}: the commit keeps the moved stop at index 2"); + assert_eq!(app.session.selected_stop(), Some(2), "bucket {bucket}: the moved stop is selected, not its 60 percent neighbor"); + } + } +} + +/// When the owner of a joined preview puts the original stops back and commits before a second Location scrub writes, +/// the original stop, back at index 1, stays selected. +#[test] +fn a_joined_preview_committed_with_the_original_stops_before_a_second_scrub_writes_keeps_the_stop() { + let (mut app, before) = released_into_a_joined_preview(); + let mut begin = EditEvents::new(); + begin.push(EditEvent::begin(GestureId::new(1), Mixed::Same(Some(80.0)), "Location".into(), None)); + apply_location(&mut app, &begin, true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "the commit keeps the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original 40 percent stop stays selected"); +} + +/// Joins another edit's preview showing `preview`, selects stop `select`, scrubs it to 80 percent, previews `lost` so its +/// stop is lost, and cancels the scrub; returns the app with the joined preview still open. +fn lost_in_a_joined_preview(preview: Value, select: usize, lost: Value) -> VectorcraftApp { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": preview})).unwrap(); + app.run("gradient.selectStop", json!({"index": select})).unwrap(); + let from = percent(fill(&app).gradient.stops[select].offset); + apply_location(&mut app, &location_gesture(from, &[80.0]), true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": lost})).unwrap(); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + app +} + +/// A stop the joined preview added and a lost Location scrub began on is not restored by index after that preview is +/// canceled, since another stop sits at that index then. +#[test] +fn a_canceled_joined_preview_does_not_restore_a_stop_it_added() { + let added = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.5, "color": "#ffaa00"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + let lost = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + let mut app = lost_in_a_joined_preview(added, 2, lost); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "the #404040 stop now at index 2 is not selected"); +} + +/// After two Location scrubs move the same stop past its neighbor in a joined preview and the second one loses it, +/// canceling that preview selects the original stop again. +#[test] +fn a_canceled_joined_preview_restores_the_stop_two_location_scrubs_moved() { + let (mut app, before) = released_into_a_joined_preview(); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let lost = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.9, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": lost})).unwrap(); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(id, CancelReason::Escape, None)); + apply_location(&mut app, &cancel, true); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(fill(&app).gradient.stops, before, "canceling the other edit restores the original four stops"); + assert_eq!(app.session.selected_stop(), Some(1), "the original 40 percent stop is selected again"); +} + +/// A midpoint picked after a Location scrub's stop was lost in a joined preview stays selected when that preview is +/// canceled. +#[test] +fn a_canceled_joined_preview_keeps_a_midpoint_picked_after_the_loss() { + let mut app = lost_in_a_joined_preview(four_stops(), 1, moved_and_recolored()); + app.ui.gradient_panel.mid_selected = Some((0, app.session.gradient_owner())); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), None, "no stop replaces the midpoint selection"); + assert_eq!(selected_mid(&app, fill(&app).gradient.stops.len()), Some(0), "the first midpoint stays selected"); +} + +/// Restoring the stop a lost Location scrub began on, when the joined preview is canceled, is announced. +#[test] +fn a_restored_location_stop_is_announced() { + let mut rig = rig_with_stop(&four_stops(), 1); + rig.app().begin_interaction("Other edit").unwrap(); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut rig.app(), &location_gesture(40.0, &[80.0]), true); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + let mut cancel = EditEvents::new(); + cancel.push(EditEvent::cancel(GestureId::default(), CancelReason::Escape, None)); + apply_location(&mut rig.app(), &cancel, true); + rig.fixture.frame(vec![]); + rig.fixture.advance(0.5).frame(vec![]); + rig.app().session.cancel_interaction().unwrap(); + rig.fixture.frame(vec![]); + assert_eq!(rig.app().session.selected_stop(), Some(1), "the original stop is selected again"); + let message = tl!("Another edit was canceled. The stop is selected again."); + let tree = rig.fixture.tree(); + let announced = + tree.keys().into_iter().any(|key| tree.role_of(key) == Some(craft::ui::contract::Role::STATUS) && tree.name_of(key) == Some(message)); + assert!(announced, "the restored selection is announced"); +} + +/// A Location scrub's stop lost in a joined preview and found by the panel pass is selected again when the owner +/// cancels that preview. +#[test] +fn a_joined_preview_canceled_after_the_panel_lost_its_location_stop_restores_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + assert!(end_lost_location_scrub(&mut app), "the panel pass reports the loss"); + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop is selected again"); +} + +/// Removing a Location gesture that joined another edit's preview keeps the original selection until that preview +/// ends: canceling it keeps the original stop, and committing it selects the moved stop. +#[test] +fn a_removed_location_gesture_in_a_joined_preview_waits_for_its_owner() { + for owner_cancels in [true, false] { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + end_removed_location_scrub(&mut app, &[GestureId::default()]); + assert!(app.session.in_interaction(), "the other edit's preview stays open"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop stays selected while that preview is open"); + if owner_cancels { + app.session.cancel_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(1), "canceling keeps the original 40 percent stop, not its 60 percent neighbor"); + } else { + app.session.commit_interaction().unwrap(); + end_lost_location_scrub(&mut app); + assert_eq!(app.session.selected_stop(), Some(2), "committing selects the moved stop"); + } + } +} + +/// A Location scrub in a joined preview moves the stop the field shows even when another edit left the selected +/// index past the end of the stops. +#[test] +fn a_location_scrub_moves_the_shown_stop_when_the_selected_index_is_out_of_bounds() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 3})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": four_stops()})).unwrap(); + apply_location(&mut app, &location_gesture(100.0, &[20.0]), true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(GestureId::default(), Mixed::Same(Some(100.0)), Some(20.0))); + apply_location(&mut app, &end, true); + let removed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.2, "color": "#000000"}, + {"offset": 0.4, "color": "#808080"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": removed})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(3), "the selected index is past the end of the three stops"); + assert_eq!(shown_stop(&app, &fill(&app).gradient.stops), Some(1), "the field shows the moved black stop"); + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(20.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(50.0))); + apply_location(&mut app, &events, true); + let expected = vec![(0.0, "#ffffff".to_owned()), (40.0, "#808080".to_owned()), (50.0, "#000000".to_owned())]; + assert_eq!(stops_and_selection(&app).0, expected, "the shown black stop moves to 50 percent"); +} + +/// A Location scrub that begins after another edit changed the tracked stop in the same frame moves nothing and +/// leaves the selection to the loss check, rather than moving the neighbor at the selected index. +#[test] +fn a_location_scrub_begun_after_its_tracked_stop_changed_moves_nothing() { + let (mut app, _) = released_into_a_joined_preview(); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": moved_and_recolored()})).unwrap(); + let stops = fill(&app).gradient.stops; + let id = GestureId::new(1); + let mut events = EditEvents::new(); + events.push(EditEvent::begin(id, Mixed::Same(Some(80.0)), "Location".into(), None)); + events.push(EditEvent::update(id, Some(90.0))); + apply_location(&mut app, &events, true); + let mut end = EditEvents::new(); + end.push(EditEvent::commit(id, Mixed::Same(Some(80.0)), Some(90.0))); + apply_location(&mut app, &end, true); + assert_eq!(fill(&app).gradient.stops, stops, "neither the recolored stop nor its #404040 neighbor moves"); + assert_eq!(app.session.selected_stop(), None, "the lost stop is no longer selected"); + assert!(app.session.in_interaction(), "the other edit's preview stays open"); +} + +/// A deferred loss report is dropped when a stop is selected again before the next pass. +#[test] +fn a_deferred_location_loss_is_not_reported_after_a_new_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + app.session.commit_interaction().unwrap(); + end_removed_location_scrub(&mut app, &[GestureId::default()]); + app.run("gradient.selectStop", json!({"index": 2})).unwrap(); + assert!(!end_lost_location_scrub(&mut app), "the next pass does not report a loss"); +} + +/// A canceled Location preview followed by another edit of a neighbor keeps the original stop selected. +#[test] +fn a_canceled_location_preview_then_a_neighbor_edit_keeps_the_original_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0, 80.0]), true); + app.session.cancel_interaction().unwrap(); + let recolored = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#808080"}, + {"offset": 0.6, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.run("paint.editGradient", json!({"stroke": false, "stops": recolored})).unwrap(); + assert!(!end_lost_location_scrub(&mut app), "no loss is reported"); + assert_eq!(app.session.selected_stop(), Some(1), "the original stop stays selected"); +} + +/// A removed Location gesture whose kept preview lost its stop reports the cleared selection in the next pass. +#[test] +fn a_removed_location_gesture_reports_its_lost_stop() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + app.session.commit_interaction().unwrap(); + end_removed_location_scrub(&mut app, &[GestureId::default()]); + assert_eq!(app.session.selected_stop(), None, "no stop is selected"); + assert!(end_lost_location_scrub(&mut app), "the next pass reports the loss"); +} + +/// A held Location scrub writes nothing after another edit ends its preview, even before the panel settles. +#[test] +fn a_location_update_after_another_edit_ends_its_preview_writes_nothing() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[70.0]), true); + app.session.commit_interaction().unwrap(); + let stops = fill(&app).gradient.stops; + let mut more = EditEvents::new(); + more.push(EditEvent::update(GestureId::default(), Some(80.0))); + apply_location(&mut app, &more, true); + assert!(!app.session.in_interaction(), "the update opens no new preview"); + assert_eq!(fill(&app).gradient.stops, stops, "the update does not move the stop"); +} + +/// Losing a Location scrub's stop after another edit commits its preview clears the selection and reports the loss. +#[test] +fn a_location_scrub_whose_committed_preview_lost_its_stop_clears_the_selection() { + let mut app = app(json!({"gradient": {"stops": four_stops()}})); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + apply_location(&mut app, &location_gesture(40.0, &[80.0]), true); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 0.8, "color": "#ff0000"}, + {"offset": 1, "color": "#000000"}, + ]); + app.session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + app.session.commit_interaction().unwrap(); + assert!(end_lost_location_scrub(&mut app), "the loss is reported"); + assert_eq!(app.session.selected_stop(), None, "no stop is selected"); +} + +/// After a Location rollback, the ramp and fields show the selected stop in another edit's preview. +#[test] +fn a_rolled_back_location_scrub_shows_the_same_stop_in_the_ramp_and_fields() { + let mut rig = rig_with_stop(&four_stops(), 1); + apply_location(&mut rig.app(), &location_gesture(40.0, &[70.0, 80.0]), true); + rig.app().session.cancel_interaction().unwrap(); + rig.app().begin_interaction("Other edit").unwrap(); + let changed = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.4, "color": "#ff0000"}, + {"offset": 0.6, "color": "#404040"}, + {"offset": 1, "color": "#000000"}, + ]); + rig.app().session.preview("paint.editGradient", &json!({"stroke": false, "stops": changed})).unwrap(); + let stops = fill(&rig.app()).gradient.stops; + assert_eq!(shown_stop(&rig.app(), &stops), Some(1), "the ramp uses the session's selection before the fields retire stale tracking"); + rig.fixture.frame(vec![]); + assert_eq!(rig.app().session.selected_stop(), Some(1), "the other preview keeps the session's selected stop"); + assert_eq!(rig.number("Location"), Some(40.0), "the fields show the session's selected stop in the other preview"); + let marked = |name: &str| rig.fixture.tree().selected_of(rig.target(name).node) == Some(true); + assert_eq!( + (marked("Color stop 2 of 4"), marked("Color stop 3 of 4")), + (true, false), + "the ramp marks the same stop the fields show in the first frame after rollback" + ); +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored (the field's value times the mirror's sign). #[test]