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    #[doc(hidden)]
183    pub const RANGE_HANDLE_PARTS: [&'static str; Self::RANGE_THUMBS] =
184        ["RangeLowerHandle", "RangeUpperHandle"];
185
186    #[doc(hidden)]
187    pub fn range_target(&self, path: &[usize]) -> Option<&Self> {
188        let target = self.interactive_at_path(path)?;
189        match target.kind {
190            "Slider" | "Dial" | "ScrollBar" | "ColorPlane" => Some(target),
191            "RangeThumb" => {
192                let (&index, parent) = path.split_last()?;
193                self.at_path(parent)
194                    .filter(|node| node.kind == "RangeSlider" && index < Self::RANGE_THUMBS)
195            }
196            _ => None,
197        }
198    }
199
200    #[doc(hidden)]
201    pub fn add_range_thumbs(&mut self) {
202        self.children
203            .extend([Self::new("RangeThumb", None), Self::new("RangeThumb", None)]);
204    }
205}
206
207/// Step by a wheel batch without iterating once per detent.
208pub(crate) fn step_float(
209    value: f64,
210    limits: (f64, f64),
211    step: f64,
212    steps: i64,
213    wrap: bool,
214    normalize: impl Fn(f64) -> f64,
215) -> f64 {
216    let (min, max) = limits;
217    if step == 0.0 || steps == 0 || min == max {
218        return value;
219    }
220    let forward = steps > 0;
221    let amount = steps.unsigned_abs() as f64;
222    let signed_step = if forward { step } else { -step };
223    let advance = |from, count| normalize(signed_step.mul_add(count, from));
224    let limit = if forward { max } else { min };
225    let fits = |candidate| {
226        if forward {
227            candidate <= limit
228        } else {
229            candidate >= limit
230        }
231    };
232    let next = advance(value, amount);
233    if !wrap || fits(next) {
234        return next.clamp(min, max);
235    }
236    let steps_in_range = |from: f64| {
237        let distance = limit - from;
238        let estimate = if distance.is_finite() {
239            distance / signed_step
240        } else {
241            (limit * 0.5 - from * 0.5) / (signed_step * 0.5)
242        }
243        .floor()
244        .min(amount);
245        if estimate < amount && fits(advance(from, estimate + 1.0)) {
246            estimate + 1.0
247        } else if estimate > 0.0 && !fits(advance(from, estimate)) {
248            estimate - 1.0
249        } else {
250            estimate
251        }
252    };
253    let start = if forward { min } else { max };
254    let remaining = (amount - steps_in_range(value) - 1.0).max(0.0);
255    let cycle = steps_in_range(start) + 1.0;
256    advance(start, remaining % cycle).clamp(min, max)
257}
258
259#[derive(Clone, Copy, Debug, PartialEq)]
260pub struct SliderRange {
261    min: f64,
262    max: f64,
263    value: f64,
264    step: f64,
265    wrap: bool,
266    snap: ScrollSnapMode,
267}
268
269impl SliderRange {
270    pub fn from_node(node: &Node) -> Self {
271        let min = node.number("minimum").unwrap_or(0.0);
272        let max = node.number("maximum").unwrap_or(100.0).max(min);
273        Self {
274            min,
275            max,
276            value: node.number("value").unwrap_or(0.0).clamp(min, max),
277            step: node.number("step").unwrap_or(1.0).max(0.0),
278            wrap: node.kind == "Dial" && node.boolean("wrap", false),
279            snap: match node.properties.get("snap-mode") {
280                Some(Value::ScrollSnapMode(mode)) => *mode,
281                _ => ScrollSnapMode::None,
282            },
283        }
284    }
285
286    pub fn with_value(mut self, value: f64) -> Self {
287        if value.is_finite() {
288            self.value = value.clamp(self.min, self.max);
289        }
290        self
291    }
292
293    #[doc(hidden)]
294    pub fn with_bounds(mut self, minimum: f64, maximum: f64) -> Self {
295        self.min = minimum;
296        self.max = maximum.max(minimum);
297        self.value = self.value.clamp(self.min, self.max);
298        self
299    }
300
301    pub fn snap_mode(self) -> ScrollSnapMode {
302        self.snap
303    }
304
305    pub fn preview_fraction(self, fraction: f64) -> f64 {
306        self.with_value(
307            self.apply(RangeAction::SetFraction(fraction))
308                .unwrap_or(self.value),
309        )
310        .fraction()
311    }
312
313    fn snap_value(self, value: f64) -> f64 {
314        let value = value.clamp(self.min, self.max);
315        if self.step == 0.0 || value == self.min || value == self.max {
316            return value;
317        }
318        let steps = ((value - self.min) / self.step).round();
319        if !steps.is_finite() {
320            return value;
321        }
322        let snapped = steps.mul_add(self.step, self.min).clamp(self.min, self.max);
323        if self.max - value < (snapped - value).abs() {
324            self.max
325        } else {
326            snapped
327        }
328    }
329
330    pub fn value(self) -> f64 {
331        self.value
332    }
333
334    pub fn fraction(self) -> f64 {
335        if self.max == self.min {
336            return 0.0;
337        }
338        let span = self.max - self.min;
339        if span.is_finite() {
340            (self.value - self.min) / span
341        } else {
342            // Halve first so even a range spanning both finite extremes works.
343            (self.value * 0.5 - self.min * 0.5) / (self.max * 0.5 - self.min * 0.5)
344        }
345    }
346
347    pub fn apply(self, action: RangeAction) -> Option<f64> {
348        let next = match action {
349            RangeAction::SetFraction(fraction) | RangeAction::CommitFraction(fraction)
350                if fraction.is_finite() =>
351            {
352                let t = fraction.clamp(0.0, 1.0);
353                let value = self.min * (1.0 - t) + self.max * t;
354                if self.snap == ScrollSnapMode::Always
355                    || self.snap == ScrollSnapMode::OnRelease && action.is_release()
356                {
357                    self.snap_value(value)
358                } else {
359                    value
360                }
361            }
362            RangeAction::SetValue(value) if value.is_finite() => {
363                if self.snap == ScrollSnapMode::None {
364                    value
365                } else {
366                    self.snap_value(value)
367                }
368            }
369            RangeAction::Decrease => self.value - self.step,
370            RangeAction::Increase => self.value + self.step,
371            RangeAction::Step(steps) => step_float(
372                self.value,
373                (self.min, self.max),
374                self.step,
375                steps,
376                self.wrap,
377                |value| value,
378            ),
379            RangeAction::Minimum => self.min,
380            RangeAction::Maximum => self.max,
381            _ => return None,
382        };
383        let next = match action {
384            RangeAction::Increase if self.wrap && next > self.max => self.min,
385            RangeAction::Decrease if self.wrap && next < self.min => self.max,
386            _ => next.clamp(self.min, self.max),
387        };
388        (next != self.value).then_some(next)
389    }
390}
391
392pub fn progress_value(node: &Node) -> f64 {
393    node.number("progress").unwrap_or(0.0).clamp(0.0, 1.0)
394}
395
396#[derive(Clone, Copy, Debug, PartialEq)]
397pub struct ScrollBarRange {
398    pub position: f64,
399    pub size: f64,
400    pub step: f64,
401}
402
403impl ScrollBarRange {
404    pub const DEFAULT_SIZE: f64 = 0.0;
405    pub const DEFAULT_STEP: f64 = 0.1;
406
407    pub fn from_node(node: &Node) -> Self {
408        Self::new(
409            node.number("position").unwrap_or_default(),
410            node.number("size").unwrap_or(Self::DEFAULT_SIZE),
411            node.number("step-size").unwrap_or(Self::DEFAULT_STEP),
412        )
413    }
414
415    pub fn new(position: f64, size: f64, step: f64) -> Self {
416        let unit = |value: f64, default| {
417            if value.is_finite() {
418                value.clamp(0.0, 1.0)
419            } else {
420                default
421            }
422        };
423        let size = unit(size, Self::DEFAULT_SIZE);
424        Self {
425            position: unit(position, 0.0).min(1.0 - size),
426            size,
427            step: unit(step, Self::DEFAULT_STEP),
428        }
429    }
430
431    #[doc(hidden)]
432    pub fn position_with(position: impl FnOnce() -> f64, size: impl FnOnce() -> f64) -> f64 {
433        Self::try_position_with(
434            || Ok::<_, std::convert::Infallible>(position()),
435            || Ok(size()),
436        )
437        .unwrap_or_else(|error| match error {})
438    }
439
440    /// Read the position binding before the size that constrains it.
441    #[doc(hidden)]
442    pub fn try_position_with<E>(
443        position: impl FnOnce() -> Result<f64, E>,
444        size: impl FnOnce() -> Result<f64, E>,
445    ) -> Result<f64, E> {
446        let position = position()?;
447        let size = size()?;
448        Ok(Self::new(position, size, 0.0).position)
449    }
450
451    pub fn maximum(self) -> f64 {
452        1.0 - self.size
453    }
454
455    #[doc(hidden)]
456    pub fn with_position(self, position: f64) -> Self {
457        Self::new(position, self.size, self.step)
458    }
459
460    pub fn apply(self, action: RangeAction) -> Option<f64> {
461        let next = match action {
462            RangeAction::SetFraction(fraction) if fraction.is_finite() => fraction * self.maximum(),
463            RangeAction::Decrease => self.position - self.step,
464            RangeAction::Increase => self.position + self.step,
465            RangeAction::Minimum => 0.0,
466            RangeAction::Maximum => self.maximum(),
467            _ => return None,
468        }
469        .clamp(0.0, self.maximum());
470        (next != self.position).then_some(next)
471    }
472}
473
474#[derive(Clone, Copy, Debug, PartialEq)]
475pub enum IndicatorState {
476    Hidden,
477    Determinate(f64),
478    Indeterminate,
479}
480
481pub fn indicator_state(node: &Node) -> Option<IndicatorState> {
482    Some(match node.kind {
483        "BusyIndicator" if node.boolean("running", true) => IndicatorState::Indeterminate,
484        "BusyIndicator" => IndicatorState::Hidden,
485        "Spinner" | "ProgressIndicator" if node.boolean("indeterminate", false) => {
486            IndicatorState::Indeterminate
487        }
488        "Spinner" | "ProgressIndicator" => IndicatorState::Determinate(progress_value(node)),
489        _ => return None,
490    })
491}
492
493#[derive(Clone, Copy, Debug)]
494pub struct SliderInterval {
495    axis: SliderRange,
496    values: [f64; 2],
497}
498
499impl SliderInterval {
500    pub fn from_node(node: &Node) -> Self {
501        let axis = SliderRange::from_node(node);
502        Self::from_values(
503            node,
504            node.number("lower-value").unwrap_or(axis.min),
505            node.number("upper-value").unwrap_or(axis.max),
506        )
507    }
508
509    pub fn from_values(node: &Node, lower: f64, upper: f64) -> Self {
510        Self::from_range(SliderRange::from_node(node), lower, upper)
511    }
512
513    #[doc(hidden)]
514    pub fn from_range(axis: SliderRange, lower: f64, upper: f64) -> Self {
515        let upper = if upper.is_finite() {
516            upper.clamp(axis.min, axis.max)
517        } else {
518            axis.max
519        };
520        let lower = if lower.is_finite() {
521            lower.clamp(axis.min, upper)
522        } else {
523            axis.min
524        };
525        Self {
526            axis,
527            values: [lower, upper],
528        }
529    }
530
531    pub fn values(self) -> [f64; 2] {
532        self.values
533    }
534
535    pub fn fractions(self) -> [f64; 2] {
536        self.values
537            .map(|value| SliderRange { value, ..self.axis }.fraction())
538    }
539
540    pub fn nearest_handle(self, fraction: f64) -> usize {
541        let [lower, upper] = self.fractions();
542        usize::from(if lower == upper {
543            fraction >= lower
544        } else {
545            (fraction - upper).abs() < (fraction - lower).abs()
546        })
547    }
548
549    pub fn preview_fractions(self, handle: usize, fraction: f64) -> [f64; 2] {
550        let values = self
551            .apply(handle, RangeAction::SetFraction(fraction))
552            .unwrap_or(self.values);
553        Self { values, ..self }.fractions()
554    }
555
556    pub fn apply(self, handle: usize, action: RangeAction) -> Option<[f64; 2]> {
557        let value = *self.values.get(handle)?;
558        let mut values = self.values;
559        let next = SliderRange { value, ..self.axis }.apply(action)?;
560        values[handle] = if handle == 0 {
561            next.min(values[1])
562        } else {
563            next.max(values[0])
564        };
565        (values != self.values).then_some(values)
566    }
567
568    #[doc(hidden)]
569    pub fn changed_values(
570        self,
571        handle: usize,
572        action: RangeAction,
573        raw: [f64; 2],
574    ) -> Option<[Option<f64>; 2]> {
575        let next = self.apply(handle, action)?;
576        Some(std::array::from_fn(|index| {
577            (next[index] != raw[index]).then_some(next[index])
578        }))
579    }
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    #[test]
587    fn batched_steps_keep_remaining_detents_after_wrap() {
588        let mut dial = Node::new("Dial", None);
589        dial.properties.insert("minimum", (-2.0_f64).into());
590        dial.properties.insert("maximum", 3.0_f64.into());
591        dial.properties.insert("value", 2.0_f64.into());
592        dial.properties.insert("wrap", true.into());
593        let range = SliderRange::from_node(&dial);
594        assert_eq!(range.apply(RangeAction::Step(3)), Some(-1.0));
595        assert_eq!(range.apply(RangeAction::Step(-6)), None);
596        assert_eq!(
597            step_float(
598                -f64::MAX,
599                (-f64::MAX, f64::MAX),
600                f64::MAX,
601                10,
602                true,
603                |value| value
604            ),
605            0.0,
606        );
607    }
608
609    #[test]
610    fn slider_snap_uses_the_minimum_and_keeps_a_partial_final_step_reachable() {
611        let mut node = Node::new("Slider", None);
612        node.properties.insert("minimum", 3.0_f64.into());
613        node.properties.insert("maximum", 17.0_f64.into());
614        node.properties.insert("step", 5.0_f64.into());
615        node.properties
616            .insert("snap-mode", ScrollSnapMode::OnRelease.into());
617        let range = SliderRange::from_node(&node);
618        assert_eq!(range.apply(RangeAction::SetFraction(0.5)), Some(10.0));
619        assert_eq!(range.apply(RangeAction::CommitFraction(0.5)), Some(8.0));
620        assert_eq!(range.apply(RangeAction::CommitFraction(0.96)), Some(17.0));
621        assert_eq!(range.apply(RangeAction::SetValue(15.0)), Some(13.0));
622        assert_eq!(range.apply(RangeAction::SetValue(f64::INFINITY)), None);
623    }
624}