1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! How a number is written, read back, and applied while being edited.
//!
//! Used by [`crate::DragValue`], [`crate::Slider`], and [`crate::RangeSlider`].
use alloc::sync::Arc;
use core::ops::RangeInclusive;
use crate::{Atoms, IntoAtoms, MINUS_CHAR_STR, emath};
/// Formats a value for display, given the range of decimals it may show.
pub type NumFormatter<'a> = Arc<dyn 'a + Fn(f64, RangeInclusive<usize>) -> String>;
/// Parses what the user typed, returning `None` if it is not a number.
pub type NumParser<'a> = Arc<dyn 'a + Fn(&str) -> Option<f64>>;
// ----------------------------------------------------------------------------
/// How a number is written, read back, and applied while being edited.
///
/// Owned by [`crate::DragValue`], and by [`crate::Slider`] and [`crate::RangeSlider`]
/// for the numbers they show beside the rail.
#[derive(Clone)]
pub struct ValueFormat<'a> {
/// Shown before the number, e.g. `"x: "`.
pub prefix: Atoms<'a>,
/// Shown after the number, e.g. a unit.
pub suffix: Atoms<'a>,
/// Show at least this many decimals.
pub min_decimals: usize,
/// Show at most this many decimals, and round values to it.
pub max_decimals: Option<usize>,
/// Turns a value into text. Default: [`crate::style::NumberFormatter`].
pub custom_formatter: Option<NumFormatter<'a>>,
/// Turns text back into a value. Default: accepts plain decimal numbers.
pub custom_parser: Option<NumParser<'a>>,
/// Apply each keystroke while typing, rather than on enter.
pub update_while_editing: bool,
}
impl Default for ValueFormat<'_> {
fn default() -> Self {
Self {
prefix: Atoms::default(),
suffix: Atoms::default(),
min_decimals: 0,
max_decimals: None,
custom_formatter: None,
custom_parser: None,
update_while_editing: true,
}
}
}
impl<'a> ValueFormat<'a> {
/// Show a prefix before the number, e.g. "x: ".
///
/// Goes in front of any prefix already set, so `.prefix("b").prefix("a")` shows `ab`.
#[inline]
pub fn prefix(mut self, prefix: impl IntoAtoms<'a>) -> Self {
self.prefix.extend_left(prefix.into_atoms());
self
}
/// Add a suffix to the number, this can be e.g. a unit ("°" or " m").
///
/// Goes after any suffix already set, so `.suffix("a").suffix("b")` shows `ab`.
#[inline]
pub fn suffix(mut self, suffix: impl IntoAtoms<'a>) -> Self {
self.suffix.extend_right(suffix.into_atoms());
self
}
/// Set a minimum number of decimals to display.
#[inline]
pub fn min_decimals(mut self, min_decimals: usize) -> Self {
self.min_decimals = min_decimals;
self
}
/// Set a maximum number of decimals to display.
/// Values will also be rounded to this number of decimals.
#[inline]
pub fn max_decimals(mut self, max_decimals: usize) -> Self {
self.max_decimals = Some(max_decimals);
self
}
/// Set the maximum number of decimals to display, or `None` to let the widget pick.
///
/// Values will also be rounded to this number of decimals when it is set.
#[inline]
pub fn max_decimals_opt(mut self, max_decimals: Option<usize>) -> Self {
self.max_decimals = max_decimals;
self
}
/// Set an exact number of decimals to display.
/// Values will also be rounded to this number of decimals.
#[inline]
pub fn fixed_decimals(mut self, num_decimals: usize) -> Self {
self.min_decimals = num_decimals;
self.max_decimals = Some(num_decimals);
self
}
/// Set custom formatter defining how numbers are converted into text.
///
/// A custom formatter takes a `f64` for the numeric value and a `RangeInclusive<usize>` representing
/// the decimal range i.e. minimum and maximum number of decimal places shown.
///
/// See also: [`Self::custom_parser`]
pub fn custom_formatter(
mut self,
formatter: impl 'a + Fn(f64, RangeInclusive<usize>) -> String,
) -> Self {
self.custom_formatter = Some(Arc::new(formatter));
self
}
/// Set custom parser defining how the text input is parsed into a number.
///
/// A custom parser takes an `&str` to parse into a number and returns a `f64` if it was successfully parsed
/// or `None` otherwise.
///
/// See also: [`Self::custom_formatter`]
#[inline]
pub fn custom_parser(mut self, parser: impl 'a + Fn(&str) -> Option<f64>) -> Self {
self.custom_parser = Some(Arc::new(parser));
self
}
/// Set `custom_formatter` and `custom_parser` to display and parse numbers as binary integers. Floating point
/// numbers are *not* supported.
///
/// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be
/// prefixed with additional 0s to match `min_width`.
///
/// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise
/// they will be prefixed with a '-' sign.
///
/// # Panics
///
/// Panics if `min_width` is 0.
pub fn binary(self, min_width: usize, twos_complement: bool) -> Self {
assert!(
0 < min_width,
"ValueFormat::binary: `min_width` must be greater than 0"
);
if twos_complement {
self.custom_formatter(move |n, _| format!("{:0>min_width$b}", n as i64))
} else {
self.custom_formatter(move |n, _| {
let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" };
format!("{sign}{:0>min_width$b}", n.abs() as i64)
})
}
.custom_parser(|s| i64::from_str_radix(s, 2).map(|n| n as f64).ok())
}
/// Set `custom_formatter` and `custom_parser` to display and parse numbers as octal integers. Floating point
/// numbers are *not* supported.
///
/// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be
/// prefixed with additional 0s to match `min_width`.
///
/// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise
/// they will be prefixed with a '-' sign.
///
/// # Panics
///
/// Panics if `min_width` is 0.
pub fn octal(self, min_width: usize, twos_complement: bool) -> Self {
assert!(
0 < min_width,
"ValueFormat::octal: `min_width` must be greater than 0"
);
if twos_complement {
self.custom_formatter(move |n, _| format!("{:0>min_width$o}", n as i64))
} else {
self.custom_formatter(move |n, _| {
let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" };
format!("{sign}{:0>min_width$o}", n.abs() as i64)
})
}
.custom_parser(|s| i64::from_str_radix(s, 8).map(|n| n as f64).ok())
}
/// Set `custom_formatter` and `custom_parser` to display and parse numbers as hexadecimal integers. Floating point
/// numbers are *not* supported.
///
/// `min_width` specifies the minimum number of displayed digits; if the number is shorter than this, it will be
/// prefixed with additional 0s to match `min_width`.
///
/// If `twos_complement` is true, negative values will be displayed as the 2's complement representation. Otherwise
/// they will be prefixed with a '-' sign.
///
/// # Panics
///
/// Panics if `min_width` is 0.
pub fn hexadecimal(self, min_width: usize, twos_complement: bool, upper: bool) -> Self {
assert!(
0 < min_width,
"ValueFormat::hexadecimal: `min_width` must be greater than 0"
);
match (twos_complement, upper) {
(true, true) => {
self.custom_formatter(move |n, _| format!("{:0>min_width$X}", n as i64))
}
(true, false) => {
self.custom_formatter(move |n, _| format!("{:0>min_width$x}", n as i64))
}
(false, true) => self.custom_formatter(move |n, _| {
let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" };
format!("{sign}{:0>min_width$X}", n.abs() as i64)
}),
(false, false) => self.custom_formatter(move |n, _| {
let sign = if n < 0.0 { MINUS_CHAR_STR } else { "" };
format!("{sign}{:0>min_width$x}", n.abs() as i64)
}),
}
.custom_parser(|s| i64::from_str_radix(s, 16).map(|n| n as f64).ok())
}
/// Update the value on each key press when text-editing the value.
///
/// Default: `true`.
/// If `false`, the value will only be updated when user presses enter or deselects the value.
#[inline]
pub fn update_while_editing(mut self, update: bool) -> Self {
self.update_while_editing = update;
self
}
/// Rounds `value` to `max_decimals`, if set.
pub fn round(&self, value: f64) -> f64 {
match self.max_decimals {
Some(max_decimals) => emath::round_to_decimals(value, max_decimals),
None => value,
}
}
}
// ----------------------------------------------------------------------------