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 let hitbox = hitbox.clone();
402 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
403 if phase.bubble() && event.button == MouseButton::Right && hitbox.is_hovered(window) {
404 cx.stop_propagation();
405 open_menu(&shared_state, &builder, event.position, window, cx);
406 }
407 });
408
409 if let Some(element) = &mut request_layout.element {
410 element.paint(window, cx);
411 }
412 }
413}
414
415type MenuBuilder = dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu;
416
417fn open_menu(
419 shared_state: &Rc<RefCell<ContextMenuSharedState>>,
420 builder: &Option<Rc<MenuBuilder>>,
421 position: Point<Pixels>,
422 window: &mut Window,
423 cx: &mut App,
424) {
425 let previous_focus_handle = window.focused(cx).and_then(|focused| {
428 let shared_state = shared_state.borrow();
429 match shared_state.menu_view.as_ref() {
430 Some(menu) if menu.read(cx).focus_handle == focused => {
431 menu.read(cx).previous_focus_handle.clone()
432 }
433 _ => Some(focused),
434 }
435 });
436
437 let previous_selection_input = {
439 let state = shared_state.borrow();
440 let menu_focused = state.menu_view.as_ref().is_some_and(|menu| {
441 let focus = menu.focus_handle(cx);
442 focus.is_focused(window) || focus.contains_focused(window, cx)
443 });
444 state
445 .selection_input
446 .as_ref()
447 .filter(|input| menu_focused || input.focus_handle(cx).is_focused(window))
448 .cloned()
449 };
450 {
451 let mut shared_state = shared_state.borrow_mut();
452 shared_state.menu_view = None;
455 shared_state.selection_input = None;
456 shared_state._subscription = None;
457 shared_state.position = position;
458 shared_state.open = true;
459 }
460
461 window.defer(cx, {
463 let shared_state = shared_state.clone();
464 let builder = builder.clone();
465 move |window, cx| {
466 let selection_input =
470 WindowState::try_update(window, cx, |state, _, _| state.focused_input.clone())
471 .flatten()
472 .filter(|input| input.focus_handle(cx).is_focused(window))
473 .or(previous_selection_input);
474 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
475 let Some(build) = &builder else {
476 return menu;
477 };
478 build(menu, window, cx)
479 });
480 let trigger_focus_handle = shared_state.borrow().trigger_focus_handle.clone();
481 menu.update(cx, |menu, cx| {
482 menu.set_trigger_focus(trigger_focus_handle, cx);
483 menu.set_previous_focus(previous_focus_handle, cx);
484 });
485
486 let selection_input = selection_input.filter(|input| {
490 let Some(bounds) = input.input_bounds(cx) else {
491 return false;
492 };
493 match menu.read(cx).action_context.as_ref() {
494 Some(target) => target == &input.focus_handle(cx),
495 None => bounds.contains(&position),
496 }
497 });
498 if let Some(input) = selection_input.as_ref() {
499 input.set_selection_focus(Some(menu.focus_handle(cx)), cx);
500 }
501
502 menu.focus_handle(cx).focus(window, cx);
506
507 let _subscription = window.subscribe(&menu, cx, {
514 let shared_state = Rc::downgrade(&shared_state);
515 move |_, _: &DismissEvent, window, _cx| {
516 if let Some(shared_state) = shared_state.upgrade() {
517 let mut state = shared_state.borrow_mut();
518 state.open = false;
519 state.selection_input = None;
520 window.refresh();
521 }
522 }
523 });
524
525 {
527 let mut state = shared_state.borrow_mut();
528 state.menu_view = Some(menu.clone());
529 state.selection_input = selection_input;
530 state._subscription = Some(_subscription);
531 window.refresh();
532 }
533 }
534 });
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540 use crate::menu::PopupMenuItem;
541 use crate::theme::Theme;
542 use gpui::{
543 Context, FocusHandle, IntoElement, KeyBinding, Render, TestAppContext, VisualTestContext,
544 actions, point, px,
545 };
546 use std::cell::Cell;
547
548 actions!(context_menu_test, [RemoveTab, CopyText]);
549
550 struct TestRoot {
554 content_focus: FocusHandle,
555 received: Rc<Cell<bool>>,
556 }
557
558 impl Render for TestRoot {
559 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
560 let received = self.received.clone();
561 div()
562 .size_full()
563 .child(
564 div()
565 .id("content")
566 .h(px(40.))
567 .track_focus(&self.content_focus),
568 )
569 .child(
570 div()
571 .id("action-bar")
572 .h(px(60.))
573 .on_action(move |_: &RemoveTab, _, _| received.set(true))
574 .child(
575 div()
576 .id("tab")
577 .size_full()
578 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
579 ),
580 )
581 }
582 }
583
584 #[gpui::test]
585 fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
586 cx.update(|cx| {
587 cx.set_global(Theme::default());
588 super::super::popup_menu::init(cx);
589 });
590
591 let received = Rc::new(Cell::new(false));
592 let (root, cx) = cx.add_window_view({
593 let received = received.clone();
594 move |window, cx| {
595 let content_focus = cx.focus_handle();
596 content_focus.focus(window, cx);
597 TestRoot {
598 content_focus,
599 received,
600 }
601 }
602 });
603 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
604 let cx: &mut VisualTestContext = cx;
605 cx.run_until_parked();
606 cx.update(|window, cx| {
607 _ = window.draw(cx);
608 });
609
610 cx.simulate_event(MouseDownEvent {
612 button: MouseButton::Right,
613 position: point(px(50.), px(70.)),
614 modifiers: Default::default(),
615 click_count: 1,
616 first_mouse: false,
617 });
618 cx.run_until_parked();
621 cx.update(|window, cx| {
622 _ = window.draw(cx);
623 });
624
625 cx.simulate_keystrokes("down enter");
628 cx.run_until_parked();
629
630 assert!(received.get());
633 cx.update(|window, cx| {
636 assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
637 });
638 }
639
640 const CONTEXT: &str = "context_menu_test";
641
642 struct UnfocusedRoot {
646 frames: Rc<Cell<usize>>,
647 }
648
649 impl Render for UnfocusedRoot {
650 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
651 self.frames.set(self.frames.get() + 1);
652 div()
653 .size_full()
654 .child(
655 div()
656 .key_context(CONTEXT)
657 .on_action(|_: &CopyText, _, _| {})
658 .child(
659 div()
660 .id("tab")
661 .w(px(100.))
662 .h(px(30.))
663 .context_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
664 ),
665 )
666 .child(div().child("Status"))
667 }
668 }
669
670 struct RowsRoot {
673 clicked: Rc<Cell<usize>>,
674 }
675
676 impl Render for RowsRoot {
677 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
678 div().size_full().children((0..3).map(|_| {
679 let clicked = self.clicked.clone();
680 div()
681 .w(px(100.))
682 .h(px(30.))
683 .context_menu(move |menu, _, _| {
684 let clicked = clicked.clone();
685 menu.item(
686 PopupMenuItem::new("Favorite")
687 .on_click(move |_, _, _| clicked.set(clicked.get() + 1)),
688 )
689 })
690 }))
691 }
692 }
693
694 #[gpui::test]
695 fn item_click_fires_once_from_rows_without_an_id(cx: &mut TestAppContext) {
696 cx.update(|cx| crate::init(cx));
697 let clicked = Rc::new(Cell::new(0));
698 let (_, cx) = cx.add_window_view({
699 let clicked = clicked.clone();
700 move |_, _| RowsRoot { clicked }
701 });
702 cx.update(|window, cx| {
703 window.draw(cx).clear(cx);
704 });
705
706 let press = point(px(10.), px(40.));
708 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
709 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
710 cx.run_until_parked();
711 cx.update(|window, cx| {
712 window.draw(cx).clear(cx);
713 });
714
715 let item = point(press.x + px(30.), press.y + px(17.));
717 cx.simulate_mouse_move(item, None, Default::default());
718 cx.simulate_click(item, Default::default());
719 cx.run_until_parked();
720
721 assert_eq!(
722 clicked.get(),
723 1,
724 "the item's on_click must fire exactly once"
725 );
726 }
727
728 #[gpui::test]
735 fn open_without_dismiss_releases_the_menu_entity(cx: &mut TestAppContext) {
736 cx.update(|cx| crate::init(cx));
737 let before = cx.update(|cx| cx.leak_detector_snapshot());
738
739 {
740 let (_, cx) = cx.add_window_view(|_, _| RowsRoot {
741 clicked: Rc::new(Cell::new(0)),
742 });
743 cx.update(|window, cx| {
744 window.draw(cx).clear(cx);
745 });
746
747 let press = point(px(10.), px(10.));
749 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
750 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
751 cx.run_until_parked();
752 cx.update(|window, cx| {
753 window.draw(cx).clear(cx);
754 });
755
756 cx.update(|window, _| window.remove_window());
758 cx.run_until_parked();
759 }
760
761 cx.update(|cx| cx.assert_no_new_leaks(&before));
765 }
766
767 struct FocusRecordingRoot {
769 content_focus: FocusHandle,
770 content_focused_at_render: Rc<Cell<bool>>,
771 }
772
773 impl Render for FocusRecordingRoot {
774 fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
775 self.content_focused_at_render
776 .set(self.content_focus.is_focused(window));
777 div()
778 .size_full()
779 .child(
780 div()
781 .id("content")
782 .h(px(40.))
783 .track_focus(&self.content_focus),
784 )
785 .child(
786 div()
787 .id("tab")
788 .h(px(60.))
789 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
790 )
791 }
792 }
793
794 #[gpui::test]
799 fn menu_takes_focus_before_its_first_frame(cx: &mut TestAppContext) {
800 cx.update(|cx| crate::init(cx));
801 let content_focused_at_render = Rc::new(Cell::new(false));
802 let (root, cx) = cx.add_window_view({
803 let content_focused_at_render = content_focused_at_render.clone();
804 move |window, cx| {
805 let content_focus = cx.focus_handle();
806 content_focus.focus(window, cx);
807 FocusRecordingRoot {
808 content_focus,
809 content_focused_at_render,
810 }
811 }
812 });
813 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
814 cx.update(|window, cx| {
815 window.draw(cx).clear(cx);
816 });
817 assert!(content_focused_at_render.get());
818
819 cx.simulate_mouse_down(
820 point(px(50.), px(70.)),
821 MouseButton::Right,
822 Default::default(),
823 );
824
825 assert!(
826 !content_focused_at_render.get(),
827 "focus must leave the content before the frame that draws the menu"
828 );
829 cx.update(|window, cx| {
830 let focused = window.focused(cx);
831 assert!(focused.is_some() && focused.as_ref() != Some(&content_focus));
832 });
833 }
834
835 #[gpui::test]
836 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
837 cx.update(|cx| {
838 crate::init(cx);
839 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
840 });
841 let frames = Rc::new(Cell::new(0));
842 let (_, cx) = cx.add_window_view({
843 let frames = frames.clone();
844 move |_, _| UnfocusedRoot { frames }
845 });
846 cx.update(|window, cx| {
847 window.draw(cx).clear(cx);
848 assert!(window.focused(cx).is_none());
849 });
850 let frames_before_open = frames.get();
851
852 cx.simulate_mouse_down(
855 point(px(10.), px(10.)),
856 MouseButton::Right,
857 Default::default(),
858 );
859
860 assert_eq!(
861 frames.get(),
862 frames_before_open + 1,
863 "the press must be followed by exactly one frame for this to test the first one"
864 );
865 assert!(
866 cx.debug_bounds("kbd:ctrl-c").is_some(),
867 "the shortcut hint must be painted on the same frame as its item"
868 );
869 }
870}