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
113struct ContextMenuSharedState {
114 menu_view: Option<Entity<PopupMenu>>,
115 selection_input: Option<AnyInputState>,
118 open: bool,
119 position: Point<Pixels>,
120 trigger_focus_handle: Option<FocusHandle>,
125 _subscription: Option<Subscription>,
126}
127
128pub struct ContextMenuState {
129 element: Option<AnyElement>,
130 draws_menu: Rc<Cell<bool>>,
138 shared_state: Rc<RefCell<ContextMenuSharedState>>,
139}
140
141impl Default for ContextMenuState {
142 fn default() -> Self {
143 Self {
144 element: None,
145 draws_menu: Rc::default(),
146 shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
147 menu_view: None,
148 selection_input: None,
149 open: false,
150 position: Default::default(),
151 trigger_focus_handle: None,
152 _subscription: None,
153 })),
154 }
155 }
156}
157
158struct DeferredMenu {
164 draws: Rc<Cell<bool>>,
165 menu_view: Entity<PopupMenu>,
166 position: Point<Pixels>,
167 anchor: Anchor,
168 menu: Option<AnyElement>,
169}
170
171impl DeferredMenu {
172 fn build_menu(&self, window: &mut Window) -> AnyElement {
173 deferred(
174 anchored().child(
175 div()
176 .w(window.bounds().size.width)
177 .h(window.bounds().size.height)
178 .on_scroll(|_, _, cx| {
179 cx.stop_propagation();
180 })
181 .child(
182 anchored()
183 .position(self.position)
184 .snap_to_window_with_margin(px(8.))
185 .anchor(self.anchor)
186 .child(self.menu_view.clone()),
187 ),
188 ),
189 )
190 .with_priority(gpui_base::POPUP_PRIORITY)
191 .into_any()
192 }
193}
194
195impl Element for DeferredMenu {
196 type RequestLayoutState = ();
197 type PrepaintState = ();
198
199 fn id(&self) -> Option<ElementId> {
200 None
201 }
202
203 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
204 None
205 }
206
207 fn request_layout(
208 &mut self,
209 _: Option<&GlobalElementId>,
210 _: Option<&InspectorElementId>,
211 window: &mut Window,
212 cx: &mut App,
213 ) -> (LayoutId, ()) {
214 let style = Style {
217 position: Position::Absolute,
218 ..Style::default()
219 };
220 (window.request_layout(style, None, cx), ())
221 }
222
223 fn prepaint(
224 &mut self,
225 _: Option<&GlobalElementId>,
226 _: Option<&InspectorElementId>,
227 bounds: Bounds<Pixels>,
228 _: &mut (),
229 window: &mut Window,
230 cx: &mut App,
231 ) {
232 if !self.draws.get() {
233 return;
234 }
235 let mut menu = self.build_menu(window);
236 menu.prepaint_as_root(bounds.origin, window.viewport_size().into(), window, cx);
237 self.menu = Some(menu);
238 }
239
240 fn paint(
241 &mut self,
242 _: Option<&GlobalElementId>,
243 _: Option<&InspectorElementId>,
244 _: Bounds<Pixels>,
245 _: &mut (),
246 _: &mut (),
247 window: &mut Window,
248 cx: &mut App,
249 ) {
250 if let Some(menu) = &mut self.menu {
251 menu.paint(window, cx);
252 }
253 }
254}
255
256impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
257 type RequestLayoutState = ContextMenuState;
258 type PrepaintState = Hitbox;
259
260 fn id(&self) -> Option<ElementId> {
261 Some(self.id.clone())
262 }
263
264 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
265 None
266 }
267
268 fn request_layout(
269 &mut self,
270 id: Option<&gpui::GlobalElementId>,
271 _: Option<&gpui::InspectorElementId>,
272 window: &mut Window,
273 cx: &mut App,
274 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
275 let anchor = gpui_base::logical_anchor(self.anchor, gpui_base::LayoutDirection::global(cx));
277
278 self.with_element_state(
279 id.unwrap(),
280 window,
281 cx,
282 |this, state: &mut ContextMenuState, window, cx| {
283 let (position, open) = {
284 let shared_state = state.shared_state.borrow();
285 (shared_state.position, shared_state.open)
286 };
287 state
288 .shared_state
289 .borrow_mut()
290 .trigger_focus_handle
291 .get_or_insert_with(|| cx.focus_handle());
292 let menu_view = state.shared_state.borrow().menu_view.clone();
293 let draws_menu = Rc::new(Cell::new(false));
294 let menu_element = menu_view
295 .filter(|menu| open && !menu.read(cx).is_empty())
296 .map(|menu_view| DeferredMenu {
297 draws: draws_menu.clone(),
298 menu_view,
299 position,
300 anchor,
301 menu: None,
302 });
303
304 let mut element = this
305 .element
306 .take()
307 .expect("Element should exists.")
308 .children(menu_element)
309 .into_any_element();
310
311 let layout_id = element.request_layout(window, cx);
312
313 (
314 layout_id,
315 ContextMenuState {
316 element: Some(element),
317 draws_menu,
318 shared_state: state.shared_state.clone(),
319 },
320 )
321 },
322 )
323 }
324
325 fn prepaint(
326 &mut self,
327 _: Option<&gpui::GlobalElementId>,
328 _: Option<&InspectorElementId>,
329 bounds: gpui::Bounds<gpui::Pixels>,
330 request_layout: &mut Self::RequestLayoutState,
331 window: &mut Window,
332 cx: &mut App,
333 ) -> Self::PrepaintState {
334 if let Some(trigger_focus) = request_layout
335 .shared_state
336 .borrow()
337 .trigger_focus_handle
338 .as_ref()
339 {
340 window.set_focus_handle(trigger_focus, cx);
341 }
342 let position = request_layout.shared_state.borrow().position;
343 request_layout.draws_menu.set(bounds.contains(&position));
344 if let Some(element) = &mut request_layout.element {
345 element.prepaint(window, cx);
346 }
347 window.insert_hitbox(bounds, HitboxBehavior::Normal)
348 }
349
350 fn paint(
351 &mut self,
352 _: Option<&gpui::GlobalElementId>,
353 _: Option<&InspectorElementId>,
354 _: gpui::Bounds<gpui::Pixels>,
355 request_layout: &mut Self::RequestLayoutState,
356 hitbox: &mut Self::PrepaintState,
357 window: &mut Window,
358 cx: &mut App,
359 ) {
360 let builder = self.menu.clone();
361 let shared_state = request_layout.shared_state.clone();
362
363 window.on_mouse_event({
368 let shared_state = shared_state.clone();
369 let builder = builder.clone();
370 let hitbox = hitbox.clone();
371 move |event: &LongPressEvent, phase, window, cx| {
372 if phase.bubble()
373 && event.phase == TouchPhase::Started
374 && !window.default_prevented()
375 && hitbox.is_hovered(window)
376 && !gpui_base::TextSelection::is_selectable_at(event.start_position, window, cx)
377 {
378 window.prevent_default();
379 open_menu(&shared_state, &builder, event.start_position, window, cx);
380 }
381 }
382 });
383
384 let hitbox = hitbox.clone();
387 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
388 if phase.bubble() && event.button == MouseButton::Right && hitbox.is_hovered(window) {
389 cx.stop_propagation();
390 open_menu(&shared_state, &builder, event.position, window, cx);
391 }
392 });
393
394 if let Some(element) = &mut request_layout.element {
395 element.paint(window, cx);
396 }
397 }
398}
399
400type MenuBuilder = dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu;
401
402fn open_menu(
404 shared_state: &Rc<RefCell<ContextMenuSharedState>>,
405 builder: &Option<Rc<MenuBuilder>>,
406 position: Point<Pixels>,
407 window: &mut Window,
408 cx: &mut App,
409) {
410 let previous_focus_handle = window.focused(cx).and_then(|focused| {
413 let shared_state = shared_state.borrow();
414 match shared_state.menu_view.as_ref() {
415 Some(menu) if menu.read(cx).focus_handle == focused => {
416 menu.read(cx).previous_focus_handle.clone()
417 }
418 _ => Some(focused),
419 }
420 });
421
422 let previous_selection_input = {
424 let state = shared_state.borrow();
425 let menu_focused = state.menu_view.as_ref().is_some_and(|menu| {
426 let focus = menu.focus_handle(cx);
427 focus.is_focused(window) || focus.contains_focused(window, cx)
428 });
429 state
430 .selection_input
431 .as_ref()
432 .filter(|input| menu_focused || input.focus_handle(cx).is_focused(window))
433 .cloned()
434 };
435 {
436 let mut shared_state = shared_state.borrow_mut();
437 shared_state.menu_view = None;
440 shared_state.selection_input = None;
441 shared_state._subscription = None;
442 shared_state.position = position;
443 shared_state.open = true;
444 }
445
446 window.defer(cx, {
448 let shared_state = shared_state.clone();
449 let builder = builder.clone();
450 move |window, cx| {
451 let selection_input =
455 WindowState::try_update(window, cx, |state, _, _| state.focused_input.clone())
456 .flatten()
457 .filter(|input| input.focus_handle(cx).is_focused(window))
458 .or(previous_selection_input);
459 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
460 let Some(build) = &builder else {
461 return menu;
462 };
463 build(menu, window, cx)
464 });
465 let trigger_focus_handle = shared_state.borrow().trigger_focus_handle.clone();
466 menu.update(cx, |menu, cx| {
467 menu.set_trigger_focus(trigger_focus_handle, cx);
468 menu.set_previous_focus(previous_focus_handle, cx);
469 });
470
471 let selection_input = selection_input.filter(|input| {
475 let Some(bounds) = input.input_bounds(cx) else {
476 return false;
477 };
478 match menu.read(cx).action_context.as_ref() {
479 Some(target) => target == &input.focus_handle(cx),
480 None => bounds.contains(&position),
481 }
482 });
483 if let Some(input) = selection_input.as_ref() {
484 input.set_selection_focus(Some(menu.focus_handle(cx)), cx);
485 }
486
487 menu.focus_handle(cx).focus(window, cx);
491
492 let _subscription = window.subscribe(&menu, cx, {
499 let shared_state = Rc::downgrade(&shared_state);
500 move |_, _: &DismissEvent, window, _cx| {
501 if let Some(shared_state) = shared_state.upgrade() {
502 let mut state = shared_state.borrow_mut();
503 state.open = false;
504 state.selection_input = None;
505 window.refresh();
506 }
507 }
508 });
509
510 {
512 let mut state = shared_state.borrow_mut();
513 state.menu_view = Some(menu.clone());
514 state.selection_input = selection_input;
515 state._subscription = Some(_subscription);
516 window.refresh();
517 }
518 }
519 });
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525 use crate::menu::PopupMenuItem;
526 use crate::theme::Theme;
527 use gpui::{
528 Context, FocusHandle, IntoElement, KeyBinding, Render, TestAppContext, VisualTestContext,
529 actions, point, px,
530 };
531 use std::cell::Cell;
532
533 actions!(context_menu_test, [RemoveTab, CopyText]);
534
535 struct TestRoot {
539 content_focus: FocusHandle,
540 received: Rc<Cell<bool>>,
541 }
542
543 impl Render for TestRoot {
544 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
545 let received = self.received.clone();
546 div()
547 .size_full()
548 .child(
549 div()
550 .id("content")
551 .h(px(40.))
552 .track_focus(&self.content_focus),
553 )
554 .child(
555 div()
556 .id("action-bar")
557 .h(px(60.))
558 .on_action(move |_: &RemoveTab, _, _| received.set(true))
559 .child(
560 div()
561 .id("tab")
562 .size_full()
563 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
564 ),
565 )
566 }
567 }
568
569 #[gpui::test]
570 fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
571 cx.update(|cx| {
572 cx.set_global(Theme::default());
573 super::super::popup_menu::init(cx);
574 });
575
576 let received = Rc::new(Cell::new(false));
577 let (root, cx) = cx.add_window_view({
578 let received = received.clone();
579 move |window, cx| {
580 let content_focus = cx.focus_handle();
581 content_focus.focus(window, cx);
582 TestRoot {
583 content_focus,
584 received,
585 }
586 }
587 });
588 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
589 let cx: &mut VisualTestContext = cx;
590 cx.run_until_parked();
591 cx.update(|window, cx| {
592 _ = window.draw(cx);
593 });
594
595 cx.simulate_event(MouseDownEvent {
597 button: MouseButton::Right,
598 position: point(px(50.), px(70.)),
599 modifiers: Default::default(),
600 click_count: 1,
601 first_mouse: false,
602 });
603 cx.run_until_parked();
606 cx.update(|window, cx| {
607 _ = window.draw(cx);
608 });
609
610 cx.simulate_keystrokes("down enter");
613 cx.run_until_parked();
614
615 assert!(received.get());
618 cx.update(|window, cx| {
621 assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
622 });
623 }
624
625 const CONTEXT: &str = "context_menu_test";
626
627 struct UnfocusedRoot {
631 frames: Rc<Cell<usize>>,
632 }
633
634 impl Render for UnfocusedRoot {
635 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
636 self.frames.set(self.frames.get() + 1);
637 div()
638 .size_full()
639 .child(
640 div()
641 .key_context(CONTEXT)
642 .on_action(|_: &CopyText, _, _| {})
643 .child(
644 div()
645 .id("tab")
646 .w(px(100.))
647 .h(px(30.))
648 .context_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
649 ),
650 )
651 .child(div().child("Status"))
652 }
653 }
654
655 struct RowsRoot {
658 clicked: Rc<Cell<usize>>,
659 }
660
661 impl Render for RowsRoot {
662 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
663 div().size_full().children((0..3).map(|_| {
664 let clicked = self.clicked.clone();
665 div()
666 .w(px(100.))
667 .h(px(30.))
668 .context_menu(move |menu, _, _| {
669 let clicked = clicked.clone();
670 menu.item(
671 PopupMenuItem::new("Favorite")
672 .on_click(move |_, _, _| clicked.set(clicked.get() + 1)),
673 )
674 })
675 }))
676 }
677 }
678
679 #[gpui::test]
680 fn item_click_fires_once_from_rows_without_an_id(cx: &mut TestAppContext) {
681 cx.update(|cx| crate::init(cx));
682 let clicked = Rc::new(Cell::new(0));
683 let (_, cx) = cx.add_window_view({
684 let clicked = clicked.clone();
685 move |_, _| RowsRoot { clicked }
686 });
687 cx.update(|window, cx| {
688 window.draw(cx).clear(cx);
689 });
690
691 let press = point(px(10.), px(40.));
693 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
694 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
695 cx.run_until_parked();
696 cx.update(|window, cx| {
697 window.draw(cx).clear(cx);
698 });
699
700 let item = point(press.x + px(30.), press.y + px(17.));
702 cx.simulate_mouse_move(item, None, Default::default());
703 cx.simulate_click(item, Default::default());
704 cx.run_until_parked();
705
706 assert_eq!(
707 clicked.get(),
708 1,
709 "the item's on_click must fire exactly once"
710 );
711 }
712
713 #[gpui::test]
720 fn open_without_dismiss_releases_the_menu_entity(cx: &mut TestAppContext) {
721 cx.update(|cx| crate::init(cx));
722 let before = cx.update(|cx| cx.leak_detector_snapshot());
723
724 {
725 let (_, cx) = cx.add_window_view(|_, _| RowsRoot {
726 clicked: Rc::new(Cell::new(0)),
727 });
728 cx.update(|window, cx| {
729 window.draw(cx).clear(cx);
730 });
731
732 let press = point(px(10.), px(10.));
734 cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
735 cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
736 cx.run_until_parked();
737 cx.update(|window, cx| {
738 window.draw(cx).clear(cx);
739 });
740
741 cx.update(|window, _| window.remove_window());
743 cx.run_until_parked();
744 }
745
746 cx.update(|cx| cx.assert_no_new_leaks(&before));
750 }
751
752 struct FocusRecordingRoot {
754 content_focus: FocusHandle,
755 content_focused_at_render: Rc<Cell<bool>>,
756 }
757
758 impl Render for FocusRecordingRoot {
759 fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
760 self.content_focused_at_render
761 .set(self.content_focus.is_focused(window));
762 div()
763 .size_full()
764 .child(
765 div()
766 .id("content")
767 .h(px(40.))
768 .track_focus(&self.content_focus),
769 )
770 .child(
771 div()
772 .id("tab")
773 .h(px(60.))
774 .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
775 )
776 }
777 }
778
779 #[gpui::test]
784 fn menu_takes_focus_before_its_first_frame(cx: &mut TestAppContext) {
785 cx.update(|cx| crate::init(cx));
786 let content_focused_at_render = Rc::new(Cell::new(false));
787 let (root, cx) = cx.add_window_view({
788 let content_focused_at_render = content_focused_at_render.clone();
789 move |window, cx| {
790 let content_focus = cx.focus_handle();
791 content_focus.focus(window, cx);
792 FocusRecordingRoot {
793 content_focus,
794 content_focused_at_render,
795 }
796 }
797 });
798 let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
799 cx.update(|window, cx| {
800 window.draw(cx).clear(cx);
801 });
802 assert!(content_focused_at_render.get());
803
804 cx.simulate_mouse_down(
805 point(px(50.), px(70.)),
806 MouseButton::Right,
807 Default::default(),
808 );
809
810 assert!(
811 !content_focused_at_render.get(),
812 "focus must leave the content before the frame that draws the menu"
813 );
814 cx.update(|window, cx| {
815 let focused = window.focused(cx);
816 assert!(focused.is_some() && focused.as_ref() != Some(&content_focus));
817 });
818 }
819
820 #[gpui::test]
821 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
822 cx.update(|cx| {
823 crate::init(cx);
824 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
825 });
826 let frames = Rc::new(Cell::new(0));
827 let (_, cx) = cx.add_window_view({
828 let frames = frames.clone();
829 move |_, _| UnfocusedRoot { frames }
830 });
831 cx.update(|window, cx| {
832 window.draw(cx).clear(cx);
833 assert!(window.focused(cx).is_none());
834 });
835 let frames_before_open = frames.get();
836
837 cx.simulate_mouse_down(
840 point(px(10.), px(10.)),
841 MouseButton::Right,
842 Default::default(),
843 );
844
845 assert_eq!(
846 frames.get(),
847 frames_before_open + 1,
848 "the press must be followed by exactly one frame for this to test the first one"
849 );
850 assert!(
851 cx.debug_bounds("kbd:ctrl-c").is_some(),
852 "the shortcut hint must be painted on the same frame as its item"
853 );
854 }
855}