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::Minimum => self.minimum,
124            SpinAction::Maximum => self.maximum,
125            SpinAction::CommitDecimal(value) => rounded(value.0, self.decimals),
126            SpinAction::CommitDecimalIfCurrent { original, value } if original == self.original => {
127                rounded(value.0, self.decimals)
128            }
129            _ => return None,
130        };
131        let next = match action {
132            SpinAction::Increase if self.wrap && next > self.maximum => self.minimum,
133            SpinAction::Decrease if self.wrap && next < self.minimum => self.maximum,
134            _ => next.clamp(self.minimum, self.maximum),
135        };
136        (next != self.original.map_or(self.value, |value| value.0)).then_some(next)
137    }
138}
139
140pub fn decimal_spin_value_after(node: &Node, action: SpinAction) -> Option<f64> {
141    if node.kind != "DoubleSpinBox"
142        || node.boolean("read-only", false)
143        || matches!(
144            action,
145            SpinAction::CommitDecimal(_) | SpinAction::CommitDecimalIfCurrent { .. }
146        ) && !spin_editable(node)
147    {
148        return None;
149    }
150    DecimalSpinRange::from_node(node).apply(action)
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn decimal_steps_compare_rounded_values_before_wrapping() {
159        let mut node = Node::new("DoubleSpinBox", None);
160        node.properties.insert("minimum", (-0.4_f64).into());
161        node.properties.insert("maximum", 0.3_f64.into());
162        node.properties.insert("step-size", 0.1_f64.into());
163        node.properties.insert("wrap", true.into());
164        node.properties.insert("value", 0.2_f64.into());
165        assert_eq!(
166            decimal_spin_value_after(&node, SpinAction::Increase),
167            Some(0.3)
168        );
169        node.properties.insert("value", 0.3_f64.into());
170        assert_eq!(
171            decimal_spin_value_after(&node, SpinAction::Increase),
172            Some(-0.4)
173        );
174        node.properties.insert("value", (-0.4_f64).into());
175        assert_eq!(
176            decimal_spin_value_after(&node, SpinAction::Decrease),
177            Some(0.3)
178        );
179
180        node.properties.insert("minimum", (-f64::MAX).into());
181        node.properties.insert("maximum", f64::MAX.into());
182        node.properties.insert("value", f64::MAX.into());
183        node.properties.insert("step-size", f64::MAX.into());
184        assert_eq!(
185            decimal_spin_value_after(&node, SpinAction::Increase),
186            Some(-f64::MAX)
187        );
188    }
189
190    #[test]
191    fn decimal_drafts_allow_partial_input_but_only_finite_values_can_commit() {
192        assert!(spin_text_is_valid("-,", Some(',')));
193        assert!(SpinDecimal::parse("-,", ',').is_none());
194        assert!(SpinDecimal::parse("1.2", ',').is_none());
195        assert!(SpinDecimal::parse("NaN", '.').is_none());
196        assert!(SpinDecimal::parse(&"9".repeat(400), '.').is_none());
197        assert!(SpinDecimal::new(f64::INFINITY).is_none());
198        assert_eq!(SpinDecimal::parse("-1,2", ','), SpinDecimal::new(-1.2));
199    }
200}