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