1use crate::input::Copy;
3use crate::{StyledExt, TextSelectionLayer};
4use gpui::{
5 Action, AnyElement, AnyView, App, AppContext, ClipboardItem, Context, Div, Entity, Global,
6 InteractiveElement, IntoElement, KeyBinding, ParentElement, Render, Stateful, StyleRefinement,
7 Styled, Subscription, Window, actions, div, prelude::FluentBuilder as _,
8};
9use std::{any::TypeId, rc::Rc};
10
11actions!(root, [Tab, TabPrev]);
12const CONTEXT: &str = "Root";
13
14fn advance_focus(window: &mut Window, cx: &mut App, advance: fn(&mut Window, &mut App)) {
19 let Some(container) = crate::active_focus_trap(window, cx) else {
20 advance(window, cx);
21 return;
22 };
23
24 advance(window, cx);
25 let mut visited = Vec::new();
29 while !container.contains_focused(window, cx) {
30 let focused = window.focused(cx);
31 if visited.contains(&focused) {
32 container.focus(window, cx);
35 break;
36 }
37 visited.push(focused);
38 advance(window, cx);
39 }
40}
41
42pub(crate) fn init(cx: &mut App) {
43 cx.bind_keys([
44 KeyBinding::new("tab", Tab, Some(CONTEXT)),
45 KeyBinding::new("shift-tab", TabPrev, Some(CONTEXT)),
46 #[cfg(target_os = "macos")]
47 KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
48 #[cfg(not(target_os = "macos"))]
49 KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
50 ]);
51}
52
53pub trait RootPlugin: Render + Sized {
75 fn prepare(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
81
82 fn style(&self, _surface: &mut Stateful<Div>, _window: &mut Window, _cx: &mut App) {}
87
88 fn decorate(
95 &self,
96 surface: AnyElement,
97 _root: &Root,
98 _window: &mut Window,
99 _cx: &mut App,
100 ) -> impl IntoElement {
101 surface
102 }
103
104 fn has_open_layers(&self, _cx: &App) -> bool {
113 true
114 }
115}
116
117type PluginFactory = Rc<dyn Fn(&mut Window, &mut Context<Root>) -> Plugin>;
118type Prepare = Rc<dyn Fn(&mut Window, &mut App)>;
119type SurfaceStyle = Rc<dyn Fn(&mut Stateful<Div>, &mut Window, &mut App)>;
120type Decorate = Rc<dyn Fn(AnyElement, &Root, &mut Window, &mut App) -> AnyElement>;
121type HasOpenLayers = Rc<dyn Fn(&App) -> bool>;
122#[derive(Default)]
123struct PluginRegistry(Vec<(TypeId, PluginFactory)>);
124impl Global for PluginRegistry {}
125struct Plugin {
126 view: AnyView,
127 prepare: Prepare,
128 style: SurfaceStyle,
129 decorate: Decorate,
130 has_open_layers: HasOpenLayers,
131}
132
133pub struct Root {
135 view: AnyView,
136 style: StyleRefinement,
137 plugins: Vec<Plugin>,
138 _unfocused_tab: Subscription,
143}
144
145impl Root {
146 pub fn register_plugin<V: RootPlugin>(
149 cx: &mut App,
150 build: fn(&mut Window, &mut Context<V>) -> V,
151 ) {
152 if !cx.has_global::<PluginRegistry>() {
153 cx.set_global(PluginRegistry::default());
154 }
155 let factory: PluginFactory = Rc::new(move |window, cx| {
156 let entity = cx.new(|cx| build(window, cx));
157 let root = cx.weak_entity();
158 let observed = entity.clone();
159 cx.defer(move |cx| {
163 cx.observe(&observed, move |_, cx| {
164 let _ = root.update(cx, |_, cx| cx.notify());
165 })
166 .detach();
167 });
168 let prepare = entity.clone();
169 let style = entity.clone();
170 let decorate = entity.clone();
171 let has_open_layers = entity.clone();
172 Plugin {
173 view: entity.into(),
174 prepare: Rc::new(move |window, cx| {
175 prepare.update(cx, |state, cx| state.prepare(window, cx))
176 }),
177 style: Rc::new(move |surface, window, cx| {
178 style.update(cx, |state, cx| state.style(surface, window, cx))
179 }),
180 decorate: Rc::new(move |surface, root, window, cx| {
181 decorate.update(cx, |state, cx| {
182 state.decorate(surface, root, window, cx).into_any_element()
183 })
184 }),
185 has_open_layers: Rc::new(move |cx| has_open_layers.read(cx).has_open_layers(cx)),
186 }
187 });
188 let plugins = &mut cx.global_mut::<PluginRegistry>().0;
189 if let Some(entry) = plugins.iter_mut().find(|(id, _)| *id == TypeId::of::<V>()) {
190 entry.1 = factory;
191 } else {
192 plugins.push((TypeId::of::<V>(), factory));
193 }
194 }
195
196 pub fn new(view: impl Into<AnyView>, window: &mut Window, cx: &mut Context<Self>) -> Self {
197 #[cfg(all(target_os = "macos", not(test)))]
198 crate::install_window_hit_test_forwarder(window);
199 let factories = cx
200 .try_global::<PluginRegistry>()
201 .map(|e| e.0.clone())
202 .unwrap_or_default();
203 let window_handle = window.window_handle();
204 let unfocused_tab = cx.observe_keystrokes(move |_, event, window, cx| {
205 if event.action.is_some()
207 || window.window_handle() != window_handle
208 || window.focused(cx).is_some()
209 {
210 return;
211 }
212 let bound_to = |action: &dyn Action, cx: &App| {
213 cx.key_bindings()
214 .borrow()
215 .bindings_for_action(action)
216 .any(|binding| {
217 binding.match_keystrokes(std::slice::from_ref(&event.keystroke))
218 == Some(false)
219 })
220 };
221 if bound_to(&Tab, cx) {
222 advance_focus(window, cx, Window::focus_next);
223 } else if bound_to(&TabPrev, cx) {
224 advance_focus(window, cx, Window::focus_prev);
225 }
226 });
227 Self {
228 view: view.into(),
229 style: StyleRefinement::default(),
230 plugins: factories
231 .into_iter()
232 .map(|(_, build)| build(window, cx))
233 .collect(),
234 _unfocused_tab: unfocused_tab,
235 }
236 }
237
238 pub fn view(&self) -> &AnyView {
240 &self.view
241 }
242
243 pub fn plugin<V: RootPlugin>(&self) -> Option<Entity<V>> {
245 self.plugins
246 .iter()
247 .find_map(|entry| entry.view.clone().downcast::<V>().ok())
248 }
249
250 pub fn read<'a>(window: &'a Window, cx: &'a App) -> &'a Self {
251 window
252 .root::<Self>()
253 .flatten()
254 .expect("window must have a Base Root")
255 .read(cx)
256 }
257 pub fn update<R>(
258 window: &mut Window,
259 cx: &mut App,
260 f: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
261 ) -> R {
262 let root = window
263 .root::<Self>()
264 .flatten()
265 .expect("window must have a Base Root");
266 root.update(cx, |root, cx| f(root, window, cx))
267 }
268 fn on_action_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
269 advance_focus(window, cx, Window::focus_next);
270 }
271
272 fn on_action_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
273 advance_focus(window, cx, Window::focus_prev);
274 }
275
276 fn on_action_copy(&mut self, _: &Copy, window: &mut Window, cx: &mut Context<Self>) {
277 let text = crate::TextSelection::selected_text(window, cx)
278 .trim()
279 .to_string();
280 if text.is_empty() {
281 cx.propagate();
282 return;
283 }
284 cx.write_to_clipboard(ClipboardItem::new_string(text));
285 }
286}
287impl Styled for Root {
288 fn style(&mut self) -> &mut StyleRefinement {
289 &mut self.style
290 }
291}
292impl Render for Root {
293 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
294 #[cfg(feature = "test-support")]
295 crate::test_support::begin_frame(window);
296 for plugin in &self.plugins {
297 (plugin.prepare)(window, cx);
298 }
299 let picking = window.is_inspector_picking(cx);
300 let mut content = div()
301 .id("root")
302 .key_context(CONTEXT)
303 .on_action(cx.listener(Self::on_action_tab))
304 .on_action(cx.listener(Self::on_action_tab_prev))
305 .on_action(cx.listener(Self::on_action_copy))
306 .relative()
307 .size_full()
308 .child(TextSelectionLayer)
309 .child(self.view.clone())
310 .children(self.plugins.iter().map(|plugin| {
311 let collapse = picking && !(plugin.has_open_layers)(cx);
314 div()
315 .absolute()
316 .map(|this| {
317 if collapse {
318 this.size_0()
319 } else {
320 this.inset_0()
321 }
322 })
323 .child(plugin.view.clone())
324 }));
325 for plugin in &self.plugins {
326 (plugin.style)(&mut content, window, cx);
327 }
328 let mut content = content.refine_style(&self.style).into_any_element();
329 for plugin in &self.plugins {
330 content = (plugin.decorate)(content, self, window, cx);
331 }
332 content
333 }
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use crate::FocusTrapElement as _;
340 use gpui::{FocusHandle, Subscription, TestAppContext, VisualTestContext, px};
341 use std::cell::Cell;
342
343 struct TrapContent {
344 background: Vec<FocusHandle>,
345 container: FocusHandle,
346 controls: Vec<FocusHandle>,
347 _focus_subscriptions: Vec<Subscription>,
348 }
349
350 impl Render for TrapContent {
351 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
352 div()
353 .tab_group()
354 .size_full()
355 .children(self.background.iter().enumerate().map(|(index, handle)| {
356 div()
357 .id(("background", index))
358 .track_focus(handle)
359 .tab_index(0)
360 .size(px(1.))
361 }))
362 .child(
363 div()
364 .id("trap")
365 .track_focus(&self.container)
366 .tab_stop(false)
367 .children(self.controls.iter().enumerate().map(|(index, handle)| {
368 div()
369 .id(("control", index))
370 .track_focus(handle)
371 .tab_index(0)
372 .size(px(1.))
373 }))
374 .focus_trap("modal", &self.container),
375 )
376 }
377 }
378
379 fn trap_harness(
380 cx: &mut TestAppContext,
381 control_count: usize,
382 ) -> (
383 &mut VisualTestContext,
384 FocusHandle,
385 Vec<FocusHandle>,
386 Vec<FocusHandle>,
387 Rc<Cell<usize>>,
388 ) {
389 cx.update(crate::init);
390 let (container, controls, background) = cx.update(|cx| {
391 (
392 cx.focus_handle(),
393 (0..control_count)
394 .map(|_| cx.focus_handle().tab_stop(true))
395 .collect::<Vec<_>>(),
396 (0..256)
399 .map(|_| cx.focus_handle().tab_stop(true))
400 .collect::<Vec<_>>(),
401 )
402 });
403 let background_focuses = Rc::new(Cell::new(0));
404 let (_, cx) = cx.add_window_view({
405 let container = container.clone();
406 let controls = controls.clone();
407 let background = background.clone();
408 let background_focuses = background_focuses.clone();
409 move |window, cx| {
410 let content = cx.new(|cx| {
411 let subscriptions = background
412 .iter()
413 .map(|handle| {
414 let focuses = background_focuses.clone();
415 cx.on_focus(handle, window, move |_, _, _| {
416 focuses.set(focuses.get() + 1)
417 })
418 })
419 .collect();
420 TrapContent {
421 background,
422 container,
423 controls,
424 _focus_subscriptions: subscriptions,
425 }
426 });
427 Root::new(content, window, cx)
428 }
429 });
430 cx.update(|window, _| window.activate_window());
431 cx.executor().run_until_parked();
432 cx.update(|window, cx| window.draw(cx).clear(cx));
433 (cx, container, controls, background, background_focuses)
434 }
435
436 fn assert_trapped_focus(
437 cx: &mut VisualTestContext,
438 container: &FocusHandle,
439 expected: &FocusHandle,
440 ) {
441 cx.update(|window, cx| {
442 window.draw(cx).clear(cx);
443 assert_eq!(window.focused(cx).as_ref(), Some(expected));
444 assert!(container.contains_focused(window, cx));
445 });
446 }
447
448 #[gpui::test]
449 fn focus_trap_wraps_forward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
450 let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
451 cx.update(|window, cx| {
452 controls[1].focus(window, cx);
453 window.draw(cx).clear(cx);
454 });
455
456 cx.dispatch_action(Tab);
457 assert_trapped_focus(cx, &container, &controls[0]);
458 cx.dispatch_action(Tab);
459 assert_trapped_focus(cx, &container, &controls[1]);
460 assert_eq!(background_focuses.get(), 0);
461 }
462
463 #[gpui::test]
464 fn focus_trap_wraps_backward_past_more_than_100_background_stops(cx: &mut TestAppContext) {
465 let (cx, container, controls, _, background_focuses) = trap_harness(cx, 2);
466 cx.update(|window, cx| {
467 controls[0].focus(window, cx);
468 window.draw(cx).clear(cx);
469 });
470
471 cx.dispatch_action(TabPrev);
472 assert_trapped_focus(cx, &container, &controls[1]);
473 cx.dispatch_action(TabPrev);
474 assert_trapped_focus(cx, &container, &controls[0]);
475 assert_eq!(background_focuses.get(), 0);
476 }
477
478 #[gpui::test]
479 fn focus_trap_without_tab_stops_keeps_its_container_focused(cx: &mut TestAppContext) {
480 let (cx, container, _, _, background_focuses) = trap_harness(cx, 0);
481 cx.update(|window, cx| {
482 container.focus(window, cx);
483 window.draw(cx).clear(cx);
484 });
485
486 cx.dispatch_action(Tab);
487 assert_trapped_focus(cx, &container, &container);
488 cx.dispatch_action(TabPrev);
489 assert_trapped_focus(cx, &container, &container);
490 assert_eq!(background_focuses.get(), 0);
491 }
492
493 thread_local! {
494 static SCRIPTED_STOPS: std::cell::RefCell<Vec<FocusHandle>> =
495 const { std::cell::RefCell::new(Vec::new()) };
496 }
497
498 fn scripted_advance(window: &mut Window, cx: &mut App) {
501 SCRIPTED_STOPS
502 .with(|stops| stops.borrow_mut().pop())
503 .expect("the search kept advancing after a stop repeated")
504 .focus(window, cx);
505 }
506
507 #[gpui::test]
508 fn focus_trap_search_ends_at_a_short_cycle_on_its_container(cx: &mut TestAppContext) {
509 let (cx, container, controls, background, _) = trap_harness(cx, 2);
510 cx.update(|window, cx| {
511 controls[0].focus(window, cx);
512 window.draw(cx).clear(cx);
513 });
514 let (first, second) = (background[0].clone(), background[1].clone());
517 SCRIPTED_STOPS.with(|stops| *stops.borrow_mut() = vec![second.clone(), second, first]);
518
519 cx.update(|window, cx| advance_focus(window, cx, scripted_advance));
520 assert_trapped_focus(cx, &container, &container);
521 assert!(SCRIPTED_STOPS.with(|stops| stops.borrow().is_empty()));
522 }
523
524 #[gpui::test]
525 fn inactive_focus_trap_does_not_capture_background_navigation(cx: &mut TestAppContext) {
526 let (cx, _, _, background, background_focuses) = trap_harness(cx, 2);
527 cx.update(|window, cx| {
528 background[0].focus(window, cx);
529 window.draw(cx).clear(cx);
530 });
531 assert_eq!(background_focuses.get(), 1);
534
535 cx.dispatch_action(Tab);
536 cx.update(|window, cx| {
537 window.draw(cx).clear(cx);
538 assert_eq!(window.focused(cx), Some(background[1].clone()));
539 });
540 cx.dispatch_action(TabPrev);
541 cx.update(|window, cx| {
542 window.draw(cx).clear(cx);
543 assert_eq!(window.focused(cx), Some(background[0].clone()));
544 });
545 assert_eq!(background_focuses.get(), 3);
546 }
547
548 struct Content;
549 impl Render for Content {
550 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
551 div()
552 }
553 }
554 struct Layer;
555 impl Render for Layer {
556 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
557 div()
558 }
559 }
560 impl RootPlugin for Layer {}
561 fn layer(_: &mut Window, _: &mut Context<Layer>) -> Layer {
562 Layer
563 }
564
565 #[gpui::test]
566 fn plugin_registration_is_idempotent_and_state_is_per_window(cx: &mut TestAppContext) {
567 cx.update(|cx| {
568 crate::init(cx);
569 Root::register_plugin(cx, layer);
570 Root::register_plugin(cx, layer);
571 });
572 let mut ids = Vec::new();
573 for _ in 0..2 {
574 let (root, _) = cx.add_window_view(|window, cx| {
575 let content = cx.new(|_| Content);
576 Root::new(content, window, cx)
577 });
578 let id = root.read_with(cx, |root, _| {
579 assert_eq!(root.plugins.len(), 1);
580 root.plugin::<Layer>().unwrap().entity_id()
581 });
582 ids.push(id);
583 }
584 assert_ne!(ids[0], ids[1]);
585 }
586
587 mod nested_traps {
588 use super::*;
589
590 struct NestedTraps {
591 containers: Vec<FocusHandle>,
592 controls: Vec<[FocusHandle; 2]>,
593 depth: usize,
594 }
595
596 impl Render for NestedTraps {
597 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
598 let mut child = div().into_any_element();
599 for index in (0..self.depth).rev() {
600 let control = |side: usize| {
601 div()
602 .id(("nested-control", index * 2 + side))
603 .track_focus(&self.controls[index][side])
604 .tab_index(0)
605 .size(px(10.))
606 };
607 child = div()
608 .tab_stop(false)
609 .child(control(0))
610 .child(child)
611 .child(control(1))
612 .focus_trap(("nested-trap", index), &self.containers[index])
613 .into_any_element();
614 }
615 div().tab_group().size_full().child(child)
616 }
617 }
618
619 #[gpui::test]
620 fn nested_traps_keep_the_innermost_scope_across_close_and_reopen(cx: &mut TestAppContext) {
621 cx.update(crate::init);
622 let (containers, controls) = cx.update(|cx| {
623 (
624 (0..6).map(|_| cx.focus_handle()).collect::<Vec<_>>(),
625 (0..6)
626 .map(|_| {
627 [
628 cx.focus_handle().tab_stop(true),
629 cx.focus_handle().tab_stop(true),
630 ]
631 })
632 .collect::<Vec<_>>(),
633 )
634 });
635 let (root, cx) = cx.add_window_view({
636 let containers = containers.clone();
637 let controls = controls.clone();
638 move |window, cx| {
639 let view = cx.new(|_| NestedTraps {
640 containers,
641 controls,
642 depth: 6,
643 });
644 Root::new(view, window, cx)
645 }
646 });
647 let view = root.read_with(cx, |root, _| {
648 root.view.clone().downcast::<NestedTraps>().unwrap()
649 });
650
651 for depth in [6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6] {
655 view.update(cx, |view, cx| {
656 view.depth = depth;
657 cx.notify();
658 });
659 let index = depth - 1;
660 cx.update(|window, cx| {
661 controls[index][1].focus(window, cx);
662 window.draw(cx).clear(cx);
663 });
664 cx.dispatch_action(Tab);
665 assert_trapped_focus(cx, &containers[index], &controls[index][0]);
666 cx.dispatch_action(TabPrev);
667 assert_trapped_focus(cx, &containers[index], &controls[index][1]);
668 }
669 }
670 }
671 struct BottomBarDemo {
672 bar: Rc<Cell<Option<gpui::Bounds<gpui::Pixels>>>>,
673 }
674
675 impl Render for BottomBarDemo {
676 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
677 let bar = self.bar.clone();
678 div()
679 .size_full()
680 .flex()
681 .flex_col()
682 .child(div().flex_1().w_full())
683 .child(
684 div().h(px(40.)).w_full().child(
685 gpui::canvas(move |bounds, _, _| bar.set(Some(bounds)), |_, _, _, _| {})
686 .size_full(),
687 ),
688 )
689 }
690 }
691
692 #[gpui::test]
695 fn size_full_view_fills_window_height(cx: &mut TestAppContext) {
696 cx.update(crate::init);
697 let bar = Rc::new(Cell::new(None));
698 let (_, cx) = cx.add_window_view({
699 let bar = bar.clone();
700 move |window, cx| {
701 let view = cx.new(|_| BottomBarDemo { bar });
702 Root::new(view, window, cx)
703 }
704 });
705 let viewport = cx.update(|window, cx| {
706 window.draw(cx).clear(cx);
707 window.viewport_size()
708 });
709 let bounds = bar.get().expect("bar painted");
710 assert_eq!(
711 bounds.bottom(),
712 viewport.height,
713 "bar at {bounds:?}, viewport {viewport:?}"
714 );
715 }
716}