1use 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
14pub type WinKey = u64;
17
18pub const UNBOUND: WinKey = 0;
19
20pub 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 pub reached: bool,
31}
32
33#[derive(Default)]
34pub struct WindowState {
35 pub painted_root: u32,
37
38 pub focused_node: u32,
39 pub pending_blur: u32,
41 pub focus_subs: HashMap<u32, Subscription>,
42 pub focus_lost: Option<Subscription>,
44
45 pub bounds: IdMap<Rect>,
46 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 pub mouse_movement: gpui::Point<gpui::Pixels>,
55 pub pointer_capture: Option<u32>,
56 pub down_claimed: bool,
59 pub press_focus: PressFocus,
60 pub up_waves: Vec<crate::render::UpWave>,
63 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 #[cfg(feature = "video")]
87 pub pending_uploads: Vec<PendingUpload>,
88}
89
90pub struct PendingMouseMove {
91 pub id: u32,
92 pub position: gpui::Point<gpui::Pixels>,
93 pub button: f64,
94 pub modifiers: gpui::Modifiers,
95}
96
97#[cfg(feature = "video")]
98pub struct PendingUpload {
101 pub node: u32,
102 pub image: Arc<RenderImage>,
103 pub gpu: sk_video::HeldGpuFrame,
104}
105
106thread_local! {
107 static WINDOWS: RefCell<HashMap<WinKey, WindowState>> = RefCell::new(HashMap::new());
108 static ROOTS: RefCell<HashMap<u32, WinKey>> = RefCell::new(HashMap::new());
109 static PRIMARY: std::cell::Cell<WinKey> = const { std::cell::Cell::new(UNBOUND) };
110}
111
112pub fn key(window: &Window) -> WinKey {
113 window.window_handle().window_id().as_u64()
114}
115
116pub fn set_primary(k: WinKey) {
117 PRIMARY.with(|c| c.set(k));
118 of(k, |w| w.painted_root = 0);
119}
120
121pub fn primary() -> WinKey {
122 PRIMARY.with(|c| c.get())
123}
124
125pub fn is_primary(k: WinKey) -> bool {
126 k == PRIMARY.with(|c| c.get())
127}
128
129pub fn here<R>(window: &Window, f: impl FnOnce(&mut WindowState) -> R) -> R {
132 of(key(window), f)
133}
134
135pub fn of<R>(k: WinKey, f: impl FnOnce(&mut WindowState) -> R) -> R {
136 WINDOWS.with(|m| f(m.borrow_mut().entry(k).or_default()))
137}
138
139pub fn queue_drops(k: WinKey, images: impl IntoIterator<Item = std::sync::Arc<gpui::RenderImage>>) {
140 let live = WINDOWS.with(|m| m.borrow().contains_key(&k));
141 if !live {
142 return;
143 }
144 of(k, |w| w.pending_drops.extend(images));
145}
146
147#[cfg(not(all(feature = "lottie", feature = "video")))]
149pub(crate) fn drain_drops(window: &mut gpui::Window, cx: &mut gpui::App) {
150 for image in here(window, |w| std::mem::take(&mut w.pending_drops)) {
151 cx.drop_image(image, Some(window));
152 }
153}
154
155pub fn peek<R>(k: WinKey, f: impl FnOnce(&WindowState) -> R) -> Option<R> {
156 WINDOWS.with(|m| m.borrow().get(&k).map(f))
157}
158
159pub fn keys() -> Vec<WinKey> {
160 let primary = primary();
161 let mut out: Vec<WinKey> = WINDOWS.with(|m| m.borrow().keys().copied().collect());
162 out.sort_unstable_by_key(|&k| (k != primary, k));
163 out
164}
165
166pub fn each(mut f: impl FnMut(WinKey, &mut WindowState)) {
167 for k in keys() {
168 of(k, |w| f(k, w));
169 }
170}
171
172pub fn set_painted_root(k: WinKey, root: u32) {
173 let previous = of(k, |w| std::mem::replace(&mut w.painted_root, root));
174 if previous == root {
175 return;
176 }
177 ROOTS.with(|m| {
178 let mut m = m.borrow_mut();
179 if previous != 0 {
180 m.remove(&previous);
181 }
182 if root != 0 {
183 m.insert(root, k);
184 }
185 });
186 for id in [previous, root] {
189 if id != 0 {
190 crate::tree::with_tree(|t| t.mark_restyle_subtree(id));
191 }
192 }
193}
194
195pub fn window_of_root(root: u32) -> Option<WinKey> {
196 if root == 0 {
197 return Some(primary());
198 }
199 ROOTS.with(|m| m.borrow().get(&root).copied())
200}
201
202pub fn root_of(k: WinKey) -> u32 {
203 peek(k, |w| w.painted_root).unwrap_or(0)
204}
205
206pub fn window_of_node(node: u32) -> WinKey {
207 if !any_secondary() {
208 return primary();
209 }
210 crate::tree::read_tree(|t| window_of_node_in(t, node))
211}
212
213pub fn window_of_node_in(t: &crate::tree::Tree, node: u32) -> WinKey {
216 let popped: Option<WinKey> = ROOTS.with(|m| {
217 let roots = m.borrow();
218 if roots.is_empty() {
219 return None;
220 }
221 let mut cursor = node;
222 for _ in 0..1024 {
224 if let Some(&k) = roots.get(&cursor) {
225 return Some(k);
226 }
227 match t.node(cursor) {
228 Some(n) if n.parent != 0 => cursor = n.parent,
229 _ => return None,
230 }
231 }
232 None
233 });
234 popped.unwrap_or_else(primary)
235}
236
237pub fn forget(k: WinKey) -> Option<WindowState> {
238 let state = WINDOWS.with(|m| m.borrow_mut().remove(&k));
239 if let Some(s) = state.as_ref() {
240 if s.painted_root != 0 {
241 ROOTS.with(|m| m.borrow_mut().remove(&s.painted_root));
242 }
243 }
244 state
245}
246
247pub fn any_secondary() -> bool {
248 ROOTS.with(|m| !m.borrow().is_empty())
249}
250
251pub fn set_env(k: WinKey, env: sk_css::Env) -> bool {
252 of(k, |w| {
253 if w.env == Some(env) {
254 return false;
255 }
256 w.env = Some(env);
257 true
258 })
259}
260
261pub fn env_of(k: WinKey) -> Option<sk_css::Env> {
262 peek(k, |w| w.env).flatten()
263}
264
265pub fn env_for_node(t: &crate::tree::Tree, node: u32, fallback: &sk_css::Env) -> sk_css::Env {
266 if !any_secondary() {
267 return *fallback;
268 }
269 let k = window_of_node_in(t, node);
272 if is_primary(k) {
273 return *fallback;
274 }
275 env_of(k).unwrap_or(*fallback)
276}
277
278pub fn env_at_root(node: u32, fallback: &sk_css::Env) -> Option<sk_css::Env> {
279 let k = ROOTS.with(|m| m.borrow().get(&node).copied())?;
280 Some(env_of(k).unwrap_or(*fallback))
281}
282
283pub fn focused_node(k: WinKey) -> u32 {
284 peek(k, |w| w.focused_node).unwrap_or(0)
285}
286
287pub fn set_focused_node(k: WinKey, node: u32) {
288 of(k, |w| w.focused_node = node);
289}
290
291pub fn set_full_res_images(k: WinKey, on: bool) {
292 of(k, |w| w.full_res_images = on);
293}
294
295pub(crate) fn any_full_res() -> bool {
296 WINDOWS.with(|m| m.borrow().values().any(|w| w.full_res_images))
297}
298
299pub type SharedFocusHandles = HashMap<u32, FocusHandle>;
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 fn reset() {
307 WINDOWS.with(|m| m.borrow_mut().clear());
308 ROOTS.with(|m| m.borrow_mut().clear());
309 PRIMARY.with(|c| c.set(UNBOUND));
310 }
311
312 #[test]
313 fn a_painted_root_maps_both_ways_and_is_forgotten_with_its_window() {
314 reset();
315 set_primary(1);
316 set_painted_root(9, 55);
317 assert_eq!(window_of_root(55), Some(9));
318 assert_eq!(root_of(9), 55);
319 forget(9);
320 assert_eq!(window_of_root(55), None);
321 assert!(peek(9, |_| ()).is_none());
322 }
323
324 #[test]
325 fn re_rooting_a_window_drops_the_old_reverse_entry() {
326 reset();
327 set_primary(1);
328 set_painted_root(9, 55);
329 set_painted_root(9, 56);
330 assert_eq!(window_of_root(55), None);
331 assert_eq!(window_of_root(56), Some(9));
332 }
333
334 #[test]
335 fn keys_put_the_primary_first_so_bounds_of_prefers_it() {
336 reset();
337 set_primary(4);
338 of(9, |_| ());
339 of(2, |_| ());
340 assert_eq!(keys(), vec![4, 2, 9]);
341 }
342}