Skip to main content

sk_tree/
windows.rs

1//! Per-window state: one process, one `JsRuntime` and one `Tree`, but N gpui windows each painting one
2//! node of it. State the windows disagree about (focus, bounds, drag regions, `@media`) lives in one
3//! [`WindowState`] per `gpui::WindowId`; single-slot thread-locals would alias across windows.
4//! "Here" is passed, never guessed.
5
6use std::cell::RefCell;
7use std::collections::HashMap;
8
9use crate::idmap::IdMap;
10use std::sync::Arc;
11
12use gpui::{FocusHandle, RenderImage, Subscription, Window, WindowControlArea};
13
14/// A gpui `WindowId` flattened to the `u64` the devtools protocol speaks; `0` is not a legal id, so
15/// it means "no window yet" ([`UNBOUND`]).
16pub type WinKey = u64;
17
18pub const UNBOUND: WinKey = 0;
19
20/// A rectangle in ONE window's client space, CSS px: `(x, y, width, height)`.
21pub type Rect = (f32, f32, f32, f32);
22
23#[derive(Default)]
24pub struct PressFocus {
25    pub pending: bool,
26    pub claims: Vec<(u32, gpui::FocusHandle)>,
27    pub cancelled: bool,
28    /// The press reached the root's bubble listener. A native widget that took it (a scrollbar stops
29    /// propagation) moves no focus unless something focusable on the path claimed it first.
30    pub reached: bool,
31}
32
33#[derive(Default)]
34pub struct WindowState {
35    /// The node this window paints as its root: `0` for the primary window, the popped-out node for a pop-out.
36    pub painted_root: u32,
37
38    pub focused_node: u32,
39    /// Queued by `gc_node_state` (which has no `Window`), applied by the next frame tick that does.
40    pub pending_blur: u32,
41    pub focus_subs: HashMap<u32, Subscription>,
42    /// Registered per window (`cx.on_focus_lost`), so a pop-out needs its own or focus leaving it is invisible.
43    pub focus_lost: Option<Subscription>,
44
45    pub bounds: IdMap<Rect>,
46    /// The previous frame's [`Self::bounds`]: the element tree for frame N is built before N's
47    /// prepaint, so a builder can only read last frame's (`<lottie>`, `<video>` size relatively).
48    pub prev_bounds: IdMap<Rect>,
49    pub transformed: IdMap<Rect>,
50    pub prev_transformed: IdMap<Rect>,
51
52    pub pending_mouse_move: Option<PendingMouseMove>,
53    /// The moves since the last delivered `mousemove`: its `movementX`/`movementY`.
54    pub mouse_movement: gpui::Point<gpui::Pixels>,
55    pub pointer_capture: Option<u32>,
56    /// Has a node already taken THIS mouse-down? gpui runs `on_any_mouse_down` on every listening box
57    /// under the pointer; the browser has one target, so without the claim an outer listener ran twice.
58    pub down_claimed: bool,
59    pub press_focus: PressFocus,
60    /// Mouse-up waves not yet delivered (`render::UpWave`): listeners only claim, one deferred flush
61    /// delivers in DOM order.
62    pub up_waves: Vec<crate::render::UpWave>,
63    /// The press in progress (`render::Press`), kept outside gpui element state so cached/direct
64    /// render switches cannot lose it.
65    pub press: Option<crate::render::Press>,
66    pub hit: Option<u32>,
67    pub down_hit: Option<u32>,
68    pub hover: crate::pointer::Hover,
69    pub active: Option<u32>,
70    pub keyboard_input: bool,
71    pub activation: Option<Subscription>,
72    pub key_prevented: bool,
73    pub key_event_claimed: u64,
74    pub key_click: Option<crate::render::KeyClick>,
75    pub space_armed: Option<u32>,
76
77    pub any_drag_region: bool,
78    pub control_hitboxes: Vec<(u32, WindowControlArea)>,
79    pub os_chrome: bool,
80
81    pub full_res_images: bool,
82
83    pub env: Option<sk_css::Env>,
84
85    pub pending_drops: Vec<Arc<RenderImage>>,
86    pub pending_uploads: Vec<PendingUpload>,
87}
88
89pub struct PendingMouseMove {
90    pub id: u32,
91    pub position: gpui::Point<gpui::Pixels>,
92    pub button: f64,
93    pub modifiers: gpui::Modifiers,
94}
95
96/// A decoded `<video>` frame still in GPU memory that must reach one window's atlas before its next
97/// draw. The texture is HELD: the window may not draw for a while.
98pub struct PendingUpload {
99    pub node: u32,
100    pub image: Arc<RenderImage>,
101    pub gpu: sk_video::HeldGpuFrame,
102}
103
104thread_local! {
105    static WINDOWS: RefCell<HashMap<WinKey, WindowState>> = RefCell::new(HashMap::new());
106    static ROOTS: RefCell<HashMap<u32, WinKey>> = RefCell::new(HashMap::new());
107    static PRIMARY: std::cell::Cell<WinKey> = const { std::cell::Cell::new(UNBOUND) };
108}
109
110pub fn key(window: &Window) -> WinKey {
111    window.window_handle().window_id().as_u64()
112}
113
114pub fn set_primary(k: WinKey) {
115    PRIMARY.with(|c| c.set(k));
116    of(k, |w| w.painted_root = 0);
117}
118
119pub fn primary() -> WinKey {
120    PRIMARY.with(|c| c.get())
121}
122
123pub fn is_primary(k: WinKey) -> bool {
124    k == PRIMARY.with(|c| c.get())
125}
126
127/// The state of the window we are standing in, creating it on first touch. `f` must not re-enter: the
128/// map is borrowed for its duration, so read or write a field first and dispatch to JS after.
129pub fn here<R>(window: &Window, f: impl FnOnce(&mut WindowState) -> R) -> R {
130    of(key(window), f)
131}
132
133pub fn of<R>(k: WinKey, f: impl FnOnce(&mut WindowState) -> R) -> R {
134    WINDOWS.with(|m| f(m.borrow_mut().entry(k).or_default()))
135}
136
137pub fn queue_drops(k: WinKey, images: impl IntoIterator<Item = std::sync::Arc<gpui::RenderImage>>) {
138    let live = WINDOWS.with(|m| m.borrow().contains_key(&k));
139    if !live {
140        return;
141    }
142    of(k, |w| w.pending_drops.extend(images));
143}
144
145pub fn peek<R>(k: WinKey, f: impl FnOnce(&WindowState) -> R) -> Option<R> {
146    WINDOWS.with(|m| m.borrow().get(&k).map(f))
147}
148
149pub fn keys() -> Vec<WinKey> {
150    let primary = primary();
151    let mut out: Vec<WinKey> = WINDOWS.with(|m| m.borrow().keys().copied().collect());
152    out.sort_unstable_by_key(|&k| (k != primary, k));
153    out
154}
155
156pub fn each(mut f: impl FnMut(WinKey, &mut WindowState)) {
157    for k in keys() {
158        of(k, |w| f(k, w));
159    }
160}
161
162pub fn set_painted_root(k: WinKey, root: u32) {
163    let previous = of(k, |w| std::mem::replace(&mut w.painted_root, root));
164    if previous == root {
165        return;
166    }
167    ROOTS.with(|m| {
168        let mut m = m.borrow_mut();
169        if previous != 0 {
170            m.remove(&previous);
171        }
172        if root != 0 {
173            m.insert(root, k);
174        }
175    });
176    // Marked here rather than left to the next mutation because there may not BE one: a pop-out
177    // that is opened and then left alone would keep the main window's answers forever.
178    for id in [previous, root] {
179        if id != 0 {
180            crate::tree::with_tree(|t| t.mark_restyle_subtree(id));
181        }
182    }
183}
184
185pub fn window_of_root(root: u32) -> Option<WinKey> {
186    if root == 0 {
187        return Some(primary());
188    }
189    ROOTS.with(|m| m.borrow().get(&root).copied())
190}
191
192pub fn root_of(k: WinKey) -> u32 {
193    peek(k, |w| w.painted_root).unwrap_or(0)
194}
195
196pub fn window_of_node(node: u32) -> WinKey {
197    if !any_secondary() {
198        return primary();
199    }
200    crate::tree::read_tree(|t| window_of_node_in(t, node))
201}
202
203/// [`window_of_node`] against a tree the caller already holds. The cascade needs this one:
204/// `Tree::restyle` runs inside `with_tree`'s mutable borrow, so a nested `read_tree` would panic.
205pub fn window_of_node_in(t: &crate::tree::Tree, node: u32) -> WinKey {
206    let popped: Option<WinKey> = ROOTS.with(|m| {
207        let roots = m.borrow();
208        if roots.is_empty() {
209            return None;
210        }
211        let mut cursor = node;
212        // A tree is a tree, but a corrupt parent chain must not hang a frame.
213        for _ in 0..1024 {
214            if let Some(&k) = roots.get(&cursor) {
215                return Some(k);
216            }
217            match t.node(cursor) {
218                Some(n) if n.parent != 0 => cursor = n.parent,
219                _ => return None,
220            }
221        }
222        None
223    });
224    popped.unwrap_or_else(primary)
225}
226
227pub fn forget(k: WinKey) -> Option<WindowState> {
228    let state = WINDOWS.with(|m| m.borrow_mut().remove(&k));
229    if let Some(s) = state.as_ref() {
230        if s.painted_root != 0 {
231            ROOTS.with(|m| m.borrow_mut().remove(&s.painted_root));
232        }
233    }
234    state
235}
236
237pub fn any_secondary() -> bool {
238    ROOTS.with(|m| !m.borrow().is_empty())
239}
240
241pub fn set_env(k: WinKey, env: sk_css::Env) -> bool {
242    of(k, |w| {
243        if w.env == Some(env) {
244            return false;
245        }
246        w.env = Some(env);
247        true
248    })
249}
250
251pub fn env_of(k: WinKey) -> Option<sk_css::Env> {
252    peek(k, |w| w.env).flatten()
253}
254
255pub fn env_for_node(t: &crate::tree::Tree, node: u32, fallback: &sk_css::Env) -> sk_css::Env {
256    if !any_secondary() {
257        return *fallback;
258    }
259    // `_in`, not the free function: the cascade holds the tree's mutable borrow, so `read_tree` here
260    // would panic.
261    let k = window_of_node_in(t, node);
262    if is_primary(k) {
263        return *fallback;
264    }
265    env_of(k).unwrap_or(*fallback)
266}
267
268pub fn env_at_root(node: u32, fallback: &sk_css::Env) -> Option<sk_css::Env> {
269    let k = ROOTS.with(|m| m.borrow().get(&node).copied())?;
270    Some(env_of(k).unwrap_or(*fallback))
271}
272
273pub fn focused_node(k: WinKey) -> u32 {
274    peek(k, |w| w.focused_node).unwrap_or(0)
275}
276
277pub fn set_focused_node(k: WinKey, node: u32) {
278    of(k, |w| w.focused_node = node);
279}
280
281pub fn set_full_res_images(k: WinKey, on: bool) {
282    of(k, |w| w.full_res_images = on);
283}
284
285pub(crate) fn any_full_res() -> bool {
286    WINDOWS.with(|m| m.borrow().values().any(|w| w.full_res_images))
287}
288
289/// The focus handle a node would use, App-scoped and therefore shared.
290pub type SharedFocusHandles = HashMap<u32, FocusHandle>;
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    fn reset() {
297        WINDOWS.with(|m| m.borrow_mut().clear());
298        ROOTS.with(|m| m.borrow_mut().clear());
299        PRIMARY.with(|c| c.set(UNBOUND));
300    }
301
302    #[test]
303    fn a_painted_root_maps_both_ways_and_is_forgotten_with_its_window() {
304        reset();
305        set_primary(1);
306        set_painted_root(9, 55);
307        assert_eq!(window_of_root(55), Some(9));
308        assert_eq!(root_of(9), 55);
309        forget(9);
310        assert_eq!(window_of_root(55), None);
311        assert!(peek(9, |_| ()).is_none());
312    }
313
314    #[test]
315    fn re_rooting_a_window_drops_the_old_reverse_entry() {
316        reset();
317        set_primary(1);
318        set_painted_root(9, 55);
319        set_painted_root(9, 56);
320        assert_eq!(window_of_root(55), None);
321        assert_eq!(window_of_root(56), Some(9));
322    }
323
324    #[test]
325    fn keys_put_the_primary_first_so_bounds_of_prefers_it() {
326        reset();
327        set_primary(4);
328        of(9, |_| ());
329        of(2, |_| ());
330        assert_eq!(keys(), vec![4, 2, 9]);
331    }
332}