Skip to main content

egui_pop_core/
number.rs

1//! A number input (a spin box): the value typed in a field, its unit
2//! beside it, and small up and down arrows. For a value whose range is
3//! too wide for a slider (a count up to millions, days up to years).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! - Typing commits on Enter or when the field loses focus; Escape
9//!   drops the typed text.
10//! - A typed value outside the range, a fraction where a whole number is
11//!   expected, or a text that is not a number is refused: the value stays
12//!   and the reason shows beside the field.
13//! - The arrows, the Up and Down keys and the mouse wheel (over the
14//!   focused field) step the value, clamped to the range; with Shift, ten
15//!   steps at once.
16//! - The value is shown in the interface's number format (large counts
17//!   grouped: 1 000 000).
18//!
19//! ```
20//! use egui_pop_core::number::NumberInput;
21//!
22//! fn kept(ui: &mut egui::Ui, files: &mut f64) {
23//!     NumberInput::new(files, "Files kept", 1000.0..=100_000_000.0)
24//!         .integer()
25//!         .unit("files")
26//!         .show(ui);
27//! }
28//! ```
29
30use std::ops::RangeInclusive;
31
32use egui::{
33    Align2, Color32, Id, Key, Modifiers, Pos2, Rect, Response, Role, Sense, Shape, Stroke,
34    TextEdit, Ui,
35};
36use egui_pop_model::values::{Descriptor, Type};
37
38use crate::strings::{self, NUMBER_DECREASE, NUMBER_INCREASE, NUMBER_NOT_A_NUMBER};
39use crate::strings::{NUMBER_OUT_OF_RANGE, NUMBER_WHOLE};
40
41/// The widest range, `max - min`, still drawn as a slider by
42/// [`crate::param`]; past it, a value is a [`NumberInput`]. An image
43/// parameter (a radius up to 500, a black point up to 255, a hue in
44/// degrees) still slides; a count up to millions or days up to years is
45/// typed. A descriptor's soft range, when it has one, is the range
46/// measured: its author asked for a slider over it.
47pub const SLIDER_SPAN: f64 = 1000.0;
48
49/// Whether a number descriptor is better typed than slid: its range is
50/// wider than [`SLIDER_SPAN`].
51pub fn is_wide(d: &Descriptor) -> bool {
52    matches!(d.ty, Type::Int | Type::Float)
53        && d.soft
54            .or(d.hard)
55            .is_some_and(|(lo, hi)| hi - lo > SLIDER_SPAN)
56}
57
58/// Why a typed value was refused.
59#[derive(Clone, Debug, PartialEq)]
60pub enum Refusal {
61    /// The text is not a number.
62    NotANumber,
63    /// A fraction where a whole number is expected.
64    NotWhole,
65    /// Outside the range.
66    OutOfRange,
67}
68
69/// A number input; see the [module](self).
70///
71/// Need (input): a number field with steps and limits.
72#[derive(Debug)]
73#[must_use = "call .show(ui)"]
74pub struct NumberInput<'a> {
75    value: &'a mut f64,
76    label: String,
77    range: RangeInclusive<f64>,
78    step: f64,
79    integer: bool,
80    unit: String,
81    decimals: usize,
82    width: Option<f32>,
83}
84
85/// A range end at or past this magnitude counts as no end: the field is
86/// sized to the value shown, not to the end (`f64::MAX` would ask for
87/// the widest field). Past it, an `f64` no longer holds every whole
88/// number.
89const UNBOUNDED: f64 = 9.0e15;
90
91/// What the field keeps between frames.
92#[derive(Clone, Default)]
93struct Typing {
94    text: String,
95    refused: Option<String>,
96    /// Typed in since the last commit: the text is the person's, not
97    /// the value's.
98    edited: bool,
99    /// The value last drawn: one changed elsewhere (a reset) drops
100    /// what was typed and its refusal.
101    value: Option<f64>,
102}
103
104impl<'a> NumberInput<'a> {
105    /// A number in `range`, named `label` (its arrows are named after it).
106    pub fn new(value: &'a mut f64, label: &str, range: RangeInclusive<f64>) -> Self {
107        Self {
108            value,
109            label: label.into(),
110            range,
111            step: 1.0,
112            integer: false,
113            unit: String::new(),
114            decimals: 0,
115            width: None,
116        }
117    }
118
119    /// The input a descriptor calls for: its hard range, step, unit and
120    /// precision; whole numbers for an int.
121    pub fn from_descriptor(value: &'a mut f64, d: &Descriptor) -> Self {
122        let (lo, hi) = d.hard.or(d.soft).unwrap_or((f64::MIN, f64::MAX));
123        let mut n = Self::new(value, &d.label, lo..=hi)
124            .step(d.step)
125            .decimals(d.precision as usize);
126        if let Some(u) = &d.unit {
127            n = n.unit(u);
128        }
129        if d.ty == Type::Int { n.integer() } else { n }
130    }
131
132    /// One arrow step (one by default).
133    pub fn step(mut self, step: f64) -> Self {
134        if step > 0.0 {
135            self.step = step;
136        }
137        self
138    }
139
140    /// Whole numbers only.
141    pub fn integer(mut self) -> Self {
142        self.integer = true;
143        self.step = self.step.max(1.0).round();
144        self.decimals = 0;
145        self
146    }
147
148    /// The unit shown after the field.
149    pub fn unit(mut self, unit: &str) -> Self {
150        self.unit = unit.into();
151        self
152    }
153
154    /// Decimals shown.
155    pub fn decimals(mut self, decimals: usize) -> Self {
156        if !self.integer {
157            self.decimals = decimals;
158        }
159        self
160    }
161
162    /// The field's width, in points (the unit and the arrows come
163    /// after it). By default the field is as wide as the range's widest
164    /// end with two more digits, or, with no range (an end at
165    /// `f64::MAX`), as the value shown with two more digits; between
166    /// 48 and 160 points either way.
167    pub fn width(mut self, points: f32) -> Self {
168        if points.is_finite() && points > 0.0 {
169            self.width = Some(points);
170        }
171        self
172    }
173
174    /// The field's width when none is given: its widest text with room
175    /// for two more digits.
176    fn field_width(&self, ui: &Ui, value: f64) -> f32 {
177        if let Some(w) = self.width {
178            return w;
179        }
180        let ctx = ui.ctx();
181        let (lo, hi) = (*self.range.start(), *self.range.end());
182        let unbounded = |v: f64| !v.is_finite() || v.abs() >= UNBOUNDED;
183        let texts = if unbounded(lo) || unbounded(hi) {
184            vec![self.shown(ctx, value)]
185        } else {
186            vec![self.shown(ctx, lo), self.shown(ctx, hi)]
187        };
188        let font = egui::TextStyle::Body.resolve(ui.style());
189        let widest = texts
190            .into_iter()
191            .map(|t| {
192                ui.painter()
193                    .layout_no_wrap(format!("{t}00"), font.clone(), Color32::WHITE)
194                    .size()
195                    .x
196            })
197            .fold(0.0_f32, f32::max);
198        widest.clamp(48.0, 160.0)
199    }
200
201    /// A typed text's value, or why it is refused.
202    pub fn parse(&self, text: &str) -> Result<f64, Refusal> {
203        let v = crate::slider::parse_typed(text).ok_or(Refusal::NotANumber)?;
204        if self.integer && v.fract() != 0.0 {
205            return Err(Refusal::NotWhole);
206        }
207        if !self.range.contains(&v) {
208            return Err(Refusal::OutOfRange);
209        }
210        Ok(v)
211    }
212
213    fn clamp(&self, v: f64) -> f64 {
214        let v = v.clamp(*self.range.start(), *self.range.end());
215        if self.integer { v.round() } else { v }
216    }
217
218    fn shown(&self, ctx: &egui::Context, v: f64) -> String {
219        strings::number(ctx, v, self.decimals)
220    }
221
222    fn reason(&self, ctx: &egui::Context, refusal: &Refusal) -> String {
223        match refusal {
224            Refusal::NotANumber => strings::tr(ctx, &NUMBER_NOT_A_NUMBER),
225            Refusal::NotWhole => strings::tr(ctx, &NUMBER_WHOLE),
226            Refusal::OutOfRange => {
227                let min = self.shown(ctx, *self.range.start());
228                let max = self.shown(ctx, *self.range.end());
229                let min = strings::quantity(ctx, &min, &self.unit);
230                let max = strings::quantity(ctx, &max, &self.unit);
231                strings::tr_args(
232                    ctx,
233                    &NUMBER_OUT_OF_RANGE,
234                    &[("min", min.as_str()), ("max", max.as_str())],
235                )
236            }
237        }
238    }
239
240    /// Draws the field, its unit, its arrows and a refusal's reason. The
241    /// response is the field's, marked changed when the value changed.
242    pub fn show(self, ui: &mut Ui) -> Response {
243        ui.horizontal(|ui| self.show_inner(ui)).inner
244    }
245
246    fn show_inner(self, ui: &mut Ui) -> Response {
247        let ctx = ui.ctx().clone();
248        let id = ui.make_persistent_id(("egui_pop.number", &self.label));
249        let edit_id = id.with("field");
250        let mut typing: Typing = ui.data(|d| d.get_temp(id)).unwrap_or_default();
251        let before = *self.value;
252        if typing.value.is_some_and(|v| v != before) {
253            typing.edited = false;
254            typing.refused = None;
255        }
256        if !typing.edited && typing.refused.is_none() {
257            typing.text = self.shown(&ctx, before);
258        }
259
260        let width = self.field_width(ui, before);
261        let mut field = ui.add(
262            TextEdit::singleline(&mut typing.text)
263                .id(edit_id)
264                .desired_width(width)
265                .align(Align2::RIGHT_CENTER),
266        );
267
268        crate::a11y::input(&ctx, field.id, &self.label);
269        if field.changed() {
270            typing.edited = true;
271        }
272        let mut next: Option<f64> = None;
273        if field.has_focus() {
274            // Shift first: a key without modifiers matches it too.
275            let (up10, down10, up, down) = ui.input_mut(|i| {
276                (
277                    i.count_and_consume_key(Modifiers::SHIFT, Key::ArrowUp),
278                    i.count_and_consume_key(Modifiers::SHIFT, Key::ArrowDown),
279                    i.count_and_consume_key(Modifiers::NONE, Key::ArrowUp),
280                    i.count_and_consume_key(Modifiers::NONE, Key::ArrowDown),
281                )
282            });
283            // The wheel steps the focused field only, so a page scrolled
284            // past it never changes it; the panel does not scroll then.
285            let wheel = if field.hovered() {
286                let w = crate::slider::wheel_steps(ui, field.id);
287                ui.input_mut(|i| {
288                    i.smooth_scroll_delta = egui::Vec2::ZERO;
289                    i.events
290                        .retain(|e| !matches!(e, egui::Event::MouseWheel { .. }));
291                });
292                w
293            } else {
294                0.0
295            };
296            let steps = up as f64 - down as f64 + 10.0 * (up10 as f64 - down10 as f64) + wheel;
297            if steps != 0.0 {
298                let from = self.parse(&typing.text).unwrap_or(before);
299                next = Some(self.clamp(from + steps * self.step));
300            }
301        }
302        if field.lost_focus() {
303            if ui.input(|i| i.key_pressed(Key::Escape)) {
304                typing.refused = None;
305                typing.edited = false;
306            } else {
307                match self.parse(&typing.text) {
308                    Ok(v) => {
309                        typing.refused = None;
310                        next = Some(self.clamp(v));
311                    }
312                    Err(r) => {
313                        typing.refused = Some(self.reason(&ctx, &r));
314                        typing.edited = false;
315                    }
316                }
317            }
318        }
319
320        if !self.unit.is_empty() {
321            ui.label(&self.unit);
322        }
323        let (up, down) = arrows(ui, id, &self.label);
324        if up || down {
325            let from = if typing.refused.is_some() {
326                before
327            } else {
328                self.parse(&typing.text).unwrap_or(before)
329            };
330            let sign = if up { 1.0 } else { -1.0 };
331            next = Some(self.clamp(from + sign * self.step));
332        }
333
334        if let Some(v) = next {
335            typing.refused = None;
336            typing.edited = false;
337            typing.text = self.shown(&ctx, v);
338            if v != before {
339                *self.value = v;
340                field.mark_changed();
341            }
342        }
343        if let Some(reason) = &typing.refused {
344            ui.colored_label(ui.visuals().error_fg_color, reason);
345        }
346        typing.value = Some(*self.value);
347        ui.data_mut(|d| d.insert_temp(id, typing));
348        field
349    }
350}
351
352/// The two small arrows, stacked; whether each was clicked.
353fn arrows(ui: &mut Ui, id: Id, label: &str) -> (bool, bool) {
354    let ctx = ui.ctx().clone();
355    let h = ui.spacing().interact_size.y;
356    let (rect, _) = ui.allocate_exact_size(egui::vec2(h * 0.6, h), Sense::hover());
357    let halves = [
358        (
359            Rect::from_min_max(rect.min, Pos2::new(rect.max.x, rect.center().y)),
360            NUMBER_INCREASE,
361            true,
362        ),
363        (
364            Rect::from_min_max(Pos2::new(rect.min.x, rect.center().y), rect.max),
365            NUMBER_DECREASE,
366            false,
367        ),
368    ];
369    let mut clicked = [false, false];
370    for (i, (half, key, up)) in halves.into_iter().enumerate() {
371        let r = ui.interact(half, id.with(("arrow", up)), Sense::click());
372        let name = strings::tr_args(&ctx, &key, &[("label", label)]);
373        crate::a11y::name(&r, Role::Button, &name);
374        let visuals = ui.style().interact(&r);
375        let c = half.center();
376        let w = half.width() * 0.3;
377        let hh = half.height() * 0.25;
378        let points = if up {
379            vec![
380                Pos2::new(c.x - w, c.y + hh),
381                Pos2::new(c.x + w, c.y + hh),
382                Pos2::new(c.x, c.y - hh),
383            ]
384        } else {
385            vec![
386                Pos2::new(c.x - w, c.y - hh),
387                Pos2::new(c.x + w, c.y - hh),
388                Pos2::new(c.x, c.y + hh),
389            ]
390        };
391        ui.painter().add(Shape::convex_polygon(
392            points,
393            visuals.fg_stroke.color,
394            Stroke::NONE,
395        ));
396        clicked[i] = r.clicked();
397    }
398    (clicked[0], clicked[1])
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn typed_values_are_checked() {
407        let mut v = 30.0;
408        let n = NumberInput::new(&mut v, "Days", 0.0..=3650.0).integer();
409        assert_eq!(n.parse("90"), Ok(90.0));
410        assert_eq!(n.parse("1 000 days"), Ok(1000.0));
411        assert_eq!(n.parse("4000"), Err(Refusal::OutOfRange));
412        assert_eq!(n.parse("-1"), Err(Refusal::OutOfRange));
413        assert_eq!(n.parse("1.5"), Err(Refusal::NotWhole));
414        assert_eq!(n.parse("many"), Err(Refusal::NotANumber));
415        assert_eq!(n.clamp(5000.0), 3650.0);
416    }
417
418    #[test]
419    fn only_wide_ranges_are_typed() {
420        assert!(is_wide(&Descriptor::int(
421            "Files",
422            1000,
423            100_000_000,
424            1_000_000
425        )));
426        assert!(is_wide(&Descriptor::int("Days", 0, 3650, 30)));
427        assert!(!is_wide(&Descriptor::int("Calls", 1, 64, 8)));
428        assert!(!is_wide(&Descriptor::int("Radius", 0, 500, 20)));
429        assert!(!is_wide(&Descriptor::float("Hue", 0.0, 360.0, 200.0)));
430        assert!(!is_wide(
431            &Descriptor::int("Files", 0, 100_000, 10).soft(0.0, 100.0)
432        ));
433        assert!(!is_wide(&Descriptor::float("Gain", 0.0, 2.0, 1.0)));
434        assert!(!is_wide(&Descriptor::bool("On", true)));
435    }
436}