1use gpui::{App, Window};
8
9use crate::tree::{self, Kind, NodeRef, Tree};
10use crate::EventPayload;
11
12#[derive(Debug, Clone)]
13pub struct NodeInfo {
14 pub id: u32,
15 pub kind: &'static str,
16 pub tag: String,
17 pub classes: Vec<String>,
18 pub scopes: Vec<String>,
19 pub props: Vec<(String, String)>,
20 pub text: String,
21 pub parent: u32,
22 pub children: Vec<u32>,
23 pub listeners: Vec<&'static str>,
24 pub bounds: Option<(f32, f32, f32, f32)>,
25 pub group_anchor: bool,
27}
28
29fn event_names(mask: u64) -> Vec<&'static str> {
31 tree::EVENT_NAMES
32 .iter()
33 .filter(|(ev, _)| mask & (1u64 << ev) != 0)
34 .map(|(_, n)| *n)
35 .collect()
36}
37
38pub fn root_id() -> u32 {
39 tree::read_tree(|t| t.root)
40}
41
42fn elements_in_document_order(t: &Tree) -> Vec<u32> {
43 let mut out = Vec::new();
44 fn walk(t: &Tree, id: u32, out: &mut Vec<u32>) {
45 let Some(node) = t.node(id) else { return };
46 if node.kind == Kind::Element {
47 out.push(id);
48 }
49 for &c in &node.children {
50 walk(t, c, out);
51 }
52 }
53 if t.root != 0 {
54 walk(t, t.root, &mut out);
55 }
56 out
57}
58
59pub fn query(selector: &str) -> Result<(Vec<u32>, Vec<String>), String> {
60 tree::read_tree(|t| {
61 let ids = elements_in_document_order(t);
62 let live = crate::live_state::LiveStates::take(t);
63 let candidates: Vec<crate::live_state::LiveRef<'_>> = ids
64 .iter()
65 .map(|&id| crate::live_state::LiveRef::new(t, id, &live))
66 .collect();
67 let result = sk_css::query_all(selector, &candidates)?;
68 for w in &result.warnings {
69 crate::log::record("css", format!("[query] {w}"));
70 }
71 Ok((
72 result.matched.iter().map(|&i| ids[i]).collect(),
73 result.warnings,
74 ))
75 })
76}
77
78pub fn node_count() -> u32 {
79 tree::read_tree(|t| t.live_count())
80}
81
82pub fn frame_counts() -> (u64, u64) {
85 (crate::render::build_count(), crate::live::present_count())
86}
87
88pub use crate::resample::ImageStats;
89pub use crate::tree::TreeMem;
90
91pub fn tree_mem() -> TreeMem {
92 tree::read_tree(|t| t.mem_estimate())
93}
94
95pub fn image_stats() -> ImageStats {
96 crate::resample::image_stats()
97}
98
99pub use crate::img::{KeptFull, ResidencyStats};
100
101pub fn residency_stats() -> ResidencyStats {
102 crate::img::residency_stats()
103}
104
105pub fn set_image_tracking(on: bool) {
106 crate::resample::set_tracking(on);
107}
108
109pub fn side_stats() -> Vec<(&'static str, u64)> {
110 let (memos, src_bytes, images, image_bytes, backgrounds) = crate::img::mem_stats();
111 let (canvases, canvas_bytes) = crate::render::canvas::mem_stats();
112 let (svg_docs, svg_rasters, svg_bytes) = crate::svg::mem_stats();
113 let (log_entries, log_bytes) = crate::log::mem_stats();
114 let (declared, waiting, waiting_bytes, registered, registered_bytes) =
115 crate::fonts::mem_stats();
116 let (boundaries, entities, cached_ids) = crate::cache::mem_stats();
117 let (focus, inputs, scrolls, bounds) = crate::render::side_state_counts();
118 let (stickers, sticker_tiles, sticker_tile_bytes) = crate::render::sticker::mem_stats();
119 let u = |v: usize| v as u64;
120 vec![
121 ("imgMemos", u(memos)),
122 ("imgSrcBytes", u(src_bytes)),
123 ("imgEncodedInMemory", u(images)),
124 ("imgEncodedInMemoryBytes", u(image_bytes)),
125 ("cssBackgroundLayers", u(backgrounds)),
126 ("canvases", u(canvases)),
127 ("canvasHostCopyBytes", u(canvas_bytes)),
128 ("svgDocs", u(svg_docs)),
129 ("svgColourRasters", u(svg_rasters)),
130 ("svgColourRasterBytes", u(svg_bytes)),
131 ("videos", u(crate::video::count())),
132 ("videosAudible", u(crate::video::audible_count())),
133 ("lotties", u(crate::lottie::count())),
134 ("stickers", u(stickers)),
135 ("stickerTiles", u(sticker_tiles)),
136 ("stickerTileBytes", u(sticker_tile_bytes)),
137 ("logRingEntries", u(log_entries)),
138 ("logRingBytes", u(log_bytes)),
139 ("fontFacesDeclared", u(declared)),
140 ("fontFacesLoadedNotRegistered", u(waiting)),
141 ("fontFacesLoadedNotRegisteredBytes", u(waiting_bytes)),
142 ("fontFacesRegistered", registered),
143 ("fontFacesRegisteredBytes", registered_bytes),
144 ("cacheBoundaries", u(boundaries)),
145 ("cacheBoundaryEntities", u(entities)),
146 ("cacheBoundaryNodeIds", u(cached_ids)),
147 ("focusHandles", u(focus)),
148 ("inputStates", u(inputs)),
149 ("scrollHandles", u(scrolls)),
150 ("boundsEntries", u(bounds)),
151 ]
152}
153
154pub fn scroll_chain_count() -> u32 {
155 sk_elements::scrollbar::chain_count() as u32
156}
157
158pub fn node_info(id: u32) -> Option<NodeInfo> {
159 tree::read_tree(|t| {
160 let n = t.node(id)?;
161 Some(NodeInfo {
162 id,
163 kind: match n.kind {
164 Kind::Element => "element",
165 Kind::Text => "text",
166 Kind::Anchor => "anchor",
167 },
168 tag: t.name(n.tag).to_string(),
169 classes: n.classes.clone(),
170 scopes: n.scopes.clone(),
171 props: n
172 .props
173 .iter()
174 .map(|(k, v, _)| (t.name(*k).to_string(), v.clone()))
175 .collect(),
176 text: n.text.clone(),
177 parent: n.parent,
178 children: n.children.clone(),
179 listeners: event_names(n.listeners),
180 bounds: crate::render::bounds_of(id),
181 group_anchor: t.is_group_anchor(id),
182 })
183 })
184}
185
186pub fn text_content(id: u32) -> Option<String> {
187 tree::read_tree(|t| {
188 t.node(id)?;
189 let mut out = String::new();
190 fn walk(t: &Tree, id: u32, out: &mut String) {
191 let Some(n) = t.node(id) else { return };
192 out.push_str(&n.text);
195 for &c in &n.children {
196 walk(t, c, out);
197 }
198 }
199 walk(t, id, &mut out);
200 Some(out)
201 })
202}
203
204pub fn input_value(id: u32, cx: &App) -> Option<String> {
205 crate::render::input_value(id, cx)
206}
207
208pub fn ime(
211 id: u32,
212 text: &str,
213 commit: bool,
214 window: &mut Window,
215 cx: &mut App,
216) -> Result<(), String> {
217 crate::render::ime(id, text, commit, window, cx)
218}
219
220pub fn is_hovered(id: u32) -> bool {
222 tree::is_hovered(id)
223}
224
225pub fn computed_styles(id: u32) -> Option<Vec<(&'static str, String)>> {
226 let live = tree::live_style(id);
229 tree::read_tree(|t| {
230 let cs = t.node(id)?.computed.as_ref()?;
231 let mut out = vec![("base", prune(&format!("{:#?}", cs.base)))];
232 if let Some(live) = &live {
233 out.push(("live", prune(&format!("{live:#?}"))));
234 }
235 for (name, slot) in [
236 ("hover", &cs.hover),
237 ("active", &cs.active),
238 ("focus", &cs.focus),
239 ("focus-visible", &cs.focus_visible),
240 ] {
241 if let Some(r) = slot {
242 out.push((name, prune(&format!("{r:#?}"))));
243 }
244 }
245 let group_focus = cs.group_focus.as_deref();
248 for (name, slot) in [
249 ("group-hover", &cs.group_hover),
250 ("group-active", &cs.group_active),
251 ("group-focus", &group_focus.and_then(|g| g.focus.clone())),
252 (
253 "group-focus-visible",
254 &group_focus.and_then(|g| g.focus_visible.clone()),
255 ),
256 (
257 "group-focus-within",
258 &group_focus.and_then(|g| g.focus_within.clone()),
259 ),
260 ] {
261 if let Some((anchor, r)) = slot {
262 out.push((
263 name,
264 format!("watching node {anchor}\n{}", prune(&format!("{r:#?}"))),
265 ));
266 }
267 }
268 if !cs.transitions.is_empty() {
269 out.push(("transitions", format!("{:#?}", cs.transitions)));
270 }
271 if !cs.animations.is_empty() {
272 out.push(("animations", format!("{:#?}", cs.animations)));
273 }
274 if cs.extras != sk_css::Extras::default() {
275 out.push(("extras", format!("{:#?}", cs.extras)));
276 }
277 Some(out)
278 })
279}
280
281pub fn shading(id: u32) -> Vec<(&'static str, gpui::EffectSpec)> {
283 tree::read_tree(|t| {
284 t.node(id)
285 .and_then(|n| n.computed.as_ref())
286 .map(shading_states)
287 .unwrap_or_default()
288 })
289}
290
291fn shading_states(cs: &sk_css::ComputedStates) -> Vec<(&'static str, gpui::EffectSpec)> {
292 let mut out = Vec::new();
293 let mut push = |name: &'static str, r: Option<&gpui::StyleRefinement>| {
294 if let Some(spec) = r.and_then(|r| r.vn_effect).filter(|s| s.is_some()) {
295 out.push((name, spec));
296 }
297 };
298 push("base", Some(&cs.base));
299 push("hover", cs.hover.as_deref());
300 push("active", cs.active.as_deref());
301 push("focus", cs.focus.as_deref());
302 push("focus-visible", cs.focus_visible.as_deref());
303 push("focus-within", cs.focus_within.as_deref());
304 push("group-hover", cs.group_hover.as_ref().map(|(_, r)| &**r));
305 push("group-active", cs.group_active.as_ref().map(|(_, r)| &**r));
306 out
307}
308
309pub fn shading_nodes() -> Vec<u32> {
312 tree::read_tree(|t| {
313 elements_in_document_order(t)
314 .into_iter()
315 .filter(|&id| {
316 t.node(id).is_some_and(|n| {
317 n.computed
318 .as_ref()
319 .is_some_and(|cs| !shading_states(cs).is_empty())
320 }) || t.style_value(id, "--shading").is_some()
321 })
322 .collect()
323 })
324}
325
326pub fn inline_style(id: u32, name: &str) -> Option<(String, bool)> {
328 tree::read_tree(|t| t.style_value(id, name).map(|(v, i)| (v.to_string(), i)))
329}
330
331pub fn set_inline_style(id: u32, name: &str, value: Option<(&str, bool)>) -> bool {
334 tree::with_tree(|t| match value {
335 Some((value, important)) => t.style_write(id, name, value.trim(), important),
336 None => t.style_remove(id, name).is_some(),
337 })
338}
339
340pub fn matched_rules(id: u32) -> Option<Vec<sk_css::MatchedRule>> {
341 let env = crate::env();
342 tree::read_tree(|t| {
343 t.node(id)?;
344 tree::with_engine(|engine| Some(engine?.matched_rules(NodeRef { tree: t, id }, &env)))
345 })
346}
347
348pub fn overlay_bounds(id: u32) -> Option<(f32, f32, f32, f32)> {
349 crate::render::painted_bounds(id)
350}
351
352pub fn hit_test(x: f32, y: f32, window: &Window) -> Vec<u32> {
356 hit_test_in(0, x, y, window)
357}
358
359pub fn hit_test_in(root: u32, x: f32, y: f32, window: &Window) -> Vec<u32> {
362 let point = gpui::Point::new(gpui::px(x), gpui::px(y));
363 tree::read_tree(|t| {
364 fn walk(
365 t: &Tree,
366 window_root: u32,
367 id: u32,
368 depth: usize,
369 point: gpui::Point<gpui::Pixels>,
370 window: &Window,
371 best: &mut Option<(usize, u32)>,
372 ) {
373 let Some(node) = t.node(id) else { return };
374 if node.kind == Kind::Element
375 && crate::render::pick_hitbox(window, id)
376 .is_some_and(|h| h.is_hovered_at(point, window))
377 && best.is_none_or(|(d, _)| depth >= d)
378 {
379 *best = Some((depth, id));
380 }
381 for &c in &node.children {
382 if window_root == 0 && crate::render::popped_out(c) {
385 continue;
386 }
387 walk(t, window_root, c, depth + 1, point, window, best);
388 }
389 }
390 let mut best = None;
391 let start = if root == 0 { t.root } else { root };
392 if start != 0 && t.node(start).is_some() {
393 walk(t, root, start, 0, point, window, &mut best);
394 }
395 let Some((_, mut id)) = best else {
396 return Vec::new();
397 };
398 let mut path = vec![id];
399 for _ in 0..1024 {
400 let Some(node) = t.node(id) else { break };
401 if node.parent == 0 {
402 break;
403 }
404 id = node.parent;
405 path.push(id);
406 }
407 path.reverse();
408 path
409 })
410}
411
412pub fn aim_point(id: u32, window: &Window) -> Option<(f32, f32)> {
413 let (x, y, w, h) = crate::render::bounds_here(window, id)?;
414 let centre = gpui::Point::new(gpui::px(x + w / 2.0), gpui::px(y + h / 2.0));
415 let hitbox = crate::render::pick_hitbox(window, id)?;
416 let scale = window.scale_factor();
417 let point = if hitbox.transformation.is_unit() {
418 centre
419 } else {
420 let d = hitbox.transformation.apply(gpui::Point::new(
421 gpui::px(f32::from(centre.x) * scale),
422 gpui::px(f32::from(centre.y) * scale),
423 ));
424 gpui::Point::new(
425 gpui::px(f32::from(d.x) / scale),
426 gpui::px(f32::from(d.y) / scale),
427 )
428 };
429 hitbox
430 .is_hovered_at(point, window)
431 .then(|| (f32::from(point.x), f32::from(point.y)))
432}
433
434fn prune(dump: &str) -> String {
435 let mut lines: Vec<String> = dump
436 .lines()
437 .filter(|l| !l.trim_end().ends_with(": None,") && l.trim() != "None,")
438 .map(str::to_string)
439 .collect();
440 loop {
441 let mut removed = false;
442 let mut i = 0;
443 while i + 1 < lines.len() {
444 let open = lines[i].trim_end().ends_with('{');
445 let close = matches!(lines[i + 1].trim(), "}" | "}," | ")" | "),");
446 if open && close {
447 lines.drain(i..=i + 1);
448 removed = true;
449 } else {
450 i += 1;
451 }
452 }
453 if !removed {
454 break;
455 }
456 }
457 lines.join("\n")
458}
459
460pub fn focus(id: u32, window: &mut Window, cx: &mut App) -> Result<(), String> {
461 crate::render::focus_node(id, window, cx)
462}
463
464pub fn is_focused(id: u32, window: &Window, cx: &App) -> bool {
465 crate::render::is_node_focused(id, window, cx)
466}
467
468pub fn focused_node(window: &Window, cx: &App) -> Option<u32> {
469 crate::render::focused_node(window, cx)
470}
471
472pub fn scroll(
473 id: u32,
474 dx: f32,
475 dy: f32,
476 window: &mut Window,
477 cx: &mut App,
478) -> Result<(f32, f32), String> {
479 crate::render::scroll_node(id, dx, dy, window, cx)
480}
481
482pub fn click(id: u32, x: f32, y: f32, button: f64, window: &mut Window, cx: &mut App) -> bool {
483 let payload = |b: f64| EventPayload {
484 a: x as f64,
485 b: y as f64,
486 c: b,
487 ..Default::default()
488 };
489 crate::render::synth_event(id, tree::EV_MOUSEDOWN, &payload(button), window, cx);
490 crate::render::synth_event(id, tree::EV_MOUSEUP, &payload(button), window, cx);
491 let proceed = crate::render::synth_event(id, tree::EV_CLICK, &payload(0.0), window, cx);
494 window.refresh();
495 proceed
496}
497
498#[cfg(test)]
499mod tests {
500 use super::*;
501
502 #[test]
504 fn text_and_anchor_nodes_have_no_tag_name() {
505 let (root, div, text, anchor) = tree::with_tree(|t| {
506 let root = t.create_root();
507 let div_tag = t.intern("div");
508 let div = t.create_element(div_tag);
509 let text = t.create_text();
510 let anchor = t.create_anchor();
511 t.insert(div, root, 0);
512 t.insert(text, div, 0);
513 t.insert(anchor, div, 0);
514 (root, div, text, anchor)
515 });
516
517 let info = |id: u32| node_info(id).expect("node exists");
518 assert_eq!(tree::read_tree(|t| t.name(0).to_string()), "");
519
520 assert_eq!(info(root).kind, "element");
521 assert_eq!(info(root).tag, "root");
522 assert_eq!(info(div).kind, "element");
523 assert_eq!(info(div).tag, "div");
524
525 assert_eq!(info(text).kind, "text");
526 assert_eq!(info(text).tag, "", "a text node has no tag name");
527 assert_eq!(info(anchor).kind, "anchor");
528 assert_eq!(info(anchor).tag, "", "a fragment anchor has no tag name");
529 }
530}
531
532#[cfg(feature = "webgpu")]
533pub fn gpu_canvas_presentation_stats() -> (u64, u64) {
534 crate::render::canvas::native_stats()
535}