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