Merge pull request #10885 from dotCooCoo/fix/gradient-location-scrub-passes-neighbors

Gradient: scrubbing a stop's Location past a neighbor moves only that stop
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-05 23:44:06 -08:00
commit 2ff1a35120
4 files changed
+2327 -26

No files matched your search

+29 -1
View File
@@ -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<Selection>, 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<Selection>) -> 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<Selection>) -> 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;
}
+3 -1
View File
@@ -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);
+551 -24
View File
@@ -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<Color>` (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<Vec<GradientStop>>,
/// 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<LocationScrub>,
/// 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<LocationRestore>,
}
/// 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<LocationInteraction>,
/// 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<GradientStop>,
/// 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<GradientStop>,
/// The whole stop list after the gesture's last write, or when it began.
stops: Vec<GradientStop>,
/// 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<GradientStop>)>,
}
/// 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<Selection>,
started: Weak<Document>,
wrote: Weak<Document>,
}
/// 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<Option<f64>>, 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<f64>, _| {});
}
}
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<usize> {
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<usize> {
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<Option<f64>>, 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<f64>, 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)))
File diff suppressed because it is too large. Load diff