Skip to main content

egui/containers/
menu.rs

1//! Popup menus, context menus and menu bars.
2//!
3//! Show menus via
4//! - [`Popup::menu`] and [`Popup::context_menu`]
5//! - [`Ui::menu_button`], [`MenuButton`] and [`SubMenuButton`]
6//! - [`MenuBar`]
7//! - [`Response::context_menu`]
8//!
9//! See [`MenuBar`] for an example.
10
11use crate::style::StyleModifier;
12use crate::{
13    Button, Color32, Context, Frame, Id, InnerResponse, IntoAtoms, Layout, PointerButton, Popup,
14    PopupCloseBehavior, Response, Style, Ui, UiBuilder, UiKind, UiStack, UiStackInfo, Widget as _,
15};
16use emath::{Align, RectAlign, Vec2, vec2};
17use epaint::Stroke;
18
19/// Apply a menu style to the [`Style`].
20///
21/// Mainly removes the background stroke and the inactive background fill.
22pub fn menu_style(style: &mut Style) {
23    style.spacing.button_padding = vec2(2.0, 0.0);
24    style.visuals.widgets.active.bg_stroke = Stroke::NONE;
25    style.visuals.widgets.open.bg_stroke = Stroke::NONE;
26    style.visuals.widgets.hovered.bg_stroke = Stroke::NONE;
27    style.visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT;
28    style.visuals.widgets.inactive.bg_stroke = Stroke::NONE;
29}
30
31/// Find the root [`UiStack`] of the menu.
32pub fn find_menu_root(ui: &Ui) -> &UiStack {
33    ui.stack()
34        .iter()
35        .find(|stack| {
36            stack.is_root_ui()
37                || [Some(UiKind::Popup), Some(UiKind::Menu)].contains(&stack.kind())
38                || stack.info.tags.contains(MenuConfig::MENU_CONFIG_TAG)
39        })
40        .expect("We should always find the root")
41}
42
43/// Is this Ui part of a menu?
44///
45/// Returns `false` if this is a menu bar.
46/// Should be used to determine if we should show a menu button or submenu button.
47pub fn is_in_menu(ui: &Ui) -> bool {
48    for stack in ui.stack().iter() {
49        if let Some(config) = stack
50            .info
51            .tags
52            .get_downcast::<MenuConfig>(MenuConfig::MENU_CONFIG_TAG)
53        {
54            return !config.bar;
55        }
56        if [Some(UiKind::Popup), Some(UiKind::Menu)].contains(&stack.kind()) {
57            return true;
58        }
59    }
60    false
61}
62
63/// Configuration and style for menus.
64#[derive(Clone, Debug)]
65pub struct MenuConfig {
66    /// Is this a menu bar?
67    bar: bool,
68
69    /// If the user clicks, should we close the menu?
70    pub close_behavior: PopupCloseBehavior,
71
72    /// Override the menu style.
73    ///
74    /// Default is [`menu_style`].
75    pub style: StyleModifier,
76}
77
78impl Default for MenuConfig {
79    fn default() -> Self {
80        Self {
81            close_behavior: PopupCloseBehavior::default(),
82            bar: false,
83            style: menu_style.into(),
84        }
85    }
86}
87
88impl MenuConfig {
89    /// The tag used to store the menu config in the [`UiStack`].
90    pub const MENU_CONFIG_TAG: &'static str = "egui_menu_config";
91
92    pub fn new() -> Self {
93        Self::default()
94    }
95
96    /// If the user clicks, should we close the menu?
97    #[inline]
98    pub fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self {
99        self.close_behavior = close_behavior;
100        self
101    }
102
103    /// Override the menu style.
104    ///
105    /// Default is [`menu_style`].
106    #[inline]
107    pub fn style(mut self, style: impl Into<StyleModifier>) -> Self {
108        self.style = style.into();
109        self
110    }
111
112    fn from_stack(stack: &UiStack) -> Self {
113        stack
114            .info
115            .tags
116            .get_downcast(Self::MENU_CONFIG_TAG)
117            .cloned()
118            .unwrap_or_default()
119    }
120
121    /// Find the config for the current menu.
122    ///
123    /// Returns the default config if no config is found.
124    pub fn find(ui: &Ui) -> Self {
125        find_menu_root(ui)
126            .info
127            .tags
128            .get_downcast(Self::MENU_CONFIG_TAG)
129            .cloned()
130            .unwrap_or_default()
131    }
132}
133
134/// Holds the state of the menu.
135#[derive(Clone)]
136pub struct MenuState {
137    /// The currently open sub menu in this menu.
138    pub open_item: Option<Id>,
139    last_visible_pass: u64,
140}
141
142impl MenuState {
143    pub const ID: &'static str = "menu_state";
144
145    /// Find the root of the menu and get the state
146    pub fn from_ui<R>(ui: &Ui, f: impl FnOnce(&mut Self, &UiStack) -> R) -> R {
147        let stack = find_menu_root(ui);
148        Self::from_id(ui.ctx(), stack.id, |state| f(state, stack))
149    }
150
151    /// Get the state via the menus root [`Ui`] id
152    pub fn from_id<R>(ctx: &Context, id: Id, f: impl FnOnce(&mut Self) -> R) -> R {
153        let pass_nr = ctx.cumulative_pass_nr();
154        ctx.data_mut(|data| {
155            let state_id = id.with(Self::ID);
156            let mut state = data.get_temp(state_id).unwrap_or(Self {
157                open_item: None,
158                last_visible_pass: pass_nr,
159            });
160            // If the menu was closed for at least a frame, reset the open item
161            if state.last_visible_pass + 1 < pass_nr {
162                state.open_item = None;
163            }
164            if let Some(item) = state.open_item
165                && data
166                    .get_temp(item.with(Self::ID))
167                    .is_none_or(|item: Self| item.last_visible_pass + 1 < pass_nr)
168            {
169                // If the open item wasn't shown for at least a frame, reset the open item
170                state.open_item = None;
171            }
172            let r = f(&mut state);
173            data.insert_temp(state_id, state);
174            r
175        })
176    }
177
178    pub fn mark_shown(ctx: &Context, id: Id) {
179        let pass_nr = ctx.cumulative_pass_nr();
180        Self::from_id(ctx, id, |state| {
181            state.last_visible_pass = pass_nr;
182        });
183    }
184
185    /// Is the menu with this id the deepest sub menu? (-> no child sub menu is open)
186    ///
187    /// Note: This only returns correct results if called after the menu contents were shown.
188    pub fn is_deepest_open_sub_menu(ctx: &Context, id: Id) -> bool {
189        let pass_nr = ctx.cumulative_pass_nr();
190        let open_item = Self::from_id(ctx, id, |state| state.open_item);
191        // If we have some open item, check if that was actually shown this frame
192        open_item.is_none_or(|submenu_id| {
193            Self::from_id(ctx, submenu_id, |state| state.last_visible_pass != pass_nr)
194        })
195    }
196}
197
198/// Horizontal menu bar where you can add [`MenuButton`]s.
199///
200/// The menu bar goes well in a [`crate::Panel::top`],
201/// but can also be placed in a [`crate::Window`].
202/// In the latter case you may want to wrap it in [`Frame`].
203///
204/// ### Example:
205/// ```
206/// # egui::__run_test_ui(|ui| {
207/// egui::MenuBar::new().ui(ui, |ui| {
208///     ui.menu_button("File", |ui| {
209///         if ui.button("Quit").clicked() {
210///             ui.send_viewport_cmd(egui::ViewportCommand::Close);
211///         }
212///     });
213/// });
214/// # });
215/// ```
216#[derive(Clone, Debug)]
217pub struct MenuBar {
218    config: MenuConfig,
219    style: StyleModifier,
220}
221
222impl Default for MenuBar {
223    fn default() -> Self {
224        Self {
225            config: MenuConfig::default(),
226            style: menu_style.into(),
227        }
228    }
229}
230
231impl MenuBar {
232    pub fn new() -> Self {
233        Self::default()
234    }
235
236    /// Set the style for buttons in the menu bar.
237    ///
238    /// Doesn't affect the style of submenus, use [`MenuConfig::style`] for that.
239    /// Default is [`menu_style`].
240    #[inline]
241    pub fn style(mut self, style: impl Into<StyleModifier>) -> Self {
242        self.style = style.into();
243        self
244    }
245
246    /// Set the config for submenus.
247    ///
248    /// Note: The config will only be passed when using [`MenuButton`], not via [`Popup::menu`].
249    #[inline]
250    pub fn config(mut self, config: MenuConfig) -> Self {
251        self.config = config;
252        self
253    }
254
255    /// Show the menu bar.
256    #[inline]
257    pub fn ui<R>(self, ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
258        let Self { mut config, style } = self;
259        config.bar = true;
260        // TODO(lucasmerlin): It'd be nice if we had a ui.horizontal_builder or something
261        // So we don't need the nested scope here
262        ui.horizontal(|ui| {
263            ui.scope_builder(
264                UiBuilder::new()
265                    .layout(Layout::left_to_right(Align::Center))
266                    .ui_stack_info(
267                        UiStackInfo::new(UiKind::Menu)
268                            .with_tag_value(MenuConfig::MENU_CONFIG_TAG, config),
269                    ),
270                |ui| {
271                    style.apply(ui.style_mut());
272
273                    // Take full width and fixed height:
274                    let height = ui.spacing().interact_size.y;
275                    ui.set_min_size(vec2(ui.available_width(), height));
276
277                    content(ui)
278                },
279            )
280            .inner
281        })
282    }
283}
284
285/// A thin wrapper around a [`Button`] that shows a [`Popup::menu`] when clicked.
286///
287/// The only thing this does is search for the current menu config (if set via [`MenuBar`]).
288/// If your menu button is not in a [`MenuBar`] it's fine to use [`Ui::button`] and [`Popup::menu`]
289/// directly.
290pub struct MenuButton<'a> {
291    pub button: Button<'a>,
292    pub config: Option<MenuConfig>,
293}
294
295impl<'a> MenuButton<'a> {
296    pub fn new(atoms: impl IntoAtoms<'a>) -> Self {
297        Self::from_button(Button::new(atoms.into_atoms()))
298    }
299
300    /// Set the config for the menu.
301    #[inline]
302    pub fn config(mut self, config: MenuConfig) -> Self {
303        self.config = Some(config);
304        self
305    }
306
307    /// Create a new menu button from a [`Button`].
308    #[inline]
309    pub fn from_button(button: Button<'a>) -> Self {
310        Self {
311            button,
312            config: None,
313        }
314    }
315
316    /// Show the menu button.
317    pub fn ui<R>(
318        self,
319        ui: &mut Ui,
320        content: impl FnOnce(&mut Ui) -> R,
321    ) -> (Response, Option<InnerResponse<R>>) {
322        let response = self.button.ui(ui);
323        let mut config = self.config.unwrap_or_else(|| MenuConfig::find(ui));
324        config.bar = false;
325        let inner = Popup::menu(&response)
326            .close_behavior(config.close_behavior)
327            .style(config.style.clone())
328            .info(
329                UiStackInfo::new(UiKind::Menu).with_tag_value(MenuConfig::MENU_CONFIG_TAG, config),
330            )
331            .show(content);
332        (response, inner)
333    }
334}
335
336/// A submenu button that shows a [`SubMenu`] if a [`Button`] is hovered.
337pub struct SubMenuButton<'a> {
338    pub button: Button<'a>,
339    pub sub_menu: SubMenu,
340}
341
342impl<'a> SubMenuButton<'a> {
343    /// The default right arrow symbol: `"⏵"`
344    pub const RIGHT_ARROW: &'static str = "⏵";
345
346    pub fn new(atoms: impl IntoAtoms<'a>) -> Self {
347        Self::from_button(Button::new(atoms.into_atoms()).right_text("⏵"))
348    }
349
350    /// Create a new submenu button from a [`Button`].
351    ///
352    /// Use [`Button::right_text`] and [`SubMenuButton::RIGHT_ARROW`] to add the default right
353    /// arrow symbol.
354    pub fn from_button(button: Button<'a>) -> Self {
355        Self {
356            button,
357            sub_menu: SubMenu::default(),
358        }
359    }
360
361    /// Set the config for the submenu.
362    ///
363    /// The close behavior will not affect the current button, but the buttons in the submenu.
364    #[inline]
365    pub fn config(mut self, config: MenuConfig) -> Self {
366        self.sub_menu.config = Some(config);
367        self
368    }
369
370    /// Show the submenu button.
371    pub fn ui<R>(
372        self,
373        ui: &mut Ui,
374        content: impl FnOnce(&mut Ui) -> R,
375    ) -> (Response, Option<InnerResponse<R>>) {
376        let my_id = ui.next_auto_id();
377        let open = MenuState::from_ui(ui, |state, _| {
378            state.open_item == Some(SubMenu::id_from_widget_id(my_id))
379        });
380        let inactive = ui.style().visuals.widgets.inactive;
381        // TODO(lucasmerlin) add `open` function to `Button`
382        if open {
383            ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open;
384        }
385        let response = self.button.ui(ui);
386        ui.style_mut().visuals.widgets.inactive = inactive;
387
388        let popup_response = self.sub_menu.show(ui, &response, content);
389
390        (response, popup_response)
391    }
392}
393
394/// Show a submenu in a menu.
395///
396/// Useful if you want to make custom menu buttons.
397/// Usually, just use [`MenuButton`] or [`SubMenuButton`] instead.
398#[derive(Clone, Debug, Default)]
399pub struct SubMenu {
400    config: Option<MenuConfig>,
401}
402
403impl SubMenu {
404    pub fn new() -> Self {
405        Self::default()
406    }
407
408    /// Set the config for the submenu.
409    ///
410    /// The close behavior will not affect the current button, but the buttons in the submenu.
411    #[inline]
412    pub fn config(mut self, config: MenuConfig) -> Self {
413        self.config = Some(config);
414        self
415    }
416
417    /// Get the id for the submenu from the widget/response id.
418    pub fn id_from_widget_id(widget_id: Id) -> Id {
419        widget_id.with("submenu")
420    }
421
422    /// Show the submenu.
423    ///
424    /// This does some heuristics to check if the `button_response` was the last thing in the
425    /// menu that was hovered/clicked, and if so, shows the submenu.
426    pub fn show<R>(
427        self,
428        ui: &Ui,
429        button_response: &Response,
430        content: impl FnOnce(&mut Ui) -> R,
431    ) -> Option<InnerResponse<R>> {
432        let frame = Frame::menu(ui.style());
433
434        let id = Self::id_from_widget_id(button_response.id);
435
436        // Get the state from the parent menu
437        let (open_item, menu_id, parent_config) = MenuState::from_ui(ui, |state, stack| {
438            (state.open_item, stack.id, MenuConfig::from_stack(stack))
439        });
440
441        let mut menu_config = self.config.unwrap_or_else(|| parent_config.clone());
442        menu_config.bar = false;
443
444        #[expect(clippy::unwrap_used)] // Since we are a child of that ui, this should always exist
445        let menu_root_response = ui.ctx().read_response(menu_id).unwrap();
446
447        let hover_pos = ui.ctx().pointer_hover_pos();
448
449        // We don't care if the user is hovering over the border
450        let menu_rect = menu_root_response.rect - frame.total_margin();
451        let is_hovering_menu = hover_pos.is_some_and(|pos| {
452            ui.ctx().layer_id_at(pos) == Some(menu_root_response.layer_id)
453                && menu_rect.contains(pos)
454        });
455
456        let is_any_open = open_item.is_some();
457        let mut is_open = open_item == Some(id);
458        let was_open = is_open;
459        let mut set_open = None;
460
461        // We expand the button rect so there is no empty space where no menu is shown
462        // TODO(lucasmerlin): Instead, maybe make item_spacing.y 0.0?
463        let button_rect = button_response
464            .rect
465            .expand2(ui.style().spacing.item_spacing / 2.0);
466
467        // In theory some other widget could cover the button and this check would still pass
468        // But since we check if no other menu is open, nothing should be able to cover the button
469        let is_hovered = hover_pos.is_some_and(|pos| button_rect.contains(pos));
470
471        // `clicked` includes keyboard and accessibility click actions.
472        // We want Enter/Space to toggle an already open submenu, while pointer clicks should keep
473        // the submenu open (for touch and pointer interactions).
474        let clicked = button_response.clicked();
475        let clicked_by_pointer = button_response.clicked_by(PointerButton::Primary);
476        let clicked_by_keyboard_or_access = clicked && !clicked_by_pointer;
477
478        if ui.is_enabled() && is_open && clicked_by_keyboard_or_access {
479            set_open = Some(false);
480            is_open = false;
481        }
482
483        // The clicked handler is there for accessibility (keyboard navigation)
484        let should_open =
485            ui.is_enabled() && ((!was_open && clicked) || (is_hovered && !is_any_open));
486        if should_open {
487            set_open = Some(true);
488            is_open = true;
489            // Ensure that all other sub menus are closed when we open the menu
490            MenuState::from_id(ui.ctx(), menu_id, |state| {
491                state.open_item = None;
492            });
493        }
494
495        let gap = frame.total_margin().sum().x / 2.0 + 2.0;
496
497        let mut response = button_response.clone();
498        // Expand the button rect so that the button and the first item in the submenu are aligned
499        let expand = Vec2::new(0.0, frame.total_margin().sum().y / 2.0);
500        response.interact_rect = response.interact_rect.expand2(expand);
501
502        let popup_response = Popup::from_response(&response)
503            .id(id)
504            .open(is_open)
505            .align(RectAlign::RIGHT_START)
506            .layout(Layout::top_down_justified(Align::Min))
507            .gap(gap)
508            .style(menu_config.style.clone())
509            .frame(frame)
510            // The close behavior is handled by the menu (see below)
511            .close_behavior(PopupCloseBehavior::IgnoreClicks)
512            .info(
513                UiStackInfo::new(UiKind::Menu)
514                    .with_tag_value(MenuConfig::MENU_CONFIG_TAG, menu_config.clone()),
515            )
516            .show(|ui| {
517                // Ensure our layer stays on top when the button is clicked
518                if button_response.clicked() || button_response.is_pointer_button_down_on() {
519                    ui.ctx().move_to_top(ui.layer_id());
520                }
521                content(ui)
522            });
523
524        if let Some(popup_response) = &popup_response {
525            // If no child sub menu is open means we must be the deepest child sub menu.
526            let is_deepest_submenu = MenuState::is_deepest_open_sub_menu(ui.ctx(), id);
527
528            // If the user clicks and the cursor is not hovering over our menu rect, it's
529            // safe to assume they clicked outside the menu, so we close everything.
530            // If they were to hover some other parent submenu we wouldn't be open.
531            // Only edge case is the user hovering this submenu's button, so we also check
532            // if we clicked outside the parent menu (which we luckily have access to here).
533            let clicked_outside = is_deepest_submenu
534                && popup_response.response.clicked_elsewhere()
535                && menu_root_response.clicked_elsewhere();
536
537            // We never automatically close when a submenu button is clicked, (so menus work
538            // on touch devices)
539            // Luckily we will always be the deepest submenu when a submenu button is clicked,
540            // so the following check is enough.
541            let submenu_button_clicked = button_response.clicked();
542
543            let clicked_inside = is_deepest_submenu
544                && !submenu_button_clicked
545                && response.ctx.input(|i| i.pointer.any_click())
546                && hover_pos.is_some_and(|pos| popup_response.response.interact_rect.contains(pos));
547
548            let click_close = match menu_config.close_behavior {
549                PopupCloseBehavior::CloseOnClick => clicked_outside || clicked_inside,
550                PopupCloseBehavior::CloseOnClickOutside => clicked_outside,
551                PopupCloseBehavior::IgnoreClicks => false,
552            };
553
554            if click_close {
555                set_open = Some(false);
556                ui.close();
557            }
558
559            let is_moving_towards_rect = ui.input(|i| {
560                i.pointer
561                    .is_moving_towards_rect(&popup_response.response.rect)
562            });
563            if is_moving_towards_rect {
564                // We need to repaint while this is true, so we can detect when
565                // the pointer is no longer moving towards the rect
566                ui.request_repaint();
567            }
568            let hovering_other_menu_entry = is_open
569                && !is_hovered
570                && !popup_response.response.contains_pointer()
571                && !is_moving_towards_rect
572                && is_hovering_menu;
573
574            let close_called = popup_response.response.should_close();
575
576            // Close the parent ui to e.g. close the popup from where the submenu was opened
577            if close_called {
578                ui.close();
579            }
580
581            if hovering_other_menu_entry {
582                set_open = Some(false);
583            }
584
585            if ui.will_parent_close() {
586                ui.data_mut(|data| data.remove_by_type::<MenuState>());
587            }
588        }
589
590        if let Some(set_open) = set_open {
591            MenuState::from_id(ui.ctx(), menu_id, |state| {
592                state.open_item = set_open.then_some(id);
593            });
594        }
595
596        popup_response
597    }
598}