diff --git a/crates/behavior/src/edit_history.rs b/crates/behavior/src/edit_history.rs index c35dfb2dc..222240417 100644 --- a/crates/behavior/src/edit_history.rs +++ b/crates/behavior/src/edit_history.rs @@ -21,8 +21,7 @@ pub enum Step { struct Entry { value: T, name: Arc, - /// The step's weight under the history's budget ([`EditHistory::with_budget`]). - #[allow(dead_code)] // P3(color-w7): co.K40 + /// The weight of `value` under the history's budget ([`EditHistory::with_budget`]). weight: usize, } @@ -41,24 +40,39 @@ pub struct EditHistory { redo: Vec>, /// The value as of the latest step. settled: T, + /// The weight of `settled`; 0 without a budget. + settled_weight: usize, open: Option, /// The most summed weight the undo steps keep, and how a value weighs. - #[allow(dead_code)] // P3(color-w7): co.K40 budget: Option<(usize, fn(&T) -> usize)>, } impl EditHistory { /// A history that starts at `now`. pub fn new(now: &T) -> Self { - EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), open: None, budget: None } + EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), settled_weight: 0, open: None, budget: None } } /// The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always /// stays; each weight is measured once at push. Without a budget nothing changes. #[must_use] - pub fn with_budget(self, max: usize, weight: fn(&T) -> usize) -> Self { - let _ = (max, weight); - todo!("co.K40") + pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self { + self.settled_weight = weight(&self.settled); + self.budget = Some((max, weight)); + self.trim(); + self + } + + /// Drops the oldest undo steps while their summed weight passes the budget; the newest stays. + fn trim(&mut self) { + let Some((max, _)) = self.budget else { return }; + let mut total = self.undo.iter().fold(0usize, |sum, entry| sum.saturating_add(entry.weight)); + let mut gone = 0; + while total > max && gone + 1 < self.undo.len() { + total = total.saturating_sub(self.undo[gone].weight); + gone += 1; + } + self.undo.drain(..gone); } /// Takes in one event. Events of a gesture other than the open one are ignored. @@ -95,8 +109,12 @@ impl EditHistory { if self.undo.len() >= LIMIT { self.undo.remove(0); } - self.undo.push(Entry { value: std::mem::replace(&mut self.settled, after.clone()), name, weight: 0 }); // P3(color-w7): co.K40 + let weight = self.budget.map_or(0, |(_, weigh)| weigh(after)); + let value = std::mem::replace(&mut self.settled, after.clone()); + let weight = std::mem::replace(&mut self.settled_weight, weight); + self.undo.push(Entry { value, name, weight }); self.redo.clear(); + self.trim(); } /// Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. @@ -107,7 +125,8 @@ impl EditHistory { Step::Redo => (&mut self.redo, &mut self.undo), }; let Some(entry) = from.pop() else { return false }; - to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name, weight: entry.weight }); + let weight = std::mem::replace(&mut self.settled_weight, entry.weight); + to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name, weight }); self.settled = entry.value; true } @@ -118,6 +137,7 @@ impl EditHistory { pub fn take_back(&mut self) -> Option { self.open = None; let entry = self.undo.pop()?; + self.settled_weight = entry.weight; self.settled = entry.value.clone(); Some(entry.value) } @@ -165,6 +185,52 @@ mod tests { assert_eq!(now, 0, "the undo takes the step before the one taken back"); } + fn weigh(value: &i32) -> usize { + usize::try_from(*value).unwrap_or(0) + } + + fn undo_weight(history: &EditHistory) -> usize { + history.undo.iter().map(|entry| entry.weight).sum() + } + + #[test] + fn a_weight_budget_drops_the_oldest_steps_and_keeps_the_newest() { + let mut history = EditHistory::new(&0).with_budget(10, weigh); + for (before, after) in [(0, 4), (4, 5), (5, 6)] { + history.record(&set(before, after)); + } + assert_eq!(history.undo.len(), 3, "weights 0, 4 and 5 fit"); + history.record(&set(6, 7)); + assert_eq!(history.undo.len(), 1, "the oldest went until the sum fit, the newest stayed"); + + let mut now = 7; + assert!(history.step(&mut now, Step::Undo)); + assert_eq!(now, 6); + assert!(!history.can_undo()); + assert!(history.step(&mut now, Step::Redo)); + assert_eq!((now, undo_weight(&history)), (7, 6), "the redo gave the step back with its own weight"); + + history.record(&set(7, 9)); + assert_eq!((history.undo.len(), undo_weight(&history)), (1, 7), "6 + 7 passes 10, the oldest went"); + + assert!(history.step(&mut now, Step::Undo)); + history.record(&set(7, 8)); + assert_eq!(history.redo_len(), 0, "a new step after an undo clears redo"); + assert_eq!(undo_weight(&history), 7); + + let mut long = EditHistory::new(&0).with_budget(usize::MAX, |_| 1); + for n in 0..120 { + long.record(&set(n, n + 1)); + } + assert_eq!(long.undo.len(), LIMIT, "the step limit still applies"); + + let mut free = EditHistory::new(&0); + for n in 0..3 { + free.record(&set(n, n + 1)); + } + assert_eq!((free.undo.len(), undo_weight(&free)), (3, 0), "without a budget nothing is trimmed or weighed"); + } + #[test] fn redo_len_counts_the_undone_steps_until_a_new_step() { let mut history = EditHistory::new(&0); diff --git a/crates/color-ui/src/gradient/stops.rs b/crates/color-ui/src/gradient/stops.rs index e75fd7170..bdd6de7d7 100644 --- a/crates/color-ui/src/gradient/stops.rs +++ b/crates/color-ui/src/gradient/stops.rs @@ -81,8 +81,16 @@ impl Default for StopRules { /// The stops with the colours of stops `i` and `j` exchanged (RGB and `tag`; locations, alpha and /// midpoints stay), and the index of the stop `i`; `None` for `i == j` or an index out of range. pub fn swap_colors(stops: &GradientStops, i: usize, j: usize) -> Option<(GradientStops, usize)> { - let _ = (stops, i, j); - todo!("co.K39") + if i == j || i >= stops.color.len() || j >= stops.color.len() { + return None; + } + let (a, b) = (stops.color[i], stops.color[j]); + let mut out = stops.clone(); + out.color[i].color = Srgba { a: a.color.a, ..b.color }; + out.color[i].tag = b.tag; + out.color[j].color = Srgba { a: b.color.a, ..a.color }; + out.color[j].tag = a.tag; + Some((out, i)) } /// One Left or Right press moves a stop or midpoint by this share of the bar or line. diff --git a/crates/color-ui/src/ui/gradient/editor.rs b/crates/color-ui/src/ui/gradient/editor.rs index fc92f3978..6c88bb536 100644 --- a/crates/color-ui/src/ui/gradient/editor.rs +++ b/crates/color-ui/src/ui/gradient/editor.rs @@ -72,7 +72,8 @@ impl

Outcome for GradientEditorOutput

{ /// Pointer: a press on a marker or diamond selects and grabs it without a jump; a drag moves it (stops pass their /// neighbours and the selection follows) and is one gesture. A stop dragged more than the tear-off distance above or /// below the ramp is removed while its row is above the minimum, and comes back on re-entry within the drag. Alt held -/// at the press drags a copy, which can't be torn off. A click on empty space adds a stop there (under `Split`, above +/// at the press drags a copy, which can't be torn off; under `AltDrop::Swap` a colour stop held over another colour +/// stop swaps their colours instead (locations, opacities and midpoints stay). A click on empty space adds a stop there (under `Split`, above /// the ramp's centre an opacity stop) as one Set; a press and drag on empty space does nothing. A double click on a /// colour stop asks for its colour. /// diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index 74b67541d..7dde3ae5f 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -133,7 +133,8 @@ struct Drag { /// Where the press was and the marker's location then, so the marker doesn't jump. press: Pos2, grab: f32, - /// Alt was held at the press: the drag moves a copy of the stop. + /// Alt was held at the press: the drag moves a copy of the stop, or under `AltDrop::Swap` swaps its colours with + /// the colour stop it is held over. copy: bool, } @@ -387,17 +388,23 @@ impl Geometry { } } - /// The colour stop or location a payload dropped at `pos` lands on. - fn drop_place(&self, stops: &GradientStops, pos: Pos2) -> StopDrop { - let near = stops + /// The colour stop other than `except` nearest to `x` and within `hit` of it. + fn nearest_color(&self, stops: &GradientStops, x: f32, except: Option) -> Option { + stops .color .iter() .enumerate() - .map(|(i, s)| (i, (self.x(s.location) - pos.x).abs())) + .filter(|(i, _)| Some(*i) != except) + .map(|(i, s)| (i, (self.x(s.location) - x).abs())) .filter(|(_, d)| *d <= self.hit) - .min_by(|a, b| a.1.total_cmp(&b.1)); - match near { - Some((i, _)) => StopDrop::OnStop(i), + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + } + + /// The colour stop or location a payload dropped at `pos` lands on. + fn drop_place(&self, stops: &GradientStops, pos: Pos2) -> StopDrop { + match self.nearest_color(stops, pos.x, None) { + Some(i) => StopDrop::OnStop(i), None => StopDrop::At(stops::round_location(self.location(pos.x))), } } @@ -482,7 +489,7 @@ impl GradientBar<'_, P> { self.select = Some(marker); } - /// The drag's stops with the marker at the pointer: moved, copied, or torn off. + /// The drag's stops with the marker at the pointer: moved, copied, colour-swapped, or torn off. fn drag_to(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, drag: &Drag, pos: Pos2) { let Drag { marker, ref base, press, grab, copy, .. } = *drag; let to = grab + geo.location(pos.x) - geo.location(press.x); @@ -500,9 +507,14 @@ impl GradientBar<'_, P> { } m => { let (row, i, at) = (m.row(), m.index(), stops::round_location(to)); + // Chosen from the stops at the press, so a pointer that leaves the other stop returns to the copy. + let swap = (moved && copy && row == StopRow::Color && rules.alt_drop == stops::AltDrop::Swap) + .then(|| geo.nearest_color(base, pos.x, Some(i)).and_then(|j| stops::swap_colors(base, i, j))) + .flatten() + .map(|(s, j)| (s, Some(StopRef::stop(row, j)))); // At the row's minimum a stop dragged off the bar stays and moves. let torn = (off && !copy).then(|| stops::remove(base, row, i, rules)).flatten().map(|(s, _)| (s, None)); - let edited = torn.or_else(|| match (moved, copy) { + let edited = swap.or(torn).or_else(|| match (moved, copy) { (false, _) => None, (true, true) => stops::copy(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))), (true, false) => stops::move_to(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))), diff --git a/crates/color-ui/src/ui/gradient/editor/stories.rs b/crates/color-ui/src/ui/gradient/editor/stories.rs index e9aecfe33..ae172c63d 100644 --- a/crates/color-ui/src/ui/gradient/editor/stories.rs +++ b/crates/color-ui/src/ui/gradient/editor/stories.rs @@ -1,6 +1,7 @@ //! Stories of `GradientEditor`. use super::{GradientEditor, GradientEditorOutput}; +use crate::gradient::stops::AltDrop; use crate::ui::gradient::{ColorStop, GradientStops, OpacityStop, StopRef, StopRows, StopRules}; use craft_theme::Srgba; use craft_ui::contract::Bind; @@ -68,6 +69,15 @@ fn gradient_editor_combined(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { hinted(ui, data, output) } +/// An Alt-drag of a colour stop onto another swaps their colours. +#[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never, title = "Alt-drop swaps")] +fn gradient_editor_alt_drop_swap(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let stops = data.value("stops", combined()); + let rules = StopRules::new(StopRows::Combined).alt_drop(AltDrop::Swap); + let output = GradientEditor::new("Gradient", Bind::bound(stops)).rules(rules).show(ui); + hinted(ui, data, output) +} + #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never)] fn gradient_editor_color_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let stops = data.value("stops", GradientStops::new(vec![color(0.0, [0.0, 0.0, 0.0]), color(1.0, [1.0, 1.0, 1.0])])); diff --git a/crates/color-ui/tests/it/gradient_bar.rs b/crates/color-ui/tests/it/gradient_bar.rs index e51c3cd76..e8f0bceb0 100644 --- a/crates/color-ui/tests/it/gradient_bar.rs +++ b/crates/color-ui/tests/it/gradient_bar.rs @@ -5,12 +5,12 @@ use std::cell::RefCell; use std::rc::Rc; use craft_behavior::EditEvent; -use craft_color_ui::ui::gradient::stops::{StopRules, sample}; +use craft_color_ui::ui::gradient::stops::{AltDrop, StopRules, sample}; use craft_color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, OpacityStop, StopDrop, StopRef, StopRows}; use craft_theme::Srgba; use craft_ui::contract::Bind; use craft_ui::testing::{Fixture, trial}; -use egui::{Color32, Event, Shape, TextureId, Vec2, vec2}; +use egui::{Color32, Event, Modifiers, Shape, TextureId, Vec2, vec2}; const RED: Srgba = Srgba::rgb(1.0, 0.0, 0.0); const BLUE: Srgba = Srgba::rgb(0.0, 0.0, 1.0); @@ -126,6 +126,38 @@ fn a_drag_past_a_neighbour_is_one_gesture_and_the_selection_follows_the_stop() { assert!(matches!(events.last(), Some(&"commit") | Some(&"set")), "{events:?}"); } +#[trial] +fn an_alt_drag_released_on_another_stop_swaps_their_colours_and_keeps_their_places() { + // Alt-drags the first stop of `three()` (the first one half transparent) to `share` of the way to the last. + let alt_drag = |rules: StopRules, share: f32| { + let mut start = three(); + start.color[0].color.a = 0.5; + let mut rig = rig(start, rules, false); + let (from, last) = (rig.marker("Color stop 1 of 3").center(), rig.marker("Color stop 3 of 3").center()); + rig.fixture.hold(Modifiers::ALT); + rig.seen.borrow_mut().events.clear(); + rig.fixture.drag_at(from, vec2((last.x - from.x) * share, 0.0)); + rig.fixture.hold(Modifiers::NONE); + rig.fixture.idle(2); + rig + }; + let swap = StopRules::new(StopRows::Combined).alt_drop(AltDrop::Swap); + + let rig = alt_drag(swap.clone(), 1.0); + let stops = rig.stops.borrow().clone(); + assert_eq!(rig.tags(), [3, 2, 1], "the tags went with the colours"); + assert_eq!(stops.color[0].color, Srgba { a: 0.5, ..BLUE }, "the first stop took the blue and kept its alpha"); + assert_eq!(stops.color[2].color, RED, "the last stop took the red and kept its alpha"); + assert_eq!(stops.color.iter().map(|s| s.location).collect::>(), [0.0, 0.5, 1.0], "the places stay"); + assert_eq!(rig.seen.borrow().selected, Some(StopRef::Color(0)), "the selection stays on the dragged stop"); + let events = rig.seen.borrow().events.clone(); + assert_eq!(events.iter().filter(|e| **e == "begin").count(), 1, "one step: {events:?}"); + + // Between stops it copies, and so does the default rule onto a stop. + assert_eq!(alt_drag(swap, 0.25).tags(), [1, 1, 2, 3], "released between stops it copies"); + assert_eq!(alt_drag(StopRules::new(StopRows::Combined), 1.0).tags(), [1, 2, 3, 1], "under Copy it copies onto the stop"); +} + /// Three colour stops (tags 1..=3) and three opacity stops (tags 11..=13). fn three_and_three() -> GradientStops { GradientStops::with_opacity(