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