Skip to main content

xrack_runtime/
range.rs

1use crate::{LayoutDirection, Node, Orientation, Property, Value};
2use std::{fmt, rc::Rc};
3
4/// Transient thumb input and the resolved layout direction for a range control.
5#[doc(hidden)]
6#[derive(Clone, Default)]
7pub struct RangePositionHandle(Rc<RangePositionState>);
8
9#[derive(Default)]
10struct RangePositionState {
11    preview: Property<Option<(usize, f64)>>,
12    direction: Property<LayoutDirection>,
13}
14
15impl PartialEq for RangePositionHandle {
16    fn eq(&self, other: &Self) -> bool {
17        Rc::ptr_eq(&self.0, &other.0)
18    }
19}
20
21impl fmt::Debug for RangePositionHandle {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.debug_struct("RangePositionHandle")
24            .finish_non_exhaustive()
25    }
26}
27
28impl RangePositionHandle {
29    pub fn publish_preview(&self, preview: Option<(usize, f64)>) {
30        self.0.preview.set_if_changed(preview);
31    }
32
33    pub fn publish_direction(&self, direction: LayoutDirection) {
34        self.0.direction.set_if_changed(direction);
35    }
36
37    pub fn slider_position(&self, range: SliderRange, live: bool) -> f64 {
38        if !live && let Some((_, fraction)) = self.0.preview.get(|| None) {
39            return range.preview_fraction(fraction);
40        }
41        range.fraction()
42    }
43
44    pub fn interval_position(&self, range: SliderInterval, live: bool, handle: usize) -> f64 {
45        let fractions = if !live && let Some((index, fraction)) = self.0.preview.get(|| None) {
46            range.preview_fractions(index, fraction)
47        } else {
48            range.fractions()
49        };
50        fractions[handle]
51    }
52
53    pub fn visual_position(&self, position: f64, orientation: Orientation) -> f64 {
54        if orientation == Orientation::Vertical
55            || self.0.direction.get(LayoutDirection::default) == LayoutDirection::RightToLeft
56        {
57            1.0 - position
58        } else {
59            position
60        }
61    }
62}
63
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
65pub enum DialInputMode {
66    #[default]
67    Circular,
68    Horizontal,
69    Vertical,
70}
71
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub enum ScrollSnapMode {
74    #[default]
75    None,
76    Always,
77    OnRelease,
78}
79
80/// The normalized input understood by range controls, independent of the backend.
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub enum RangeAction {
83    SetFraction(f64),
84    CommitFraction(f64),
85    SetValue(f64),
86    SetPoint { x: f64, y: f64 },
87    Decrease,
88    Increase,
89    Step(i64),
90    Minimum,
91    Maximum,
92    Release,
93}
94
95impl RangeAction {
96    pub fn is_release(self) -> bool {
97        matches!(self, Self::Release | Self::CommitFraction(_))
98    }
99
100    /// A release observes live values after the change handler has run.
101    #[doc(hidden)]
102    pub fn try_deliver<T, E>(
103        self,
104        change: Option<T>,
105        commit: impl FnOnce(T) -> Result<bool, E>,
106        release: impl FnOnce() -> Result<(), E>,
107    ) -> Result<bool, E> {
108        match change {
109            Some(value) => {
110                if !commit(value)? {
111                    return Ok(false);
112                }
113            }
114            None if !self.is_release() => return Ok(false),
115            None => {}
116        }
117        if self.is_release() {
118            release()?;
119        }
120        Ok(true)
121    }
122
123    #[doc(hidden)]
124    pub fn deliver<T>(
125        self,
126        change: Option<T>,
127        commit: impl FnOnce(T),
128        release: impl FnOnce(),
129    ) -> bool {
130        self.try_deliver(
131            change,
132            |value| {
133                commit(value);
134                Ok::<_, std::convert::Infallible>(true)
135            },
136            || {
137                release();
138                Ok(())
139            },
140        )
141        .unwrap_or_else(|error| match error {})
142    }
143}
144
145#[doc(hidden)]
146pub const RANGE_VIEW_PROPERTIES: &[&str] = &[
147    "minimum",
148    "maximum",
149    "step",
150    "snap-mode",
151    "wrap",
152    "orientation",
153    "input-mode",
154    "start-angle",
155    "end-angle",
156    "live",
157];
158
159#[doc(hidden)]
160pub fn range_view_properties(kind: &str) -> &'static [&'static str] {
161    if kind == "ScrollBar" {
162        &[
163            "size",
164            "step-size",
165            "minimum-size",
166            "interactive",
167            "policy",
168            "orientation",
169            "snap-mode",
170        ]
171    } else {
172        RANGE_VIEW_PROPERTIES
173    }
174}
175
176/// Validate the range settings and capture live values before applying input.
177#[doc(hidden)]
178pub fn try_prepare_range_view<T, E>(
179    node: &Node,
180    action: RangeAction,
181    available: impl FnOnce() -> Result<bool, E>,
182    mut read: impl FnMut(&str) -> Result<Option<Value>, E>,
183    values: impl FnOnce() -> Result<T, E>,
184) -> Result<Option<T>, E> {
185    if node.kind == "ScrollBar"
186        && !match action {
187            RangeAction::SetFraction(value) => value.is_finite(),
188            RangeAction::Increase
189            | RangeAction::Decrease
190            | RangeAction::Minimum
191            | RangeAction::Maximum => true,
192            _ => false,
193        }
194    {
195        return Ok(None);
196    }
197    let pointer = matches!(
198        action,
199        RangeAction::SetFraction(_) | RangeAction::CommitFraction(_) | RangeAction::SetPoint { .. }
200    );
201    crate::property::watch_reads(|reads| {
202        if !available()? || reads.changed() {
203            return Ok(None);
204        }
205        if action != RangeAction::Release {
206            for &name in range_view_properties(node.kind) {
207                let used = pointer
208                    || !matches!(
209                        name,
210                        "orientation" | "input-mode" | "start-angle" | "end-angle" | "live"
211                    );
212                if used && (read(name)?.as_ref() != node.properties.get(name) || reads.changed()) {
213                    return Ok(None);
214                }
215            }
216        }
217        let values = values()?;
218        Ok((!reads.changed()).then_some(values))
219    })
220}
221
222#[doc(hidden)]
223pub fn prepare_range_view<T>(
224    node: &Node,
225    action: RangeAction,
226    available: impl FnOnce() -> bool,
227    mut read: impl FnMut(&str) -> Option<Value>,
228    values: impl FnOnce() -> T,
229) -> Option<T> {
230    try_prepare_range_view(
231        node,
232        action,
233        || Ok::<_, std::convert::Infallible>(available()),
234        |name| Ok(read(name)),
235        || Ok(values()),
236    )
237    .unwrap_or_else(|error| match error {})
238}
239
240impl Node {
241    #[doc(hidden)]
242    pub const RANGE_THUMBS: usize = 2;
243    #[doc(hidden)]
244    pub const RANGE_HANDLE_PARTS: [&'static str; Self::RANGE_THUMBS] =
245        ["RangeLowerHandle", "RangeUpperHandle"];
246
247    #[doc(hidden)]
248    pub fn range_target(&self, path: &[usize]) -> Option<&Self> {
249        let target = self.interactive_at_path(path)?;
250        match target.kind {
251            "Slider" | "Dial" | "ScrollBar" | "ColorPlane" => Some(target),
252            "RangeThumb" => {
253                let (&index, parent) = path.split_last()?;
254                self.at_path(parent)
255                    .filter(|node| node.kind == "RangeSlider" && index < Self::RANGE_THUMBS)
256            }
257            _ => None,
258        }
259    }
260
261    #[doc(hidden)]
262    pub fn add_range_thumbs(&mut self) {
263        self.children
264            .extend([Self::new("RangeThumb", None), Self::new("RangeThumb", None)]);
265    }
266}
267
268/// Step by a wheel batch without iterating once per detent.
269pub(crate) fn step_float(
270    value: f64,
271    limits: (f64, f64),
272    step: f64,
273    steps: i64,
274    wrap: bool,
275    normalize: impl Fn(f64) -> f64,
276) -> f64 {
277    let (min, max) = limits;
278    if step == 0.0 || steps == 0 || min == max {
279        return value;
280    }
281    let forward = steps > 0;
282    let amount = steps.unsigned_abs() as f64;
283    let signed_step = if forward { step } else { -step };
284    let advance = |from, count| normalize(signed_step.mul_add(count, from));
285    let limit = if forward { max } else { min };
286    let fits = |candidate| {
287        if forward {
288            candidate <= limit
289        } else {
290            candidate >= limit
291        }
292    };
293    let next = advance(value, amount);
294    if !wrap || fits(next) {
295        return next.clamp(min, max);
296    }
297    let steps_in_range = |from: f64| {
298        let distance = limit - from;
299        let estimate = if distance.is_finite() {
300            distance / signed_step
301        } else {
302            (limit * 0.5 - from * 0.5) / (signed_step * 0.5)
303        }
304        .floor()
305        .min(amount);
306        if estimate < amount && fits(advance(from, estimate + 1.0)) {
307            estimate + 1.0
308        } else if estimate > 0.0 && !fits(advance(from, estimate)) {
309            estimate - 1.0
310        } else {
311            estimate
312        }
313    };
314    let start = if forward { min } else { max };
315    let remaining = (amount - steps_in_range(value) - 1.0).max(0.0);
316    let cycle = steps_in_range(start) + 1.0;
317    advance(start, remaining % cycle).clamp(min, max)
318}
319
320#[derive(Clone, Copy, Debug, PartialEq)]
321pub struct SliderRange {
322    min: f64,
323    max: f64,
324    value: f64,
325    step: f64,
326    wrap: bool,
327    snap: ScrollSnapMode,
328}
329
330impl SliderRange {
331    pub fn from_node(node: &Node) -> Self {
332        Self::new(
333            node.number("minimum").unwrap_or(0.0),
334            node.number("maximum").unwrap_or(100.0),
335            node.number("value").unwrap_or(0.0),
336            node.number("step").unwrap_or(1.0),
337            node.kind == "Dial" && node.boolean("wrap", false),
338            match node.properties.get("snap-mode") {
339                Some(Value::ScrollSnapMode(mode)) => *mode,
340                _ => ScrollSnapMode::None,
341            },
342        )
343    }
344
345    #[doc(hidden)]
346    pub fn new(
347        min: f64,
348        max: f64,
349        value: f64,
350        step: f64,
351        wrap: bool,
352        snap: ScrollSnapMode,
353    ) -> Self {
354        let min = if min.is_finite() { min } else { 0.0 };
355        let max = if max.is_finite() { max } else { 100.0 };
356        let value = if value.is_finite() { value } else { 0.0 };
357        let step = if step.is_finite() { step } else { 1.0 };
358        let max = max.max(min);
359        Self {
360            min,
361            max,
362            value: value.clamp(min, max),
363            step: step.max(0.0),
364            wrap,
365            snap,
366        }
367    }
368
369    pub fn with_value(mut self, value: f64) -> Self {
370        if value.is_finite() {
371            self.value = value.clamp(self.min, self.max);
372        }
373        self
374    }
375
376    #[doc(hidden)]
377    pub fn with_bounds(mut self, minimum: f64, maximum: f64) -> Self {
378        self.min = minimum;
379        self.max = maximum.max(minimum);
380        self.value = self.value.clamp(self.min, self.max);
381        self
382    }
383
384    pub fn snap_mode(self) -> ScrollSnapMode {
385        self.snap
386    }
387
388    pub fn preview_fraction(self, fraction: f64) -> f64 {
389        self.with_value(
390            self.apply(RangeAction::SetFraction(fraction))
391                .unwrap_or(self.value),
392        )
393        .fraction()
394    }
395
396    fn snap_value(self, value: f64) -> f64 {
397        let value = value.clamp(self.min, self.max);
398        if self.step == 0.0 || value == self.min || value == self.max {
399            return value;
400        }
401        let steps = ((value - self.min) / self.step).round();
402        if !steps.is_finite() {
403            return value;
404        }
405        let snapped = steps.mul_add(self.step, self.min).clamp(self.min, self.max);
406        if self.max - value < (snapped - value).abs() {
407            self.max
408        } else {
409            snapped
410        }
411    }
412
413    pub fn value(self) -> f64 {
414        self.value
415    }
416
417    pub fn fraction(self) -> f64 {
418        if self.max == self.min {
419            return 0.0;
420        }
421        let span = self.max - self.min;
422        if span.is_finite() {
423            (self.value - self.min) / span
424        } else {
425            // Halve first so even a range spanning both finite extremes works.
426            (self.value * 0.5 - self.min * 0.5) / (self.max * 0.5 - self.min * 0.5)
427        }
428    }
429
430    pub fn apply(self, action: RangeAction) -> Option<f64> {
431        let next = match action {
432            RangeAction::SetFraction(fraction) | RangeAction::CommitFraction(fraction)
433                if fraction.is_finite() =>
434            {
435                let t = fraction.clamp(0.0, 1.0);
436                let value = self.min * (1.0 - t) + self.max * t;
437                if self.snap == ScrollSnapMode::Always
438                    || self.snap == ScrollSnapMode::OnRelease && action.is_release()
439                {
440                    self.snap_value(value)
441                } else {
442                    value
443                }
444            }
445            RangeAction::SetValue(value) if value.is_finite() => {
446                if self.snap == ScrollSnapMode::None {
447                    value
448                } else {
449                    self.snap_value(value)
450                }
451            }
452            RangeAction::Decrease => self.value - self.step,
453            RangeAction::Increase => self.value + self.step,
454            RangeAction::Step(steps) => step_float(
455                self.value,
456                (self.min, self.max),
457                self.step,
458                steps,
459                self.wrap,
460                |value| value,
461            ),
462            RangeAction::Minimum => self.min,
463            RangeAction::Maximum => self.max,
464            _ => return None,
465        };
466        let next = match action {
467            RangeAction::Increase if self.wrap && next > self.max => self.min,
468            RangeAction::Decrease if self.wrap && next < self.min => self.max,
469            _ => next.clamp(self.min, self.max),
470        };
471        (next != self.value).then_some(next)
472    }
473}
474
475pub fn progress_value(node: &Node) -> f64 {
476    node.number("progress").unwrap_or(0.0).clamp(0.0, 1.0)
477}
478
479/// Numeric bounds and the clamped business value of a progress bar.
480#[doc(hidden)]
481#[derive(Clone, Copy, Debug, PartialEq)]
482pub struct ProgressRange {
483    pub minimum: f64,
484    pub maximum: f64,
485    pub value: f64,
486}
487
488impl ProgressRange {
489    pub fn new(minimum: f64, maximum: f64, value: f64) -> Self {
490        let minimum = if minimum.is_finite() { minimum } else { 0.0 };
491        let maximum = if maximum.is_finite() { maximum } else { 1.0 }.max(minimum);
492        let value = if value.is_finite() { value } else { 0.0 }.clamp(minimum, maximum);
493        Self {
494            minimum,
495            maximum,
496            value,
497        }
498    }
499
500    pub fn from_node(node: &Node) -> Self {
501        Self::new(
502            node.number("minimum").unwrap_or(0.0),
503            node.number("maximum").unwrap_or(1.0),
504            node.number("progress").unwrap_or(0.0),
505        )
506    }
507
508    pub fn position(self) -> f64 {
509        let span = self.maximum - self.minimum;
510        if span == 0.0 {
511            return 0.0;
512        }
513        if span.is_finite() {
514            (self.value - self.minimum) / span
515        } else {
516            // Halve before subtracting when finite opposite bounds overflow.
517            (self.value * 0.5 - self.minimum * 0.5) / (self.maximum * 0.5 - self.minimum * 0.5)
518        }
519    }
520}
521
522#[derive(Clone, Copy, Debug, PartialEq)]
523pub struct ScrollBarRange {
524    pub position: f64,
525    pub size: f64,
526    pub step: f64,
527}
528
529impl ScrollBarRange {
530    pub const DEFAULT_SIZE: f64 = 0.0;
531    pub const DEFAULT_STEP: f64 = 0.1;
532
533    pub fn from_node(node: &Node) -> Self {
534        Self::new(
535            node.number("position").unwrap_or_default(),
536            node.number("size").unwrap_or(Self::DEFAULT_SIZE),
537            node.number("step-size").unwrap_or(Self::DEFAULT_STEP),
538        )
539    }
540
541    pub fn new(position: f64, size: f64, step: f64) -> Self {
542        let unit = |value: f64, default| {
543            if value.is_finite() {
544                value.clamp(0.0, 1.0)
545            } else {
546                default
547            }
548        };
549        let size = unit(size, Self::DEFAULT_SIZE);
550        Self {
551            position: unit(position, 0.0).min(1.0 - size),
552            size,
553            step: unit(step, Self::DEFAULT_STEP),
554        }
555    }
556
557    #[doc(hidden)]
558    pub fn position_with(position: impl FnOnce() -> f64, size: impl FnOnce() -> f64) -> f64 {
559        Self::try_position_with(
560            || Ok::<_, std::convert::Infallible>(position()),
561            || Ok(size()),
562        )
563        .unwrap_or_else(|error| match error {})
564    }
565
566    /// Read the position binding before the size that constrains it.
567    #[doc(hidden)]
568    pub fn try_position_with<E>(
569        position: impl FnOnce() -> Result<f64, E>,
570        size: impl FnOnce() -> Result<f64, E>,
571    ) -> Result<f64, E> {
572        let position = position()?;
573        let size = size()?;
574        Ok(Self::new(position, size, 0.0).position)
575    }
576
577    pub fn maximum(self) -> f64 {
578        1.0 - self.size
579    }
580
581    #[doc(hidden)]
582    pub fn with_position(self, position: f64) -> Self {
583        Self::new(position, self.size, self.step)
584    }
585
586    pub fn apply(self, action: RangeAction) -> Option<f64> {
587        let next = match action {
588            RangeAction::SetFraction(fraction) if fraction.is_finite() => fraction * self.maximum(),
589            RangeAction::Decrease => self.position - self.step,
590            RangeAction::Increase => self.position + self.step,
591            RangeAction::Minimum => 0.0,
592            RangeAction::Maximum => self.maximum(),
593            _ => return None,
594        }
595        .clamp(0.0, self.maximum());
596        (next != self.position).then_some(next)
597    }
598}
599
600#[derive(Clone, Copy, Debug, PartialEq)]
601pub enum IndicatorState {
602    Hidden,
603    Determinate(f64),
604    Indeterminate,
605}
606
607pub fn indicator_state(node: &Node) -> Option<IndicatorState> {
608    Some(match node.kind {
609        "BusyIndicator" if node.boolean("running", true) => IndicatorState::Indeterminate,
610        "BusyIndicator" => IndicatorState::Hidden,
611        "Spinner" | "ProgressIndicator" if node.boolean("indeterminate", false) => {
612            IndicatorState::Indeterminate
613        }
614        "ProgressIndicator" => {
615            IndicatorState::Determinate(ProgressRange::from_node(node).position())
616        }
617        "Spinner" => IndicatorState::Determinate(progress_value(node)),
618        _ => return None,
619    })
620}
621
622#[derive(Clone, Copy, Debug)]
623pub struct SliderInterval {
624    axis: SliderRange,
625    values: [f64; 2],
626}
627
628impl SliderInterval {
629    pub fn from_node(node: &Node) -> Self {
630        let axis = SliderRange::from_node(node);
631        Self::from_values(
632            node,
633            node.number("lower-value").unwrap_or(axis.min),
634            node.number("upper-value").unwrap_or(axis.max),
635        )
636    }
637
638    pub fn from_values(node: &Node, lower: f64, upper: f64) -> Self {
639        Self::from_range(SliderRange::from_node(node), lower, upper)
640    }
641
642    #[doc(hidden)]
643    pub fn from_range(axis: SliderRange, lower: f64, upper: f64) -> Self {
644        let upper = if upper.is_finite() {
645            upper.clamp(axis.min, axis.max)
646        } else {
647            axis.max
648        };
649        let lower = if lower.is_finite() {
650            lower.clamp(axis.min, upper)
651        } else {
652            axis.min
653        };
654        Self {
655            axis,
656            values: [lower, upper],
657        }
658    }
659
660    pub fn values(self) -> [f64; 2] {
661        self.values
662    }
663
664    pub fn fractions(self) -> [f64; 2] {
665        self.values
666            .map(|value| SliderRange { value, ..self.axis }.fraction())
667    }
668
669    pub fn nearest_handle(self, fraction: f64) -> usize {
670        let [lower, upper] = self.fractions();
671        usize::from(if lower == upper {
672            fraction >= lower
673        } else {
674            (fraction - upper).abs() < (fraction - lower).abs()
675        })
676    }
677
678    pub fn preview_fractions(self, handle: usize, fraction: f64) -> [f64; 2] {
679        let values = self
680            .apply(handle, RangeAction::SetFraction(fraction))
681            .unwrap_or(self.values);
682        Self { values, ..self }.fractions()
683    }
684
685    pub fn apply(self, handle: usize, action: RangeAction) -> Option<[f64; 2]> {
686        let value = *self.values.get(handle)?;
687        let mut values = self.values;
688        let next = SliderRange { value, ..self.axis }.apply(action)?;
689        values[handle] = if handle == 0 {
690            next.min(values[1])
691        } else {
692            next.max(values[0])
693        };
694        (values != self.values).then_some(values)
695    }
696
697    #[doc(hidden)]
698    pub fn changed_values(
699        self,
700        handle: usize,
701        action: RangeAction,
702        raw: [f64; 2],
703    ) -> Option<[Option<f64>; 2]> {
704        let next = self.apply(handle, action)?;
705        Some(std::array::from_fn(|index| {
706            (next[index] != raw[index]).then_some(next[index])
707        }))
708    }
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714
715    #[test]
716    fn progress_range_stays_finite_for_extreme_and_collapsed_bounds() {
717        assert_eq!(ProgressRange::new(-f64::MAX, f64::MAX, 0.0).position(), 0.5);
718        assert_eq!(ProgressRange::new(100.0, 90.0, 120.0).position(), 0.0);
719        assert_eq!(ProgressRange::new(100.0, 900.0, f64::NAN).value, 100.0);
720        assert_eq!(ProgressRange::new(100.0, 900.0, 1100.0).value, 900.0);
721    }
722
723    #[test]
724    fn batched_steps_keep_remaining_detents_after_wrap() {
725        let mut dial = Node::new("Dial", None);
726        dial.properties.insert("minimum", (-2.0_f64).into());
727        dial.properties.insert("maximum", 3.0_f64.into());
728        dial.properties.insert("value", 2.0_f64.into());
729        dial.properties.insert("wrap", true.into());
730        let range = SliderRange::from_node(&dial);
731        assert_eq!(range.apply(RangeAction::Step(3)), Some(-1.0));
732        assert_eq!(range.apply(RangeAction::Step(-6)), None);
733        assert_eq!(
734            step_float(
735                -f64::MAX,
736                (-f64::MAX, f64::MAX),
737                f64::MAX,
738                10,
739                true,
740                |value| value
741            ),
742            0.0,
743        );
744    }
745
746    #[test]
747    fn slider_snap_uses_the_minimum_and_keeps_a_partial_final_step_reachable() {
748        let mut node = Node::new("Slider", None);
749        node.properties.insert("minimum", 3.0_f64.into());
750        node.properties.insert("maximum", 17.0_f64.into());
751        node.properties.insert("step", 5.0_f64.into());
752        node.properties
753            .insert("snap-mode", ScrollSnapMode::OnRelease.into());
754        let range = SliderRange::from_node(&node);
755        assert_eq!(range.apply(RangeAction::SetFraction(0.5)), Some(10.0));
756        assert_eq!(range.apply(RangeAction::CommitFraction(0.5)), Some(8.0));
757        assert_eq!(range.apply(RangeAction::CommitFraction(0.96)), Some(17.0));
758        assert_eq!(range.apply(RangeAction::SetValue(15.0)), Some(13.0));
759        assert_eq!(range.apply(RangeAction::SetValue(f64::INFINITY)), None);
760    }
761}