1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use gpui::{
7 Anchor, AnyElement, App, Bounds, Context, DismissEvent, Element, ElementId, Entity,
8 FocusHandle, Focusable, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId,
9 InteractiveElement, IntoElement, LayoutId, LongPressEvent, MouseButton, MouseDownEvent,
10 ParentElement, Pixels, Point, Position, Style, StyleRefinement, Styled, Subscription,
11 TouchPhase, Window, anchored, deferred, div, px,
12};
13
14use crate::{input::AnyInputState, menu::PopupMenu, root::WindowState};
15
16pub trait ContextMenuExt: InteractiveElement + ParentElement + Styled {
18 #[track_caller]
23 fn context_menu(
24 mut self,
25 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
26 ) -> ContextMenu<Self>
27 where
28 Self: Sized,
29 {
30 let caller = std::panic::Location::caller();
33 let id = self
34 .interactivity()
35 .element_id
36 .clone()
37 .map(|id| ElementId::Name(format!("context-menu-{:?}", id).into()))
38 .unwrap_or_else(|| ElementId::CodeLocation(*caller));
39 ContextMenu::new(id, self).menu(f)
40 }
41}
42
43impl<E: InteractiveElement + ParentElement + Styled> ContextMenuExt for E {}
44
45pub struct ContextMenu<E: ParentElement + Styled + Sized> {
47 id: ElementId,
48 element: Option<E>,
49 menu: Option<Rc<MenuBuilder>>,
50 _ignore_style: StyleRefinement,
52 anchor: Anchor,
53}
54
55impl<E: ParentElement + Styled> ContextMenu<E> {
56 pub fn new(id: impl Into<ElementId>, element: E) -> Self {
58 Self {
59 id: id.into(),
60 element: Some(element),
61 menu: None,
62 anchor: Anchor::TopLeft,
63 _ignore_style: StyleRefinement::default(),
64 }
65 }
66
67 #[must_use]
69 fn menu<F>(mut self, builder: F) -> Self
70 where
71 F: Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
72 {
73 self.menu = Some(Rc::new(builder));
74 self
75 }
76
77 fn with_element_state<R>(
78 &mut self,
79 id: &GlobalElementId,
80 window: &mut Window,
81 cx: &mut App,
82 f: impl FnOnce(&mut Self, &mut ContextMenuState, &mut Window, &mut App) -> R,
83 ) -> R {
84 window.with_optional_element_state::<ContextMenuState, _>(
85 Some(id),
86 |element_state, window| {
87 let mut element_state = element_state.unwrap().unwrap_or_default();
88 let result = f(self, &mut element_state, window, cx);
89 (result, Some(element_state))
90 },
91 )
92 }
93}
94
95impl<E: ParentElement + Styled> ParentElement for ContextMenu<E> {
96 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
97 if let Some(element) = &mut self.element {
98 element.extend(elements);
99 }
100 }
101}
102
103impl<E: ParentElement + Styled> Styled for ContextMenu<E> {
104 fn style(&mut self) -> &mut StyleRefinement {
105 if let Some(element) = &mut self.element {
106 element.style()
107 } else {
108 &mut self._ignore_style
109 }
110 }
111}
112
113impl<E: ParentElement + Styled + IntoElement + 'static> IntoElement for ContextMenu<E> {
114 type Element = Self;
115
116 fn into_element(self) -> Self::Element {
117 self
118 }
119}
120
121struct ContextMenuSharedState {
122 menu_view: Option<Entity<PopupMenu>>,
123 selection_input: Option<AnyInputState>,
126 open: bool,
127 position: Point<Pixels>,
128 trigger_focus_handle: Option<FocusHandle>,
133 _subscription: Option<Subscription>,
134}
135
136pub struct ContextMenuState {
137 element: Option<AnyElement>,
138 draws_menu: Rc<Cell<bool>>,
146 shared_state: Rc<RefCell<ContextMenuSharedState>>,
147}
148
149impl Default for ContextMenuState {
150 fn default() -> Self {
151 Self {
152 element: None,
153 draws_menu: Rc::default(),
154 shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
155 menu_view: None,
156 selection_input: None,
157 open: false,
158 position: Default::default(),
159 trigger_focus_handle: None,
160 _subscription: None,
161 })),
162 }
163 }
164}
165
166struct DeferredMenu {
172 draws: Rc<Cell<bool>>,
173 menu_view: Entity<PopupMenu>,
174 position: Point<Pixels>,
175 anchor: Anchor,
176 menu: Option<AnyElement>,
177}
178
179impl DeferredMenu {
180 fn build_menu(&self, window: &mut Window) -> AnyElement {
181 deferred(
182 anchored().child(
183 div()
184 .w(window.bounds().size.width)
185 .h(window.bounds().size.height)
186 .on_scroll_wheel(|_, _, cx| {
187 cx.stop_propagation();
188 })
189 .child(
190 anchored()
191 .position(self.position)
192 .snap_to_window_with_margin(px(8.))
193 .anchor(self.anchor)
194 .child(self.menu_view.clone()),
195 ),
196 ),
197 )
198 .with_priority(gpui_base::POPUP_PRIORITY)
199 .into_any()
200 }
201}
202
203impl IntoElement for DeferredMenu {
204 type Element = Self;
205
206 fn into_element(self) -> Self::Element {
207 self
208 }
209}
210
211impl Element for DeferredMenu {
212 type RequestLayoutState = ();
213 type PrepaintState = ();
214
215 fn id(&self) -> Option<ElementId> {
216 None
217 }
218
219 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
220 None
221 }
222
223 fn request_layout(
224 &mut self,
225 _: Option<&GlobalElementId>,
226 _: Option<&InspectorElementId>,
227 window: &mut Window,
228 cx: &mut App,
229 ) -> (LayoutId, ()) {
230 let style = Style {
233 position: Position::Absolute,
234 ..Style::default()
235 };
236 (window.request_layout(style, None, cx), ())
237 }
238
239 fn prepaint(
240 &mut self,
241 _: Option<&GlobalElementId>,
242 _: Option<&InspectorElementId>,
243 bounds: Bounds<Pixels>,
244 _: &mut (),
245 window: &mut Window,
246 cx: &mut App,
247 ) {
248 if !self.draws.get() {
249 return;
250 }
251 let mut menu = self.build_menu(window);
252 menu.prepaint_as_root(bounds.origin, window.viewport_size().into(), window, cx);
253 self.menu = Some(menu);
254 }
255
256 fn paint(
257 &mut self,
258 _: Option<&GlobalElementId>,
259 _: Option<&InspectorElementId>,
260 _: Bounds<Pixels>,
261 _: &mut (),
262 _: &mut (),
263 window: &mut Window,
264 cx: &mut App,
265 ) {
266 if let Some(menu) = &mut self.menu {
267 menu.paint(window, cx);
268 }
269 }
270}
271
272impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
273 type RequestLayoutState = ContextMenuState;
274 type PrepaintState = Hitbox;
275
276 fn id(&self) -> Option<ElementId> {
277 Some(self.id.clone())
278 }
279
280 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
281 None
282 }
283
284 fn request_layout(
285 &mut self,
286 id: Option<&gpui::GlobalElementId>,
287 _: Option<&gpui::InspectorElementId>,
288 window: &mut Window,
289 cx: &mut App,
290 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
291 let anchor = self.anchor;
292
293 self.with_element_state(
294 id.unwrap(),
295 window,
296 cx,
297 |this, state: &mut ContextMenuState, window, cx| {
298 let (position, open) = {
299 let shared_state = state.shared_state.borrow();
300 (shared_state.position, shared_state.open)
301 };
302 state
303 .shared_state
304 .borrow_mut()
305 .trigger_focus_handle
306 .get_or_insert_with(|| cx.focus_handle());
307 let menu_view = state.shared_state.borrow().menu_view.clone();
308 let draws_menu = Rc::new(Cell::new(false));
309 let menu_element = menu_view
310 .filter(|menu| open && !menu.read(cx).is_empty())
311 .map(|menu_view| DeferredMenu {
312 draws: draws_menu.clone(),
313 menu_view,
314 position,
315 anchor,
316 menu: None,
317 });
318
319 let mut element = this
320 .element
321 .take()
322 .expect("Element should exists.")
323 .children(menu_element)
324 .into_any_element();
325
326 let layout_id = element.request_layout(window, cx);
327
328 (
329 layout_id,
330 ContextMenuState {
331 element: Some(element),
332 draws_menu,
333 shared_state: state.shared_state.clone(),
334 },
335 )
336 },
337 )
338 }
339
340 fn prepaint(
341 &mut self,
342 _: Option<&gpui::GlobalElementId>,
343 _: Option<&InspectorElementId>,
344 bounds: gpui::Bounds<gpui::Pixels>,
345 request_layout: &mut Self::RequestLayoutState,
346 window: &mut Window,
347 cx: &mut App,
348 ) -> Self::PrepaintState {
349 if let Some(trigger_focus) = request_layout
350 .shared_state
351 .borrow()
352 .trigger_focus_handle
353 .as_ref()
354 {
355 window.set_focus_handle(trigger_focus, cx);
356 }
357 let position = request_layout.shared_state.borrow().position;
358 request_layout.draws_menu.set(bounds.contains(&position));
359 if let Some(element) = &mut request_layout.element {
360 element.prepaint(window, cx);
361 }
362 window.insert_hitbox(bounds, HitboxBehavior::Normal)
363 }
364
365 fn paint(
366 &mut self,
367 _: Option<&gpui::GlobalElementId>,
368 _: Option<&InspectorElementId>,
369 _: gpui::Bounds<gpui::Pixels>,
370 request_layout: &mut Self::RequestLayoutState,
371 hitbox: &mut Self::PrepaintState,
372 window: &mut Window,
373 cx: &mut App,
374 ) {
375 let builder = self.menu.clone();
376 let shared_state = request_layout.shared_state.clone();
377
378 window.on_mouse_event({
383 let shared_state = shared_state.clone();
384 let builder = builder.clone();
385 let hitbox = hitbox.clone();
386 move |event: &LongPressEvent, phase, window, cx| {
387 if phase.bubble()
388 && event.phase == TouchPhase::Started
389 && !window.default_prevented()
390 && hitbox.is_hovered(window)
391 && !gpui_base::TextSelection::is_selectable_at(event.start_position, window, cx)
392 {
393 window.prevent_default();
394 open_menu(&shared_state, &builder, event.start_position, window, cx);
395 }
396 }
397 });
398
399 if let Some(element) = &mut request_layout.element {
400 element.paint(window, cx);
401 }
402
403 let hitbox = hitbox.clone();
405 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
406 if phase.bubble() && event.button == MouseButton::Right && hitbox.is_hovered(window) {
407 open_menu(&shared_state, &builder, event.position, window, cx);
408 }
409 });
410 }
411}
412
413type MenuBuilder = dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu;
414
415fn open_menu(
417 shared_state: &Rc<RefCell<ContextMenuSharedState>>,
418 builder: &Option<Rc<MenuBuilder>>,
419 position: Point<Pixels>,
420 window: &mut Window,
421 cx: &mut App,
422) {
423 let previous_focus_handle = window.focused(cx).and_then(|focused| {
426 let shared_state = shared_state.borrow();
427 match shared_state.menu_view.as_ref() {
428 Some(menu) if menu.read(cx).focus_handle == focused => {
429 menu.read(cx).previous_focus_handle.clone()
430 }
431 _ => Some(focused),
432 }
433 });
434
435 let previous_selection_input = {
437 let state = shared_state.borrow();
438 let menu_focused = state.menu_view.as_ref().is_some_and(|menu| {
439 let focus = menu.focus_handle(cx);
440 focus.is_focused(window) || focus.contains_focused(window, cx)
441 });
442 state
443 .selection_input
444 .as_ref()
445 .filter(|input| menu_focused || input.focus_handle(cx).is_focused(window))
446 .cloned()
447 };
448 {
449 let mut shared_state = shared_state.borrow_mut();
450 shared_state.menu_view = None;
453 shared_state.selection_input = None;
454 shared_state._subscription = None;
455 shared_state.position = position;
456 shared_state.open = true;
457 }
458
459 window.defer(cx, {
461 let shared_state = shared_state.clone();
462 let builder = builder.clone();
463 move |window, cx| {
464 let selection_input =
468 WindowState::try_update(window, cx, |state, _, _| state.focused_input.clone())
469 .flatten()
470 .filter(|input| input.focus_handle(cx).is_focused(window))
471 .or(previous_selection_input);
472 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
473 let Some(build) = &builder else {
474 return menu;
475 };
476 build(menu, window, cx)
477 });
478 let trigger_focus_handle = shared_state.borrow().trigger_focus_handle.clone();
479 menu.update(cx, |menu, cx| {
480 menu.set_trigger_focus(trigger_focus_handle, cx);
481 menu.set_previous_focus(previous_focus_handle, cx);
482 });
483
484 let selection_input = selection_input.filter(|input| {
488 let Some(bounds) = input.input_bounds(cx) else {
489 return false;
490 };
491 match menu.read(cx).action_context.as_ref() {
492 Some(target) => target == &input.focus_handle(cx),
493 None => bounds.contains(&position),
494 }
495 });
496 if let Some(input) = selection_input.as_ref() {
497 input.set_selection_focus(Some(menu.focus_handle(cx)), cx);
498 }
499
500 menu.focus_handle(cx).focus(window, cx);
504
505 let _subscription = window.subscribe(&menu, cx, {
512 let shared_state = Rc::downgrade(&shared_state);
513 move |_, _: &DismissEvent, window, _cx| {
514 if let Some(shared_state) = shared_state.upgrade() {
515 let mut state = shared_state.borrow_mut();
516 state.open = false;
517 state.selection_input = None;
518 window.refresh();
519 }
520 }
521 });
522
523 {
525 let mut state = shared_state.borrow_mut();
526 state.menu_view = Some(menu.clone());
527 state.selection_input = selection_input;
528 state._subscription = Some(_subscription);
529 window.refresh();
530 }
531 }
532 });
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538 use crate::menu::PopupMenuItem;
539 use crate::theme::Theme;
540 use gpui::{
541 Context, FocusHandle, IntoElement, KeyBinding, Render, TestAppContext, VisualTestContext,
542 actions, point, px,
543 };
544 use std::cell::Cell;
545
546 actions!(context_menu_test, [RemoveTab, CopyText]);
547
548 struct TestRoot {
552 content_focus: FocusHandle,
553 received: Rc<Cell<bool>>,
554 }
555
556 impl Render for TestRoot {
557 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
558 let received = self.received.clone();
559 div()
560 .size_full()
561 .child(
562 div()
563 .id("content")
564 .h(px(40.))
565 .track_focus(&self.content_focus),
566 )
567 .child(
568 div()
569 .id("action-bar")
570 .h(px(60.))
571 .on_action(move |_: &RemoveTab, _, _| received.set(true))
572 .child(
573 div()
574 .id("tab")
575 .size_full()
576 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
577 ),
578 )
579 }
580 }
581
582 #[gpui::test]
583 fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
584 cx.update(|cx| {
585 cx.set_global(Theme::default());
586 super::super::popup_menu::init(cx);
587 });
588
589 let received = Rc::new(Cell::new(false));
590 let (root, cx) = cx.add_window_view({
591 let received = received.clone();
592 move |window, cx| {
593 let content_focus = cx.focus_handle();
594 content_focus.focus(window, cx);
595 TestRoot {
596 content_focus,
597 received,
598 }
599 }
600 });
601 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
602 let cx: &mut VisualTestContext = cx;
603 cx.run_until_parked();
604 cx.update(|window, cx| {
605 _ = window.draw(cx);
606 });
607
608 cx.simulate_event(MouseDownEvent {
610 button: MouseButton::Right,
611 position: point(px(50.), px(70.)),
612 modifiers: Default::default(),
613 click_count: 1,
614 first_mouse: false,
615 });
616 cx.run_until_parked();
619 cx.update(|window, cx| {
620 _ = window.draw(cx);
621 });
622
623 cx.simulate_keystrokes("down enter");
626 cx.run_until_parked();
627
628 assert!(received.get());
631 cx.update(|window, cx| {
634 assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
635 });
636 }
637
638 const CONTEXT: &str = "context_menu_test";
639
640 struct UnfocusedRoot {
644 frames: Rc<Cell<usize>>,
645 }
646
647 impl Render for UnfocusedRoot {
648 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
649 self.frames.set(self.frames.get() + 1);
650 div()
651 .size_full()
652 .child(
653 div()
654 .key_context(CONTEXT)
655 .on_action(|_: &CopyText, _, _| {})
656 .child(
657 div()
658 .id("tab")
659 .w(px(100.))
660 .h(px(30.))
661 .context_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
662 ),
663 )
664 .child(div().child("Status"))
665 }
666 }
667
668 struct RowsRoot {
671 clicked: Rc<Cell<usize>>,
672 }
673
674 impl Render for RowsRoot {
675 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
676 div().size_full().children((0..3).map(|_| {
677 let clicked = self.clicked.clone();
678 div()
679 .w(px(100.))
680 .h(px(30.))
681 .context_menu(move |menu, _, _| {
682 let clicked = clicked.clone();
683 menu.item(
684 PopupMenuItem::new("Favorite")
685 .on_click(move |_, _, _| clicked.set(clicked.get() + 1)),
686 )
687 })
688 }))
689 }
690 }
691
692 #[gpui::test]
693 fn item_click_fires_once_from_rows_without_an_id(cx: &mut TestAppContext) {
694 cx.update(|cx| crate::init(cx));
695 let clicked = Rc::new(Cell::new(0));
696 let (_, cx) = cx.add_window_view({
697 let clicked = clicked.clone();
698 move |_, _| RowsRoot { clicked }
699 });
700 cx.update(|window, cx| {
701 window.draw(cx).clear(cx);
702 });
703
704 let press = point(px(10.), px(40.));
706 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
707 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
708 cx.run_until_parked();
709 cx.update(|window, cx| {
710 window.draw(cx).clear(cx);
711 });
712
713 let item = point(press.x + px(30.), press.y + px(17.));
715 cx.simulate_mouse_move(item, None, Default::default());
716 cx.simulate_click(item, Default::default());
717 cx.run_until_parked();
718
719 assert_eq!(
720 clicked.get(),
721 1,
722 "the item's on_click must fire exactly once"
723 );
724 }
725
726 #[gpui::test]
733 fn open_without_dismiss_releases_the_menu_entity(cx: &mut TestAppContext) {
734 cx.update(|cx| crate::init(cx));
735 let before = cx.update(|cx| cx.leak_detector_snapshot());
736
737 {
738 let (_, cx) = cx.add_window_view(|_, _| RowsRoot {
739 clicked: Rc::new(Cell::new(0)),
740 });
741 cx.update(|window, cx| {
742 window.draw(cx).clear(cx);
743 });
744
745 let press = point(px(10.), px(10.));
747 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
748 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
749 cx.run_until_parked();
750 cx.update(|window, cx| {
751 window.draw(cx).clear(cx);
752 });
753
754 cx.update(|window, _| window.remove_window());
756 cx.run_until_parked();
757 }
758
759 cx.update(|cx| cx.assert_no_new_leaks(&before));
763 }
764
765 struct FocusRecordingRoot {
767 content_focus: FocusHandle,
768 content_focused_at_render: Rc<Cell<bool>>,
769 }
770
771 impl Render for FocusRecordingRoot {
772 fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
773 self.content_focused_at_render
774 .set(self.content_focus.is_focused(window));
775 div()
776 .size_full()
777 .child(
778 div()
779 .id("content")
780 .h(px(40.))
781 .track_focus(&self.content_focus),
782 )
783 .child(
784 div()
785 .id("tab")
786 .h(px(60.))
787 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
788 )
789 }
790 }
791
792 #[gpui::test]
797 fn menu_takes_focus_before_its_first_frame(cx: &mut TestAppContext) {
798 cx.update(|cx| crate::init(cx));
799 let content_focused_at_render = Rc::new(Cell::new(false));
800 let (root, cx) = cx.add_window_view({
801 let content_focused_at_render = content_focused_at_render.clone();
802 move |window, cx| {
803 let content_focus = cx.focus_handle();
804 content_focus.focus(window, cx);
805 FocusRecordingRoot {
806 content_focus,
807 content_focused_at_render,
808 }
809 }
810 });
811 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
812 cx.update(|window, cx| {
813 window.draw(cx).clear(cx);
814 });
815 assert!(content_focused_at_render.get());
816
817 cx.simulate_mouse_down(
818 point(px(50.), px(70.)),
819 MouseButton::Right,
820 Default::default(),
821 );
822
823 assert!(
824 !content_focused_at_render.get(),
825 "focus must leave the content before the frame that draws the menu"
826 );
827 cx.update(|window, cx| {
828 let focused = window.focused(cx);
829 assert!(focused.is_some() && focused.as_ref() != Some(&content_focus));
830 });
831 }
832
833 #[gpui::test]
834 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
835 cx.update(|cx| {
836 crate::init(cx);
837 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
838 });
839 let frames = Rc::new(Cell::new(0));
840 let (_, cx) = cx.add_window_view({
841 let frames = frames.clone();
842 move |_, _| UnfocusedRoot { frames }
843 });
844 cx.update(|window, cx| {
845 window.draw(cx).clear(cx);
846 assert!(window.focused(cx).is_none());
847 });
848 let frames_before_open = frames.get();
849
850 cx.simulate_mouse_down(
853 point(px(10.), px(10.)),
854 MouseButton::Right,
855 Default::default(),
856 );
857
858 assert_eq!(
859 frames.get(),
860 frames_before_open + 1,
861 "the press must be followed by exactly one frame for this to test the first one"
862 );
863 assert!(
864 cx.debug_bounds("kbd:ctrl-c").is_some(),
865 "the shortcut hint must be painted on the same frame as its item"
866 );
867 }
868}