Skip to main content

waft_winui/controls/menu_flyout/
mod.rs

1//! MenuFlyout's collection, presenter and cascading item behavior.
2
3mod item;
4mod item_widget;
5mod presenter;
6mod template;
7
8use crate::InputDevice;
9pub use item::{MenuCheckedChanged, MenuFlyoutItem, MenuFlyoutItemKind};
10use presenter::{MenuFlyoutPresenter, MenuFlyoutPresenterState};
11
12use crate::*;
13use std::{fmt, rc::Rc};
14use waft_embedder::Size;
15use waft_foundation::{App, Handle, Listener, Ref};
16use waft_services::KeyEvent;
17use waft_widgets::*;
18
19/// MenuFlyoutPresenter's style: at least `FlyoutThemeMinWidth` wide and `MenuFlyoutThemeMinHeight`
20/// tall, and no maximum.
21fn menu_flyout_presenter_sizes(r: &ThemeResources) -> (Size, Size) {
22    (
23        Size::new(r.flyout_theme_min_width, r.menu_flyout_theme_min_height),
24        Size::new(f64::INFINITY, f64::INFINITY),
25    )
26}
27
28/// MenuBar receives unhandled keys from the menu collection that originated them.
29pub(crate) type MenuKeyHandler =
30    Rc<dyn Fn(&mut App, Handle<MenuFlyout>, &KeyEvent) -> KeyEventResult>;
31
32/// Persistent owner of a collection displayed by a MenuFlyoutPresenter.
33///
34/// Keep the `MenuFlyout` for as long as its flyout (see `as_flyout`) is in use: the flyout's
35/// closures name the menu without keeping it.
36pub struct MenuFlyout {
37    /// Shared flyout lifecycle and overlay ownership.
38    flyout: Ref<Flyout>,
39
40    /// Configuration supplied by the application, in display order.
41    items: Vec<MenuFlyoutItem>,
42
43    /// Mounted presenter, retained between openings.
44    presenter: Option<Handle<MenuFlyoutPresenterState>>,
45
46    /// Root menu closed when a command is invoked in any submenu.
47    root: Option<Handle<MenuFlyout>>,
48
49    /// Item that owns this submenu, when this is not the root collection.
50    owner_item: Option<Handle<item_widget::MenuItemState>>,
51
52    /// Opening device, captured once for each menu opening.
53    input: InputDevice,
54
55    /// Prevents late use after the owning state disposes the menu.
56    disposed: bool,
57
58    /// Owner navigation after the menu's own keyboard handling.
59    pub(crate) key_handler: Option<MenuKeyHandler>,
60}
61
62impl fmt::Debug for MenuFlyout {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.debug_struct("MenuFlyout")
65            .field("items", &self.items)
66            .field("disposed", &self.disposed)
67            .finish_non_exhaustive()
68    }
69}
70
71impl MenuFlyout {
72    /// Records the current raw pointer before a header opens its menu on press or entry.
73    pub(crate) fn pointer_input(app: &mut App, kind: waft_embedder::PointerDeviceKind) {
74        InputDevice::pointer(app, kind);
75    }
76
77    /// Creates a root menu; checked values follow the kit's owner-state convention.
78    pub fn new(app: &mut App, items: Vec<MenuFlyoutItem>) -> Ref<Self> {
79        Self::with_root(app, items, None)
80    }
81
82    /// Creates a menu whose invocations report to `root`'s owner (a submenu), or a root menu
83    /// for `None`.
84    fn with_root(
85        app: &mut App,
86        items: Vec<MenuFlyoutItem>,
87        root: Option<Handle<Self>>,
88    ) -> Ref<Self> {
89        InputDevice::initialize(app);
90        let flyout = Flyout::new(app, SizedBox::shrink());
91        let owner = app.create(Self {
92            flyout: flyout.clone(),
93            items,
94            presenter: None,
95            root,
96            owner_item: None,
97            input: InputDevice::None,
98            disposed: false,
99            key_handler: None,
100        });
101        let menu = owner.handle();
102        let base = app.get_mut(&flyout);
103        base.is_sub_menu = root.is_some();
104        base.presenter_sizes = menu_flyout_presenter_sizes;
105        base.on_opening = Some(Listener::new(move |app| menu.on_opening(app)));
106        base.on_closed = Some(Listener::new(move |app| {
107            if let Some(presenter) = app.get(menu).presenter {
108                presenter.prepare_close(app);
109            }
110        }));
111        base.flyout_presenter_style = Some(Rc::new(move |_, _, _| {
112            MenuFlyoutPresenter { menu }.into_widget()
113        }));
114        owner
115    }
116
117    /// Returns the shared flyout object for DropDownButton, placement and lifecycle callbacks.
118    ///
119    /// Call `.handle()` to use it, or `.clone()` to keep it.
120    pub fn as_flyout(self: Handle<Self>, app: &App) -> &Ref<Flyout> {
121        &app.get(self).flyout
122    }
123
124    /// The flyout this menu presents in, for a call that takes the `App` mutably.
125    fn flyout(self: Handle<Self>, app: &App) -> Handle<Flyout> {
126        self.as_flyout(app).handle()
127    }
128
129    /// Replaces the item configuration while preserving keyed item state.
130    pub fn items(self: Handle<Self>, app: &mut App, items: Vec<MenuFlyoutItem>) {
131        assert!(
132            !app.get(self).disposed,
133            "cannot update a disposed MenuFlyout"
134        );
135        app.get_mut(self).items = items;
136        self.flyout(app).rebuild_content(app);
137    }
138
139    /// Shows from a context beneath FlyoutTarget.
140    pub fn show_at(self: Handle<Self>, app: &mut App, target: BuildContext) {
141        self.flyout(app).show_at(app, target);
142    }
143
144    /// Shows with per-opening placement and input policy.
145    pub fn show_at_with_options(
146        self: Handle<Self>,
147        app: &mut App,
148        target: BuildContext,
149        options: FlyoutShowOptions,
150    ) {
151        self.flyout(app).show_at_with_options(app, target, options);
152    }
153
154    /// Hides this menu and its open descendants.
155    pub fn hide(self: Handle<Self>, app: &mut App) {
156        self.flyout(app).hide(app);
157    }
158
159    /// Whether this menu is currently shown.
160    pub fn is_open(self: Handle<Self>, app: &App) -> bool {
161        self.flyout(app).is_open(app)
162    }
163
164    /// Releases the retained presenter and its child menus.
165    pub fn dispose(self: Handle<Self>, app: &mut App) {
166        if app.get(self).disposed {
167            return;
168        }
169        app.get_mut(self).disposed = true;
170        self.flyout(app).dispose(app);
171    }
172
173    /// Captures the source padding mode and resets the collection's scroll position.
174    fn on_opening(self: Handle<Self>, app: &mut App) {
175        let input = if let Some(root) = app.get(self).root {
176            app.get(root).input
177        } else {
178            InputDevice::current(app)
179        };
180        app.get_mut(self).input = input;
181        self.flyout(app)
182            .menu_point_placement(app, input == InputDevice::Touch);
183        if let Some(presenter) = app.get(self).presenter {
184            presenter.prepare_open(app);
185        }
186    }
187
188    /// Whether the currently focused entry owns children and must keep its arrow keys.
189    pub(crate) fn focused_item_has_children(self: Handle<Self>, app: &App) -> bool {
190        app.get(self).presenter.is_some_and(|presenter| {
191            app.get(presenter).containers.values().any(|item| {
192                item.focus_node(app).has_primary_focus(app)
193                    && matches!(&item.widget(app).item.kind, MenuFlyoutItemKind::SubItem { items } if !items.is_empty())
194            })
195        })
196    }
197
198    /// Bubbles keys from nested collections to a MenuBar owner, when present.
199    fn owner_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
200        let root = self.root(app);
201        app.get(root)
202            .key_handler
203            .clone()
204            .map_or(KeyEventResult::Ignored, |handler| handler(app, self, event))
205    }
206
207    /// The root collection owns command dismissal across the entire chain.
208    fn root(self: Handle<Self>, app: &App) -> Handle<Self> {
209        app.get(self).root.unwrap_or(self)
210    }
211}