Skip to main content

waft_winui/controls/
combo_box.rs

1//! ComboBox_themeresources.xaml and ComboBox_Partial.cpp: a box showing the selected item that
2//! opens a drop-down of the items, or, editable, a text box whose text the box matches to the
3//! items. The drop-down puts the selected item over the box where it fits, at least as wide as
4//! the box and within the window, and closes when a press lands outside it.
5//!
6//! The application owns the selection: `selected_index`, and in an editable box `custom_value`,
7//! are what it passes, and `selection_changed` asks for another. The selection the box asks for
8//! is what the box itself reads as its selection until the application next builds it; if the
9//! application passed another by then, the box shows that one. The drop-down is the box's own
10//! unless the application takes it over with `is_drop_down_open`.
11
12mod item;
13mod popup;
14mod search;
15
16pub use item::ComboBoxItem;
17
18use super::flyout::shadow::PopupShadow;
19use super::text_control::TextControl;
20use crate::*;
21// Waft exports a `FocusState` of its own; the XAML one is meant here.
22use crate::FocusState;
23use item::{ComboBoxItemContainer, ITEM_MARGIN};
24use popup::{ArrangeInput, Arrangement, ItemProbe, PopupPosition};
25use search::{Match, TypeAhead};
26use std::{
27    cell::Cell,
28    collections::{HashMap, HashSet},
29    fmt,
30    rc::Rc,
31    time::Duration,
32};
33use waft_embedder::{Color, FontWeight, Offset, Rect, Size, TextAffinity, TextSelection};
34use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref, ValueKey};
35use waft_gestures::{GestureBinding, K_PRIMARY_BUTTON, PointerEvent};
36use waft_painting::{
37    Alignment, EdgeInsetsGeometry, PaintingBinding, TextPainter, TextSpan, transform_rect,
38};
39use waft_rendering::{BoxConstraints, HitTestBehavior};
40use waft_scheduler::FrameCallback;
41use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey, TextEditingValue};
42use waft_widgets::Listener as PointerListener;
43use waft_widgets::*;
44
45/// XAML `ComboBoxSelectionChangedTrigger`: what moving through the open drop-down with the
46/// keyboard does.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
48pub enum ComboBoxSelectionChangedTrigger {
49    /// The item moved to is drawn selected; Enter or a click selects it.
50    #[default]
51    Committed,
52    /// The item moved to is selected.
53    Always,
54}
55
56/// Something a `ComboBox` selects: an element of `RemovedItems` or `AddedItems`.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum ComboBoxSelectedItem {
59    /// The item at `index` of `items`, with its `id`.
60    Item {
61        /// Its index in `items`.
62        index: usize,
63        /// Its `id`.
64        id: String,
65    },
66    /// A custom value: text committed in an editable box that matches no item.
67    CustomValue(String),
68}
69
70impl ComboBoxSelectedItem {
71    /// The item's index, for an item of `items`.
72    pub fn index(&self) -> Option<usize> {
73        match self {
74            Self::Item { index, .. } => Some(*index),
75            Self::CustomValue(_) => None,
76        }
77    }
78
79    /// The text, for a custom value.
80    pub fn custom_value(&self) -> Option<&str> {
81        match self {
82            Self::Item { .. } => None,
83            Self::CustomValue(text) => Some(text),
84        }
85    }
86}
87
88/// XAML `SelectionChangedEventArgs` of a ComboBox: what was selected and what is now.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct ComboBoxSelectionChangedEventArgs {
91    /// `RemovedItems`: what was selected, if anything.
92    pub removed_item: Option<ComboBoxSelectedItem>,
93
94    /// `AddedItems`: what the box asks to select, if anything.
95    pub added_item: Option<ComboBoxSelectedItem>,
96}
97
98impl ComboBoxSelectionChangedEventArgs {
99    /// The `selected_index` the box asks for.
100    pub fn selected_index(&self) -> Option<usize> {
101        self.added_item
102            .as_ref()
103            .and_then(ComboBoxSelectedItem::index)
104    }
105
106    /// The `custom_value` the box asks for.
107    pub fn custom_value(&self) -> Option<&str> {
108        self.added_item
109            .as_ref()
110            .and_then(ComboBoxSelectedItem::custom_value)
111    }
112}
113
114/// Receives XAML `SelectionChanged`.
115pub type ComboBoxSelectionChangedHandler = Rc<dyn Fn(&mut App, ComboBoxSelectionChangedEventArgs)>;
116
117/// XAML `ComboBoxTextSubmittedEventArgs`.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct ComboBoxTextSubmittedEventArgs {
120    /// `Text`: the text committed, which matches no item.
121    pub text: String,
122
123    /// `Handled`: set it to keep the box from selecting the text as a custom value.
124    pub handled: bool,
125}
126
127/// Receives XAML `TextSubmitted`.
128pub type ComboBoxTextSubmittedHandler = Rc<dyn Fn(&mut App, &mut ComboBoxTextSubmittedEventArgs)>;
129
130/// Asks the application to open or close a drop-down it owns.
131pub type ComboBoxDropDownOpenChangedHandler = Rc<dyn Fn(&mut App, bool)>;
132
133/// XAML `ComboBox` with the template of `DefaultComboBoxStyle`.
134#[derive(Clone)]
135pub struct ComboBox {
136    /// `Items`, in order; ids are unique and stay the same across rebuilds.
137    pub items: Vec<ComboBoxItem>,
138
139    /// `SelectedIndex`; an index of `items`.
140    pub selected_index: Option<usize>,
141
142    /// `SelectionChanged`: asks the application for another selection; the application owns
143    /// `selected_index` and `custom_value`.
144    pub selection_changed: ComboBoxSelectionChangedHandler,
145
146    /// `SelectedItem` when it is a custom value of an editable box: text matching no item,
147    /// selected while `selected_index` is `None`.
148    pub custom_value: Option<String>,
149
150    /// `Header`: shown above the box.
151    pub header: Option<WidgetRef>,
152
153    /// `PlaceholderText`: shown while nothing is selected.
154    pub placeholder_text: String,
155
156    /// `PlaceholderForeground`: overrides the placeholder's foreground in every state.
157    pub placeholder_foreground: Option<Color>,
158
159    /// `Description`: shown below the box.
160    pub description: Option<WidgetRef>,
161
162    /// `IsDropDownOpen`, when the application owns it; `None` leaves the drop-down to the box.
163    pub is_drop_down_open: Option<bool>,
164
165    /// Asks the application, when it owns `is_drop_down_open`, to open or close the drop-down.
166    pub is_drop_down_open_changed: Option<ComboBoxDropDownOpenChangedHandler>,
167
168    /// `DropDownOpened`.
169    pub drop_down_opened: Option<Listener>,
170
171    /// `DropDownClosed`.
172    pub drop_down_closed: Option<Listener>,
173
174    /// `MaxDropDownHeight`: the tallest the drop-down is; 504 by default.
175    pub max_drop_down_height: f64,
176
177    /// `IsEnabled`.
178    pub is_enabled: bool,
179
180    /// `IsEditable`: whether the box is a text box whose text is matched to the items.
181    pub is_editable: bool,
182
183    /// `TextSubmitted`: an editable box committing text that matches no item.
184    pub text_submitted: Option<ComboBoxTextSubmittedHandler>,
185
186    /// `IsTextSearchEnabled`: whether typing selects an item by its text; true by default.
187    pub is_text_search_enabled: bool,
188
189    /// `SelectionChangedTrigger`.
190    pub selection_changed_trigger: ComboBoxSelectionChangedTrigger,
191
192    /// Identity retained across parent rebuilds.
193    pub key: Option<KeyRef>,
194}
195
196impl ComboBox {
197    /// Creates a box choosing among `items`, showing `selected_index`, which asks for other
198    /// selections through `selection_changed`.
199    pub fn new(
200        items: Vec<ComboBoxItem>,
201        selected_index: Option<usize>,
202        selection_changed: impl Fn(&mut App, ComboBoxSelectionChangedEventArgs) + 'static,
203    ) -> ComboBox {
204        ComboBox {
205            items,
206            selected_index,
207            selection_changed: Rc::new(selection_changed),
208            custom_value: None,
209            header: None,
210            placeholder_text: String::new(),
211            placeholder_foreground: None,
212            description: None,
213            is_drop_down_open: None,
214            is_drop_down_open_changed: None,
215            drop_down_opened: None,
216            drop_down_closed: None,
217            max_drop_down_height: MAX_DROP_DOWN_HEIGHT,
218            is_enabled: true,
219            is_editable: false,
220            text_submitted: None,
221            is_text_search_enabled: true,
222            selection_changed_trigger: ComboBoxSelectionChangedTrigger::Committed,
223            key: None,
224        }
225    }
226
227    /// Sets SelectedItem to a custom value.
228    pub fn custom_value(mut self, value: impl Into<String>) -> Self {
229        self.custom_value = Some(value.into());
230        self
231    }
232
233    /// Sets Header.
234    #[cfg_attr(debug_assertions, track_caller)]
235    pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
236        self.header = Some(value.into_widget());
237        self
238    }
239
240    /// Sets PlaceholderText.
241    pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
242        self.placeholder_text = value.into();
243        self
244    }
245
246    /// Sets PlaceholderForeground.
247    pub fn placeholder_foreground(mut self, value: Color) -> Self {
248        self.placeholder_foreground = Some(value);
249        self
250    }
251
252    /// Sets Description.
253    #[cfg_attr(debug_assertions, track_caller)]
254    pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
255        self.description = Some(value.into_widget());
256        self
257    }
258
259    /// Gives the application IsDropDownOpen: the box shows `open` and asks for changes through
260    /// `changed`.
261    pub fn is_drop_down_open(
262        mut self,
263        open: bool,
264        changed: impl Fn(&mut App, bool) + 'static,
265    ) -> Self {
266        self.is_drop_down_open = Some(open);
267        self.is_drop_down_open_changed = Some(Rc::new(changed));
268        self
269    }
270
271    /// Sets DropDownOpened.
272    pub fn drop_down_opened(mut self, value: Listener) -> Self {
273        self.drop_down_opened = Some(value);
274        self
275    }
276
277    /// Sets DropDownClosed.
278    pub fn drop_down_closed(mut self, value: Listener) -> Self {
279        self.drop_down_closed = Some(value);
280        self
281    }
282
283    /// Sets MaxDropDownHeight.
284    pub fn max_drop_down_height(mut self, value: f64) -> Self {
285        self.max_drop_down_height = value;
286        self
287    }
288
289    /// Sets IsEnabled.
290    pub fn is_enabled(mut self, value: bool) -> Self {
291        self.is_enabled = value;
292        self
293    }
294
295    /// Sets IsEditable.
296    pub fn is_editable(mut self, value: bool) -> Self {
297        self.is_editable = value;
298        self
299    }
300
301    /// Sets TextSubmitted.
302    pub fn text_submitted(
303        mut self,
304        value: impl Fn(&mut App, &mut ComboBoxTextSubmittedEventArgs) + 'static,
305    ) -> Self {
306        self.text_submitted = Some(Rc::new(value));
307        self
308    }
309
310    /// Sets IsTextSearchEnabled.
311    pub fn is_text_search_enabled(mut self, value: bool) -> Self {
312        self.is_text_search_enabled = value;
313        self
314    }
315
316    /// Sets SelectionChangedTrigger.
317    pub fn selection_changed_trigger(mut self, value: ComboBoxSelectionChangedTrigger) -> Self {
318        self.selection_changed_trigger = value;
319        self
320    }
321
322    /// Sets widget identity.
323    pub fn key(mut self, key: KeyRef) -> Self {
324        self.key = Some(key);
325        self
326    }
327}
328
329impl fmt::Debug for ComboBox {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        f.debug_struct("ComboBox")
332            .field("items", &self.items)
333            .field("selected_index", &self.selected_index)
334            .field("custom_value", &self.custom_value)
335            .field("placeholder_text", &self.placeholder_text)
336            .field("is_editable", &self.is_editable)
337            .field("is_enabled", &self.is_enabled)
338            .finish_non_exhaustive()
339    }
340}
341
342/// `DefaultComboBoxStyle`'s `MaxDropDownHeight`.
343const MAX_DROP_DOWN_HEIGHT: f64 = 504.0;
344
345/// `ColumnDefinition` 1 of the template: the glyph's column.
346const GLYPH_COLUMN_WIDTH: f64 = 38.0;
347
348/// `DropDownGlyph`'s `Width`, `Height`, `Margin` and its fallback icon's `FontSize`.
349const GLYPH_SIZE: f64 = 12.0;
350const GLYPH_MARGIN: [f64; 4] = [0.0, 0.0, 14.0, 0.0];
351
352/// `DropDownOverlay`'s `Width` and `Margin`.
353const DROP_DOWN_OVERLAY_WIDTH: f64 = 30.0;
354const DROP_DOWN_OVERLAY_MARGIN: [f64; 4] = [4.0; 4];
355
356/// `HighlightBackground`'s `Margin`.
357const HIGHLIGHT_BACKGROUND_MARGIN: [f64; 4] = [-4.0; 4];
358
359/// `Pill`'s `Margin` in the box.
360const PILL_MARGIN: [f64; 4] = [1.0, 0.0, 0.0, 0.0];
361
362/// `HeaderContentPresenter`'s `LineHeight`.
363const HEADER_LINE_HEIGHT: f64 = 20.0;
364
365/// `ScrollViewerLineDelta` of ScrollViewer_Partial.h: one line of `ScrollInDirection`.
366const LINE_DELTA: f64 = 16.0;
367
368/// `ComboBoxTextBoxStyle`: the TextBox template of an editable box's `EditableText`, with the
369/// corner radius `ComboBoxHelper` gives it.
370#[derive(Clone, Copy, Debug, PartialEq)]
371pub(super) struct ComboBoxTextBoxStyle {
372    /// `CornerRadius`: the box's, with the corners next to an open drop-down square.
373    pub(super) corner_radius: [f64; 4],
374}
375
376/// `SelectedIndex` and `SelectedItem` together.
377#[derive(Clone, Debug, PartialEq, Eq)]
378enum Selection {
379    /// Nothing selected.
380    None,
381    /// The item at this index.
382    Index(usize),
383    /// A custom value.
384    Custom(String),
385}
386
387impl Selection {
388    /// The selection `widget` passes.
389    fn of(widget: &ComboBox) -> Selection {
390        match (widget.selected_index, &widget.custom_value) {
391            (Some(index), _) => Selection::Index(index),
392            (None, Some(text)) => Selection::Custom(text.clone()),
393            (None, None) => Selection::None,
394        }
395    }
396
397    /// `SelectedIndex`.
398    fn index(&self) -> Option<usize> {
399        match self {
400            Selection::Index(index) => Some(*index),
401            _ => None,
402        }
403    }
404
405    /// `SelectedItem`, as `SelectionChangedEventArgs` reports it.
406    fn item(&self, items: &[ComboBoxItem]) -> Option<ComboBoxSelectedItem> {
407        match self {
408            Selection::None => None,
409            Selection::Index(index) => Some(ComboBoxSelectedItem::Item {
410                index: *index,
411                id: items[*index].id.clone(),
412            }),
413            Selection::Custom(text) => Some(ComboBoxSelectedItem::CustomValue(text.clone())),
414        }
415    }
416}
417
418/// `FocusStates` of the box.
419#[derive(Clone, Copy, Debug, PartialEq, Eq)]
420enum ComboBoxFocusState {
421    /// `HighlightBackground` and `Pill` show.
422    Focused,
423    /// As `Focused`, pressed.
424    FocusedPressed,
425    Unfocused,
426    PointerFocused,
427    /// The drop-down is open.
428    FocusedDropDown,
429}
430
431/// `EditableModeStates` of an editable box: whether its text box has the focus, and the pointer
432/// over `DropDownOverlay`.
433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434#[allow(clippy::enum_variant_names, reason = "the template's state names")]
435enum EditableModeState {
436    TextBoxFocused,
437    TextBoxFocusedOverlayPointerOver,
438    TextBoxFocusedOverlayPressed,
439    TextBoxOverlayPointerOver,
440    TextBoxOverlayPressed,
441    TextBoxUnfocused,
442}
443
444/// What a key typed in an editable box's text box was to `ProcessSearch`: a character, or
445/// Backspace, which searches for exact matches only.
446#[derive(Clone, Debug, PartialEq, Eq)]
447enum Typed {
448    Character(String),
449    Backspace,
450}
451
452impl Typed {
453    /// The `L' '` that `ProcessSearch` is called with when no key prompted it.
454    fn none() -> Typed {
455        Typed::Character(" ".to_owned())
456    }
457}
458
459impl StatefulWidget for ComboBox {
460    type State = ComboBoxState;
461
462    fn key(&self) -> Option<&KeyRef> {
463        self.key.as_ref()
464    }
465
466    fn create_state(&self) -> ComboBoxState {
467        ComboBoxState {
468            state: StateData::new(),
469            scope_focus: None,
470            focus: None,
471            text: None,
472            text_focus: None,
473            popup: None,
474            item_focus: HashMap::new(),
475            scroll: None,
476            background_key: GlobalKey::new(),
477            overlay_key: GlobalKey::new(),
478            heights: HashMap::new(),
479            widths: HashMap::new(),
480            last_popup_height: Rc::new(Cell::new(0.0)),
481            window_at_open: None,
482            selection: Selection::of(self),
483            requested: None,
484            open: false,
485            closing: false,
486            opened_up: false,
487            pointer_over_main: false,
488            pointer_over_popup: false,
489            pointer_over_overlay: false,
490            pressed: false,
491            restore_index_set: false,
492            index_to_restore: None,
493            closing_due_to_cancel: false,
494            ignore_cancel_key_downs: false,
495            focused_index: None,
496            forced_selected: None,
497            forced_unselected: None,
498            selection_active: false,
499            type_ahead: TypeAhead::default(),
500            search_result: None,
501            custom_value_ref: None,
502            pending_typed: None,
503            text_box_enabled: false,
504            should_move_focus_to_text_box: false,
505            building: false,
506            open_epoch: 0,
507            key_time: None,
508            pending_open: None,
509        }
510    }
511}
512
513/// The parts ComboBox_Partial.cpp keeps of its template, its flags and its search.
514pub struct ComboBoxState {
515    state: StateData<ComboBox>,
516
517    /// Focus anywhere in the box, its text box or its drop-down: what `HasFocus` asks.
518    scope_focus: Option<Ref<FocusNode>>,
519
520    /// The ComboBox's own focus, which `Focus` gives it.
521    focus: Option<Ref<FocusNode>>,
522
523    /// `EditableText`'s text.
524    text: Option<Ref<TextEditingController>>,
525
526    /// `EditableText`'s focus.
527    text_focus: Option<Ref<FocusNode>>,
528
529    /// Shows `Popup`.
530    popup: Option<Ref<OverlayPortalController>>,
531
532    /// The items' focus, by id, owned here so that the box can focus an item it scrolls to.
533    item_focus: HashMap<String, Ref<FocusNode>>,
534
535    /// The drop-down's scroll position, made at each opening where the opening starts.
536    scroll: Option<Ref<ScrollViewportController>>,
537
538    /// Identifies `Background`, the drop-down's anchor.
539    background_key: GlobalKey,
540
541    /// Identifies `DropDownOverlay`.
542    overlay_key: GlobalKey,
543
544    /// Each item's height in the drop-down, by id, as last laid out.
545    heights: HashMap<String, f64>,
546
547    /// The width each item laid out in this opening asks for, by id; the drop-down is as wide
548    /// as the widest.
549    widths: HashMap<String, f64>,
550
551    /// The drop-down's height in its last layout.
552    last_popup_height: Rc<Cell<f64>>,
553
554    /// The window's size when the drop-down opened; a change closes it.
555    window_at_open: Option<Size>,
556
557    /// The application's selection, as last passed.
558    selection: Selection,
559
560    /// The selection the box last asked for, until the application next builds it.
561    requested: Option<Selection>,
562
563    /// `IsDropDownOpen`, as the box has it.
564    open: bool,
565
566    /// `m_isDropDownClosing`.
567    closing: bool,
568
569    /// `m_openedUp`: an editable box's drop-down is above the box.
570    opened_up: bool,
571
572    /// `m_IsPointerOverMain`.
573    pointer_over_main: bool,
574
575    /// `m_IsPointerOverPopup`.
576    pointer_over_popup: bool,
577
578    /// `m_IsPointerOverDropDownOverlay`.
579    pointer_over_overlay: bool,
580
581    /// `m_bIsPressed`.
582    pressed: bool,
583
584    /// `m_restoreIndexSet`.
585    restore_index_set: bool,
586
587    /// `m_indexToRestoreOnCancel`.
588    index_to_restore: Option<usize>,
589
590    /// `m_isClosingDueToCancel`.
591    closing_due_to_cancel: bool,
592
593    /// `m_ignoreCancelKeyDowns`.
594    ignore_cancel_key_downs: bool,
595
596    /// The Selector's `m_focusedIndex`.
597    focused_index: Option<usize>,
598
599    /// `m_indexForcedToSelectedVisual`.
600    forced_selected: Option<usize>,
601
602    /// `m_indexForcedToUnselectedVisual`.
603    forced_unselected: Option<usize>,
604
605    /// `IsSelectionActive`: the box has the focus.
606    selection_active: bool,
607
608    /// A non-editable box's typed search, and both kinds' `m_searchString`.
609    type_ahead: TypeAhead,
610
611    /// `m_searchResultIndexSet` and `m_searchResultIndex`.
612    search_result: Option<Option<usize>>,
613
614    /// `m_customValueRef`.
615    custom_value_ref: Option<String>,
616
617    /// The key typed in the text box whose edit has not arrived yet.
618    pending_typed: Option<Typed>,
619
620    /// `EditableText` has its size: it is shown instead of `ContentPresenter`.
621    text_box_enabled: bool,
622
623    /// `m_shouldMoveFocusToTextBox`.
624    should_move_focus_to_text_box: bool,
625
626    /// The application's values are being applied, during a build: callbacks to the
627    /// application wait for the frame's end.
628    building: bool,
629
630    /// Invalidates work queued for an earlier opening.
631    open_epoch: u64,
632
633    /// When the last key event arrived, the clock of the typed search.
634    key_time: Option<Duration>,
635
636    /// The drop-down state an application that owns it passed, waiting for the frame's end.
637    pending_open: Option<bool>,
638}
639
640impl ComboBoxState {
641    fn scope_focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
642        app.get(self)
643            .scope_focus
644            .handle()
645            .expect("an initialized ComboBox")
646    }
647
648    fn box_focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
649        app.get(self)
650            .focus
651            .handle()
652            .expect("an initialized ComboBox")
653    }
654
655    fn text(self: Handle<Self>, app: &App) -> Handle<TextEditingController> {
656        app.get(self)
657            .text
658            .handle()
659            .expect("an initialized ComboBox")
660    }
661
662    fn text_focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
663        app.get(self)
664            .text_focus
665            .handle()
666            .expect("an initialized ComboBox")
667    }
668
669    fn popup(self: Handle<Self>, app: &App) -> Handle<OverlayPortalController> {
670        app.get(self)
671            .popup
672            .handle()
673            .expect("an initialized ComboBox")
674    }
675
676    fn alive(self: Handle<Self>, app: &App) -> bool {
677        app.contains(self) && self.mounted(app)
678    }
679
680    fn view(self: Handle<Self>, app: &App) -> Option<waft_embedder::ViewId> {
681        View::maybe_id_of(app, self.context(app))
682    }
683
684    /// Runs `work` once the frame is over, if the box is still mounted.
685    fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
686        let view = self.view(app);
687        after_next_frame(
688            app,
689            view,
690            FrameCallback::new(move |app, _| {
691                if self.alive(app) {
692                    work(app);
693                }
694            }),
695        );
696    }
697
698    /// Calls the application now, or at the frame's end while its values are being applied.
699    fn raise(self: Handle<Self>, app: &mut App, call: impl Fn(&mut App) + 'static) {
700        if app.get(self).building {
701            let view = self.view(app);
702            after_next_frame(app, view, FrameCallback::new(move |app, _| call(app)));
703        } else {
704            call(app);
705        }
706    }
707
708    fn is_editable(self: Handle<Self>, app: &App) -> bool {
709        self.widget(app).is_editable
710    }
711
712    fn item_count(self: Handle<Self>, app: &App) -> usize {
713        self.widget(app).items.len()
714    }
715
716    // MARK: Selection
717
718    /// `SelectedIndex` and `SelectedItem` as the box's own logic reads them: what it last asked
719    /// for, until the application answers, else the application's.
720    fn selected(self: Handle<Self>, app: &App) -> Selection {
721        let state = app.get(self);
722        state
723            .requested
724            .clone()
725            .unwrap_or_else(|| state.selection.clone())
726    }
727
728    /// `SelectedIndex`.
729    fn selected_index(self: Handle<Self>, app: &App) -> Option<usize> {
730        self.selected(app).index()
731    }
732
733    /// The `put_SelectedIndex` and `put_SelectedItem` of the box's own logic: a different
734    /// selection becomes what the box reads, runs what `SelectedItem` and `OnSelectionChanged`
735    /// do, and is asked of the application through `SelectionChanged`.
736    fn set_selection(self: Handle<Self>, app: &mut App, new: Selection) {
737        let old = self.selected(app);
738        if old == new {
739            return;
740        }
741        app.get_mut(self).requested = Some(new.clone());
742        self.selection_did_change(app, &old, &new);
743        let items = self.widget(app).items.clone();
744        let args = ComboBoxSelectionChangedEventArgs {
745            removed_item: old.item(&items),
746            added_item: new.item(&items),
747        };
748        let handler = self.widget(app).selection_changed.clone();
749        self.raise(app, move |app| handler(app, args.clone()));
750        self.set_state(app, |_| {});
751    }
752
753    /// What follows a change of selection: `OnPropertyChanged2` for `SelectedItem`, then
754    /// `OnSelectionChanged`.
755    fn selection_did_change(self: Handle<Self>, app: &mut App, old: &Selection, new: &Selection) {
756        self.selected_item_changed(app);
757        self.on_selection_changed(app, old.index(), new.index());
758    }
759
760    /// `OnPropertyChanged2` for `SelectedItem` in an editable box: the search result becomes the
761    /// selected index, a custom value is kept for a revert, the text box shows the selection
762    /// with its text selected, and a search the closed box has not committed is committed.
763    fn selected_item_changed(self: Handle<Self>, app: &mut App) {
764        if !self.is_editable(app) {
765            return;
766        }
767        let selected = self.selected(app);
768        app.get_mut(self).search_result = Some(selected.index());
769        if let Selection::Custom(text) = &selected {
770            app.get_mut(self).custom_value_ref = Some(text.clone());
771        }
772        if let Some(text) = self.selection_text(app, &selected) {
773            self.update_editable_text_box(app, &text, true, true);
774        }
775        if matches!(app.get(self).search_result, Some(Some(_))) && !app.get(self).open {
776            self.commit_revert_editable_search(app, false);
777        }
778    }
779
780    /// `ComboBox::OnSelectionChanged`: in the open drop-down, the Selector focuses the newly
781    /// selected item, except in an editable box; a closed editable box remembers the selection
782    /// to restore.
783    fn on_selection_changed(
784        self: Handle<Self>,
785        app: &mut App,
786        old: Option<usize>,
787        new: Option<usize>,
788    ) {
789        if app.get(self).open {
790            if !self.is_editable(app)
791                && let Some(new) = new
792            {
793                self.set_focused_item_keeping_state(app, Some(new), true);
794            }
795        } else if self.is_editable(app) && !app.get(self).restore_index_set {
796            let state = app.get_mut(self);
797            state.restore_index_set = true;
798            state.index_to_restore = old;
799        }
800    }
801
802    /// The text `TryGetStringValue` gets from a selection: an item's text, which is empty for an
803    /// item without, or the custom value; none without a selection.
804    fn selection_text(self: Handle<Self>, app: &App, selection: &Selection) -> Option<String> {
805        match selection {
806            Selection::None => None,
807            Selection::Index(index) => Some(self.item_text(app, *index)),
808            Selection::Custom(text) => Some(text.clone()),
809        }
810    }
811
812    /// An item's text, empty for an item without.
813    fn item_text(self: Handle<Self>, app: &App, index: usize) -> String {
814        self.widget(app).items[index]
815            .plain_text
816            .clone()
817            .unwrap_or_default()
818    }
819
820    /// `OverrideSelectedIndexForVisualStates`: draws `index` selected and the selected item
821    /// unselected, while they differ.
822    fn override_selected_index_for_visual_states(
823        self: Handle<Self>,
824        app: &mut App,
825        index: Option<usize>,
826    ) {
827        self.clear_selected_index_override_for_visual_states(app);
828        let selected = self.selected_index(app);
829        if index != selected {
830            let state = app.get_mut(self);
831            state.forced_selected = index;
832            if selected.is_some() {
833                state.forced_unselected = selected;
834            }
835        }
836        self.set_state(app, |_| {});
837    }
838
839    /// `ClearSelectedIndexOverrideForVisualStates`.
840    fn clear_selected_index_override_for_visual_states(self: Handle<Self>, app: &mut App) {
841        self.set_state(app, |state| {
842            state.forced_selected = None;
843            state.forced_unselected = None;
844        });
845    }
846
847    /// `ComboBoxItem::ChangeVisualState`'s `IsSelected`: the search result in an editable box
848    /// that has one, else the selection, unless the box draws another item in its place.
849    fn appears_selected(self: Handle<Self>, app: &App, index: usize) -> bool {
850        let state = app.get(self);
851        let mut selected = match state.search_result {
852            Some(result) => result == Some(index),
853            None => self.selected_index(app) == Some(index),
854        };
855        if state.forced_selected == Some(index) {
856            selected = true;
857        } else if state.forced_unselected == Some(index) {
858            selected = false;
859        }
860        selected
861    }
862
863    // MARK: Opening and closing
864
865    /// `put_IsDropDownOpen` from the box's own logic: a change opens or closes the drop-down and
866    /// is asked of an application that owns `is_drop_down_open`.
867    fn put_is_drop_down_open(self: Handle<Self>, app: &mut App, open: bool) {
868        if app.get(self).open == open {
869            return;
870        }
871        if let Some(changed) = self.widget(app).is_drop_down_open_changed.clone() {
872            self.raise(app, move |app| changed(app, open));
873        }
874        self.set_drop_down_open(app, open);
875    }
876
877    /// `OnIsDropDownOpenChanged`: an opening while the drop-down is still closing finishes the
878    /// closing first.
879    fn set_drop_down_open(self: Handle<Self>, app: &mut App, open: bool) {
880        if app.get(self).open == open {
881            return;
882        }
883        app.get_mut(self).open = open;
884        if app.get(self).closing && open {
885            self.finish_closing_drop_down(app);
886        }
887        if open {
888            self.on_open(app);
889        } else {
890            self.on_close(app);
891        }
892    }
893
894    /// `OnOpen`: remembers the selection to restore on cancel, shows the drop-down, and moves the
895    /// focus into it: to the text box of an editable box, else to the selected item or, with
896    /// nothing selected, to the first, which the box draws selected.
897    fn on_open(self: Handle<Self>, app: &mut App) {
898        let selected = self.selected_index(app);
899        let state = app.get_mut(self);
900        if !state.restore_index_set {
901            state.restore_index_set = true;
902            state.index_to_restore = selected;
903        }
904        state.closing_due_to_cancel = false;
905        self.show_popup(app);
906        if let Some(opened) = self.widget(app).drop_down_opened.clone() {
907            self.raise(app, move |app| opened.call(app));
908        }
909        self.set_state(app, |_| {});
910        let programmatic = FocusState::coerce_programmatic(app);
911        if self.is_editable(app) {
912            if !self.editable_text_has_focus(app) {
913                self.text_focus(app).request_focus(app, None);
914            }
915        } else if let Some(index) = selected {
916            self.set_focused_item(app, Some(index), false, true, programmatic);
917        } else if self.item_count(app) > 0 {
918            if self.widget(app).selection_changed_trigger == ComboBoxSelectionChangedTrigger::Always
919            {
920                self.set_selection(app, Selection::Index(0));
921            } else {
922                self.override_selected_index_for_visual_states(app, Some(0));
923            }
924            self.set_focused_item(app, Some(0), false, true, programmatic);
925        }
926    }
927
928    /// `OnClose`: an editable box commits its search, or reverts it when cancelled; a cancelled
929    /// non-editable box goes back to the selection it opened with. Without the closing theme
930    /// animation, the drop-down finishes closing at once.
931    fn on_close(self: Handle<Self>, app: &mut App) {
932        app.get_mut(self).closing = true;
933        let cancel = app.get(self).closing_due_to_cancel;
934        if self.is_editable(app) {
935            self.commit_revert_editable_search(app, cancel);
936        } else if cancel
937            && let Some(index) = app.get(self).index_to_restore
938            && index < self.item_count(app)
939        {
940            self.set_selection(app, Selection::Index(index));
941        }
942        let state = app.get_mut(self);
943        state.index_to_restore = None;
944        state.restore_index_set = false;
945        state.closing_due_to_cancel = false;
946        self.clear_selected_index_override_for_visual_states(app);
947        self.finish_closing_drop_down(app);
948        self.set_state(app, |state| {
949            state.pointer_over_popup = false;
950            state.pointer_over_main = false;
951            state.pointer_over_overlay = false;
952        });
953    }
954
955    /// `FinishClosingDropDown`: the focus goes back from the drop-down to the box, the drop-down
956    /// hides, and `DropDownClosed` is raised.
957    fn finish_closing_drop_down(self: Handle<Self>, app: &mut App) {
958        self.set_focused_item_keeping_state(app, None, false);
959        let state = app.get_mut(self);
960        state.should_move_focus_to_text_box = true;
961        state.pointer_over_popup = false;
962        state.closing = false;
963        // `ResetMinimumDesiredWindowWidth`.
964        state.widths.clear();
965        state.window_at_open = None;
966        state.focused_index = None;
967        self.hide_popup(app);
968        if let Some(closed) = self.widget(app).drop_down_closed.clone() {
969            self.raise(app, move |app| closed.call(app));
970        }
971        self.set_state(app, |_| {});
972    }
973
974    /// Shows `Popup`, with its list starting where `ArrangePopup` scrolls a pannable list: at the
975    /// first item it shows.
976    fn show_popup(self: Handle<Self>, app: &mut App) {
977        let geometry = self.popup_geometry(app);
978        let context = self.context(app);
979        let mut offset = 0.0;
980        if let Some((target, window)) = geometry
981            && let Some(arrangement) = self.arrangement(app, context, target, window)
982            && arrangement.pannable
983            && !self.is_editable(app)
984        {
985            let heights = self.item_heights(app, context);
986            offset = heights[..arrangement.first_item].iter().sum();
987        }
988        let old = app.get_mut(self).scroll.take();
989        self.retire_scroll(app, old);
990        let scroll = ScrollViewportController::with_initial_offset(app, offset);
991        let state = app.get_mut(self);
992        state.scroll = Some(scroll);
993        state.window_at_open = geometry.map(|(_, window)| window);
994        state.open_epoch += 1;
995        let epoch = state.open_epoch;
996        self.popup(app).show(app);
997        // `OnElementPopupChildLoaded`.
998        self.after_frame(app, move |app| {
999            if app.get(self).open && app.get(self).open_epoch == epoch {
1000                self.popup_child_loaded(app);
1001            }
1002        });
1003    }
1004
1005    /// Hides `Popup`; its list's scroll position is released once the list is gone.
1006    fn hide_popup(self: Handle<Self>, app: &mut App) {
1007        app.get_mut(self).open_epoch += 1;
1008        self.popup(app).hide(app);
1009        let old = app.get_mut(self).scroll.take();
1010        self.retire_scroll(app, old);
1011    }
1012
1013    /// Disposes a drop-down's scroll position after its list unmounts.
1014    fn retire_scroll(
1015        self: Handle<Self>,
1016        app: &mut App,
1017        scroll: Option<Ref<ScrollViewportController>>,
1018    ) {
1019        let Some(scroll) = scroll else {
1020            return;
1021        };
1022        let view = self.view(app);
1023        after_next_frame(
1024            app,
1025            view,
1026            FrameCallback::new(move |app, _| {
1027                scroll.dispose(app);
1028            }),
1029        );
1030    }
1031
1032    /// `OnElementPopupChildLoaded`: an editable box scrolls its selection, or the item its search
1033    /// found, into view, drawing a found item selected while selection waits for a commit.
1034    fn popup_child_loaded(self: Handle<Self>, app: &mut App) {
1035        if !self.is_editable(app) {
1036            return;
1037        }
1038        let trigger = self.widget(app).selection_changed_trigger;
1039        let current = match app.get(self).search_result {
1040            Some(result) if trigger != ComboBoxSelectionChangedTrigger::Always => {
1041                self.override_selected_index_for_visual_states(app, result);
1042                result
1043            }
1044            _ => self.selected_index(app),
1045        };
1046        if let Some(index) = current {
1047            self.scroll_into_view(app, index);
1048        }
1049    }
1050
1051    /// The light-dismiss canvas: a press of the left button outside the drop-down cancels it.
1052    fn light_dismiss(self: Handle<Self>, app: &mut App) {
1053        app.get_mut(self).closing_due_to_cancel = true;
1054        self.put_is_drop_down_open(app, false);
1055    }
1056
1057    // MARK: Focus
1058
1059    /// `HasFocus`: whether the focus is in the box, its text box or its drop-down.
1060    fn has_focus(self: Handle<Self>, app: &mut App) -> bool {
1061        self.scope_focus(app).has_focus(app)
1062    }
1063
1064    /// `EditableTextHasFocus`.
1065    fn editable_text_has_focus(self: Handle<Self>, app: &App) -> bool {
1066        self.is_editable(app) && self.text_focus(app).has_primary_focus(app)
1067    }
1068
1069    /// `Focus(state)` on the box itself.
1070    fn focus_box(self: Handle<Self>, app: &mut App, state: FocusState) {
1071        let node = self.box_focus(app);
1072        FocusState::name(app, node.as_node(), state);
1073        node.request_focus(app, None);
1074    }
1075
1076    /// `SetFocusedItem` with the focus state of the element that has the focus, or programmatic
1077    /// focus without.
1078    fn set_focused_item_keeping_state(
1079        self: Handle<Self>,
1080        app: &mut App,
1081        index: Option<usize>,
1082        scroll: bool,
1083    ) {
1084        let state = if self.has_focus(app) {
1085            FocusState::current(app)
1086        } else {
1087            FocusState::coerce_programmatic(app)
1088        };
1089        self.set_focused_item(app, index, scroll, false, state);
1090    }
1091
1092    /// `SetFocusedItem`: records the focused index, scrolls the item into view when asked and the
1093    /// drop-down is open, and focuses it when `force` or the box has the focus. Without an item,
1094    /// the box focuses itself.
1095    fn set_focused_item(
1096        self: Handle<Self>,
1097        app: &mut App,
1098        index: Option<usize>,
1099        scroll: bool,
1100        force: bool,
1101        state: FocusState,
1102    ) {
1103        let count = self.item_count(app);
1104        let index = index.filter(|index| *index < count);
1105        let should_focus = force || self.has_focus(app);
1106        if should_focus
1107            || app
1108                .get(self)
1109                .focused_index
1110                .is_some_and(|focused| focused >= count)
1111        {
1112            app.get_mut(self).focused_index = index;
1113        }
1114        let Some(index) = index else {
1115            if should_focus {
1116                self.focus_box(app, state);
1117            }
1118            return;
1119        };
1120        if scroll && app.get(self).open {
1121            self.scroll_into_view(app, index);
1122        }
1123        if should_focus {
1124            self.focus_item(app, index, state);
1125        }
1126    }
1127
1128    /// `FocusSelfOrChild` on the item at `index`: once it is built, if the drop-down is still
1129    /// open then.
1130    fn focus_item(self: Handle<Self>, app: &mut App, index: usize, state: FocusState) {
1131        let id = self.widget(app).items[index].id.clone();
1132        let node = self.item_focus_node(app, &id);
1133        FocusState::name(app, node.as_node(), state);
1134        self.request_item_focus(app, node, app.get(self).open_epoch, 0);
1135    }
1136
1137    /// Requests focus for an item, retrying for a few frames while the list builds it.
1138    fn request_item_focus(
1139        self: Handle<Self>,
1140        app: &mut App,
1141        node: Ref<FocusNode>,
1142        epoch: u64,
1143        attempt: u32,
1144    ) {
1145        if node.as_node().context(app).is_some() {
1146            node.request_focus(app, None);
1147            return;
1148        }
1149        if attempt < 3 {
1150            self.after_frame(app, move |app| {
1151                if app.get(self).open && app.get(self).open_epoch == epoch {
1152                    self.request_item_focus(app, node.clone(), epoch, attempt + 1);
1153                }
1154            });
1155        }
1156    }
1157
1158    /// The focus of the item `id`, made the first time it is asked for.
1159    fn item_focus_node(self: Handle<Self>, app: &mut App, id: &str) -> Ref<FocusNode> {
1160        if let Some(node) = app.get(self).item_focus.get(id) {
1161            return node.clone();
1162        }
1163        let node = FocusNode::new(app);
1164        // The items are reached with the arrow keys, never by Tab.
1165        node.as_node().set_skip_traversal(app, true);
1166        app.get_mut(self)
1167            .item_focus
1168            .insert(id.to_owned(), node.clone());
1169        node
1170    }
1171
1172    /// The index of the item with the primary focus.
1173    fn focused_item_index(self: Handle<Self>, app: &App) -> Option<usize> {
1174        let focus = app.get(self);
1175        let id = focus
1176            .item_focus
1177            .iter()
1178            .find(|(_, node)| node.has_primary_focus(app))?
1179            .0;
1180        self.widget(app)
1181            .items
1182            .iter()
1183            .position(|item| &item.id == id)
1184    }
1185
1186    /// `FocusChanged`: the box is selection-active while it has the focus, and losing the focus
1187    /// cancels the drop-down.
1188    fn focus_changed(self: Handle<Self>, app: &mut App, has_focus: bool) {
1189        app.get_mut(self).selection_active = has_focus;
1190        if !has_focus {
1191            app.get_mut(self).closing_due_to_cancel = true;
1192            self.put_is_drop_down_open(app, false);
1193        }
1194        self.set_state(app, |_| {});
1195    }
1196
1197    /// `OnGotFocus`, for the focus arriving anywhere in the box. In an editable box, a focused
1198    /// text box takes its size and selects its text, matching it to the items; the focus arriving
1199    /// elsewhere moves on to the text box when it has no size yet or has to.
1200    fn on_got_focus(self: Handle<Self>, app: &mut App) {
1201        let has_focus = self.has_focus(app);
1202        self.focus_changed(app, has_focus);
1203        if !self.is_editable(app) {
1204            return;
1205        }
1206        if self.editable_text_has_focus(app) {
1207            app.get_mut(self).should_move_focus_to_text_box = false;
1208            self.ensure_text_box_is_enabled(app, false);
1209            self.select_all(app);
1210            self.process_search(app, &Typed::none());
1211        } else if !app.get(self).text_box_enabled || app.get(self).should_move_focus_to_text_box {
1212            self.ensure_text_box_is_enabled(app, true);
1213        }
1214    }
1215
1216    /// `OnLostFocus`, for the focus leaving the box: an editable box commits its text, and its
1217    /// text box gives way to `ContentPresenter`.
1218    fn on_lost_focus(self: Handle<Self>, app: &mut App) {
1219        let has_focus = self.has_focus(app);
1220        self.focus_changed(app, has_focus);
1221        if self.is_editable(app) && !has_focus {
1222            self.commit_revert_editable_search(app, false);
1223            self.set_state(app, |state| {
1224                state.text_box_enabled = false;
1225                state.should_move_focus_to_text_box = true;
1226            });
1227        }
1228    }
1229
1230    /// The box's focus changed: arriving focus runs `OnGotFocus`.
1231    fn box_focus_changed(self: Handle<Self>, app: &mut App) {
1232        if self.box_focus(app).has_primary_focus(app) {
1233            self.on_got_focus(app);
1234        }
1235        self.set_state(app, |_| {});
1236    }
1237
1238    /// The text box's focus changed: arriving focus runs `OnGotFocus`.
1239    fn text_focus_changed(self: Handle<Self>, app: &mut App) {
1240        if self.text_focus(app).has_primary_focus(app) {
1241            self.on_got_focus(app);
1242        }
1243        self.set_state(app, |_| {});
1244    }
1245
1246    /// `ItemFocused` and `ItemUnfocused`, then `OnGotFocus`.
1247    fn item_focus_changed(self: Handle<Self>, app: &mut App, index: usize, focused: bool) {
1248        if focused {
1249            app.get_mut(self).focused_index = Some(index);
1250            self.on_got_focus(app);
1251        } else if app.get(self).focused_index == Some(index) {
1252            app.get_mut(self).focused_index = None;
1253        }
1254        self.set_state(app, |_| {});
1255    }
1256
1257    /// The focus entered or left the box as a whole.
1258    fn scope_focus_changed(self: Handle<Self>, app: &mut App, has_focus: bool) {
1259        if !has_focus {
1260            self.on_lost_focus(app);
1261        }
1262    }
1263
1264    // MARK: Editable mode
1265
1266    /// `EnsureTextBoxIsEnabled`: the text box takes its size in place of `ContentPresenter`, and
1267    /// the focus when asked.
1268    fn ensure_text_box_is_enabled(self: Handle<Self>, app: &mut App, move_focus: bool) {
1269        self.set_state(app, |state| state.text_box_enabled = true);
1270        if move_focus {
1271            self.text_focus(app).request_focus(app, None);
1272            app.get_mut(self).should_move_focus_to_text_box = false;
1273        }
1274    }
1275
1276    /// `SetupEditableMode`: the text box shows the selection, with no search or revert pending.
1277    fn setup_editable_mode(self: Handle<Self>, app: &mut App) {
1278        let selected = self.selected(app);
1279        if let Some(text) = self.selection_text(app, &selected) {
1280            self.update_editable_text_box(app, &text, false, false);
1281        }
1282        let state = app.get_mut(self);
1283        state.restore_index_set = false;
1284        state.index_to_restore = None;
1285        state.search_result = None;
1286        state.type_ahead.reset();
1287    }
1288
1289    /// `DisableEditableMode`: no search or revert pending, and a custom value is no longer
1290    /// selected.
1291    fn disable_editable_mode(self: Handle<Self>, app: &mut App) {
1292        let state = app.get_mut(self);
1293        state.search_result = None;
1294        state.type_ahead.reset();
1295        state.should_move_focus_to_text_box = false;
1296        state.restore_index_set = false;
1297        state.index_to_restore = None;
1298        state.text_box_enabled = false;
1299        if state.custom_value_ref.take().is_some() {
1300            self.set_selection(app, Selection::None);
1301        }
1302        self.text(app).set_value(app, TextEditingValue::new());
1303    }
1304
1305    /// `CommitRevertEditableSearch`. Reverting goes back to the selection remembered when the
1306    /// drop-down opened or the selection last changed. Committing selects the item the search
1307    /// found; text that matches no item and is not only spaces raises `TextSubmitted`, and
1308    /// unless the application handles it, selects an item it matches exactly or else becomes a
1309    /// custom value. The text box then shows the selection with its text selected.
1310    fn commit_revert_editable_search(self: Handle<Self>, app: &mut App, restore: bool) {
1311        if restore {
1312            if app.get(self).restore_index_set {
1313                let restore = match app.get(self).index_to_restore {
1314                    Some(index) if index < self.item_count(app) => Selection::Index(index),
1315                    _ => match app.get(self).custom_value_ref.clone() {
1316                        Some(text) => Selection::Custom(text),
1317                        None => Selection::None,
1318                    },
1319                };
1320                self.set_selection(app, restore);
1321            }
1322        } else {
1323            if app.get(self).search_result.is_none() {
1324                self.process_search(app, &Typed::none());
1325            }
1326            if let Some(Some(index)) = app.get(self).search_result {
1327                self.set_selection(app, Selection::Index(index));
1328                app.get_mut(self).custom_value_ref = None;
1329            } else {
1330                let text = self.text(app).text_value(app).to_owned();
1331                if search::is_search_string_valid(&text) {
1332                    let send = app
1333                        .get(self)
1334                        .custom_value_ref
1335                        .as_ref()
1336                        .is_none_or(|stored| !search::are_strings_equal(stored, &text));
1337                    if send {
1338                        if !self.raise_text_submitted(app, &text) {
1339                            match self.search_item_source_index(
1340                                app,
1341                                &Typed::none(),
1342                                false,
1343                                Match::Exact,
1344                            ) {
1345                                Some(index) => {
1346                                    app.get_mut(self).custom_value_ref = None;
1347                                    self.set_selection(app, Selection::Index(index));
1348                                }
1349                                None => self.set_selection(app, Selection::Custom(text)),
1350                            }
1351                        }
1352                    } else if self.selected_index(app).is_some() {
1353                        self.set_selection(app, Selection::Custom(text));
1354                    }
1355                }
1356            }
1357        }
1358        let selected = self.selected(app);
1359        match self.selection_text(app, &selected) {
1360            Some(text) => self.update_editable_text_box(app, &text, true, true),
1361            None => {
1362                self.text(app).set_value(app, TextEditingValue::new());
1363                self.select_all(app);
1364            }
1365        }
1366        let state = app.get_mut(self);
1367        state.search_result = None;
1368        state.restore_index_set = false;
1369        state.index_to_restore = None;
1370        self.set_state(app, |_| {});
1371    }
1372
1373    /// `RaiseTextSubmittedEvent`: whether the application handled the text.
1374    fn raise_text_submitted(self: Handle<Self>, app: &mut App, text: &str) -> bool {
1375        let Some(handler) = self.widget(app).text_submitted.clone() else {
1376            return false;
1377        };
1378        let mut args = ComboBoxTextSubmittedEventArgs {
1379            text: text.to_owned(),
1380            handled: false,
1381        };
1382        handler(app, &mut args);
1383        args.handled
1384    }
1385
1386    /// `UpdateEditableTextBox`: the text box shows `text`, unless it already does but for the
1387    /// case of ASCII letters. With `select_all`, all of it is selected; otherwise, completing
1388    /// typed text, what follows the caret is.
1389    fn update_editable_text_box(
1390        self: Handle<Self>,
1391        app: &mut App,
1392        text: &str,
1393        select_text: bool,
1394        select_all: bool,
1395    ) {
1396        let controller = self.text(app);
1397        if search::are_strings_equal(text, controller.text_value(app)) {
1398            return;
1399        }
1400        app.get_mut(self).type_ahead.search = text.to_owned();
1401        let length = text.encode_utf16().count() as i32;
1402        let start = controller.selection(app).range().start.max(0);
1403        let selection = if select_text && select_all {
1404            TextSelection::new(0, length)
1405        } else if select_text {
1406            TextSelection::new(start.min(length), length)
1407        } else {
1408            // Setting `Text` puts the caret at the start.
1409            TextSelection::collapsed(0, TextAffinity::Downstream)
1410        };
1411        controller.set_value(app, TextEditingValue::new().text(text).selection(selection));
1412    }
1413
1414    /// `TextBox::SelectAll`.
1415    fn select_all(self: Handle<Self>, app: &mut App) {
1416        let controller = self.text(app);
1417        let end = controller.text_value(app).encode_utf16().count() as i32;
1418        controller.set_selection(app, TextSelection::new(0, end));
1419    }
1420
1421    /// The text box's text changed through an edit: a character or Backspace typed for it is
1422    /// what `OnCharacterReceived` receives once the text box has taken it.
1423    fn text_edited(self: Handle<Self>, app: &mut App) {
1424        let typed = app.get_mut(self).pending_typed.take();
1425        if let Some(typed) = typed
1426            && self.widget(app).is_text_search_enabled
1427        {
1428            self.process_search(app, &typed);
1429        }
1430    }
1431
1432    /// A key reached the text box's focus before the text box: a character or Backspace is
1433    /// remembered for the edit it makes.
1434    fn text_box_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
1435        if matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
1436            let typed = if event.logical_key() == LogicalKeyboardKey::BACKSPACE {
1437                Some(Typed::Backspace)
1438            } else {
1439                event
1440                    .character()
1441                    .map(|text| Typed::Character(text.to_owned()))
1442            };
1443            app.get_mut(self).pending_typed = typed;
1444        }
1445        KeyEventResult::Ignored
1446    }
1447
1448    // MARK: Search
1449
1450    /// `ProcessSearch`. An editable box matches its text to the items, completing the text with
1451    /// the item that starts with it, and draws the item selected in an open drop-down; a
1452    /// non-editable box adds `typed` to its typed search and selects the item it finds.
1453    fn process_search(self: Handle<Self>, app: &mut App, typed: &Typed) {
1454        if self.is_editable(app) {
1455            let text = self.text(app).text_value(app).to_owned();
1456            if search::are_strings_equal(&text, &app.get(self).type_ahead.search) {
1457                return;
1458            }
1459            let found = if text.is_empty() {
1460                app.get_mut(self).type_ahead.reset();
1461                None
1462            } else {
1463                self.search_item_source_index(app, typed, false, Match::Prefix)
1464            };
1465            app.get_mut(self).search_result = Some(found);
1466            if self.widget(app).selection_changed_trigger == ComboBoxSelectionChangedTrigger::Always
1467                && let Some(index) = found
1468            {
1469                self.set_selection(app, Selection::Index(index));
1470            }
1471            if app.get(self).open {
1472                self.override_selected_index_for_visual_states(app, found);
1473                if let Some(index) = found {
1474                    self.scroll_into_view(app, index);
1475                }
1476            }
1477            self.set_state(app, |_| {});
1478        } else if let Some(index) = self.search_item_source_index(app, typed, true, Match::Prefix) {
1479            self.set_selection(app, Selection::Index(index));
1480        }
1481    }
1482
1483    /// `SearchItemSourceIndex`: an editable box searches with its text from the first item; a
1484    /// non-editable box adds `typed` and searches from the selection. Backspace in an editable
1485    /// box searches for exact matches only; a prefix match there completes the text.
1486    fn search_item_source_index(
1487        self: Handle<Self>,
1488        app: &mut App,
1489        typed: &Typed,
1490        from_current: bool,
1491        rule: Match,
1492    ) -> Option<usize> {
1493        let editable = self.is_editable(app);
1494        let count = self.item_count(app);
1495        let created = if editable {
1496            let text = self.text(app).text_value(app).to_owned();
1497            app.get_mut(self).type_ahead.search = text;
1498            false
1499        } else {
1500            let character = match typed {
1501                Typed::Character(character) => character.clone(),
1502                Typed::Backspace => return None,
1503            };
1504            let now = app.get(self).last_key_time();
1505            app.get_mut(self).type_ahead.append(&character, now)
1506        };
1507        let start = if from_current {
1508            search::search_start(self.selected_index(app), count, created)
1509        } else {
1510            0
1511        };
1512        let rule = if editable && *typed == Typed::Backspace {
1513            Match::Exact
1514        } else {
1515            rule
1516        };
1517        let widget = self.widget(app).clone();
1518        let texts: Vec<Option<&str>> = widget
1519            .items
1520            .iter()
1521            .map(|item| item.plain_text.as_deref())
1522            .collect();
1523        let found = search::find_item(&texts, &app.get(self).type_ahead.search, start, rule);
1524        if editable
1525            && rule == Match::Prefix
1526            && let Some(index) = found
1527        {
1528            let text = self.item_text(app, index);
1529            self.update_editable_text_box(app, &text, true, false);
1530        }
1531        found
1532    }
1533
1534    /// `IsInSearchingMode`.
1535    fn is_in_searching_mode(self: Handle<Self>, app: &mut App) -> bool {
1536        let now = app.get(self).last_key_time();
1537        self.widget(app).is_text_search_enabled && app.get_mut(self).type_ahead.is_searching(now)
1538    }
1539
1540    // MARK: Keyboard
1541
1542    /// The box's key handler, which every key of the box, its text box and its drop-down reaches:
1543    /// `OnKeyDownPrivate` and `OnKeyUpPrivate`, and for a key the box leaves unhandled,
1544    /// `OnCharacterReceived`. Keys the text box takes first in WinUI are left to it.
1545    fn on_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
1546        app.get_mut(self).key_time = Some(event.time_stamp());
1547        match event {
1548            KeyEvent::Down(_) | KeyEvent::Repeat(_) => {
1549                if self.editable_text_has_focus(app) && is_text_box_key(event.logical_key()) {
1550                    return KeyEventResult::Ignored;
1551                }
1552                if self.key_down(app, event) {
1553                    app.get_mut(self).pending_typed = None;
1554                    return KeyEventResult::Handled;
1555                }
1556                if let Some(character) = event.character()
1557                    && character != "\u{1b}"
1558                    && !self.is_editable(app)
1559                    && self.widget(app).is_enabled
1560                    && self.widget(app).is_text_search_enabled
1561                {
1562                    self.process_search(app, &Typed::Character(character.to_owned()));
1563                }
1564                KeyEventResult::Ignored
1565            }
1566            KeyEvent::Up(_) => {
1567                if app.get(self).ignore_cancel_key_downs
1568                    && event.logical_key() == LogicalKeyboardKey::ESCAPE
1569                {
1570                    app.get_mut(self).ignore_cancel_key_downs = false;
1571                    return KeyEventResult::Handled;
1572                }
1573                KeyEventResult::Ignored
1574            }
1575        }
1576    }
1577
1578    /// `OnKeyDownPrivate`: whether the box handled the key.
1579    fn key_down(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> bool {
1580        let key = event.logical_key();
1581        if app.get(self).ignore_cancel_key_downs && key == LogicalKeyboardKey::ESCAPE {
1582            return true;
1583        }
1584        if !self.widget(app).is_enabled {
1585            return false;
1586        }
1587        if app.get(self).open {
1588            self.popup_key_down(app, key)
1589        } else {
1590            self.main_key_down(app, key)
1591        }
1592    }
1593
1594    /// `MainKeyDown`, for a closed drop-down: F4, Alt+Up and Alt+Down, Enter and Space open it,
1595    /// Up, Down, Home and End select. An editable box opens with Up and Down too, commits on
1596    /// Enter and Tab and reverts on Escape.
1597    fn main_key_down(self: Handle<Self>, app: &mut App, key: LogicalKeyboardKey) -> bool {
1598        let modifiers = Modifiers::of(app);
1599        let editable = self.is_editable(app);
1600        let mut handled = true;
1601        let mut new_index = None;
1602        match key {
1603            LogicalKeyboardKey::ESCAPE => {
1604                if editable {
1605                    self.commit_revert_editable_search(app, true);
1606                    self.clear_selected_index_override_for_visual_states(app);
1607                } else {
1608                    handled = false;
1609                }
1610            }
1611            LogicalKeyboardKey::ENTER | LogicalKeyboardKey::NUMPAD_ENTER => {
1612                if editable {
1613                    self.commit_revert_editable_search(app, false);
1614                } else if !self.is_in_searching_mode(app) {
1615                    self.put_is_drop_down_open(app, true);
1616                }
1617            }
1618            LogicalKeyboardKey::TAB => {
1619                if editable {
1620                    self.commit_revert_editable_search(app, false);
1621                }
1622                handled = false;
1623            }
1624            LogicalKeyboardKey::SPACE => {
1625                if editable {
1626                    handled = false;
1627                } else if self.is_in_searching_mode(app) {
1628                    self.process_search(app, &Typed::none());
1629                } else {
1630                    self.put_is_drop_down_open(app, true);
1631                }
1632            }
1633            LogicalKeyboardKey::ARROW_DOWN | LogicalKeyboardKey::ARROW_UP
1634                if editable || modifiers.alt =>
1635            {
1636                self.put_is_drop_down_open(app, true);
1637            }
1638            LogicalKeyboardKey::ARROW_DOWN
1639            | LogicalKeyboardKey::ARROW_UP
1640            | LogicalKeyboardKey::HOME
1641            | LogicalKeyboardKey::END => {
1642                let selected = self.selected_index(app);
1643                new_index = self.handle_navigation_key(app, key, false, selected);
1644            }
1645            LogicalKeyboardKey::F4 => {
1646                if modifiers.none() {
1647                    self.put_is_drop_down_open(app, true);
1648                } else {
1649                    handled = false;
1650                }
1651            }
1652            _ => handled = false,
1653        }
1654        if let Some(index) = new_index {
1655            self.set_selection(app, Selection::Index(index));
1656        }
1657        handled
1658    }
1659
1660    /// `PopupKeyDown`, for an open drop-down: Escape cancels it, Tab, F4 and Alt+Up or Alt+Down
1661    /// close it, Enter and Space select the focused item and close it, and Up, Down, Home, End,
1662    /// Page Up and Page Down move through the items. Space while typing a search is typed.
1663    fn popup_key_down(self: Handle<Self>, app: &mut App, key: LogicalKeyboardKey) -> bool {
1664        let modifiers = Modifiers::of(app);
1665        let editable = self.is_editable(app);
1666        let text_focus = self.editable_text_has_focus(app);
1667        let mut handled = false;
1668        let mut new_focused: Option<usize> = None;
1669        match key {
1670            LogicalKeyboardKey::ESCAPE => {
1671                let state = FocusState::coerce_programmatic(app);
1672                self.focus_box(app, state);
1673                app.get_mut(self).closing_due_to_cancel = true;
1674                self.put_is_drop_down_open(app, false);
1675                app.get_mut(self).ignore_cancel_key_downs = true;
1676                handled = true;
1677            }
1678            LogicalKeyboardKey::TAB => {
1679                // Tab then moves on from the box. The text box of an editable box is where it
1680                // moves on from: its box is no tab stop of its own.
1681                if !editable {
1682                    let state = FocusState::coerce_programmatic(app);
1683                    self.focus_box(app, state);
1684                    FocusManager::instance(app).apply_focus_changes_if_needed(app);
1685                }
1686                self.put_is_drop_down_open(app, false);
1687            }
1688            LogicalKeyboardKey::SPACE if editable || self.is_in_searching_mode(app) => {}
1689            LogicalKeyboardKey::SPACE
1690            | LogicalKeyboardKey::ENTER
1691            | LogicalKeyboardKey::NUMPAD_ENTER => {
1692                if !(modifiers.alt && !modifiers.control) {
1693                    if editable && text_focus {
1694                        self.put_is_drop_down_open(app, false);
1695                        handled = true;
1696                    } else if let Some(index) = self.focused_item_index(app) {
1697                        if modifiers.control && self.selected_index(app) == Some(index) {
1698                            self.set_selection(app, Selection::None);
1699                        } else {
1700                            let focused = app.get(self).focused_index;
1701                            self.set_selection(
1702                                app,
1703                                focused.map_or(Selection::None, Selection::Index),
1704                            );
1705                            self.put_is_drop_down_open(app, false);
1706                        }
1707                        handled = true;
1708                    }
1709                }
1710            }
1711            LogicalKeyboardKey::ARROW_UP | LogicalKeyboardKey::ARROW_DOWN
1712                if editable && text_focus =>
1713            {
1714                let current = match app.get(self).search_result {
1715                    Some(result) => result,
1716                    None => self.selected_index(app),
1717                };
1718                new_focused = Some(match (current, key) {
1719                    (Some(index), LogicalKeyboardKey::ARROW_DOWN) => index + 1,
1720                    (None, LogicalKeyboardKey::ARROW_DOWN) => 0,
1721                    (Some(index), _) => index.saturating_sub(1),
1722                    (None, _) => 0,
1723                });
1724            }
1725            LogicalKeyboardKey::ARROW_UP | LogicalKeyboardKey::ARROW_DOWN if modifiers.alt => {
1726                self.put_is_drop_down_open(app, false);
1727                handled = true;
1728            }
1729            LogicalKeyboardKey::ARROW_UP
1730            | LogicalKeyboardKey::ARROW_DOWN
1731            | LogicalKeyboardKey::HOME
1732            | LogicalKeyboardKey::END
1733            | LogicalKeyboardKey::PAGE_UP
1734            | LogicalKeyboardKey::PAGE_DOWN => {
1735                let focused = app.get(self).focused_index;
1736                new_focused = self.handle_navigation_key(app, key, true, focused);
1737                handled = true;
1738            }
1739            LogicalKeyboardKey::ARROW_LEFT | LogicalKeyboardKey::ARROW_RIGHT => handled = true,
1740            LogicalKeyboardKey::F4 if modifiers.none() => {
1741                self.put_is_drop_down_open(app, false);
1742                handled = true;
1743            }
1744            _ => {}
1745        }
1746        if let Some(new) = new_focused {
1747            handled = true;
1748            let count = self.item_count(app);
1749            if count > 0 {
1750                let new = new.min(count - 1);
1751                if editable && text_focus {
1752                    app.get_mut(self).search_result = Some(Some(new));
1753                    let text = self.item_text(app, new);
1754                    self.update_editable_text_box(app, &text, true, true);
1755                    self.scroll_into_view(app, new);
1756                } else {
1757                    self.set_focused_item(app, Some(new), true, false, FocusState::Keyboard);
1758                }
1759                if self.widget(app).selection_changed_trigger
1760                    == ComboBoxSelectionChangedTrigger::Always
1761                {
1762                    self.set_selection(app, Selection::Index(new));
1763                } else {
1764                    self.override_selected_index_for_visual_states(app, Some(new));
1765                }
1766            }
1767        }
1768        handled
1769    }
1770
1771    /// `HandleNavigationKey` for the vertical list: Up and Down move to the previous and next
1772    /// enabled item, scrolling a line instead where there is none and `scroll_viewport` is set;
1773    /// Home and End go to the first and last item; Page Up and Page Down by a page.
1774    fn handle_navigation_key(
1775        self: Handle<Self>,
1776        app: &mut App,
1777        key: LogicalKeyboardKey,
1778        scroll_viewport: bool,
1779        index: Option<usize>,
1780    ) -> Option<usize> {
1781        let count = self.item_count(app);
1782        let focused = app.get(self).focused_index;
1783        let new = match key {
1784            LogicalKeyboardKey::ARROW_UP => {
1785                let new = self.select_prev(app, index);
1786                if focused == new && scroll_viewport {
1787                    self.scroll_by(app, -LINE_DELTA);
1788                }
1789                new
1790            }
1791            LogicalKeyboardKey::ARROW_DOWN => {
1792                let new = self.select_next(app, index);
1793                if focused == new && scroll_viewport {
1794                    self.scroll_by(app, LINE_DELTA);
1795                }
1796                new
1797            }
1798            LogicalKeyboardKey::HOME => Some(0),
1799            LogicalKeyboardKey::END => count.checked_sub(1),
1800            LogicalKeyboardKey::PAGE_UP => self.navigate_by_page(app, false),
1801            LogicalKeyboardKey::PAGE_DOWN => self.navigate_by_page(app, true),
1802            _ => index,
1803        };
1804        new.filter(|new| *new < count)
1805    }
1806
1807    /// `SelectNext`: the next enabled item after `index`, or `index`.
1808    fn select_next(self: Handle<Self>, app: &App, index: Option<usize>) -> Option<usize> {
1809        let start = index.map_or(0, |index| index + 1);
1810        let items = &self.widget(app).items;
1811        (start..items.len())
1812            .find(|index| items[*index].is_enabled)
1813            .or(index)
1814    }
1815
1816    /// `SelectPrev`: the previous enabled item before `index`, or `index`.
1817    fn select_prev(self: Handle<Self>, app: &App, index: Option<usize>) -> Option<usize> {
1818        let items = &self.widget(app).items;
1819        let start = index?;
1820        (0..start)
1821            .rev()
1822            .find(|index| items[*index].is_enabled)
1823            .or(Some(start))
1824    }
1825
1826    /// `NavigateByPage`: the last item fully on the page in the direction of travel, scrolling a
1827    /// page when the focused item already is, and advancing at least one item.
1828    fn navigate_by_page(self: Handle<Self>, app: &mut App, forward: bool) -> Option<usize> {
1829        let focused = app.get(self).focused_index;
1830        let Some(focused) = focused else {
1831            return self.first_item_on_current_page(app, None, forward);
1832        };
1833        if !self.is_on_current_page(app, focused, true) {
1834            self.scroll_into_view(app, focused);
1835        }
1836        let mut new = self.first_item_on_current_page(app, Some(focused), forward);
1837        if new == Some(focused) {
1838            let viewport = self
1839                .scroll_metrics(app)
1840                .map_or(0.0, |metrics| metrics.viewport_length);
1841            self.scroll_by(app, if forward { viewport } else { -viewport });
1842            new = self.first_item_on_current_page(app, Some(focused), forward);
1843            if new == Some(focused) {
1844                let count = self.item_count(app);
1845                if forward && count > 0 && focused < count - 1 {
1846                    new = Some(focused + 1);
1847                } else if !forward && focused > 0 {
1848                    new = Some(focused - 1);
1849                }
1850            }
1851        }
1852        new
1853    }
1854
1855    /// `GetFirstItemOnCurrentPage`: from `start`, the first item at least partly on the page in
1856    /// the direction of travel, then the last one after it that is fully on it.
1857    fn first_item_on_current_page(
1858        self: Handle<Self>,
1859        app: &mut App,
1860        start: Option<usize>,
1861        forward: bool,
1862    ) -> Option<usize> {
1863        let count = self.item_count(app) as i64;
1864        let delta = if forward { 1 } else { -1 };
1865        let mut result = start.map_or(-1, |start| start as i64);
1866        let mut probe = result;
1867        let in_range = |probe: i64| 0 <= probe && probe < count;
1868        let mut on_page = false;
1869        while in_range(probe) {
1870            on_page = self.is_on_current_page(app, probe as usize, true);
1871            if on_page {
1872                break;
1873            }
1874            result = probe;
1875            probe += delta;
1876        }
1877        if on_page {
1878            result = probe;
1879            probe += delta;
1880            on_page = in_range(probe) && self.is_on_current_page(app, probe as usize, false);
1881            if on_page {
1882                result = probe;
1883                probe += delta;
1884                while in_range(probe) && self.is_on_current_page(app, probe as usize, false) {
1885                    result = probe;
1886                    probe += delta;
1887                }
1888            }
1889        }
1890        (result >= 0).then_some(result as usize)
1891    }
1892
1893    /// `IsOnCurrentPage`: whether the item is on the drop-down's visible page, at least partly
1894    /// with `partial`, else entirely.
1895    fn is_on_current_page(self: Handle<Self>, app: &mut App, index: usize, partial: bool) -> bool {
1896        let Some(metrics) = self.scroll_metrics(app) else {
1897            return false;
1898        };
1899        let r = ThemeResources::of(app, self.context(app));
1900        let heights = self.item_heights(app, self.context(app));
1901        let top = heights[..index].iter().sum::<f64>() - metrics.offset;
1902        let bottom = top + heights[index];
1903        // The scroll host is the viewport with the items' fixed margin around it.
1904        let margin = r.combo_box_dropdown_content_margin;
1905        let (host_top, host_bottom) = (-margin[1], metrics.viewport_length + margin[3]);
1906        if partial {
1907            top < host_bottom && host_top < bottom
1908        } else {
1909            host_top <= top && bottom <= host_bottom
1910        }
1911    }
1912
1913    /// `ScrollIntoView` with the default alignment: the least scrolling that shows the item.
1914    fn scroll_into_view(self: Handle<Self>, app: &mut App, index: usize) {
1915        let Some(metrics) = self.scroll_metrics(app) else {
1916            // The list has not been laid out yet.
1917            let epoch = app.get(self).open_epoch;
1918            self.after_frame(app, move |app| {
1919                if app.get(self).open
1920                    && app.get(self).open_epoch == epoch
1921                    && self.scroll_metrics(app).is_some()
1922                    && index < self.item_count(app)
1923                {
1924                    self.scroll_into_view(app, index);
1925                }
1926            });
1927            return;
1928        };
1929        let heights = self.item_heights(app, self.context(app));
1930        let top: f64 = heights[..index].iter().sum();
1931        let bottom = top + heights[index];
1932        let target = if top < metrics.offset {
1933            top
1934        } else if bottom > metrics.offset + metrics.viewport_length {
1935            bottom - metrics.viewport_length
1936        } else {
1937            return;
1938        };
1939        let scroll = app.get(self).scroll.clone().unwrap();
1940        scroll.change_view(app, target, true);
1941    }
1942
1943    /// Scrolls the drop-down by `delta` at once.
1944    fn scroll_by(self: Handle<Self>, app: &mut App, delta: f64) {
1945        if let Some(scroll) = app.get(self).scroll.handle() {
1946            scroll.scroll_by(app, delta, true);
1947        }
1948    }
1949
1950    /// The drop-down list's scroll metrics, once it is laid out.
1951    fn scroll_metrics(self: Handle<Self>, app: &App) -> Option<ScrollViewportMetrics> {
1952        let scroll = app.get(self).scroll.handle()?;
1953        let metrics = scroll.metrics(app);
1954        (metrics.viewport_length > 0.0).then_some(metrics)
1955    }
1956
1957    // MARK: Pointer
1958
1959    /// `OnPointerPressed` on the box: the left button presses it.
1960    fn pointer_pressed(self: Handle<Self>, app: &mut App) {
1961        if self.widget(app).is_enabled {
1962            self.set_state(app, |state| state.pressed = true);
1963        }
1964    }
1965
1966    /// `OnPointerReleased` and `PerformPointerUpAction`: the box takes the focus, then opens, or
1967    /// in an editable box, opens or closes when the press was on `DropDownOverlay`.
1968    fn pointer_released(self: Handle<Self>, app: &mut App, on_overlay: bool) {
1969        if !std::mem::take(&mut app.get_mut(self).pressed) {
1970            return;
1971        }
1972        self.set_state(app, |_| {});
1973        self.focus_box(app, FocusState::Pointer);
1974        if !self.is_editable(app) {
1975            self.put_is_drop_down_open(app, true);
1976        } else if on_overlay {
1977            let open = app.get(self).open;
1978            self.put_is_drop_down_open(app, !open);
1979        }
1980    }
1981
1982    /// `OnPointerWheelChanged`: while the box has the focus it takes the wheel, and while closed
1983    /// selects the next or previous enabled item.
1984    fn pointer_signal(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
1985        if !matches!(event, PointerEvent::Scroll(_))
1986            || !self.widget(app).is_enabled
1987            || !self.has_focus(app)
1988        {
1989            return;
1990        }
1991        let resolver = GestureBinding::instance(app).pointer_signal_resolver(app);
1992        resolver.register(
1993            app,
1994            event,
1995            Rc::new(move |app, event| self.wheel(app, event)),
1996        );
1997    }
1998
1999    /// One wheel event the box took. `MouseWheelDelta` is positive for a wheel turned away from
2000    /// the user, where Waft's vertical scroll delta is negative, and for a wheel tilted right.
2001    fn wheel(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
2002        let PointerEvent::Scroll(scroll) = event else {
2003            return;
2004        };
2005        if !self.alive(app) || app.get(self).open {
2006            return;
2007        }
2008        let delta = if scroll.scroll_delta.dy() != 0.0 {
2009            -scroll.scroll_delta.dy()
2010        } else {
2011            scroll.scroll_delta.dx()
2012        };
2013        let selected = self.selected_index(app);
2014        let new = if delta < 0.0 {
2015            self.select_next(app, selected)
2016        } else {
2017            self.select_prev(app, selected)
2018        };
2019        if let Some(new) = new {
2020            self.set_selection(app, Selection::Index(new));
2021        }
2022    }
2023
2024    /// A click on the item at `index`: `OnSelectorItemClicked` focuses it and selects it, or with
2025    /// Ctrl toggles its selection, then the drop-down closes.
2026    fn item_clicked(self: Handle<Self>, app: &mut App, index: usize) {
2027        self.focus_item(app, index, FocusState::Pointer);
2028        let control = HardwareKeyboard::instance(app).is_control_pressed(app);
2029        let is_selected = self.selected_index(app) == Some(index);
2030        let select = if control { !is_selected } else { true };
2031        self.set_selection(
2032            app,
2033            if select {
2034                Selection::Index(index)
2035            } else {
2036                Selection::None
2037            },
2038        );
2039        self.put_is_drop_down_open(app, false);
2040    }
2041
2042    /// An item reported its size in the drop-down.
2043    fn item_measured(self: Handle<Self>, app: &mut App, id: &str, size: Size) {
2044        if !self.alive(app) {
2045            return;
2046        }
2047        let state = app.get(self);
2048        if state.heights.get(id) == Some(&size.height())
2049            && state.widths.get(id) == Some(&size.width())
2050        {
2051            return;
2052        }
2053        let id = id.to_owned();
2054        self.set_state(app, |state| {
2055            state.heights.insert(id.clone(), size.height());
2056            state.widths.insert(id, size.width());
2057        });
2058    }
2059
2060    // MARK: Popup placement
2061
2062    /// `Background`'s bounds in the root overlay, and the overlay's size: what `ArrangePopup`
2063    /// reads at the opening.
2064    fn popup_geometry(self: Handle<Self>, app: &mut App) -> Option<(Rect, Size)> {
2065        let target = app
2066            .get(self)
2067            .background_key
2068            .clone()
2069            .current_context(app)?
2070            .find_render_object(app)?
2071            .as_box()?;
2072        let overlay = Overlay::of(app, self.context(app), true);
2073        let root = overlay.context(app).find_render_object(app)?.as_box()?;
2074        let transform = target
2075            .as_object()
2076            .get_transform_to(app, Some(root.as_object()));
2077        Some((
2078            transform_rect(&transform, Offset::ZERO & target.size(app)),
2079            root.size(app),
2080        ))
2081    }
2082
2083    /// Each item's height in the drop-down: as last laid out, or for an item not laid out yet,
2084    /// what an item of one line of text takes.
2085    fn item_heights(self: Handle<Self>, app: &mut App, context: BuildContext) -> Vec<f64> {
2086        let estimate = text_item_size(app, context, "").height();
2087        let widget = self.widget(app).clone();
2088        let heights = &app.get(self).heights;
2089        widget
2090            .items
2091            .iter()
2092            .map(|item| heights.get(&item.id).copied().unwrap_or(estimate))
2093            .collect()
2094    }
2095
2096    /// The width the drop-down's content asks for: the widest item laid out in this opening, and
2097    /// the text of the items it is about to show that are not laid out yet.
2098    fn content_width(
2099        self: Handle<Self>,
2100        app: &mut App,
2101        context: BuildContext,
2102        first_item: usize,
2103        window: Size,
2104    ) -> f64 {
2105        let r = ThemeResources::of(app, context);
2106        let widget = self.widget(app).clone();
2107        let shown = first_item..first_item + r.combo_box_popup_max_number_of_items as usize;
2108        let mut widest: f64 = 0.0;
2109        for (index, item) in widget.items.iter().enumerate() {
2110            let measured = app.get(self).widths.get(&item.id).copied();
2111            if let Some(width) = measured {
2112                widest = widest.max(width);
2113            } else if shown.contains(&index)
2114                && let Some(text) = &item.plain_text
2115            {
2116                widest = widest.max(text_item_size(app, context, text).width());
2117            }
2118        }
2119        let border =
2120            r.combo_box_dropdown_border_thickness[0] + r.combo_box_dropdown_border_thickness[2];
2121        (widest + border).max(popup::popup_min_width(&r, window))
2122    }
2123
2124    /// `ArrangePopup` with the box at `target` in a window of `window`.
2125    fn arrangement(
2126        self: Handle<Self>,
2127        app: &mut App,
2128        context: BuildContext,
2129        target: Rect,
2130        window: Size,
2131    ) -> Option<Arrangement> {
2132        let heights = self.item_heights(app, context);
2133        let fallback_height = text_item_size(app, context, "").height();
2134        let widget = self.widget(app).clone();
2135        let editable = widget.is_editable.then(|| {
2136            if app.get(self).text_box_enabled {
2137                target.height()
2138            } else {
2139                0.0
2140            }
2141        });
2142        let rtl = Directionality::maybe_of(app, context) == Some(waft_embedder::TextDirection::Rtl);
2143        let input = ArrangeInput {
2144            target,
2145            window,
2146            heights: &heights,
2147            fallback_height,
2148            selected: self.selected_index(app),
2149            max_drop_down_height: widget.max_drop_down_height,
2150            editable,
2151            content_width: 0.0,
2152            last_height: app.get(self).last_popup_height.get(),
2153            rtl,
2154        };
2155        let r = ThemeResources::of(app, context);
2156        let first_item = popup::arrange(&r, &input)?.first_item;
2157        let content_width = self.content_width(app, context, first_item, window);
2158        popup::arrange(
2159            &r,
2160            &ArrangeInput {
2161                content_width,
2162                ..input
2163            },
2164        )
2165    }
2166
2167    // MARK: Template
2168
2169    /// The box's `CommonStates`, `FocusStates` and, editable, `EditableModeStates`, as
2170    /// `ChangeVisualState` chooses them.
2171    fn visual_states(
2172        self: Handle<Self>,
2173        app: &mut App,
2174    ) -> (CommonState, ComboBoxFocusState, Option<EditableModeState>) {
2175        let shows_focus_visual = FocusState::current(app).shows_focus_visual();
2176        let widget = self.widget(app);
2177        let state = app.get(self);
2178        let editable = widget.is_editable.then(|| {
2179            let text_focus = self.editable_text_has_focus(app);
2180            match (state.pointer_over_overlay, state.pressed, text_focus) {
2181                (true, true, true) => EditableModeState::TextBoxFocusedOverlayPressed,
2182                (true, true, false) => EditableModeState::TextBoxOverlayPressed,
2183                (true, false, true) => EditableModeState::TextBoxFocusedOverlayPointerOver,
2184                (true, false, false) => EditableModeState::TextBoxOverlayPointerOver,
2185                (false, _, true) => EditableModeState::TextBoxFocused,
2186                (false, _, false) => EditableModeState::TextBoxUnfocused,
2187            }
2188        });
2189        let ignore_pressed = widget.is_editable && state.pointer_over_overlay && state.pressed;
2190        let common = if !widget.is_enabled {
2191            CommonState::Disabled
2192        } else if state.pressed && !ignore_pressed {
2193            CommonState::Pressed
2194        } else if state.pointer_over_main || state.pointer_over_popup {
2195            CommonState::PointerOver
2196        } else {
2197            CommonState::Normal
2198        };
2199        let box_focused = self.box_focus(app).has_primary_focus(app);
2200        let focus = if !state.selection_active || !widget.is_enabled {
2201            ComboBoxFocusState::Unfocused
2202        } else if state.open {
2203            ComboBoxFocusState::FocusedDropDown
2204        } else if !box_focused {
2205            ComboBoxFocusState::Unfocused
2206        } else if !shows_focus_visual {
2207            ComboBoxFocusState::PointerFocused
2208        } else if state.pressed {
2209            ComboBoxFocusState::FocusedPressed
2210        } else {
2211            ComboBoxFocusState::Focused
2212        };
2213        (common, focus, editable)
2214    }
2215}
2216
2217impl ComboBoxState {
2218    /// When the last key event arrived.
2219    fn last_key_time(&self) -> Duration {
2220        self.key_time.unwrap_or_default()
2221    }
2222}
2223
2224impl ComboBoxState {
2225    /// Keeps the focus of the items in `items`, and checks what the application passes: ids are
2226    /// unique, and `selected_index` is an index of `items`.
2227    fn sync_items(self: Handle<Self>, app: &mut App) {
2228        let widget = self.widget(app).clone();
2229        let ids: HashSet<&str> = widget.items.iter().map(|item| item.id.as_str()).collect();
2230        assert_eq!(
2231            ids.len(),
2232            widget.items.len(),
2233            "ComboBox item ids must be unique"
2234        );
2235        assert!(
2236            widget
2237                .selected_index
2238                .is_none_or(|index| index < widget.items.len()),
2239            "ComboBox selected_index must be an index of items"
2240        );
2241        let removed: Vec<String> = app
2242            .get(self)
2243            .item_focus
2244            .keys()
2245            .filter(|id| !ids.contains(id.as_str()))
2246            .cloned()
2247            .collect();
2248        for id in removed {
2249            let state = app.get_mut(self);
2250            let node = state.item_focus.remove(&id).unwrap();
2251            state.heights.remove(&id);
2252            state.widths.remove(&id);
2253            // The item's widget may still hold the node until the frame ends.
2254            let view = self.view(app);
2255            after_next_frame(
2256                app,
2257                view,
2258                FrameCallback::new(move |app, _| {
2259                    node.dispose(app);
2260                }),
2261            );
2262        }
2263    }
2264
2265    /// The application has answered the selection the box asked for, by building the box again:
2266    /// a selection it did not take is undone, which the text box of an editable box shows once
2267    /// the frame is over.
2268    fn settle_request(self: Handle<Self>, app: &mut App) {
2269        let Some(requested) = app.get_mut(self).requested.take() else {
2270            return;
2271        };
2272        let selection = app.get(self).selection.clone();
2273        if requested != selection {
2274            self.after_frame(app, move |app| {
2275                self.selection_did_change(app, &requested, &selection);
2276                self.set_state(app, |_| {});
2277            });
2278        }
2279    }
2280
2281    /// An application that owns `is_drop_down_open` and passes another state than the box has,
2282    /// or did not take the one the box asked for, has the box open or close once the frame is
2283    /// over.
2284    fn settle_drop_down_open(self: Handle<Self>, app: &mut App) {
2285        let Some(open) = self.widget(app).is_drop_down_open else {
2286            return;
2287        };
2288        if open == app.get(self).open || app.get(self).pending_open == Some(open) {
2289            return;
2290        }
2291        app.get_mut(self).pending_open = Some(open);
2292        self.after_frame(app, move |app| {
2293            app.get_mut(self).pending_open = None;
2294            if self.widget(app).is_drop_down_open == Some(open) {
2295                self.set_drop_down_open(app, open);
2296                self.set_state(app, |_| {});
2297            }
2298        });
2299    }
2300}
2301
2302impl State for ComboBoxState {
2303    type Widget = ComboBox;
2304    waft_widgets::state_accessors!();
2305
2306    fn init_state(self: Handle<Self>, app: &mut App) {
2307        // Programmatic focus, which opening gives the selected item, shows the focus visual only
2308        // after keyboard input.
2309        InputDevice::initialize(app);
2310        let scope_focus = FocusNode::new(app);
2311        let focus = FocusNode::new(app);
2312        focus.add_listener(app, Listener::handle_method(self, Self::box_focus_changed));
2313        let text = TextEditingController::new(app);
2314        let text_focus = FocusNode::new(app);
2315        text_focus.as_node().set_on_key_event(
2316            app,
2317            Some(Rc::new(move |app, _, event| self.text_box_key(app, event))),
2318        );
2319        text_focus.add_listener(app, Listener::handle_method(self, Self::text_focus_changed));
2320        let popup = OverlayPortalController::new(app, Some("ComboBox Popup".into()));
2321        let state = app.get_mut(self);
2322        state.scope_focus = Some(scope_focus);
2323        state.focus = Some(focus.clone());
2324        state.text = Some(text);
2325        state.text_focus = Some(text_focus.clone());
2326        state.popup = Some(popup);
2327        self.sync_items(app);
2328        if self.is_editable(app) {
2329            self.setup_editable_mode(app);
2330        }
2331    }
2332
2333    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ComboBox) {
2334        app.get_mut(self).building = true;
2335        self.sync_items(app);
2336        let widget = self.widget(app).clone();
2337        let passed = Selection::of(&widget);
2338        let current = self.selected(app);
2339        let state = app.get_mut(self);
2340        state.selection = passed.clone();
2341        state.requested = None;
2342        if current != passed {
2343            self.selection_did_change(app, &current, &passed);
2344        }
2345        // `OnPropertyChanged2` for `IsEditable`.
2346        if old.is_editable != widget.is_editable {
2347            if widget.is_editable {
2348                self.setup_editable_mode(app);
2349            } else {
2350                self.disable_editable_mode(app);
2351            }
2352        }
2353        // `OnIsEnabledChanged`'s `ClearStateFlags`.
2354        if old.is_enabled && !widget.is_enabled {
2355            let state = app.get_mut(self);
2356            state.pointer_over_main = false;
2357            state.pointer_over_popup = false;
2358            state.pointer_over_overlay = false;
2359            state.pressed = false;
2360            self.after_frame(app, move |app| self.put_is_drop_down_open(app, false));
2361        }
2362        app.get_mut(self).building = false;
2363    }
2364
2365    fn dispose(self: Handle<Self>, app: &mut App) {
2366        // `OnUnloaded` closes the drop-down.
2367        if app.get(self).open
2368            && let Some(closed) = self.widget(app).drop_down_closed.clone()
2369        {
2370            after_next_frame(
2371                app,
2372                None,
2373                FrameCallback::new(move |app, _| closed.call(app)),
2374            );
2375        }
2376        let state = app.get_mut(self);
2377        let scope_focus = state.scope_focus.take().expect("an initialized ComboBox");
2378        let focus = state.focus.take().expect("an initialized ComboBox");
2379        let text = state.text.take().expect("an initialized ComboBox");
2380        let text_focus = state.text_focus.take().expect("an initialized ComboBox");
2381        let popup = state.popup.take().expect("an initialized ComboBox");
2382        let scroll = state.scroll.take();
2383        let items: Vec<_> = state.item_focus.drain().map(|(_, node)| node).collect();
2384        focus.remove_listener(app, &Listener::handle_method(self, Self::box_focus_changed));
2385        text_focus.remove_listener(
2386            app,
2387            &Listener::handle_method(self, Self::text_focus_changed),
2388        );
2389        for node in [scope_focus, focus, text_focus].into_iter().chain(items) {
2390            node.dispose(app);
2391        }
2392        text.dispose(app);
2393        drop(popup);
2394        if let Some(scroll) = scroll {
2395            scroll.dispose(app);
2396        }
2397    }
2398
2399    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2400        self.settle_request(app);
2401        self.settle_drop_down_open(app);
2402        let widget = self.widget(app).clone();
2403        let resources = ThemeResources::of(app, context);
2404        let r = &resources;
2405        let (common, _, _) = self.visual_states(app);
2406        let mut cells = Vec::new();
2407        if let Some(header) = widget.header.clone() {
2408            // `HeaderContentPresenter`.
2409            let foreground = if common == CommonState::Disabled {
2410                r.combo_box_header_foreground_disabled
2411            } else {
2412                r.combo_box_header_foreground
2413            };
2414            cells.push(
2415                GridCell::new(Margin::new(
2416                    r.combo_box_top_header_margin,
2417                    DefaultTextStyle::new(
2418                        control_text_style(
2419                            &resources,
2420                            r.control_content_theme_font_size,
2421                            r.combo_box_header_theme_font_weight,
2422                            foreground,
2423                        )
2424                        .height(HEADER_LINE_HEIGHT / r.control_content_theme_font_size),
2425                        header,
2426                    ),
2427                ))
2428                .into_widget(),
2429            );
2430        }
2431        cells.push(
2432            GridCell::new(self.target_area(app, context))
2433                .row(1)
2434                .into_widget(),
2435        );
2436        // `LayoutRoot`.
2437        let layout_root = Grid::new()
2438            .row_definitions([
2439                RowDefinition::new(GridLength::AUTO),
2440                RowDefinition::new(GridLength::STAR),
2441            ])
2442            .children(cells);
2443        let root = Focus::new(layout_root)
2444            .focus_node(
2445                app.get(self)
2446                    .scope_focus
2447                    .as_ref()
2448                    .expect("an initialized ComboBox")
2449                    .erase(),
2450            )
2451            .can_request_focus(false)
2452            .skip_traversal(true)
2453            .on_key_event(Rc::new(move |app, _, event| self.on_key(app, event)))
2454            .on_focus_change(move |app, has_focus| self.scope_focus_changed(app, has_focus));
2455        // An editable box is one text field to the platform: pressing it or its drop-down leaves
2456        // the text box focused.
2457        TextFieldTapRegion::new(root)
2458            .enabled(widget.is_editable)
2459            .into_widget()
2460    }
2461}
2462
2463impl ComboBoxState {
2464    /// The part of the template that takes pointer input, which the source's `IsChildOfTarget`
2465    /// tells from the header: rows 1 and 2, with the box's own focus.
2466    fn target_area(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2467        let widget = self.widget(app).clone();
2468        let resources = ThemeResources::of(app, context);
2469        let r = &resources;
2470        let (common, focus, editable_state) = self.visual_states(app);
2471        let text_box_enabled = widget.is_editable && app.get(self).text_box_enabled;
2472        let focused = matches!(
2473            focus,
2474            ComboBoxFocusState::Focused | ComboBoxFocusState::FocusedPressed
2475        );
2476        let mut cells = Vec::new();
2477        // `HighlightBackground`, behind `Background`, 4 pixels around it.
2478        cells.push(
2479            GridCell::new(
2480                Opacity::new(if focused { 1.0 } else { 0.0 }).child(Margin::new(
2481                    HIGHLIGHT_BACKGROUND_MARGIN,
2482                    ControlBorder::new(
2483                        Brush::Solid(r.combo_box_background_focused),
2484                        Brush::Solid(r.combo_box_background_border_brush_focused),
2485                    )
2486                    .border_thickness_ltrb(r.combo_box_background_border_thickness_focused)
2487                    .corner_radius_corners(r.combo_box_higlight_border_corner_radius),
2488                )),
2489            )
2490            .column_span(2)
2491            .into_widget(),
2492        );
2493        // `Background`, where `Popup` opens from.
2494        let (background, border) = match common {
2495            CommonState::Normal => (
2496                Brush::Solid(r.combo_box_background),
2497                Brush::ControlElevation(r.combo_box_border_brush),
2498            ),
2499            CommonState::PointerOver => (
2500                Brush::Solid(r.combo_box_background_pointer_over),
2501                Brush::ControlElevation(r.combo_box_border_brush_pointer_over),
2502            ),
2503            CommonState::Pressed => (
2504                Brush::Solid(r.combo_box_background_pressed),
2505                Brush::Solid(r.combo_box_border_brush_pressed),
2506            ),
2507            CommonState::Disabled => (
2508                Brush::Solid(r.combo_box_background_disabled),
2509                Brush::Solid(r.combo_box_border_brush_disabled),
2510            ),
2511        };
2512        let background = KeyedSubtree::new(
2513            ConstrainedBox::new(BoxConstraints::new().min_width(r.combo_box_theme_min_width))
2514                .child(
2515                    ControlBorder::new(background, border)
2516                        .border_thickness_ltrb(r.combo_box_border_theme_thickness)
2517                        .corner_radius_corners(r.control_corner_radius),
2518                ),
2519        )
2520        .key(app.get(self).background_key.clone().into());
2521        let popup = OverlayPortal::overlay_child_layout_builder(
2522            app.get(self)
2523                .popup
2524                .clone()
2525                .expect("an initialized ComboBox"),
2526            move |app, context, info| self.popup_overlay(app, context, info),
2527        )
2528        .overlay_location(OverlayChildLocation::RootOverlay)
2529        .child(background);
2530        cells.push(GridCell::new(popup).column_span(2).into_widget());
2531        // `Pill`.
2532        cells.push(
2533            GridCell::new(Margin::new(
2534                PILL_MARGIN,
2535                Align::new()
2536                    .alignment(Alignment::CENTER_LEFT.into())
2537                    .width_factor(1.0)
2538                    .height_factor(1.0)
2539                    .child(
2540                        Opacity::new(if focused { 1.0 } else { 0.0 }).child(
2541                            SizedBox::new()
2542                                .width(r.combo_box_item_pill_width)
2543                                .height(r.combo_box_item_pill_height)
2544                                .child(
2545                                    ControlBorder::new(
2546                                        Brush::Solid(r.combo_box_item_pill_fill_brush),
2547                                        Brush::Solid(Color::new(0)),
2548                                    )
2549                                    .border_thickness(0.0)
2550                                    .corner_radius_corners(r.combo_box_item_pill_corner_radius),
2551                                ),
2552                        ),
2553                    ),
2554            ))
2555            .into_widget(),
2556        );
2557        // `ContentPresenter`, collapsed while the text box shows. Its cell stays, so that the
2558        // cells after it keep their elements and the text box its input connection.
2559        let content = if text_box_enabled {
2560            SizedBox::shrink().into_widget()
2561        } else {
2562            self.content_presenter(app, context, common, focus)
2563        };
2564        cells.push(GridCell::new(content).into_widget());
2565        if widget.is_editable {
2566            // `EditableText`, which has no size while the box shows `ContentPresenter`.
2567            cells.push(
2568                GridCell::new(
2569                    Offstage::new()
2570                        .offstage(!text_box_enabled)
2571                        .child(self.editable_text(app, context)),
2572                )
2573                .column_span(2)
2574                .into_widget(),
2575            );
2576            cells.push(
2577                GridCell::new(self.drop_down_overlay(
2578                    app,
2579                    context,
2580                    editable_state,
2581                    text_box_enabled,
2582                ))
2583                .column(1)
2584                .into_widget(),
2585            );
2586        }
2587        // `DropDownGlyph`, which takes no pointer input.
2588        let glyph = if common == CommonState::Disabled {
2589            r.combo_box_drop_down_glyph_foreground_disabled
2590        } else {
2591            match (focus, editable_state) {
2592                (ComboBoxFocusState::Focused, _) => r.combo_box_drop_down_glyph_foreground_focused,
2593                (ComboBoxFocusState::FocusedPressed, _) => {
2594                    r.combo_box_drop_down_glyph_foreground_focused_pressed
2595                }
2596                (
2597                    _,
2598                    Some(
2599                        EditableModeState::TextBoxFocused
2600                        | EditableModeState::TextBoxFocusedOverlayPointerOver
2601                        | EditableModeState::TextBoxFocusedOverlayPressed,
2602                    ),
2603                ) => r.combo_box_editable_drop_down_glyph_foreground,
2604                _ => r.combo_box_drop_down_glyph_foreground,
2605            }
2606        };
2607        cells.push(
2608            GridCell::new(
2609                IgnorePointer::new().child(
2610                    Align::new()
2611                        .alignment(Alignment::CENTER_RIGHT.into())
2612                        .width_factor(1.0)
2613                        .height_factor(1.0)
2614                        .child(Margin::new(
2615                            GLYPH_MARGIN,
2616                            SizedBox::new()
2617                                .width(GLYPH_SIZE)
2618                                .height(r.combo_box_min_height)
2619                                .child(
2620                                    Center::new().child(
2621                                        FontIcon::symbol(FluentSymbol::ChevronDown)
2622                                            .font_size(GLYPH_SIZE)
2623                                            .foreground(glyph),
2624                                    ),
2625                                ),
2626                        )),
2627                ),
2628            )
2629            .column(1)
2630            .into_widget(),
2631        );
2632        let row_grid = Grid::new()
2633            .column_definitions([
2634                ColumnDefinition::new(GridLength::STAR),
2635                ColumnDefinition::new(GridLength::pixel(GLYPH_COLUMN_WIDTH)),
2636            ])
2637            .children(cells);
2638        // Pressing the box opens it; with an editable box's text box shown, only presses on
2639        // `DropDownOverlay` reach the box, the rest being the text box's.
2640        let row = self.pointer_target(app, row_grid.into_widget(), !text_box_enabled);
2641        let mut rows = vec![GridCell::new(row).into_widget()];
2642        if let Some(description) = widget.description.clone() {
2643            // `DescriptionPresenter`.
2644            rows.push(
2645                GridCell::new(
2646                    self.pointer_target(
2647                        app,
2648                        DefaultTextStyle::new(
2649                            control_text_style(
2650                                &resources,
2651                                r.control_content_theme_font_size,
2652                                FontWeight::NORMAL,
2653                                r.system_control_description_text_foreground_brush,
2654                            ),
2655                            description,
2656                        )
2657                        .into_widget(),
2658                        true,
2659                    ),
2660                )
2661                .row(1)
2662                .into_widget(),
2663            );
2664        }
2665        let target = Grid::new()
2666            .row_definitions([
2667                RowDefinition::new(GridLength::STAR),
2668                RowDefinition::new(GridLength::AUTO),
2669            ])
2670            .children(rows);
2671        let target = MouseRegion::new()
2672            .on_enter(Rc::new(move |app, _| {
2673                // `OnPointerEntered`.
2674                self.set_state(app, |state| {
2675                    state.pointer_over_main = true;
2676                    state.pressed = false;
2677                })
2678            }))
2679            .on_exit(Rc::new(move |app, _| {
2680                // `OnPointerExited`.
2681                self.set_state(app, |state| {
2682                    state.pointer_over_main = false;
2683                    state.pressed = false;
2684                })
2685            }))
2686            .child(
2687                PointerListener::new()
2688                    .on_pointer_signal(Rc::new(move |app, event| self.pointer_signal(app, &event)))
2689                    .child(target),
2690            );
2691        Focus::new(target)
2692            .focus_node(
2693                app.get(self)
2694                    .focus
2695                    .as_ref()
2696                    .expect("an initialized ComboBox")
2697                    .erase(),
2698            )
2699            .can_request_focus(widget.is_enabled)
2700            // An editable box is reached by Tab in its text box.
2701            .skip_traversal(widget.is_editable || !widget.is_enabled)
2702            .into_widget()
2703    }
2704
2705    /// Takes the box's presses while `takes_presses` and the box is enabled: `OnPointerPressed`
2706    /// and `OnPointerReleased`. The widget stays the same either way, so that what it holds keeps
2707    /// its state.
2708    fn pointer_target(
2709        self: Handle<Self>,
2710        app: &App,
2711        child: WidgetRef,
2712        takes_presses: bool,
2713    ) -> WidgetRef {
2714        let gesture = GestureDetector::new()
2715            .behavior(HitTestBehavior::Opaque)
2716            .child(child);
2717        if !takes_presses || !self.widget(app).is_enabled {
2718            return gesture.into_widget();
2719        }
2720        gesture
2721            .on_tap_down(Rc::new(move |app, _| self.pointer_pressed(app)))
2722            .on_tap_up(Rc::new(move |app, details: waft_gestures::TapUpDetails| {
2723                let on_overlay = self.is_on_overlay(app, details.global_position);
2724                self.pointer_released(app, on_overlay);
2725            }))
2726            .on_tap_cancel(Listener::new(move |app| {
2727                self.set_state(app, |state| state.pressed = false)
2728            }))
2729            .into_widget()
2730    }
2731
2732    /// Whether `position` is on `DropDownOverlay`: `IsDropDownOverlay`.
2733    fn is_on_overlay(self: Handle<Self>, app: &mut App, position: Offset) -> bool {
2734        let Some(render) = app
2735            .get(self)
2736            .overlay_key
2737            .clone()
2738            .current_context(app)
2739            .and_then(|context| context.find_render_object(app))
2740            .and_then(|object| object.as_box())
2741        else {
2742            return false;
2743        };
2744        let origin = render.local_to_global(app, Offset::ZERO, None);
2745        let bounds = origin & render.size(app);
2746        bounds.contains(position)
2747    }
2748
2749    /// `ContentPresenter`: the selected item's content at `Padding`, or for an editable box's
2750    /// custom value its text, or `PlaceholderTextBlock`, hidden while the drop-down is open or an
2751    /// item is selected.
2752    fn content_presenter(
2753        self: Handle<Self>,
2754        app: &mut App,
2755        context: BuildContext,
2756        common: CommonState,
2757        focus: ComboBoxFocusState,
2758    ) -> WidgetRef {
2759        let widget = self.widget(app).clone();
2760        let r = ThemeResources::of(app, context);
2761        let foreground = match (focus, common) {
2762            (ComboBoxFocusState::Focused, _) => r.combo_box_foreground_focused,
2763            (ComboBoxFocusState::FocusedPressed, _) => r.combo_box_foreground_focused_pressed,
2764            (_, CommonState::Normal) => r.combo_box_foreground,
2765            (_, CommonState::PointerOver) => r.combo_box_foreground_pointer_over,
2766            (_, CommonState::Pressed) => r.combo_box_foreground_pressed,
2767            (_, CommonState::Disabled) => r.combo_box_foreground_disabled,
2768        };
2769        let placeholder = widget
2770            .placeholder_foreground
2771            .unwrap_or(match (focus, common) {
2772                (ComboBoxFocusState::Focused, _) => r.combo_box_place_holder_foreground_focused,
2773                (ComboBoxFocusState::FocusedPressed, _) => {
2774                    r.combo_box_place_holder_foreground_focused_pressed
2775                }
2776                (_, CommonState::Normal) => r.combo_box_place_holder_foreground,
2777                (_, CommonState::PointerOver) => r.combo_box_place_holder_foreground_pointer_over,
2778                (_, CommonState::Pressed) => r.combo_box_place_holder_foreground_pressed,
2779                (_, CommonState::Disabled) => r.combo_box_place_holder_foreground_disabled,
2780            });
2781        let open = app.get(self).open;
2782        let content = match self.selected(app) {
2783            Selection::Index(index) if !open => widget.items[index].content.clone(),
2784            Selection::Custom(text) if !open && widget.is_editable => {
2785                Text::new(text).soft_wrap(false).into_widget()
2786            }
2787            selected => {
2788                // `PlaceholderTextBlock`, the content `SetContentPresenter(-1)` puts back.
2789                let visible = !open && selected.index().is_none();
2790                Opacity::new(if visible { 1.0 } else { 0.0 })
2791                    .child(
2792                        Text::new(widget.placeholder_text.clone())
2793                            .style(control_text_style(
2794                                &r,
2795                                r.control_content_theme_font_size,
2796                                FontWeight::NORMAL,
2797                                placeholder,
2798                            ))
2799                            .soft_wrap(false),
2800                    )
2801                    .into_widget()
2802            }
2803        };
2804        let content = DefaultTextStyle::new(
2805            control_text_style(
2806                &r,
2807                r.control_content_theme_font_size,
2808                FontWeight::NORMAL,
2809                foreground,
2810            ),
2811            content,
2812        );
2813        // `HorizontalContentAlignment` is Stretch, and `VerticalContentAlignment` Center,
2814        // `Control`'s default: the content takes the row's width and its own height, centred.
2815        let aligned = Grid::new()
2816            .row_definitions([
2817                RowDefinition::new(GridLength::STAR),
2818                RowDefinition::new(GridLength::AUTO),
2819                RowDefinition::new(GridLength::STAR),
2820            ])
2821            .children([GridCell::new(content).row(1).into_widget()]);
2822        Margin::new(r.combo_box_padding, aligned).into_widget()
2823    }
2824
2825    /// `EditableText`: a TextBox in `ComboBoxTextBoxStyle` at `ComboBoxEditableTextPadding`, its
2826    /// border transparent until hovered or focused, with the corners next to an open drop-down
2827    /// square.
2828    fn editable_text(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2829        let widget = self.widget(app).clone();
2830        let r = ThemeResources::of(app, context);
2831        let mut config = TextBox::new(
2832            app.get(self)
2833                .text
2834                .as_ref()
2835                .expect("an initialized ComboBox")
2836                .erase(),
2837        )
2838        .focus_node(
2839            app.get(self)
2840                .text_focus
2841                .as_ref()
2842                .expect("an initialized ComboBox")
2843                .erase(),
2844        )
2845        .placeholder_text(widget.placeholder_text.clone())
2846        .is_enabled(widget.is_enabled)
2847        .padding(r.combo_box_editable_text_padding)
2848        .border_brush(Brush::Solid(Color::new(0)))
2849        .foreground(
2850            widget
2851                .placeholder_foreground
2852                .unwrap_or(r.combo_box_place_holder_foreground),
2853        )
2854        .text_changed(move |app, _| self.text_edited(app));
2855        if let Some(color) = widget.placeholder_foreground {
2856            config = config.placeholder_foreground(color);
2857        }
2858        let radius = r.control_corner_radius;
2859        let corner_radius = match (app.get(self).open, app.get(self).opened_up) {
2860            (false, _) => radius,
2861            (true, false) => [radius[0], radius[1], 0.0, 0.0],
2862            (true, true) => [0.0, 0.0, radius[2], radius[3]],
2863        };
2864        TextControl::new(config, None)
2865            .combo_box_style(ComboBoxTextBoxStyle { corner_radius })
2866            .into_widget()
2867    }
2868
2869    /// `DropDownOverlay`: the area over the glyph of an editable box, which opens and closes the
2870    /// drop-down and shows the pointer over it.
2871    fn drop_down_overlay(
2872        self: Handle<Self>,
2873        app: &mut App,
2874        context: BuildContext,
2875        state: Option<EditableModeState>,
2876        text_box_enabled: bool,
2877    ) -> WidgetRef {
2878        let r = ThemeResources::of(app, context);
2879        let background = match state {
2880            Some(
2881                EditableModeState::TextBoxFocusedOverlayPointerOver
2882                | EditableModeState::TextBoxOverlayPointerOver,
2883            ) => r.combo_box_drop_down_background_pointer_over,
2884            Some(EditableModeState::TextBoxFocusedOverlayPressed) => {
2885                r.combo_box_focused_drop_down_background_pointer_pressed
2886            }
2887            Some(EditableModeState::TextBoxOverlayPressed) => {
2888                r.combo_box_drop_down_background_pointer_pressed
2889            }
2890            _ => Color::new(0),
2891        };
2892        let overlay = MouseRegion::new()
2893            .on_enter(Rc::new(move |app, _| {
2894                self.set_state(app, |state| state.pointer_over_overlay = true)
2895            }))
2896            .on_exit(Rc::new(move |app, _| {
2897                self.set_state(app, |state| state.pointer_over_overlay = false)
2898            }))
2899            .child(
2900                KeyedSubtree::new(
2901                    ControlBorder::new(Brush::Solid(background), Brush::Solid(Color::new(0)))
2902                        .border_thickness(0.0)
2903                        .corner_radius_corners(
2904                            r.combo_box_drop_down_button_background_corner_radius,
2905                        ),
2906                )
2907                .key(app.get(self).overlay_key.clone().into()),
2908            );
2909        let overlay = self.pointer_target(app, overlay.into_widget(), text_box_enabled);
2910        // Right-aligned and stretched to the row, inside its margin; it adds nothing to the
2911        // row's size.
2912        let [left, top, right, bottom] = DROP_DOWN_OVERLAY_MARGIN;
2913        debug_assert!(left >= 0.0);
2914        Stack::new()
2915            .children([
2916                // What the stack sizes to: nothing of its own, the whole cell once arranged.
2917                SizedBox::shrink().into_widget(),
2918                Positioned::new(overlay)
2919                    .top(top)
2920                    .bottom(bottom)
2921                    .right(right)
2922                    .width(DROP_DOWN_OVERLAY_WIDTH)
2923                    .into_widget(),
2924            ])
2925            .into_widget()
2926    }
2927
2928    /// The child of `Popup` in the root overlay: the light-dismiss canvas over the window and
2929    /// `PopupBorder` where `ArrangePopup` puts it. A change of the window's size closes it, as
2930    /// `Popup`'s own light dismiss does.
2931    fn popup_overlay(
2932        self: Handle<Self>,
2933        app: &mut App,
2934        context: BuildContext,
2935        info: OverlayChildLayoutInfo,
2936    ) -> WidgetRef {
2937        let window = info.overlay_size();
2938        if app
2939            .get(self)
2940            .window_at_open
2941            .is_some_and(|at_open| at_open != window)
2942        {
2943            app.get_mut(self).window_at_open = None;
2944            self.after_frame(app, move |app| {
2945                if app.get(self).open {
2946                    self.put_is_drop_down_open(app, false);
2947                }
2948            });
2949        }
2950        let target = transform_rect(
2951            &info.child_paint_transform(),
2952            Offset::ZERO & info.child_size(),
2953        );
2954        let Some(arrangement) = self.arrangement(app, context, target, window) else {
2955            return SizedBox::shrink().into_widget();
2956        };
2957        if arrangement.opened_up != app.get(self).opened_up {
2958            // `ComboBoxHelper::UpdateCornerRadius`, after the drop-down opened.
2959            self.after_frame(app, move |app| {
2960                self.set_state(app, |state| state.opened_up = arrangement.opened_up)
2961            });
2962        }
2963        let barrier = PointerListener::new()
2964            .behavior(HitTestBehavior::Opaque)
2965            .on_pointer_down(Rc::new(move |app, event| {
2966                // `OnElementOutsidePopupPointerPressed`.
2967                if event.buttons & K_PRIMARY_BUTTON != 0 {
2968                    self.light_dismiss(app);
2969                }
2970            }))
2971            .child(SizedBox::expand());
2972        let presenter = self.popup_border(app, context, arrangement);
2973        let overlay = Stack::new()
2974            .fit(waft_rendering::StackFit::Expand)
2975            .children([
2976                barrier.into_widget(),
2977                CustomSingleChildLayout::new(Rc::new(PopupPosition {
2978                    arrangement,
2979                    laid_out_height: app.get(self).last_popup_height.clone(),
2980                }))
2981                .child(presenter)
2982                .into_widget(),
2983            ]);
2984        TextFieldTapRegion::new(overlay)
2985            .enabled(self.is_editable(app))
2986            .into_widget()
2987    }
2988
2989    /// `PopupBorder`: the lazy list of the items in `ScrollViewer`, inside the items' margin, on
2990    /// acrylic, with ElevationHelper's shadow.
2991    fn popup_border(
2992        self: Handle<Self>,
2993        app: &mut App,
2994        context: BuildContext,
2995        arrangement: Arrangement,
2996    ) -> WidgetRef {
2997        let resources = ThemeResources::of(app, context);
2998        let r = &resources;
2999        let Some(scroll) = app.get(self).scroll.clone() else {
3000            return SizedBox::shrink().into_widget();
3001        };
3002        let overlay = r.overlay_corner_radius;
3003        let corner_radius = if !self.is_editable(app) {
3004            overlay
3005        } else if arrangement.opened_up {
3006            [overlay[0], overlay[1], 0.0, 0.0]
3007        } else {
3008            [0.0, 0.0, overlay[2], overlay[3]]
3009        };
3010        let ids: Vec<String> = self
3011            .widget(app)
3012            .items
3013            .iter()
3014            .map(|item| item.id.clone())
3015            .collect();
3016        let list = ListView::builder(move |app, _, index| self.item_container(app, index as usize))
3017            .item_count(ids.len() as i32)
3018            .find_child_index_callback(Rc::new(move |key| {
3019                (key.key() as &dyn std::any::Any)
3020                    .downcast_ref::<ValueKey<String>>()
3021                    .and_then(|key| ids.iter().position(|id| *id == key.value))
3022                    .map(|index| index as i32)
3023            }))
3024            .build()
3025            .controller(scroll.native_controller(app))
3026            .shrink_wrap(true)
3027            .padding(EdgeInsetsGeometry::ZERO);
3028        // `ItemsPresenter`'s margin stays while the items scroll.
3029        let scroll_viewer = ScrollBarViewport::scroller(
3030            scroll,
3031            Padding::new(insets(r.combo_box_dropdown_content_margin)).child(list),
3032        );
3033        let border = ControlBorder::new(
3034            Brush::Acrylic(r.combo_box_drop_down_background),
3035            Brush::Solid(r.combo_box_drop_down_border_brush),
3036        )
3037        .border_thickness_ltrb(r.combo_box_dropdown_border_thickness)
3038        .corner_radius_corners(corner_radius)
3039        .background_sizing(BackgroundSizing::InnerBorderEdge)
3040        .padding(r.combo_box_dropdown_border_padding)
3041        .child(DefaultTextStyle::new(
3042            control_text_style(
3043                &resources,
3044                r.control_content_theme_font_size,
3045                FontWeight::NORMAL,
3046                r.combo_box_drop_down_foreground,
3047            ),
3048            scroll_viewer,
3049        ));
3050        MouseRegion::new()
3051            .on_enter(Rc::new(move |app, _| {
3052                // `OnElementPopupChildPointerEntered`.
3053                self.set_state(app, |state| state.pointer_over_popup = true)
3054            }))
3055            .on_exit(Rc::new(move |app, _| {
3056                self.set_state(app, |state| state.pointer_over_popup = false)
3057            }))
3058            .child(
3059                CustomPaint::new()
3060                    .painter(PopupShadow::for_anchored_popup(
3061                        resources.theme,
3062                        corner_radius,
3063                    ))
3064                    .child(border),
3065            )
3066            .into_widget()
3067    }
3068
3069    /// The container of the item at `index`, measured where the list lays it out.
3070    fn item_container(self: Handle<Self>, app: &mut App, index: usize) -> Option<WidgetRef> {
3071        let item = self.widget(app).items.get(index)?.clone();
3072        let id = item.id.clone();
3073        let focus_node = self.item_focus_node(app, &id);
3074        let shows_focus_visual = FocusState::current(app).shows_focus_visual();
3075        let state = app.get(self);
3076        let container = ComboBoxItemContainer {
3077            appears_selected: self.appears_selected(app, index),
3078            selection_active: state.selection_active,
3079            shows_focus_visual,
3080            focus_node,
3081            clicked: Rc::new(move |app, index| self.item_clicked(app, index)),
3082            focus_changed: Rc::new(move |app, index, focused| {
3083                self.item_focus_changed(app, index, focused)
3084            }),
3085            item,
3086            index,
3087        };
3088        let measured = id.clone();
3089        Some(
3090            KeyedSubtree::new(ItemProbe::new(
3091                container,
3092                Rc::new(move |app, size| self.item_measured(app, &measured, size)),
3093            ))
3094            .key(ValueKey::new(id).into())
3095            .into_widget(),
3096        )
3097    }
3098}
3099
3100/// The keyboard modifiers `Input_GetKeyboardModifiers` reports.
3101#[derive(Clone, Copy, Debug)]
3102struct Modifiers {
3103    alt: bool,
3104    control: bool,
3105    shift: bool,
3106    meta: bool,
3107}
3108
3109impl Modifiers {
3110    fn of(app: &mut App) -> Modifiers {
3111        let keyboard = HardwareKeyboard::instance(app);
3112        Modifiers {
3113            alt: keyboard.is_alt_pressed(app),
3114            control: keyboard.is_control_pressed(app),
3115            shift: keyboard.is_shift_pressed(app),
3116            meta: keyboard.is_meta_pressed(app),
3117        }
3118    }
3119
3120    /// `VirtualKeyModifiers_None`.
3121    fn none(self) -> bool {
3122        !(self.alt || self.control || self.shift || self.meta)
3123    }
3124}
3125
3126/// Keys the box handles that WinUI's TextBox takes first, so that they never reach an editable
3127/// box's key handling while its text box has the focus. `CTextBoxBase::OnKeyDown` passes on Page
3128/// Up and Page Down when they move no caret, as in one line, and Backspace always.
3129fn is_text_box_key(key: LogicalKeyboardKey) -> bool {
3130    matches!(
3131        key,
3132        LogicalKeyboardKey::ARROW_LEFT
3133            | LogicalKeyboardKey::ARROW_RIGHT
3134            | LogicalKeyboardKey::HOME
3135            | LogicalKeyboardKey::END
3136            | LogicalKeyboardKey::DELETE
3137    )
3138}
3139
3140/// The size an item container takes for one line of `text`: its content's, `Padding`, and
3141/// `LayoutRoot`'s margin, at least `Pill`'s height.
3142fn text_item_size(app: &mut App, context: BuildContext, text: &str) -> Size {
3143    let r = ThemeResources::of(app, context);
3144    let fonts = PaintingBinding::instance(app).fonts(app);
3145    let mut painter = TextPainter::new();
3146    painter.set_text(Some(Rc::new(TextSpan::new().text(text.to_owned()).style(
3147        control_text_style(
3148            &r,
3149            r.control_content_theme_font_size,
3150            FontWeight::NORMAL,
3151            Color::new(0),
3152        ),
3153    ))));
3154    painter.set_text_direction(Some(Directionality::of(app, context)));
3155    painter.set_text_scaler(MediaQuery::text_scaler_of(app, context));
3156    painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
3157    let size = Size::new(painter.width(), painter.height());
3158    painter.dispose();
3159    let padding = r.combo_box_item_theme_padding;
3160    Size::new(
3161        size.width() + padding[0] + padding[2] + ITEM_MARGIN[0] + ITEM_MARGIN[2],
3162        (size.height() + padding[1] + padding[3]).max(r.combo_box_item_pill_height)
3163            + ITEM_MARGIN[1]
3164            + ITEM_MARGIN[3],
3165    )
3166}
3167
3168/// Converts XAML thickness order into padding.
3169fn insets(value: [f64; 4]) -> EdgeInsetsGeometry {
3170    EdgeInsetsGeometry::from_ltrb(value[0], value[1], value[2], value[3])
3171}
3172
3173#[cfg(test)]
3174mod tests {
3175    use super::*;
3176
3177    #[test]
3178    fn the_selection_changed_arguments_name_the_new_selection() {
3179        let args = ComboBoxSelectionChangedEventArgs {
3180            removed_item: Some(ComboBoxSelectedItem::CustomValue("13".to_owned())),
3181            added_item: Some(ComboBoxSelectedItem::Item {
3182                index: 2,
3183                id: "b".to_owned(),
3184            }),
3185        };
3186        assert_eq!(args.selected_index(), Some(2));
3187        assert_eq!(args.custom_value(), None);
3188    }
3189
3190    #[test]
3191    fn a_widget_passes_an_index_before_a_custom_value() {
3192        let widget =
3193            ComboBox::new(vec![ComboBoxItem::text("a", "A")], Some(0), |_, _| {}).custom_value("x");
3194        assert_eq!(Selection::of(&widget), Selection::Index(0));
3195        let widget = ComboBox::new(Vec::new(), None, |_, _| {}).custom_value("x");
3196        assert_eq!(Selection::of(&widget), Selection::Custom("x".to_owned()));
3197    }
3198}