Skip to main content

xrack_runtime/
range.rs

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