Skip to main content

xrack_runtime/
double_spin.rs

1use crate::{Node, SpinAction, spin_editable};
2
3/// A finite value carried by a decimal editor action.
4#[derive(Clone, Copy, Debug, PartialEq)]
5pub struct SpinDecimal(f64);
6
7impl Eq for SpinDecimal {}
8
9impl SpinDecimal {
10    pub fn new(value: f64) -> Option<Self> {
11        value.is_finite().then_some(Self(value))
12    }
13
14    pub fn parse(text: &str, separator: char) -> Option<Self> {
15        if !spin_text_is_valid(text, Some(separator)) {
16            return None;
17        }
18        let normalized;
19        let text = if separator == '.' {
20            text
21        } else {
22            normalized = text.replace(separator, ".");
23            &normalized
24        };
25        Self::new(text.parse().ok()?)
26    }
27}
28
29pub fn spin_text_is_valid(text: &str, separator: Option<char>) -> bool {
30    let digits = text.strip_prefix(['-', '+']).unwrap_or(text);
31    let ascii_digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
32    if let Some((whole, fraction)) = separator.and_then(|separator| digits.split_once(separator)) {
33        ascii_digits(whole) && ascii_digits(fraction)
34    } else {
35        ascii_digits(digits)
36    }
37}
38
39pub fn decimal_separator(node: &Node) -> char {
40    if node.text("decimal-separator") == Some(",") {
41        ','
42    } else {
43        '.'
44    }
45}
46
47#[derive(Clone, Copy, Debug)]
48pub struct DecimalSpinRange {
49    minimum: f64,
50    maximum: f64,
51    original: Option<SpinDecimal>,
52    value: f64,
53    step: f64,
54    decimals: usize,
55    separator: char,
56    wrap: bool,
57}
58
59fn rounded(value: f64, decimals: usize) -> f64 {
60    if !value.is_finite() {
61        return value;
62    }
63    // Use the same decimal rounding for display, steps and commits.
64    // The fixed-format form also handles finite values beyond integer scales.
65    let rounded = format!("{value:.decimals$}").parse().unwrap_or(value);
66    if rounded == 0.0 { 0.0 } else { rounded }
67}
68
69impl DecimalSpinRange {
70    pub fn from_node(node: &Node) -> Self {
71        let decimals = node.int("decimals").unwrap_or(2).clamp(0, 15) as usize;
72        let round = |value| rounded(value, decimals);
73        let minimum = round(node.number("minimum").unwrap_or(0.0));
74        let maximum = round(node.number("maximum").unwrap_or(100.0)).max(minimum);
75        let original = node.number("value").and_then(SpinDecimal::new);
76        let value = original
77            .map_or(minimum, |value| round(value.0))
78            .clamp(minimum, maximum);
79        let step = node.number("step-size").unwrap_or(1.0).max(0.0);
80        let step = if step == 0.0 {
81            0.0
82        } else {
83            round(step).max(10.0_f64.powi(-(decimals as i32)))
84        };
85        let separator = decimal_separator(node);
86        Self {
87            minimum,
88            maximum,
89            original,
90            value,
91            step,
92            decimals,
93            separator,
94            wrap: node.boolean("wrap", false),
95        }
96    }
97
98    pub fn value(self) -> f64 {
99        self.value
100    }
101
102    pub fn limits(self) -> (f64, f64) {
103        (self.minimum, self.maximum)
104    }
105
106    pub fn step(self) -> f64 {
107        self.step
108    }
109
110    pub fn display(self) -> String {
111        let text = format!("{:.*}", self.decimals, self.value);
112        if self.separator == '.' {
113            text
114        } else {
115            text.replace('.', ",")
116        }
117    }
118
119    pub fn apply(self, action: SpinAction) -> Option<f64> {
120        let next = match action {
121            SpinAction::Increase => rounded(self.value + self.step, self.decimals),
122            SpinAction::Decrease => rounded(self.value - self.step, self.decimals),
123            SpinAction::Step(steps) => crate::range::step_float(
124                self.value,
125                self.limits(),
126                self.step,
127                steps,
128                self.wrap,
129                |value| rounded(value, self.decimals),
130            ),
131            SpinAction::Minimum => self.minimum,
132            SpinAction::Maximum => self.maximum,
133            SpinAction::CommitDecimal(value) => rounded(value.0, self.decimals),
134            SpinAction::CommitDecimalIfCurrent { original, value } if original == self.original => {
135                rounded(value.0, self.decimals)
136            }
137            _ => return None,
138        };
139        let next = match action {
140            SpinAction::Increase if self.wrap && next > self.maximum => self.minimum,
141            SpinAction::Decrease if self.wrap && next < self.minimum => self.maximum,
142            _ => next.clamp(self.minimum, self.maximum),
143        };
144        (next != self.original.map_or(self.value, |value| value.0)).then_some(next)
145    }
146}
147
148pub fn decimal_spin_value_after(node: &Node, action: SpinAction) -> Option<f64> {
149    if node.kind != "DoubleSpinBox"
150        || node.boolean("read-only", false)
151        || matches!(
152            action,
153            SpinAction::CommitDecimal(_) | SpinAction::CommitDecimalIfCurrent { .. }
154        ) && !spin_editable(node)
155    {
156        return None;
157    }
158    DecimalSpinRange::from_node(node).apply(action)
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn decimal_steps_compare_rounded_values_before_wrapping() {
167        let mut node = Node::new("DoubleSpinBox", None);
168        node.properties.insert("minimum", (-0.4_f64).into());
169        node.properties.insert("maximum", 0.3_f64.into());
170        node.properties.insert("step-size", 0.1_f64.into());
171        node.properties.insert("wrap", true.into());
172        node.properties.insert("value", 0.2_f64.into());
173        assert_eq!(
174            decimal_spin_value_after(&node, SpinAction::Increase),
175            Some(0.3)
176        );
177        node.properties.insert("value", 0.3_f64.into());
178        assert_eq!(
179            decimal_spin_value_after(&node, SpinAction::Increase),
180            Some(-0.4)
181        );
182        node.properties.insert("value", (-0.4_f64).into());
183        assert_eq!(
184            decimal_spin_value_after(&node, SpinAction::Decrease),
185            Some(0.3)
186        );
187
188        node.properties.insert("minimum", (-f64::MAX).into());
189        node.properties.insert("maximum", f64::MAX.into());
190        node.properties.insert("value", f64::MAX.into());
191        node.properties.insert("step-size", f64::MAX.into());
192        assert_eq!(
193            decimal_spin_value_after(&node, SpinAction::Increase),
194            Some(-f64::MAX)
195        );
196    }
197
198    #[test]
199    fn decimal_drafts_allow_partial_input_but_only_finite_values_can_commit() {
200        assert!(spin_text_is_valid("-,", Some(',')));
201        assert!(SpinDecimal::parse("-,", ',').is_none());
202        assert!(SpinDecimal::parse("1.2", ',').is_none());
203        assert!(SpinDecimal::parse("NaN", '.').is_none());
204        assert!(SpinDecimal::parse(&"9".repeat(400), '.').is_none());
205        assert!(SpinDecimal::new(f64::INFINITY).is_none());
206        assert_eq!(SpinDecimal::parse("-1,2", ','), SpinDecimal::new(-1.2));
207    }
208}