Skip to main content

gpui_base/
global_state.rs

1use std::rc::{Rc, Weak};
2
3use gpui::{App, Global, OwnedMenu};
4
5/// Holds the deferred interaction context open for as long as it is alive.
6///
7/// Handed out by [`GlobalState::register_deferred_popover`]; drop it to close
8/// the context again. The registry only ever weighs the token's liveness, so
9/// there is nothing inside to read.
10pub struct DeferredPopover(#[allow(dead_code)] Rc<()>);
11
12/// Application-wide state shared by Base behaviors.
13pub struct GlobalState {
14    app_menus: Vec<OwnedMenu>,
15    deferred_popovers: Vec<Weak<()>>,
16    suppress_text_selection: bool,
17}
18
19impl Global for GlobalState {}
20
21impl GlobalState {
22    fn new() -> Self {
23        Self {
24            app_menus: Vec::new(),
25            deferred_popovers: Vec::new(),
26            suppress_text_selection: false,
27        }
28    }
29
30    /// Ensures that the Base global exists.
31    #[doc(hidden)]
32    pub fn init(cx: &mut App) {
33        if !cx.has_global::<Self>() {
34            cx.set_global(Self::new());
35        }
36    }
37
38    /// Suppresses window-level text selection for the current mouse down.
39    ///
40    /// Controls that own a press or drag interaction use this so the same
41    /// pointer event does not also start application text selection.
42    pub fn suppress_text_selection(cx: &mut App) {
43        Self::global_mut(cx).suppress_text_selection = true;
44    }
45
46    /// Clears the current mouse-down text-selection suppression.
47    #[doc(hidden)]
48    pub fn reset_text_selection_suppression(cx: &mut App) {
49        Self::global_mut(cx).suppress_text_selection = false;
50    }
51
52    /// Returns whether the current mouse down suppresses text selection.
53    #[doc(hidden)]
54    pub fn is_text_selection_suppressed(cx: &App) -> bool {
55        Self::global(cx).suppress_text_selection
56    }
57
58    pub fn global(cx: &App) -> &Self {
59        cx.global::<Self>()
60    }
61
62    pub fn global_mut(cx: &mut App) -> &mut Self {
63        cx.global_mut::<Self>()
64    }
65
66    /// Returns the application menus.
67    pub fn app_menus(&self) -> &[OwnedMenu] {
68        &self.app_menus
69    }
70
71    /// Replaces the application menus.
72    pub fn set_app_menus(&mut self, menus: Vec<OwnedMenu>) {
73        self.app_menus = menus;
74    }
75
76    /// Returns whether any deferred popup currently owns an open interaction
77    /// context.
78    pub fn is_in_deferred_context(cx: &App) -> bool {
79        Self::global(cx)
80            .deferred_popovers
81            .iter()
82            .any(|popover| popover.strong_count() > 0)
83    }
84
85    /// Registers an open deferred popup, which stays registered for as long as
86    /// the returned token is held.
87    ///
88    /// A token rather than an identifier, because popup state is routinely
89    /// dropped without ever being closed: state that stops being rendered — a
90    /// popover scrolled out of a virtual list, a panel closed while its menu is
91    /// open — is collected at the end of the frame, with no chance to
92    /// deregister. A registration that outlived its popup would leave the
93    /// application believing a popup is open forever, and everything that
94    /// steps aside for open popups (the native context menu of a text input,
95    /// say) would stay disabled for the rest of the session.
96    pub fn register_deferred_popover(cx: &mut App) -> DeferredPopover {
97        let token = Rc::new(());
98        let state = Self::global_mut(cx);
99        state
100            .deferred_popovers
101            .retain(|popover| popover.strong_count() > 0);
102        state.deferred_popovers.push(Rc::downgrade(&token));
103        DeferredPopover(token)
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[gpui::test]
112    fn initialization_is_idempotent_and_suppression_can_be_reset(cx: &mut gpui::TestAppContext) {
113        cx.update(|cx| {
114            GlobalState::init(cx);
115            GlobalState::suppress_text_selection(cx);
116            GlobalState::init(cx);
117            assert!(GlobalState::is_text_selection_suppressed(cx));
118
119            GlobalState::reset_text_selection_suppression(cx);
120            assert!(!GlobalState::is_text_selection_suppressed(cx));
121
122            assert!(!GlobalState::is_in_deferred_context(cx));
123            let popover = GlobalState::register_deferred_popover(cx);
124            assert!(GlobalState::is_in_deferred_context(cx));
125            drop(popover);
126            assert!(!GlobalState::is_in_deferred_context(cx));
127        });
128    }
129
130    /// Popup state is routinely dropped without being closed first, and a
131    /// registration that survived it would disable everything that steps aside
132    /// for an open popup, permanently.
133    #[gpui::test]
134    fn a_dropped_registration_closes_the_deferred_context(cx: &mut gpui::TestAppContext) {
135        cx.update(|cx| {
136            GlobalState::init(cx);
137
138            let outer = GlobalState::register_deferred_popover(cx);
139            {
140                let _inner = GlobalState::register_deferred_popover(cx);
141                assert!(GlobalState::is_in_deferred_context(cx));
142            }
143            assert!(GlobalState::is_in_deferred_context(cx));
144
145            drop(outer);
146            assert!(!GlobalState::is_in_deferred_context(cx));
147
148            // Registering again must not resurrect the collected ones.
149            let popover = GlobalState::register_deferred_popover(cx);
150            assert_eq!(GlobalState::global(cx).deferred_popovers.len(), 1);
151            drop(popover);
152            assert!(!GlobalState::is_in_deferred_context(cx));
153        });
154    }
155}