cosmic/widget/
context_menu.rs

1// Copyright 2024 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4//! A context menu is a menu in a graphical user interface that appears upon user interaction, such as a right-click mouse operation.
5
6use crate::widget::menu::{
7    self, CloseCondition, ItemHeight, ItemWidth, MenuBarState, PathHighlight,
8};
9use derive_setters::Setters;
10use iced::touch::Finger;
11use iced::{Event, Vector};
12use iced_core::widget::{Tree, Widget, tree};
13use iced_core::{Length, Point, Size, event, mouse, touch};
14use std::collections::HashSet;
15
16/// A context menu is a menu in a graphical user interface that appears upon user interaction, such as a right-click mouse operation.
17pub fn context_menu<'a, Message: 'a>(
18    content: impl Into<crate::Element<'a, Message>> + 'a,
19    // on_context: Message,
20    context_menu: Option<Vec<menu::Tree<'a, Message>>>,
21) -> ContextMenu<'a, Message> {
22    let mut this = ContextMenu {
23        content: content.into(),
24        context_menu: context_menu.map(|menus| {
25            vec![menu::Tree::with_children(
26                crate::widget::row::<'static, Message>(),
27                menus,
28            )]
29        }),
30    };
31
32    if let Some(ref mut context_menu) = this.context_menu {
33        context_menu.iter_mut().for_each(menu::Tree::set_index);
34    }
35
36    this
37}
38
39/// A context menu is a menu in a graphical user interface that appears upon user interaction, such as a right-click mouse operation.
40#[derive(Setters)]
41#[must_use]
42pub struct ContextMenu<'a, Message> {
43    #[setters(skip)]
44    content: crate::Element<'a, Message>,
45    #[setters(skip)]
46    context_menu: Option<Vec<menu::Tree<'a, Message>>>,
47}
48
49impl<Message: Clone> Widget<Message, crate::Theme, crate::Renderer> for ContextMenu<'_, Message> {
50    fn tag(&self) -> tree::Tag {
51        tree::Tag::of::<LocalState>()
52    }
53
54    fn state(&self) -> tree::State {
55        #[allow(clippy::default_trait_access)]
56        tree::State::new(LocalState {
57            context_cursor: Point::default(),
58            fingers_pressed: Default::default(),
59        })
60    }
61
62    fn children(&self) -> Vec<Tree> {
63        let mut children = Vec::with_capacity(if self.context_menu.is_some() { 2 } else { 1 });
64
65        children.push(Tree::new(self.content.as_widget()));
66
67        // Assign the context menu's elements as this widget's children.
68        if let Some(ref context_menu) = self.context_menu {
69            let mut tree = Tree::empty();
70            tree.state = tree::State::new(MenuBarState::default());
71            tree.children = context_menu
72                .iter()
73                .map(|root| {
74                    let mut tree = Tree::empty();
75                    let flat = root
76                        .flattern()
77                        .iter()
78                        .map(|mt| Tree::new(mt.item.as_widget()))
79                        .collect();
80                    tree.children = flat;
81                    tree
82                })
83                .collect();
84
85            children.push(tree);
86        }
87
88        children
89    }
90
91    fn diff(&mut self, tree: &mut Tree) {
92        tree.children[0].diff(self.content.as_widget_mut());
93
94        // if let Some(ref mut context_menus) = self.context_menu {
95        //     for (menu, tree) in context_menus
96        //         .iter_mut()
97        //         .zip(tree.children[1].children.iter_mut())
98        //     {
99        //         menu.item.as_widget_mut().diff(tree);
100        //     }
101        // }
102    }
103
104    fn size(&self) -> Size<Length> {
105        self.content.as_widget().size()
106    }
107
108    fn layout(
109        &self,
110        tree: &mut Tree,
111        renderer: &crate::Renderer,
112        limits: &iced_core::layout::Limits,
113    ) -> iced_core::layout::Node {
114        self.content
115            .as_widget()
116            .layout(&mut tree.children[0], renderer, limits)
117    }
118
119    fn draw(
120        &self,
121        tree: &Tree,
122        renderer: &mut crate::Renderer,
123        theme: &crate::Theme,
124        style: &iced_core::renderer::Style,
125        layout: iced_core::Layout<'_>,
126        cursor: iced_core::mouse::Cursor,
127        viewport: &iced::Rectangle,
128    ) {
129        self.content.as_widget().draw(
130            &tree.children[0],
131            renderer,
132            theme,
133            style,
134            layout,
135            cursor,
136            viewport,
137        );
138    }
139
140    fn operate(
141        &self,
142        tree: &mut Tree,
143        layout: iced_core::Layout<'_>,
144        renderer: &crate::Renderer,
145        operation: &mut dyn iced_core::widget::Operation<()>,
146    ) {
147        self.content
148            .as_widget()
149            .operate(&mut tree.children[0], layout, renderer, operation);
150    }
151
152    fn on_event(
153        &mut self,
154        tree: &mut Tree,
155        event: iced::Event,
156        layout: iced_core::Layout<'_>,
157        cursor: iced_core::mouse::Cursor,
158        renderer: &crate::Renderer,
159        clipboard: &mut dyn iced_core::Clipboard,
160        shell: &mut iced_core::Shell<'_, Message>,
161        viewport: &iced::Rectangle,
162    ) -> iced_core::event::Status {
163        let state = tree.state.downcast_mut::<LocalState>();
164        let bounds = layout.bounds();
165
166        if cursor.is_over(bounds) {
167            let fingers_pressed = state.fingers_pressed.len();
168
169            match event {
170                Event::Touch(touch::Event::FingerPressed { id, .. }) => {
171                    state.fingers_pressed.insert(id);
172                }
173
174                Event::Touch(touch::Event::FingerLifted { id, .. }) => {
175                    state.fingers_pressed.remove(&id);
176                }
177
178                _ => (),
179            }
180
181            // Present a context menu on a right click event.
182            if self.context_menu.is_some()
183                && (right_button_released(&event) || (touch_lifted(&event) && fingers_pressed == 2))
184            {
185                state.context_cursor = cursor.position().unwrap_or_default();
186
187                let menu_state = tree.children[1].state.downcast_mut::<MenuBarState>();
188                menu_state.open = true;
189                menu_state.view_cursor = cursor;
190
191                return event::Status::Captured;
192            }
193        }
194
195        self.content.as_widget_mut().on_event(
196            &mut tree.children[0],
197            event,
198            layout,
199            cursor,
200            renderer,
201            clipboard,
202            shell,
203            viewport,
204        )
205    }
206
207    fn overlay<'b>(
208        &'b mut self,
209        tree: &'b mut Tree,
210        layout: iced_core::Layout<'_>,
211        _renderer: &crate::Renderer,
212        translation: Vector,
213    ) -> Option<iced_core::overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
214        let state = tree.state.downcast_ref::<LocalState>();
215
216        let Some(context_menu) = self.context_menu.as_mut() else {
217            return None;
218        };
219
220        if !tree.children[1].state.downcast_ref::<MenuBarState>().open {
221            return None;
222        }
223
224        let mut bounds = layout.bounds();
225        bounds.x = state.context_cursor.x;
226        bounds.y = state.context_cursor.y;
227
228        Some(
229            crate::widget::menu::Menu {
230                tree: &mut tree.children[1],
231                menu_roots: context_menu,
232                bounds_expand: 16,
233                menu_overlays_parent: true,
234                close_condition: CloseCondition {
235                    leave: false,
236                    click_outside: true,
237                    click_inside: true,
238                },
239                item_width: ItemWidth::Uniform(240),
240                item_height: ItemHeight::Dynamic(40),
241                bar_bounds: bounds,
242                main_offset: -(bounds.height as i32),
243                cross_offset: 0,
244                root_bounds_list: vec![bounds],
245                path_highlight: Some(PathHighlight::MenuActive),
246                style: &crate::theme::menu_bar::MenuBarStyle::Default,
247                position: Point::new(translation.x, translation.y),
248            }
249            .overlay(),
250        )
251    }
252
253    #[cfg(feature = "a11y")]
254    /// get the a11y nodes for the widget
255    fn a11y_nodes(
256        &self,
257        layout: iced_core::Layout<'_>,
258        state: &Tree,
259        p: mouse::Cursor,
260    ) -> iced_accessibility::A11yTree {
261        let c_state = &state.children[0];
262        self.content.as_widget().a11y_nodes(layout, c_state, p)
263    }
264}
265
266impl<'a, Message: Clone + 'a> From<ContextMenu<'a, Message>> for crate::Element<'a, Message> {
267    fn from(widget: ContextMenu<'a, Message>) -> Self {
268        Self::new(widget)
269    }
270}
271
272fn right_button_released(event: &Event) -> bool {
273    matches!(
274        event,
275        Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right,))
276    )
277}
278
279fn touch_lifted(event: &Event) -> bool {
280    matches!(event, Event::Touch(touch::Event::FingerLifted { .. }))
281}
282
283pub struct LocalState {
284    context_cursor: Point,
285    fingers_pressed: HashSet<Finger>,
286}