Skip to main content

waft_winui/controls/
number_box.rs

1//! NumberBox.xaml, NumberBox_themeresources.xaml and NumberBox.cpp: a text box for one number.
2//! It shows the value formatted, reads what is typed (as arithmetic with `accepts_expression`),
3//! keeps the value between `minimum` and `maximum`, and steps it by `small_change` and
4//! `large_change` from the arrow and page keys, the mouse wheel and its spin buttons, inline or
5//! in a popup.
6//!
7//! The application owns the value: `value` is what it passes, and `value_changed` asks for
8//! another. A value the box asks for is what the box itself reads as its value, and what it
9//! shows, until the application next builds it; if the application passed another value by
10//! then, the box shows that one. A change the box makes to a value the application passes,
11//! coercing it into range, is reported after the frame.
12
13mod formatter;
14mod parser;
15
16pub use formatter::{ComparableNumberFormatter, DecimalFormatter, NumberFormatter};
17
18use super::flyout::shadow::PopupShadow;
19use super::repeat_button::{RepeatButtonSetters, repeat_button_presenter};
20use super::text_control::TextControl;
21use crate::*;
22use formatter::round_for_display;
23use std::{any::Any, fmt, rc::Rc};
24use waft_embedder::{
25    Color, FontWeight, Offset, Rect, Size, TextAffinity, TextAlign, TextSelection,
26};
27use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref};
28use waft_gestures::{GestureBinding, PointerEvent};
29use waft_painting::{AlignmentGeometry, transform_rect};
30use waft_rendering::{BoxConstraints, SingleChildLayoutDelegate};
31use waft_scheduler::FrameCallback;
32use waft_services::{KeyEvent, LogicalKeyboardKey, TextEditingValue};
33use waft_widgets::Listener as PointerListener;
34use waft_widgets::*;
35
36/// XAML `NumberBoxSpinButtonPlacementMode`: where the spin buttons are.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
38pub enum NumberBoxSpinButtonPlacementMode {
39    /// No spin buttons.
40    #[default]
41    Hidden,
42    /// In a popup beside the box while it has the focus, with an indicator in the box.
43    Compact,
44    /// Inside the box, after the text.
45    Inline,
46}
47
48/// XAML `NumberBoxValidationMode`: what becomes of text that is not a number, and of values out
49/// of range.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51pub enum NumberBoxValidationMode {
52    /// Text that is not a number is replaced by the value, and a value out of range is moved to
53    /// the bound it passed.
54    #[default]
55    InvalidInputOverwritten,
56    /// Text that is not a number stays, and a value out of range is kept.
57    Disabled,
58}
59
60/// XAML `NumberBoxValueChangedEventArgs`.
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct NumberBoxValueChangedEventArgs {
63    /// `OldValue`: the value before the change; NaN for none.
64    pub old_value: f64,
65    /// `NewValue`: the value the box asks for; NaN for none.
66    pub new_value: f64,
67}
68
69/// Receives XAML `ValueChanged`.
70pub type NumberBoxValueChangedHandler = Rc<dyn Fn(&mut App, NumberBoxValueChangedEventArgs)>;
71
72/// XAML `NumberBox` with the template of `NumberBox.xaml`.
73#[derive(Clone)]
74pub struct NumberBox {
75    /// `Value`: the number shown, NaN for none.
76    pub value: f64,
77
78    /// `ValueChanged`: asks the application for another value; the application owns `value`.
79    pub value_changed: NumberBoxValueChangedHandler,
80
81    /// `Minimum`: the lowest value; the lowest finite double by default.
82    pub minimum: f64,
83
84    /// `Maximum`: the highest value; the highest finite double by default.
85    pub maximum: f64,
86
87    /// `SmallChange`: the step of the arrow keys, the wheel and the spin buttons; 1 by default.
88    pub small_change: f64,
89
90    /// `LargeChange`: the step of Page Up and Page Down; 10 by default.
91    pub large_change: f64,
92
93    /// `Text`: text for the box to read as if it were typed and committed, applied when it
94    /// changes; while `value` is NaN it gives the first value.
95    pub text: Option<String>,
96
97    /// `Header`: shown above the box.
98    pub header: Option<WidgetRef>,
99
100    /// `PlaceholderText`: shown while the box is empty.
101    pub placeholder_text: String,
102
103    /// `Description`: shown below the box.
104    pub description: Option<WidgetRef>,
105
106    /// `ValidationMode`.
107    pub validation_mode: NumberBoxValidationMode,
108
109    /// `SpinButtonPlacementMode`.
110    pub spin_button_placement_mode: NumberBoxSpinButtonPlacementMode,
111
112    /// `IsWrapEnabled`: whether a step past one bound goes to the other.
113    pub is_wrap_enabled: bool,
114
115    /// `AcceptsExpression`: whether typed arithmetic is computed.
116    pub accepts_expression: bool,
117
118    /// `NumberFormatter`: formats the value and reads typed numbers; `None` is NumberBox's own,
119    /// a `DecimalFormatter` with one integer digit and no fraction digits. The text is
120    /// formatted again when a formatter of another type or value is passed.
121    pub number_formatter: Option<Rc<dyn ComparableNumberFormatter>>,
122
123    /// `IsEnabled`.
124    pub is_enabled: bool,
125
126    /// `FontSize`: of the text, the header and the inline spin buttons' glyphs; the theme's `ControlContentThemeFontSize` when `None`.
127    pub font_size: Option<f64>,
128
129    /// `CornerRadius`: of the box and its inline spin buttons; the theme's `ControlCornerRadius`
130    /// when `None`.
131    pub corner_radius: Option<f64>,
132
133    /// `SelectionHighlightColor`: overrides the selection fill.
134    pub selection_highlight_color: Option<Color>,
135
136    /// `TextAlignment`.
137    pub text_alignment: TextAlign,
138
139    /// Identity retained across parent rebuilds.
140    pub key: Option<KeyRef>,
141}
142
143impl NumberBox {
144    /// Creates a box showing `value`, which asks for others through `value_changed`.
145    pub fn new(
146        value: f64,
147        value_changed: impl Fn(&mut App, NumberBoxValueChangedEventArgs) + 'static,
148    ) -> NumberBox {
149        NumberBox {
150            value,
151            value_changed: Rc::new(value_changed),
152            minimum: -f64::MAX,
153            maximum: f64::MAX,
154            small_change: 1.0,
155            large_change: 10.0,
156            text: None,
157            header: None,
158            placeholder_text: String::new(),
159            description: None,
160            validation_mode: NumberBoxValidationMode::InvalidInputOverwritten,
161            spin_button_placement_mode: NumberBoxSpinButtonPlacementMode::Hidden,
162            is_wrap_enabled: false,
163            accepts_expression: false,
164            number_formatter: None,
165            is_enabled: true,
166            font_size: None,
167            corner_radius: None,
168            selection_highlight_color: None,
169            text_alignment: TextAlign::Start,
170            key: None,
171        }
172    }
173
174    /// Sets Minimum.
175    pub fn minimum(mut self, value: f64) -> Self {
176        self.minimum = value;
177        self
178    }
179
180    /// Sets Maximum.
181    pub fn maximum(mut self, value: f64) -> Self {
182        self.maximum = value;
183        self
184    }
185
186    /// Sets SmallChange.
187    pub fn small_change(mut self, value: f64) -> Self {
188        self.small_change = value;
189        self
190    }
191
192    /// Sets LargeChange.
193    pub fn large_change(mut self, value: f64) -> Self {
194        self.large_change = value;
195        self
196    }
197
198    /// Sets Text.
199    pub fn text(mut self, value: impl Into<String>) -> Self {
200        self.text = Some(value.into());
201        self
202    }
203
204    /// Sets Header.
205    #[cfg_attr(debug_assertions, track_caller)]
206    pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
207        self.header = Some(value.into_widget());
208        self
209    }
210
211    /// Sets PlaceholderText.
212    pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
213        self.placeholder_text = value.into();
214        self
215    }
216
217    /// Sets Description.
218    #[cfg_attr(debug_assertions, track_caller)]
219    pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
220        self.description = Some(value.into_widget());
221        self
222    }
223
224    /// Sets ValidationMode.
225    pub fn validation_mode(mut self, value: NumberBoxValidationMode) -> Self {
226        self.validation_mode = value;
227        self
228    }
229
230    /// Sets SpinButtonPlacementMode.
231    pub fn spin_button_placement_mode(mut self, value: NumberBoxSpinButtonPlacementMode) -> Self {
232        self.spin_button_placement_mode = value;
233        self
234    }
235
236    /// Sets IsWrapEnabled.
237    pub fn is_wrap_enabled(mut self, value: bool) -> Self {
238        self.is_wrap_enabled = value;
239        self
240    }
241
242    /// Sets AcceptsExpression.
243    pub fn accepts_expression(mut self, value: bool) -> Self {
244        self.accepts_expression = value;
245        self
246    }
247
248    /// Sets NumberFormatter.
249    pub fn number_formatter(mut self, value: impl NumberFormatter + PartialEq + 'static) -> Self {
250        self.number_formatter = Some(Rc::new(value));
251        self
252    }
253
254    /// The formatter in use: `number_formatter`, or NumberBox's own.
255    fn formatter(&self) -> Rc<dyn NumberFormatter> {
256        match &self.number_formatter {
257            Some(formatter) => Rc::clone(formatter) as Rc<dyn NumberFormatter>,
258            None => Rc::new(DecimalFormatter::default()),
259        }
260    }
261
262    /// Sets IsEnabled.
263    pub fn is_enabled(mut self, value: bool) -> Self {
264        self.is_enabled = value;
265        self
266    }
267
268    /// Sets FontSize.
269    pub fn font_size(mut self, value: f64) -> Self {
270        self.font_size = Some(value);
271        self
272    }
273
274    /// Sets CornerRadius.
275    pub fn corner_radius(mut self, value: f64) -> Self {
276        self.corner_radius = Some(value);
277        self
278    }
279
280    /// Sets SelectionHighlightColor.
281    pub fn selection_highlight_color(mut self, value: Color) -> Self {
282        self.selection_highlight_color = Some(value);
283        self
284    }
285
286    /// Sets TextAlignment.
287    pub fn text_alignment(mut self, value: TextAlign) -> Self {
288        self.text_alignment = value;
289        self
290    }
291
292    /// Sets widget identity.
293    pub fn key(mut self, key: KeyRef) -> Self {
294        self.key = Some(key);
295        self
296    }
297}
298
299impl fmt::Debug for NumberBox {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("NumberBox")
302            .field("value", &self.value)
303            .field("minimum", &self.minimum)
304            .field("maximum", &self.maximum)
305            .field(
306                "spin_button_placement_mode",
307                &self.spin_button_placement_mode,
308            )
309            .field("is_enabled", &self.is_enabled)
310            .finish_non_exhaustive()
311    }
312}
313
314/// `CommonStates`: the header's foreground.
315#[derive(Clone, Copy, Debug, PartialEq, Eq)]
316enum NumberBoxCommonState {
317    Normal,
318    Disabled,
319}
320
321/// `SpinButtonStates`, which `UpdateSpinButtonPlacement` sets on the box and on `InputBox`
322/// alike.
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324#[allow(clippy::enum_variant_names, reason = "the template's state names")]
325pub(super) enum SpinButtonsState {
326    SpinButtonsCollapsed,
327    /// `UpSpinButton`, `DownSpinButton` and `InputEater` show, and `InputBox` is at least
328    /// `NumberBoxMinWidth` wide.
329    SpinButtonsVisible,
330    /// `InputBox` shows its `PopupIndicator`.
331    SpinButtonsPopup,
332}
333
334impl SpinButtonsState {
335    /// The state `UpdateSpinButtonPlacement` goes to for `mode`.
336    fn of(mode: NumberBoxSpinButtonPlacementMode) -> SpinButtonsState {
337        match mode {
338            NumberBoxSpinButtonPlacementMode::Hidden => SpinButtonsState::SpinButtonsCollapsed,
339            NumberBoxSpinButtonPlacementMode::Compact => SpinButtonsState::SpinButtonsPopup,
340            NumberBoxSpinButtonPlacementMode::Inline => SpinButtonsState::SpinButtonsVisible,
341        }
342    }
343}
344
345/// `UpSpinButtonEnabledStates` and `DownSpinButtonEnabledStates`: whether the inline and popup
346/// button of one direction can be pressed.
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
348enum SpinButtonEnabledState {
349    Enabled,
350    Disabled,
351}
352
353/// `NumberBoxTextBoxStyle`: the TextBox template of NumberBox's `InputBox`, in the
354/// `SpinButtonStates` state the box sends it to.
355#[derive(Clone, Copy, Debug, PartialEq)]
356pub(super) struct NumberBoxTextBoxStyle {
357    /// The state `UpdateSpinButtonPlacement` sets on `InputBox`.
358    pub(super) spin_buttons: SpinButtonsState,
359    /// `InputBox.MinWidth`: `TextControlThemeMinWidth`, or `NumberBoxMinWidth` while the spin
360    /// buttons are inline.
361    pub(super) min_width: f64,
362}
363
364/// `MinWidth` of the template's `DeleteButton`.
365const DELETE_BUTTON_MIN_WIDTH: f64 = 40.0;
366
367/// `SpinButtonsColumn.Width` in the `SpinButtonsVisible` state: the room the inline spin buttons
368/// cover.
369const SPIN_BUTTONS_COLUMN_WIDTH: f64 = 72.0;
370
371/// `NumberBoxSpinButtonStyle`'s `MinWidth`.
372const SPIN_BUTTON_MIN_WIDTH: f64 = 32.0;
373
374/// `NumberBoxPopupSpinButtonStyle`'s `Width` and `Height`.
375const POPUP_SPIN_BUTTON_SIZE: f64 = 36.0;
376
377/// `NumberBoxPopupSpinButtonStyle`'s `FontSize`.
378const POPUP_SPIN_BUTTON_FONT_SIZE: f64 = 16.0;
379
380/// `PopupContentRoot`'s `Padding`.
381const POPUP_CONTENT_PADDING: f64 = 6.0;
382
383/// `PopupIndicator`'s `FontSize`.
384const POPUP_INDICATOR_FONT_SIZE: f64 = 12.0;
385
386impl NumberBoxTextBoxStyle {
387    /// `SpinButtonsColumn`: 72 wide while the spin buttons are inline, else as wide as what it
388    /// holds.
389    pub(super) fn spin_buttons_column(self) -> ColumnDefinition {
390        ColumnDefinition::new(match self.spin_buttons {
391            SpinButtonsState::SpinButtonsVisible => GridLength::pixel(SPIN_BUTTONS_COLUMN_WIDTH),
392            _ => GridLength::AUTO,
393        })
394    }
395
396    /// `PopupIndicator`, which the `SpinButtonsPopup` state shows in `SpinButtonsColumn`.
397    pub(super) fn popup_indicator(self, resources: &ThemeResources) -> Option<WidgetRef> {
398        if self.spin_buttons != SpinButtonsState::SpinButtonsPopup {
399            return None;
400        }
401        let foreground = resources.number_box_popup_indicator_foreground;
402        Some(
403            Margin::new(
404                resources.number_box_popup_indicator_margin,
405                Center::new().width_factor(1.0).height_factor(1.0).child(
406                    FontIcon::symbol(FluentSymbol::ChevronUpDown)
407                        .font_size(POPUP_INDICATOR_FONT_SIZE)
408                        .foreground(foreground),
409                ),
410            )
411            .into_widget(),
412        )
413    }
414
415    /// `DeleteButton`'s width: its height, as `TextBox::OnDeleteButtonSizeChanged` keeps it,
416    /// but not under its `MinWidth`.
417    pub(super) fn delete_button_width(self, height: f64) -> f64 {
418        height.max(DELETE_BUTTON_MIN_WIDTH)
419    }
420}
421
422/// `Minimum` and `Maximum`, as `CoerceMinimum` and `CoerceMaximum` leave them.
423#[derive(Clone, Copy, Debug, PartialEq)]
424struct Bounds {
425    minimum: f64,
426    maximum: f64,
427}
428
429impl Bounds {
430    /// The bounds after `minimum` or `maximum` changed. A change of `Maximum` alone runs
431    /// `CoerceMinimum`, lowering a `Minimum` above it to it; any other runs `CoerceMaximum`,
432    /// raising a `Maximum` below `Minimum` to it.
433    fn new(minimum: f64, maximum: f64, maximum_changed_alone: bool) -> Bounds {
434        if maximum_changed_alone && minimum > maximum {
435            Bounds {
436                minimum: maximum,
437                maximum,
438            }
439        } else if maximum < minimum {
440            Bounds {
441                minimum,
442                maximum: minimum,
443            }
444        } else {
445            Bounds { minimum, maximum }
446        }
447    }
448
449    /// `IsInBounds`.
450    fn contain(self, value: f64) -> bool {
451        value >= self.minimum && value <= self.maximum
452    }
453}
454
455/// `CoerceValue`: a value out of bounds goes to the bound it passed when invalid input is
456/// overwritten; NaN stays.
457fn coerce_value(value: f64, bounds: Bounds, mode: NumberBoxValidationMode) -> f64 {
458    if value.is_nan()
459        || bounds.contain(value)
460        || mode != NumberBoxValidationMode::InvalidInputOverwritten
461    {
462        value
463    } else if value > bounds.maximum {
464        bounds.maximum
465    } else {
466        bounds.minimum
467    }
468}
469
470/// `StepValue`'s arithmetic: `value` moved by `change`, and with wrapping a value past one bound
471/// goes to the other.
472fn stepped(value: f64, change: f64, bounds: Bounds, wrap: bool) -> f64 {
473    let value = value + change;
474    if !wrap {
475        value
476    } else if value > bounds.maximum {
477        bounds.minimum
478    } else if value < bounds.minimum {
479        bounds.maximum
480    } else {
481        value
482    }
483}
484
485/// `UpdateSpinButtonEnabled`: with a value, both directions can step when wrapping or when
486/// invalid input is kept, and otherwise each until its bound; without one neither can.
487fn spin_button_enabled_states(
488    value: f64,
489    bounds: Bounds,
490    wrap: bool,
491    mode: NumberBoxValidationMode,
492) -> (SpinButtonEnabledState, SpinButtonEnabledState) {
493    let state = |enabled: bool| {
494        if enabled {
495            SpinButtonEnabledState::Enabled
496        } else {
497            SpinButtonEnabledState::Disabled
498        }
499    };
500    if value.is_nan() {
501        return (state(false), state(false));
502    }
503    if wrap || mode != NumberBoxValidationMode::InvalidInputOverwritten {
504        return (state(true), state(true));
505    }
506    (state(value < bounds.maximum), state(value > bounds.minimum))
507}
508
509/// Whether `new` is another value than `old`, NaN being one value: `OnValuePropertyChanged`'s
510/// test before it raises `ValueChanged`.
511fn differs(old: f64, new: f64) -> bool {
512    new != old && !(new.is_nan() && old.is_nan())
513}
514
515/// What `UpdateTextToValue` shows for `value`: nothing for NaN, else the value rounded by the
516/// display rounder and formatted.
517fn displayed_text(value: f64, formatter: &dyn NumberFormatter) -> String {
518    if value.is_nan() {
519        String::new()
520    } else {
521        formatter.format_double(round_for_display(value))
522    }
523}
524
525/// `trim` of NumberBox.cpp: without leading and trailing spaces, line breaks, tabs, form feeds
526/// and vertical tabs.
527fn trim(text: &str) -> &str {
528    text.trim_matches([' ', '\n', '\r', '\t', '\x0c', '\x0b'])
529}
530
531impl StatefulWidget for NumberBox {
532    type State = NumberBoxState;
533
534    fn key(&self) -> Option<&KeyRef> {
535        self.key.as_ref()
536    }
537
538    fn create_state(&self) -> NumberBoxState {
539        NumberBoxState {
540            state: StateData::new(),
541            controller: None,
542            focus: None,
543            popup: None,
544            value: f64::NAN,
545            bounds: Bounds {
546                minimum: self.minimum,
547                maximum: self.maximum,
548            },
549            requested: None,
550            focused: false,
551        }
552    }
553}
554
555/// The parts NumberBox.cpp keeps of its template, and its value.
556pub struct NumberBoxState {
557    state: StateData<NumberBox>,
558
559    /// `InputBox`'s text.
560    controller: Option<Ref<TextEditingController>>,
561
562    /// `InputBox`'s focus, which takes the arrow, page, Enter and Escape keys before the text
563    /// box does, as `PreviewKeyDown` and `KeyUp` do.
564    focus: Option<Ref<FocusNode>>,
565
566    /// Shows `UpDownPopup`.
567    popup: Option<Ref<OverlayPortalController>>,
568
569    /// `Value`: the application's value, as `CoerceValue` left it.
570    value: f64,
571
572    /// `Minimum` and `Maximum`, as their coercion left them.
573    bounds: Bounds,
574
575    /// The value the box last asked for, until the application next builds it.
576    requested: Option<f64>,
577
578    /// Whether `InputBox` has the focus, as `GotFocus` and `LostFocus` last said.
579    focused: bool,
580}
581
582impl NumberBoxState {
583    fn controller(self: Handle<Self>, app: &App) -> Handle<TextEditingController> {
584        app.get(self)
585            .controller
586            .handle()
587            .expect("an initialized NumberBox")
588    }
589
590    fn focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
591        app.get(self)
592            .focus
593            .handle()
594            .expect("an initialized NumberBox")
595    }
596
597    fn popup(self: Handle<Self>, app: &App) -> Handle<OverlayPortalController> {
598        app.get(self)
599            .popup
600            .handle()
601            .expect("an initialized NumberBox")
602    }
603
604    /// `Value()` as the box's own logic reads it: the value it last asked for, until the
605    /// application answers, else the application's.
606    fn current_value(self: Handle<Self>, app: &App) -> f64 {
607        let state = app.get(self);
608        state.requested.unwrap_or(state.value)
609    }
610
611    /// The `Value` setter, for a value the box sets, and `OnValuePropertyChanged`: setting NaN
612    /// over NaN, or the value there already is, changes nothing; otherwise `CoerceValue` keeps
613    /// it in range, `ValueChanged` asks the application for it when it is another value, and the
614    /// text shows it.
615    fn put_value(self: Handle<Self>, app: &mut App, value: f64) {
616        let old = self.current_value(app);
617        if !differs(old, value) {
618            return;
619        }
620        let widget = self.widget(app);
621        let (handler, mode) = (widget.value_changed.clone(), widget.validation_mode);
622        let new = coerce_value(value, app.get(self).bounds, mode);
623        if differs(old, new) {
624            self.set_state(app, |state| state.requested = Some(new));
625            handler(
626                app,
627                NumberBoxValueChangedEventArgs {
628                    old_value: old,
629                    new_value: new,
630                },
631            );
632        }
633        if self.mounted(app) {
634            self.update_text_to_value(app, new);
635        }
636    }
637
638    /// `UpdateTextToValue`: `InputBox` shows `value`. Replacing its text puts the caret at the
639    /// start, as setting `TextBox.Text` does.
640    fn update_text_to_value(self: Handle<Self>, app: &mut App, value: f64) {
641        let text = displayed_text(value, &*self.widget(app).formatter());
642        self.set_text(app, text);
643    }
644
645    /// Puts `text` in `InputBox` when it holds other text, with the caret at the start.
646    fn set_text(self: Handle<Self>, app: &mut App, text: String) {
647        let controller = self.controller(app);
648        if controller.text_value(app) != text {
649            controller.set_value(
650                app,
651                TextEditingValue::new()
652                    .text(text)
653                    .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
654            );
655        }
656    }
657
658    /// `ValidateInput`: commits `InputBox`'s text. Empty text clears the value. Text that reads
659    /// as a number, or computes to one with `accepts_expression`, becomes the value, and is
660    /// formatted even when the value stays. Other text is replaced by the value unless
661    /// validation is disabled.
662    fn validate_input(self: Handle<Self>, app: &mut App) {
663        let text = trim(self.controller(app).text_value(app)).to_owned();
664        if text.is_empty() {
665            self.put_value(app, f64::NAN);
666            return;
667        }
668        let widget = self.widget(app);
669        let (formatter, mode) = (widget.formatter(), widget.validation_mode);
670        let value = if widget.accepts_expression {
671            parser::compute(&text, &*formatter)
672        } else {
673            formatter.parse_double(&text)
674        };
675        let current = self.current_value(app);
676        match value {
677            None if mode == NumberBoxValidationMode::InvalidInputOverwritten => {
678                self.update_text_to_value(app, current)
679            }
680            None => {}
681            // `3` after `1 + 2` with a value of 3 still becomes `3`.
682            Some(value) if value == current => self.update_text_to_value(app, current),
683            Some(value) => self.put_value(app, value),
684        }
685    }
686
687    /// `StepValue`: commits the text first so that it is not lost, then moves the value by
688    /// `change` and puts the caret at the end. Nothing moves while there is no value.
689    fn step_value(self: Handle<Self>, app: &mut App, change: f64) {
690        self.validate_input(app);
691        let value = self.current_value(app);
692        if value.is_nan() {
693            return;
694        }
695        let wrap = self.widget(app).is_wrap_enabled;
696        let bounds = app.get(self).bounds;
697        self.put_value(app, stepped(value, change, bounds, wrap));
698        self.move_caret_to_text_end(app);
699    }
700
701    /// `MoveCaretToTextEnd`.
702    fn move_caret_to_text_end(self: Handle<Self>, app: &mut App) {
703        let controller = self.controller(app);
704        let end = controller.text_value(app).encode_utf16().count() as i32;
705        controller.set_selection(app, TextSelection::collapsed(end, TextAffinity::Downstream));
706    }
707
708    /// `TextBox::SelectAll`.
709    fn select_all(self: Handle<Self>, app: &mut App) {
710        let controller = self.controller(app);
711        let end = controller.text_value(app).encode_utf16().count() as i32;
712        controller.set_selection(app, TextSelection::new(0, end));
713    }
714
715    /// `OnNumberBoxKeyDown`, which WinUI hooks to `InputBox`'s `PreviewKeyDown` because the text
716    /// box takes some of these keys: the arrows step by `small_change` and the page keys by
717    /// `large_change`, on each press and repeat. And `OnNumberBoxKeyUp`: Enter commits the text
718    /// and Escape puts the value back in it.
719    fn key_event(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
720        let key = event.logical_key();
721        match event {
722            KeyEvent::Down(_) | KeyEvent::Repeat(_) => {
723                let widget = self.widget(app);
724                let change = match key {
725                    LogicalKeyboardKey::ARROW_UP => widget.small_change,
726                    LogicalKeyboardKey::ARROW_DOWN => -widget.small_change,
727                    LogicalKeyboardKey::PAGE_UP => widget.large_change,
728                    LogicalKeyboardKey::PAGE_DOWN => -widget.large_change,
729                    _ => return KeyEventResult::Ignored,
730                };
731                self.step_value(app, change);
732                KeyEventResult::Handled
733            }
734            KeyEvent::Up(_) => match key {
735                LogicalKeyboardKey::ENTER
736                | LogicalKeyboardKey::NUMPAD_ENTER
737                | LogicalKeyboardKey::GAME_BUTTON_A => {
738                    self.validate_input(app);
739                    KeyEventResult::Handled
740                }
741                LogicalKeyboardKey::ESCAPE | LogicalKeyboardKey::GAME_BUTTON_B => {
742                    let value = self.current_value(app);
743                    self.update_text_to_value(app, value);
744                    KeyEventResult::Handled
745                }
746                _ => KeyEventResult::Ignored,
747            },
748        }
749    }
750
751    /// `OnNumberBoxScroll`: while `InputBox` has the focus, the box takes each wheel event, so
752    /// that the page does not scroll, and steps by `small_change` in the wheel's direction.
753    fn pointer_signal(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
754        if !matches!(event, PointerEvent::Scroll(_)) || !self.focus(app).has_focus(app) {
755            return;
756        }
757        let resolver = GestureBinding::instance(app).pointer_signal_resolver(app);
758        resolver.register(
759            app,
760            event,
761            Rc::new(move |app, event| self.wheel(app, event)),
762        );
763    }
764
765    /// One wheel event the box took. `MouseWheelDelta` is positive for a wheel turned away from
766    /// the user, where Waft's vertical scroll delta is negative, and for a wheel tilted right.
767    fn wheel(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
768        let PointerEvent::Scroll(scroll) = event else {
769            return;
770        };
771        if !self.mounted(app) {
772            return;
773        }
774        let delta = if scroll.scroll_delta.dy() != 0.0 {
775            -scroll.scroll_delta.dy()
776        } else {
777            scroll.scroll_delta.dx()
778        };
779        let small_change = self.widget(app).small_change;
780        if delta > 0.0 {
781            self.step_value(app, small_change);
782        } else if delta < 0.0 {
783            self.step_value(app, -small_change);
784        }
785    }
786
787    /// `OnNumberBoxGotFocus` and `OnNumberBoxLostFocus`: taking the focus selects the text and
788    /// opens the popup of compact spin buttons; losing it commits the text and closes the
789    /// popup.
790    fn focus_changed(self: Handle<Self>, app: &mut App) {
791        let focused = self.focus(app).has_focus(app);
792        if focused == app.get(self).focused {
793            return;
794        }
795        app.get_mut(self).focused = focused;
796        let popup = self.popup(app);
797        if focused {
798            self.select_all(app);
799            if self.widget(app).spin_button_placement_mode
800                == NumberBoxSpinButtonPlacementMode::Compact
801            {
802                popup.show(app);
803            }
804        } else {
805            self.validate_input(app);
806            if self.mounted(app) {
807                popup.hide(app);
808            }
809        }
810    }
811
812    /// The application has answered the value the box asked for, by building the box again: if
813    /// `InputBox` still shows the asked-for value, it shows the application's.
814    fn settle_request(self: Handle<Self>, app: &mut App) {
815        let Some(requested) = app.get_mut(self).requested.take() else {
816            return;
817        };
818        let formatter = self.widget(app).formatter();
819        if self.controller(app).text_value(app) == displayed_text(requested, &*formatter) {
820            let value = app.get(self).value;
821            self.update_text_to_value(app, value);
822        }
823    }
824
825    /// The property changes of `OnValuePropertyChanged`, `OnMinimumPropertyChanged`,
826    /// `OnMaximumPropertyChanged`, `OnNumberFormatterPropertyChanged`, `OnTextPropertyChanged`
827    /// and `OnValidationModePropertyChanged`, from `old` (none on the first build) to the
828    /// widget, and `OnApplyTemplate`'s first text. What would raise `ValueChanged` during the
829    /// build runs after the frame.
830    fn apply_widget(self: Handle<Self>, app: &mut App, old: Option<&NumberBox>) {
831        let widget = self.widget(app).clone();
832        let bounds_changed =
833            old.is_none_or(|old| old.minimum != widget.minimum || old.maximum != widget.maximum);
834        let bounds = if bounds_changed {
835            let maximum_changed_alone = old.is_some_and(|old| old.minimum == widget.minimum);
836            Bounds::new(widget.minimum, widget.maximum, maximum_changed_alone)
837        } else {
838            app.get(self).bounds
839        };
840        let value_set = old.is_none_or(|old| differs(old.value, widget.value));
841        let previous = app.get(self).value;
842        let value = if value_set || bounds_changed {
843            coerce_value(widget.value, bounds, widget.validation_mode)
844        } else {
845            previous
846        };
847        let state = app.get_mut(self);
848        state.bounds = bounds;
849        state.value = value;
850        self.settle_request(app);
851        let formatter_changed =
852            old.is_some_and(
853                |old| match (&old.number_formatter, &widget.number_formatter) {
854                    (None, None) => false,
855                    (Some(old), Some(new)) => !old.same_as(&**new),
856                    _ => true,
857                },
858            );
859        if value_set || differs(previous, value) || formatter_changed {
860            self.update_text_to_value(app, value);
861        }
862        if differs(previous, value) && differs(widget.value, value) {
863            self.report_coercion_after_frame(app, previous, value);
864        }
865        let text_set = match old {
866            // `OnApplyTemplate` reads a `Text` set without a `Value`.
867            None => widget.value.is_nan() && widget.text.is_some(),
868            Some(old) => widget.text.is_some() && old.text != widget.text,
869        };
870        if let Some(text) = widget.text.clone().filter(|_| text_set) {
871            // `UpdateValueToText`.
872            self.set_text(app, text);
873            self.validate_input_after_frame(app);
874        } else if old.is_some_and(|old| old.validation_mode != widget.validation_mode) {
875            self.validate_input_after_frame(app);
876        }
877    }
878
879    /// Raises the `ValueChanged` that coercing the application's value from `old` to `new`
880    /// raises in WinUI, once the frame is over, if the box still has that value then.
881    fn report_coercion_after_frame(self: Handle<Self>, app: &mut App, old: f64, new: f64) {
882        let view = View::maybe_id_of(app, self.context(app));
883        after_next_frame(
884            app,
885            view,
886            FrameCallback::new(move |app, _| {
887                if !self.mounted(app) || differs(app.get(self).value, new) {
888                    return;
889                }
890                let handler = self.widget(app).value_changed.clone();
891                handler(
892                    app,
893                    NumberBoxValueChangedEventArgs {
894                        old_value: old,
895                        new_value: new,
896                    },
897                );
898            }),
899        );
900    }
901
902    /// Runs `ValidateInput` once the frame is over, where it may ask the application for a
903    /// value.
904    fn validate_input_after_frame(self: Handle<Self>, app: &mut App) {
905        let view = View::maybe_id_of(app, self.context(app));
906        after_next_frame(
907            app,
908            view,
909            FrameCallback::new(move |app, _| {
910                if self.mounted(app) {
911                    self.validate_input(app);
912                }
913            }),
914        );
915    }
916}
917
918impl State for NumberBoxState {
919    type Widget = NumberBox;
920    waft_widgets::state_accessors!();
921
922    fn init_state(self: Handle<Self>, app: &mut App) {
923        let controller = TextEditingController::new(app);
924        let focus = FocusNode::new(app);
925        focus.as_node().set_on_key_event(
926            app,
927            Some(Rc::new(move |app, _, event| self.key_event(app, event))),
928        );
929        focus.add_listener(app, Listener::handle_method(self, Self::focus_changed));
930        let popup = OverlayPortalController::new(app, Some("NumberBox UpDownPopup".into()));
931        let state = app.get_mut(self);
932        state.controller = Some(controller);
933        state.focus = Some(focus.clone());
934        state.popup = Some(popup);
935        self.apply_widget(app, None);
936    }
937
938    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &NumberBox) {
939        self.apply_widget(app, Some(old));
940    }
941
942    fn dispose(self: Handle<Self>, app: &mut App) {
943        let state = app.get_mut(self);
944        let (controller, focus, popup) = (
945            state.controller.take().expect("an initialized NumberBox"),
946            state.focus.take().expect("an initialized NumberBox"),
947            state.popup.take().expect("an initialized NumberBox"),
948        );
949        focus.remove_listener(app, &Listener::handle_method(self, Self::focus_changed));
950        focus.dispose(app);
951        controller.dispose(app);
952        drop(popup);
953    }
954
955    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
956        // A value asked for since the last build that the application did not pass is undone.
957        self.settle_request(app);
958        let widget = self.widget(app).clone();
959        let resources = ThemeResources::of(app, context);
960        let r = &resources;
961        let common = if widget.is_enabled {
962            NumberBoxCommonState::Normal
963        } else {
964            NumberBoxCommonState::Disabled
965        };
966        let spin_buttons = SpinButtonsState::of(widget.spin_button_placement_mode);
967        let mut cells = Vec::new();
968        if let Some(header) = widget.header.clone() {
969            // `HeaderContentPresenter`.
970            let foreground = match common {
971                NumberBoxCommonState::Normal => r.text_control_header_foreground,
972                NumberBoxCommonState::Disabled => r.text_control_header_foreground_disabled,
973            };
974            cells.push(
975                GridCell::new(Margin::new(
976                    r.text_box_top_header_margin,
977                    DefaultTextStyle::new(
978                        control_text_style(
979                            &resources,
980                            widget
981                                .font_size
982                                .unwrap_or(r.control_content_theme_font_size),
983                            FontWeight::NORMAL,
984                            foreground,
985                        ),
986                        header,
987                    ),
988                ))
989                .column_span(3)
990                .into_widget(),
991            );
992        }
993        // `InputBox`.
994        cells.push(
995            GridCell::new(self.input_box(&resources, app, spin_buttons))
996                .row(1)
997                .column_span(3)
998                .into_widget(),
999        );
1000        // `UpDownPopup`, at the start of its cell.
1001        cells.push(
1002            GridCell::new(self.up_down_popup(app))
1003                .row(1)
1004                .column(1)
1005                .into_widget(),
1006        );
1007        if spin_buttons == SpinButtonsState::SpinButtonsVisible {
1008            // `InputEater`: a button with an empty template, which takes presses between and
1009            // around the spin buttons so that they never reach `InputBox` beneath.
1010            cells.push(
1011                GridCell::new(Margin::new(
1012                    [4.0, 0.0, 0.0, 0.0],
1013                    // It measures as nothing in the Auto columns and takes its cell.
1014                    PointerListener::new()
1015                        .behavior(waft_rendering::HitTestBehavior::Opaque)
1016                        .child(SizedBox::shrink()),
1017                ))
1018                .row(1)
1019                .column(1)
1020                .column_span(2)
1021                .into_widget(),
1022            );
1023            let (up, down) = self.spin_button_enabled_states(app);
1024            // `UpSpinButton` and `DownSpinButton`.
1025            cells.push(
1026                GridCell::new(Margin::new(
1027                    [4.0; 4],
1028                    self.inline_spin_button(&resources, app, FluentSymbol::ChevronUp, 1.0, up),
1029                ))
1030                .row(1)
1031                .column(1)
1032                .into_widget(),
1033            );
1034            cells.push(
1035                GridCell::new(Margin::new(
1036                    [0.0, 4.0, 4.0, 4.0],
1037                    self.inline_spin_button(&resources, app, FluentSymbol::ChevronDown, -1.0, down),
1038                ))
1039                .row(1)
1040                .column(2)
1041                .into_widget(),
1042            );
1043        }
1044        if let Some(description) = widget.description.clone() {
1045            // `DescriptionPresenter`.
1046            cells.push(
1047                GridCell::new(DefaultTextStyle::new(
1048                    control_text_style(
1049                        &resources,
1050                        widget
1051                            .font_size
1052                            .unwrap_or(r.control_content_theme_font_size),
1053                        FontWeight::NORMAL,
1054                        r.system_control_description_text_foreground_brush,
1055                    ),
1056                    description,
1057                ))
1058                .row(2)
1059                .column_span(3)
1060                .into_widget(),
1061            );
1062        }
1063        let template = Grid::new()
1064            .row_definitions([
1065                RowDefinition::new(GridLength::AUTO),
1066                RowDefinition::new(GridLength::STAR),
1067                RowDefinition::new(GridLength::AUTO),
1068            ])
1069            .column_definitions([
1070                ColumnDefinition::new(GridLength::STAR),
1071                ColumnDefinition::new(GridLength::AUTO),
1072                ColumnDefinition::new(GridLength::AUTO),
1073            ])
1074            .children(cells);
1075        // The box is one text field to the platform: pressing a spin button, the header or the
1076        // popup leaves `InputBox` focused.
1077        TextFieldTapRegion::new(
1078            PointerListener::new()
1079                .on_pointer_signal(Rc::new(move |app, event| self.pointer_signal(app, &event)))
1080                .child(template),
1081        )
1082        .into_widget()
1083    }
1084}
1085
1086impl NumberBoxState {
1087    /// `InputBox`: a TextBox in `NumberBoxTextBoxStyle`, with the box's text properties.
1088    fn input_box(
1089        self: Handle<Self>,
1090        r: &ThemeResources,
1091        app: &App,
1092        spin_buttons: SpinButtonsState,
1093    ) -> WidgetRef {
1094        let widget = self.widget(app);
1095        let mut config = TextBox::new(
1096            app.get(self)
1097                .controller
1098                .as_ref()
1099                .expect("an initialized NumberBox")
1100                .erase(),
1101        )
1102        .focus_node(
1103            app.get(self)
1104                .focus
1105                .as_ref()
1106                .expect("an initialized NumberBox")
1107                .erase(),
1108        )
1109        .placeholder_text(widget.placeholder_text.clone())
1110        .is_enabled(widget.is_enabled)
1111        .font_size(
1112            widget
1113                .font_size
1114                .unwrap_or(r.control_content_theme_font_size),
1115        )
1116        .corner_radius(widget.corner_radius.unwrap_or(r.control_corner_radius[0]))
1117        .text_alignment(widget.text_alignment);
1118        if let Some(color) = widget.selection_highlight_color {
1119            config = config.selection_highlight_color(color);
1120        }
1121        let min_width = if spin_buttons == SpinButtonsState::SpinButtonsVisible {
1122            r.number_box_min_width
1123        } else {
1124            r.text_control_theme_min_width
1125        };
1126        TextControl::new(config, None)
1127            .number_box_style(NumberBoxTextBoxStyle {
1128                spin_buttons,
1129                min_width,
1130            })
1131            .into_widget()
1132    }
1133
1134    /// The up and down states of `UpdateSpinButtonEnabled`.
1135    fn spin_button_enabled_states(
1136        self: Handle<Self>,
1137        app: &App,
1138    ) -> (SpinButtonEnabledState, SpinButtonEnabledState) {
1139        let widget = self.widget(app);
1140        spin_button_enabled_states(
1141            self.current_value(app),
1142            app.get(self).bounds,
1143            widget.is_wrap_enabled,
1144            widget.validation_mode,
1145        )
1146    }
1147
1148    /// A spin button, stepping by `direction` times `small_change` on each `Click`
1149    /// (`OnSpinUpClick` and `OnSpinDownClick`).
1150    fn spin_button(
1151        self: Handle<Self>,
1152        app: &App,
1153        glyph: FluentSymbol,
1154        direction: f64,
1155        state: SpinButtonEnabledState,
1156        setters: RepeatButtonSetters,
1157    ) -> RepeatButton {
1158        let enabled = self.widget(app).is_enabled && state == SpinButtonEnabledState::Enabled;
1159        let click = Listener::new(move |app| {
1160            let change = direction * self.widget(app).small_change;
1161            self.step_value(app, change);
1162        });
1163        RepeatButton::new(FontIcon::symbol(glyph).font_size(setters.font_size), click)
1164            .is_enabled(enabled)
1165            .is_tab_stop(false)
1166            .template(move |app, context, states, content| {
1167                let resources = ThemeResources::of(app, context);
1168                repeat_button_presenter(
1169                    &resources,
1170                    spin_button_brushes(&resources, states.common),
1171                    setters,
1172                    content,
1173                )
1174            })
1175    }
1176
1177    /// `UpSpinButton` or `DownSpinButton`, in `NumberBoxSpinButtonStyle`: at least 32 wide, as
1178    /// tall as the box less their margins, with the box's font size and corner radius.
1179    fn inline_spin_button(
1180        self: Handle<Self>,
1181        r: &ThemeResources,
1182        app: &App,
1183        glyph: FluentSymbol,
1184        direction: f64,
1185        state: SpinButtonEnabledState,
1186    ) -> WidgetRef {
1187        let widget = self.widget(app);
1188        let setters = RepeatButtonSetters {
1189            border_thickness: r.number_box_spin_button_border_thickness,
1190            corner_radius: widget.corner_radius.unwrap_or(r.control_corner_radius[0]),
1191            padding: [0.0; 4],
1192            font_size: widget
1193                .font_size
1194                .unwrap_or(r.control_content_theme_font_size),
1195        };
1196        ConstrainedBox::new(BoxConstraints::new().min_width(SPIN_BUTTON_MIN_WIDTH))
1197            .child(self.spin_button(app, glyph, direction, state, setters))
1198            .into_widget()
1199    }
1200
1201    /// `PopupUpSpinButton` or `PopupDownSpinButton`, in `NumberBoxPopupSpinButtonStyle`: 36 by
1202    /// 36 at the left of its row and centered in it, overflowing evenly a row that is shorter,
1203    /// as XAML arranges an element of fixed size.
1204    fn popup_spin_button(
1205        self: Handle<Self>,
1206        r: &ThemeResources,
1207        app: &App,
1208        glyph: FluentSymbol,
1209        direction: f64,
1210        state: SpinButtonEnabledState,
1211    ) -> WidgetRef {
1212        let setters = RepeatButtonSetters {
1213            border_thickness: r.number_box_popup_spin_button_border_thickness,
1214            corner_radius: r.control_corner_radius[0],
1215            padding: [0.0; 4],
1216            font_size: POPUP_SPIN_BUTTON_FONT_SIZE,
1217        };
1218        SizedBox::new()
1219            .width(POPUP_SPIN_BUTTON_SIZE)
1220            .height(POPUP_SPIN_BUTTON_SIZE)
1221            .child(
1222                OverflowBox::new()
1223                    .alignment(AlignmentGeometry::CENTER_LEFT)
1224                    .min_width(POPUP_SPIN_BUTTON_SIZE)
1225                    .max_width(POPUP_SPIN_BUTTON_SIZE)
1226                    .min_height(POPUP_SPIN_BUTTON_SIZE)
1227                    .max_height(POPUP_SPIN_BUTTON_SIZE)
1228                    .child(self.spin_button(app, glyph, direction, state, setters)),
1229            )
1230            .into_widget()
1231    }
1232
1233    /// `UpDownPopup`: no light dismiss, opened and closed by the focus; its content is placed
1234    /// from where the popup is in the template.
1235    fn up_down_popup(self: Handle<Self>, app: &App) -> WidgetRef {
1236        OverlayPortal::overlay_child_layout_builder(
1237            app.get(self)
1238                .popup
1239                .clone()
1240                .expect("an initialized NumberBox"),
1241            move |app, context, info| {
1242                let r = ThemeResources::of(app, context);
1243                let slot = transform_rect(
1244                    &info.child_paint_transform(),
1245                    Offset::ZERO & info.child_size(),
1246                );
1247                CustomSingleChildLayout::new(Rc::new(PopupLayout {
1248                    slot,
1249                    offset: Offset::new(
1250                        r.number_box_popup_horizonal_offset,
1251                        r.number_box_popup_vertical_offset,
1252                    ),
1253                }))
1254                .child(self.popup_content_root(app, context))
1255                .into_widget()
1256            },
1257        )
1258        .overlay_location(OverlayChildLocation::RootOverlay)
1259        .child(SizedBox::shrink())
1260        .into_widget()
1261    }
1262
1263    /// `PopupContentRoot`: the popup spin buttons on acrylic, raised by
1264    /// `NumberBoxPopupShadowDepth`.
1265    fn popup_content_root(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1266        let resources = ThemeResources::of(app, context);
1267        let r = &resources;
1268        let (up, down) = self.spin_button_enabled_states(app);
1269        let root = Grid::new()
1270            .row_definitions([
1271                RowDefinition::new(GridLength::STAR),
1272                RowDefinition::new(GridLength::STAR),
1273            ])
1274            .padding([POPUP_CONTENT_PADDING; 4])
1275            .background(Brush::Acrylic(r.number_box_popup_background))
1276            .border_brush(Brush::Solid(r.number_box_popup_border_brush))
1277            .border_thickness_ltrb(r.number_box_popup_border_thickness)
1278            .corner_radius_corners(r.overlay_corner_radius)
1279            .children([
1280                GridCell::new(Margin::new(
1281                    [0.0, 0.0, 0.0, 4.0],
1282                    self.popup_spin_button(&resources, app, FluentSymbol::ChevronUp, 1.0, up),
1283                ))
1284                .into_widget(),
1285                GridCell::new(self.popup_spin_button(
1286                    &resources,
1287                    app,
1288                    FluentSymbol::ChevronDown,
1289                    -1.0,
1290                    down,
1291                ))
1292                .row(1)
1293                .into_widget(),
1294            ]);
1295        TextFieldTapRegion::new(
1296            CustomPaint::new()
1297                .painter(PopupShadow::for_number_box_popup(
1298                    &resources,
1299                    resources.theme,
1300                ))
1301                .child(root),
1302        )
1303        .into_widget()
1304    }
1305}
1306
1307/// The brushes `DefaultRepeatButtonStyle`'s `CommonStates` give a spin button, where the
1308/// template's `Grid.Resources` set the `RepeatButton` brushes of the normal, pointer-over and
1309/// pressed states, and the disabled border, to their `TextControlButton` counterparts.
1310fn spin_button_brushes(resources: &ThemeResources, state: CommonState) -> RepeatButtonBrushes {
1311    let r = &resources;
1312    let (background, border, foreground) = match state {
1313        CommonState::Normal => (
1314            r.text_control_button_background,
1315            r.text_control_button_border_brush,
1316            r.text_control_button_foreground,
1317        ),
1318        CommonState::PointerOver => (
1319            r.text_control_button_background_pointer_over,
1320            r.text_control_button_border_brush_pointer_over,
1321            r.text_control_button_foreground_pointer_over,
1322        ),
1323        CommonState::Pressed => (
1324            r.text_control_button_background_pressed,
1325            r.text_control_button_border_brush_pressed,
1326            r.text_control_button_foreground_pressed,
1327        ),
1328        CommonState::Disabled => {
1329            let repeat_button = &resources;
1330            (
1331                repeat_button.repeat_button_background_disabled,
1332                r.text_control_button_border_brush,
1333                repeat_button.repeat_button_foreground_disabled,
1334            )
1335        }
1336    };
1337    RepeatButtonBrushes {
1338        background,
1339        border: Brush::Solid(border),
1340        foreground,
1341    }
1342}
1343
1344/// Places `PopupContentRoot` where `UpDownPopup` opens it: at the top left of the popup's slot
1345/// (row 1, column 1 of the template), moved by `NumberBoxPopupHorizonalOffset` and
1346/// `NumberBoxPopupVerticalOffset`.
1347#[derive(Debug, PartialEq)]
1348struct PopupLayout {
1349    /// The popup's slot in the overlay.
1350    slot: Rect,
1351    /// `NumberBoxPopupHorizonalOffset` and `NumberBoxPopupVerticalOffset`.
1352    offset: Offset,
1353}
1354
1355impl SingleChildLayoutDelegate for PopupLayout {
1356    /// A popup measures its child against an unbounded size.
1357    fn get_constraints_for_child(&self, _constraints: BoxConstraints) -> BoxConstraints {
1358        BoxConstraints::new()
1359    }
1360
1361    fn get_position_for_child(&self, _size: Size, _child_size: Size) -> Offset {
1362        Offset::new(
1363            self.slot.left + self.offset.dx(),
1364            self.slot.top + self.offset.dy(),
1365        )
1366    }
1367
1368    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
1369        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
1370    }
1371
1372    fn as_any(&self) -> &dyn Any {
1373        self
1374    }
1375}
1376
1377#[cfg(test)]
1378mod tests {
1379    use super::*;
1380
1381    const OVERWRITTEN: NumberBoxValidationMode = NumberBoxValidationMode::InvalidInputOverwritten;
1382
1383    fn bounds(minimum: f64, maximum: f64) -> Bounds {
1384        Bounds { minimum, maximum }
1385    }
1386
1387    #[test]
1388    fn crossed_bounds_keep_the_one_that_changed() {
1389        assert_eq!(Bounds::new(10.0, 5.0, false), bounds(10.0, 10.0));
1390        assert_eq!(Bounds::new(10.0, 5.0, true), bounds(5.0, 5.0));
1391        assert_eq!(Bounds::new(0.0, 5.0, true), bounds(0.0, 5.0));
1392    }
1393
1394    #[test]
1395    fn coercion_moves_a_value_to_the_bound_it_passed_unless_validation_is_disabled() {
1396        let range = bounds(0.0, 100.0);
1397        assert_eq!(coerce_value(150.0, range, OVERWRITTEN), 100.0);
1398        assert_eq!(coerce_value(-5.0, range, OVERWRITTEN), 0.0);
1399        assert_eq!(coerce_value(50.0, range, OVERWRITTEN), 50.0);
1400        assert!(coerce_value(f64::NAN, range, OVERWRITTEN).is_nan());
1401        assert_eq!(
1402            coerce_value(150.0, range, NumberBoxValidationMode::Disabled),
1403            150.0
1404        );
1405    }
1406
1407    #[test]
1408    fn steps_wrap_past_a_bound_to_the_other() {
1409        let range = bounds(0.0, 100.0);
1410        assert_eq!(stepped(95.0, 10.0, range, false), 105.0);
1411        assert_eq!(stepped(95.0, 10.0, range, true), 0.0);
1412        assert_eq!(stepped(5.0, -10.0, range, true), 100.0);
1413        assert_eq!(stepped(50.0, 10.0, range, true), 60.0);
1414    }
1415
1416    #[test]
1417    fn spin_buttons_stop_at_their_bound_unless_wrapping_or_keeping_invalid_input() {
1418        use SpinButtonEnabledState::{Disabled, Enabled};
1419        let range = bounds(0.0, 100.0);
1420        assert_eq!(
1421            spin_button_enabled_states(100.0, range, false, OVERWRITTEN),
1422            (Disabled, Enabled)
1423        );
1424        assert_eq!(
1425            spin_button_enabled_states(0.0, range, false, OVERWRITTEN),
1426            (Enabled, Disabled)
1427        );
1428        assert_eq!(
1429            spin_button_enabled_states(100.0, range, true, OVERWRITTEN),
1430            (Enabled, Enabled)
1431        );
1432        assert_eq!(
1433            spin_button_enabled_states(100.0, range, false, NumberBoxValidationMode::Disabled),
1434            (Enabled, Enabled)
1435        );
1436        assert_eq!(
1437            spin_button_enabled_states(f64::NAN, range, true, OVERWRITTEN),
1438            (Disabled, Disabled)
1439        );
1440    }
1441
1442    #[test]
1443    fn nan_to_nan_is_no_change() {
1444        assert!(!differs(f64::NAN, f64::NAN));
1445        assert!(differs(f64::NAN, 1.0));
1446        assert!(differs(1.0, f64::NAN));
1447        assert!(!differs(1.0, 1.0));
1448    }
1449
1450    #[test]
1451    fn the_shown_text_is_the_rounded_formatted_value() {
1452        let formatter = DecimalFormatter::default();
1453        assert_eq!(displayed_text(f64::NAN, &formatter), "");
1454        assert_eq!(displayed_text(0.1 + 0.2, &formatter), "0.3");
1455        assert_eq!(trim(" \t12\n"), "12");
1456    }
1457}