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
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    /// Kept while open so replacing the menu preserves its input's selection
124    /// after the input has left the focused-input registry.
125    selection_input: Option<AnyInputState>,
126    open: bool,
127    position: Point<Pixels>,
128    /// Registered on this element's dispatch node every frame and never
129    /// focused, so the menu can resolve its shortcut hints against the
130    /// trigger's key contexts on the frame it opens: GPUI looks a handle up in
131    /// the previously rendered frame, where the menu's own element is not yet.
132    trigger_focus_handle: Option<FocusHandle>,
133    _subscription: Option<Subscription>,
134}
135
136pub struct ContextMenuState {
137    element: Option<AnyElement>,
138    /// Whether this trigger draws the open menu this frame.
139    ///
140    /// Triggers without an `ElementId` fall back to their code location, so
141    /// rows rendered from one call site share the element state and all see
142    /// the menu as open. Only the trigger that was pressed draws it: stacked
143    /// copies of one `PopupMenu` share an item's pending-click state, and the
144    /// covered copies clear it on mouse up before the visible one fires.
145    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
166/// The deferred menu layer of one trigger.
167///
168/// Every trigger that shares the open state carries one, but only the trigger
169/// whose bounds contain the press builds and lays out the menu, so an open
170/// menu is rendered once per frame rather than once per row.
171struct 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        // An empty absolute placeholder, where the menu's `anchored` root used
231        // to sit, so the trigger's own layout is unchanged.
232        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        // A finger has no right button, so a long press opens the menu. This
379        // listener goes in before the children paint, so an input inside the
380        // trigger claims its long press first. Rich-text selection is handled
381        // by the window layer, which runs later; yield over its text geometry.
382        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        // When right mouse click, to build content menu, and show it at the mouse position.
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                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
415/// Builds the menu and shows it at `position`.
416fn 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    // Capture the focused element to restore focus to on dismiss.
424    // If focus is still on the previous menu, keep its captured focus.
425    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    // Retain the old menu's owner before clearing replacement state.
436    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        // Clear any existing menu view to allow immediate replacement
451        // Set the new position and open the menu
452        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    // Use defer to build the menu in the next frame, avoiding race conditions
460    window.defer(cx, {
461        let shared_state = shared_state.clone();
462        let builder = builder.clone();
463        move |window, cx| {
464            // Resolve after pointer dispatch: the inner input has
465            // now taken focus and published its state, even if it
466            // was unfocused in the last rendered frame.
467            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            // A menu on another element must not keep the last
485            // focused input highlighted. An explicit action target
486            // takes precedence over where the press landed.
487            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            // Focus before the menu's first frame, not while prepainting it:
501            // a frame reports one focused accessibility node, and the element
502            // that held focus may already have claimed it by then.
503            menu.focus_handle(cx).focus(window, cx);
504
505            // Set up the subscription for dismiss handling.
506            // Hold a Weak here, not a strong clone: the closure
507            // would otherwise close the cycle
508            // `shared_state -> _subscription -> closure ->
509            // shared_state`, so a menu left open when the window
510            // closes leaks its PopupMenu entity.
511            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            // Update the shared state with the built menu and subscription
524            {
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    /// The regression shape: the action handler lives on the trigger's
549    /// ancestor (like an action bar), which is NOT on the focus path while
550    /// focus is in the content area.
551    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        // Right-click inside the tab to open the context menu.
609        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        // The menu entity is built and focused in a deferred callback, then
617        // rendered on the next draw.
618        cx.run_until_parked();
619        cx.update(|window, cx| {
620            _ = window.draw(cx);
621        });
622
623        // Select "Close" and confirm. Keyboard confirm and mouse click share
624        // the same `confirm` path in `PopupMenu`.
625        cx.simulate_keystrokes("down enter");
626        cx.run_until_parked();
627
628        // The action must reach the handler on the trigger's ancestor chain,
629        // even though the action bar was never on the focus path.
630        assert!(received.get());
631        // And dismiss must restore focus to where it was before the menu
632        // opened, keeping the dangling-focus fix (#2614).
633        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    /// The story shape: nothing is focused, the key binding lives in the key
641    /// context of the trigger's ancestor, and other content outside that
642    /// context paints after the trigger.
643    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    /// The issue shape (#3134): rows rendered from one call site without an
669    /// `ElementId` share the context menu's element state.
670    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        // Right-click the second row; the menu opens at the press position.
705        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        // Click the first item, which sits inside the menu's content padding.
714        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    /// Opening a context menu and closing the window without dismissing the
727    /// menu must release the `PopupMenu` entity (#3223): the dismiss
728    /// subscription used to capture a strong `Rc` clone of `shared_state`,
729    /// and the app-global listener registry kept that clone alive even after
730    /// the window (and its element state) was gone, so the menu entity
731    /// survived the window. The subscription now holds a `Weak` instead.
732    #[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            // Right-click the first row; the menu opens and is left open.
746            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            // Close the window without dismissing the menu.
755            cx.update(|window, _| window.remove_window());
756            cx.run_until_parked();
757        }
758
759        // The app itself is still alive here, so the global listener registry
760        // (which held the subscription's strong `Rc` clone) is too: any entity
761        // leaked by the old cycle is still reachable and detected.
762        cx.update(|cx| cx.assert_no_new_leaks(&before));
763    }
764
765    /// Records whether the content held focus as each frame began.
766    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    /// The issue shape (#3364): a frame reports one focused accessibility
793    /// node, claimed in prepaint by whichever focused element comes first.
794    /// Moving focus to the menu while prepainting it let the previous focus
795    /// claim the frame first, which aborts debug builds.
796    #[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        // Right-click inside the tab; the menu is built in a deferred callback
851        // and drawn on the frame that follows.
852        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}