1#[cfg(wayland_platform)]
7use crate::app::cosmic::{WINDOWING_SYSTEM, WindowingSystem};
8use crate::widget::menu::{
9 self, CloseCondition, Direction, ItemHeight, ItemWidth, MenuBarState, PathHighlight,
10 init_root_menu, menu_roots_diff,
11};
12use derive_setters::Setters;
13use iced::touch::Finger;
14use iced::{Event, Vector, keyboard, window};
15use iced_core::widget::{Tree, Widget, tree};
16use iced_core::{Length, Point, Size, mouse, touch};
17use std::collections::HashSet;
18use std::sync::Arc;
19
20use crate::widget::RcWrapper;
21
22pub fn context_menu<'a, Message: 'static + Clone>(
24 content: impl Into<crate::Element<'a, Message>>,
25 context_menu: Option<Vec<menu::Tree<Message>>>,
27) -> ContextMenu<'a, Message> {
28 let mut this = ContextMenu {
29 content: content.into(),
30 context_menu: context_menu.map(|menus| {
31 vec![menu::Tree::with_children(
32 crate::Element::from(crate::widget::Row::new()),
33 menus,
34 )]
35 }),
36 close_on_escape: true,
37 window_id: window::Id::RESERVED,
38 item_width: ItemWidth::Uniform(240),
39 on_open: None,
40 on_close: None,
41 on_surface_action: None,
42 };
43
44 if let Some(ref mut context_menu) = this.context_menu {
45 context_menu.iter_mut().for_each(menu::Tree::set_index);
46 }
47
48 this
49}
50
51#[derive(Setters)]
53#[must_use]
54pub struct ContextMenu<'a, Message> {
55 #[setters(skip)]
56 content: crate::Element<'a, Message>,
57 #[setters(skip)]
58 context_menu: Option<Vec<menu::Tree<Message>>>,
59 pub window_id: window::Id,
60 pub close_on_escape: bool,
61 pub item_width: ItemWidth,
63 #[setters(strip_option)]
65 pub on_open: Option<Message>,
66 #[setters(strip_option)]
68 pub on_close: Option<Message>,
69 #[setters(skip)]
70 pub(crate) on_surface_action:
71 Option<Arc<dyn Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static>>,
72}
73
74impl<Message: Clone + 'static> ContextMenu<'_, Message> {
75 fn report_open_state(
77 &self,
78 state: &mut LocalState<Message>,
79 shell: &mut iced_core::Shell<'_, Message>,
80 ) {
81 let open = state.menu_bar_state.inner.with_data(|d| d.open);
82 if open == state.reported_open {
83 return;
84 }
85 state.reported_open = open;
86 let message = if open { &self.on_open } else { &self.on_close };
87 if let Some(message) = message.clone() {
88 shell.publish(message);
89 }
90 }
91
92 #[cfg(wayland_platform)]
93 #[allow(clippy::too_many_lines)]
94 fn create_popup(
95 &mut self,
96 layout: iced_core::Layout<'_>,
97 view_cursor: iced_core::mouse::Cursor,
98 renderer: &crate::Renderer,
99 shell: &mut iced_core::Shell<'_, Message>,
100 viewport: &iced::Rectangle,
101 my_state: &mut LocalState<Message>,
102 ) {
103 if self.window_id != window::Id::NONE
104 && let Some(surface_action) = self.on_surface_action.as_ref()
105 {
106 use crate::surface::action::{LiveSettings, destroy_popup};
107 use crate::theme::THEME;
108 use crate::widget::menu::{Menu, StyleSheet as _};
109 use iced_runtime::platform_specific::wayland::CornerRadius;
110 use iced_runtime::platform_specific::wayland::popup::{
111 SctkPopupSettings, SctkPositioner,
112 };
113
114 let mut bounds = layout.bounds();
115 bounds.x = my_state.context_cursor.x;
116 bounds.y = my_state.context_cursor.y;
117
118 let (id, _root_list) = my_state.menu_bar_state.inner.with_data_mut(|state| {
119 if let Some(id) = state.popup_id.get(&self.window_id).copied() {
120 state.menu_states.clear();
122 state.active_root.clear();
123
124 shell.publish(surface_action(destroy_popup(id)));
125 state.view_cursor = view_cursor;
126 }
127 (
129 window::Id::unique(),
130 layout.children().map(|lo| lo.bounds()).collect::<Vec<_>>(),
131 )
132 });
133 let Some(context_menu) = self.context_menu.as_mut() else {
134 return;
135 };
136
137 let mut popup_menu: Menu<'static, _> = Menu {
138 tree: my_state.menu_bar_state.clone(),
139 menu_roots: std::borrow::Cow::Owned(context_menu.clone()),
140 bounds_expand: 16,
141 menu_overlays_parent: true,
142 close_condition: CloseCondition {
143 leave: false,
144 click_outside: true,
145 click_inside: true,
146 },
147 item_width: self.item_width,
148 item_height: ItemHeight::Dynamic(40),
149 bar_bounds: bounds,
150 main_offset: -(bounds.height as i32),
151 cross_offset: 0,
152 root_bounds_list: vec![bounds],
153 path_highlight: Some(PathHighlight::MenuActive),
154 style: std::borrow::Cow::Owned(crate::theme::menu_bar::MenuBarStyle::Default),
155 position: Point::new(0., 0.),
156 is_overlay: false,
157 window_id: id,
158 depth: 0,
159 on_surface_action: self.on_surface_action.clone(),
160 };
161
162 init_root_menu(
163 &mut popup_menu,
164 renderer,
165 shell,
166 view_cursor.position().unwrap(),
167 viewport.size(),
168 Vector::new(0., 0.),
169 layout.bounds(),
170 -bounds.height,
171 );
172 let (anchor_rect, _gravity) = my_state.menu_bar_state.inner.with_data_mut(|state| {
173 use iced::Rectangle;
174
175 state.popup_id.insert(self.window_id, id);
176 ({
177 let pos = view_cursor.position().unwrap_or_default();
178 Rectangle {
179 x: pos.x as i32,
180 y: pos.y as i32,
181 width: 1,
182 height: 1,
183 }
184 },
185 match (state.horizontal_direction, state.vertical_direction) {
186 (Direction::Positive, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
187 (Direction::Positive, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopRight,
188 (Direction::Negative, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomLeft,
189 (Direction::Negative, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopLeft,
190 })
191 });
192
193 let menu_node =
194 popup_menu.layout(renderer, iced::Limits::NONE.min_width(1.).min_height(1.));
195 let popup_size = menu_node.size();
196 let positioner = SctkPositioner {
197 size: Some((
198 popup_size.width.ceil() as u32 + 2,
199 popup_size.height.ceil() as u32 + 2,
200 )),
201 anchor_rect,
202 anchor: cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Anchor::None,
203 gravity: cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
204 reactive: true,
205 ..Default::default()
206 };
207 let parent = self.window_id;
208 let roots = my_state.roots.clone();
209 let t = THEME.lock().unwrap();
210 let styling = t.appearance(&crate::theme::menu_bar::MenuBarStyle::Default, false);
211 drop(t);
212 let rad = styling.menu_border_radius;
213
214 shell.publish(surface_action(crate::surface::action::simple_popup(
215 move || LiveSettings {
216 corners: Some(CornerRadius {
217 top_left: rad[0] as u32,
218 top_right: rad[1] as u32,
219 bottom_left: rad[2] as u32,
220 bottom_right: rad[3] as u32,
221 }),
222 ..Default::default()
223 },
224 move || SctkPopupSettings {
225 parent,
226 id,
227 positioner: positioner.clone(),
228 parent_size: None,
229 grab: true,
230 close_with_children: false,
231 input_zone: None,
232 },
233 Some(move || {
234 let mut popup_menu = popup_menu.clone();
236 popup_menu.menu_roots = std::borrow::Cow::Owned(roots.with_data(Clone::clone));
237 crate::Element::from(crate::widget::container(popup_menu).center(Length::Fill))
238 .map(crate::action::app)
239 }),
240 )));
241 }
242 }
243
244 pub fn on_surface_action(
245 mut self,
246 handler: impl Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static,
247 ) -> Self {
248 self.on_surface_action = Some(Arc::new(handler));
249 self
250 }
251}
252
253impl<Message: 'static + Clone> Widget<Message, crate::Theme, crate::Renderer>
254 for ContextMenu<'_, Message>
255{
256 fn tag(&self) -> tree::Tag {
257 tree::Tag::of::<LocalState<Message>>()
258 }
259
260 fn state(&self) -> tree::State {
261 #[allow(clippy::default_trait_access)]
262 tree::State::new(LocalState {
263 context_cursor: Point::default(),
264 fingers_pressed: Default::default(),
265 menu_bar_state: Default::default(),
266 reported_open: false,
267 roots: RcWrapper::new(self.context_menu.clone().unwrap_or_default()),
268 reshape: false,
269 })
270 }
271
272 fn children(&self) -> Vec<Tree> {
273 let mut children = Vec::with_capacity(if self.context_menu.is_some() { 2 } else { 1 });
274
275 children.push(Tree::new(self.content.as_widget()));
276
277 if let Some(ref context_menu) = self.context_menu {
279 let mut tree = Tree::empty();
280 tree.children = context_menu
281 .iter()
282 .map(|root| {
283 let mut tree = Tree::empty();
284 let flat = root
285 .flattern()
286 .iter()
287 .map(|mt| Tree::new(mt.item.clone()))
288 .collect();
289 tree.children = flat;
290 tree
291 })
292 .collect();
293
294 children.push(tree);
295 }
296
297 children
298 }
299
300 fn diff(&mut self, tree: &mut Tree) {
301 tree.diff_children(std::slice::from_mut(&mut self.content));
302 let state = tree.state.downcast_mut::<LocalState<Message>>();
303 if let Some(context_menu) = self.context_menu.as_mut() {
304 let popup_open = state
309 .menu_bar_state
310 .inner
311 .with_data(|d| !d.popup_id.is_empty());
312 let shape = |roots: &Vec<menu::Tree<Message>>| -> Vec<tree::Tag> {
313 roots.first().map_or_else(Vec::new, |root| {
314 root.flattern().iter().map(|mt| mt.item.tag()).collect()
315 })
316 };
317 if popup_open && state.roots.with_data(shape) != shape(context_menu) {
318 state.reshape = true;
319 return;
320 }
321 state.menu_bar_state.inner.with_data_mut(|inner| {
322 menu_roots_diff(context_menu, &mut inner.tree);
323 });
324 state
325 .roots
326 .with_data_mut(|roots| roots.clone_from(context_menu));
327 }
328
329 }
338
339 fn size(&self) -> Size<Length> {
340 self.content.as_widget().size()
341 }
342
343 fn layout(
344 &mut self,
345 tree: &mut Tree,
346 renderer: &crate::Renderer,
347 limits: &iced_core::layout::Limits,
348 ) -> iced_core::layout::Node {
349 self.content
350 .as_widget_mut()
351 .layout(&mut tree.children[0], renderer, limits)
352 }
353
354 fn draw(
355 &self,
356 tree: &Tree,
357 renderer: &mut crate::Renderer,
358 theme: &crate::Theme,
359 style: &iced_core::renderer::Style,
360 layout: iced_core::Layout<'_>,
361 cursor: iced_core::mouse::Cursor,
362 viewport: &iced::Rectangle,
363 ) {
364 self.content.as_widget().draw(
365 &tree.children[0],
366 renderer,
367 theme,
368 style,
369 layout,
370 cursor,
371 viewport,
372 );
373 }
374
375 fn mouse_interaction(
376 &self,
377 tree: &Tree,
378 layout: iced_core::Layout<'_>,
379 cursor: iced_core::mouse::Cursor,
380 viewport: &iced::Rectangle,
381 renderer: &crate::Renderer,
382 ) -> mouse::Interaction {
383 self.content.as_widget().mouse_interaction(
384 &tree.children[0],
385 layout,
386 cursor,
387 viewport,
388 renderer,
389 )
390 }
391
392 fn drag_destinations(
393 &self,
394 tree: &Tree,
395 layout: iced_core::Layout<'_>,
396 renderer: &crate::Renderer,
397 dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
398 ) {
399 self.content.as_widget().drag_destinations(
400 &tree.children[0],
401 layout,
402 renderer,
403 dnd_rectangles,
404 );
405 }
406
407 fn operate(
408 &mut self,
409 tree: &mut Tree,
410 layout: iced_core::Layout<'_>,
411 renderer: &crate::Renderer,
412 operation: &mut dyn iced_core::widget::Operation<()>,
413 ) {
414 self.content
415 .as_widget_mut()
416 .operate(&mut tree.children[0], layout, renderer, operation);
417 }
418
419 #[allow(clippy::too_many_lines)]
420 fn update(
421 &mut self,
422 tree: &mut Tree,
423 event: &iced::Event,
424 layout: iced_core::Layout<'_>,
425 cursor: iced_core::mouse::Cursor,
426 renderer: &crate::Renderer,
427 clipboard: &mut dyn iced_core::Clipboard,
428 shell: &mut iced_core::Shell<'_, Message>,
429 viewport: &iced::Rectangle,
430 ) {
431 let state = tree.state.downcast_mut::<LocalState<Message>>();
432 let bounds = layout.bounds();
433
434 #[cfg(wayland_platform)]
436 if let iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(
437 iced::event::wayland::Event::Popup(iced::event::wayland::PopupEvent::Done, _, popup),
438 )) = event
439 {
440 state.menu_bar_state.inner.with_data_mut(|d| {
441 if d.popup_id.get(&self.window_id) == Some(popup) {
442 d.popup_id.remove(&self.window_id);
443 d.reset();
444 }
445 });
446 }
447
448 #[cfg(wayland_platform)]
450 if state.reshape {
451 state.reshape = false;
452 if state.menu_bar_state.inner.with_data(|d| d.open) {
453 if let Some(context_menu) = self.context_menu.as_mut() {
454 state.menu_bar_state.inner.with_data_mut(|inner| {
455 menu_roots_diff(context_menu, &mut inner.tree);
456 });
457 state
458 .roots
459 .with_data_mut(|roots| roots.clone_from(context_menu));
460 }
461 let view_cursor = state.menu_bar_state.inner.with_data(|d| d.view_cursor);
462 self.create_popup(layout, view_cursor, renderer, shell, viewport, state);
463 }
464 }
465
466 let reset = self.window_id != window::Id::NONE
468 && state
469 .menu_bar_state
470 .inner
471 .with_data(|d| !d.open && !d.active_root.is_empty());
472
473 let open = state.menu_bar_state.inner.with_data_mut(|state| {
474 if reset
475 && let Some(popup_id) = state.popup_id.get(&self.window_id).copied()
476 && let Some(handler) = self.on_surface_action.as_ref()
477 {
478 shell.publish((handler)(crate::surface::Action::DestroyPopup(popup_id)));
479 state.reset();
480 }
481 state.open
482 });
483 let mut was_open = false;
484 if matches!(event,
485 Event::Keyboard(keyboard::Event::KeyPressed {
486 key: keyboard::Key::Named(keyboard::key::Named::Escape),
487 ..
488 })
489 | Event::Mouse(mouse::Event::ButtonPressed(
490 mouse::Button::Right | mouse::Button::Left,
491 ))
492 | Event::Touch(touch::Event::FingerPressed { .. })
493 if open )
494 {
495 state.menu_bar_state.inner.with_data_mut(|state| {
496 was_open = true;
497 state.menu_states.clear();
498 state.active_root.clear();
499 state.open = false;
500
501 #[cfg(wayland_platform)]
502 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
503 && let Some(id) = state.popup_id.remove(&self.window_id)
504 {
505 {
506 let surface_action = self.on_surface_action.as_ref().unwrap();
507 shell.publish(surface_action(crate::surface::action::destroy_popup(id)));
508 }
509 state.view_cursor = cursor;
510 }
511 });
512 }
513
514 if !was_open && cursor.is_over(bounds) {
515 let fingers_pressed = state.fingers_pressed.len();
516
517 match event {
518 Event::Touch(touch::Event::FingerPressed { id, .. }) => {
519 state.fingers_pressed.insert(*id);
520 }
521
522 Event::Touch(touch::Event::FingerLifted { id, .. }) => {
523 state.fingers_pressed.remove(id);
524 }
525
526 _ => (),
527 }
528
529 if !was_open
531 && self.context_menu.is_some()
532 && (right_button_released(event) || (touch_lifted(event) && fingers_pressed == 2))
533 {
534 state.context_cursor = cursor.position().unwrap_or_default();
535 let state = tree.state.downcast_mut::<LocalState<Message>>();
536 state.menu_bar_state.inner.with_data_mut(|state| {
537 state.open = true;
538 state.view_cursor = cursor;
539 });
540 #[cfg(wayland_platform)]
541 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland)) {
542 self.create_popup(layout, cursor, renderer, shell, viewport, state);
543 }
544
545 shell.request_redraw();
546 shell.capture_event();
547 self.report_open_state(tree.state.downcast_mut::<LocalState<Message>>(), shell);
548 return;
549 } else if !was_open && right_button_released(event)
550 || (touch_lifted(event))
551 || left_button_released(event)
552 {
553 state.menu_bar_state.inner.with_data_mut(|state| {
554 was_open = true;
555 state.menu_states.clear();
556 state.active_root.clear();
557 state.open = false;
558
559 #[cfg(wayland_platform)]
560 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
561 && let Some(id) = state.popup_id.remove(&self.window_id)
562 {
563 {
564 let surface_action = self.on_surface_action.as_ref().unwrap();
565 shell
566 .publish(surface_action(crate::surface::action::destroy_popup(id)));
567 }
568 state.view_cursor = cursor;
569 }
570 });
571 }
572 }
573 self.content.as_widget_mut().update(
574 &mut tree.children[0],
575 event,
576 layout,
577 cursor,
578 renderer,
579 clipboard,
580 shell,
581 viewport,
582 );
583 self.report_open_state(tree.state.downcast_mut::<LocalState<Message>>(), shell);
584 }
585
586 fn overlay<'b>(
587 &'b mut self,
588 tree: &'b mut Tree,
589 layout: iced_core::Layout<'b>,
590 renderer: &crate::Renderer,
591 viewport: &iced::Rectangle,
592 translation: Vector,
593 ) -> Option<iced_core::overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
594 let content = self.content.as_widget_mut().overlay(
596 &mut tree.children[0],
597 layout,
598 renderer,
599 viewport,
600 translation,
601 );
602
603 #[cfg(wayland_platform)]
604 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
605 && self.window_id != window::Id::NONE
606 && self.on_surface_action.is_some()
607 {
608 return content;
609 }
610
611 let state = tree.state.downcast_ref::<LocalState<Message>>();
612 let Some(context_menu) = self.context_menu.as_mut() else {
613 return content;
614 };
615 if !state.menu_bar_state.inner.with_data(|state| state.open) {
616 return content;
617 }
618
619 let bounds = iced::Rectangle::new(state.context_cursor, Size::new(1.0, 1.0));
621 let menu = crate::widget::menu::Menu {
622 tree: state.menu_bar_state.clone(),
623 menu_roots: std::borrow::Cow::Owned(context_menu.clone()),
624 bounds_expand: 16,
625 menu_overlays_parent: true,
626 close_condition: CloseCondition {
627 leave: false,
628 click_outside: true,
629 click_inside: true,
630 },
631 item_width: self.item_width,
632 item_height: ItemHeight::Dynamic(40),
633 bar_bounds: bounds,
634 main_offset: 0,
635 cross_offset: 0,
636 root_bounds_list: vec![bounds],
637 path_highlight: Some(PathHighlight::MenuActive),
638 style: std::borrow::Cow::Borrowed(&crate::theme::menu_bar::MenuBarStyle::Default),
639 position: Point::new(translation.x, translation.y),
640 is_overlay: true,
641 window_id: window::Id::NONE,
642 depth: 0,
643 on_surface_action: None,
644 }
645 .overlay();
646
647 Some(match content {
648 Some(content) => {
649 iced_core::overlay::Group::with_children(vec![content, menu]).overlay()
650 }
651 None => menu,
652 })
653 }
654
655 #[cfg(feature = "a11y")]
656 fn a11y_nodes(
658 &self,
659 layout: iced_core::Layout<'_>,
660 state: &Tree,
661 p: mouse::Cursor,
662 ) -> iced_accessibility::A11yTree {
663 let c_state = &state.children[0];
664 self.content.as_widget().a11y_nodes(layout, c_state, p)
665 }
666}
667
668impl<'a, Message: Clone + 'static> From<ContextMenu<'a, Message>> for crate::Element<'a, Message> {
669 fn from(widget: ContextMenu<'a, Message>) -> Self {
670 Self::new(widget)
671 }
672}
673
674fn right_button_released(event: &Event) -> bool {
675 matches!(
676 event,
677 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right,))
678 )
679}
680
681fn left_button_released(event: &Event) -> bool {
682 matches!(
683 event,
684 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left,))
685 )
686}
687
688fn touch_lifted(event: &Event) -> bool {
689 matches!(event, Event::Touch(touch::Event::FingerLifted { .. }))
690}
691
692pub struct LocalState<Message> {
693 context_cursor: Point,
694 fingers_pressed: HashSet<Finger>,
695 menu_bar_state: MenuBarState,
696 reported_open: bool,
697 roots: RcWrapper<Vec<menu::Tree<Message>>>,
698 reshape: bool,
700}