1use crate::{Node, SpinAction, spin_editable};
2
3#[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 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 SpinAction::StepFromDecimalDraft {
142 original,
143 draft,
144 steps,
145 } if original == self.original => {
146 let value = rounded(draft.0, self.decimals).clamp(self.minimum, self.maximum);
147 crate::range::step_float(
148 value,
149 self.limits(),
150 self.step,
151 steps,
152 self.wrap,
153 |value| rounded(value, self.decimals),
154 )
155 }
156 _ => return None,
157 };
158 let next = match action {
159 SpinAction::Increase if self.wrap && next > self.maximum => self.minimum,
160 SpinAction::Decrease if self.wrap && next < self.minimum => self.maximum,
161 _ => next.clamp(self.minimum, self.maximum),
162 };
163 (next != self.original.map_or(self.value, |value| value.0)).then_some(next)
164 }
165}
166
167pub fn decimal_spin_value_after(node: &Node, action: SpinAction) -> Option<f64> {
168 if node.kind != "DoubleSpinBox"
169 || node.boolean("read-only", false)
170 || matches!(
171 action,
172 SpinAction::CommitDecimal(_)
173 | SpinAction::CommitDecimalIfCurrent { .. }
174 | SpinAction::StepFromDecimalDraft { .. }
175 ) && !spin_editable(node)
176 {
177 return None;
178 }
179 DecimalSpinRange::from_node(node).apply(action)
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn draft_step_wraps_at_the_display_precision_and_rejects_a_stale_step_size() {
188 let mut node = Node::new("DoubleSpinBox", None);
189 node.properties.insert("value", 0.2_f64.into());
190 node.properties.insert("minimum", (-0.4_f64).into());
191 node.properties.insert("maximum", 0.3_f64.into());
192 node.properties.insert("wrap", true.into());
193 node.properties.insert("step-size", 0.1_f64.into());
194 let action = SpinAction::StepFromDecimalDraft {
195 original: SpinDecimal::new(0.2),
196 draft: SpinDecimal::parse("0,30", ',').unwrap(),
197 steps: 1,
198 };
199 let prepare = |live: &Node| {
200 crate::prepare_spin_view(
201 &node,
202 action,
203 || true,
204 || live.properties["value"].clone(),
205 |name| live.properties.get(name).cloned(),
206 || decimal_spin_value_after(&node, action),
207 )
208 };
209 assert_eq!(prepare(&node), Some(-0.4));
210 let mut live = node.clone();
211 live.properties.insert("step-size", 0.25_f64.into());
212 assert_eq!(prepare(&live), None);
213 assert_eq!(decimal_spin_value_after(&live, action), Some(-0.4));
214 live.properties.insert("value", 0.1_f64.into());
215 assert_eq!(decimal_spin_value_after(&live, action), None);
216 }
217
218 #[test]
219 fn decimal_steps_compare_rounded_values_before_wrapping() {
220 let mut node = Node::new("DoubleSpinBox", None);
221 node.properties.insert("minimum", (-0.4_f64).into());
222 node.properties.insert("maximum", 0.3_f64.into());
223 node.properties.insert("step-size", 0.1_f64.into());
224 node.properties.insert("wrap", true.into());
225 node.properties.insert("value", 0.2_f64.into());
226 assert_eq!(
227 decimal_spin_value_after(&node, SpinAction::Increase),
228 Some(0.3)
229 );
230 node.properties.insert("value", 0.3_f64.into());
231 assert_eq!(
232 decimal_spin_value_after(&node, SpinAction::Increase),
233 Some(-0.4)
234 );
235 node.properties.insert("value", (-0.4_f64).into());
236 assert_eq!(
237 decimal_spin_value_after(&node, SpinAction::Decrease),
238 Some(0.3)
239 );
240
241 node.properties.insert("minimum", (-f64::MAX).into());
242 node.properties.insert("maximum", f64::MAX.into());
243 node.properties.insert("value", f64::MAX.into());
244 node.properties.insert("step-size", f64::MAX.into());
245 assert_eq!(
246 decimal_spin_value_after(&node, SpinAction::Increase),
247 Some(-f64::MAX)
248 );
249 }
250
251 #[test]
252 fn decimal_drafts_allow_partial_input_but_only_finite_values_can_commit() {
253 assert!(spin_text_is_valid("-,", Some(',')));
254 assert!(SpinDecimal::parse("-,", ',').is_none());
255 assert!(SpinDecimal::parse("1.2", ',').is_none());
256 assert!(SpinDecimal::parse("NaN", '.').is_none());
257 assert!(SpinDecimal::parse(&"9".repeat(400), '.').is_none());
258 assert!(SpinDecimal::new(f64::INFINITY).is_none());
259 assert_eq!(SpinDecimal::parse("-1,2", ','), SpinDecimal::new(-1.2));
260 }
261}