diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index cb45db81a6..12cebda239 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -154,10 +154,10 @@ impl Codec for PlainText { } } -/// A reader a caller adds for words that stand for numbers. +/// A caller's text-to-number reader. type Custom = Arc Option + Send + Sync>; -/// An optional number: empty text is `None`; anything else reads through a [`Reader`]. +/// An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`]. #[derive(Clone)] pub struct NumberCodec { reader: Reader, @@ -165,6 +165,8 @@ pub struct NumberCodec { /// Every decimal place is written, trailing zeros included. fixed: bool, custom: Option, + /// An authoritative reader for the complete, trimmed, non-empty input. + primary: Option, /// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]). zoom: bool, /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). @@ -182,6 +184,7 @@ impl fmt::Debug for NumberCodec { .field("share", &self.share) .field("signed_zoom", &self.signed_zoom) .field("custom", &self.custom.is_some()) + .field("primary", &self.primary.is_some()) .finish() } } @@ -193,6 +196,11 @@ impl PartialEq for NumberCodec { (Some(a), Some(b)) => Arc::ptr_eq(a, b), _ => false, }; + let same_primary = match (&self.primary, &other.primary) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + }; self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed @@ -200,6 +208,7 @@ impl PartialEq for NumberCodec { && self.share == other.share && self.signed_zoom == other.signed_zoom && same_custom + && same_primary } } @@ -233,7 +242,7 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false } } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -303,6 +312,16 @@ impl NumberCodec { self } + /// The same codec with an authoritative reader for the complete, trimmed, non-empty input. It replaces the + /// reader's expressions/relative input, zoom parsing and `or_parse`: `None` or a non-finite result rejects the + /// input without fallback. Empty text still means `None`. Formatting and the character filter are unchanged. + /// + /// Use this when a domain's existing grammar must own the whole value, rather than adding a word with `or_parse`. + pub fn parse_with(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self { + self.primary = Some(Arc::new(parse)); + self + } + /// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of /// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized /// for any value it shows in it. @@ -367,6 +386,9 @@ impl Codec for NumberCodec { if trimmed.is_empty() { return Ok((None, ParseNote::default())); } + if let Some(parse) = &self.primary { + return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue); + } if self.zoom { return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 617f1f0347..9a9f8a7ef8 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -120,7 +120,7 @@ pub use value::{ Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Preview, Validity, Value, same_in_f32, same_in_f32_at, }; -pub use value_drag::{DragWarp, ValueDrag, wrap_value}; +pub use value_drag::{DragModifier, DragModifiers, DragWarp, ValueDrag, wrap_value}; pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; #[cfg(test)] diff --git a/crates/behavior/src/value_drag.rs b/crates/behavior/src/value_drag.rs index 4a69c6a4e0..e2968b7285 100644 --- a/crates/behavior/src/value_drag.rs +++ b/crates/behavior/src/value_drag.rs @@ -5,6 +5,52 @@ use crate::press::{PressPhase, PressState}; use emath::{Pos2, Rect, Vec2}; use std::ops::{Range, RangeInclusive}; +/// A modifier that changes continuous pointer-drag sensitivity. It does not remap input or keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DragModifier { + /// Alt (Option). + Alt, + /// Shift. + Shift, + /// Control. + Control, + /// The platform's command modifier. + Command, +} + +impl DragModifier { + fn held(self, press: &PressState) -> bool { + match self { + Self::Alt => press.mods.alt, + Self::Shift => press.mods.shift, + Self::Control => press.mods.ctrl, + Self::Command => press.mods.cmd, + } + } +} + +/// The pointer-only fine/coarse bindings of a continuous drag. Fine wins when both bindings match. +/// Unbound modifiers leave travel normal. Defaults retain Alt fine, Shift coarse. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DragModifiers { + fine: Option, + coarse: Option, +} + +impl DragModifiers { + /// Selects the fine and coarse bindings; `None` disables that binding. + pub const fn new(fine: Option, coarse: Option) -> Self { + Self { fine, coarse } + } +} + +impl Default for DragModifiers { + fn default() -> Self { + Self::new(Some(DragModifier::Alt), Some(DragModifier::Shift)) + } +} + /// How the pointer's position along the axis becomes a value. #[derive(Clone, Debug, PartialEq)] enum Mapping { @@ -24,6 +70,7 @@ pub struct ValueDrag { hide_cursor: bool, fine: f64, coarse: Option, + modifiers: DragModifiers, } /// The factor Alt (Option) applies to travel when a drag sets none. @@ -40,12 +87,30 @@ impl ValueDrag { /// A track whose `start` lies after its `end` runs backwards, as a vertical slider's does, and a range whose start /// exceeds its end maps the track the other way; the value stays within the range either way. pub fn absolute(track: Range, range: RangeInclusive) -> Self { - ValueDrag { mapping: Mapping::Absolute { track }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None } + ValueDrag { + mapping: Mapping::Absolute { track }, + axis: Axis::X, + range, + warp: false, + hide_cursor: false, + fine: FINE, + coarse: None, + modifiers: DragModifiers::default(), + } } /// The value changes by `rate` units per point of travel from the press. Vertical travel upwards increases it. pub fn relative(rate: f64, range: RangeInclusive) -> Self { - ValueDrag { mapping: Mapping::Relative { rate }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None } + ValueDrag { + mapping: Mapping::Relative { rate }, + axis: Axis::X, + range, + warp: false, + hide_cursor: false, + fine: FINE, + coarse: None, + modifiers: DragModifiers::default(), + } } /// The axis the pointer travels on; the default is horizontal. @@ -67,6 +132,12 @@ impl ValueDrag { self } + /// Selects pointer fine/coarse bindings without changing keyboard or wheel behavior. + pub const fn modifiers(mut self, modifiers: DragModifiers) -> Self { + self.modifiers = modifiers; + self + } + /// Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end /// ([`ValueDrag::warp_by`], [`DragWarp`]). It sets no wrap of the value. pub const fn warp(mut self, on: bool) -> Self { @@ -129,9 +200,9 @@ impl ValueDrag { _ => return None, }; let pos = pos - shift; - let fine = if press.mods.alt { + let fine = if self.modifiers.fine.is_some_and(|binding| binding.held(press)) { self.fine - } else if press.mods.shift { + } else if self.modifiers.coarse.is_some_and(|binding| binding.held(press)) { self.coarse.unwrap_or(1.0) } else { 1.0 @@ -236,6 +307,38 @@ mod tests { use craft_keymap::Mods; use emath::{Vec2, pos2}; + #[test] + fn pointer_modifier_policy_preserves_defaults_and_raw_modifiers() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0); + let mut both = Mods::ALT; + both.shift = true; + for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 200.0), (Mods::ALT, 2.0), (both, 2.0)] { + let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods); + assert_eq!(base.value(0.0, &press, false), Some(expected)); + assert_eq!(press.mods, mods); + } + } + + #[test] + fn pointer_modifier_policy_selects_shift_fine_and_alt_normal() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0).modifiers(DragModifiers::new(Some(DragModifier::Shift), None)); + let mut both = Mods::ALT; + both.shift = true; + for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 2.0), (Mods::ALT, 20.0), (both, 2.0)] { + let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods); + assert_eq!(base.value(0.0, &press, false), Some(expected)); + assert_eq!(press.mods, mods); + } + } + + #[test] + fn pointer_modifier_policy_unbound_and_overlapping_bindings_are_explicit() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0); + let shift = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), Mods::SHIFT); + assert_eq!(base.clone().modifiers(DragModifiers::new(None, None)).value(0.0, &shift, false), Some(20.0)); + assert_eq!(base.modifiers(DragModifiers::new(Some(DragModifier::Shift), Some(DragModifier::Shift))).value(0.0, &shift, false), Some(2.0)); + } + fn drag(from: Pos2, to: Pos2, mods: Mods) -> PressState { let start = PressStart::new(from, PointerButton::Primary, 0.0, 1); PressState::new(PressPhase::Drag { start, pos: to, delta: Vec2::ZERO }).mods(mods) diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 12c36a01e3..3f75b029e8 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -362,6 +362,10 @@ pub struct WheelTaker { /// It takes any axis (scroll or zoom) only while focused or armed: a value control, unless its scope frees it, /// or any taker inside a gated scope. pub gated: bool, + /// Directional value editing: dominant horizontal (or Shift) scroll edits under the pointer; + /// vertical scroll requires explicit arming, not keyboard focus. The existing arming lifecycle + /// disarms on leaving the control, without changing keyboard focus. + pub directional: bool, /// A scroll region (a scrolling body or collection): Shift turns the vertical wheel sideways over it. pub scrolls: bool, /// The distance of one wheel line. @@ -430,6 +434,7 @@ impl WheelTaker { vertical: false, zoom: false, gated: false, + directional: false, scrolls: false, notch: WheelNotch::DEFAULT, room: None, @@ -497,6 +502,14 @@ impl WheelTaker { self } + /// Opts a value control into directional editing, without changing the default focus gate. + /// The caller registers both scroll axes and keeps the taker gated so presses can arm it. + #[must_use] + pub const fn directional(mut self, on: bool) -> Self { + self.directional = on; + self + } + /// The distance of one wheel line. pub const fn notch(mut self, notch: WheelNotch) -> Self { self.notch = notch; @@ -637,7 +650,8 @@ pub fn split( if !running { *gesture = WheelGesture::default(); } - let field = focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && taker.owner == *focused)); + let field = + focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && !taker.directional && taker.owner == *focused)); let app_field = focus.app_field && !focus.by_position; // A value control keeps its gesture only while the pointer is over it: once the pointer leaves, the gesture goes // on by position as a running one (value controls excluded) and the control hears its end now, so its edit run @@ -696,17 +710,43 @@ fn split_at( // Takers register outer first, so among equal areas the later one is the deeper (or the upper) and goes first. let mut under: Vec<&WheelTaker> = takers.iter().rev().filter(|taker| taker.rect.contains(at)).collect(); under.sort_by(|a, b| a.rect.area().total_cmp(&b.rect.area())); - // A trackpad steps a value control only while it is focused or armed: over anything else it scrolls the panel. + // Read intent without changing anyone's input: a running panel gesture can cross a + // directional control without that control becoming an eligible recipient. + // A dominant horizontal swipe, or a Shift-wheel whatever its vertical component; the edit distance is the axis + // that intent names, so a Shift-wheel with a little sideways drift still edits by its vertical share. + let horizontal = wheel.scroll.x.abs() > wheel.scroll.y.abs(); + let sideways = horizontal || (wheel.mods.shift && wheel.scroll.y != 0.0); + // A trackpad otherwise steps a value control only while it is focused or armed. let fingers = wheel.source.fingers(); - let open = |taker: &WheelTaker| (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner); + let open = |taker: &WheelTaker| { + if taker.directional { + !(wheel.mods.alt || wheel.mods.cmd || wheel.mods.ctrl) && (sideways || armed == Some(taker.owner)) + } else { + (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner) + } + }; // The running gesture's owner, while it is registered and open; it takes its axes wherever the pointer is. A // focused field holds the wheel by the field rule alone, so a wheel with Alt or Cmd/Ctrl still reaches the view. - let held: Option<&WheelTaker> = latch - .flatten() - .and_then(|owner| takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && focused == Some(taker.owner)))); + let held: Option<&WheelTaker> = latch.flatten().and_then(|owner| { + // A focused field holds the wheel by the field rule alone, not a directional control: that one took the + // gesture by position and keeps it while it runs. + takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && !taker.directional && focused == Some(taker.owner))) + }); // Who takes a scroll axis by position: any open taker for a new gesture; during a running one no value control, // so a control the pointer passes over does not take the scroll over. let free = |taker: &WheelTaker| open(taker) && (latch.is_none() || !taker.value); + let horizontal_recipient = held + .filter(|taker| taker.horizontal) + .or_else(|| under.iter().copied().find(|taker| taker.horizontal && free(taker) && taker.has_room(false, wheel.scroll.x))); + let wheel = if sideways && horizontal_recipient.is_some_and(|taker| taker.directional) { + // Only the selected directional recipient reads a normalized dominant-axis share. + // Another owner, including a latched panel or a command-chord recipient, keeps the + // device's original components unchanged. + let (along, lines) = if horizontal { (wheel.scroll.x, wheel.lines.x) } else { (wheel.scroll.y, wheel.lines.y) }; + Wheel { scroll: Vec2::new(along, 0.0), lines: Vec2::new(lines, 0.0), ..wheel } + } else { + wheel + }; let zone = (wheel.scroll.y != 0.0).then(|| under.iter().position(|t| (t.vertical || t.zooms_view) && open(t))).flatten(); let zone_view = zone.filter(|&at| !under[at].vertical).and_then(|at| under[at + 1..].iter().find(|t| t.zoom && open(t))).map(|t| t.owner); // A running gesture zooms a view by the zone only when it is that view's gesture. @@ -758,6 +798,13 @@ fn split_at( None => shares.push((owner, part)), } } + // A directional value control reads a plain notch: Shift reached it as the request for the sideways wheel (the + // rule above), never as a multiplier of its step. Another taker keeps its modifiers. + for (owner, share) in &mut shares { + if takers.iter().any(|taker| taker.directional && taker.owner == *owner) { + share.mods = Mods { shift: false, ..share.mods }; + } + } shares } @@ -770,6 +817,12 @@ mod tests { Wheel::new(Vec2::new(x, y), Mods::NONE, WheelUnit::Point, WheelPhase::Move) } + /// The first share of a split at `at` with nothing armed or latched. + fn share_of(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: Option, armed: Option) -> (u8, Wheel) { + let mut gesture = WheelGesture::default(); + split(takers, at, wheel, WheelFocus::new(focus), armed, &mut gesture, 0.0)[0] + } + fn rect(size: f32) -> Rect { Rect::from_min_size(pos2(0.0, 0.0), Vec2::splat(size)) } @@ -856,4 +909,70 @@ mod tests { assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again"); assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch"); } + + #[test] + fn directional_value_wheel_keeps_plain_defaults_and_requires_arming_only_for_vertical() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let control = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true); + let at = pos2(10.0, 10.0); + let shares = + |control, wheel, focus, armed| split(&[panel, control], at, wheel, WheelFocus::new(focus), armed, &mut WheelGesture::default(), 0.0); + assert_eq!(shares(control, wheel(0.0, 6.0), Some(2), None)[0].0, 2, "default focus gate is unchanged"); + assert_eq!(shares(control, wheel(6.0, 0.0), None, None)[0].0, 1, "default unfocused sideways scroll stays with the panel"); + let directional = control.directional(true); + assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), None)[0].0, 1, "focus alone does not rearm vertical editing"); + assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), Some(2))[0].0, 2, "an explicit press arms vertical editing"); + let horizontal = shares(directional, wheel(6.0, 0.0).source(WheelSource::Trackpad), None, None); + assert_eq!((horizontal[0].0, horizontal[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "an unselected horizontal trackpad swipe edits"); + let diagonal_right = shares(directional, wheel(12.0, -3.0), None, None); + assert_eq!((diagonal_right[0].0, diagonal_right[0].1.scroll), (2, Vec2::new(12.0, 0.0)), "horizontal-dominant intent keeps its sign"); + let shifted = shares(directional, Wheel { mods: Mods::SHIFT, ..wheel(0.0, 6.0) }, None, None); + assert_eq!((shifted[0].0, shifted[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "Shift-wheel is explicitly sideways"); + assert!(!shifted[0].1.mods.shift, "the directional share carries one plain notch, not Shift's ten"); + let diagonal = shares(directional, wheel(3.0, -12.0), Some(2), None); + assert!(diagonal.iter().all(|(owner, _)| *owner == 1), "a vertical-dominant swipe stays with the panel despite focus"); + assert_eq!(diagonal[0].1.scroll.y, -12.0, "vertical scrolling remains available"); + for mods in [Mods::CTRL, Mods::ALT, Mods::CMD, Mods { shift: true, ..Mods::CTRL }] { + let chord = shares(directional, Wheel { mods, ..wheel(12.0, -3.0) }, None, None); + assert_eq!((chord[0].0, chord[0].1.scroll), (1, Vec2::new(12.0, -3.0)), "command chords keep both original panel components: {mods:?}"); + } + } + + #[test] + fn directional_shift_wheel_with_both_axes_edits_by_its_vertical_share() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let directional = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true); + let at = pos2(10.0, 10.0); + let mixed = share_of(&[panel, directional], at, Wheel { mods: Mods::SHIFT, ..wheel(3.0, -12.0) }, None, None); + assert_eq!(mixed.0, 2, "Shift-wheel with mixed axes reaches the directional control"); + assert_eq!(mixed.1.scroll, Vec2::new(-12.0, 0.0), "and edits by its vertical share"); + assert!(!mixed.1.mods.shift, "one plain notch"); + let plain = share_of(&[panel, directional], at, wheel(3.0, -12.0), None, None); + assert_eq!(plain.0, 1, "without Shift a vertical-dominant swipe is the panel's"); + } + + #[test] + fn a_focused_directional_field_keeps_its_running_gesture() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let field = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true).field(true); + let at = pos2(10.0, 10.0); + let mut gesture = WheelGesture::default(); + let first = split(&[panel, field], at, wheel(6.0, -3.0), WheelFocus::new(Some(2)), None, &mut gesture, 0.0); + assert_eq!(first[0].0, 2, "the focused directional field takes the first sideways event"); + let second = split(&[panel, field], at, wheel(6.0, -3.0), WheelFocus::new(Some(2)), None, &mut gesture, 0.05); + assert_eq!(second[0].0, 2, "and the next event of the same gesture, though it is a focused field"); + } + + #[test] + fn directional_control_under_a_running_panel_scroll_must_not_strip_its_vertical_share() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let directional = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true); + let mut gesture = WheelGesture::default(); + let first = split(&[panel, directional], pos2(200.0, 200.0), wheel(12.0, -3.0), WheelFocus::new(None), None, &mut gesture, 0.0); + assert_eq!((first[0].0, first[0].1.scroll), (1, Vec2::new(12.0, -3.0))); + // The existing panel-owned gesture crosses an opted-in slider. Values are excluded while + // another owner holds the gesture, so the untouched panel must retain BOTH scroll axes. + let crossing = split(&[panel, directional], pos2(10.0, 10.0), wheel(12.0, -3.0), WheelFocus::new(None), None, &mut gesture, 0.001); + assert_eq!((crossing[0].0, crossing[0].1.scroll), (1, Vec2::new(12.0, -3.0))); + } } diff --git a/crates/behavior/tests/codec_override.rs b/crates/behavior/tests/codec_override.rs new file mode 100644 index 0000000000..2f6923f0d6 --- /dev/null +++ b/crates/behavior/tests/codec_override.rs @@ -0,0 +1,64 @@ +//! An opt-in primary numeric grammar never falls through to expression, relative or fallback parsing. + +use craft_behavior::{Codec, NotAValue, NumberCodec, ParseNote, Reader}; + +fn absolute(text: &str) -> Option { + text.parse().ok() +} + +#[test] +fn codec_override_reads_complete_trimmed_values_absolutely() { + let codec = NumberCodec::default().parse_with(|text| { + assert_eq!(text, text.trim()); + absolute(text) + }); + assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(12.0))); + assert_eq!(codec.parse("-12", &Some(50.0)), Ok(Some(-12.0))); + assert_eq!(codec.parse(" ", &Some(50.0)), Ok(None), "the existing empty-value convention stays intact"); + assert_eq!(codec.parse_tagged("12", &Some(50.0)), Ok((Some(12.0), ParseNote::default()))); + for text in ["1+2", "*2", "1.2.3", "12 widgets", "1 2", "1,2.3"] { + assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "reject the entire input {text:?}"); + } +} + +#[test] +fn codec_override_rejection_never_falls_through_to_other_readers() { + let codec = NumberCodec::new(Reader::new().unit("widgets", 2.0), 2).or_parse(|_| Some(999.0)).zoom_typing().parse_with(absolute); + for text in ["1+2", "8/4", "2 widgets", "Auto", "1.2.3"] { + assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "no secondary reader may accept {text:?}"); + } + assert_eq!(codec.parse("+12", &Some(50.0)), Ok(Some(12.0))); + // Setter order does not silently replace the authoritative reader with the fallback reader. + let codec = NumberCodec::default().parse_with(absolute).or_parse(|_| Some(999.0)); + assert_eq!(codec.parse("Auto", &None), Err(NotAValue)); +} + +#[test] +fn codec_override_rejects_nonfinite_callback_results() { + let codec = NumberCodec::default().parse_with(absolute); + for text in ["NaN", "inf", "-inf", "1e9999"] { + assert_eq!(codec.parse(text, &None), Err(NotAValue), "non-finite {text:?}"); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let codec = NumberCodec::default().parse_with(move |_| Some(value)); + assert_eq!(codec.parse("anything", &None), Err(NotAValue)); + } +} + +#[test] +fn codec_override_preserves_formatting_filter_equality_and_all_default_grammars() { + let original = NumberCodec::new(Reader::new().decimal(','), 2).fixed().zoom_typing(); + let custom = original.clone().parse_with(absolute); + assert_eq!(original.format(&Some(12.5)), custom.format(&Some(12.5))); + assert_eq!(custom.format(&Some(12.5)), "12,50"); + for c in ['1', ',', '/', '+', '-', '*', 'w'] { + assert_eq!(original.filter(c), custom.filter(c), "filter {c}"); + } + assert_eq!(custom, custom.clone()); + assert_ne!(original, custom); + let default = NumberCodec::default(); + assert_eq!(default.parse("+12", &Some(50.0)), Ok(Some(62.0))); + assert_eq!(default.parse("1+2", &Some(50.0)), Ok(Some(3.0))); + assert_eq!(default.clone().or_parse(|text| (text == "Auto").then_some(99.0)).parse("Auto", &None), Ok(Some(99.0))); + assert_eq!(default.zoom_typing().parse("8/4", &None), Ok(Some(200.0))); +} diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index c52c1045ec..d01da9d642 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -2,6 +2,7 @@ mod canvas_view; mod cells; +mod codec_override; mod digit_keys; mod dock; mod dock_apply; diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index 84fb52ff8e..b62685d339 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -26,6 +26,7 @@ pub(crate) fn register_wheel( scope: WheelScope, ) { let free = sensed.is_some() && scope == WheelScope::Free; + let directional = sensed.is_some() && value_control && scope == WheelScope::Directional; let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); let taker = sensed.or_else(|| value_control.then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); if let Some(taker) = taker { @@ -34,7 +35,9 @@ pub(crate) fn register_wheel( taker .value(value_control) .field(value_control && text && sensed.is_some()) - .gated(scope == WheelScope::Gated || (value_control && !free && !zone)), + .gated(scope == WheelScope::Gated || (value_control && !free && !zone)) + .horizontal(taker.horizontal || directional) + .directional(directional), ); } } diff --git a/crates/ui-contract/src/runtime/egui/mod.rs b/crates/ui-contract/src/runtime/egui/mod.rs index 340b21a696..4e43041ab8 100644 --- a/crates/ui-contract/src/runtime/egui/mod.rs +++ b/crates/ui-contract/src/runtime/egui/mod.rs @@ -1,5 +1,9 @@ //! The one egui adapter: the only importer of egui's behavioural APIs. +/// The layer a widget was shown in, for a component whose own API carries one (a scalar row): egui's layer type is a +/// behavioural API (`contract/egui-import`), so it is named through here. +pub use egui::LayerId; + pub mod access; pub mod alloc; pub(crate) mod alt_code; diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index 2d43b3aecd..390c03094b 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -107,6 +107,11 @@ pub enum WheelScope { /// Every taker takes the wheel only while focused or armed: a card in a scrolling overview. Wins over a `Free` set /// inside it, so a scroll of the overview never stops on a story's slider. Gated, + /// Value controls that sense the wheel edit on a dominant horizontal swipe or Shift-wheel + /// under the pointer. Vertical scrolling edits only after an explicit press and only until + /// the pointer leaves; keyboard focus survives but never rearms wheel editing. Other takers + /// are unchanged. An outer `Gated` scope still wins. + Directional, } /// Changes to the inherited values for a stretch of code. diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index ceb9750c6d..c9ab92e365 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -15,6 +15,11 @@ mod input; mod intents; mod nodes; mod route; +mod scalar; + +pub use scalar::{ScalarKeyPolicy, ScalarKeyTrigger}; +#[doc(hidden)] +pub use scalar::{ScalarRow, register_scalar}; #[doc(hidden)] pub use claims::capture; @@ -273,6 +278,8 @@ struct Source { #[derive(Clone, Default)] struct Routed { items: Vec, + /// Scalar-row moves selected by the canonical router, distinct from ordinary focused navigation. + scalar_moves: Vec<(NavMove, MoveMods)>, nudge: Option, /// The chords a recorder stop's presses spell this pass. chords: Vec, @@ -328,6 +335,8 @@ pub(crate) struct Stage { layout: Layout, nodes: HashMap, last_nodes: HashMap, + /// Opt-in real rows declared this pass; taken at the next begin, so unmounted rows cannot accumulate. + scalar_rows: Vec, activated: IdMap, alt: AltTrack, /// The keys down now, as the input hook read them before it withheld any press. diff --git a/crates/ui-contract/src/runtime/keys/intents.rs b/crates/ui-contract/src/runtime/keys/intents.rs index 6b368115a4..05859ecb55 100644 --- a/crates/ui-contract/src/runtime/keys/intents.rs +++ b/crates/ui-contract/src/runtime/keys/intents.rs @@ -17,6 +17,8 @@ pub struct Intents { /// one has none. sources: Vec>, took_arrows: Vec, + scalar_moves: Vec<((NavMove, MoveMods), bool)>, + scalar_at: usize, nudge: Option, chords: Vec, set_value: Option<(Option, f64)>, @@ -90,6 +92,15 @@ impl Intents { } } + /// Takes one scalar-row move selected by the canonical router, independently of ordinary focused navigation. + #[doc(hidden)] + pub fn take_scalar_move(&mut self) -> Option<(NavMove, MoveMods)> { + let item = self.scalar_moves.get_mut(self.scalar_at)?; + self.scalar_at += 1; + item.1 = true; + Some(item.0) + } + /// Takes the next move, whichever it is: for a component that acts on every move. A move taken is the component's, /// so the Page Up, Page Down, Home and End it takes never reach the scroll owner around it (a page view under a /// focused page part); a component that acts on some moves takes those with [`take_move_where`](Self::take_move_where) @@ -287,6 +298,8 @@ pub fn intents_of(ctx: &Context, id: Option, rtl: bool) -> Intents { items, sources, took_arrows: Vec::new(), + scalar_moves: routed.scalar_moves.into_iter().map(|movement| (movement, false)).collect(), + scalar_at: 0, nudge: routed.nudge, chords: routed.chords, set_value: routed.set_value, @@ -474,6 +487,8 @@ pub fn settle(ctx: &Context, id: Option, intents: &Intents) { let Some(routed) = stage.routed.get_mut(&id) else { return }; let mut taken = intents.items.iter().map(|(_, taken)| *taken); routed.items.retain(|_| !taken.next().unwrap_or(false)); + let mut scalar_taken = intents.scalar_moves.iter().map(|(_, taken)| *taken); + routed.scalar_moves.retain(|_| !scalar_taken.next().unwrap_or(false)); if intents.nudge.is_none() { routed.nudge = None; } diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index ae693a4614..adf878984a 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -1,7 +1,7 @@ //! The begin hook's routing: key presses, shortcuts and AccessKit requests to the intents of their owners. use super::input::chrome_toggle_of; -use super::{Batch, EscapePress, Item, LeftClip, MenuKey, Node, Nudge, Press, Routed, Shortcuts, Source, Taken, current, with}; +use super::{Batch, EscapePress, Item, LeftClip, MenuKey, Node, Nudge, Press, Routed, Shortcuts, Source, Taken, current, scalar, with}; use crate::runtime::commands::{self, ClipContent, FirePhase}; use crate::runtime::egui::input::{Action, ActionKind, Leftover, leftover}; use crate::runtime::focus::{self, StopRec}; @@ -22,7 +22,7 @@ use std::sync::Arc; pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let os = crate::runtime::windows::os_of(ctx); let target = focus::focused_rec(ctx); - let (batch, nodes, captures, held_claims, alt_claims, fired_claims, hover_deletes) = current(ctx, |stage| { + let (batch, nodes, captures, held_claims, alt_claims, fired_claims, hover_deletes, scalar_rows) = current(ctx, |stage| { stage.routed.clear(); stage.fired.clear(); stage.intents_read = false; @@ -43,6 +43,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { alt_claims, fired, std::mem::take(&mut stage.hover_deletes), + std::mem::take(&mut stage.scalar_rows), ) }); let alt_tapped = alt_claims.first().copied().filter(|_| batch.alt_tap); @@ -81,6 +82,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let mut routed: HashMap, Routed> = HashMap::new(); let mut activated = IdMap::default(); let mut consumed = vec![Taken::No; batch.presses.len()]; + let scalar_owned = route_scalar_rows(ctx, &scalar_rows, target.as_ref(), press_captured, &batch, &mut routed, &mut consumed); let driven = target.as_ref().and_then(|rec| Driven::of(ctx, rec)); let field_list = target.as_ref().filter(|_| driven.is_none()).and_then(|rec| list_of_field(ctx, rec)); // Whether a component took each text of the pass, as typing, type-ahead or digits; and whether the framework took @@ -96,7 +98,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { .chain(batch.presses.iter().filter(|press| held_press(press)).filter_map(|press| press.text)) .collect(); if let Some(rec) = &target { - for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, _)| !press.canvas) { + for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, taken)| !press.canvas && **taken == Taken::No) { *taken = if let Some(id) = hover_delete.filter(|id| Some(*id) != target.as_ref().map(|rec| rec.stop.id)) && press.mods.is_none() && matches!(press.key, Key::Delete | Key::Backspace) @@ -145,7 +147,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { // arrows with the modifiers it acts on (`KeyUse::nudge_mods`); the others are the app's, as is a page key bound to // a command that runs now (`page_key_runs`). let declared = |mods: Mods| canvas.as_ref().is_none_or(|canvas| canvas.stop.keys.nudge_mods.contains(mods)); - for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, _)| !press.canvas) { + for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, taken)| !press.canvas && **taken == Taken::No) { if let Some(id) = hover_delete && press.mods.is_none() && matches!(press.key, Key::Delete | Key::Backspace) @@ -188,10 +190,10 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { push(&mut routed, focused, Intent::Edit(command), false); } let over: Vec = batch.presses.iter().map(held_press).collect(); - let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts, &over); + let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts, &over, &scalar_owned); // The app's own widget, focused or the window's canvas, reads its keys from egui. let host = target.as_ref().or(canvas.as_ref()).is_some_and(|rec| rec.stop.host); - withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts); + withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts, &scalar_owned); let pasted = batch.paste.clone().zip(focused).map(|(content, id)| (id, content)); // PLAN: a repeat Tab of a held-over key is not gated; `take_nav` reads `batch.tabs` before this hook runs (owner: focus). // One Escape press cancels once: its repeats cancel nothing more, in the layer it closed or in what that uncovered. @@ -249,9 +251,11 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { } } for request in &batch.access { - route_access(ctx, request, &nodes, &mut routed, &mut activated); + route_access(ctx, request, &nodes, &mut routed, &mut activated, &scalar_rows, press_captured); } current(ctx, |stage| { + stage.scalar_rows = scalar_rows; + stage.scalar_rows.clear(); stage.routed = routed; stage.claimed = claimed; stage.activated = activated; @@ -343,12 +347,44 @@ pub(crate) fn focus_in_modal_dialog(ctx: &Context) -> bool { }) } +/// Routes each plain or Shift Up and Down press of the batch to the scalar row the router chooses (`scalar::choose`): +/// the row takes it as a scalar move, and no other route sees it. Interest comes from real components in last pass's +/// draw order, never from a synthetic focus stop. Returns which presses the row took; empty when no row was declared. +fn route_scalar_rows( + ctx: &Context, + rows: &[scalar::ScalarRow], + target: Option<&StopRec>, + press_captured: bool, + batch: &Batch, + routed: &mut HashMap, Routed>, + consumed: &mut [Taken], +) -> Vec { + let mut owned = if rows.is_empty() { Vec::new() } else { vec![false; batch.presses.len()] }; + let Some(row) = scalar::choose(ctx, rows, target, press_captured) else { return owned }; + for (at, press) in batch.presses.iter().enumerate() { + let movement = match press.key { + Key::Up => NavMove::Up, + Key::Down => NavMove::Down, + _ => continue, + }; + if press.canvas || !(press.mods.is_none() || press.mods == Mods::SHIFT) || batch.claimed.contains(&Chord::new(press.mods, press.key)) { + continue; + } + let modifiers = MoveMods::new(press.mods == Mods::SHIFT, false, MoveMods::PLAIN.by); + routed.entry(Some(row.owner)).or_default().scalar_moves.push((movement, modifiers)); + owned[at] = true; + consumed[at] = Taken::Yes; + } + owned +} + /// The shortcut events the key owner leaves to the app (9.3), and the presses the focused component holds /// (`holds_press`). The owner is the focused component's class, or `Blocked` while a modal layer is stacked above the /// focus; inside a layer its `Overlay.keys` class ranks with the component's. A `Recorder` keeps every key and a `Menu` /// its navigation keys (`keeps_key`); a text field keeps the text its presses typed. `consumed` is what -/// routing did with each press, `taken_texts` whether a component took each text of the pass, and `over` whether each -/// press is a repeat of a key held over a modal layer's opening or closing, which runs no shortcut either. +/// routing did with each press, `taken_texts` whether a component took each text of the pass, `over` whether each +/// press is a repeat of a key held over a modal layer's opening or closing, which runs no shortcut either, and +/// `scalar_owned` whether a scalar row took each press. fn owned_shortcuts( ctx: &Context, target: Option<&StopRec>, @@ -356,6 +392,7 @@ fn owned_shortcuts( consumed: &[Taken], taken_texts: &[bool], over: &[bool], + scalar_owned: &[bool], ) -> (Shortcuts, Vec) { let scopes = target.map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(); let owner = owner_at(ctx, target, &scopes, None); @@ -369,12 +406,26 @@ fn owned_shortcuts( .iter() .zip(consumed) // The canvas's Space is never the focused stop's; a press the unfocused window's canvas took is the canvas's. - .map(|(press, taken)| { + .enumerate() + .map(|(at, (press, taken))| { // Text an input method committed for the press goes to the text stop that has the IME. let typed = press.text.is_some_and(|at| taken_texts[at]) || (press.ime && target.is_some_and(|rec| rec.stop.text)); - !press.canvas && (matches!(*taken, Taken::Canvas | Taken::Hover) || holds_press(owner, target, press, *taken == Taken::Yes, typed)) + scalar_owned.get(at).copied().unwrap_or(false) + || (!press.canvas + && (matches!(*taken, Taken::Canvas | Taken::Hover) || holds_press(owner, target, press, *taken == Taken::Yes, typed))) }) .collect(); + // Only Up/Down are scalar presses. Summarize paired releases once rather than scanning all presses per shortcut. + let scalar_releases = batch.presses.iter().zip(scalar_owned).fold([false; 2], |mut held, (press, owned)| { + if *owned { + match press.release { + Some(Key::Up) => held[0] = true, + Some(Key::Down) => held[1] = true, + _ => {} + } + } + held + }); // A shortcut without a press of its own (a release, or the clipboard event that stands for ⌘C) follows the owner by // its modifiers, as its press would. let kept: Vec = batch @@ -382,7 +433,17 @@ fn owned_shortcuts( .iter() .map(|shortcut| { let key = shortcut.input.typed.or(shortcut.input.physical); - !keeps_key(owner, key, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at] || over[at]) + // A release in the same batch belongs to its scalar press too; later releases are withheld by the strip. + // A release that names its own press is judged by that press below (`held`), which already knows whether it + // was scalar's: only a release with no press of its own is paired to a scalar press by its key here. + let scalar_release = shortcut.phase == FirePhase::Release + && shortcut.press.is_none() + && match key { + Some(Key::Up) => scalar_releases[0], + Some(Key::Down) => scalar_releases[1], + _ => false, + }; + !scalar_release && !keeps_key(owner, key, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at] || over[at]) }) .collect(); let keys = batch.shortcuts.iter().zip(&kept).filter(|(_, stays)| **stays).map(|(shortcut, _)| *shortcut).collect(); @@ -517,11 +578,18 @@ pub fn focus_holds(ctx: &Context, chord: Chord) -> bool { /// Takes what the framework handed to one taker out of the running pass's egui input, where the app and egui's text /// widgets read their keys: one press, one action, and one text, one reader. `held` marks the presses the focused /// component (or the unfocused window's canvas) holds; the app's own widget (`Stop::host`, `host`) reads its keys from -/// egui, so its presses stay. `texts` are the places in `Batch::texts` of the texts a claim or a framework taker took. -/// A held press whose release has not come yet leaves its release to the strip. -fn withdraw_taken(ctx: &Context, host: bool, batch: &Batch, held: &[bool], texts: &[usize]) { - let presses: Vec<&Press> = - batch.presses.iter().zip(held).filter(|(press, held)| !host && **held && press.in_egui.is_some()).map(|(press, _)| press).collect(); +/// egui, so its presses stay, except the scalar-row presses (`scalar_owned`) the framework routed. `texts` are the +/// places in `Batch::texts` of the texts a claim or a framework taker took. A held press whose release has not come yet +/// leaves its release to the strip. +fn withdraw_taken(ctx: &Context, host: bool, batch: &Batch, held: &[bool], texts: &[usize], scalar_owned: &[bool]) { + let presses: Vec<&Press> = batch + .presses + .iter() + .zip(held) + .enumerate() + .filter(|(at, (press, held))| (!host || scalar_owned.get(*at).copied().unwrap_or(false)) && **held && press.in_egui.is_some()) + .map(|(_, (press, _))| press) + .collect(); if presses.is_empty() && texts.is_empty() { return; } @@ -990,7 +1058,15 @@ fn nudge_of(press: &Press) -> Option { /// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). A request /// that acts on a disabled node is dropped before it moves focus. -fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, routed: &mut HashMap, Routed>, activated: &mut IdMap) { +fn route_access( + ctx: &Context, + request: &Action, + nodes: &HashMap, + routed: &mut HashMap, Routed>, + activated: &mut IdMap, + scalar_rows: &[scalar::ScalarRow], + press_captured: bool, +) { let Some(node) = nodes.get(&request.node()).copied() else { return }; if !node.enabled && request.acts() { return; @@ -1001,6 +1077,16 @@ fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, rou let target = node.part.map_or(focus::FocusTarget::Id(node.owner), |part| focus::FocusTarget::Part(node.owner, part)); focus::request_now(ctx, target); } + if matches!(request.kind(), ActionKind::Increment | ActionKind::Decrement) + && (node.part.is_none() || node.focusable) + && let Some(row) = scalar_rows.iter().find(|row| node.owner == row.slider || Some(node.owner) == row.editor) + { + if !scalar::captured(ctx, press_captured) && scalar::allowed(ctx, row) { + let movement = if matches!(request.kind(), ActionKind::Increment) { NavMove::Forward } else { NavMove::Back }; + routed.entry(Some(row.owner)).or_default().scalar_moves.push((movement, MoveMods::PLAIN)); + } + return; + } match request.kind() { ActionKind::Focus if node.focusable => {} ActionKind::Expand | ActionKind::Collapse if node.expanded.is_some() => { diff --git a/crates/ui-contract/src/runtime/keys/scalar.rs b/crates/ui-contract/src/runtime/keys/scalar.rs new file mode 100644 index 0000000000..a342848c5e --- /dev/null +++ b/crates/ui-contract/src/runtime/keys/scalar.rs @@ -0,0 +1,193 @@ +//! Optional scalar-row key interest. Geometry and real stops come from the ordinary component pass. + +use super::{current, route}; +use crate::runtime::egui::LayerId; +use crate::runtime::egui::areas; +use crate::runtime::focus::{self, StopRec}; +use crate::runtime::pointer; +use craft_behavior::{KeyOwner, MoveMods, NavMove, OwnerClass}; +use egui::{Context, Id, Rect}; + +/// Which real scalar row can take a vertical arrow, without moving keyboard focus. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum ScalarKeyTrigger { + /// Only the row whose slider has keyboard focus. + #[default] + Focused, + /// The first drawn eligible row: its slider has focus, or its clipped whole row is hovered. + HoveredOrFocused, +} + +/// Opt-in additive model-unit vertical-key and accessibility nudges. +/// +/// Pointer, typed-value and wheel quantization keep their original steps. The widget snaps the result of the +/// addition to its original value grid, not a new grid based on `nudge`. A policy is optional: omitting it keeps +/// the existing slider behavior. Non-positive or non-finite amounts make the policy inactive. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScalarKeyPolicy { + nudge: f64, + shift_factor: f64, + trigger: ScalarKeyTrigger, + model_step: Option, +} + +impl ScalarKeyPolicy { + /// A focused-row policy, with Shift multiplying the additive nudge by five. + pub const fn new(nudge: f64) -> Self { + Self { nudge, shift_factor: 5.0, trigger: ScalarKeyTrigger::Focused, model_step: None } + } + + /// Chooses whether whole-row hover also makes a row eligible. This never changes focus. + pub const fn trigger(mut self, trigger: ScalarKeyTrigger) -> Self { + self.trigger = trigger; + self + } + + /// Sets the multiplier used by Shift. This does not change any global or wheel step multiplier. + pub const fn shift_factor(mut self, factor: f64) -> Self { + self.shift_factor = factor; + self + } + + /// Selects an explicit zero-origin model grid for scalar keys and accessibility actions only. + /// The final value is rounded to a multiple of `step`, then clamped to the slider bounds, before any edit event. + /// This does not change the additive nudge or pointer, wheel, horizontal-key, or numeric-editor quantization. + /// By default no model grid is selected: the original track grid and its on-grid bit preservation stay unchanged. + /// Non-positive or non-finite steps make this optional scalar policy inactive. + pub const fn model_step(mut self, step: f64) -> Self { + self.model_step = Some(step); + self + } + + /// The optional model grid used by the SDK component's scalar landing, not its input routing or other paths. + #[doc(hidden)] + pub const fn model_quantum(self) -> Option { + self.model_step + } + + /// Whether the amounts and any selected model step describe usable, finite positive changes. + pub fn is_valid(self) -> bool { + self.nudge.is_finite() + && self.nudge > 0.0 + && self.shift_factor.is_finite() + && self.shift_factor > 0.0 + && (self.nudge * self.shift_factor).is_finite() + && self.nudge * self.shift_factor > 0.0 + && self.model_step.is_none_or(|step| step.is_finite() && step > 0.0) + } + + /// The unmodified model-unit accessibility increment. + pub fn amount(self) -> Option { + self.is_valid().then_some(self.nudge) + } + + /// An additive offset for vertical keys or accessibility increment/decrement (Forward/Back). + pub fn offset(self, movement: NavMove, modifiers: MoveMods) -> Option { + let direction = match movement { + NavMove::Up | NavMove::Forward => 1.0, + NavMove::Down | NavMove::Back => -1.0, + _ => return None, + }; + self.amount().map(|amount| direction * amount * if modifiers.extend { self.shift_factor } else { 1.0 }) + } +} + +/// SDK component metadata for one real scalar row. It creates no widget or focus stop. +#[doc(hidden)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScalarRow { + pub(super) owner: Id, + pub(super) slider: Id, + pub(super) editor: Option, + rect: Rect, + layer: LayerId, + policy: ScalarKeyPolicy, +} + +impl crate::runtime::Shift for ScalarRow { + fn shifted(&self, by: &egui::RecordShift) -> Self { + ScalarRow { rect: by.rect(self.rect), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + ScalarRow { rect: self.rect.snapped(&to.rect, within), ..*self } + } +} + +impl ScalarRow { + /// Uses the component's clipped allocated rect and the actual slider stop's owner. + pub fn new(owner: Id, slider: Id, policy: ScalarKeyPolicy, rect: Rect, layer: LayerId) -> Self { + Self { owner, slider, editor: None, rect, layer, policy } + } + + /// Associates the real numeric child for accessibility increment/decrement; focused typing keeps its keys. + pub fn editor(mut self, editor: Id) -> Self { + self.editor = Some(editor); + self + } +} + +/// Records opt-in interest in component draw order, exactly like the ordinary stop/node records. +#[doc(hidden)] +pub fn register_scalar(ctx: &Context, row: ScalarRow) { + if crate::runtime::measure::active(ctx) || !row.policy.is_valid() || !row.rect.is_positive() { + return; + } + crate::runtime::replay::journal(ctx, || row, |ctx, row| register_scalar(ctx, *row)); + current(ctx, |stage| stage.scalar_rows.push(row)); +} + +/// A captured gesture wins even over a different row; no raw pointer/key path bypasses that ownership. +pub(super) fn captured(ctx: &Context, press_captured: bool) -> bool { + press_captured || pointer::with_pass_pointer(ctx, |pointer| pointer.primary_down) +} + +/// Only rows whose real stop is allowed by the canonical popup/modal owner can act. +pub(super) fn allowed(ctx: &Context, row: &ScalarRow) -> bool { + focus::stop_rec(ctx, (row.slider, None)).is_some_and(|record| { + matches!( + route::owner_at(ctx, Some(&record), &focus::scope_chain(ctx, &record), None), + KeyOwner::Class(OwnerClass::Widget | OwnerClass::Dialog) + ) + }) +} + +/// The focused row wins over a hovered one. Hover takes the arrows only where the focus leaves them, and source order +/// resolves the remaining rows. +pub(super) fn choose(ctx: &Context, rows: &[ScalarRow], focused: Option<&StopRec>, press_captured: bool) -> Option { + if rows.is_empty() || captured(ctx, press_captured) + // A real native editor/widget without a framework stop still owns its focused editing keys. + || (focused.is_none() && crate::runtime::egui::focus::focused(ctx).is_some()) + || focused.is_some_and(|record| { + record.stop.text || !matches!(route::owner_at(ctx, Some(record), &focus::scope_chain(ctx, record), None), + KeyOwner::Class(OwnerClass::Widget | OwnerClass::Dialog | OwnerClass::App)) + || crate::runtime::ime::composing(ctx, record.stop.root) + }) + { + return None; + } + let is_focused = |row: &ScalarRow| focused.is_some_and(|record| record.stop.id == row.slider || record.stop.root == row.slider); + if let Some(row) = rows.iter().find(|row| is_focused(row) && allowed(ctx, row)).copied() { + return Some(row); + } + // A hovered row never takes Up and Down from a focused component that acts on the arrow moves itself: a + // collection declares them in its key role, a select or a menu in its key use, and the stop's role holds both. + if focused.is_some_and(|record| record.stop.role.moves) { + return None; + } + let pointer = pointer::with_pass_pointer(ctx, |pointer| pointer.hover); + rows.iter() + .find(|row| { + row.policy.trigger == ScalarKeyTrigger::HoveredOrFocused + && pointer.is_some_and(|point| { + let local = areas::layer_map(ctx, row.layer).map_or(point, |map| map.to_layer(point)); + row.rect.contains(local) + && pointer::with_hover(ctx, crate::runtime::egui::pass::current_viewport(ctx), |under, _| { + under.is_some_and(|under| under.contains(row.owner)) + }) + }) + && allowed(ctx, row) + }) + .copied() +} diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 7f253e1d3a..b3815c4bc9 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -209,15 +209,16 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { // take the wheel by position. let by_position = wheel_in.is_some() && hover.is_some_and(|at| focus::popup_above_focus(ctx, at) || hole.as_ref().is_some_and(|hole| hole.answers(at))); - let pressed_on = pass_pointer - .events - .iter() - .rev() - .find_map(|event| match event { - PointerEvent::Pressed { button: PointerButton::Primary, pos, .. } => Some(*pos), + let last_press = pass_pointer.events.iter().rposition(|event| matches!(event, PointerEvent::Pressed { button: PointerButton::Primary, .. })); + let pressed_on = last_press + .and_then(|at| match pass_pointer.events[at] { + PointerEvent::Pressed { pos, .. } => Some(pos), _ => None, }) .map(|at| pointer::press_winner(ctx, at, pass_pointer.press_targets).map(|(winner, _)| winner.owner)); + // The pointer's path through the pass after the press that may arm a control: a slow frame merges a move out of + // the control and back into one pass, which still leaves it. + let path = &pass_pointer.events[last_press.map_or(0, |at| at + 1)..]; // A modal layer holds the wheel, except over the canvas it keeps open and inside its own family. let blocked = hover.is_some_and(|at| !sampler::wheel_allowed(ctx, at)); let modal_family = crate::runtime::overlay::top_modal_in(ctx, viewport) @@ -231,13 +232,14 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.armed = winner.filter(|id| state.last.iter().any(|taker| taker.gated && taker.owner == *id)); } if let Some(armed) = state.armed { - let inside = state - .last - .iter() - .find(|taker| taker.owner == armed) - .zip(hover) - .is_some_and(|(taker, at): (&WheelTaker, Pos2)| taker.rect.contains(at)); - if !inside { + let rect = state.last.iter().find(|taker| taker.owner == armed).map(|taker| taker.rect); + let inside = rect.zip(hover).is_some_and(|(rect, at): (egui::Rect, Pos2)| rect.contains(at)); + let left = path.iter().any(|event| match event { + PointerEvent::Moved { at, .. } => rect.is_none_or(|rect| !rect.contains(*at)), + PointerEvent::Gone => true, + _ => false, + }); + if !inside || left { state.armed = None; } } diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index efa12ac5cf..c5b9aa0f4e 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -4,14 +4,15 @@ pub(crate) mod stories; use crate::contract::{ - Bind, BindCheck, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, MeasureCx, Outcome, PaintUi, Props as _, Role, SideLabel, - Sizing, Validity, WordSetCx as _, + Bind, BindCheck, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, Focus as _, MeasureCx, Outcome, PaintUi, Props as _, Role, + SideLabel, Sizing, Validity, WordSetCx as _, }; use crate::runtime::env::{Label, UnitKind}; +use crate::runtime::keys::{ScalarKeyPolicy, ScalarRow, register_scalar}; use crate::style::{ComponentStyle, StyleCx}; use crate::text::{NumberField, RangeAlert}; use crate::value_drag::{Slider, SliderScale, SliderThumb, TrackFace, TrackPress}; -use craft_behavior::{Flow, Metrics, Mixed, Proposal, Sense, decimals_for_step}; +use craft_behavior::{Flow, Metrics, Mixed, NumberCodec, Proposal, Sense, decimals_for_step}; use egui::{Rect, Response, Vec2, pos2}; use std::ops::{Deref, RangeInclusive}; @@ -68,13 +69,13 @@ pub struct SliderFieldStyle { /// /// The step moves the slider's keys and wheel and the field's keys, wheel and scrub; typed values snap to it unless /// `typed_decimals` sets their independent precision. Without a step the field steps by a hundredth on a range 10 wide -/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field shows -/// its own look's decimals (for a percent, its step's up to one) unless `field_decimals` asks for the step's or a fixed -/// count, which leaves typing's snap to the step as it was; a scrub keeps the step's decimals either way, so a field -/// showing whole numbers over a hundredth step still moves by hundredths. The field and the slider are Tab stops in the -/// order they are read: the field and then the slider when stacked, the slider and then the field when inline. A click -/// on the row's label focuses the number field in either layout. A log or power scale curves the slider's track only: -/// the field, typing and steps stay linear. +/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. An explicit +/// `number_codec` controls the display; otherwise the field shows its own look's decimals (for a percent, its step's up +/// to one) unless `field_decimals` asks for the step's or a fixed count. That choice leaves typing's snap to the step as +/// it was. A scrub keeps the step's precision even when the field shows fewer places, so a field showing whole numbers +/// over a hundredth step still moves by hundredths. The field and the slider are Tab stops in the order they are read: +/// the field then the slider when stacked, the slider then the field when inline. Clicking the label focuses the number +/// field in either layout. A log, power or custom scale curves only the track: field, typing and steps stay in model units. #[derive(crate::contract::Component, crate::contract::Props)] pub struct SliderField<'a> { #[common] @@ -88,6 +89,10 @@ pub struct SliderField<'a> { /// How positions along the slider's track map to values. #[prop] scale: SliderScale, + /// The number field's codec. Without one it reads and writes using the environment's locale and unit kind. + /// Range limits, typed-value snapping and model-unit steps still belong to this slider field. + #[prop] + number_codec: Option, /// The change of one arrow press, wheel notch or label scrub point, and by default the grid typed values snap to. #[prop(quantity = "step")] step: Option, @@ -105,6 +110,22 @@ pub struct SliderField<'a> { /// When a press on the slider's track sets the value (`Slider::track_press`): on its release or drag by default. #[prop] track_press: TrackPress, + /// The change per point of a scrub on the number field or its caption, in the field's shown units + /// (`NumberField::scrub_step`), in place of the field's step: the range over the track's width moves the value as + /// far as the same drag on the slider's thumb. An omitted, non-positive or non-finite rate scrubs by the step. + #[prop(quantity = "step")] + scrub_step: Option, + /// Optional independent vertical-key and accessibility nudges for the full clipped row, including its caption. + /// Its focused numeric child keeps the normal editor precedence and its original typing/wheel properties. + #[prop] + key_policy: Option, + /// Pointer sensitivity bindings forwarded to the real slider and numeric/label scrub; not key/wheel policy. + #[prop] + pointer_modifiers: craft_behavior::DragModifiers, + /// Optional zero-origin model grid for this field's real slider pointer values, not its numeric/label editor. + /// None preserves original pointer snapping. Keys, wheel and accessibility keep their independent policies. + #[prop(quantity = "step")] + pointer_model_step: Option, /// What the number counts: the field shows its unit and reads its spellings. #[prop] unit_kind: Option, @@ -180,11 +201,16 @@ impl<'a> SliderField<'a> { range, layout: SliderFieldLayout::Stacked, scale: SliderScale::Linear, + number_codec: None, step: None, typed_decimals: None, field_decimals: FieldDecimals::Look, wheel_step: None, track_press: TrackPress::OnRelease, + scrub_step: None, + key_policy: None, + pointer_modifiers: craft_behavior::DragModifiers::default(), + pointer_model_step: None, unit_kind: None, unit: None, fill: true, @@ -220,10 +246,15 @@ impl<'a> SliderField<'a> { track_press: self.track_press, range: self.range.clone(), scale: self.scale, + number_codec: self.number_codec.clone(), step: self.step, typed_decimals: self.typed_decimals, field_decimals: self.field_decimals, wheel_step: self.wheel_step, + scrub_step: self.scrub_step, + key_policy: self.key_policy, + pointer_modifiers: self.pointer_modifiers, + pointer_model_step: self.pointer_model_step, unit_kind: self.unit_kind, unit: self.unit.clone(), fill: self.fill, @@ -251,10 +282,15 @@ struct Look { track_press: TrackPress, range: RangeInclusive, scale: SliderScale, + number_codec: Option, step: Option, typed_decimals: Option, field_decimals: FieldDecimals, wheel_step: Option, + scrub_step: Option, + key_policy: Option, + pointer_modifiers: craft_behavior::DragModifiers, + pointer_model_step: Option, unit_kind: Option, unit: Option