diff --git a/crates/imaging/src/layer_style/model.rs b/crates/imaging/src/layer_style/model.rs index 91cc773ed..d55db2c53 100644 --- a/crates/imaging/src/layer_style/model.rs +++ b/crates/imaging/src/layer_style/model.rs @@ -222,36 +222,6 @@ impl BlendIfRange { } BlendIfRange(q) } - - /// Handle `handle` (0..4) moved to `to`. `split` (Alt held): only that half moves. Otherwise - /// the pair (0 and 1, or 2 and 3) moves by the same amount, keeping its spread, each half - /// clamped to 0..=255. Then the order is restored by pushing: handles before `handle` are - /// lowered to at most its value, handles after it raised to at least it, and each value - /// raised to at least the one before. - // pc: crates/ui-egui/src/dialogs/layer_style.rs:1399-1430 (the drag in `blend_if_bar`). - pub fn moved(self, handle: usize, to: u8, split: bool) -> BlendIfRange { - let Some(¤t) = self.0.get(handle) else { - return self; - }; - let mut n = self.0; - if split { - n[handle] = to; - } else { - let delta = i16::from(to) - i16::from(current); - let pair = if handle < 2 { 0 } else { 2 }; - for v in &mut n[pair..pair + 2] { - *v = u8::try_from((i16::from(*v) + delta).clamp(0, 255)).unwrap_or(*v); - } - } - for i in 0..4 { - if i < handle { - n[i] = n[i].min(n[handle]); - } else if i > handle { - n[i] = n[i].max(n[handle]); - } - } - BlendIfRange::ordered(n) - } } /// The Blend If ranges of one channel entry. diff --git a/crates/imaging/src/layer_style/tests.rs b/crates/imaging/src/layer_style/tests.rs index 1d22168b6..2add64e1a 100644 --- a/crates/imaging/src/layer_style/tests.rs +++ b/crates/imaging/src/layer_style/tests.rs @@ -76,23 +76,10 @@ fn shadow_drag_uses_whole_degrees_and_pixels_and_moves_the_global_angle() { // The blend defaults of a spec become the host's keys; unknown names stay. Bevel & Emboss has two // Blend fields: only the one defaulting to Multiply is renamed. -// `BlendIfRange::ordered` and `moved` always give black low ≤ black high ≤ white low ≤ white -// high, pushing the other handles. +// `BlendIfRange::ordered` raises each value to at least the one before it. #[trial] -fn blend_if_edits_keep_the_four_values_ordered() { +fn blend_if_ranges_read_ordered() { assert_eq!(BlendIfRange::ordered([10, 5, 200, 100]), BlendIfRange([10, 10, 200, 200])); - let start = BlendIfRange([10, 30, 200, 220]); - for handle in 0..4 { - for to in (0..=255u8).step_by(5) { - for split in [false, true] { - let r = start.moved(handle, to, split).0; - assert!(r.windows(2).all(|w| w[0] <= w[1]), "{handle} {to} {split}: {r:?}"); - } - } - } - // A split move past a neighbour pushes it. - assert_eq!(start.moved(1, 210, true), BlendIfRange([10, 210, 210, 220])); - assert_eq!(start.moved(9, 0, false), start); } // A `StyleValue::Other` key no field shows survives `set_param`, `toggle` and diff --git a/crates/imaging/src/ui/adjust/hue_saturation.rs b/crates/imaging/src/ui/adjust/hue_saturation.rs index 1299016b9..2a31c51f1 100644 --- a/crates/imaging/src/ui/adjust/hue_saturation.rs +++ b/crates/imaging/src/ui/adjust/hue_saturation.rs @@ -13,7 +13,7 @@ use craft_ui::form::Field; use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, Label, UnitKind}; use craft_ui::style::{DataColor, TypeRole}; -use craft_ui::value_drag::{Anchor, Thumb, ThumbRow, TrackFace}; +use craft_ui::value_drag::{Anchor, OffThumbs, SpanInk, Thumb, ThumbRow, ThumbSpan, TrackFace}; use egui::{Color32, Ui}; use super::sliders::{Run, editor_group, lifted, read, words}; @@ -35,6 +35,8 @@ const COLORIZE_SATURATION: f64 = 25.0; const TURN: f64 = 360.0; /// The most a range spans: the end thumb is at most this far past the start. const MAX_SPAN: f64 = 359.0; +/// The bands under a range's thumbs: the whole range faint, its full-strength part muted. +const RANGE_SPANS: [ThumbSpan; 2] = [ThumbSpan::new(0, 3, SpanInk::Faint), ThumbSpan::new(1, 2, SpanInk::Muted)]; /// One of Hue/Saturation's six colour ranges (Reds, Yellows, Greens, Cyans, Blues, Magentas). #[derive(Clone, Copy, Debug, PartialEq)] @@ -251,8 +253,9 @@ impl std::ops::Deref for HueSaturationOutput { /// [`adjusted_spectrum`](Self::adjusted_spectrum) below (the same 37 hues after the adjustment; the input bar again /// without it). Not mirrored in right-to-left layouts: they are scales of the image. /// - **Range thumbs** (a range shown): four thumbs under the lower bar as one thumb row that wraps through 0° and keeps -/// its order going round from the first thumb. A drag moves a thumb with [`HueRangeValue::move_bound`], whole -/// degrees. Under the bars a readout "a° / b° · c° \ d°", each bound within one turn. +/// its order going round from the first thumb, over a faint band from the first thumb to the last and a muted one +/// between the middle two. A drag on a thumb moves it with [`HueRangeValue::move_bound`], whole degrees; a press +/// off the thumbs does nothing. The row is not mirrored either. Under the bars a readout "a° / b° · c° \ d°", each bound within one turn. #[must_use = "show the editor with `show`"] #[derive(Pattern)] pub struct HueSaturationEditor<'a> { @@ -377,8 +380,11 @@ impl<'a> HueSaturationEditor<'a> { .step(1.0) .anchor(Anchor::new(0, MAX_SPAN)) .thumbs(thumbs) + .off_thumbs(OffThumbs::Ignore) + .spans(&RANGE_SPANS) .track_face(TrackFace::new(ToneRamp::new(&after))) .label(words.spectrum_after.clone()) + .ltr_axis() .show(ui) .edit; run.push(cx, row, move |now: &HueSaturation, row: &[Mixed; 4]| now.with_thumbs(r, row)); diff --git a/crates/imaging/src/ui/layer_style/blend_if/mod.rs b/crates/imaging/src/ui/layer_style/blend_if/mod.rs index 0b83cc6f8..0ea55c985 100644 --- a/crates/imaging/src/ui/layer_style/blend_if/mod.rs +++ b/crates/imaging/src/ui/layer_style/blend_if/mod.rs @@ -10,7 +10,7 @@ use craft_ui::layout::RowAlign; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::style::{DataColor, TypeRole}; -use craft_ui::value_drag::{Neighbours, Order, Thumb, ThumbRow, TrackFace}; +use craft_ui::value_drag::{Neighbours, OffThumbs, Order, Thumb, ThumbRow, TrackFace}; use egui::{Color32, Ui}; use crate::layer_style::BlendIfRange; @@ -61,11 +61,14 @@ impl BlendIfRange { /// A Blend If slider: a black-to-white ramp with a black and a white handle under it, each split into two halves by /// Alt (the layer fades between them). A split pair shows two half triangles; a pair whose halves coincide, one whole /// triangle. The readout ("0 / 20 255": a split side as "low / high") sits above the bar at the trailing end. The -/// bar mirrors with the row, like every thumb row. +/// bar never mirrors: it is a tone scale. /// -/// - Pointer: a press picks the nearest handle; a drag moves its pair, keeping the spread, or with Alt the half alone. -/// A handle pushes the handles it runs into along, so the order holds. One gesture per drag; Esc cancels. -/// - Keys: the four handles are Tab stops in order. Arrows, Page keys, Home, End and the wheel move one half. +/// - Pointer: a press picks the nearest handle, and on a triangle of coinciding halves the half on its side of the +/// tip. A drag moves the handle's pair to the pointer, keeping the spread; while Alt is held, the half alone. A +/// handle pushes the handles it runs into along, so the order holds. One gesture per drag; Esc cancels. A tap +/// focuses the nearest handle and moves nothing. +/// - Keys: the four handles are Tab stops in order. Arrows, Page keys, Home, End and the wheel move the focused +/// handle's pair, Shift by ten levels; with Alt the focused half alone. /// - AccessKit: each handle is a slider named by [`BlendIfWords::handle`] ("Black low, This Layer"). #[must_use = "show the bar with `show`"] #[derive(craft_ui::contract::Pattern)] @@ -120,8 +123,10 @@ impl<'a> BlendIfBar<'a> { .step(1.0) .thumbs(thumbs) .neighbours(Neighbours::Push) + .off_thumbs(OffThumbs::Nearest) .track_face(TrackFace::new(ToneRamp::new(&ramp))) .label(label.clone()) + .ltr_axis() .show(ui) .edit .map(|row| BlendIfRange::of_row(&row)); diff --git a/crates/ui-widgets/src/value_drag/mod.rs b/crates/ui-widgets/src/value_drag/mod.rs index 7fd87dd14..30cb3c902 100644 --- a/crates/ui-widgets/src/value_drag/mod.rs +++ b/crates/ui-widgets/src/value_drag/mod.rs @@ -12,6 +12,9 @@ pub use angle_dial::{AngleDial, AngleDialStyle, AngleOrientation}; pub use point_picker::{Backdrop, PointPicker, PointPickerStyle, PointPickerWords}; pub use range_slider::{RangeSlider, RangeSliderStyle}; pub use slider::{Slider, SliderStyle, SliderThumb}; -pub use thumb_row::{Anchor, Follow, Neighbours, Order, RowOp, RowRules, Thumb, ThumbHold, ThumbOp, ThumbRow, ThumbRowOutput, ThumbRowStyle}; +pub use thumb_row::{ + Anchor, Follow, Neighbours, OffThumbs, Order, RowOp, RowRules, SpanInk, Thumb, ThumbHold, ThumbOp, ThumbRow, ThumbRowOutput, ThumbRowStyle, + ThumbSpan, +}; pub use track::{SliderScale, TrackFace}; pub use words::ValueDragWords; diff --git a/crates/ui-widgets/src/value_drag/thumb_row.rs b/crates/ui-widgets/src/value_drag/thumb_row.rs index 9ba28cc6c..3d531f285 100644 --- a/crates/ui-widgets/src/value_drag/thumb_row.rs +++ b/crates/ui-widgets/src/value_drag/thumb_row.rs @@ -2,10 +2,11 @@ //! editor do. One leaf with a focusable thumb part per value. A press on a thumb grabs it and a drag moves it by the //! pointer's travel; a press elsewhere on the row jumps the nearest thumb there; arrows, the wheel and AccessKit step //! the focused thumb. Each value is mixed or not on its own. The row's rules (order, wrap, split halves) are -//! `RowRules`. +//! `RowRules`; what a press off the thumbs does is the row's [`OffThumbs`]. //! -//! Alt keeps the meaning it has in Photoshop's levels: a drag that begins with Alt held moves one half of a split -//! thumb alone, at full rate. On a thumb that is not split, Alt scales a drag finer as on every value control. +//! Alt keeps the meaning it has in Photoshop's Blend If: on a split thumb it moves one half alone, at full rate on a +//! drag (from the moment it is held) and by the plain step on a key or the wheel; without it the pair moves together. +//! On a thumb that is not split, Alt scales a move finer as on every value control. use super::track::{self, Pick, Press, Scale, SliderScale, ThumbRing, TrackFace, Travel, travel}; use super::words::ValueDragWords; @@ -25,7 +26,7 @@ use craft_behavior::{ }; use craft_keymap::Mods; use craft_theme::{Rgba, Stateful, States}; -use egui::{Pos2, Rangef, Rect, Vec2, pos2}; +use egui::{CornerRadius, Pos2, Rangef, Rect, Vec2, pos2}; use std::ops::RangeInclusive; #[cfg(feature = "testing")] @@ -56,6 +57,12 @@ pub struct ThumbRowStyle { track: TrackLook, /// The length a row asks for along its axis. length: f32, + /// The ink of a [`SpanInk::Faint`] span. + span_faint: StyleColor, + /// The ink of a [`SpanInk::Muted`] span. + span_muted: StyleColor, + /// The thickness of a span. + span: f32, } /// How a thumb's value is kept among the row's other values. @@ -95,6 +102,49 @@ pub enum Neighbours { Push, } +/// What a press off the thumbs does: one beyond the reach of every thumb. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum OffThumbs { + /// The nearest thumb jumps to the pointer, on a tap and on a drag: a levels row. + #[default] + Jump, + /// A drag takes the nearest thumb to the pointer; a tap only focuses it: a Blend If bar. + Nearest, + /// Nothing: only a press on a thumb moves one. The range thumbs of a hue editor. + Ignore, +} + +/// The ink of a [`ThumbSpan`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SpanInk { + /// The theme's faint text colour. + Faint, + /// The theme's muted text colour. + Muted, +} + +/// A band along the row from one thumb to another, under the thumbs' tips: the extent of a hue range and of its +/// full-strength part. In a wrapping row it runs forward from `from` round to `to`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct ThumbSpan { + /// The thumb the span starts at. + pub from: usize, + /// The thumb the span ends at. + pub to: usize, + /// Its ink. + pub ink: SpanInk, +} + +impl ThumbSpan { + /// A span from thumb `from` to thumb `to` in `ink`. + pub const fn new(from: usize, to: usize, ink: SpanInk) -> Self { + ThumbSpan { from, to, ink } + } +} + /// Where a thumb sits that a function of the row's values places (a levels gamma thumb, between the black and the /// white one). Both functions get the row's values as drawn. #[derive(Clone, Copy, Debug)] @@ -191,9 +241,11 @@ impl Thumb { /// drawn as the left half of a triangle; the next one only brings its own face, range and order. The pair's /// values `[low, high]` sit in consecutive entries with `low <= high`. /// - /// A press that begins without Alt moves the pair together, keeping the spread; with Alt it moves only the half - /// it grabs, at full rate (Alt is not the fine scale on that drag). Where the halves coincide they draw as one triangle. Keys, the wheel and AccessKit move one half. A - /// row does not combine a split thumb with wrapping. + /// A drag, a key, the wheel and an AccessKit change of either half move the pair together, keeping the spread. + /// While Alt is held a drag moves only the half it grabs, at full rate, and a key or the wheel moves the focused + /// half alone by the plain step: Alt is not the fine scale on a split thumb. Where the halves coincide they draw + /// as one triangle, and a press takes the half on its side of the tip. A row does not combine a split thumb with + /// wrapping. #[must_use] pub fn split(mut self) -> Self { self.split = true; @@ -313,6 +365,11 @@ impl RowRules<'_, N> { /// Where thumb `i` may go among the thumbs it is ordered with, which are at `values`. In a wrapping row the /// bounds are measured the short way round from the thumb's own value, and open where it has no neighbour. fn order_bounds(&self, values: &[f64; N], i: usize) -> (f64, f64) { + self.order_bounds_besides(values, i, None) + } + + /// [`order_bounds`](Self::order_bounds), with thumb `except` not counted: it moves with thumb `i`. + fn order_bounds_besides(&self, values: &[f64; N], i: usize, except: Option) -> (f64, f64) { if let Some(anchor) = self.anchored { return self.anchored_bounds(values, i, anchor); } @@ -324,7 +381,7 @@ impl RowRules<'_, N> { } let Order::Between { below, above, gap } = self.thumbs[i].order else { return open }; let side = |j: Option, gap: f64, end: f64| { - j.and_then(|j| values.get(j)).map_or(end, |v| { + j.filter(|j| Some(*j) != except).and_then(|j| values.get(j)).map_or(end, |v| { if self.wrap.is_some() { values[i] + self.short(v - values[i]) + gap } else { (v + gap).clamp(scale.min, scale.max) } }) }; @@ -461,10 +518,49 @@ impl RowRules<'_, N> { (lo, hi) } - /// The bounds AccessKit reports for thumb `i`: the range of a wrapping row, else [`bounds`](Self::bounds). + /// Where thumb `i` may go when its split partner `j` moves with it, keeping the spread: within its own bounds + /// among the other thumbs while the partner stays within its own. + fn pair_bounds(&self, values: &[f64; N], i: usize, j: usize) -> (f64, f64) { + let (lo_i, hi_i) = self.order_bounds_besides(values, i, Some(j)); + let (lo_j, hi_j) = self.order_bounds_besides(values, j, Some(i)); + let hi = (hi_i - values[i]).min(hi_j - values[j]); + let lo = (lo_i - values[i]).max(lo_j - values[j]).min(hi); + (values[i] + lo, values[i] + hi) + } + + /// The split partner a move of thumb `i` takes along: none when the thumb is not split or moves `alone`. + fn taken_along(&self, i: usize, alone: bool) -> Option { + self.partner(i).filter(|_| !alone) + } + + /// Where a move of thumb `i` may take it: with its partner, if it takes one, or else alone among the others. + fn move_bounds(&self, values: &[f64; N], i: usize, alone: bool) -> (f64, f64) { + match self.taken_along(i, alone) { + Some(j) => self.pair_bounds(values, i, j), + None => self.bounds(values, i), + } + } + + /// `row`, whose values are drawn at `values`, with thumb `i` moved to `to_i`, a value settled within its + /// [`move_bounds`](Self::move_bounds): a split half takes its partner along by the same amount unless it moves + /// `alone`, and the thumbs they run into are pushed along. + fn moved_to(&self, row: &[Mixed; N], values: &[f64; N], i: usize, to_i: f64, alone: bool) -> [Mixed; N] { + let mut to = *values; + to[i] = to_i; + match self.taken_along(i, alone) { + Some(j) => { + to[j] = values[j] + (to[i] - values[i]); + self.with_moved(row, to, &[i, j]) + } + None => self.with_moved(row, to, &[i]), + } + } + + /// The bounds AccessKit reports for thumb `i`: the range of a wrapping row, else where a change of its value may + /// take it (a split half with its partner). fn reported_bounds(&self, values: &[f64; N], i: usize) -> (f64, f64) { let scale = self.scale_of(i); - if self.wrap.is_some() { (scale.min, scale.max) } else { self.bounds(values, i) } + if self.wrap.is_some() { (scale.min, scale.max) } else { self.move_bounds(values, i, false) } } /// `value` for thumb `i`: within `bounds` and on its stops; in a wrapping row, then wrapped. @@ -479,13 +575,25 @@ impl RowRules<'_, N> { /// `row` with `op` applied to its thumb: from where the thumb is drawn (an unset or mixed thumb steps from where /// it sits), on its stops and within its bounds among the others, so the order and the gap hold. The thumb takes - /// a number; the other thumbs keep `row`'s values, mixed or not. + /// a number; the other thumbs keep `row`'s values, mixed or not. On a half of a split thumb the op moves the pair, + /// keeping the spread; a move with the fine flag (Alt) or a wheel event with Alt moves the half alone, by the + /// plain step. pub fn apply(&self, op: &RowOp, row: &[Mixed; N]) -> [Mixed; N] { let values = self.placed(row); let i = op.thumb; - let mut to = values; - to[i] = if self.wrap.is_some() { self.apply_wrapped(&op.op, &values, i) } else { self.apply_plain(&op.op, &values, i) }; - self.with_moved(row, to, &[i]) + let (op, alone) = match (self.partner(i), op.op) { + (None, op) => (op, false), + (Some(_), ThumbOp::Move(mv, mods)) => (ThumbOp::Move(mv, mods.fine(false)), mods.fine), + (Some(_), ThumbOp::Wheel(wheel, rtl)) => { + let mut plain = wheel; + plain.mods.alt = false; + (ThumbOp::Wheel(plain, rtl), wheel.mods.alt) + } + (Some(_), op @ ThumbOp::Set(_)) => (op, false), + }; + let bounds = self.move_bounds(&values, i, alone); + let to = if self.wrap.is_some() { self.apply_wrapped(&op, &values, i, bounds) } else { self.apply_plain(&op, &values, i, bounds) }; + self.moved_to(row, &values, i, to, alone) } /// What `op` does to the step maths: a move or a wheel event gives the new value from `steps`. @@ -497,9 +605,9 @@ impl RowRules<'_, N> { } } - fn apply_plain(&self, op: &ThumbOp, values: &[f64; N], i: usize) -> f64 { + /// The value `op` gives thumb `i`, which may go within `bounds`. + fn apply_plain(&self, op: &ThumbOp, values: &[f64; N], i: usize, bounds: (f64, f64)) -> f64 { let scale = self.scale_of(i); - let bounds = self.bounds(values, i); let small = scale.small(); let steps = ValueSteps::new(values[i], bounds.0, bounds.1, small, small * LARGE_STEPS); match Self::stepped(op, &steps) { @@ -511,9 +619,8 @@ impl RowRules<'_, N> { /// [`apply_plain`](Self::apply_plain) for a wrapping row: a step goes on past the range's end and comes back at /// its start, and Home and End go to the neighbours, or the range's start and its end less a step where there /// are none. - fn apply_wrapped(&self, op: &ThumbOp, values: &[f64; N], i: usize) -> f64 { + fn apply_wrapped(&self, op: &ThumbOp, values: &[f64; N], i: usize, bounds: (f64, f64)) -> f64 { let scale = self.scale_of(i); - let bounds = self.bounds(values, i); let from = if self.anchored.is_some() { self.aim(values, i, values[i]) } else { values[i] }; let target = match op { ThumbOp::Set(value) => self.aim(values, i, *value), @@ -542,10 +649,11 @@ struct Layout<'r, const N: usize> { pick: Pick, /// The press moves only the half of a split thumb it grabs. alone: bool, + off: OffThumbs, } impl<'r, const N: usize> Layout<'r, N> { - fn new(rules: RowRules<'r, N>, rect: Rect, thumb: Vec2, rtl: bool, reach: f32, alone: bool) -> Self { + fn new(rules: RowRules<'r, N>, rect: Rect, thumb: Vec2, rtl: bool, reach: f32, alone: bool, off: OffThumbs) -> Self { let travel = travel(rect, thumb.x); let (left, right) = (travel.min, travel.max); // A wrapping row's period in points; 0 when the row does not wrap. @@ -553,7 +661,7 @@ impl<'r, const N: usize> Layout<'r, N> { Some(period) if rules.scale.span() > 0.0 => ((right - left) as f64 * period / rules.scale.span()) as f32, _ => 0.0, }; - Layout { rules, left, right, rtl, pick: Pick { reach, overlap: thumb.x, period, span: false }, alone } + Layout { rules, left, right, rtl, pick: Pick { reach, overlap: thumb.x, period, span: false }, alone, off } } fn x_of(&self, value: f64) -> f32 { @@ -570,9 +678,49 @@ impl<'r, const N: usize> Layout<'r, N> { std::array::from_fn(|i| self.x_of(self.at(values, i))) } - /// What a press at `x` moves, with the thumbs at `values`. + /// What a press at `x` moves, with the thumbs at `values`: none off the thumbs in a row that ignores such a + /// press. fn press(&self, values: &[f64; N], x: f32) -> Option { - self.pick.press(&self.xs(values), x) + let xs = self.xs(values); + let press = self.side_of_tip(self.pick.press(&xs, x)?, &xs, x); + match (press, self.off) { + (Press::Jump(_), OffThumbs::Ignore) => None, + _ => Some(press), + } + } + + /// `press` on a split thumb whose halves coincide, drawn as one triangle at `xs`, as a press on the half on the + /// side of the tip where `x` is: the low half toward the lower values. Other presses are as they are. + fn side_of_tip(&self, press: Press, xs: &[f32; N], x: f32) -> Press { + let pair = match press { + Press::Either { first, last } => Some((first, last)), + Press::Grab(i) | Press::Jump(i) => self.rules.partner(i).map(|j| (i.min(j), i.max(j))), + Press::Span => None, + }; + let Some((low, high)) = pair.filter(|&(low, high)| self.rules.partner(low) == Some(high) && xs[low] == xs[high]) else { + return press; + }; + let toward_low = if self.rtl { x > xs[low] } else { x <= xs[low] }; + let half = if toward_low { low } else { high }; + if let Press::Jump(_) = press { Press::Jump(half) } else { Press::Grab(half) } + } + + /// The pieces of `span` along the row, as x ranges: between its thumbs, and in a wrapping row forward from the + /// first round to the second, in two pieces when that passes the end of the range. + fn span_xs(&self, values: &[f64; N], span: &ThumbSpan) -> Vec<(f32, f32)> { + if span.from >= N || span.to >= N { + return Vec::new(); + } + let (a, b) = (self.at(values, span.from), self.at(values, span.to)); + let scale = &self.rules.scale; + let pieces = if self.rules.wrap.is_some() && b < a { vec![(a, scale.max), (scale.min, b)] } else { vec![(a.min(b), a.max(b))] }; + pieces + .into_iter() + .map(|(lo, hi)| { + let (x, y) = (self.x_of(lo), self.x_of(hi)); + (x.min(y), x.max(y)) + }) + .collect() } /// The values with `press` dragged to the position `state` holds: the moved thumb from where it was at `anchor` @@ -592,7 +740,6 @@ impl<'r, const N: usize> Layout<'r, N> { let from = rules.placed(anchor); let placed_at = if rules.anchored.is_some() { rules.aim(&from, i, self.at(&from, i)) } else { self.at(&from, i) }; let travel = Travel { track: self.left..self.right, units: rules.scale.min..=rules.scale.max, rtl: self.rtl }; - let half = rules.partner(i).filter(|_| !self.alone); // Alt moves one half of a split thumb alone: that drag is not scaled finer. let fine = !click && !rules.thumbs[i].alt_reports && !(self.alone && rules.partner(i).is_some()); let Some(at) = travel.value(press, placed_at, state, fine) else { return out }; @@ -605,20 +752,8 @@ impl<'r, const N: usize> Layout<'r, N> { } else { from[i] + rules.short(value - from[i]) }; - if let Some(j) = half { - let (lo_i, hi_i) = rules.order_bounds(&from, i); - let (lo_j, hi_j) = rules.order_bounds(&from, j); - let (lo, hi) = ((lo_i - from[i]).max(lo_j - from[j]), (hi_i - from[i]).min(hi_j - from[j])); - let lo = lo.min(hi); - let moved = rules.scale_of(i).snap(from[i] + (value - from[i]).clamp(lo, hi)).clamp(from[i] + lo, from[i] + hi); - let mut to = from; - to[i] = moved; - to[j] = from[j] + (moved - from[i]); - return rules.with_moved(anchor, to, &[i, j]); - } - let mut to = from; - to[i] = rules.settle(i, value, rules.bounds(&from, i)); - rules.with_moved(anchor, to, &[i]) + let to = rules.settle(i, value, rules.move_bounds(&from, i, self.alone)); + rules.moved_to(anchor, &from, i, to, self.alone) } } @@ -646,12 +781,11 @@ fn triangle(tip: Pos2, size: Vec2, half: Option, rtl: bool) -> Vec { vec![tip, pos2(right, tip.y + size.y), pos2(left, tip.y + size.y)] } -/// The values of the running drag when it began, the press it resolved to, and whether it moves a half alone. +/// The values of the running drag when it began and the press it resolved to. #[derive(Clone, Default)] struct Held { anchor: Vec>, press: Option, - alone: bool, /// The thumb the pointer moves now, and the modifiers held in the latest pass of the drag. thumb: Option, mods: Mods, @@ -736,6 +870,12 @@ pub struct ThumbRow<'a, const N: usize> { /// What a thumb does when a move takes it into a thumb it is ordered with: stop (the default) or push it along. #[prop] neighbours: Neighbours, + /// What a press off the thumbs does: the nearest thumb jumps there (the default), only takes a drag, or nothing. + #[prop] + off_thumbs: OffThumbs, + /// Bands along the row between thumbs, under their tips; none by default. + #[prop] + spans: &'a [ThumbSpan], /// Paints a groove above the thumbs with `face`, a component shown as the look of the track (a colour gradient); /// the thumbs point up at it. #[prop] @@ -773,6 +913,8 @@ impl<'a, const N: usize> ThumbRow<'a, N> { wrap: false, anchor: None, neighbours: Neighbours::Stop, + off_thumbs: OffThumbs::Jump, + spans: &[], track_face: None, } } @@ -817,6 +959,9 @@ impl Component for ThumbRow<'_, N> { thumb: Vec2::new(cx.tokens.size.marker.width, cx.tokens.size.marker.height), track: TrackLook { thickness: cx.tokens.size.ramp.bar, ..cx.track() }, length, + span_faint: cx.color(colors.text.faint), + span_muted: cx.color(colors.text.muted), + span: cx.tokens.size.ramp.groove, } } @@ -848,7 +993,7 @@ impl Component for ThumbRow<'_, N> { let row = cx.value().cloned().unwrap_or_else(all_mixed); let shown = rules.placed(&row); let size = cx.style.thumb; - let layout = Layout::new(rules, rect, size, cx.flow.is_rtl(), 0.0, false); + let layout = Layout::new(rules, rect, size, cx.flow.is_rtl(), 0.0, false, self.off_thumbs); let xs = layout.xs(&shown); let groove = self.track_face.is_some().then_some(cx.style.track.thickness); let thumbs = band(rect, groove); @@ -882,7 +1027,7 @@ impl Component for ThumbRow<'_, N> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let rules = self.rules(); - let (rect, rtl, reach) = (cx.rect, cx.flow.is_rtl(), cx.style.hit); + let (rect, rtl, reach, off) = (cx.rect, cx.flow.is_rtl(), cx.style.hit, self.off_thumbs); let size = cx.style.thumb; let row = cx.value().cloned().unwrap_or_else(all_mixed); let parts: Vec = std::iter::once(PartRef::from(ROW)).chain((0..N).map(|i| Thumb::PART.at(i as u64))).collect(); @@ -890,10 +1035,11 @@ impl Component for ThumbRow<'_, N> { let press = cx.part(part).press; match press.phase { PressPhase::DragStart { start, pos, .. } => { - let layout = Layout::new(rules, rect, size, rtl, reach, press.mods.alt); + // Alt moves a half of a split thumb alone while it is held, from the values the drag began at. + let layout = Layout::new(rules, rect, size, rtl, reach, press.mods.alt, off); if let Some(picked) = layout.press(&rules.placed(&row), start.origin.x) { let thumb = picked.thumb(start.origin.x, pos.x); - *cx.memory::() = Held { anchor: row.to_vec(), press: Some(picked), alone: press.mods.alt, thumb, mods: press.mods }; + *cx.memory::() = Held { anchor: row.to_vec(), press: Some(picked), thumb, mods: press.mods }; if let Some(thumb) = thumb { cx.focus_part(Thumb::PART.at(thumb as u64)); } @@ -909,7 +1055,7 @@ impl Component for ThumbRow<'_, N> { now.mods = press.mods; } if let (Some(picked), Ok(anchor)) = (held.press, <[Mixed; N]>::try_from(held.anchor)) { - let layout = Layout::new(rules, rect, size, rtl, reach, held.alone); + let layout = Layout::new(rules, rect, size, rtl, reach, press.mods.alt, off); cx.propose(layout.moved(&anchor, picked, &press, false)); } } @@ -917,18 +1063,20 @@ impl Component for ThumbRow<'_, N> { if cx.gesture().is_some() { let held = cx.memory::().clone(); if let (Some(picked), Ok(anchor)) = (held.press, <[Mixed; N]>::try_from(held.anchor)) { - let layout = Layout::new(rules, rect, size, rtl, reach, held.alone); + let layout = Layout::new(rules, rect, size, rtl, reach, press.mods.alt, off); cx.propose(layout.moved(&anchor, picked, &press, false)); } cx.commit(); } else if click && start.clicks < 2 { - // A tap off the thumbs moves the nearest one there; a tap on a thumb moves none. A second - // click is the reset, which the pipeline applies. - let layout = Layout::new(rules, rect, size, rtl, reach, false); - if let Some(picked @ Press::Jump(thumb)) = layout.press(&rules.placed(&row), start.origin.x) - && let Some(&target) = layout.moved(&row, picked, &press, true)[thumb].same() - { - cx.set(rules.apply(&RowOp::new(thumb, ThumbOp::Set(target)), &row)); + // A tap off the thumbs focuses the nearest one and, in a row whose thumbs jump, moves it there; + // a tap on a thumb moves none. A second click is the reset, which the pipeline applies. + let layout = Layout::new(rules, rect, size, rtl, reach, false, off); + if let Some(picked @ Press::Jump(thumb)) = layout.press(&rules.placed(&row), start.origin.x) { + if off == OffThumbs::Jump + && let Some(&target) = layout.moved(&row, picked, &press, true)[thumb].same() + { + cx.set(rules.apply(&RowOp::new(thumb, ThumbOp::Set(target)), &row)); + } cx.focus_part(Thumb::PART.at(thumb as u64)); } } @@ -1001,7 +1149,7 @@ impl Component for ThumbRow<'_, N> { let row = cx.value().cloned().unwrap_or_else(all_mixed); let shown = rules.placed(&row); let size = style.thumb; - let layout = Layout::new(rules, cx.rect, size, cx.flow.is_rtl(), style.hit, false); + let layout = Layout::new(rules, cx.rect, size, cx.flow.is_rtl(), style.hit, false, self.off_thumbs); let xs = layout.xs(&shown); let running = cx.gesture().and_then(|_| cx.recall::().press); let hovered = std::iter::once(PartRef::from(ROW)) @@ -1011,6 +1159,15 @@ impl Component for ThumbRow<'_, N> { let thumbs = band(cx.rect, self.track_face.is_some().then_some(style.track.thickness)); let top = thumbs.top(); let halves = self.halves(&rules, &shown); + for span in self.spans { + let ink = match span.ink { + SpanInk::Faint => style.span_faint, + SpanInk::Muted => style.span_muted, + }; + for (left, right) in layout.span_xs(&shown, span) { + draw.fill(&PaintShape::Rect(Rect::from_x_y_ranges(left..=right, top..=top + style.span), CornerRadius::ZERO), ink); + } + } for i in 0..N { // Coinciding halves are one triangle, which the low half draws. if halves[i].is_none() && rules.partner(i).is_some_and(|j| j < i) { diff --git a/crates/ui-widgets/tests/it/value_drag/thumb_row.rs b/crates/ui-widgets/tests/it/value_drag/thumb_row.rs index 825497e08..b461dfdb0 100644 --- a/crates/ui-widgets/tests/it/value_drag/thumb_row.rs +++ b/crates/ui-widgets/tests/it/value_drag/thumb_row.rs @@ -1,9 +1,12 @@ -//! `ThumbRow` rules: the order thumbs keep, split halves, wrapping. +//! `ThumbRow` rules: the order thumbs keep, split halves, wrapping; and what a press on the row moves. -use craft_behavior::{Mixed, MoveMods, NavMove}; -use craft_ui::contract::Bind; -use craft_ui::testing::trial; -use craft_ui::value_drag::{Anchor, Neighbours, Order, RowOp, Thumb, ThumbOp, ThumbRow}; +use craft_behavior::{Mixed, MotionMode, MoveMods, NavMove}; +use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::value_drag::{Anchor, Neighbours, OffThumbs, Order, RowOp, Thumb, ThumbOp, ThumbRow}; +use egui::{Modifiers, Pos2, Rangef, Rect, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; fn forward(thumb: usize) -> RowOp { RowOp::new(thumb, ThumbOp::Move(NavMove::Forward, MoveMods::PLAIN)) @@ -24,8 +27,8 @@ fn an_anchored_row_keeps_its_span_and_order() { } /// Two split pairs ordered black below white, as a Blend If bar's handles: in a row that pushes, setting the black -/// high half past the white pair pushes the white pair along and the order holds; in a row that stops, the half stops -/// at the white pair. +/// high half past the white pair moves the black pair there and pushes the white pair along, and the order holds; in +/// a row that stops, the black pair stops at the white pair. #[trial] fn a_pushing_row_moves_the_thumbs_ahead_and_a_stopping_row_stops_at_them() { let ordered = |below, above| Order::between(below, above, 0.0); @@ -40,7 +43,114 @@ fn a_pushing_row_moves_the_thumbs_ahead_and_a_stopping_row_stops_at_them() { let at = Mixed::each([10.0, 20.0, 100.0, 120.0]); let set = RowOp::new(1, ThumbOp::Set(150.0)); let pushing = ThumbRow::new(Bind::given(at), 0.0..=255.0).step(1.0).thumbs(thumbs()).neighbours(Neighbours::Push); - assert_eq!(pushing.rules().apply(&set, &at), Mixed::each([10.0, 150.0, 150.0, 150.0])); + assert_eq!(pushing.rules().apply(&set, &at), Mixed::each([140.0, 150.0, 150.0, 150.0])); let stopping = ThumbRow::new(Bind::given(at), 0.0..=255.0).step(1.0).thumbs(thumbs()); - assert_eq!(stopping.rules().apply(&set, &at), Mixed::each([10.0, 100.0, 100.0, 120.0])); + assert_eq!(stopping.rules().apply(&set, &at), Mixed::each([90.0, 100.0, 100.0, 120.0])); +} + +/// A key, the wheel or a set value on either half of a split thumb moves the pair and keeps the spread, up to where +/// the pair meets the end; with Alt (the fine flag) the focused half moves alone, by the plain step. +#[trial] +fn a_split_thumb_moves_as_a_pair_and_with_alt_as_one_half() { + let at = Mixed::each([10.0, 20.0]); + let row = ThumbRow::new(Bind::given(at), 0.0..=255.0).step(1.0).thumbs([Thumb::new("low").split(), Thumb::new("high")]); + let rules = row.rules(); + assert_eq!(rules.apply(&forward(1), &at), Mixed::each([11.0, 21.0])); + let alt = RowOp::new(1, ThumbOp::Move(NavMove::Forward, MoveMods::PLAIN.fine(true))); + assert_eq!(rules.apply(&alt, &at), Mixed::each([10.0, 21.0])); + assert_eq!(rules.apply(&RowOp::new(0, ThumbOp::Set(100.0)), &at), Mixed::each([100.0, 110.0])); + assert_eq!(rules.apply(&RowOp::new(0, ThumbOp::Set(250.0)), &at), Mixed::each([245.0, 255.0])); +} + +const FIELD: Rect = Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(276.0, 50.0) }; + +/// A split thumb shown in `FIELD` over 0..=255, holding its values and where its thumbs travel. +struct Split { + values: RefCell<[Mixed; 2]>, + travel: Cell, + off: OffThumbs, +} + +impl Split { + /// The split thumb at `values` in a row whose presses off the thumbs do `off`, shown and settled. + fn rig(values: [f64; 2], off: OffThumbs) -> (Rc, Fixture) { + let split = Rc::new(Split { values: RefCell::new(Mixed::each(values)), travel: Cell::new(Rangef::NOTHING), off }); + let shown = Rc::clone(&split); + let mut fixture = Fixture::new(move |ui| shown.show(ui)); + fixture.motion(MotionMode::Off).settle(); + (split, fixture) + } + + fn show(&self, ui: &mut egui::Ui) { + let thumbs = [Thumb::new("low").split(), Thumb::new("high")]; + let mut values = self.values.borrow_mut(); + let row = ThumbRow::new(Bind::bound(&mut *values), 0.0..=255.0).step(1.0).thumbs(thumbs).off_thumbs(self.off).label("Blend"); + self.travel.set(row.show_at(ui, FIELD).travel); + } + + /// The point on the row at `value`. + fn at(&self, value: f64) -> Pos2 { + let travel = self.travel.get(); + Pos2::new(travel.min + travel.span() * (value / 255.0) as f32, FIELD.center().y) + } + + fn values(&self) -> [f64; 2] { + let values = *self.values.borrow(); + values.map(|value| value.same().copied().unwrap_or(f64::NAN)) + } +} + +/// Presses at `from`, moves `by` along the row in four frames, with Alt held from the third on when `alt`, and +/// releases. +fn drag(fixture: &mut Fixture, from: Pos2, by: f32, alt: bool) { + fixture.frame(vec![pointer::moved(from)]); + fixture.frame(vec![pointer::press(from)]); + for step in 1..=4 { + if alt && step == 3 { + fixture.hold(Modifiers::ALT); + } + fixture.frame(vec![pointer::moved(from + Vec2::new(by * step as f32 / 4.0, 0.0))]); + } + fixture.frame(vec![pointer::release(from + Vec2::new(by, 0.0))]); + fixture.hold(Modifiers::NONE).settle(); +} + +/// The thumb that has the focus. +fn focused(fixture: &Fixture) -> Option { + fixture.focused_stop().and_then(|(_, part)| part).and_then(|part| part.index) +} + +/// A drag on a half of a split thumb moves the pair; once Alt is held, the half alone, from where the drag began. +#[trial] +fn a_drag_moves_a_split_pair_and_with_alt_held_its_half() { + let (split, mut fixture) = Split::rig([100.0, 150.0], OffThumbs::Jump); + drag(&mut fixture, split.at(150.0), 20.0, false); + let [low, high] = split.values(); + assert!(high > 150.0 && high - low == 50.0, "the pair did not move together: {low}, {high}"); + drag(&mut fixture, split.at(high), 20.0, true); + let [alone_low, alone_high] = split.values(); + assert!(alone_low == low && alone_high > high, "the high half did not move alone: {alone_low}, {alone_high}"); +} + +/// A press on the triangle of coinciding halves takes the half on its side of the tip, even as it drags toward the +/// other side. +#[trial] +fn a_press_on_coinciding_halves_takes_the_half_on_its_side_of_the_tip() { + for (side, half) in [(-3.0_f32, 0), (3.0, 1)] { + let (split, mut fixture) = Split::rig([100.0, 100.0], OffThumbs::Jump); + drag(&mut fixture, split.at(100.0) + Vec2::new(side, 0.0), -20.0 * side.signum(), false); + assert_eq!(focused(&fixture), Some(half), "a press {side} points from the tip took another half"); + } +} + +/// A tap off the thumbs focuses the nearest thumb in a row whose presses off them take the nearest, and does nothing +/// in a row that ignores them; neither moves a thumb. +#[trial] +fn a_tap_off_the_thumbs_focuses_the_nearest_or_does_nothing_as_the_row_says() { + for (off, expected) in [(OffThumbs::Nearest, Some(1)), (OffThumbs::Ignore, None)] { + let (split, mut fixture) = Split::rig([100.0, 150.0], off); + fixture.click_at(split.at(220.0)).settle(); + assert_eq!(split.values(), [100.0, 150.0], "a tap in a {off:?} row moved a thumb"); + assert_eq!(focused(&fixture), expected, "a tap in a {off:?} row focused another thumb"); + } }