Skip to main content

cosmic/widget/menu/
menu_bar.rs

1// From iced_aw, license MIT
2
3//! A widget that handles menu trees
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use super::menu_inner::{
8    CloseCondition, Direction, ItemHeight, ItemWidth, Menu, MenuState, PathHighlight,
9    close_innermost,
10};
11use super::menu_tree::MenuTree;
12use crate::Renderer;
13#[cfg(wayland_platform)]
14use crate::app::cosmic::{WINDOWING_SYSTEM, WindowingSystem};
15use crate::style::menu_bar::StyleSheet;
16use crate::widget::RcWrapper;
17use crate::widget::menu::menu_inner::init_root_menu;
18
19use iced::{Point, Shadow, Vector, window};
20use iced_core::Border;
21use iced_widget::core::layout::{Limits, Node};
22use iced_widget::core::mouse::{self, Cursor};
23use iced_widget::core::renderer::{self, Renderer as IcedRenderer};
24use iced_widget::core::widget::{Tree, tree};
25use iced_widget::core::{
26    Alignment, Clipboard, Element, Layout, Length, Padding, Rectangle, Shell, Widget, event,
27    overlay, touch,
28};
29
30/// A `MenuBar` collects `MenuTree`s and handles all the layout, event processing, and drawing.
31pub fn menu_bar<Message>(menu_roots: Vec<MenuTree<Message>>) -> MenuBar<Message>
32where
33    Message: Clone + 'static,
34{
35    MenuBar::new(menu_roots)
36}
37
38#[derive(Clone, Default)]
39pub(crate) struct MenuBarState {
40    pub(crate) inner: RcWrapper<MenuBarStateInner>,
41}
42
43pub(crate) struct MenuBarStateInner {
44    pub(crate) tree: Tree,
45    pub(crate) popup_id: HashMap<window::Id, window::Id>,
46    pub(crate) pressed: bool,
47    pub(crate) bar_pressed: bool,
48    pub(crate) view_cursor: Cursor,
49    pub(crate) open: bool,
50    pub(crate) active_root: Vec<usize>,
51    pub(crate) horizontal_direction: Direction,
52    pub(crate) vertical_direction: Direction,
53    /// List of all menu states
54    pub(crate) menu_states: Vec<MenuState>,
55}
56impl MenuBarStateInner {
57    /// get the list of indices hovered for the menu
58    pub(super) fn get_trimmed_indices(&self, index: usize) -> impl Iterator<Item = usize> + '_ {
59        self.menu_states
60            .iter()
61            .skip(index)
62            .take_while(|ms| ms.index.is_some())
63            .map(|ms| ms.index.expect("No indices were found in the menu state."))
64    }
65
66    pub(crate) fn reset(&mut self) {
67        self.open = false;
68        self.active_root = Vec::new();
69        self.menu_states.clear();
70    }
71}
72impl Default for MenuBarStateInner {
73    fn default() -> Self {
74        Self {
75            tree: Tree::empty(),
76            pressed: false,
77            view_cursor: Cursor::Available([-0.5, -0.5].into()),
78            open: false,
79            active_root: Vec::new(),
80            horizontal_direction: Direction::Positive,
81            vertical_direction: Direction::Positive,
82            menu_states: Vec::new(),
83            popup_id: HashMap::new(),
84            bar_pressed: false,
85        }
86    }
87}
88
89pub(crate) fn menu_roots_children<Message>(menu_roots: &[MenuTree<Message>]) -> Vec<Tree>
90where
91    Message: Clone + 'static,
92{
93    /*
94    menu bar
95        menu root 1 (stateless)
96            flat tree
97        menu root 2 (stateless)
98            flat tree
99        ...
100    */
101
102    menu_roots
103        .iter()
104        .map(|root| {
105            let mut tree = Tree::empty();
106            let flat = root
107                .flattern()
108                .iter()
109                .map(|mt| Tree::new(mt.item.clone()))
110                .collect();
111            tree.children = flat;
112            tree
113        })
114        .collect()
115}
116
117#[allow(invalid_reference_casting)]
118pub(crate) fn menu_roots_diff<Message>(menu_roots: &mut [MenuTree<Message>], tree: &mut Tree)
119where
120    Message: Clone + 'static,
121{
122    if tree.children.len() > menu_roots.len() {
123        tree.children.truncate(menu_roots.len());
124    }
125
126    tree.children
127        .iter_mut()
128        .zip(menu_roots.iter())
129        .for_each(|(t, root)| {
130            let mut flat = root
131                .flattern()
132                .iter()
133                .map(|mt| {
134                    let widget = &mt.item;
135                    let widget_ptr = widget as *const dyn Widget<Message, crate::Theme, Renderer>;
136                    let widget_ptr_mut =
137                        widget_ptr as *mut dyn Widget<Message, crate::Theme, Renderer>;
138                    //TODO: find a way to diff_children without unsafe code
139                    unsafe { &mut *widget_ptr_mut }
140                })
141                .collect::<Vec<_>>();
142
143            t.diff_children(flat.as_mut_slice());
144        });
145
146    if tree.children.len() < menu_roots.len() {
147        let extended = menu_roots[tree.children.len()..].iter().map(|root| {
148            let mut tree = Tree::empty();
149            let flat = root
150                .flattern()
151                .iter()
152                .map(|mt| Tree::new(mt.item.clone()))
153                .collect();
154            tree.children = flat;
155            tree
156        });
157        tree.children.extend(extended);
158    }
159}
160
161pub fn get_mut_or_default<T: Default>(vec: &mut Vec<T>, index: usize) -> &mut T {
162    if index < vec.len() {
163        &mut vec[index]
164    } else {
165        vec.resize_with(index + 1, T::default);
166        &mut vec[index]
167    }
168}
169
170/// A `MenuBar` collects `MenuTree`s and handles all the layout, event processing, and drawing.
171#[allow(missing_debug_implementations)]
172pub struct MenuBar<Message> {
173    width: Length,
174    height: Length,
175    spacing: f32,
176    padding: Padding,
177    bounds_expand: u16,
178    main_offset: i32,
179    cross_offset: i32,
180    close_condition: CloseCondition,
181    item_width: ItemWidth,
182    item_height: ItemHeight,
183    path_highlight: Option<PathHighlight>,
184    menu_roots: Vec<MenuTree<Message>>,
185    style: <crate::Theme as StyleSheet>::Style,
186    window_id: window::Id,
187    #[cfg(wayland_platform)]
188    positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
189    pub(crate) on_surface_action:
190        Option<Arc<dyn Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static>>,
191}
192
193impl<Message> MenuBar<Message>
194where
195    Message: Clone + 'static,
196{
197    /// Creates a new [`MenuBar`] with the given menu roots
198    #[must_use]
199    pub fn new(menu_roots: Vec<MenuTree<Message>>) -> Self {
200        let mut menu_roots = menu_roots;
201        menu_roots.iter_mut().for_each(MenuTree::set_index);
202
203        Self {
204            width: Length::Shrink,
205            height: Length::Shrink,
206            spacing: 0.0,
207            padding: Padding::ZERO,
208            bounds_expand: 16,
209            main_offset: 0,
210            cross_offset: 0,
211            close_condition: CloseCondition {
212                leave: false,
213                click_outside: true,
214                click_inside: true,
215            },
216            item_width: ItemWidth::Uniform(150),
217            item_height: ItemHeight::Dynamic(40),
218            path_highlight: Some(PathHighlight::MenuActive),
219            menu_roots,
220            style: <crate::Theme as StyleSheet>::Style::default(),
221            window_id: window::Id::RESERVED,
222            #[cfg(wayland_platform)]
223            positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner::default(),
224            on_surface_action: None,
225        }
226    }
227
228    /// Sets the expand value for each menu's check bounds
229    ///
230    /// When the cursor goes outside of a menu's check bounds,
231    /// the menu will be closed automatically, this value expands
232    /// the check bounds
233    #[must_use]
234    pub fn bounds_expand(mut self, value: u16) -> Self {
235        self.bounds_expand = value;
236        self
237    }
238
239    /// [`CloseCondition`]
240    #[must_use]
241    pub fn close_condition(mut self, close_condition: CloseCondition) -> Self {
242        self.close_condition = close_condition;
243        self
244    }
245
246    /// Moves each menu in the horizontal open direction
247    #[must_use]
248    pub fn cross_offset(mut self, value: i32) -> Self {
249        self.cross_offset = value;
250        self
251    }
252
253    /// Sets the height of the [`MenuBar`]
254    #[must_use]
255    pub fn height(mut self, height: Length) -> Self {
256        self.height = height;
257        self
258    }
259
260    /// [`ItemHeight`]
261    #[must_use]
262    pub fn item_height(mut self, item_height: ItemHeight) -> Self {
263        self.item_height = item_height;
264        self
265    }
266
267    /// [`ItemWidth`]
268    #[must_use]
269    pub fn item_width(mut self, item_width: ItemWidth) -> Self {
270        self.item_width = item_width;
271        self
272    }
273
274    /// Moves all the menus in the vertical open direction
275    #[must_use]
276    pub fn main_offset(mut self, value: i32) -> Self {
277        self.main_offset = value;
278        self
279    }
280
281    /// Sets the [`Padding`] of the [`MenuBar`]
282    #[must_use]
283    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
284        self.padding = padding.into();
285        self
286    }
287
288    /// Sets the method for drawing path highlight
289    #[must_use]
290    pub fn path_highlight(mut self, path_highlight: Option<PathHighlight>) -> Self {
291        self.path_highlight = path_highlight;
292        self
293    }
294
295    /// Sets the spacing between menu roots
296    #[must_use]
297    pub fn spacing(mut self, units: f32) -> Self {
298        self.spacing = units;
299        self
300    }
301
302    /// Sets the style of the menu bar and its menus
303    #[must_use]
304    pub fn style(mut self, style: impl Into<<crate::Theme as StyleSheet>::Style>) -> Self {
305        self.style = style.into();
306        self
307    }
308
309    /// Sets the width of the [`MenuBar`]
310    #[must_use]
311    pub fn width(mut self, width: Length) -> Self {
312        self.width = width;
313        self
314    }
315
316    #[cfg(wayland_platform)]
317    pub fn with_positioner(
318        mut self,
319        positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
320    ) -> Self {
321        self.positioner = positioner;
322        self
323    }
324
325    #[must_use]
326    pub fn window_id(mut self, id: window::Id) -> Self {
327        self.window_id = id;
328        self
329    }
330
331    #[must_use]
332    pub fn window_id_maybe(mut self, id: Option<window::Id>) -> Self {
333        if let Some(id) = id {
334            self.window_id = id;
335        }
336        self
337    }
338
339    #[must_use]
340    pub fn on_surface_action(
341        mut self,
342        handler: impl Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static,
343    ) -> Self {
344        self.on_surface_action = Some(Arc::new(handler));
345        self
346    }
347
348    #[cfg(wayland_platform)]
349    #[allow(clippy::too_many_lines)]
350    fn create_popup(
351        &mut self,
352        layout: Layout<'_>,
353        view_cursor: Cursor,
354        renderer: &Renderer,
355        shell: &mut Shell<'_, Message>,
356        viewport: &Rectangle,
357        my_state: &mut MenuBarState,
358    ) {
359        if self.window_id != window::Id::NONE
360            && let Some(surface_action) = self.on_surface_action.as_ref()
361        {
362            use crate::surface::action::{LiveSettings, destroy_popup};
363            use crate::theme::THEME;
364            use iced_runtime::platform_specific::wayland::CornerRadius;
365            use iced_runtime::platform_specific::wayland::popup::{
366                SctkPopupSettings, SctkPositioner,
367            };
368
369            let old_active_root = my_state
370                .inner
371                .with_data(|state| state.active_root.first().copied());
372
373            // if position is not on menu bar button skip.
374            let hovered_root = layout
375                .children()
376                .position(|lo| view_cursor.is_over(lo.bounds()));
377            if hovered_root.is_none()
378                || old_active_root
379                    .zip(hovered_root)
380                    .is_some_and(|r| r.0 == r.1)
381            {
382                return;
383            }
384
385            let (id, root_list) = my_state.inner.with_data_mut(|state| {
386                if let Some(id) = state.popup_id.get(&self.window_id).copied() {
387                    // close existing popups
388                    state.menu_states.clear();
389                    state.active_root.clear();
390                    shell.publish(surface_action(destroy_popup(id)));
391                    state.view_cursor = view_cursor;
392                }
393                // A fresh id per popup, so the old popup's Done cannot be mistaken for the new one's
394                (
395                    window::Id::unique(),
396                    layout.children().map(|lo| lo.bounds()).collect(),
397                )
398            });
399
400            let mut popup_menu: Menu<'static, _> = Menu {
401                tree: my_state.clone(),
402                menu_roots: std::borrow::Cow::Owned(self.menu_roots.clone()),
403                bounds_expand: self.bounds_expand,
404                menu_overlays_parent: false,
405                close_condition: self.close_condition,
406                item_width: self.item_width,
407                item_height: self.item_height,
408                bar_bounds: layout.bounds(),
409                main_offset: self.main_offset,
410                cross_offset: self.cross_offset,
411                root_bounds_list: root_list,
412                path_highlight: self.path_highlight,
413                style: std::borrow::Cow::Owned(self.style.clone()),
414                position: Point::new(0., 0.),
415                is_overlay: false,
416                window_id: id,
417                depth: 0,
418                on_surface_action: self.on_surface_action.clone(),
419            };
420
421            init_root_menu(
422                &mut popup_menu,
423                renderer,
424                shell,
425                view_cursor.position().unwrap(),
426                viewport.size(),
427                Vector::new(0., 0.),
428                layout.bounds(),
429                self.main_offset as f32,
430            );
431            let (anchor_rect, gravity) = my_state.inner.with_data_mut(|state| {
432                state.popup_id.insert(self.window_id, id);
433                (state
434                    .menu_states
435                    .iter()
436                    .find(|s| s.index.is_none())
437                    .map(|s| s.menu_bounds.parent_bounds)
438                    .map_or_else(
439                        || {
440                            let bounds = layout.bounds();
441                            Rectangle {
442                                x: bounds.x as i32,
443                                y: bounds.y as i32,
444                                width: bounds.width as i32,
445                                height: bounds.height as i32,
446                            }
447                        },
448                        |r| Rectangle {
449                            x: r.x as i32,
450                            y: r.y as i32,
451                            width: r.width as i32,
452                            height: r.height as i32,
453                        },
454                    ), match (state.horizontal_direction, state.vertical_direction) {
455                        (Direction::Positive, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
456                        (Direction::Positive, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopRight,
457                        (Direction::Negative, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomLeft,
458                        (Direction::Negative, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopLeft,
459                    })
460            });
461
462            let menu_node = popup_menu.layout(renderer, Limits::NONE.min_width(1.).min_height(1.));
463            let popup_size = menu_node.size();
464            let positioner = SctkPositioner {
465                size: Some((
466                    popup_size.width.ceil() as u32 + 2,
467                    popup_size.height.ceil() as u32 + 2,
468                )),
469                anchor_rect,
470                anchor:
471                    cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Anchor::BottomLeft,
472                gravity,
473                reactive: true,
474                ..Default::default()
475            };
476            let parent = self.window_id;
477
478            let t = THEME.lock().unwrap();
479            let styling = t.appearance(&crate::theme::menu_bar::MenuBarStyle::Default, false);
480            drop(t);
481            let rad = styling.menu_border_radius;
482
483            shell.publish((surface_action)(crate::surface::action::simple_popup(
484                move || LiveSettings {
485                    corners: Some(CornerRadius {
486                        top_left: rad[0] as u32,
487                        top_right: rad[1] as u32,
488                        bottom_left: rad[2] as u32,
489                        bottom_right: rad[3] as u32,
490                    }),
491                    ..Default::default()
492                },
493                move || SctkPopupSettings {
494                    parent,
495                    id,
496                    positioner: positioner.clone(),
497                    parent_size: None,
498                    grab: true,
499                    close_with_children: false,
500                    input_zone: None,
501                },
502                Some(move || {
503                    Element::from(crate::widget::container(popup_menu.clone()).center(Length::Fill))
504                        .map(crate::action::app)
505                }),
506            )));
507        }
508    }
509}
510impl<Message> Widget<Message, crate::Theme, Renderer> for MenuBar<Message>
511where
512    Message: Clone + 'static,
513{
514    fn size(&self) -> iced_core::Size<Length> {
515        iced_core::Size::new(self.width, self.height)
516    }
517
518    fn diff(&mut self, tree: &mut Tree) {
519        let state = tree.state.downcast_mut::<MenuBarState>();
520        state
521            .inner
522            .with_data_mut(|inner| menu_roots_diff(&mut self.menu_roots, &mut inner.tree));
523    }
524
525    fn tag(&self) -> tree::Tag {
526        tree::Tag::of::<MenuBarState>()
527    }
528
529    fn state(&self) -> tree::State {
530        tree::State::new(MenuBarState::default())
531    }
532
533    fn children(&self) -> Vec<Tree> {
534        menu_roots_children(&self.menu_roots)
535    }
536
537    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
538        use super::flex;
539
540        let limits = limits.width(self.width).height(self.height);
541        let mut children = self
542            .menu_roots
543            .iter_mut()
544            .map(|root| &mut root.item)
545            .collect::<Vec<_>>();
546        // the first children of the tree are the menu roots items
547        let mut tree_children = tree
548            .children
549            .iter_mut()
550            .map(|t| &mut t.children[0])
551            .collect::<Vec<_>>();
552        flex::resolve_wrapper(
553            &flex::Axis::Horizontal,
554            renderer,
555            &limits,
556            self.padding,
557            self.spacing,
558            Alignment::Center,
559            &mut children,
560            &mut tree_children,
561        )
562    }
563
564    #[allow(clippy::too_many_lines)]
565    fn update(
566        &mut self,
567        tree: &mut Tree,
568        event: &event::Event,
569        layout: Layout<'_>,
570        view_cursor: Cursor,
571        renderer: &Renderer,
572        clipboard: &mut dyn Clipboard,
573        shell: &mut Shell<'_, Message>,
574        viewport: &Rectangle,
575    ) {
576        use event::Event::{Mouse, Touch};
577        use mouse::Button::Left;
578        use mouse::Event::ButtonReleased;
579        use touch::Event::{FingerLifted, FingerLost};
580
581        process_root_events(
582            &mut self.menu_roots,
583            view_cursor,
584            tree,
585            event,
586            layout,
587            renderer,
588            clipboard,
589            shell,
590            viewport,
591        );
592
593        let my_state = tree.state.downcast_mut::<MenuBarState>();
594
595        // The compositor dismissed our popup: nothing else tells this state about it.
596        #[cfg(wayland_platform)]
597        if let iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(
598            iced::event::wayland::Event::Popup(iced::event::wayland::PopupEvent::Done, _, popup),
599        )) = event
600        {
601            my_state.inner.with_data_mut(|d| {
602                if d.popup_id.get(&self.window_id) == Some(popup) {
603                    // submenus were dismissed with it
604                    d.popup_id.clear();
605                    d.reset();
606                }
607            });
608        }
609
610        // XXX this should reset the state if there are no other copies of the state, which implies no dropdown menus open.
611        let reset = self.window_id != window::Id::NONE
612            && my_state
613                .inner
614                .with_data(|d| !d.open && !d.active_root.is_empty());
615
616        let open = my_state.inner.with_data_mut(|state| {
617            if reset
618                && let Some(popup_id) = state.popup_id.get(&self.window_id).copied()
619                && let Some(handler) = self.on_surface_action.as_ref()
620            {
621                shell.publish((handler)(crate::surface::Action::DestroyPopup(popup_id)));
622                state.reset();
623            }
624            state.open
625        });
626
627        match event {
628            event::Event::Keyboard(iced_widget::core::keyboard::Event::KeyPressed {
629                key:
630                    iced_widget::core::keyboard::Key::Named(
631                        iced_widget::core::keyboard::key::Named::Escape,
632                    ),
633                ..
634            }) if open => {
635                my_state.inner.with_data_mut(|state| {
636                    let handler = self.on_surface_action.as_ref();
637                    close_innermost(state, &mut |id| {
638                        if let Some(handler) = handler {
639                            shell.publish((handler)(crate::surface::Action::DestroyPopup(id)));
640                        }
641                    });
642                });
643                shell.capture_event();
644            }
645            Mouse(mouse::Event::ButtonPressed(Left))
646            | Touch(touch::Event::FingerPressed { .. })
647                if view_cursor.is_over(layout.bounds()) =>
648            {
649                // TODO should we track that it has been pressed?
650                shell.capture_event();
651            }
652            Mouse(ButtonReleased(Left)) | Touch(FingerLifted { .. } | FingerLost { .. }) => {
653                let create_popup = my_state.inner.with_data_mut(|state| {
654                    let mut create_popup = false;
655                    if state.menu_states.is_empty() && view_cursor.is_over(layout.bounds()) {
656                        state.view_cursor = view_cursor;
657                        state.open = true;
658                        create_popup = true;
659                    } else if let Some(_id) = state.popup_id.remove(&self.window_id) {
660                        state.menu_states.clear();
661                        state.active_root.clear();
662                        state.open = false;
663                        #[cfg(wayland_platform)]
664                        {
665                            let surface_action = self.on_surface_action.as_ref().unwrap();
666                            shell.capture_event();
667
668                            shell.publish(surface_action(crate::surface::action::destroy_popup(
669                                _id,
670                            )));
671                        }
672                        state.view_cursor = view_cursor;
673                    }
674                    create_popup
675                });
676
677                if !create_popup {
678                    return;
679                }
680                shell.capture_event();
681                shell.request_redraw();
682                #[cfg(wayland_platform)]
683                if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland)) {
684                    self.create_popup(layout, view_cursor, renderer, shell, viewport, my_state);
685                }
686            }
687            Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::CursorEntered)
688                if open && view_cursor.is_over(layout.bounds()) =>
689            {
690                shell.request_redraw();
691                shell.capture_event();
692                #[cfg(wayland_platform)]
693                if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland)) {
694                    self.create_popup(layout, view_cursor, renderer, shell, viewport, my_state);
695                }
696            }
697            _ => (),
698        }
699    }
700
701    fn draw(
702        &self,
703        tree: &Tree,
704        renderer: &mut Renderer,
705        theme: &crate::Theme,
706        style: &renderer::Style,
707        layout: Layout<'_>,
708        view_cursor: Cursor,
709        viewport: &Rectangle,
710    ) {
711        let state = tree.state.downcast_ref::<MenuBarState>();
712        let cursor_pos = view_cursor.position().unwrap_or_default();
713        state.inner.with_data_mut(|state| {
714            let position = if state.open && (cursor_pos.x < 0.0 || cursor_pos.y < 0.0) {
715                state.view_cursor
716            } else {
717                view_cursor
718            };
719
720            // draw path highlight
721            if self.path_highlight.is_some() {
722                let mut is_overlay = true;
723                #[cfg(wayland_platform)]
724                if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
725                    && self.on_surface_action.is_some()
726                    && self.window_id != window::Id::NONE
727                {
728                    is_overlay = true;
729                };
730                let styling = theme.appearance(&self.style, is_overlay);
731                if let Some(active) = state.active_root.first() {
732                    let active_bounds = layout
733                        .children()
734                        .nth(*active)
735                        .expect("Active child not found in menu?")
736                        .bounds();
737                    let path_quad = renderer::Quad {
738                        bounds: active_bounds,
739                        border: Border {
740                            radius: styling.bar_border_radius.into(),
741                            ..Default::default()
742                        },
743                        shadow: Shadow::default(),
744                        snap: true,
745                    };
746
747                    renderer.fill_quad(path_quad, styling.path);
748                }
749            }
750
751            self.menu_roots
752                .iter()
753                .zip(&tree.children)
754                .zip(layout.children())
755                .for_each(|((root, t), lo)| {
756                    root.item.draw(
757                        &t.children[root.index],
758                        renderer,
759                        theme,
760                        style,
761                        lo,
762                        position,
763                        viewport,
764                    );
765                });
766        });
767    }
768
769    fn overlay<'b>(
770        &'b mut self,
771        tree: &'b mut Tree,
772        layout: Layout<'b>,
773        _renderer: &Renderer,
774        _viewport: &Rectangle,
775        translation: Vector,
776    ) -> Option<overlay::Element<'b, Message, crate::Theme, Renderer>> {
777        #[cfg(wayland_platform)]
778        if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
779            && self.on_surface_action.is_some()
780            && self.window_id != window::Id::NONE
781        {
782            return None;
783        }
784
785        let state = tree.state.downcast_ref::<MenuBarState>();
786        if state.inner.with_data(|state| !state.open) {
787            return None;
788        }
789
790        Some(
791            Menu {
792                tree: state.clone(),
793                menu_roots: std::borrow::Cow::Owned(self.menu_roots.clone()),
794                bounds_expand: self.bounds_expand,
795                menu_overlays_parent: false,
796                close_condition: self.close_condition,
797                item_width: self.item_width,
798                item_height: self.item_height,
799                bar_bounds: layout.bounds(),
800                main_offset: self.main_offset,
801                cross_offset: self.cross_offset,
802                root_bounds_list: layout.children().map(|lo| lo.bounds()).collect(),
803                path_highlight: self.path_highlight,
804                style: std::borrow::Cow::Borrowed(&self.style),
805                position: Point::new(translation.x, translation.y),
806                is_overlay: true,
807                window_id: window::Id::NONE,
808                depth: 0,
809                on_surface_action: self.on_surface_action.clone(),
810            }
811            .overlay(),
812        )
813    }
814}
815
816impl<Message> From<MenuBar<Message>> for Element<'_, Message, crate::Theme, Renderer>
817where
818    Message: Clone + 'static,
819{
820    fn from(value: MenuBar<Message>) -> Self {
821        Self::new(value)
822    }
823}
824
825#[allow(unused_results, clippy::too_many_arguments)]
826fn process_root_events<Message>(
827    menu_roots: &mut [MenuTree<Message>],
828    view_cursor: Cursor,
829    tree: &mut Tree,
830    event: &event::Event,
831    layout: Layout<'_>,
832    renderer: &Renderer,
833    clipboard: &mut dyn Clipboard,
834    shell: &mut Shell<'_, Message>,
835    viewport: &Rectangle,
836) {
837    for ((root, t), lo) in menu_roots
838        .iter_mut()
839        .zip(&mut tree.children)
840        .zip(layout.children())
841    {
842        // assert!(t.tag == tree::Tag::stateless());
843        root.item.update(
844            &mut t.children[root.index],
845            event,
846            lo,
847            view_cursor,
848            renderer,
849            clipboard,
850            shell,
851            viewport,
852        );
853    }
854}