Skip to main content

gpui_component/
root.rs

1use crate::{
2    ActiveTheme, ElementExt, Placement, StyledExt,
3    dialog::{ANIMATION_DURATION, Dialog},
4    input::{AnyInputState, Copy},
5    native_menu::FallbackMenuOverlay,
6    notification::{Notification, NotificationList},
7    sheet::Sheet,
8    tooltip::render_tooltip,
9    window_border,
10};
11use gpui::{
12    AnyView, App, AppContext, ClipboardItem, Context, DefiniteLength, ElementId, Entity,
13    FocusHandle, InteractiveElement, IntoElement, KeyBinding, ParentElement as _, Pixels, Render,
14    StyleRefinement, Styled, WeakFocusHandle, Window, actions, div, prelude::FluentBuilder as _,
15};
16use gpui_base::{TextSelection, TextSelectionLayer, TextSelectionScopeId};
17use std::{any::TypeId, rc::Rc};
18
19actions!(root, [Tab, TabPrev]);
20
21const CONTEXT: &str = "Root";
22pub(crate) fn init(cx: &mut App) {
23    cx.bind_keys([
24        KeyBinding::new("tab", Tab, Some(CONTEXT)),
25        KeyBinding::new("shift-tab", TabPrev, Some(CONTEXT)),
26        #[cfg(target_os = "macos")]
27        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
28        #[cfg(not(target_os = "macos"))]
29        KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
30    ]);
31}
32
33/// Root is a view for the App window for as the top level view (Must be the first view in the window).
34///
35/// It is used to manage the Sheet, Dialog, and Notification.
36pub struct Root {
37    style: StyleRefinement,
38    view: AnyView,
39    pub(crate) active_sheet: Option<ActiveSheet>,
40    pub(crate) active_dialogs: Vec<ActiveDialog>,
41    pub(super) focused_input: Option<AnyInputState>,
42    pub notification: Entity<NotificationList>,
43    pub(crate) tooltip_overlay: Entity<gpui_base::TooltipOverlay>,
44    pub(crate) native_menu_overlay: Entity<FallbackMenuOverlay>,
45    sheet_size: Option<DefiniteLength>,
46    window_shadow_size: Pixels,
47    /// Render the Linux CSD `window_border` wrapper.
48    bordered: bool,
49    /// The focus handle that will be restored after a dialog is closed with animation.
50    /// Used to handle rapid dialog opening/closing to maintain correct focus chain.
51    pending_focus_restore: Option<WeakFocusHandle>,
52    window_id: gpui::WindowId,
53}
54
55#[derive(Clone)]
56pub(crate) struct ActiveSheet {
57    focus_handle: FocusHandle,
58    /// The previous focused handle before opening the Sheet.
59    previous_focused_handle: Option<WeakFocusHandle>,
60    placement: Placement,
61    selection_scope: TextSelectionScopeId,
62    builder: Rc<dyn Fn(Sheet, &mut Window, &mut App) -> Sheet + 'static>,
63}
64
65#[derive(Clone)]
66pub(crate) struct ActiveDialog {
67    focus_handle: FocusHandle,
68    /// The previous focused handle before opening the Dialog.
69    previous_focused_handle: Option<WeakFocusHandle>,
70    selection_scope: TextSelectionScopeId,
71    builder: Rc<dyn Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static>,
72}
73
74impl ActiveDialog {
75    pub(crate) fn new(
76        focus_handle: FocusHandle,
77        previous_focused_handle: Option<WeakFocusHandle>,
78        selection_scope: TextSelectionScopeId,
79        builder: impl Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
80    ) -> Self {
81        Self {
82            focus_handle,
83            previous_focused_handle,
84            selection_scope,
85            builder: Rc::new(builder),
86        }
87    }
88}
89
90impl Root {
91    /// Clears window-owned text selection synchronously.
92    #[deprecated(note = "use gpui_base::TextSelection::clear instead")]
93    pub fn clear_text_selection(&mut self, cx: &mut Context<Self>) {
94        gpui_base::TextSelection::clear_for_window(self.window_id, cx);
95    }
96
97    /// Create a new Root view.
98    pub fn new(view: impl Into<AnyView>, window: &mut Window, cx: &mut Context<Self>) -> Self {
99        #[cfg(all(target_os = "macos", not(test)))]
100        gpui_base::install_window_hit_test_forwarder(window);
101
102        Self {
103            style: StyleRefinement::default(),
104            view: view.into(),
105            active_sheet: None,
106            active_dialogs: Vec::new(),
107            focused_input: None,
108            notification: cx.new(|cx| NotificationList::new(window, cx)),
109            tooltip_overlay: cx
110                .new(|_| gpui_base::TooltipOverlay::new().render_with(render_tooltip)),
111            native_menu_overlay: cx.new(|_| FallbackMenuOverlay::new()),
112            sheet_size: None,
113            window_shadow_size: window_border::SHADOW_SIZE,
114            bordered: true,
115            pending_focus_restore: None,
116            window_id: window.window_handle().window_id(),
117        }
118    }
119
120    fn allocate_text_selection_scope(&mut self) -> TextSelectionScopeId {
121        TextSelectionScopeId::new()
122    }
123
124    pub(crate) fn active_text_selection_scope(&self) -> TextSelectionScopeId {
125        self.active_dialogs
126            .last()
127            .map(|dialog| dialog.selection_scope)
128            .or_else(|| {
129                self.active_sheet
130                    .as_ref()
131                    .map(|sheet| sheet.selection_scope)
132            })
133            .unwrap_or_default()
134    }
135
136    /// Enable or disable the Linux client-side window border wrapper.
137    ///
138    /// Defaults to `true`. Use `bordered(false)` for layer-shell fullscreen windows
139    /// or other surfaces that should not render GPUI Component's window border.
140    pub fn bordered(mut self, bordered: bool) -> Self {
141        self.bordered = bordered;
142        self
143    }
144
145    /// Set the window border shadow size for Linux client-side decorations.
146    ///
147    /// Default: [`window_border::SHADOW_SIZE`]
148    pub fn window_shadow_size(mut self, size: impl Into<Pixels>) -> Self {
149        self.window_shadow_size = size.into();
150        self
151    }
152
153    pub fn update<F, R>(window: &mut Window, cx: &mut App, f: F) -> R
154    where
155        F: FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
156    {
157        let root = window
158            .root::<Root>()
159            .flatten()
160            .expect("BUG: window first layer should be a gpui_component::Root.");
161
162        root.update(cx, |root, cx| f(root, window, cx))
163    }
164
165    pub(crate) fn try_update<F, R>(window: &mut Window, cx: &mut App, f: F) -> Option<R>
166    where
167        F: FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
168    {
169        let root = window.root::<Root>().flatten()?;
170        Some(root.update(cx, |root, cx| f(root, window, cx)))
171    }
172
173    pub fn read<'a>(window: &'a Window, cx: &'a App) -> &'a Self {
174        &window
175            .root::<Root>()
176            .expect("The window root view should be of type `ui::Root`.")
177            .unwrap()
178            .read(cx)
179    }
180
181    // Render Notification layer.
182    pub fn render_notification_layer(
183        window: &mut Window,
184        cx: &mut App,
185    ) -> Option<impl IntoElement + use<>> {
186        let root = window.root::<Root>()??;
187
188        let active_sheet_placement = root.read(cx).active_sheet.clone().map(|d| d.placement);
189
190        let sheet_size = root.read(cx).sheet_size;
191        let (mt, mr, mb, ml) = match active_sheet_placement {
192            Some(Placement::Top) => (sheet_size, None, None, None),
193            Some(Placement::Right) => (None, sheet_size, None, None),
194            Some(Placement::Bottom) => (None, None, sheet_size, None),
195            Some(Placement::Left) => (None, None, None, sheet_size),
196            _ => (None, None, None, None),
197        };
198
199        Some(
200            div()
201                .absolute()
202                .inset_0()
203                .when_some(mt, |this, offset| this.mt(offset))
204                .when_some(mr, |this, offset| this.mr(offset))
205                .when_some(mb, |this, offset| this.mb(offset))
206                .when_some(ml, |this, offset| this.ml(offset))
207                .child(root.read(cx).notification.clone()),
208        )
209    }
210
211    /// Render the Sheet layer.
212    pub fn render_sheet_layer(
213        window: &mut Window,
214        cx: &mut App,
215    ) -> Option<impl IntoElement + use<>> {
216        let root = window.root::<Root>()??;
217
218        if let Some(active_sheet) = root.read(cx).active_sheet.clone() {
219            let mut sheet = Sheet::new(window, cx);
220            sheet = (active_sheet.builder)(sheet, window, cx);
221            sheet.focus_handle = active_sheet.focus_handle.clone();
222            sheet.placement = active_sheet.placement;
223            sheet.selection_scope = active_sheet.selection_scope;
224
225            let size = sheet.size;
226
227            return Some(
228                div()
229                    .relative()
230                    .child(sheet)
231                    .on_prepaint(move |_, _, cx| root.update(cx, |r, _| r.sheet_size = Some(size))),
232            );
233        }
234
235        None
236    }
237
238    /// Render the Dialog layer.
239    pub fn render_dialog_layer(
240        window: &mut Window,
241        cx: &mut App,
242    ) -> Option<impl IntoElement + use<>> {
243        let root = window.root::<Root>()??;
244
245        let active_dialogs = root.read(cx).active_dialogs.clone();
246
247        if active_dialogs.is_empty() {
248            return None;
249        }
250
251        let mut show_overlay_ix = None;
252
253        let mut dialogs = active_dialogs
254            .iter()
255            .enumerate()
256            .map(|(i, active_dialog)| {
257                let mut dialog = Dialog::new(cx);
258
259                dialog = (active_dialog.builder)(dialog, window, cx);
260
261                // Give the dialog the focus handle, because `dialog` is a temporary value, is not possible to
262                // keep the focus handle in the dialog.
263                //
264                // So we keep the focus handle in the `active_dialog`, this is owned by the `Root`.
265                dialog.focus_handle = active_dialog.focus_handle.clone();
266                dialog.selection_scope = active_dialog.selection_scope;
267
268                dialog.layer_ix = i;
269                // Find the dialog which one needs to show overlay.
270                if dialog.has_overlay() {
271                    show_overlay_ix = Some(i);
272                }
273
274                dialog
275            })
276            .collect::<Vec<_>>();
277
278        if let Some(ix) = show_overlay_ix {
279            if let Some(dialog) = dialogs.get_mut(ix) {
280                dialog.props.overlay_visible = true;
281            }
282        }
283
284        Some(div().children(dialogs))
285    }
286
287    pub fn open_dialog<F>(&mut self, build: F, window: &mut Window, cx: &mut Context<'_, Root>)
288    where
289        F: Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
290    {
291        let mut previous_focused_handle = window.focused(cx).map(|h| h.downgrade());
292
293        // Use pending focus restore if available to maintain correct focus chain
294        // when a new dialog is opened immediately after closing another dialog.
295        if let Some(pending_handle) = self.pending_focus_restore.take() {
296            previous_focused_handle = Some(pending_handle);
297        }
298
299        let focus_handle = cx.focus_handle();
300        focus_handle.focus(window, cx);
301
302        let selection_scope = self.allocate_text_selection_scope();
303        self.active_dialogs.push(ActiveDialog::new(
304            focus_handle,
305            previous_focused_handle,
306            selection_scope,
307            build,
308        ));
309        // Opening a modal confines selection to it; drop any background
310        // selection so it cannot linger (or be copied) under the modal.
311        gpui_base::TextSelection::clear(window, cx);
312        cx.notify();
313    }
314
315    fn close_dialog_internal(&mut self) -> Option<FocusHandle> {
316        self.focused_input = None;
317        self.active_dialogs
318            .pop()
319            .and_then(|d| d.previous_focused_handle)
320            .and_then(|h| h.upgrade())
321    }
322
323    pub fn close_dialog(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
324        if let Some(handle) = self.close_dialog_internal() {
325            window.focus(&handle, cx);
326        }
327        gpui_base::TextSelection::clear(window, cx);
328        cx.notify();
329    }
330
331    pub(crate) fn defer_close_dialog(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
332        if let Some(handle) = self.close_dialog_internal() {
333            let dialogs_count = self.active_dialogs.len();
334
335            // Save for new dialogs opened during animation to maintain focus chain
336            self.pending_focus_restore = Some(handle.downgrade());
337
338            cx.spawn_in(window, async move |this, cx| {
339                cx.background_executor().timer(*ANIMATION_DURATION).await;
340                let _ = this.update_in(cx, |this, window, cx| {
341                    let current_dialogs_count = this.active_dialogs.len();
342                    // Only restore focus if no new dialogs were opened during animation
343                    if current_dialogs_count == dialogs_count {
344                        window.focus(&handle, cx);
345                    }
346                    this.pending_focus_restore = None;
347                });
348            })
349            .detach();
350        }
351        gpui_base::TextSelection::clear(window, cx);
352        cx.notify();
353    }
354
355    pub fn close_all_dialogs(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
356        self.focused_input = None;
357        let previous_focused_handle = self
358            .active_dialogs
359            .first()
360            .and_then(|d| d.previous_focused_handle.clone());
361        self.active_dialogs.clear();
362        if let Some(handle) = previous_focused_handle.and_then(|h| h.upgrade()) {
363            window.focus(&handle, cx);
364        }
365        gpui_base::TextSelection::clear(window, cx);
366        cx.notify();
367    }
368
369    pub fn open_sheet_at<F>(
370        &mut self,
371        placement: Placement,
372        build: F,
373        window: &mut Window,
374        cx: &mut Context<'_, Root>,
375    ) where
376        F: Fn(Sheet, &mut Window, &mut App) -> Sheet + 'static,
377    {
378        let previous_focused_handle = self
379            .active_sheet
380            .take()
381            .and_then(|s| s.previous_focused_handle)
382            .or_else(|| window.focused(cx).map(|h| h.downgrade()));
383
384        let focus_handle = cx.focus_handle();
385        focus_handle.focus(window, cx);
386        let selection_scope = self.allocate_text_selection_scope();
387        self.active_sheet = Some(ActiveSheet {
388            focus_handle,
389            previous_focused_handle,
390            placement,
391            selection_scope,
392            builder: Rc::new(build),
393        });
394        // Opening a modal confines selection to it; drop any background
395        // selection so it cannot linger (or be copied) under the modal.
396        gpui_base::TextSelection::clear(window, cx);
397        cx.notify();
398    }
399
400    pub fn close_sheet(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
401        self.focused_input = None;
402        if let Some(previous_handle) = self
403            .active_sheet
404            .as_ref()
405            .and_then(|s| s.previous_focused_handle.as_ref())
406            .and_then(|h| h.upgrade())
407        {
408            window.focus(&previous_handle, cx);
409        }
410        self.active_sheet = None;
411        gpui_base::TextSelection::clear(window, cx);
412        cx.notify();
413    }
414
415    pub fn push_notification(
416        &mut self,
417        note: impl Into<Notification>,
418        window: &mut Window,
419        cx: &mut Context<'_, Root>,
420    ) {
421        self.notification
422            .update(cx, |view, cx| view.push(note, window, cx));
423        cx.notify();
424    }
425
426    /// Removes all notifications whose id matches `T`, including ones registered with
427    /// either [`Notification::id`] or [`Notification::id1`] (any key).
428    pub fn remove_notification<T: Sized + 'static>(
429        &mut self,
430        window: &mut Window,
431        cx: &mut Context<'_, Root>,
432    ) {
433        self.notification.update(cx, |view, cx| {
434            view.close_by_type(TypeId::of::<T>(), window, cx);
435        });
436        cx.notify();
437    }
438
439    /// Removes the notification matching the given type and element id (paired with [`Notification::id1`]).
440    pub fn remove_notification1<T: Sized + 'static>(
441        &mut self,
442        key: impl Into<ElementId>,
443        window: &mut Window,
444        cx: &mut Context<'_, Root>,
445    ) {
446        let key = key.into();
447        self.notification.update(cx, |view, cx| {
448            view.close((TypeId::of::<T>(), key), window, cx);
449        });
450        cx.notify();
451    }
452
453    pub fn clear_notifications(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
454        self.notification
455            .update(cx, |view, cx| view.clear(window, cx));
456        cx.notify();
457    }
458
459    /// Get the tooltip overlay entity for this window.
460    pub(crate) fn tooltip_overlay(
461        window: &Window,
462        cx: &App,
463    ) -> Option<Entity<gpui_base::TooltipOverlay>> {
464        let root = window.root::<Root>()??;
465        Some(root.read(cx).tooltip_overlay.clone())
466    }
467
468    /// Get the fallback native-menu overlay entity for this window.
469    pub(crate) fn native_menu_overlay(
470        window: &Window,
471        cx: &App,
472    ) -> Option<Entity<FallbackMenuOverlay>> {
473        let root = window.root::<Root>()??;
474        Some(root.read(cx).native_menu_overlay.clone())
475    }
476
477    /// Return the root view of the Root.
478    pub fn view(&self) -> &AnyView {
479        &self.view
480    }
481
482    fn on_action_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
483        // Check if we're inside a focus trap
484        if let Some(container_focus_handle) = gpui_base::active_focus_trap(window, cx) {
485            // We're in a focus trap - try to focus next, then check if we're still inside
486            let before_focus = window.focused(cx);
487
488            // Try normal focus navigation
489            window.focus_next(cx);
490
491            // Check if we're still in the trap
492            if !container_focus_handle.contains_focused(window, cx) {
493                // We jumped out of the trap - need to cycle back to the beginning
494                // Find the first focusable element in the trap by continuing to focus_next
495                let mut attempts = 0;
496                const MAX_ATTEMPTS: usize = 100; // Prevent infinite loop
497
498                while !container_focus_handle.contains_focused(window, cx)
499                    && attempts < MAX_ATTEMPTS
500                {
501                    window.focus_next(cx);
502                    attempts += 1;
503
504                    // If we cycled back to where we started, restore original focus
505                    if window.focused(cx) == before_focus {
506                        break;
507                    }
508                }
509            }
510            return;
511        }
512
513        // Normal tab navigation
514        window.focus_next(cx);
515    }
516
517    fn on_action_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
518        // Check if we're inside a focus trap
519        if let Some(container_focus_handle) = gpui_base::active_focus_trap(window, cx) {
520            // We're in a focus trap - try to focus previous, then check if we're still inside
521            let before_focus = window.focused(cx);
522
523            // Try normal focus navigation
524            window.focus_prev(cx);
525
526            // Check if we're still in the trap
527            if !container_focus_handle.contains_focused(window, cx) {
528                // We jumped out of the trap - need to cycle back to the end
529                // Find the last focusable element in the trap by continuing to focus_prev
530                let mut attempts = 0;
531                const MAX_ATTEMPTS: usize = 100; // Prevent infinite loop
532
533                while !container_focus_handle.contains_focused(window, cx)
534                    && attempts < MAX_ATTEMPTS
535                {
536                    window.focus_prev(cx);
537                    attempts += 1;
538
539                    // If we cycled back to where we started, restore original focus
540                    if window.focused(cx) == before_focus {
541                        break;
542                    }
543                }
544            }
545            return;
546        }
547
548        // Normal tab navigation
549        window.focus_prev(cx);
550    }
551
552    fn on_action_copy(&mut self, _: &Copy, window: &mut Window, cx: &mut Context<Self>) {
553        let text = gpui_base::TextSelection::selected_text(window, cx)
554            .trim()
555            .to_string();
556        if text.is_empty() {
557            cx.propagate();
558            return;
559        }
560        cx.write_to_clipboard(ClipboardItem::new_string(text));
561    }
562}
563
564impl Styled for Root {
565    fn style(&mut self) -> &mut StyleRefinement {
566        &mut self.style
567    }
568}
569
570impl Render for Root {
571    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
572        window.set_rem_size(cx.theme().font_size);
573        if !cx.has_global::<crate::global_state::UiGlobalState>() {
574            crate::global_state::init(cx);
575        }
576        crate::global_state::UiGlobalState::global_mut(cx).begin_selection_frame();
577        let active_scope = self.active_text_selection_scope();
578        TextSelection::activate_scope(active_scope, window, cx);
579
580        let inner = div()
581            .id("root")
582            .key_context(CONTEXT)
583            .on_action(cx.listener(Self::on_action_tab))
584            .on_action(cx.listener(Self::on_action_tab_prev))
585            .on_action(cx.listener(Self::on_action_copy))
586            .relative()
587            .size_full()
588            .font_family(cx.theme().font_family.clone())
589            .bg(cx.theme().tokens.background)
590            .text_color(cx.theme().foreground)
591            .refine_style(&self.style)
592            .child(TextSelectionLayer)
593            .child(self.view.clone())
594            .child(self.tooltip_overlay.clone())
595            .child(self.native_menu_overlay.clone());
596
597        if self.bordered {
598            window_border()
599                .shadow_size(self.window_shadow_size)
600                .child(inner)
601                .into_any_element()
602        } else {
603            inner.into_any_element()
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611    use gpui::TestAppContext;
612
613    struct TestView;
614
615    impl Render for TestView {
616        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
617            div()
618        }
619    }
620
621    #[gpui::test]
622    fn bordered_builder_toggles_window_border(cx: &mut TestAppContext) {
623        cx.update(crate::init);
624
625        let (default_root, _) = cx.add_window_view(|window, cx| {
626            let view = cx.new(|_| TestView);
627            Root::new(view, window, cx)
628        });
629        assert!(default_root.read_with(cx, |root, _| root.bordered));
630
631        let (root, _) = cx.add_window_view(|window, cx| {
632            let view = cx.new(|_| TestView);
633            Root::new(view, window, cx).bordered(false)
634        });
635        assert!(!root.read_with(cx, |root, _| root.bordered));
636
637        let (root, _) = cx.add_window_view(|window, cx| {
638            let view = cx.new(|_| TestView);
639            Root::new(view, window, cx).bordered(false).bordered(true)
640        });
641        assert!(root.read_with(cx, |root, _| root.bordered));
642    }
643}