Skip to main content

gpui_component/menu/
context_menu.rs

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
16/// A extension trait for adding a context menu to an element.
17pub trait ContextMenuExt: InteractiveElement + ParentElement + Styled {
18    /// Add a context menu to the element.
19    ///
20    /// This will changed the element to be `relative` positioned, and add a child `ContextMenu` element.
21    /// Because the `ContextMenu` element is positioned `absolute`, it will not affect the layout of the parent element.
22    #[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        // The ID must be stable across renders, otherwise the element state
31        // (open menu) is lost on every re-render.
32        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
45/// A context menu that can be shown on right-click.
46pub struct ContextMenu<E: ParentElement + Styled + Sized> {
47    id: ElementId,
48    element: Option<E>,
49    menu: Option<Rc<MenuBuilder>>,
50    // This is not in use, just for style refinement forwarding.
51    _ignore_style: StyleRefinement,
52    anchor: Anchor,
53}
54
55impl<E: ParentElement + Styled> ContextMenu<E> {
56    /// Create a new context menu with the given ID.
57    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    /// Build the context menu using the given builder function.
68    #[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
113#[cfg(not(feature = "gpui-fast"))]
114impl<E: ParentElement + Styled + IntoElement + 'static> IntoElement for ContextMenu<E> {
115    type Element = Self;
116
117    fn into_element(self) -> Self::Element {
118        self
119    }
120}
121
122struct ContextMenuSharedState {
123    menu_view: Option<Entity<PopupMenu>>,
124    /// Kept while open so replacing the menu preserves its input's selection
125    /// after the input has left the focused-input registry.
126    selection_input: Option<AnyInputState>,
127    open: bool,
128    position: Point<Pixels>,
129    /// Registered on this element's dispatch node every frame and never
130    /// focused, so the menu can resolve its shortcut hints against the
131    /// trigger's key contexts on the frame it opens: GPUI looks a handle up in
132    /// the previously rendered frame, where the menu's own element is not yet.
133    trigger_focus_handle: Option<FocusHandle>,
134    _subscription: Option<Subscription>,
135}
136
137pub struct ContextMenuState {
138    element: Option<AnyElement>,
139    /// Whether this trigger draws the open menu this frame.
140    ///
141    /// Triggers without an `ElementId` fall back to their code location, so
142    /// rows rendered from one call site share the element state and all see
143    /// the menu as open. Only the trigger that was pressed draws it: stacked
144    /// copies of one `PopupMenu` share an item's pending-click state, and the
145    /// covered copies clear it on mouse up before the visible one fires.
146    draws_menu: Rc<Cell<bool>>,
147    shared_state: Rc<RefCell<ContextMenuSharedState>>,
148}
149
150impl Default for ContextMenuState {
151    fn default() -> Self {
152        Self {
153            element: None,
154            draws_menu: Rc::default(),
155            shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
156                menu_view: None,
157                selection_input: None,
158                open: false,
159                position: Default::default(),
160                trigger_focus_handle: None,
161                _subscription: None,
162            })),
163        }
164    }
165}
166
167/// The deferred menu layer of one trigger.
168///
169/// Every trigger that shares the open state carries one, but only the trigger
170/// whose bounds contain the press builds and lays out the menu, so an open
171/// menu is rendered once per frame rather than once per row.
172struct DeferredMenu {
173    draws: Rc<Cell<bool>>,
174    menu_view: Entity<PopupMenu>,
175    position: Point<Pixels>,
176    anchor: Anchor,
177    menu: Option<AnyElement>,
178}
179
180impl DeferredMenu {
181    fn build_menu(&self, window: &mut Window) -> AnyElement {
182        deferred(
183            anchored().child(
184                div()
185                    .w(window.bounds().size.width)
186                    .h(window.bounds().size.height)
187                    .on_scroll(|_, _, cx| {
188                        cx.stop_propagation();
189                    })
190                    .child(
191                        anchored()
192                            .position(self.position)
193                            .snap_to_window_with_margin(px(8.))
194                            .anchor(self.anchor)
195                            .child(self.menu_view.clone()),
196                    ),
197            ),
198        )
199        .with_priority(gpui_base::POPUP_PRIORITY)
200        .into_any()
201    }
202}
203
204#[cfg(not(feature = "gpui-fast"))]
205impl IntoElement for DeferredMenu {
206    type Element = Self;
207
208    fn into_element(self) -> Self::Element {
209        self
210    }
211}
212
213impl Element for DeferredMenu {
214    type RequestLayoutState = ();
215    type PrepaintState = ();
216
217    fn id(&self) -> Option<ElementId> {
218        None
219    }
220
221    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
222        None
223    }
224
225    fn request_layout(
226        &mut self,
227        _: Option<&GlobalElementId>,
228        _: Option<&InspectorElementId>,
229        window: &mut Window,
230        cx: &mut App,
231    ) -> (LayoutId, ()) {
232        // An empty absolute placeholder, where the menu's `anchored` root used
233        // to sit, so the trigger's own layout is unchanged.
234        let style = Style {
235            position: Position::Absolute,
236            ..Style::default()
237        };
238        (window.request_layout(style, None, cx), ())
239    }
240
241    fn prepaint(
242        &mut self,
243        _: Option<&GlobalElementId>,
244        _: Option<&InspectorElementId>,
245        bounds: Bounds<Pixels>,
246        _: &mut (),
247        window: &mut Window,
248        cx: &mut App,
249    ) {
250        if !self.draws.get() {
251            return;
252        }
253        let mut menu = self.build_menu(window);
254        menu.prepaint_as_root(bounds.origin, window.viewport_size().into(), window, cx);
255        self.menu = Some(menu);
256    }
257
258    fn paint(
259        &mut self,
260        _: Option<&GlobalElementId>,
261        _: Option<&InspectorElementId>,
262        _: Bounds<Pixels>,
263        _: &mut (),
264        _: &mut (),
265        window: &mut Window,
266        cx: &mut App,
267    ) {
268        if let Some(menu) = &mut self.menu {
269            menu.paint(window, cx);
270        }
271    }
272}
273
274impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
275    type RequestLayoutState = ContextMenuState;
276    type PrepaintState = Hitbox;
277
278    fn id(&self) -> Option<ElementId> {
279        Some(self.id.clone())
280    }
281
282    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
283        None
284    }
285
286    fn request_layout(
287        &mut self,
288        id: Option<&gpui::GlobalElementId>,
289        _: Option<&gpui::InspectorElementId>,
290        window: &mut Window,
291        cx: &mut App,
292    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
293        // At the pointer, the menu opens toward the end edge.
294        let anchor = gpui_base::logical_anchor(self.anchor, gpui_base::LayoutDirection::global(cx));
295
296        self.with_element_state(
297            id.unwrap(),
298            window,
299            cx,
300            |this, state: &mut ContextMenuState, window, cx| {
301                let (position, open) = {
302                    let shared_state = state.shared_state.borrow();
303                    (shared_state.position, shared_state.open)
304                };
305                state
306                    .shared_state
307                    .borrow_mut()
308                    .trigger_focus_handle
309                    .get_or_insert_with(|| cx.focus_handle());
310                let menu_view = state.shared_state.borrow().menu_view.clone();
311                let draws_menu = Rc::new(Cell::new(false));
312                let menu_element = menu_view
313                    .filter(|menu| open && !menu.read(cx).is_empty())
314                    .map(|menu_view| DeferredMenu {
315                        draws: draws_menu.clone(),
316                        menu_view,
317                        position,
318                        anchor,
319                        menu: None,
320                    });
321
322                let mut element = this
323                    .element
324                    .take()
325                    .expect("Element should exists.")
326                    .children(menu_element)
327                    .into_any_element();
328
329                let layout_id = element.request_layout(window, cx);
330
331                (
332                    layout_id,
333                    ContextMenuState {
334                        element: Some(element),
335                        draws_menu,
336                        shared_state: state.shared_state.clone(),
337                    },
338                )
339            },
340        )
341    }
342
343    fn prepaint(
344        &mut self,
345        _: Option<&gpui::GlobalElementId>,
346        _: Option<&InspectorElementId>,
347        bounds: gpui::Bounds<gpui::Pixels>,
348        request_layout: &mut Self::RequestLayoutState,
349        window: &mut Window,
350        cx: &mut App,
351    ) -> Self::PrepaintState {
352        if let Some(trigger_focus) = request_layout
353            .shared_state
354            .borrow()
355            .trigger_focus_handle
356            .as_ref()
357        {
358            window.set_focus_handle(trigger_focus, cx);
359        }
360        let position = request_layout.shared_state.borrow().position;
361        request_layout.draws_menu.set(bounds.contains(&position));
362        if let Some(element) = &mut request_layout.element {
363            element.prepaint(window, cx);
364        }
365        window.insert_hitbox(bounds, HitboxBehavior::Normal)
366    }
367
368    fn paint(
369        &mut self,
370        _: Option<&gpui::GlobalElementId>,
371        _: Option<&InspectorElementId>,
372        _: gpui::Bounds<gpui::Pixels>,
373        request_layout: &mut Self::RequestLayoutState,
374        hitbox: &mut Self::PrepaintState,
375        window: &mut Window,
376        cx: &mut App,
377    ) {
378        let builder = self.menu.clone();
379        let shared_state = request_layout.shared_state.clone();
380
381        // A finger has no right button, so a long press opens the menu. This
382        // listener goes in before the children paint, so an input inside the
383        // trigger claims its long press first. Rich-text selection is handled
384        // by the window layer, which runs later; yield over its text geometry.
385        window.on_mouse_event({
386            let shared_state = shared_state.clone();
387            let builder = builder.clone();
388            let hitbox = hitbox.clone();
389            move |event: &LongPressEvent, phase, window, cx| {
390                if phase.bubble()
391                    && event.phase == TouchPhase::Started
392                    && !window.default_prevented()
393                    && hitbox.is_hovered(window)
394                    && !gpui_base::TextSelection::is_selectable_at(event.start_position, window, cx)
395                {
396                    window.prevent_default();
397                    open_menu(&shared_state, &builder, event.start_position, window, cx);
398                }
399            }
400        });
401
402        // Register before child paint so bubbling reaches the innermost
403        // trigger first, after its input has had a chance to take focus.
404        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                cx.stop_propagation();
408                open_menu(&shared_state, &builder, event.position, window, cx);
409            }
410        });
411
412        if let Some(element) = &mut request_layout.element {
413            element.paint(window, cx);
414        }
415    }
416}
417
418type MenuBuilder = dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu;
419
420/// Builds the menu and shows it at `position`.
421fn open_menu(
422    shared_state: &Rc<RefCell<ContextMenuSharedState>>,
423    builder: &Option<Rc<MenuBuilder>>,
424    position: Point<Pixels>,
425    window: &mut Window,
426    cx: &mut App,
427) {
428    // Capture the focused element to restore focus to on dismiss.
429    // If focus is still on the previous menu, keep its captured focus.
430    let previous_focus_handle = window.focused(cx).and_then(|focused| {
431        let shared_state = shared_state.borrow();
432        match shared_state.menu_view.as_ref() {
433            Some(menu) if menu.read(cx).focus_handle == focused => {
434                menu.read(cx).previous_focus_handle.clone()
435            }
436            _ => Some(focused),
437        }
438    });
439
440    // Retain the old menu's owner before clearing replacement state.
441    let previous_selection_input = {
442        let state = shared_state.borrow();
443        let menu_focused = state.menu_view.as_ref().is_some_and(|menu| {
444            let focus = menu.focus_handle(cx);
445            focus.is_focused(window) || focus.contains_focused(window, cx)
446        });
447        state
448            .selection_input
449            .as_ref()
450            .filter(|input| menu_focused || input.focus_handle(cx).is_focused(window))
451            .cloned()
452    };
453    {
454        let mut shared_state = shared_state.borrow_mut();
455        // Clear any existing menu view to allow immediate replacement
456        // Set the new position and open the menu
457        shared_state.menu_view = None;
458        shared_state.selection_input = None;
459        shared_state._subscription = None;
460        shared_state.position = position;
461        shared_state.open = true;
462    }
463
464    // Use defer to build the menu in the next frame, avoiding race conditions
465    window.defer(cx, {
466        let shared_state = shared_state.clone();
467        let builder = builder.clone();
468        move |window, cx| {
469            // Resolve after pointer dispatch: the inner input has
470            // now taken focus and published its state, even if it
471            // was unfocused in the last rendered frame.
472            let selection_input =
473                WindowState::try_update(window, cx, |state, _, _| state.focused_input.clone())
474                    .flatten()
475                    .filter(|input| input.focus_handle(cx).is_focused(window))
476                    .or(previous_selection_input);
477            let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
478                let Some(build) = &builder else {
479                    return menu;
480                };
481                build(menu, window, cx)
482            });
483            let trigger_focus_handle = shared_state.borrow().trigger_focus_handle.clone();
484            menu.update(cx, |menu, cx| {
485                menu.set_trigger_focus(trigger_focus_handle, cx);
486                menu.set_previous_focus(previous_focus_handle, cx);
487            });
488
489            // A menu on another element must not keep the last
490            // focused input highlighted. An explicit action target
491            // takes precedence over where the press landed.
492            let selection_input = selection_input.filter(|input| {
493                let Some(bounds) = input.input_bounds(cx) else {
494                    return false;
495                };
496                match menu.read(cx).action_context.as_ref() {
497                    Some(target) => target == &input.focus_handle(cx),
498                    None => bounds.contains(&position),
499                }
500            });
501            if let Some(input) = selection_input.as_ref() {
502                input.set_selection_focus(Some(menu.focus_handle(cx)), cx);
503            }
504
505            // Focus before the menu's first frame, not while prepainting it:
506            // a frame reports one focused accessibility node, and the element
507            // that held focus may already have claimed it by then.
508            menu.focus_handle(cx).focus(window, cx);
509
510            // Set up the subscription for dismiss handling.
511            // Hold a Weak here, not a strong clone: the closure
512            // would otherwise close the cycle
513            // `shared_state -> _subscription -> closure ->
514            // shared_state`, so a menu left open when the window
515            // closes leaks its PopupMenu entity.
516            let _subscription = window.subscribe(&menu, cx, {
517                let shared_state = Rc::downgrade(&shared_state);
518                move |_, _: &DismissEvent, window, _cx| {
519                    if let Some(shared_state) = shared_state.upgrade() {
520                        let mut state = shared_state.borrow_mut();
521                        state.open = false;
522                        state.selection_input = None;
523                        window.refresh();
524                    }
525                }
526            });
527
528            // Update the shared state with the built menu and subscription
529            {
530                let mut state = shared_state.borrow_mut();
531                state.menu_view = Some(menu.clone());
532                state.selection_input = selection_input;
533                state._subscription = Some(_subscription);
534                window.refresh();
535            }
536        }
537    });
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543    use crate::menu::PopupMenuItem;
544    use crate::theme::Theme;
545    use gpui::{
546        Context, FocusHandle, IntoElement, KeyBinding, Render, TestAppContext, VisualTestContext,
547        actions, point, px,
548    };
549    use std::cell::Cell;
550
551    actions!(context_menu_test, [RemoveTab, CopyText]);
552
553    /// The regression shape: the action handler lives on the trigger's
554    /// ancestor (like an action bar), which is NOT on the focus path while
555    /// focus is in the content area.
556    struct TestRoot {
557        content_focus: FocusHandle,
558        received: Rc<Cell<bool>>,
559    }
560
561    impl Render for TestRoot {
562        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
563            let received = self.received.clone();
564            div()
565                .size_full()
566                .child(
567                    div()
568                        .id("content")
569                        .h(px(40.))
570                        .track_focus(&self.content_focus),
571                )
572                .child(
573                    div()
574                        .id("action-bar")
575                        .h(px(60.))
576                        .on_action(move |_: &RemoveTab, _, _| received.set(true))
577                        .child(
578                            div()
579                                .id("tab")
580                                .size_full()
581                                .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
582                        ),
583                )
584        }
585    }
586
587    #[gpui::test]
588    fn action_bubbles_from_trigger_and_focus_restores_on_dismiss(cx: &mut TestAppContext) {
589        cx.update(|cx| {
590            cx.set_global(Theme::default());
591            super::super::popup_menu::init(cx);
592        });
593
594        let received = Rc::new(Cell::new(false));
595        let (root, cx) = cx.add_window_view({
596            let received = received.clone();
597            move |window, cx| {
598                let content_focus = cx.focus_handle();
599                content_focus.focus(window, cx);
600                TestRoot {
601                    content_focus,
602                    received,
603                }
604            }
605        });
606        let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
607        let cx: &mut VisualTestContext = cx;
608        cx.run_until_parked();
609        cx.update(|window, cx| {
610            _ = window.draw(cx);
611        });
612
613        // Right-click inside the tab to open the context menu.
614        cx.simulate_event(MouseDownEvent {
615            button: MouseButton::Right,
616            position: point(px(50.), px(70.)),
617            modifiers: Default::default(),
618            click_count: 1,
619            first_mouse: false,
620        });
621        // The menu entity is built and focused in a deferred callback, then
622        // rendered on the next draw.
623        cx.run_until_parked();
624        cx.update(|window, cx| {
625            _ = window.draw(cx);
626        });
627
628        // Select "Close" and confirm. Keyboard confirm and mouse click share
629        // the same `confirm` path in `PopupMenu`.
630        cx.simulate_keystrokes("down enter");
631        cx.run_until_parked();
632
633        // The action must reach the handler on the trigger's ancestor chain,
634        // even though the action bar was never on the focus path.
635        assert!(received.get());
636        // And dismiss must restore focus to where it was before the menu
637        // opened, keeping the dangling-focus fix (#2614).
638        cx.update(|window, cx| {
639            assert_eq!(window.focused(cx).as_ref(), Some(&content_focus));
640        });
641    }
642
643    const CONTEXT: &str = "context_menu_test";
644
645    /// The story shape: nothing is focused, the key binding lives in the key
646    /// context of the trigger's ancestor, and other content outside that
647    /// context paints after the trigger.
648    struct UnfocusedRoot {
649        frames: Rc<Cell<usize>>,
650    }
651
652    impl Render for UnfocusedRoot {
653        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
654            self.frames.set(self.frames.get() + 1);
655            div()
656                .size_full()
657                .child(
658                    div()
659                        .key_context(CONTEXT)
660                        .on_action(|_: &CopyText, _, _| {})
661                        .child(
662                            div()
663                                .id("tab")
664                                .w(px(100.))
665                                .h(px(30.))
666                                .context_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
667                        ),
668                )
669                .child(div().child("Status"))
670        }
671    }
672
673    /// The issue shape (#3134): rows rendered from one call site without an
674    /// `ElementId` share the context menu's element state.
675    struct RowsRoot {
676        clicked: Rc<Cell<usize>>,
677    }
678
679    impl Render for RowsRoot {
680        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
681            div().size_full().children((0..3).map(|_| {
682                let clicked = self.clicked.clone();
683                div()
684                    .w(px(100.))
685                    .h(px(30.))
686                    .context_menu(move |menu, _, _| {
687                        let clicked = clicked.clone();
688                        menu.item(
689                            PopupMenuItem::new("Favorite")
690                                .on_click(move |_, _, _| clicked.set(clicked.get() + 1)),
691                        )
692                    })
693            }))
694        }
695    }
696
697    #[gpui::test]
698    fn item_click_fires_once_from_rows_without_an_id(cx: &mut TestAppContext) {
699        cx.update(|cx| crate::init(cx));
700        let clicked = Rc::new(Cell::new(0));
701        let (_, cx) = cx.add_window_view({
702            let clicked = clicked.clone();
703            move |_, _| RowsRoot { clicked }
704        });
705        cx.update(|window, cx| {
706            window.draw(cx).clear(cx);
707        });
708
709        // Right-click the second row; the menu opens at the press position.
710        let press = point(px(10.), px(40.));
711        cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
712        cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
713        cx.run_until_parked();
714        cx.update(|window, cx| {
715            window.draw(cx).clear(cx);
716        });
717
718        // Click the first item, which sits inside the menu's content padding.
719        let item = point(press.x + px(30.), press.y + px(17.));
720        cx.simulate_mouse_move(item, None, Default::default());
721        cx.simulate_click(item, Default::default());
722        cx.run_until_parked();
723
724        assert_eq!(
725            clicked.get(),
726            1,
727            "the item's on_click must fire exactly once"
728        );
729    }
730
731    /// Opening a context menu and closing the window without dismissing the
732    /// menu must release the `PopupMenu` entity (#3223): the dismiss
733    /// subscription used to capture a strong `Rc` clone of `shared_state`,
734    /// and the app-global listener registry kept that clone alive even after
735    /// the window (and its element state) was gone, so the menu entity
736    /// survived the window. The subscription now holds a `Weak` instead.
737    #[gpui::test]
738    fn open_without_dismiss_releases_the_menu_entity(cx: &mut TestAppContext) {
739        cx.update(|cx| crate::init(cx));
740        let before = cx.update(|cx| cx.leak_detector_snapshot());
741
742        {
743            let (_, cx) = cx.add_window_view(|_, _| RowsRoot {
744                clicked: Rc::new(Cell::new(0)),
745            });
746            cx.update(|window, cx| {
747                window.draw(cx).clear(cx);
748            });
749
750            // Right-click the first row; the menu opens and is left open.
751            let press = point(px(10.), px(10.));
752            cx.simulate_mouse_down(press, MouseButton::Right, Default::default());
753            cx.simulate_mouse_up(press, MouseButton::Right, Default::default());
754            cx.run_until_parked();
755            cx.update(|window, cx| {
756                window.draw(cx).clear(cx);
757            });
758
759            // Close the window without dismissing the menu.
760            cx.update(|window, _| window.remove_window());
761            cx.run_until_parked();
762        }
763
764        // The app itself is still alive here, so the global listener registry
765        // (which held the subscription's strong `Rc` clone) is too: any entity
766        // leaked by the old cycle is still reachable and detected.
767        cx.update(|cx| cx.assert_no_new_leaks(&before));
768    }
769
770    /// Records whether the content held focus as each frame began.
771    struct FocusRecordingRoot {
772        content_focus: FocusHandle,
773        content_focused_at_render: Rc<Cell<bool>>,
774    }
775
776    impl Render for FocusRecordingRoot {
777        fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
778            self.content_focused_at_render
779                .set(self.content_focus.is_focused(window));
780            div()
781                .size_full()
782                .child(
783                    div()
784                        .id("content")
785                        .h(px(40.))
786                        .track_focus(&self.content_focus),
787                )
788                .child(
789                    div()
790                        .id("tab")
791                        .h(px(60.))
792                        .context_menu(|menu, _, _| menu.menu("Close", Box::new(RemoveTab))),
793                )
794        }
795    }
796
797    /// The issue shape (#3364): a frame reports one focused accessibility
798    /// node, claimed in prepaint by whichever focused element comes first.
799    /// Moving focus to the menu while prepainting it let the previous focus
800    /// claim the frame first, which aborts debug builds.
801    #[gpui::test]
802    fn menu_takes_focus_before_its_first_frame(cx: &mut TestAppContext) {
803        cx.update(|cx| crate::init(cx));
804        let content_focused_at_render = Rc::new(Cell::new(false));
805        let (root, cx) = cx.add_window_view({
806            let content_focused_at_render = content_focused_at_render.clone();
807            move |window, cx| {
808                let content_focus = cx.focus_handle();
809                content_focus.focus(window, cx);
810                FocusRecordingRoot {
811                    content_focus,
812                    content_focused_at_render,
813                }
814            }
815        });
816        let content_focus = root.read_with(cx, |root, _| root.content_focus.clone());
817        cx.update(|window, cx| {
818            window.draw(cx).clear(cx);
819        });
820        assert!(content_focused_at_render.get());
821
822        cx.simulate_mouse_down(
823            point(px(50.), px(70.)),
824            MouseButton::Right,
825            Default::default(),
826        );
827
828        assert!(
829            !content_focused_at_render.get(),
830            "focus must leave the content before the frame that draws the menu"
831        );
832        cx.update(|window, cx| {
833            let focused = window.focused(cx);
834            assert!(focused.is_some() && focused.as_ref() != Some(&content_focus));
835        });
836    }
837
838    #[gpui::test]
839    fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
840        cx.update(|cx| {
841            crate::init(cx);
842            cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
843        });
844        let frames = Rc::new(Cell::new(0));
845        let (_, cx) = cx.add_window_view({
846            let frames = frames.clone();
847            move |_, _| UnfocusedRoot { frames }
848        });
849        cx.update(|window, cx| {
850            window.draw(cx).clear(cx);
851            assert!(window.focused(cx).is_none());
852        });
853        let frames_before_open = frames.get();
854
855        // Right-click inside the tab; the menu is built in a deferred callback
856        // and drawn on the frame that follows.
857        cx.simulate_mouse_down(
858            point(px(10.), px(10.)),
859            MouseButton::Right,
860            Default::default(),
861        );
862
863        assert_eq!(
864            frames.get(),
865            frames_before_open + 1,
866            "the press must be followed by exactly one frame for this to test the first one"
867        );
868        assert!(
869            cx.debug_bounds("kbd:ctrl-c").is_some(),
870            "the shortcut hint must be painted on the same frame as its item"
871        );
872    }
873}