Skip to main content

gpui_deck/
root.rs

1//! Window content and modal focus navigation.
2//! Modified for GPUI Deck: removed styled-layer plugins and rich-text hosting.
3use crate::StyledExt;
4use gpui::{
5    Action, AnyView, App, Context, InteractiveElement, IntoElement, KeyBinding, ParentElement,
6    Render, StyleRefinement, Styled, Subscription, Window, actions, div,
7};
8
9actions!(root, [Tab, TabPrev]);
10const CONTEXT: &str = "Root";
11
12/// Scan at most one cycle of the rendered tab order, preserving containment
13/// regardless of how many controls exist behind a modal. GPUI exposes traversal
14/// but not candidate enumeration. This scan is synchronous: only the final
15/// focus path is published at the next draw, not the background candidates.
16fn advance_focus(window: &mut Window, cx: &mut App, advance: fn(&mut Window, &mut App)) {
17    let Some(container) = crate::active_focus_trap(window, cx) else {
18        advance(window, cx);
19        return;
20    };
21
22    advance(window, cx);
23    // GPUI's tab order can cycle short of the whole window (a stop whose
24    // previous stop is itself), so the walk ends at the first repeated stop,
25    // not only on a return to the one it began with.
26    let mut visited = Vec::new();
27    while !container.contains_focused(window, cx) {
28        let focused = window.focused(cx);
29        if visited.contains(&focused) {
30            // No tab stop in the trap is reachable. Its own handle remains a
31            // safe focus target even when excluded from ordinary tab order.
32            container.focus(window, cx);
33            break;
34        }
35        visited.push(focused);
36        advance(window, cx);
37    }
38}
39
40pub(crate) fn init(cx: &mut App) {
41    cx.bind_keys([
42        KeyBinding::new("tab", Tab, Some(CONTEXT)),
43        KeyBinding::new("shift-tab", TabPrev, Some(CONTEXT)),
44    ]);
45}
46
47/// The window's content and overlay host, independent of any styled component library.
48pub struct Root {
49    view: AnyView,
50    style: StyleRefinement,
51    /// Runs Tab and Shift-Tab while nothing in the window is focused. GPUI
52    /// then dispatches from the window's root element, above this root's key
53    /// context, so the context bindings match nothing there.
54    _unfocused_tab: Subscription,
55}
56
57impl Root {
58    pub fn new(view: impl Into<AnyView>, window: &mut Window, cx: &mut Context<Self>) -> Self {
59        #[cfg(all(target_os = "macos", not(test)))]
60        crate::install_window_hit_test_forwarder(window);
61        let window_handle = window.window_handle();
62        let unfocused_tab = cx.observe_keystrokes(move |_, event, window, cx| {
63            // Only a key that no binding took, in this window, with nothing
64            // focused, so an application binding for Tab still wins.
65            if event.action.is_some()
66                || window.window_handle() != window_handle
67                || window.focused(cx).is_some()
68            {
69                return;
70            }
71            // Read the keymap so that rebinding the actions carries over.
72            let bound_to = |action: &dyn Action, cx: &App| {
73                cx.key_bindings()
74                    .borrow()
75                    .bindings_for_action(action)
76                    .any(|binding| {
77                        binding.match_keystrokes(std::slice::from_ref(&event.keystroke))
78                            == Some(false)
79                    })
80            };
81            if bound_to(&Tab, cx) {
82                advance_focus(window, cx, Window::focus_next);
83            } else if bound_to(&TabPrev, cx) {
84                advance_focus(window, cx, Window::focus_prev);
85            }
86        });
87        Self {
88            view: view.into(),
89            style: StyleRefinement::default(),
90            _unfocused_tab: unfocused_tab,
91        }
92    }
93
94    /// The original application content entity.
95    pub fn view(&self) -> &AnyView {
96        &self.view
97    }
98
99    pub fn read<'a>(window: &'a Window, cx: &'a App) -> &'a Self {
100        window
101            .root::<Self>()
102            .flatten()
103            .expect("window must have a GPUI Deck Root")
104            .read(cx)
105    }
106    pub fn update<R>(
107        window: &mut Window,
108        cx: &mut App,
109        f: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
110    ) -> R {
111        let root = window
112            .root::<Self>()
113            .flatten()
114            .expect("window must have a GPUI Deck Root");
115        root.update(cx, |root, cx| f(root, window, cx))
116    }
117    fn on_action_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
118        advance_focus(window, cx, Window::focus_next);
119    }
120
121    fn on_action_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
122        advance_focus(window, cx, Window::focus_prev);
123    }
124}
125impl Styled for Root {
126    fn style(&mut self) -> &mut StyleRefinement {
127        &mut self.style
128    }
129}
130impl Render for Root {
131    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
132        #[cfg(feature = "test-support")]
133        crate::test_support::begin_frame(window);
134        #[cfg(not(feature = "test-support"))]
135        let _ = window;
136        div()
137            .id("root")
138            .key_context(CONTEXT)
139            .on_action(cx.listener(Self::on_action_tab))
140            .on_action(cx.listener(Self::on_action_tab_prev))
141            .relative()
142            .size_full()
143            .child(self.view.clone())
144            .refine_style(&self.style)
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use crate::FocusTrapElement as _;
152    use gpui::{AppContext, FocusHandle, Subscription, TestAppContext, VisualTestContext, px};
153    use std::{cell::Cell, rc::Rc};
154
155    struct TrapContent {
156        background: Vec<FocusHandle>,
157        container: FocusHandle,
158        controls: Vec<FocusHandle>,
159        _focus_subscriptions: Vec<Subscription>,
160    }
161
162    impl Render for TrapContent {
163        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
164            div()
165                .tab_group()
166                .size_full()
167                .children(self.background.iter().enumerate().map(|(index, handle)| {
168                    div()
169                        .id(("background", index))
170                        .track_focus(handle)
171                        .tab_index(0)
172                        .size(px(1.))
173                }))
174                .child(
175                    div()
176                        .id("trap")
177                        .track_focus(&self.container)
178                        .tab_stop(false)
179                        .children(self.controls.iter().enumerate().map(|(index, handle)| {
180                            div()
181                                .id(("control", index))
182                                .track_focus(handle)
183                                .tab_index(0)
184                                .size(px(1.))
185                        }))
186                        .focus_trap("modal", &self.container),
187                )
188        }
189    }
190
191    fn trap_harness(
192        cx: &mut TestAppContext,
193        control_count: usize,
194    ) -> (
195        &mut VisualTestContext,
196        FocusHandle,
197        Vec<FocusHandle>,
198        Vec<FocusHandle>,
199        Rc<Cell<usize>>,
200    ) {
201        cx.update(crate::init);
202        let (container, controls, background) = cx.update(|cx| {
203            (
204                cx.focus_handle(),
205                (0..control_count)
206                    .map(|_| cx.focus_handle().tab_stop(true))
207                    .collect::<Vec<_>>(),
208                // Regression: traversing past the modal must cross more than
209                // the former 100-attempt limit before reaching its other end.
210                (0..256)
211                    .map(|_| cx.focus_handle().tab_stop(true))
212                    .collect::<Vec<_>>(),
213            )
214        });
215        let background_focuses = Rc::new(Cell::new(0));
216        let (_, cx) = cx.add_window_view({
217            let container = container.clone();
218            let controls = controls.clone();
219            let background = background.clone();
220            let background_focuses = background_focuses.clone();
221            move |window, cx| {
222                let content = cx.new(|cx| {
223                    let subscriptions = background
224                        .iter()
225                        .map(|handle| {
226                            let focuses = background_focuses.clone();
227                            cx.on_focus(handle, window, move |_, _, _| {
228                                focuses.set(focuses.get() + 1)
229                            })
230                        })
231                        .collect();
232                    TrapContent {
233                        background,
234                        container,
235                        controls,
236                        _focus_subscriptions: subscriptions,
237                    }
238                });
239                Root::new(content, window, cx)
240            }
241        });
242        cx.update(|window, _| window.activate_window());
243        cx.executor().run_until_parked();
244        cx.update(|window, cx| window.draw(cx).clear(cx));
245        (cx, container, controls, background, background_focuses)
246    }
247
248    fn assert_trapped_focus(
249        cx: &mut VisualTestContext,
250        container: &FocusHandle,
251        expected: &FocusHandle,
252    ) {
253        cx.update(|window, cx| {
254            window.draw(cx).clear(cx);
255            assert_eq!(window.focused(cx).as_ref(), Some(expected));
256            assert!(container.contains_focused(window, cx));
257        });
258    }
259
260    #[gpui::test]
261    fn focus_trap_wraps_forward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
262        let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
263        cx.update(|window, cx| {
264            controls[1].focus(window, cx);
265            window.draw(cx).clear(cx);
266        });
267
268        cx.dispatch_action(Tab);
269        assert_trapped_focus(cx, &container, &controls[0]);
270        cx.dispatch_action(Tab);
271        assert_trapped_focus(cx, &container, &controls[1]);
272        assert_eq!(background_focuses.get(), 0);
273    }
274
275    #[gpui::test]
276    fn focus_trap_wraps_backward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
277        let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
278        cx.update(|window, cx| {
279            controls[0].focus(window, cx);
280            window.draw(cx).clear(cx);
281        });
282
283        cx.dispatch_action(TabPrev);
284        assert_trapped_focus(cx, &container, &controls[1]);
285        cx.dispatch_action(TabPrev);
286        assert_trapped_focus(cx, &container, &controls[0]);
287        assert_eq!(background_focuses.get(), 0);
288    }
289
290    #[gpui::test]
291    fn focus_trap_without_tab_stops_keeps_its_container_focused(cx: &mut TestAppContext) {
292        let (cx, container, _, _, background_focuses) = trap_harness(cx, 0);
293        cx.update(|window, cx| {
294            container.focus(window, cx);
295            window.draw(cx).clear(cx);
296        });
297
298        cx.dispatch_action(Tab);
299        assert_trapped_focus(cx, &container, &container);
300        cx.dispatch_action(TabPrev);
301        assert_trapped_focus(cx, &container, &container);
302        assert_eq!(background_focuses.get(), 0);
303    }
304
305    thread_local! {
306        static SCRIPTED_STOPS: std::cell::RefCell<Vec<FocusHandle>> =
307            const { std::cell::RefCell::new(Vec::new()) };
308    }
309
310    /// Moves focus to the next scripted stop, in place of `focus_prev`. Running
311    /// out fails the test, so a search that never stops cannot hang it.
312    fn scripted_advance(window: &mut Window, cx: &mut App) {
313        SCRIPTED_STOPS
314            .with(|stops| stops.borrow_mut().pop())
315            .expect("the search kept advancing after a stop repeated")
316            .focus(window, cx);
317    }
318
319    #[gpui::test]
320    fn focus_trap_search_ends_at_a_short_cycle_on_its_container(cx: &mut TestAppContext) {
321        let (cx, container, controls, background, _) = trap_harness(cx, 2);
322        cx.update(|window, cx| {
323            controls[0].focus(window, cx);
324            window.draw(cx).clear(cx);
325        });
326        // A tab order in which the second stop is its own neighbor never
327        // returns to the first. Popped from the end: first, second, second.
328        let (first, second) = (background[0].clone(), background[1].clone());
329        SCRIPTED_STOPS.with(|stops| *stops.borrow_mut() = vec![second.clone(), second, first]);
330
331        cx.update(|window, cx| advance_focus(window, cx, scripted_advance));
332        assert_trapped_focus(cx, &container, &container);
333        assert!(SCRIPTED_STOPS.with(|stops| stops.borrow().is_empty()));
334    }
335
336    #[gpui::test]
337    fn inactive_focus_trap_does_not_capture_background_navigation(cx: &mut TestAppContext) {
338        let (cx, _, _, background, background_focuses) = trap_harness(cx, 2);
339        cx.update(|window, cx| {
340            background[0].focus(window, cx);
341            window.draw(cx).clear(cx);
342        });
343        // Prove that the observers used by the containment regressions really
344        // receive native focus notifications when a background control is used.
345        assert_eq!(background_focuses.get(), 1);
346
347        cx.dispatch_action(Tab);
348        cx.update(|window, cx| {
349            window.draw(cx).clear(cx);
350            assert_eq!(window.focused(cx), Some(background[1].clone()));
351        });
352        cx.dispatch_action(TabPrev);
353        cx.update(|window, cx| {
354            window.draw(cx).clear(cx);
355            assert_eq!(window.focused(cx), Some(background[0].clone()));
356        });
357        assert_eq!(background_focuses.get(), 3);
358    }
359
360    struct Stops(Vec<FocusHandle>);
361
362    impl Render for Stops {
363        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
364            div()
365                .tab_group()
366                .size_full()
367                .children(self.0.iter().enumerate().map(|(index, handle)| {
368                    div()
369                        .id(("stop", index))
370                        .track_focus(handle)
371                        .tab_index(0)
372                        .size(px(10.))
373                }))
374        }
375    }
376
377    actions!(root_test, [AppTab]);
378
379    #[gpui::test]
380    fn tab_and_shift_tab_reach_controls_while_nothing_is_focused(cx: &mut TestAppContext) {
381        cx.update(crate::init);
382        let stops = cx.update(|cx| {
383            (0..3)
384                .map(|_| cx.focus_handle().tab_stop(true))
385                .collect::<Vec<_>>()
386        });
387        let (_, cx) = cx.add_window_view({
388            let stops = stops.clone();
389            move |window, cx| Root::new(cx.new(|_| Stops(stops)), window, cx)
390        });
391        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
392        draw(cx);
393        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
394
395        cx.simulate_keystrokes("tab");
396        draw(cx);
397        cx.update(|window, cx| assert_eq!(window.focused(cx), Some(stops[0].clone())));
398
399        cx.update(|window, cx| window.blur(cx));
400        draw(cx);
401        cx.simulate_keystrokes("shift-tab");
402        draw(cx);
403        cx.update(|window, cx| assert_eq!(window.focused(cx), Some(stops[2].clone())));
404
405        // An application binding for Tab outside any context takes the key.
406        let ran = Rc::new(Cell::new(false));
407        cx.update({
408            let ran = ran.clone();
409            move |window, cx| {
410                cx.bind_keys([KeyBinding::new("tab", AppTab, None)]);
411                cx.on_action(move |_: &AppTab, _| ran.set(true));
412                window.blur(cx);
413            }
414        });
415        draw(cx);
416        cx.simulate_keystrokes("tab");
417        draw(cx);
418        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
419        assert!(ran.get());
420    }
421
422    mod nested_traps {
423        use super::*;
424
425        struct NestedTraps {
426            containers: Vec<FocusHandle>,
427            controls: Vec<[FocusHandle; 2]>,
428            depth: usize,
429        }
430
431        impl Render for NestedTraps {
432            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
433                let mut child = div().into_any_element();
434                for index in (0..self.depth).rev() {
435                    let control = |side: usize| {
436                        div()
437                            .id(("nested-control", index * 2 + side))
438                            .track_focus(&self.controls[index][side])
439                            .tab_index(0)
440                            .size(px(10.))
441                    };
442                    child = div()
443                        .tab_stop(false)
444                        .child(control(0))
445                        .child(child)
446                        .child(control(1))
447                        .focus_trap(("nested-trap", index), &self.containers[index])
448                        .into_any_element();
449                }
450                div().tab_group().size_full().child(child)
451            }
452        }
453
454        #[gpui::test]
455        fn nested_traps_keep_the_innermost_scope_across_close_and_reopen(cx: &mut TestAppContext) {
456            cx.update(crate::init);
457            let (containers, controls) = cx.update(|cx| {
458                (
459                    (0..6).map(|_| cx.focus_handle()).collect::<Vec<_>>(),
460                    (0..6)
461                        .map(|_| {
462                            [
463                                cx.focus_handle().tab_stop(true),
464                                cx.focus_handle().tab_stop(true),
465                            ]
466                        })
467                        .collect::<Vec<_>>(),
468                )
469            });
470            let (root, cx) = cx.add_window_view({
471                let containers = containers.clone();
472                let controls = controls.clone();
473                move |window, cx| {
474                    let view = cx.new(|_| NestedTraps {
475                        containers,
476                        controls,
477                        depth: 6,
478                    });
479                    Root::new(view, window, cx)
480                }
481            });
482            let view = root.read_with(cx, |root, _| {
483                root.view.clone().downcast::<NestedTraps>().unwrap()
484            });
485
486            // Retain every container handle while inner scopes disappear and
487            // return. Rendered containment, not registration order or ownership
488            // lifetime, must decide which remaining scope handles Tab.
489            for depth in [6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6] {
490                view.update(cx, |view, cx| {
491                    view.depth = depth;
492                    cx.notify();
493                });
494                let index = depth - 1;
495                cx.update(|window, cx| {
496                    controls[index][1].focus(window, cx);
497                    window.draw(cx).clear(cx);
498                });
499                cx.dispatch_action(Tab);
500                assert_trapped_focus(cx, &containers[index], &controls[index][0]);
501                cx.dispatch_action(TabPrev);
502                assert_trapped_focus(cx, &containers[index], &controls[index][1]);
503            }
504        }
505    }
506}