Skip to main content

waft_winui/controls/command_bar/
mod.rs

1//! XAML `CommandBar` with the `DefaultCommandBarStyle` of `CommandBar_themeresources.xaml`, and `CommandBar_Partial.cpp` over `AppBar_Partial.cpp`: a bar of primary commands, an overflow menu of secondary commands behind the `MoreButton`, and the primary commands that do not fit moved into that menu.
2//!
3//! The template is `LayoutRoot` (see [`layout_root`]) over `ContentRoot` (see [`content_root`]) and `OverflowPopup` (see [`overflow`]). The bar is closed or open, as its owner says, and `DisplayModeStates` animates between them; `Opening` and `Closing` are raised when the owner's value changes, `Opened` and `Closed` when the transition ends. While it is not closed the bar is drawn in the root overlay over the light-dismiss layer, as WinUI draws it through a layout transition element, and its place in the layout keeps its closed size. A later editor must keep the bar subtree under its global key in both places, so its focus and pointer state follow it in and out of the overlay.
4
5mod app_bar_button;
6mod app_bar_separator;
7mod app_bar_toggle_button;
8mod content_root;
9mod dynamic_overflow;
10mod element;
11mod keyboard;
12mod layout_root;
13mod overflow;
14
15pub use app_bar_button::AppBarButton;
16pub use app_bar_separator::AppBarSeparator;
17pub use app_bar_toggle_button::{
18    AppBarToggleButton, AppBarToggleButtonCheckedHandler, AppBarToggleButtonState,
19};
20pub use element::{CommandBarDefaultLabelPosition, CommandBarElement, CommandBarLabelPosition};
21
22use content_root::{ContentRoot, ContentRootLayout, MoreButtonVisibility};
23use dynamic_overflow::{DynamicOverflow, OverflowEntry, PrimaryCommand};
24use element::{ElementHost, ElementPresentation};
25use layout_root::{AppBarLayout, AppBarLayoutRoot, AppBarMetrics, DisplayModeMotion};
26use overflow::{CommandBarOverlayLayout, OverflowReveal, part};
27
28use crate::controls::flyout::shadow::PopupShadow;
29use crate::{
30    Brush, CommonState, ControlBorder, ControlStates, FluentSymbol, FocusState, FocusVisual,
31    FontIcon, InputDevice, LightDismissOverlayMode, Margin, ScrollBarViewport,
32    ScrollViewportController, TextBlockStyle, ThemeResources, ToolTip, ToolTipService,
33};
34use std::cell::RefCell;
35use std::collections::HashMap;
36use std::fmt;
37use std::rc::Rc;
38use std::time::Duration;
39use waft_animation::{Cubic, Curve};
40use waft_embedder::{Color, Offset, TextDirection};
41use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
42use waft_painting::{PaintingBinding, TextPainter, TextSpan, transform_rect};
43use waft_rendering::{BoxConstraints, CrossAxisAlignment, HitTestBehavior, MainAxisSize};
44use waft_scheduler::{FrameCallback, Ticker};
45use waft_widgets::*;
46
47/// XAML `AppBarClosedDisplayMode`: how much of the bar shows while it is closed.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
49pub enum AppBarClosedDisplayMode {
50    /// The commands' icons, `AppBarThemeCompactHeight` tall.
51    #[default]
52    Compact,
53    /// A thin strip with the `MoreButton`, `AppBarThemeMinimalHeight` tall.
54    Minimal,
55    /// Nothing.
56    Hidden,
57}
58
59/// XAML `CommandBarOverflowButtonVisibility`.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
61pub enum CommandBarOverflowButtonVisibility {
62    /// Shown when there is something to open: overflow commands, hidden labels or a bar that is not compact.
63    #[default]
64    Auto,
65    Visible,
66    Collapsed,
67}
68
69/// XAML `CommandBarDynamicOverflowAction`.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub enum CommandBarDynamicOverflowAction {
72    AddingToOverflow,
73    RemovingFromOverflow,
74}
75
76/// XAML `DynamicOverflowItemsChangingEventArgs`.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub struct DynamicOverflowItemsChangingEventArgs {
79    /// `Action`: whether primary commands are moving into the overflow or out of it.
80    pub action: CommandBarDynamicOverflowAction,
81}
82
83/// Receives XAML `DynamicOverflowItemsChanging`.
84pub type DynamicOverflowItemsChangingHandler =
85    Rc<dyn Fn(&mut App, &DynamicOverflowItemsChangingEventArgs)>;
86
87/// Receives the `IsOpen` value the bar asks for.
88pub type CommandBarOpenChangedHandler = Rc<dyn Fn(&mut App, bool)>;
89
90/// `DisplayModeStates` as the bar moves between its closed and open states.
91#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
92pub(crate) enum CommandBarDisplayPhase {
93    #[default]
94    Closed,
95    /// The `VisualTransition` into an open state.
96    Opening,
97    Open,
98    /// The `VisualTransition` into the closed state.
99    Closing,
100}
101
102/// XAML `CommandBar`.
103#[derive(Clone)]
104pub struct CommandBar {
105    /// `IsOpen`.
106    pub is_open: bool,
107    /// Asked for a new `IsOpen` by the `MoreButton`, a command, light dismiss and the keyboard; the bar opens and closes as `is_open` follows.
108    pub changed: CommandBarOpenChangedHandler,
109    /// `PrimaryCommands`: the commands in the bar.
110    pub primary_commands: Vec<CommandBarElement>,
111    /// `SecondaryCommands`: the commands in the overflow menu.
112    pub secondary_commands: Vec<CommandBarElement>,
113    /// `Content`: shown at the bar's start.
114    pub content: Option<WidgetRef>,
115    /// `DefaultLabelPosition`.
116    pub default_label_position: CommandBarDefaultLabelPosition,
117    /// `OverflowButtonVisibility`.
118    pub overflow_button_visibility: CommandBarOverflowButtonVisibility,
119    /// `IsDynamicOverflowEnabled`: primary commands that do not fit move into the overflow.
120    pub is_dynamic_overflow_enabled: bool,
121    /// `ClosedDisplayMode`.
122    pub closed_display_mode: AppBarClosedDisplayMode,
123    /// `IsSticky`: the open bar keeps the focus where it is and ignores light dismiss.
124    pub is_sticky: bool,
125    /// `LightDismissOverlayMode`: whether the layer under the open bar dims the window.
126    pub light_dismiss_overlay_mode: LightDismissOverlayMode,
127    /// `Background`, while the bar is closed; the theme's `CommandBarBackground` when `None`.
128    pub background: Option<Brush>,
129    /// `Opening`.
130    pub opening: Option<Listener>,
131    /// `Opened`.
132    pub opened: Option<Listener>,
133    /// `Closing`.
134    pub closing: Option<Listener>,
135    /// `Closed`.
136    pub closed: Option<Listener>,
137    /// `DynamicOverflowItemsChanging`.
138    pub dynamic_overflow_items_changing: Option<DynamicOverflowItemsChangingHandler>,
139    /// Identity retained across parent rebuilds.
140    pub key: Option<KeyRef>,
141}
142
143impl CommandBar {
144    /// Creates a bar with its `IsOpen` and the callback asked for a new one.
145    pub fn new(is_open: bool, changed: impl Fn(&mut App, bool) + 'static) -> Self {
146        Self {
147            is_open,
148            changed: Rc::new(changed),
149            primary_commands: Vec::new(),
150            secondary_commands: Vec::new(),
151            content: None,
152            default_label_position: CommandBarDefaultLabelPosition::Bottom,
153            overflow_button_visibility: CommandBarOverflowButtonVisibility::Auto,
154            is_dynamic_overflow_enabled: true,
155            closed_display_mode: AppBarClosedDisplayMode::Compact,
156            is_sticky: false,
157            light_dismiss_overlay_mode: LightDismissOverlayMode::Auto,
158            background: None,
159            opening: None,
160            opened: None,
161            closing: None,
162            closed: None,
163            dynamic_overflow_items_changing: None,
164            key: None,
165        }
166    }
167
168    /// Sets the XAML `PrimaryCommands`.
169    pub fn primary_commands(mut self, commands: Vec<CommandBarElement>) -> Self {
170        self.primary_commands = commands;
171        self
172    }
173
174    /// Sets the XAML `SecondaryCommands`.
175    pub fn secondary_commands(mut self, commands: Vec<CommandBarElement>) -> Self {
176        self.secondary_commands = commands;
177        self
178    }
179
180    /// Sets the XAML `Content`.
181    #[cfg_attr(debug_assertions, track_caller)]
182    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> Self {
183        self.content = Some(content.into_widget());
184        self
185    }
186
187    /// Sets the XAML `DefaultLabelPosition`.
188    pub fn default_label_position(mut self, position: CommandBarDefaultLabelPosition) -> Self {
189        self.default_label_position = position;
190        self
191    }
192
193    /// Sets the XAML `OverflowButtonVisibility`.
194    pub fn overflow_button_visibility(
195        mut self,
196        visibility: CommandBarOverflowButtonVisibility,
197    ) -> Self {
198        self.overflow_button_visibility = visibility;
199        self
200    }
201
202    /// Sets the XAML `IsDynamicOverflowEnabled`.
203    pub fn is_dynamic_overflow_enabled(mut self, value: bool) -> Self {
204        self.is_dynamic_overflow_enabled = value;
205        self
206    }
207
208    /// Sets the XAML `ClosedDisplayMode`.
209    pub fn closed_display_mode(mut self, mode: AppBarClosedDisplayMode) -> Self {
210        self.closed_display_mode = mode;
211        self
212    }
213
214    /// Sets the XAML `IsSticky`.
215    pub fn is_sticky(mut self, value: bool) -> Self {
216        self.is_sticky = value;
217        self
218    }
219
220    /// Sets the XAML `LightDismissOverlayMode`.
221    pub fn light_dismiss_overlay_mode(mut self, mode: LightDismissOverlayMode) -> Self {
222        self.light_dismiss_overlay_mode = mode;
223        self
224    }
225
226    /// Sets the XAML `Background`.
227    pub fn background(mut self, brush: Brush) -> Self {
228        self.background = Some(brush);
229        self
230    }
231
232    /// Sets the XAML `Opening` handler.
233    pub fn opening(mut self, listener: Listener) -> Self {
234        self.opening = Some(listener);
235        self
236    }
237
238    /// Sets the XAML `Opened` handler.
239    pub fn opened(mut self, listener: Listener) -> Self {
240        self.opened = Some(listener);
241        self
242    }
243
244    /// Sets the XAML `Closing` handler.
245    pub fn closing(mut self, listener: Listener) -> Self {
246        self.closing = Some(listener);
247        self
248    }
249
250    /// Sets the XAML `Closed` handler.
251    pub fn closed(mut self, listener: Listener) -> Self {
252        self.closed = Some(listener);
253        self
254    }
255
256    /// Sets the XAML `DynamicOverflowItemsChanging` handler.
257    pub fn dynamic_overflow_items_changing(
258        mut self,
259        handler: impl Fn(&mut App, &DynamicOverflowItemsChangingEventArgs) + 'static,
260    ) -> Self {
261        self.dynamic_overflow_items_changing = Some(Rc::new(handler));
262        self
263    }
264
265    /// Sets the identity retained across rebuilds.
266    pub fn key(mut self, key: KeyRef) -> Self {
267        self.key = Some(key);
268        self
269    }
270
271    /// What the dynamic overflow model knows of the commands.
272    fn overflow_commands(&self) -> (Vec<PrimaryCommand>, usize) {
273        let primary = self
274            .primary_commands
275            .iter()
276            .map(|command| PrimaryCommand {
277                is_separator: command.is_separator(),
278                order: command.dynamic_overflow_order(),
279            })
280            .collect();
281        (primary, self.secondary_commands.len())
282    }
283
284    /// What the bar compares between builds to tell whether its commands changed.
285    fn signature(&self) -> CommandsSignature {
286        let of = |commands: &[CommandBarElement]| {
287            commands.iter().map(CommandBarElement::signature).collect()
288        };
289        (of(&self.primary_commands), of(&self.secondary_commands))
290    }
291}
292
293type CommandsSignature = (
294    Vec<(u8, Option<String>, i32)>,
295    Vec<(u8, Option<String>, i32)>,
296);
297
298impl fmt::Debug for CommandBar {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.debug_struct("CommandBar")
301            .field("is_open", &self.is_open)
302            .field("primary_commands", &self.primary_commands)
303            .field("secondary_commands", &self.secondary_commands)
304            .field("default_label_position", &self.default_label_position)
305            .field("closed_display_mode", &self.closed_display_mode)
306            .field("is_sticky", &self.is_sticky)
307            .finish_non_exhaustive()
308    }
309}
310
311/// The transitions' `ControlNormalAnimationDuration`, `ControlFastAnimationDuration` and `ControlFastOutSlowInKeySpline`, as the last build read them.
312#[derive(Clone, Copy, Debug, Default)]
313struct TransitionTiming {
314    normal: Duration,
315    fast: Duration,
316    key_spline: [f64; 4],
317}
318
319/// `OverflowInitialFocusItem`: which overflow item an arrow key that opened the bar focuses.
320#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
321enum OverflowInitialFocusItem {
322    #[default]
323    None,
324    FirstItem,
325    LastItem,
326}
327
328impl StatefulWidget for CommandBar {
329    type State = CommandBarState;
330
331    fn key(&self) -> Option<&KeyRef> {
332        self.key.as_ref()
333    }
334
335    fn create_state(&self) -> CommandBarState {
336        let (primary, secondary) = self.overflow_commands();
337        CommandBarState {
338            state: StateData::new(),
339            single_ticker_provider: Default::default(),
340            ticker: None,
341            phase: CommandBarDisplayPhase::Closed,
342            elapsed: Duration::ZERO,
343            timing: TransitionTiming::default(),
344            overflow: Rc::new(RefCell::new(DynamicOverflow::new(primary, secondary))),
345            signature: self.signature(),
346            metrics: Rc::new(AppBarMetrics::default()),
347            portal: None,
348            bar_key: GlobalKey::new(),
349            content_focus: None,
350            primary_focus: Vec::new(),
351            overflow_focus: HashMap::new(),
352            more_focus: None,
353            overflow_scroll: None,
354            opened_with_expand_button: false,
355            overflow_initial_focus_item: OverflowInitialFocusItem::None,
356            saved_focus: None,
357            input_device_used_to_open: InputDevice::Touch,
358            layout_change_queued: false,
359        }
360    }
361}
362
363/// The bar's view of its owner's `IsOpen`, its transition, the dynamic overflow, its overlay and its focus.
364pub struct CommandBarState {
365    state: StateData<CommandBar>,
366    single_ticker_provider: SingleTickerProviderStateMixinData,
367    /// Clock of the `DisplayModeStates` transition.
368    ticker: Option<Ref<Ticker>>,
369    phase: CommandBarDisplayPhase,
370    /// Time since the transition began.
371    elapsed: Duration,
372    timing: TransitionTiming,
373    overflow: Rc<RefCell<DynamicOverflow>>,
374    /// The commands the model was last given.
375    signature: CommandsSignature,
376    metrics: Rc<AppBarMetrics>,
377    portal: Option<Ref<OverlayPortalController>>,
378    /// The bar subtree, in its place or in the overlay.
379    bar_key: GlobalKey,
380    /// Groups the `Content`'s focusable descendants.
381    content_focus: Option<FocusNodeRef>,
382    /// The bar's copies of the primary commands, by index.
383    primary_focus: Vec<FocusNodeRef>,
384    /// The overflow's copies of its entries.
385    overflow_focus: HashMap<OverflowEntry, FocusNodeRef>,
386    more_focus: Option<FocusNodeRef>,
387    overflow_scroll: Option<Ref<ScrollViewportController>>,
388    /// `m_openedWithExpandButton`.
389    opened_with_expand_button: bool,
390    /// `m_overflowInitialFocusItem`.
391    overflow_initial_focus_item: OverflowInitialFocusItem,
392    /// `m_savedFocusedElementWeakRef` and `m_savedFocusState`.
393    saved_focus: Option<(AnyFocusNode, FocusState)>,
394    /// `m_inputDeviceTypeUsedToOpen`.
395    input_device_used_to_open: InputDevice,
396    /// The rebuild after a layout that changed what the bar builds is waiting for the end of the frame.
397    layout_change_queued: bool,
398}
399
400impl SingleTickerProviderStateMixin for CommandBarState {
401    fn single_ticker_provider_data(
402        self: Handle<Self>,
403        app: &App,
404    ) -> &SingleTickerProviderStateMixinData {
405        &app.get(self).single_ticker_provider
406    }
407
408    fn single_ticker_provider_data_mut(
409        self: Handle<Self>,
410        app: &mut App,
411    ) -> &mut SingleTickerProviderStateMixinData {
412        &mut app.get_mut(self).single_ticker_provider
413    }
414}
415
416// MARK: Opening and closing
417
418impl CommandBarState {
419    fn alive(self: Handle<Self>, app: &App) -> bool {
420        app.contains(self) && self.mounted(app)
421    }
422
423    /// Runs `work` once the frame is over, if the bar is still mounted.
424    fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
425        let view = View::maybe_id_of(app, self.context(app));
426        crate::after_next_frame(
427            app,
428            view,
429            FrameCallback::new(move |app, _| {
430                if self.alive(app) {
431                    work(app);
432                }
433            }),
434        );
435    }
436
437    /// Asks the owner for `is_open`.
438    pub(crate) fn request_open(self: Handle<Self>, app: &mut App, is_open: bool) {
439        let changed = self.widget(app).changed.clone();
440        changed(app, is_open);
441    }
442
443    fn raise(app: &mut App, listener: Option<Listener>) {
444        if let Some(listener) = listener {
445            listener.call(app);
446        }
447    }
448
449    /// The transition's length: `ControlNormalAnimationDuration` opening, `ControlFastAnimationDuration` closing.
450    fn transition_duration(self: Handle<Self>, app: &App) -> Duration {
451        let timing = app.get(self).timing;
452        match app.get(self).phase {
453            CommandBarDisplayPhase::Closing => timing.fast,
454            _ => timing.normal,
455        }
456    }
457
458    /// The transition's progress through `ControlFastOutSlowInKeySpline`.
459    fn motion(self: Handle<Self>, app: &mut App) -> DisplayModeMotion {
460        let phase = app.get(self).phase;
461        let progress = match phase {
462            CommandBarDisplayPhase::Opening | CommandBarDisplayPhase::Closing => {
463                let [x1, y1, x2, y2] = app.get(self).timing.key_spline;
464                let duration = self.transition_duration(app).as_secs_f64();
465                let t = (app.get(self).elapsed.as_secs_f64() / duration).clamp(0.0, 1.0);
466                Cubic::new(x1, y1, x2, y2).transform(t)
467            }
468            CommandBarDisplayPhase::Open | CommandBarDisplayPhase::Closed => 1.0,
469        };
470        DisplayModeMotion { phase, progress }
471    }
472
473    fn start_transition(self: Handle<Self>, app: &mut App, phase: CommandBarDisplayPhase) {
474        let ticker = app.get(self).ticker.clone().expect("made in `init_state`");
475        ticker.stop(app, false);
476        app.get_mut(self).phase = phase;
477        app.get_mut(self).elapsed = Duration::ZERO;
478        ticker.start(app);
479    }
480
481    /// The transition's frame; at its end `OnDisplayModesStateChanged` raises `Opened` or `Closed`.
482    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
483        let finished = elapsed >= self.transition_duration(app);
484        self.set_state(app, |state| state.elapsed = elapsed);
485        if !finished {
486            return;
487        }
488        app.get(self).ticker.handle().unwrap().stop(app, false);
489        match app.get(self).phase {
490            CommandBarDisplayPhase::Opening => {
491                self.set_state(app, |state| state.phase = CommandBarDisplayPhase::Open);
492                Self::raise(app, self.widget(app).opened.clone());
493            }
494            CommandBarDisplayPhase::Closing => {
495                // `OnClosedImpl`: the bar compacts, the popup and the overlay go, then `Closed`.
496                self.set_state(app, |state| state.phase = CommandBarDisplayPhase::Closed);
497                Self::raise(app, self.widget(app).closed.clone());
498            }
499            _ => {}
500        }
501    }
502
503    /// `OnIsOpenChanged(true)`: the transition starts now; `Opening` and the focus wait for the bar to be in the overlay.
504    fn begin_opening(self: Handle<Self>, app: &mut App, animated: bool) {
505        // `UpdateInputDeviceTypeUsedToOpen`.
506        app.get_mut(self).input_device_used_to_open = InputDevice::current(app);
507        if animated {
508            self.start_transition(app, CommandBarDisplayPhase::Opening);
509        } else {
510            app.get_mut(self).phase = CommandBarDisplayPhase::Open;
511        }
512        self.after_frame(app, move |app| self.on_opening(app));
513    }
514
515    /// `AppBar::OnOpeningImpl` and `CommandBar::OnOpeningImpl`, once the overlay holds the bar.
516    fn on_opening(self: Handle<Self>, app: &mut App) {
517        if let Some(portal) = app.get(self).portal.clone() {
518            // The overlay comes in front of what opened since the bar mounted.
519            portal.show(app);
520        }
521        if !self.widget(app).is_sticky {
522            self.set_focus_on_app_bar(app);
523        }
524        Self::raise(app, self.widget(app).opening.clone());
525        if app.get(self).opened_with_expand_button {
526            // The first overflow item, focused as the expand button was used.
527            let state = FocusState::coerce_programmatic(app);
528            if let Some(first) = self.overflow_focusables(app).first().copied() {
529                Self::focus(app, first, state);
530            }
531        }
532        // `OnSecondaryItemsControlLoaded`.
533        let initial = std::mem::take(&mut app.get_mut(self).overflow_initial_focus_item);
534        if initial != OverflowInitialFocusItem::None {
535            self.set_focused_element_in_overflow(
536                app,
537                initial == OverflowInitialFocusItem::FirstItem,
538            );
539        }
540    }
541
542    /// `OnIsOpenChanged(false)`.
543    fn begin_closing(self: Handle<Self>, app: &mut App) {
544        self.start_transition(app, CommandBarDisplayPhase::Closing);
545        self.after_frame(app, move |app| self.on_closing(app));
546    }
547
548    /// `AppBar::OnClosingImpl` and `CommandBar::OnClosingImpl`.
549    fn on_closing(self: Handle<Self>, app: &mut App) {
550        app.get_mut(self).opened_with_expand_button = false;
551        self.restore_saved_focus(app);
552        // `CloseSubMenus`.
553        let widget = self.widget(app).clone();
554        for command in widget
555            .primary_commands
556            .iter()
557            .chain(&widget.secondary_commands)
558        {
559            if let CommandBarElement::Button(button) = command
560                && let Some(flyout) = &button.flyout
561                && flyout.is_open(app)
562            {
563                flyout.hide(app);
564            }
565        }
566        Self::raise(app, widget.closing);
567    }
568
569    /// `OnExpandButtonClick`.
570    fn on_expand_button_click(self: Handle<Self>, app: &mut App) {
571        let is_open = self.widget(app).is_open;
572        if !is_open {
573            app.get_mut(self).opened_with_expand_button = true;
574        }
575        self.request_open(app, !is_open);
576    }
577
578    /// `CommandBar::OnCommandExecutionStatic`: a command closes its bar.
579    fn on_command_execution(self: Handle<Self>, app: &mut App) {
580        if self.alive(app) && self.widget(app).is_open {
581            self.request_open(app, false);
582        }
583    }
584
585    /// `TryDismissInlineAppBar`: closes the bar unless it is sticky. Answers whether it did.
586    fn try_dismiss_inline_app_bar(self: Handle<Self>, app: &mut App) -> bool {
587        let widget = self.widget(app);
588        if widget.is_sticky || !widget.is_open {
589            return false;
590        }
591        self.request_open(app, false);
592        true
593    }
594
595    /// `OnPointerPressed` of a closed minimal bar: a press opens it.
596    fn on_bar_pointer_down(self: Handle<Self>, app: &mut App, position: Offset) {
597        let widget = self.widget(app);
598        if widget.is_open || widget.closed_display_mode != AppBarClosedDisplayMode::Minimal {
599            return;
600        }
601        if app
602            .get(self)
603            .metrics
604            .more_button
605            .get()
606            .is_some_and(|rect| rect.contains(position))
607        {
608            return;
609        }
610        self.request_open(app, true);
611    }
612}
613
614// MARK: Dynamic overflow
615
616impl CommandBarState {
617    /// `OnPrimaryCommandsChanged` and `OnSecondaryCommandsChanged`: commands that changed start over in the bar.
618    fn sync_commands(self: Handle<Self>, app: &mut App) {
619        let signature = self.widget(app).signature();
620        if signature == app.get(self).signature {
621            return;
622        }
623        let (primary, secondary) = self.widget(app).overflow_commands();
624        app.get(self)
625            .overflow
626            .borrow_mut()
627            .set_commands(primary, secondary);
628        app.get_mut(self).signature = signature;
629    }
630
631    /// The layout moved commands, raised `DynamicOverflowItemsChanging` or changed the heights the `MoreButton` is shown by: the events go out and the bar rebuilds after the frame.
632    fn layout_changed(self: Handle<Self>, app: &mut App) {
633        if !self.alive(app) || app.get(self).layout_change_queued {
634            return;
635        }
636        app.get_mut(self).layout_change_queued = true;
637        self.after_frame(app, move |app| {
638            app.get_mut(self).layout_change_queued = false;
639            let raised = std::mem::take(&mut app.get(self).overflow.borrow_mut().raised);
640            if let Some(handler) = self.widget(app).dynamic_overflow_items_changing.clone() {
641                for action in raised {
642                    handler(app, &DynamicOverflowItemsChangingEventArgs { action });
643                }
644            }
645            self.set_state(app, |_| {});
646        });
647    }
648
649    /// `SetOverflowStyleParams` over the overflow's entries: whether any has an icon, is a toggle button, or has accelerator text.
650    fn overflow_style_params(self: Handle<Self>, app: &App) -> (bool, bool, bool) {
651        let widget = self.widget(app);
652        let overflow = app.get(self).overflow.borrow();
653        let mut params = (false, false, false);
654        for entry in &overflow.dynamic_secondary {
655            let Some(element) = Self::entry_element(widget, *entry) else {
656                continue;
657            };
658            params.0 |= element.has_icon();
659            params.1 |= matches!(element, CommandBarElement::ToggleButton(_));
660            params.2 |= !element.keyboard_accelerator_text().is_empty();
661        }
662        params
663    }
664
665    fn entry_element(widget: &CommandBar, entry: OverflowEntry) -> Option<&CommandBarElement> {
666        match entry {
667            OverflowEntry::Primary(index) => widget.primary_commands.get(index),
668            OverflowEntry::Secondary(index) => widget.secondary_commands.get(index),
669            OverflowEntry::Separator => None,
670        }
671    }
672
673    /// `UpdateTemplateSettings`' `KeyboardAcceleratorTextMinWidth`: the widest accelerator text in the overflow, in `CaptionTextBlockStyle`.
674    fn keyboard_accelerator_text_min_width(
675        self: Handle<Self>,
676        app: &mut App,
677        context: BuildContext,
678    ) -> f64 {
679        let r = ThemeResources::of(app, context);
680        let texts: Vec<String> = {
681            let widget = self.widget(app);
682            let overflow = app.get(self).overflow.borrow();
683            overflow
684                .dynamic_secondary
685                .iter()
686                .filter_map(|entry| Self::entry_element(widget, *entry))
687                .map(|element| element.keyboard_accelerator_text().to_string())
688                .filter(|text| !text.is_empty())
689                .collect()
690        };
691        let fonts = PaintingBinding::instance(app).fonts(app);
692        let direction = Directionality::of(app, context);
693        let scaler = MediaQuery::text_scaler_of(app, context);
694        let mut widest: f64 = 0.0;
695        for text in texts {
696            let mut painter = TextPainter::new();
697            painter.set_text(Some(Rc::new(
698                TextSpan::new().text(text).style(
699                    TextBlockStyle::Caption
700                        .text_style(&r, r.app_bar_button_keyboard_accelerator_text_foreground),
701                ),
702            )));
703            painter.set_text_direction(Some(direction));
704            painter.set_text_scaler(scaler.clone());
705            painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
706            widest = widest.max(painter.width());
707            painter.dispose();
708        }
709        widest
710    }
711}
712
713// MARK: Building
714
715/// What one build of the bar shares among its parts.
716#[derive(Clone, Copy)]
717struct BarBuild {
718    motion: DisplayModeMotion,
719    closed: bool,
720    /// `MinimalClosed`: the content and commands are transparent and take no input.
721    minimal_closed: bool,
722    /// `HiddenClosed` and `MinimalClosed`: the content and commands are disabled.
723    inert: bool,
724    /// The content's and commands' opacity in the minimal states.
725    minimal_opacity: f64,
726    /// The compact open states set `ContentRoot`'s open background, corner radius and `OpenBorder`.
727    open_chrome: bool,
728}
729
730impl CommandBarState {
731    fn bar_build(self: Handle<Self>, app: &mut App) -> BarBuild {
732        let motion = self.motion(app);
733        let mode = self.widget(app).closed_display_mode;
734        let closed = motion.phase == CommandBarDisplayPhase::Closed;
735        let minimal = mode == AppBarClosedDisplayMode::Minimal;
736        let minimal_opacity = if !minimal {
737            1.0
738        } else {
739            match motion.phase {
740                CommandBarDisplayPhase::Closed => 0.0,
741                CommandBarDisplayPhase::Opening => motion.progress,
742                CommandBarDisplayPhase::Open => 1.0,
743                CommandBarDisplayPhase::Closing => 1.0 - motion.progress,
744            }
745        };
746        BarBuild {
747            motion,
748            closed,
749            minimal_closed: minimal && closed,
750            inert: closed && mode != AppBarClosedDisplayMode::Compact,
751            minimal_opacity,
752            open_chrome: mode == AppBarClosedDisplayMode::Compact
753                && matches!(
754                    motion.phase,
755                    CommandBarDisplayPhase::Opening | CommandBarDisplayPhase::Open
756                ),
757        }
758    }
759
760    fn primary_node(self: Handle<Self>, app: &mut App, index: usize) -> FocusNodeRef {
761        while app.get(self).primary_focus.len() <= index {
762            let node: FocusNodeRef = FocusNode::new(app).into_erased();
763            app.get_mut(self).primary_focus.push(node);
764        }
765        app.get(self).primary_focus[index].clone()
766    }
767
768    fn overflow_node(self: Handle<Self>, app: &mut App, entry: OverflowEntry) -> FocusNodeRef {
769        if let Some(node) = app.get(self).overflow_focus.get(&entry) {
770            return node.clone();
771        }
772        let node: FocusNodeRef = FocusNode::new(app).into_erased();
773        app.get_mut(self).overflow_focus.insert(entry, node.clone());
774        node
775    }
776
777    fn host(self: Handle<Self>, focus_node: FocusNodeRef) -> ElementHost {
778        ElementHost {
779            executed: Listener::new(move |app| self.on_command_execution(app)),
780            focus_node,
781        }
782    }
783
784    /// `UpdateTemplateSettings`' `EffectiveOverflowButtonVisibility`, as far as a build knows it.
785    fn more_button_visibility(
786        self: Handle<Self>,
787        app: &mut App,
788        context: BuildContext,
789    ) -> MoreButtonVisibility {
790        let widget = self.widget(app).clone();
791        match widget.overflow_button_visibility {
792            CommandBarOverflowButtonVisibility::Visible => MoreButtonVisibility {
793                shown: true,
794                when_overflowing: false,
795            },
796            CommandBarOverflowButtonVisibility::Collapsed => MoreButtonVisibility {
797                shown: false,
798                when_overflowing: false,
799            },
800            CommandBarOverflowButtonVisibility::Auto => {
801                let metrics = app.get(self).metrics.clone();
802                // A delta that rounds to the same physical pixel does not count.
803                let scale = MediaQuery::maybe_device_pixel_ratio_of(app, context).unwrap_or(1.0);
804                let delta = metrics.compact_height.get() - metrics.content_height.get();
805                let has_bottom_label = {
806                    let overflow = app.get(self).overflow.borrow();
807                    overflow.dynamic_primary.iter().any(|index| {
808                        widget.primary_commands[*index].has_label_at(
809                            widget.default_label_position,
810                            CommandBarDefaultLabelPosition::Bottom,
811                        )
812                    })
813                };
814                let shown = !widget.secondary_commands.is_empty()
815                    || widget.closed_display_mode != AppBarClosedDisplayMode::Compact
816                    || (scale > 0.0 && delta.abs() >= 0.5 / scale)
817                    || has_bottom_label;
818                MoreButtonVisibility {
819                    shown,
820                    when_overflowing: true,
821                }
822            }
823        }
824    }
825
826    /// `HasRightLabelDynamicPrimaryCommand || HasNonLabeledDynamicPrimaryCommand`: every command is labelled, so only a right label counts.
827    fn grows_with_content(self: Handle<Self>, app: &App) -> bool {
828        let widget = self.widget(app);
829        let overflow = app.get(self).overflow.borrow();
830        overflow.dynamic_primary.iter().any(|index| {
831            widget.primary_commands[*index].has_label_at(
832                widget.default_label_position,
833                CommandBarDefaultLabelPosition::Right,
834            )
835        })
836    }
837
838    /// `LayoutRoot` > `ContentRoot`, in its place or in the overlay.
839    fn bar(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
840        let r = ThemeResources::of(app, context);
841        let widget = self.widget(app).clone();
842        let build = self.bar_build(app);
843        let more_button = self.more_button_visibility(app, context);
844        let overflowing = !app.get(self).overflow.borrow().dynamic_secondary.is_empty();
845        let more_button_shown = more_button.shown || (more_button.when_overflowing && overflowing);
846        let foreground = r.command_bar_foreground;
847
848        // ContentControl
849        let content_focus = app
850            .get(self)
851            .content_focus
852            .clone()
853            .expect("made in `init_state`");
854        let content = widget
855            .content
856            .clone()
857            .unwrap_or_else(|| SizedBox::shrink().into_widget());
858        let content = Margin::new(
859            // The style's `Padding`.
860            [4.0, 0.0, 0.0, 0.0],
861            Self::inert(
862                build,
863                Focus::new(DefaultTextStyle::new(
864                    crate::control_text_style(
865                        &r,
866                        r.control_content_theme_font_size,
867                        waft_embedder::FontWeight::NORMAL,
868                        foreground,
869                    ),
870                    content,
871                ))
872                .focus_node(content_focus)
873                .can_request_focus(false)
874                .skip_traversal(true)
875                .into_widget(),
876                false,
877            ),
878        );
879        let mut children = vec![content.into_widget()];
880
881        // PrimaryItemsControl
882        let presentation = ElementPresentation {
883            // `SetCompactMode`: compact until `Opening`, again from `Closed`.
884            is_compact: build.closed,
885            default_label_position: widget.default_label_position,
886            in_command_bar: true,
887            ..Default::default()
888        };
889        for (index, command) in widget.primary_commands.iter().enumerate() {
890            let node = self.primary_node(app, index);
891            let moved = app.get(self).overflow.borrow().is_moved(index)
892                || !app
893                    .get(self)
894                    .overflow
895                    .borrow()
896                    .dynamic_primary
897                    .contains(&index);
898            let hosted = command.hosted(presentation, self.host(node));
899            children.push(Self::inert(build, Self::element_widget(hosted), moved));
900        }
901
902        // MoreButton
903        children.push(self.more_button(app, context, &r, build, more_button_shown));
904
905        let panel = ContentRoot {
906            layout: ContentRootLayout {
907                dynamic_overflow_enabled: widget.is_dynamic_overflow_enabled,
908                more_button,
909                more_button_column_min_width: r.app_bar_more_button_column_min_width,
910                min_height: r.app_bar_theme_compact_height,
911                more_button_stretches: !build.closed,
912                rtl: Directionality::maybe_of(app, context) == Some(TextDirection::Rtl),
913            },
914            overflow: app.get(self).overflow.clone(),
915            metrics: app.get(self).metrics.clone(),
916            overflow_changed: Rc::new(move |app| self.layout_changed(app)),
917            children,
918        };
919        let background = if build.open_chrome {
920            Brush::Acrylic(r.command_bar_background_open)
921        } else {
922            widget
923                .background
924                .unwrap_or(Brush::Solid(r.command_bar_background))
925        };
926        let corner_radius = if build.open_chrome {
927            r.control_corner_radius
928        } else {
929            [0.0; 4]
930        };
931        let mut layers = vec![panel.into_widget()];
932        if build.open_chrome {
933            // OpenBorder
934            layers.push(
935                Positioned::fill(
936                    IgnorePointer::new().child(
937                        ControlBorder::new_optional(
938                            None,
939                            Some(Brush::Solid(r.command_bar_border_brush_open)),
940                        )
941                        .border_thickness_ltrb(r.command_bar_border_thickness_open)
942                        .corner_radius_corners(corner_radius),
943                    ),
944                )
945                .into_widget(),
946            );
947        }
948        let content_root =
949            ConstrainedBox::new(BoxConstraints::new().min_height(r.app_bar_theme_compact_height))
950                .child(
951                    ControlBorder::new_optional(Some(background), None)
952                        .border_thickness(0.0)
953                        .corner_radius_corners(corner_radius)
954                        .child(Stack::new().children(layers)),
955                );
956        let content_root = waft_widgets::Listener::new()
957            .behavior(HitTestBehavior::Translucent)
958            .on_pointer_down(Rc::new(move |app, event| {
959                self.on_bar_pointer_down(app, event.local_position())
960            }))
961            .child(content_root);
962        let layout_root = AppBarLayoutRoot {
963            layout: AppBarLayout {
964                closed_display_mode: widget.closed_display_mode,
965                is_open: widget.is_open,
966                grows_with_content: self.grows_with_content(app),
967                min_compact_height: r.app_bar_theme_compact_height,
968                minimal_height: r.app_bar_theme_minimal_height,
969                motion: build.motion,
970            },
971            metrics: app.get(self).metrics.clone(),
972            child: content_root.into_widget(),
973        };
974        KeyedSubtree::new(layout_root.into_widget())
975            .key(app.get(self).bar_key.clone().into())
976            .into_widget()
977    }
978
979    /// An element as a widget.
980    fn element_widget(element: CommandBarElement) -> WidgetRef {
981        match element {
982            CommandBarElement::Button(button) => button.into_widget(),
983            CommandBarElement::ToggleButton(button) => button.into_widget(),
984            CommandBarElement::Separator(separator) => separator.into_widget(),
985        }
986    }
987
988    /// The minimal and hidden closed states' `IsEnabled`, `IsHitTestVisible` and `Opacity` on the content and the commands; a command moved to the overflow is out of reach too.
989    fn inert(build: BarBuild, child: WidgetRef, moved: bool) -> WidgetRef {
990        let child = ExcludeFocus::new(child)
991            .excluding(build.inert || moved)
992            .into_widget();
993        let child = IgnorePointer::new()
994            .ignoring(build.minimal_closed || moved)
995            .child(child)
996            .into_widget();
997        if build.minimal_opacity < 1.0 {
998            Opacity::new(build.minimal_opacity)
999                .child(child)
1000                .into_widget()
1001        } else {
1002            child
1003        }
1004    }
1005
1006    /// `MoreButton` with the `EllipsisButton` style.
1007    fn more_button(
1008        self: Handle<Self>,
1009        app: &mut App,
1010        _context: BuildContext,
1011        r: &ThemeResources,
1012        build: BarBuild,
1013        shown: bool,
1014    ) -> WidgetRef {
1015        let widget = self.widget(app).clone();
1016        let minimal = widget.closed_display_mode == AppBarClosedDisplayMode::Minimal;
1017        let node = app
1018            .get(self)
1019            .more_focus
1020            .clone()
1021            .expect("made in `init_state`");
1022        let (glyph_size, circle) = (20.0, r.app_bar_expand_button_circle_diameter);
1023        // EllipsisIcon: the glyph centred on a line `AppBarExpandButtonCircleDiameter` tall.
1024        let icon = SizedBox::new().height(circle).child(
1025            OverflowBox::new()
1026                .max_height(f64::INFINITY)
1027                .child(FontIcon::symbol(FluentSymbol::More).font_size(glyph_size)),
1028        );
1029        let foreground = r.command_bar_foreground;
1030        let button = crate::Button::new(
1031            icon,
1032            Listener::new(move |app| self.on_expand_button_click(app)),
1033        )
1034        .focus_node(node)
1035        // `HiddenClosed` takes the button out of tab navigation.
1036        .is_tab_stop(
1037            !(build.closed && widget.closed_display_mode == AppBarClosedDisplayMode::Hidden),
1038        )
1039        .template(move |app, context, states, content| {
1040            ellipsis_button_template(app, context, states, content, foreground)
1041        });
1042        let tool_tip = if widget.is_open {
1043            "See less"
1044        } else {
1045            "See more"
1046        };
1047        let min_height = if minimal {
1048            r.app_bar_theme_minimal_height
1049        } else {
1050            r.app_bar_theme_compact_height
1051        };
1052        let button = SizedBox::new()
1053            .width(r.app_bar_expand_button_theme_width)
1054            .child(
1055                ConstrainedBox::new(BoxConstraints::new().min_height(min_height))
1056                    .child(ToolTipService::new(button, ToolTip::text(tool_tip))),
1057            );
1058        ExcludeFocus::new(button).excluding(!shown).into_widget()
1059    }
1060
1061    /// The overflow menu's items: the moved primary commands, the separator, the secondary commands.
1062    fn overflow_items(self: Handle<Self>, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
1063        let widget = self.widget(app).clone();
1064        let (with_icons, with_toggle_buttons, with_keyboard_accelerator_text) =
1065            self.overflow_style_params(app);
1066        let input_mode = if app.get(self).input_device_used_to_open == InputDevice::Touch {
1067            InputDevice::Touch
1068        } else {
1069            InputDevice::None
1070        };
1071        let presentation = ElementPresentation {
1072            use_overflow_style: true,
1073            default_label_position: widget.default_label_position,
1074            with_icons,
1075            with_toggle_buttons,
1076            with_keyboard_accelerator_text,
1077            input_mode,
1078            keyboard_accelerator_text_min_width: self
1079                .keyboard_accelerator_text_min_width(app, context),
1080            in_command_bar: true,
1081            ..Default::default()
1082        };
1083        let entries = app.get(self).overflow.borrow().dynamic_secondary.clone();
1084        entries
1085            .into_iter()
1086            .map(|entry| match Self::entry_element(&widget, entry).cloned() {
1087                Some(element) => {
1088                    let node = self.overflow_node(app, entry);
1089                    Self::element_widget(element.hosted(presentation, self.host(node)))
1090                }
1091                None => AppBarSeparator {
1092                    presentation,
1093                    ..AppBarSeparator::default()
1094                }
1095                .into_widget(),
1096            })
1097            .collect()
1098    }
1099
1100    /// `OverflowContentRoot` > `SecondaryItemsControlShadowWrapper` > `CommandBarOverflowPresenter`.
1101    fn overflow_presenter(
1102        self: Handle<Self>,
1103        app: &mut App,
1104        context: BuildContext,
1105        full_width: bool,
1106    ) -> WidgetRef {
1107        let r = ThemeResources::of(app, context);
1108        let items = self.overflow_items(app, context);
1109        let opens_up = app.get(self).metrics.opens_up.get();
1110        // `DisplayModeStates` of the presenter.
1111        let (thickness, padding) = match (full_width, opens_up) {
1112            (false, _) => (
1113                r.command_bar_overflow_presenter_border_thickness,
1114                r.command_bar_overflow_presenter_border_padding,
1115            ),
1116            (true, false) => (
1117                r.command_bar_overflow_presenter_border_down_thickness,
1118                r.command_bar_overflow_presenter_border_down_padding,
1119            ),
1120            (true, true) => (
1121                r.command_bar_overflow_presenter_border_up_thickness,
1122                r.command_bar_overflow_presenter_border_up_padding,
1123            ),
1124        };
1125        let items = Column::new()
1126            .main_axis_size(MainAxisSize::Min)
1127            .cross_axis_alignment(CrossAxisAlignment::Stretch)
1128            .children(items);
1129        let scroll = app
1130            .get(self)
1131            .overflow_scroll
1132            .clone()
1133            .expect("made in `init_state`");
1134        let presenter = ControlBorder::new(
1135            Brush::Acrylic(r.command_bar_overflow_presenter_background),
1136            Brush::Solid(r.command_bar_overflow_presenter_border_brush),
1137        )
1138        .border_thickness_ltrb(thickness)
1139        .corner_radius_corners(r.overlay_corner_radius)
1140        .padding(padding)
1141        .child(ScrollBarViewport::new(
1142            scroll,
1143            Margin::new(r.command_bar_overflow_presenter_margin, items),
1144        ));
1145        let shadowed = CustomPaint::new()
1146            .painter(PopupShadow::for_flyout(&r, r.theme, 0))
1147            .child(IntrinsicWidth::new().child(presenter));
1148        let presenter = Focus::new(shadowed)
1149            .can_request_focus(false)
1150            .skip_traversal(true)
1151            .on_key_event(Rc::new(move |app, _, event| self.overflow_key(app, event)));
1152        let motion = self.motion(app);
1153        OverflowReveal {
1154            motion,
1155            closed_display_mode: self.widget(app).closed_display_mode,
1156            minimal_height: r.app_bar_theme_minimal_height,
1157            metrics: app.get(self).metrics.clone(),
1158            child: presenter.into_widget(),
1159        }
1160        .into_widget()
1161    }
1162
1163    /// `AppBar::SetupOverlayState`'s light-dismiss layer: hit unless the bar is sticky, dimming the window when `LightDismissOverlayMode` is on, fading in and out with the bar.
1164    fn light_dismiss_layer(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1165        let r = ThemeResources::of(app, context);
1166        let widget = self.widget(app).clone();
1167        let motion = self.motion(app);
1168        let color = if widget.light_dismiss_overlay_mode == LightDismissOverlayMode::On {
1169            let opacity = match motion.phase {
1170                CommandBarDisplayPhase::Opening => motion.progress,
1171                CommandBarDisplayPhase::Closing => 1.0 - motion.progress,
1172                _ => 1.0,
1173            };
1174            let base = r.app_bar_light_dismiss_overlay_background;
1175            Color {
1176                a: base.a * opacity,
1177                ..base
1178            }
1179        } else {
1180            Color::new(0)
1181        };
1182        IgnorePointer::new()
1183            .ignoring(widget.is_sticky)
1184            .child(
1185                waft_widgets::Listener::new()
1186                    .behavior(HitTestBehavior::Opaque)
1187                    // `OnOverlayElementPointerPressed`.
1188                    .on_pointer_down(Rc::new(move |app, _| {
1189                        self.try_dismiss_inline_app_bar(app);
1190                    }))
1191                    .child(ColoredBox::new(color)),
1192            )
1193            .into_widget()
1194    }
1195
1196    /// The overlay while the bar is not closed: the light-dismiss layer, the bar where its place in the layout is, and the overflow menu.
1197    fn overlay(
1198        self: Handle<Self>,
1199        app: &mut App,
1200        context: BuildContext,
1201        info: OverlayChildLayoutInfo,
1202    ) -> WidgetRef {
1203        if app.get(self).phase == CommandBarDisplayPhase::Closed {
1204            return SizedBox::shrink().into_widget();
1205        }
1206        let r = ThemeResources::of(app, context);
1207        let widget = self.widget(app).clone();
1208        let target = transform_rect(
1209            &info.child_paint_transform(),
1210            Offset::ZERO & info.child_size(),
1211        );
1212        let overlay_size = info.overlay_size();
1213        let (has_primary_commands, has_overflow) = {
1214            let overflow = app.get(self).overflow.borrow();
1215            (
1216                !widget.primary_commands.is_empty(),
1217                !overflow.dynamic_secondary.is_empty(),
1218            )
1219        };
1220        let mut children = vec![
1221            LayoutId::new(part("barrier"), self.light_dismiss_layer(app, context)).into_widget(),
1222            LayoutId::new(part("bar"), self.bar(app, context)).into_widget(),
1223        ];
1224        if has_overflow {
1225            let full_width = overlay_size.width() <= r.command_bar_overflow_max_width;
1226            children.push(
1227                LayoutId::new(
1228                    part("overflow"),
1229                    self.overflow_presenter(app, context, full_width),
1230                )
1231                .into_widget(),
1232            );
1233        }
1234        let overflow_min_width = if app.get(self).input_device_used_to_open == InputDevice::Touch {
1235            r.command_bar_overflow_touch_min_width
1236        } else {
1237            r.command_bar_overflow_min_width
1238        };
1239        CustomMultiChildLayout::new(Rc::new(CommandBarOverlayLayout {
1240            target,
1241            metrics: app.get(self).metrics.clone(),
1242            has_bar: true,
1243            has_overflow,
1244            has_primary_commands,
1245            overflow_min_width,
1246            overflow_max_width: r.command_bar_overflow_max_width,
1247            rtl: Directionality::maybe_of(app, context) == Some(TextDirection::Rtl),
1248            closed_display_mode: widget.closed_display_mode,
1249            motion: self.motion(app),
1250            compact_height_resource: r.app_bar_theme_compact_height,
1251            minimal_height: r.app_bar_theme_minimal_height,
1252        }))
1253        .children(children)
1254        .into_widget()
1255    }
1256}
1257
1258/// The `EllipsisButton` style's template: `ContentPresenter` with the `AppBarButton` brushes of its `CommonStates`, inside `AppBarEllipsisButtonInnerBorderMargin`, and the system focus visual around it.
1259fn ellipsis_button_template(
1260    app: &mut App,
1261    context: BuildContext,
1262    states: ControlStates,
1263    content: WidgetRef,
1264    foreground: Color,
1265) -> WidgetRef {
1266    let r = ThemeResources::of(app, context);
1267    let (background, border, foreground) = match states.common {
1268        CommonState::Normal => (
1269            r.app_bar_button_background,
1270            r.app_bar_button_border_brush,
1271            foreground,
1272        ),
1273        CommonState::PointerOver => (
1274            r.app_bar_button_background_pointer_over,
1275            r.app_bar_button_border_brush_pointer_over,
1276            r.app_bar_button_foreground_pointer_over,
1277        ),
1278        CommonState::Pressed => (
1279            r.app_bar_button_background_pressed,
1280            r.app_bar_button_border_brush_pressed,
1281            r.app_bar_button_foreground_pressed,
1282        ),
1283        CommonState::Disabled => (
1284            r.app_bar_button_background_disabled,
1285            r.app_bar_button_border_brush_disabled,
1286            r.app_bar_button_foreground_disabled,
1287        ),
1288    };
1289    let corner_radius = r.control_corner_radius;
1290    let presenter = ControlBorder::new(Brush::Solid(background), Brush::Solid(border))
1291        .border_thickness(0.0)
1292        .corner_radius_corners(corner_radius)
1293        .child(Center::new().child(DefaultTextStyle::new(
1294            crate::control_text_style(
1295                &r,
1296                r.control_content_theme_font_size,
1297                waft_embedder::FontWeight::W600,
1298                foreground,
1299            ),
1300            content,
1301        )));
1302    let presenter = FocusVisual::new(presenter, r.theme)
1303        .visible(states.focused)
1304        .margin([-3.0; 4])
1305        .corner_radius(corner_radius[0]);
1306    Margin::new(r.app_bar_ellipsis_button_inner_border_margin, presenter).into_widget()
1307}
1308
1309impl State for CommandBarState {
1310    type Widget = CommandBar;
1311    waft_widgets::state_accessors!();
1312
1313    fn init_state(self: Handle<Self>, app: &mut App) {
1314        InputDevice::initialize(app);
1315        let ticker = SingleTickerProviderStateMixin::create_ticker(
1316            self,
1317            app,
1318            FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
1319        );
1320        let portal = OverlayPortalController::new(app, Some("CommandBar".into()));
1321        // The overlay stays shown; it is empty while the bar is closed.
1322        portal.show(app);
1323        let content_focus = FocusNode::new(app).into_erased();
1324        let more_focus = FocusNode::new(app).into_erased();
1325        let overflow_scroll = ScrollViewportController::new(app);
1326        *app.get(self).metrics.heights_changed.borrow_mut() =
1327            Some(Rc::new(move |app| self.layout_changed(app)));
1328        let state = app.get_mut(self);
1329        state.ticker = Some(ticker);
1330        state.portal = Some(portal);
1331        state.content_focus = Some(content_focus);
1332        state.more_focus = Some(more_focus);
1333        state.overflow_scroll = Some(overflow_scroll);
1334        if self.widget(app).is_open {
1335            // `OnLoaded` with `IsOpen` set: no transition runs, so no `Opened` follows.
1336            self.begin_opening(app, false);
1337        }
1338    }
1339
1340    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &CommandBar) {
1341        self.sync_commands(app);
1342        let widget = self.widget(app).clone();
1343        if old.is_dynamic_overflow_enabled != widget.is_dynamic_overflow_enabled {
1344            app.get(self).overflow.borrow_mut().reset_dynamic_commands();
1345        }
1346        if old.is_open != widget.is_open {
1347            if widget.is_open {
1348                self.begin_opening(app, true);
1349            } else {
1350                self.begin_closing(app);
1351            }
1352        }
1353    }
1354
1355    fn activate(self: Handle<Self>, app: &mut App) {
1356        SingleTickerProviderStateMixin::activate(self, app);
1357    }
1358
1359    fn dispose(self: Handle<Self>, app: &mut App) {
1360        if let Some(ticker) = app.get_mut(self).ticker.take() {
1361            ticker.dispose(app);
1362        }
1363        let state = app.get_mut(self);
1364        let mut nodes: Vec<FocusNodeRef> = std::mem::take(&mut state.primary_focus);
1365        nodes.extend(state.overflow_focus.drain().map(|(_, node)| node));
1366        nodes.extend(state.content_focus.take());
1367        nodes.extend(state.more_focus.take());
1368        let scroll = state.overflow_scroll.take();
1369        for node in nodes {
1370            node.dispose(app);
1371        }
1372        if let Some(scroll) = scroll {
1373            scroll.dispose(app);
1374        }
1375        SingleTickerProviderStateMixin::dispose(self, app);
1376    }
1377
1378    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1379        let r = ThemeResources::of(app, context);
1380        app.get_mut(self).timing = TransitionTiming {
1381            normal: r.control_normal_animation_duration,
1382            fast: r.control_fast_animation_duration,
1383            key_spline: r.control_fast_out_slow_in_key_spline,
1384        };
1385        let in_overlay = app.get(self).phase != CommandBarDisplayPhase::Closed;
1386        let child = if in_overlay {
1387            // The bar's place keeps its closed size while the bar is in the overlay.
1388            let metrics = app.get(self).metrics.clone();
1389            LayoutBuilder::new(move |_, _, constraints| {
1390                let constraints = constraints.constraints();
1391                let width = if constraints.max_width.is_finite() {
1392                    constraints.max_width
1393                } else {
1394                    metrics.width.get()
1395                };
1396                SizedBox::new()
1397                    .width(width)
1398                    .height(metrics.closed_height.get())
1399                    .into_widget()
1400            })
1401            .into_widget()
1402        } else {
1403            self.bar(app, context)
1404        };
1405        let portal = OverlayPortal::overlay_child_layout_builder(
1406            app.get(self).portal.clone().expect("made in `init_state`"),
1407            move |app, context, info| self.overlay(app, context, info),
1408        )
1409        .overlay_location(OverlayChildLocation::RootOverlay)
1410        .child(child);
1411        Focus::new(portal)
1412            .can_request_focus(false)
1413            .skip_traversal(true)
1414            .on_key_event(Rc::new(move |app, _, event| self.bar_key(app, event)))
1415            .into_widget()
1416    }
1417}