mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 09:46:29 +01:00
Merge pull request #3271
This commit is contained in:
commit
e8bb26145d
25 files changed
+2612
-73
No files matched your search
@@ -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<dyn Fn(&str) -> Option<f64> + 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<Custom>,
|
||||
/// An authoritative reader for the complete, trimmed, non-empty input.
|
||||
primary: Option<Custom>,
|
||||
/// 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<f64> + 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));
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<DragModifier>,
|
||||
coarse: Option<DragModifier>,
|
||||
}
|
||||
|
||||
impl DragModifiers {
|
||||
/// Selects the fine and coarse bindings; `None` disables that binding.
|
||||
pub const fn new(fine: Option<DragModifier>, coarse: Option<DragModifier>) -> 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<f64>,
|
||||
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<f32>, range: RangeInclusive<f64>) -> 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<f64>) -> 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)
|
||||
|
||||
@@ -362,6 +362,10 @@ pub struct WheelTaker<O> {
|
||||
/// 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<O> WheelTaker<O> {
|
||||
vertical: false,
|
||||
zoom: false,
|
||||
gated: false,
|
||||
directional: false,
|
||||
scrolls: false,
|
||||
notch: WheelNotch::DEFAULT,
|
||||
room: None,
|
||||
@@ -497,6 +502,14 @@ impl<O> WheelTaker<O> {
|
||||
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<O: Copy + PartialEq>(
|
||||
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<O: Copy + PartialEq>(
|
||||
// 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<O>> = 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<O>| (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner);
|
||||
let open = |taker: &WheelTaker<O>| {
|
||||
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<O>> = latch
|
||||
.flatten()
|
||||
.and_then(|owner| takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && focused == Some(taker.owner))));
|
||||
let held: Option<&WheelTaker<O>> = 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<O>| 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<O: Copy + PartialEq>(
|
||||
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<u8>], at: Pos2, wheel: Wheel, focus: Option<u8>, armed: Option<u8>) -> (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)));
|
||||
}
|
||||
}
|
||||
@@ -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<f64> {
|
||||
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)));
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod canvas_view;
|
||||
mod cells;
|
||||
mod codec_override;
|
||||
mod digit_keys;
|
||||
mod dock;
|
||||
mod dock_apply;
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Item>,
|
||||
/// Scalar-row moves selected by the canonical router, distinct from ordinary focused navigation.
|
||||
scalar_moves: Vec<(NavMove, MoveMods)>,
|
||||
nudge: Option<Nudge>,
|
||||
/// The chords a recorder stop's presses spell this pass.
|
||||
chords: Vec<Chord>,
|
||||
@@ -328,6 +335,8 @@ pub(crate) struct Stage {
|
||||
layout: Layout,
|
||||
nodes: HashMap<u64, Node>,
|
||||
last_nodes: HashMap<u64, Node>,
|
||||
/// Opt-in real rows declared this pass; taken at the next begin, so unmounted rows cannot accumulate.
|
||||
scalar_rows: Vec<scalar::ScalarRow>,
|
||||
activated: IdMap<Id>,
|
||||
alt: AltTrack,
|
||||
/// The keys down now, as the input hook read them before it withheld any press.
|
||||
|
||||
@@ -17,6 +17,8 @@ pub struct Intents {
|
||||
/// one has none.
|
||||
sources: Vec<Option<Source>>,
|
||||
took_arrows: Vec<NavMove>,
|
||||
scalar_moves: Vec<((NavMove, MoveMods), bool)>,
|
||||
scalar_at: usize,
|
||||
nudge: Option<Nudge>,
|
||||
chords: Vec<Chord>,
|
||||
set_value: Option<(Option<PartRef>, 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<Id>, 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<Id>, 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;
|
||||
}
|
||||
|
||||
@@ -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<Option<Id>, 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<bool> = 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<Option<Id>, Routed>,
|
||||
consumed: &mut [Taken],
|
||||
) -> Vec<bool> {
|
||||
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<bool>) {
|
||||
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<bool> = 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<Nudge> {
|
||||
|
||||
/// 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<u64, Node>, routed: &mut HashMap<Option<Id>, Routed>, activated: &mut IdMap<Id>) {
|
||||
fn route_access(
|
||||
ctx: &Context,
|
||||
request: &Action,
|
||||
nodes: &HashMap<u64, Node>,
|
||||
routed: &mut HashMap<Option<Id>, Routed>,
|
||||
activated: &mut IdMap<Id>,
|
||||
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<u64, Node>, 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() => {
|
||||
|
||||
@@ -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<f64>,
|
||||
}
|
||||
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<Id>,
|
||||
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<ScalarRow> {
|
||||
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()
|
||||
}
|
||||
@@ -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<Id>, 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<NumberCodec>,
|
||||
/// 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<f64>,
|
||||
@@ -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<f64>,
|
||||
/// 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<ScalarKeyPolicy>,
|
||||
/// 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<f64>,
|
||||
/// What the number counts: the field shows its unit and reads its spellings.
|
||||
#[prop]
|
||||
unit_kind: Option<UnitKind>,
|
||||
@@ -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<f64>,
|
||||
scale: SliderScale,
|
||||
number_codec: Option<NumberCodec>,
|
||||
step: Option<f64>,
|
||||
typed_decimals: Option<usize>,
|
||||
field_decimals: FieldDecimals,
|
||||
wheel_step: Option<f64>,
|
||||
scrub_step: Option<f64>,
|
||||
key_policy: Option<ScalarKeyPolicy>,
|
||||
pointer_modifiers: craft_behavior::DragModifiers,
|
||||
pointer_model_step: Option<f64>,
|
||||
unit_kind: Option<UnitKind>,
|
||||
unit: Option<Label>,
|
||||
fill: bool,
|
||||
@@ -296,7 +332,12 @@ impl Look {
|
||||
.fill(self.fill)
|
||||
.thumb(self.thumb)
|
||||
.short(self.short)
|
||||
.label(name.clone());
|
||||
.label(name.clone())
|
||||
.pointer_modifiers(self.pointer_modifiers);
|
||||
let slider = match self.pointer_model_step {
|
||||
Some(step) => slider.pointer_model_step(step),
|
||||
None => slider,
|
||||
};
|
||||
let slider = match &self.marks {
|
||||
Some(FieldMarks::Plain(marks)) => slider.marks(marks),
|
||||
Some(FieldMarks::Labelled(marks)) => slider.marks_labelled(marks.iter().cloned()),
|
||||
@@ -310,6 +351,10 @@ impl Look {
|
||||
Some(step) => slider.step(step),
|
||||
None => slider,
|
||||
};
|
||||
let slider = match self.key_policy.filter(|policy| policy.is_valid()) {
|
||||
Some(policy) => slider.delegated_scalar(policy),
|
||||
None => slider,
|
||||
};
|
||||
match self.wheel_step {
|
||||
Some(step) => slider.wheel_step(step),
|
||||
None => slider,
|
||||
@@ -336,7 +381,17 @@ impl Look {
|
||||
.step(step)
|
||||
.snap_typed(typed_decimals.is_none() && self.set_step().is_some())
|
||||
.commit_decimals(typed_decimals.unwrap_or_else(|| decimals_for_step(step)))
|
||||
.scrub_by_label();
|
||||
.scrub_by_label()
|
||||
.pointer_modifiers(self.pointer_modifiers)
|
||||
.scalar_access_step(self.key_policy.and_then(ScalarKeyPolicy::amount).unwrap_or(0.0));
|
||||
let field = match self.scrub_step {
|
||||
Some(rate) => field.scrub_step(rate),
|
||||
None => field,
|
||||
};
|
||||
let field = match &self.number_codec {
|
||||
Some(codec) => field.codec(codec.clone()),
|
||||
None => field,
|
||||
};
|
||||
let field = match typed_decimals {
|
||||
Some(decimals) => field.max_decimals(decimals),
|
||||
None => field,
|
||||
@@ -402,7 +457,8 @@ impl Component for SliderField<'_> {
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
// Hover-only geometry belongs to this real row, not a new focus stop or input proxy.
|
||||
if self.key_policy.is_some_and(ScalarKeyPolicy::is_valid) { Sense::HOVER } else { Sense::empty() }
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
@@ -429,6 +485,22 @@ impl Component for SliderField<'_> {
|
||||
craft_behavior::same_in_f32(*proposed, *host)
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let Some(policy) = self.key_policy.filter(|policy| policy.is_valid()) else { return };
|
||||
let helper = self.look().slider(&cx.label(), shown_of(cx.value()), None, None);
|
||||
while let Some((movement, modifiers)) = cx.intents().take_scalar_move() {
|
||||
if !cx.resolved.enabled || cx.resolved.read_only || (cx.gesture().is_some() && !cx.in_wheel_run()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(next) = helper.scalar_nudged(policy, cx.value().copied(), movement, modifiers) {
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
}
|
||||
cx.set(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let shown = shown_of(cx.value());
|
||||
let name = cx.label();
|
||||
@@ -486,6 +558,15 @@ impl Component for SliderField<'_> {
|
||||
}
|
||||
});
|
||||
cx.adopt(&dragged, &start, |value, mine| *mine = *value);
|
||||
if cx.resolved.enabled
|
||||
&& !cx.resolved.read_only
|
||||
&& let Some(policy) = self.key_policy.filter(|policy| policy.is_valid())
|
||||
{
|
||||
register_scalar(
|
||||
&cx.core.ctx,
|
||||
ScalarRow::new(cx.id, dragged.response.id, policy, cx.visible, cx.response.layer_id).editor(typed.response.id),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> SliderFieldOutput {
|
||||
|
||||
@@ -169,6 +169,13 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
|
||||
/// ladder); the step is ignored for them. The range still holds the result.
|
||||
#[prop(func = "Fn(f64, i32, f64) -> f64")]
|
||||
stepper: Option<NumberStepper<'a>>,
|
||||
/// A composite may route AX increment/decrement in separate model units; editing/typing/wheel still use step.
|
||||
/// Zero (or a non-finite amount) leaves the rule's step.
|
||||
#[prop(quantity = "step", vis = "pub(crate)")]
|
||||
scalar_access_step: f64,
|
||||
/// Pointer-only fine/coarse bindings for the field, label and popup-slider scrubs.
|
||||
#[prop]
|
||||
pointer_modifiers: craft_behavior::DragModifiers,
|
||||
/// A unit shown after the number.
|
||||
#[prop(into)]
|
||||
unit: Option<Label>,
|
||||
@@ -294,6 +301,8 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
step: None,
|
||||
scrub_step: None,
|
||||
stepper: None,
|
||||
scalar_access_step: 0.0,
|
||||
pointer_modifiers: craft_behavior::DragModifiers::default(),
|
||||
unit: None,
|
||||
unit_placement: UnitPlacement::Inside,
|
||||
step_arrows: StepArrows::Hidden,
|
||||
@@ -856,7 +865,12 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
fn scrub(&self) -> Option<Scrub<V>> {
|
||||
let rule = self.rule();
|
||||
let step = self.scrub_step.filter(|step| step.is_finite() && *step > 0.0).unwrap_or(rule.step);
|
||||
let drag = ValueDrag::relative(step, rule.bounds()).warp(true).hide_cursor(true).coarse(LARGE_STEPS).fine(1.0 / LARGE_STEPS);
|
||||
let drag = ValueDrag::relative(step, rule.bounds())
|
||||
.warp(true)
|
||||
.hide_cursor(true)
|
||||
.coarse(LARGE_STEPS)
|
||||
.fine(1.0 / LARGE_STEPS)
|
||||
.modifiers(self.pointer_modifiers);
|
||||
// Rounded to the field's decimals, and to the step's where the step needs more, so a scrubbed value carries no
|
||||
// float noise and keeps the step's precision even where the field shows fewer decimals: a field of hundredths
|
||||
// that shows no decimals still moves by a hundredth, not by nothing. The step is not a grid here: an Alt drag
|
||||
@@ -874,7 +888,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
if let Some(range) = self.popup_slider.as_ref().filter(|_| self.track > 0.0) {
|
||||
let shown = range.start() * scale..=range.end() * scale;
|
||||
let rate = (shown.end() - shown.start()) / f64::from(self.track);
|
||||
scrub = scrub.part(SLIDER, ValueDrag::relative(rate, shown));
|
||||
scrub = scrub.part(SLIDER, ValueDrag::relative(rate, shown).modifiers(self.pointer_modifiers));
|
||||
}
|
||||
Some(scrub)
|
||||
}
|
||||
@@ -973,7 +987,8 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
Some(value) => Numeric::new(value, rule.bounds()),
|
||||
None => Numeric::empty(rule.bounds()),
|
||||
};
|
||||
access.numeric(numeric.step(rule.step));
|
||||
let access_step = self.scalar_access_step;
|
||||
access.numeric(numeric.step(if access_step.is_finite() && access_step > 0.0 { access_step } else { rule.step }));
|
||||
if let Some(unit) = self.painted_unit(cx) {
|
||||
access.unit(cx.env.resolve(&unit).as_str());
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ pub(crate) mod thumb_row;
|
||||
pub(crate) mod track;
|
||||
mod words;
|
||||
|
||||
pub use crate::runtime::keys::{ScalarKeyPolicy, ScalarKeyTrigger};
|
||||
pub use angle_dial::{AngleDial, AngleDialStyle, AngleOrientation};
|
||||
pub use craft_behavior::{DragModifier, DragModifiers};
|
||||
pub use point_picker::{Backdrop, PointMark, PointPicker, PointPickerStyle, PointPickerWords, SamePoint};
|
||||
pub use range_slider::{RangeSlider, RangeSliderStyle};
|
||||
pub use slider::{Slider, SliderStyle, SliderThumb, TrackPress};
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::contract::{
|
||||
};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use crate::runtime::keys::{ScalarKeyPolicy, ScalarRow, register_scalar};
|
||||
use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceStyle, TextLook, TrackLook};
|
||||
use crate::text::NumberStepper;
|
||||
use craft_behavior::intent::{MoveMods, NavMove};
|
||||
@@ -62,6 +63,20 @@ struct Held {
|
||||
press: Option<Press>,
|
||||
}
|
||||
|
||||
/// The one zero-origin model grid both input policies land on: rounded to `step` from zero, then clamped to `bounds`.
|
||||
/// A step that is not finite and positive selects no grid.
|
||||
fn model_grid_landing(value: f64, step: f64, bounds: (f64, f64)) -> Option<f64> {
|
||||
if !(step.is_finite() && step > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let ticks = value / step;
|
||||
// A quantum below the value's representable resolution need not produce an infinite intermediate.
|
||||
let landed = if ticks.is_finite() { ticks.round() * step } else { value };
|
||||
let landed = if landed.is_finite() { landed } else { value };
|
||||
// Overflow reaches the finite bound; NaN has the same deterministic minimum landing as the key policy.
|
||||
Some(if landed.is_nan() { bounds.0 } else { landed.clamp(bounds.0, bounds.1) })
|
||||
}
|
||||
|
||||
/// A slider over `range`.
|
||||
#[derive(crate::contract::Component, crate::contract::Props)]
|
||||
pub struct Slider<'a> {
|
||||
@@ -99,6 +114,18 @@ pub struct Slider<'a> {
|
||||
/// down. Presses on the thumb and keyboard, wheel and editor input do not change.
|
||||
#[prop]
|
||||
track_press: TrackPress,
|
||||
/// Optional independent vertical-key and accessibility nudges. None keeps the existing key behavior.
|
||||
#[prop]
|
||||
key_policy: Option<ScalarKeyPolicy>,
|
||||
/// A SliderField declares the full real row; its child must not register a competing track-only row.
|
||||
scalar_delegate: bool,
|
||||
/// Continuous pointer fine/coarse bindings. Keyboard, wheel and accessibility steps are independent.
|
||||
#[prop]
|
||||
pointer_modifiers: craft_behavior::DragModifiers,
|
||||
/// Optional zero-origin model grid for thumb/track pointer values only. None keeps original track snapping.
|
||||
/// A non-positive or non-finite quantum is ignored. Keys, wheel, accessibility and editors are independent.
|
||||
#[prop(quantity = "step")]
|
||||
pointer_model_step: Option<f64>,
|
||||
/// The value as the caller words it ("50 %"), in place of the slider's own value text: the number in the step's
|
||||
/// decimals, in one decimal without a step, or at the local step's precision with a custom stepper. Assistive
|
||||
/// technology reads it, and so does a viewer that shows the value beside the slider.
|
||||
@@ -160,6 +187,10 @@ impl<'a> Slider<'a> {
|
||||
marks: Marks::default(),
|
||||
wheel_step: None,
|
||||
track_press: TrackPress::OnRelease,
|
||||
key_policy: None,
|
||||
scalar_delegate: false,
|
||||
pointer_modifiers: craft_behavior::DragModifiers::default(),
|
||||
pointer_model_step: None,
|
||||
value_text: None,
|
||||
track_face: None,
|
||||
trim: None,
|
||||
@@ -167,6 +198,23 @@ impl<'a> Slider<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The composite owns interest and consumes scalar moves; this child still paints its own real slider/AX node.
|
||||
pub(crate) fn delegated_scalar(mut self, policy: ScalarKeyPolicy) -> Self {
|
||||
self.key_policy = Some(policy);
|
||||
self.scalar_delegate = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds in model units, then uses the explicitly selected model grid or the unchanged original track grid.
|
||||
pub(crate) fn scalar_nudged(&self, policy: ScalarKeyPolicy, value: Option<f64>, movement: NavMove, modifiers: MoveMods) -> Option<f64> {
|
||||
let scale = self.track_scale();
|
||||
let offset = policy.offset(movement, modifiers)?;
|
||||
if let Some(step) = policy.model_quantum() {
|
||||
return model_grid_landing(value.unwrap_or_else(|| scale.middle()) + offset, step, (scale.min, scale.max));
|
||||
}
|
||||
Some(scale.snap(value.unwrap_or_else(|| scale.middle()) + offset))
|
||||
}
|
||||
|
||||
/// Values the thumb snaps to when a drag or a press brings it near, drawn as marks under the track. A mark outside
|
||||
/// the range is ignored. Keys and the wheel use the step only, so with a step the marks should lie on it.
|
||||
pub fn marks(mut self, marks: &[f64]) -> Self {
|
||||
@@ -304,7 +352,14 @@ impl Component for Slider<'_> {
|
||||
let travel = Travel { track: along.travel().min..along.travel().max, units: 0.0..=1.0, rtl };
|
||||
let pick = along.pick(false);
|
||||
let marks = &self.marks;
|
||||
let at = |position: f64| marks.snapped(&scale, length, position).unwrap_or_else(|| scale.snap(scale.at_position(position)));
|
||||
let at = |position: f64| {
|
||||
if let Some(next) = self.pointer_model_step.and_then(|step| {
|
||||
model_grid_landing(marks.snapped(&scale, length, position).unwrap_or_else(|| scale.at_position(position)), step, bounds)
|
||||
}) {
|
||||
return next;
|
||||
}
|
||||
marks.snapped(&scale, length, position).unwrap_or_else(|| scale.snap(scale.at_position(position)))
|
||||
};
|
||||
let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or_else(|| scale.middle());
|
||||
let press_at = |cx: &Cx<'_, Self>, x: f32| pick.press(&[along.x(scale.position(current(cx)))], x);
|
||||
// Multi-clicks keep the legacy track path: reset wins on Down, and a later drag
|
||||
@@ -350,14 +405,18 @@ impl Component for Slider<'_> {
|
||||
}
|
||||
PressPhase::Drag { .. } => {
|
||||
let held = cx.memory::<Held>().clone();
|
||||
if let Some(next) = held.press.and_then(|press_of| travel.value(press_of, held.from, &press, true)) {
|
||||
if let Some(next) =
|
||||
held.press.and_then(|press_of| travel.value_with_modifiers(press_of, held.from, &press, true, self.pointer_modifiers))
|
||||
{
|
||||
cx.propose(at(next));
|
||||
}
|
||||
}
|
||||
PressPhase::Release { start, click, .. } => {
|
||||
if cx.gesture().is_some() {
|
||||
let held = cx.memory::<Held>().clone();
|
||||
if let Some(next) = held.press.and_then(|press_of| travel.value(press_of, held.from, &press, true)) {
|
||||
if let Some(next) =
|
||||
held.press.and_then(|press_of| travel.value_with_modifiers(press_of, held.from, &press, true, self.pointer_modifiers))
|
||||
{
|
||||
cx.propose(at(next));
|
||||
}
|
||||
cx.commit();
|
||||
@@ -392,6 +451,19 @@ impl Component for Slider<'_> {
|
||||
cx.set(next);
|
||||
}
|
||||
}
|
||||
while let Some((movement, modifiers)) = cx.intents().take_scalar_move() {
|
||||
if pressing || !cx.resolved.enabled || cx.resolved.read_only {
|
||||
continue;
|
||||
}
|
||||
if let Some(policy) = self.key_policy.filter(|policy| policy.is_valid())
|
||||
&& let Some(next) = self.scalar_nudged(policy, cx.value().copied(), movement, modifiers)
|
||||
{
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
}
|
||||
cx.set(next);
|
||||
}
|
||||
}
|
||||
if let Some(next) = set_value {
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
@@ -421,11 +493,17 @@ impl Component for Slider<'_> {
|
||||
Some(value) => Numeric::new(*value, range),
|
||||
None => Numeric::empty(range),
|
||||
};
|
||||
if let Some(stepper) = &self.stepper {
|
||||
let can_step = |steps| ladder_value(stepper, &scale, cx.value().copied(), steps).is_some();
|
||||
access.numeric(numeric).variable_steps(can_step(1.0), can_step(-1.0));
|
||||
} else {
|
||||
access.numeric(numeric.step(scale.small()));
|
||||
// A stepper's ladder decides which ways the row can step, and a fixed step would contradict it; otherwise a key
|
||||
// policy's own amount is the step the row reports, else the scale's small step.
|
||||
match &self.stepper {
|
||||
Some(stepper) => {
|
||||
let can_step = |steps| ladder_value(stepper, &scale, cx.value().copied(), steps).is_some();
|
||||
access.numeric(numeric).variable_steps(can_step(1.0), can_step(-1.0));
|
||||
}
|
||||
None => {
|
||||
let step = self.key_policy.and_then(ScalarKeyPolicy::amount).unwrap_or_else(|| scale.small());
|
||||
access.numeric(numeric.step(step));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,6 +541,13 @@ impl Component for Slider<'_> {
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
if !self.scalar_delegate
|
||||
&& cx.resolved.enabled
|
||||
&& !cx.resolved.read_only
|
||||
&& let Some(policy) = self.key_policy.filter(|policy| policy.is_valid())
|
||||
{
|
||||
register_scalar(&cx.core.ctx, ScalarRow::new(cx.id, cx.id, policy, cx.visible, cx.response.layer_id));
|
||||
}
|
||||
let style = cx.style;
|
||||
let flow = cx.flow;
|
||||
let scale = self.track_scale();
|
||||
|
||||
@@ -320,7 +320,7 @@ pub(crate) fn paint(draw: &Draw<'_>, look: &TrackLook, along: Along, groove: Sty
|
||||
}
|
||||
|
||||
/// How positions along a slider's track map to values.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub enum SliderScale {
|
||||
/// Equal distances are equal changes.
|
||||
@@ -331,6 +331,42 @@ pub enum SliderScale {
|
||||
/// The value grows with the position raised to the exponent: above 1 the start edge gets more room, below 1 the
|
||||
/// end edge. The exponent must be positive.
|
||||
Power(f32),
|
||||
/// A caller's increasing, mutually inverse projection between model values and track positions. Each callback
|
||||
/// receives the ascending range bounds. `position(value, min, max)` returns a fraction from 0 to 1;
|
||||
/// `value_at(position, min, max)` returns a model value in the range. Both must map the endpoints to endpoints.
|
||||
///
|
||||
/// Only the track is curved: text, steps, wheel notches and accessibility remain in model units. Inputs and
|
||||
/// outputs are clamped to their ranges; a non-finite output falls back to the corresponding linear projection.
|
||||
/// The caller owns monotonicity and the inverse relationship; the widget does not sample or fit the curve.
|
||||
#[non_exhaustive]
|
||||
Custom {
|
||||
/// The track fraction for a model value.
|
||||
position: fn(f64, f64, f64) -> f64,
|
||||
/// The model value at a track fraction.
|
||||
value_at: fn(f64, f64, f64) -> f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl SliderScale {
|
||||
/// A caller's own projection: `position(value, min, max)` gives the track fraction, `value_at(position, min, max)`
|
||||
/// the model value. The variant is `#[non_exhaustive]`, so this is how a caller outside the crate builds one.
|
||||
#[must_use]
|
||||
pub const fn custom(position: fn(f64, f64, f64) -> f64, value_at: fn(f64, f64, f64) -> f64) -> Self {
|
||||
SliderScale::Custom { position, value_at }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for SliderScale {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (*self, *other) {
|
||||
(Self::Linear, Self::Linear) | (Self::Log, Self::Log) => true,
|
||||
(Self::Power(a), Self::Power(b)) => a == b,
|
||||
(Self::Custom { position: a, value_at: b }, Self::Custom { position: c, value_at: d }) => {
|
||||
std::ptr::fn_addr_eq(a, c) && std::ptr::fn_addr_eq(b, d)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The decimals of a track's value text when it has no step.
|
||||
@@ -356,7 +392,7 @@ impl Scale {
|
||||
debug_assert!(a.is_finite() && b.is_finite(), "a slider's range needs finite bounds, not {a}..={b}");
|
||||
let (min, max) = if a <= b { (a, b) } else { (b, a) };
|
||||
let fits = match kind {
|
||||
SliderScale::Linear => true,
|
||||
SliderScale::Linear | SliderScale::Custom { .. } => true,
|
||||
SliderScale::Power(k) => k.is_finite() && k > 0.0,
|
||||
SliderScale::Log => min > 0.0 && max > min,
|
||||
};
|
||||
@@ -378,6 +414,11 @@ impl Scale {
|
||||
SliderScale::Linear => linear,
|
||||
SliderScale::Power(k) => linear.powf(1.0 / f64::from(k)),
|
||||
SliderScale::Log => ((value.max(self.min) / self.min).ln() / (self.max / self.min).ln()).clamp(0.0, 1.0),
|
||||
SliderScale::Custom { position, .. } => {
|
||||
let value = self.place(value);
|
||||
let projected = position(value, self.min, self.max);
|
||||
if projected.is_finite() { projected.clamp(0.0, 1.0) } else { (value - self.min) / self.span() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,6 +429,14 @@ impl Scale {
|
||||
SliderScale::Linear => self.min + t * self.span(),
|
||||
SliderScale::Power(k) => self.min + t.powf(f64::from(k)) * self.span(),
|
||||
SliderScale::Log => self.min * (self.max / self.min).powf(t),
|
||||
SliderScale::Custom { value_at, .. } => {
|
||||
let t = if t.is_finite() { t } else { 0.0 };
|
||||
if self.span() <= 0.0 {
|
||||
return self.min;
|
||||
}
|
||||
let projected = value_at(t, self.min, self.max);
|
||||
if projected.is_finite() { self.place(projected) } else { self.min + t * self.span() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,6 +681,18 @@ impl Travel {
|
||||
/// grab moves the thumb by the pointer's travel, Shift ten times as far; a jump puts it at the pointer. Alt
|
||||
/// scales a drag finer when `fine`; a click passes false, so it lands where it points.
|
||||
pub fn value(&self, press: Press, from: f64, state: &PressState, fine: bool) -> Option<f64> {
|
||||
self.value_with_modifiers(press, from, state, fine, craft_behavior::DragModifiers::default())
|
||||
}
|
||||
|
||||
/// The same travel with caller-selected pointer bindings; clicks still land without fine scaling.
|
||||
pub fn value_with_modifiers(
|
||||
&self,
|
||||
press: Press,
|
||||
from: f64,
|
||||
state: &PressState,
|
||||
fine: bool,
|
||||
modifiers: craft_behavior::DragModifiers,
|
||||
) -> Option<f64> {
|
||||
let drag = if press.grabs() {
|
||||
let length = f64::from(self.track.end - self.track.start);
|
||||
let rate = if length > 0.0 { (self.units.end() - self.units.start()) / length } else { 0.0 };
|
||||
@@ -640,6 +701,6 @@ impl Travel {
|
||||
ValueDrag::absolute(self.track.clone(), self.units.clone())
|
||||
};
|
||||
let drag = if fine { drag } else { drag.fine(1.0) };
|
||||
drag.value(from, state, self.rtl)
|
||||
drag.modifiers(modifiers).value(from, state, self.rtl)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,16 @@ pub(crate) mod mark_labels;
|
||||
|
||||
pub(crate) mod dials;
|
||||
|
||||
pub(crate) mod codec_override;
|
||||
|
||||
pub(crate) mod custom_scale;
|
||||
|
||||
pub(crate) mod scalar_key_policy;
|
||||
|
||||
pub(crate) mod scalar_contracts;
|
||||
|
||||
pub(crate) mod slider_field_scrub;
|
||||
|
||||
pub(crate) mod thumb_row;
|
||||
|
||||
use craft_behavior::{EditEvent, MotionMode};
|
||||
@@ -552,3 +562,112 @@ fn a_slider_drag_on_a_given_value_runs_one_pass_a_frame() {
|
||||
assert!(model.get() > 50.0, "the drag moved the app's value");
|
||||
assert!(passes.iter().all(|&n| n == 1), "slider drag frames ran {passes:?} passes");
|
||||
}
|
||||
|
||||
/// A slow frame can merge the pointer's move out of an armed slider and back (or out of the window and back) into one
|
||||
/// pass: the slider still left, so the vertical wheel is disarmed though the pass ends with the pointer over it.
|
||||
#[trial]
|
||||
fn directional_slider_wheel_disarms_on_a_leave_and_return_within_one_frame() {
|
||||
use craft_ui::runtime::env::{WheelScope, with_env};
|
||||
for away in [pointer::moved(Pos2::new(400.0, 200.0)), pointer::gone()] {
|
||||
let value = RefCell::new(START);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
with_env(
|
||||
ui,
|
||||
|set| set.wheel = Some(WheelScope::Directional),
|
||||
|ui| {
|
||||
Slider::new(Bind::bound(&mut *value.borrow_mut()), 0.0..=100.0).step(1.0).label("Position").show_at(ui, FIELD);
|
||||
},
|
||||
);
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(3, &mut show);
|
||||
pointer::click(&mut frames, FIELD.center(), &mut show);
|
||||
let before = *value.borrow();
|
||||
frames.frame(vec![pointer::wheel(40.0)], &mut show);
|
||||
frames.idle(30, &mut show);
|
||||
assert!(*value.borrow() > before, "the press armed vertical wheel editing");
|
||||
let armed = *value.borrow();
|
||||
frames.frame(vec![away.clone(), pointer::moved(FIELD.center()), pointer::wheel(-80.0)], &mut show);
|
||||
frames.idle(30, &mut show);
|
||||
assert_eq!(*value.borrow(), armed, "the pointer left the slider within the frame ({away:?})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift asks for the sideways wheel rather than for a coarser step: one Shift-wheel notch over the directional slider
|
||||
/// moves it as far as one plain sideways notch.
|
||||
#[trial]
|
||||
fn directional_slider_shift_wheel_steps_one_plain_notch() {
|
||||
use craft_ui::runtime::env::{WheelScope, with_env};
|
||||
let edited_by = |modifiers: Modifiers, delta: Vec2, source: egui::MouseWheelSource| {
|
||||
let value = RefCell::new(START);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
with_env(
|
||||
ui,
|
||||
|set| set.wheel = Some(WheelScope::Directional),
|
||||
|ui| {
|
||||
Slider::new(Bind::bound(&mut *value.borrow_mut()), 0.0..=100.0).step(1.0).label("Position").show_at(ui, FIELD);
|
||||
},
|
||||
);
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(3, &mut show);
|
||||
frames.frame(vec![pointer::moved(FIELD.center())], &mut show);
|
||||
frames.frame(
|
||||
vec![egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta, phase: egui::TouchPhase::Move, modifiers, source }],
|
||||
&mut show,
|
||||
);
|
||||
frames.idle(30, &mut show);
|
||||
*value.borrow() - START
|
||||
};
|
||||
let sideways = edited_by(Modifiers::NONE, Vec2::new(40.0, 0.0), egui::MouseWheelSource::Trackpad);
|
||||
assert!(sideways > 0.0, "a plain sideways notch edits the value");
|
||||
let shifted = edited_by(Modifiers::SHIFT, Vec2::new(0.0, 40.0), egui::MouseWheelSource::Wheel);
|
||||
assert!(shifted > 0.0, "Shift-wheel edits the value");
|
||||
assert!(shifted <= sideways + 1.0, "Shift-wheel steps once, like a plain sideways notch: {shifted} against {sideways}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn directional_slider_wheel_disarms_on_leave_without_losing_keyboard_focus() {
|
||||
use craft_ui::runtime::env::{WheelScope, with_env};
|
||||
let value = RefCell::new(START);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
with_env(
|
||||
ui,
|
||||
|set| set.wheel = Some(WheelScope::Directional),
|
||||
|ui| {
|
||||
Slider::new(Bind::bound(&mut *value.borrow_mut()), 0.0..=100.0).step(1.0).label("Position").show_at(ui, FIELD);
|
||||
},
|
||||
);
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(3, &mut show);
|
||||
let sideways = |dx| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: Vec2::new(dx, 0.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
};
|
||||
frames.frame(vec![pointer::moved(FIELD.center())], &mut show);
|
||||
frames.frame(vec![sideways(40.0)], &mut show);
|
||||
frames.idle(30, &mut show);
|
||||
assert!(*value.borrow() > START, "a horizontal trackpad swipe edits without selecting");
|
||||
pointer::click(&mut frames, FIELD.center(), &mut show);
|
||||
let before = *value.borrow();
|
||||
frames.frame(vec![pointer::wheel(40.0)], &mut show);
|
||||
frames.idle(30, &mut show);
|
||||
assert!(*value.borrow() > before, "an explicit press arms vertical wheel editing");
|
||||
let before_leave = *value.borrow();
|
||||
frames.frame(vec![pointer::moved(Pos2::new(400.0, 200.0))], &mut show);
|
||||
frames.frame(vec![pointer::moved(FIELD.center())], &mut show);
|
||||
frames.frame(vec![pointer::wheel(-80.0)], &mut show);
|
||||
frames.idle(30, &mut show);
|
||||
assert_eq!(*value.borrow(), before_leave, "returning with keyboard focus does not rearm the wheel");
|
||||
frames.frame(vec![pointer::moved(Pos2::new(400.0, 200.0))], &mut show);
|
||||
frames.frame(
|
||||
vec![egui::Event::Key { key: Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }],
|
||||
&mut show,
|
||||
);
|
||||
frames.idle(2, &mut show);
|
||||
assert!(*value.borrow() > before_leave, "keyboard focus survives leaving the slider");
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! SliderField forwards an opt-in number codec without changing the default parser or numeric stepping.
|
||||
|
||||
use craft_behavior::{MotionMode, NumberCodec};
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
fn typed(codec: Option<NumberCodec>, text: &str, step: f64) -> (Fixture, Rc<RefCell<f64>>) {
|
||||
let value = Rc::new(RefCell::new(40.0));
|
||||
let held = Rc::clone(&value);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut value = held.borrow_mut();
|
||||
let field = SliderField::new("Mapped", Bind::bound(&mut *value), 0.0..=100.0).step(step);
|
||||
let field = match &codec {
|
||||
Some(codec) => field.number_codec(codec.clone()),
|
||||
None => field,
|
||||
};
|
||||
field.show(ui);
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).first().copied().expect("number field");
|
||||
fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text(text).key(Key::Enter, Modifiers::NONE).settle();
|
||||
(fixture, value)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn codec_override_slider_field_reads_absolute_plus_without_changing_default_relative_plus() {
|
||||
let (_, default) = typed(None, "+12", 1.0);
|
||||
assert_eq!(*default.borrow(), 52.0);
|
||||
let (mut fixture, value) = typed(Some(NumberCodec::default().parse_with(|text| text.parse().ok())), "+12", 1.0);
|
||||
assert_eq!(*value.borrow(), 12.0);
|
||||
let slider = fixture.by_role(Role::SLIDER).first().copied().expect("slider");
|
||||
assert_eq!(fixture.tree().numeric_of(slider.node).expect("numeric slider").value, Some(12.0));
|
||||
fixture.access(AccessActionKind::Focus, &slider).key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
assert_eq!(*value.borrow(), 13.0, "the typed domain value keeps model-unit nudges");
|
||||
let (_, stepped) = typed(Some(NumberCodec::default().parse_with(|text| text.parse().ok())), "12", 5.0);
|
||||
assert_eq!(*stepped.borrow(), 10.0, "typed values still snap to the slider field's step");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn codec_override_slider_field_keeps_rejected_input_from_the_model() {
|
||||
for text in ["1+2", "*2", "Auto", "NaN", "inf", "1.2.3", "1,2.3", ""] {
|
||||
let codec = NumberCodec::default().or_parse(|_| Some(77.0)).parse_with(|text| text.parse().ok());
|
||||
let (_, value) = typed(Some(codec), text, 1.0);
|
||||
assert_eq!(*value.borrow(), 40.0, "rejected whole input {text:?} must not land or fall through");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn codec_override_slider_field_retains_range_limits_with_a_domain_reader() {
|
||||
let codec = NumberCodec::default().parse_with(|text| text.strip_suffix(" widgets")?.parse().ok());
|
||||
let (_, value) = typed(Some(codec.clone()), "1000 widgets", 1.0);
|
||||
assert_eq!(*value.borrow(), 100.0, "typed domain values are still range-limited");
|
||||
let (_, value) = typed(Some(codec), "7 widgets", 1.0);
|
||||
assert_eq!(*value.borrow(), 7.0, "the complete custom grammar reaches the real field");
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Custom track projections are generic: model values and all non-pointer edits keep their units.
|
||||
|
||||
use craft_behavior::MotionMode;
|
||||
use craft_ui::contract::{Bind, Props as _, Role, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use craft_ui::value_drag::{Slider, SliderScale};
|
||||
use egui::{Id, Key, Modifiers, Pos2, Rect};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
const MIN: f64 = -20.0;
|
||||
const MAX: f64 = 180.0;
|
||||
const FIELD: Rect = Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(420.0, 50.0) };
|
||||
|
||||
// An arbitrary piecewise curve, not a product/unit-specific scale: the first fifth of the model range
|
||||
// occupies half the track; the rest grows quadratically. Exercise both sides and their shared midpoint.
|
||||
fn position(value: f64, min: f64, max: f64) -> f64 {
|
||||
assert!(min < max && (min..=max).contains(&value), "the widget bounds the callback input");
|
||||
let x = (value - min) / (max - min);
|
||||
if x <= 0.2 { x * 2.5 } else { 0.5 + 0.5 * ((x - 0.2) / 0.8).sqrt() }
|
||||
}
|
||||
|
||||
fn value_at(t: f64, min: f64, max: f64) -> f64 {
|
||||
assert!(min < max && (0.0..=1.0).contains(&t), "the widget bounds the callback input");
|
||||
let x = if t <= 0.5 { t * 0.4 } else { 0.2 + 0.8 * (2.0 * t - 1.0).powi(2) };
|
||||
min + x * (max - min)
|
||||
}
|
||||
|
||||
const CUSTOM: SliderScale = SliderScale::custom(position, value_at);
|
||||
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
value: Rc<RefCell<f64>>,
|
||||
id: Rc<Cell<Id>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(scale: SliderScale, range: std::ops::RangeInclusive<f64>, step: Option<f64>) -> Self {
|
||||
let value = Rc::new(RefCell::new(*range.start()));
|
||||
let id = Rc::new(Cell::new(Id::NULL));
|
||||
let (held, seen) = (Rc::clone(&value), Rc::clone(&id));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut value = held.borrow_mut();
|
||||
let slider = Slider::new(Bind::bound(&mut *value), range.clone()).scale(scale).label("Mapped");
|
||||
let slider = match step {
|
||||
Some(step) => slider.step(step),
|
||||
None => slider,
|
||||
};
|
||||
seen.set(slider.show_at(ui, FIELD).response.id);
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
Self { fixture, value, id }
|
||||
}
|
||||
|
||||
/// Sets the value, and runs a frame past the one that shows it: the thumb's bounds are read from last pass's
|
||||
/// shape record (`Fixture::part_rect`), and a settle may run only the one frame.
|
||||
fn set(&mut self, value: f64) {
|
||||
*self.value.borrow_mut() = value;
|
||||
self.fixture.settle().idle(1);
|
||||
}
|
||||
|
||||
/// The thumb's sensed bounds, as last pass recorded them.
|
||||
fn thumb(&self) -> Rect {
|
||||
self.fixture.part_rect(self.id.get(), Slider::THUMB).expect("the thumb's sensed bounds")
|
||||
}
|
||||
|
||||
fn at(&self, fraction: f64) -> Pos2 {
|
||||
let inset = self.thumb().width() / 2.0;
|
||||
Pos2::new(FIELD.left() + inset + fraction as f32 * (FIELD.width() - 2.0 * inset), FIELD.center().y)
|
||||
}
|
||||
|
||||
fn click(&mut self, fraction: f64) {
|
||||
let at = self.at(fraction);
|
||||
self.fixture.advance(1.0).click_at(at).settle();
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn custom_scale_positions_and_pointer_inverse_agree_across_the_midpoint() {
|
||||
let mut rig = Rig::new(CUSTOM, MIN..=MAX, None);
|
||||
for t in [0.0, 0.1, 0.25, 0.499, 0.5, 0.501, 0.65, 0.9, 1.0] {
|
||||
let value = value_at(t, MIN, MAX);
|
||||
rig.set(value);
|
||||
assert!((rig.thumb().center().x - rig.at(t).x).abs() < 0.001, "value {value} sits at {t}");
|
||||
rig.set(if t < 0.5 { MAX } else { MIN });
|
||||
rig.click(t);
|
||||
assert!((*rig.value.borrow() - value).abs() < 0.001, "position {t} gives {value}, got {}", rig.value.borrow());
|
||||
}
|
||||
rig.set(MIN - 100.0);
|
||||
assert!((rig.thumb().center().x - rig.at(0.0).x).abs() < 0.001);
|
||||
rig.set(MAX + 100.0);
|
||||
assert!((rig.thumb().center().x - rig.at(1.0).x).abs() < 0.001);
|
||||
let mut reversed = Rig::new(CUSTOM, MAX..=MIN, None);
|
||||
reversed.click(0.5);
|
||||
assert!((*reversed.value.borrow() - value_at(0.5, MIN, MAX)).abs() < 0.001, "callbacks receive ascending bounds");
|
||||
// A grabbed thumb uses the same inverse while crossing the join, not an absolute pointer jump.
|
||||
rig.set(value_at(0.4, MIN, MAX));
|
||||
let from = rig.thumb().center();
|
||||
let by = rig.at(0.7) - from;
|
||||
rig.fixture.advance(1.0).drag_at(from, by).settle();
|
||||
assert!((*rig.value.borrow() - value_at(0.7, MIN, MAX)).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn custom_scale_keys_wheel_and_accessibility_stay_in_model_units() {
|
||||
for step in [None, Some(5.0)] {
|
||||
let mut rig = Rig::new(CUSTOM, MIN..=MAX, step);
|
||||
rig.set(20.0);
|
||||
let target = rig.fixture.by_role(Role::SLIDER).first().copied().expect("slider");
|
||||
let numeric = rig.fixture.tree().numeric_of(target.node).expect("numeric slider");
|
||||
assert_eq!(numeric.value, Some(20.0));
|
||||
assert_eq!(numeric.range, MIN..=MAX);
|
||||
let small = step.unwrap_or((MAX - MIN) * 0.01);
|
||||
assert_eq!(numeric.step, Some(small));
|
||||
rig.fixture.access(AccessActionKind::Focus, &target).settle();
|
||||
rig.fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
assert_eq!(*rig.value.borrow(), 20.0 + small);
|
||||
rig.fixture.access(AccessActionKind::Increment, &target).settle();
|
||||
assert_eq!(*rig.value.borrow(), 20.0 + 2.0 * small);
|
||||
let before = *rig.value.borrow();
|
||||
let at = rig.thumb().center();
|
||||
rig.fixture.frame(vec![pointer::moved(at)]).frame(vec![pointer::wheel_lines(1.0)]).advance(1.0).settle();
|
||||
assert_eq!((*rig.value.borrow() - before).abs(), small, "one wheel notch is one model step");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn custom_scale_slider_field_types_and_reads_model_values() {
|
||||
let value = Rc::new(RefCell::new(20.0));
|
||||
let held = Rc::clone(&value);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
SliderField::new("Mapped", Bind::bound(&mut *held.borrow_mut()), MIN..=MAX).scale(CUSTOM).step(5.0).show(ui);
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).first().copied().expect("number field");
|
||||
fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text("135").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(*value.borrow(), 135.0);
|
||||
let slider = fixture.by_role(Role::SLIDER).first().copied().expect("slider");
|
||||
assert_eq!(fixture.tree().numeric_of(slider.node).expect("numeric slider").value, Some(135.0));
|
||||
fixture.access(AccessActionKind::Focus, &slider).key(Key::ArrowLeft, Modifiers::NONE).settle();
|
||||
assert_eq!(*value.borrow(), 130.0, "typing did not change the model-unit nudge");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn custom_scale_bounds_and_nonfinite_results_are_contained() {
|
||||
fn linear(value: f64, min: f64, max: f64) -> f64 {
|
||||
(value - min) / (max - min)
|
||||
}
|
||||
fn nan(_: f64, _: f64, _: f64) -> f64 {
|
||||
f64::NAN
|
||||
}
|
||||
fn infinity(_: f64, _: f64, _: f64) -> f64 {
|
||||
f64::INFINITY
|
||||
}
|
||||
fn below(_: f64, _: f64, _: f64) -> f64 {
|
||||
-1000.0
|
||||
}
|
||||
fn above(_: f64, _: f64, _: f64) -> f64 {
|
||||
1000.0
|
||||
}
|
||||
for (callback, expected) in [(nan as fn(f64, f64, f64) -> f64, 0.75), (infinity, 0.75), (below, 0.0), (above, 1.0)] {
|
||||
let mut rig = Rig::new(SliderScale::custom(callback, value_at), MIN..=MAX, None);
|
||||
rig.set(MIN + 0.75 * (MAX - MIN));
|
||||
assert!((rig.thumb().center().x - rig.at(expected).x).abs() < 0.001);
|
||||
let mut rig = Rig::new(SliderScale::custom(linear, callback), MIN..=MAX, None);
|
||||
rig.click(0.75);
|
||||
let expected_value = MIN + expected * (MAX - MIN);
|
||||
assert!((*rig.value.borrow() - expected_value).abs() < 0.001);
|
||||
}
|
||||
let mut singleton = Rig::new(CUSTOM, 42.0..=42.0, None);
|
||||
singleton.click(0.75);
|
||||
assert_eq!(*singleton.value.borrow(), 42.0);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn custom_scale_does_not_change_builtin_linear_power_or_log_tracks() {
|
||||
for (scale, range, value) in
|
||||
[(SliderScale::Linear, 0.0..=100.0, 50.0), (SliderScale::Power(2.0), 0.0..=100.0, 25.0), (SliderScale::Log, 1.0..=10000.0, 100.0)]
|
||||
{
|
||||
let mut rig = Rig::new(scale, range, None);
|
||||
rig.click(0.5);
|
||||
assert!((*rig.value.borrow() - value).abs() < 0.001, "{scale:?} midpoint");
|
||||
assert!((rig.thumb().center().x - rig.at(0.5).x).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Public scalar contracts: real sensed thumbs, not synthetic response coordinates.
|
||||
use craft_behavior::{CancelReason, EditEvent, MotionMode};
|
||||
use craft_ui::contract::{Bind, Props as _, Role, Show as _};
|
||||
use craft_ui::form::{SliderField, SliderFieldLayout};
|
||||
use craft_ui::runtime::edit::cancel_all;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use craft_ui::value_drag::{DragModifier, DragModifiers, Slider};
|
||||
use egui::{Id, Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const ROWS: [Rect; 2] =
|
||||
[Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(420.0, 90.0) }, Rect { min: Pos2::new(20.0, 120.0), max: Pos2::new(420.0, 190.0) }];
|
||||
fn fine_shift() -> DragModifiers {
|
||||
DragModifiers::new(Some(DragModifier::Shift), None)
|
||||
}
|
||||
|
||||
struct State {
|
||||
values: [[f64; 2]; 2],
|
||||
owner: usize,
|
||||
shown: bool,
|
||||
enabled: bool,
|
||||
read_only: bool,
|
||||
events: [Vec<EditEvent<f64>>; 2],
|
||||
}
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
state: Rc<RefCell<State>>,
|
||||
}
|
||||
impl Rig {
|
||||
fn new(fields: bool, policy: Option<DragModifiers>) -> Self {
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
values: [[50.0; 2]; 2],
|
||||
owner: 0,
|
||||
shown: true,
|
||||
enabled: true,
|
||||
read_only: false,
|
||||
events: [Vec::new(), Vec::new()],
|
||||
}));
|
||||
let held = Rc::clone(&state);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = held.borrow_mut();
|
||||
if !state.shown {
|
||||
return;
|
||||
}
|
||||
let owner = state.owner;
|
||||
ui.push_id(("scalar-model", owner), |ui| {
|
||||
let starts = state.values[owner];
|
||||
for (row, start) in starts.iter().copied().enumerate() {
|
||||
let mut value = start;
|
||||
let edit = if fields {
|
||||
let field = SliderField::new(if row == 0 { "Amount" } else { "Balance" }, Bind::bound(&mut value), 0.0..=100.0)
|
||||
.step(0.01)
|
||||
.layout(SliderFieldLayout::Stacked)
|
||||
.id_salt(row)
|
||||
.enabled(state.enabled)
|
||||
.read_only(state.read_only);
|
||||
let field = if row == 0 {
|
||||
match policy {
|
||||
Some(policy) => field.pointer_modifiers(policy),
|
||||
None => field,
|
||||
}
|
||||
} else {
|
||||
field
|
||||
};
|
||||
field.show_at(ui, ROWS[row]).edit
|
||||
} else {
|
||||
let slider = Slider::new(Bind::bound(&mut value), 0.0..=100.0)
|
||||
.step(0.01)
|
||||
.id_salt(row)
|
||||
.enabled(state.enabled)
|
||||
.read_only(state.read_only);
|
||||
let slider = if row == 0 {
|
||||
match policy {
|
||||
Some(policy) => slider.pointer_modifiers(policy),
|
||||
None => slider,
|
||||
}
|
||||
} else {
|
||||
slider
|
||||
};
|
||||
slider.show_at(ui, ROWS[row])
|
||||
};
|
||||
state.values[owner][row] = value;
|
||||
state.events[row].extend(edit.events);
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
Self { fixture, state }
|
||||
}
|
||||
fn thumb(&mut self, row: usize) -> Pos2 {
|
||||
let target = self.fixture.by_role(Role::SLIDER)[row];
|
||||
self.fixture.access(AccessActionKind::Focus, &target).settle();
|
||||
let id = self.fixture.focused_stop().expect("actual slider focus").0;
|
||||
assert_ne!(id, Id::NULL);
|
||||
self.fixture.part_rect(id, Slider::THUMB).expect("real sensed thumb").center()
|
||||
}
|
||||
fn drag(&mut self, row: usize, mods: Modifiers) -> f64 {
|
||||
let thumb = self.thumb(row);
|
||||
self.fixture.hold(mods).drag_at(thumb, Vec2::new(18.0, 0.0)).settle();
|
||||
self.state.borrow().values[0][row]
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn scalar_contracts_pointer_shift_fine_alt_normal_are_exact_default_swaps() {
|
||||
for fields in [false, true] {
|
||||
let plain = Rig::new(fields, None).drag(0, Modifiers::NONE);
|
||||
let fine = Rig::new(fields, None).drag(0, Modifiers::ALT);
|
||||
let coarse = Rig::new(fields, None).drag(0, Modifiers::SHIFT);
|
||||
assert!(fine > 50.0 && fine < plain && plain < coarse);
|
||||
assert_eq!(Rig::new(fields, Some(fine_shift())).drag(0, Modifiers::NONE), plain);
|
||||
assert_eq!(Rig::new(fields, Some(fine_shift())).drag(0, Modifiers::SHIFT), fine);
|
||||
assert_eq!(Rig::new(fields, Some(fine_shift())).drag(0, Modifiers::ALT), plain);
|
||||
assert_eq!(Rig::new(fields, None).drag(0, Modifiers::ALT | Modifiers::SHIFT), fine);
|
||||
assert_eq!(Rig::new(fields, Some(fine_shift())).drag(0, Modifiers::ALT | Modifiers::SHIFT), fine);
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn scalar_contracts_pointer_policy_never_leaks_to_other_row_or_keyboard() {
|
||||
for fields in [false, true] {
|
||||
let baseline = Rig::new(fields, None).drag(1, Modifiers::SHIFT);
|
||||
let mut rig = Rig::new(fields, Some(fine_shift()));
|
||||
assert_eq!(rig.drag(1, Modifiers::SHIFT), baseline);
|
||||
assert_eq!(rig.state.borrow().values[0][0], 50.0);
|
||||
for mods in [Modifiers::NONE, Modifiers::SHIFT, Modifiers::ALT] {
|
||||
let mut base = Rig::new(fields, None);
|
||||
let mut selected = Rig::new(fields, Some(fine_shift()));
|
||||
base.thumb(0);
|
||||
selected.thumb(0);
|
||||
base.fixture.key(Key::ArrowUp, mods).settle();
|
||||
selected.fixture.key(Key::ArrowUp, mods).settle();
|
||||
assert_eq!(base.state.borrow().values, selected.state.borrow().values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn scalar_contracts_pointer_disabled_read_only_and_absent_are_inert() {
|
||||
for fields in [false, true] {
|
||||
for mode in 0..3 {
|
||||
let mut rig = Rig::new(fields, Some(fine_shift()));
|
||||
let thumb = rig.thumb(0);
|
||||
match mode {
|
||||
0 => rig.state.borrow_mut().enabled = false,
|
||||
1 => rig.state.borrow_mut().read_only = true,
|
||||
_ => rig.state.borrow_mut().shown = false,
|
||||
}
|
||||
rig.fixture.settle().hold(Modifiers::SHIFT).drag_at(thumb, Vec2::new(18.0, 0.0)).settle();
|
||||
assert_eq!(rig.state.borrow().values, [[50.0; 2]; 2]);
|
||||
assert!(rig.state.borrow().events.iter().all(Vec::is_empty));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn scalar_contracts_pointer_cancel_does_not_replay_on_release_or_reappearance() {
|
||||
for fields in [false, true] {
|
||||
let mut rig = Rig::new(fields, Some(fine_shift()));
|
||||
let thumb = rig.thumb(0);
|
||||
let end = thumb + Vec2::new(18.0, 0.0);
|
||||
rig.fixture.hold(Modifiers::SHIFT).drag_hold_at(thumb, end - thumb);
|
||||
assert!(rig.state.borrow().values[0][0] > 50.0);
|
||||
cancel_all(rig.fixture.ctx(), CancelReason::Escape);
|
||||
rig.fixture.settle().release_at(end).settle();
|
||||
assert_eq!(rig.state.borrow().values, [[50.0; 2]; 2]);
|
||||
rig.state.borrow_mut().shown = false;
|
||||
rig.fixture.settle();
|
||||
rig.state.borrow_mut().shown = true;
|
||||
rig.fixture.settle();
|
||||
assert_eq!(rig.state.borrow().values, [[50.0; 2]; 2]);
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn scalar_contracts_pointer_owner_switch_cannot_capture_or_replay_into_new_owner() {
|
||||
for fields in [false, true] {
|
||||
let mut rig = Rig::new(fields, Some(fine_shift()));
|
||||
let thumb = rig.thumb(0);
|
||||
let end = thumb + Vec2::new(18.0, 0.0);
|
||||
rig.fixture.hold(Modifiers::SHIFT).drag_hold_at(thumb, end - thumb);
|
||||
rig.state.borrow_mut().owner = 1;
|
||||
rig.fixture.settle().release_at(end).settle();
|
||||
assert_eq!(rig.state.borrow().values[1], [50.0; 2]);
|
||||
rig.state.borrow_mut().owner = 0;
|
||||
rig.fixture.settle();
|
||||
let current = rig.state.borrow().values;
|
||||
rig.fixture.frame(vec![pointer::moved(end)]).settle();
|
||||
assert_eq!(rig.state.borrow().values, current);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
||||
//! A `SliderField`'s scrub rate reaches its number field: a sideways drag on the value moves it by the rate per
|
||||
//! point, as the same drag on the thumb would with a rate of the range over the track's width.
|
||||
|
||||
use craft_behavior::{EditEvent, MotionMode};
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Pos2, Rect, vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const ROW: Rect = Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(420.0, 80.0) };
|
||||
|
||||
/// The fixture of an exposure field, its value and the edit events it reported.
|
||||
type Exposure = (Fixture, Rc<RefCell<f64>>, Rc<RefCell<Vec<EditEvent<f64>>>>);
|
||||
|
||||
/// A field over -5..=5 on hundredths, scrubbing by `rate` when one is given; the value and the edit events it saw.
|
||||
fn exposure(rate: Option<f64>) -> Exposure {
|
||||
let (value, events) = (Rc::new(RefCell::new(0.5)), Rc::new(RefCell::new(Vec::new())));
|
||||
let (held, seen) = (Rc::clone(&value), Rc::clone(&events));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = held.borrow_mut();
|
||||
let field = SliderField::new("Exposure", Bind::bound(&mut *current), -5.0..=5.0).step(0.01);
|
||||
let field = match rate {
|
||||
Some(rate) => field.scrub_step(rate),
|
||||
None => field,
|
||||
};
|
||||
seen.borrow_mut().extend(field.show_at(ui, ROW).edit.events.iter().cloned());
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
(fixture, value, events)
|
||||
}
|
||||
|
||||
fn scrub_value(fixture: &mut Fixture, by: f32) {
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).first().copied().expect("the number field");
|
||||
fixture.drag_at(field.center(), vec2(by, 0.0)).settle();
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_slider_field_scrubs_its_value_at_the_rate_it_is_given() {
|
||||
let (mut fixture, value, events) = exposure(Some(0.05));
|
||||
scrub_value(&mut fixture, 40.0);
|
||||
assert!((*value.borrow() - 2.5).abs() < 1e-9, "40 points at 0.05 a point add 2: {}", value.borrow());
|
||||
let seen = events.take();
|
||||
let count = |begin: bool| {
|
||||
seen.iter().filter(|event| if begin { matches!(event, EditEvent::Begin { .. }) } else { matches!(event, EditEvent::Commit { .. }) }).count()
|
||||
};
|
||||
assert_eq!((count(true), count(false)), (1, 1), "the scrub is one gesture: {seen:?}");
|
||||
scrub_value(&mut fixture, -400.0);
|
||||
assert_eq!(*value.borrow(), -5.0, "a scrub stops at the range");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_slider_field_without_a_scrub_rate_scrubs_by_its_step() {
|
||||
for rate in [None, Some(0.0), Some(-1.0), Some(f64::NAN)] {
|
||||
let (mut fixture, value, _) = exposure(rate);
|
||||
scrub_value(&mut fixture, 40.0);
|
||||
assert!((*value.borrow() - 0.9).abs() < 1e-9, "40 points at the 0.01 step add 0.4 for {rate:?}: {}", value.borrow());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user