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
113struct ContextMenuSharedState {
114    menu_view: Option<Entity<PopupMenu>>,
115    /// Kept while open so replacing the menu preserves its input's selection
116    /// after the input has left the focused-input registry.
117    selection_input: Option<AnyInputState>,
118    open: bool,
119    position: Point<Pixels>,
120    /// Registered on this element's dispatch node every frame and never
121    /// focused, so the menu can resolve its shortcut hints against the
122    /// trigger's key contexts on the frame it opens: GPUI looks a handle up in
123    /// the previously rendered frame, where the menu's own element is not yet.
124    trigger_focus_handle: Option<FocusHandle>,
125    _subscription: Option<Subscription>,
126}
127
128pub struct ContextMenuState {
129    element: Option<AnyElement>,
130    /// Whether this trigger draws the open menu this frame.
131    ///
132    /// Triggers without an `ElementId` fall back to their code location, so
133    /// rows rendered from one call site share the element state and all see
134    /// the menu as open. Only the trigger that was pressed draws it: stacked
135    /// copies of one `PopupMenu` share an item's pending-click state, and the
136    /// covered copies clear it on mouse up before the visible one fires.
137    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
158/// The deferred menu layer of one trigger.
159///
160/// Every trigger that shares the open state carries one, but only the trigger
161/// whose bounds contain the press builds and lays out the menu, so an open
162/// menu is rendered once per frame rather than once per row.
163struct 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        // An empty absolute placeholder, where the menu's `anchored` root used
215        // to sit, so the trigger's own layout is unchanged.
216        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        // At the pointer, the menu opens toward the end edge.
276        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        // A finger has no right button, so a long press opens the menu. This
364        // listener goes in before the children paint, so an input inside the
365        // trigger claims its long press first. Rich-text selection is handled
366        // by the window layer, which runs later; yield over its text geometry.
367        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        // Register before child paint so bubbling reaches the innermost
385        // trigger first, after its input has had a chance to take focus.
386        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
402/// Builds the menu and shows it at `position`.
403fn 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    // Capture the focused element to restore focus to on dismiss.
411    // If focus is still on the previous menu, keep its captured focus.
412    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    // Retain the old menu's owner before clearing replacement state.
423    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        // Clear any existing menu view to allow immediate replacement
438        // Set the new position and open the menu
439        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    // Use defer to build the menu in the next frame, avoiding race conditions
447    window.defer(cx, {
448        let shared_state = shared_state.clone();
449        let builder = builder.clone();
450        move |window, cx| {
451            // Resolve after pointer dispatch: the inner input has
452            // now taken focus and published its state, even if it
453            // was unfocused in the last rendered frame.
454            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            // A menu on another element must not keep the last
472            // focused input highlighted. An explicit action target
473            // takes precedence over where the press landed.
474            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            // Focus before the menu's first frame, not while prepainting it:
488            // a frame reports one focused accessibility node, and the element
489            // that held focus may already have claimed it by then.
490            menu.focus_handle(cx).focus(window, cx);
491
492            // Set up the subscription for dismiss handling.
493            // Hold a Weak here, not a strong clone: the closure
494            // would otherwise close the cycle
495            // `shared_state -> _subscription -> closure ->
496            // shared_state`, so a menu left open when the window
497            // closes leaks its PopupMenu entity.
498            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            // Update the shared state with the built menu and subscription
511            {
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    /// The regression shape: the action handler lives on the trigger's
536    /// ancestor (like an action bar), which is NOT on the focus path while
537    /// focus is in the content area.
538    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        // Right-click inside the tab to open the context menu.
596        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        // The menu entity is built and focused in a deferred callback, then
604        // rendered on the next draw.
605        cx.run_until_parked();
606        cx.update(|window, cx| {
607            _ = window.draw(cx);
608        });
609
610        // Select "Close" and confirm. Keyboard confirm and mouse click share
611        // the same `confirm` path in `PopupMenu`.
612        cx.simulate_keystrokes("down enter");
613        cx.run_until_parked();
614
615        // The action must reach the handler on the trigger's ancestor chain,
616        // even though the action bar was never on the focus path.
617        assert!(received.get());
618        // And dismiss must restore focus to where it was before the menu
619        // opened, keeping the dangling-focus fix (#2614).
620        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    /// The story shape: nothing is focused, the key binding lives in the key
628    /// context of the trigger's ancestor, and other content outside that
629    /// context paints after the trigger.
630    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    /// The issue shape (#3134): rows rendered from one call site without an
656    /// `ElementId` share the context menu's element state.
657    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        // Right-click the second row; the menu opens at the press position.
692        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        // Click the first item, which sits inside the menu's content padding.
701        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    /// Opening a context menu and closing the window without dismissing the
714    /// menu must release the `PopupMenu` entity (#3223): the dismiss
715    /// subscription used to capture a strong `Rc` clone of `shared_state`,
716    /// and the app-global listener registry kept that clone alive even after
717    /// the window (and its element state) was gone, so the menu entity
718    /// survived the window. The subscription now holds a `Weak` instead.
719    #[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            // Right-click the first row; the menu opens and is left open.
733            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            // Close the window without dismissing the menu.
742            cx.update(|window, _| window.remove_window());
743            cx.run_until_parked();
744        }
745
746        // The app itself is still alive here, so the global listener registry
747        // (which held the subscription's strong `Rc` clone) is too: any entity
748        // leaked by the old cycle is still reachable and detected.
749        cx.update(|cx| cx.assert_no_new_leaks(&before));
750    }
751
752    /// Records whether the content held focus as each frame began.
753    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    /// The issue shape (#3364): a frame reports one focused accessibility
780    /// node, claimed in prepaint by whichever focused element comes first.
781    /// Moving focus to the menu while prepainting it let the previous focus
782    /// claim the frame first, which aborts debug builds.
783    #[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        // Right-click inside the tab; the menu is built in a deferred callback
838        // and drawn on the frame that follows.
839        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}