Skip to main content

sk_tree/
devtools.rs

1//! The read/drive surface `sk-devtools` sits on: selector queries against the REAL cascade matcher,
2//! node dumps off the retained tree, and synthesized input through the ordinary dispatch path.
3//!
4//! It lives here because the node slab and side maps are private to this crate; sk-app owns the
5//! transport. Nothing is dev-gated here: sk-app compiles its callers out under `--features prod`.
6
7use 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    /// A descendant's `group-hover:` rule watches this element, so it got gpui's `.group(name)` (and a hitbox).
26    pub group_anchor: bool,
27}
28
29/// The listener bits as names, off [`tree::EVENT_NAMES`], so this listing cannot drift from the codes.
30fn 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
82/// `(element-tree builds, paint-only presents)` since start, in any window; a `<video>` or moving
83/// `<canvas>` frame is a present (`crate::live`).
84pub fn frame_counts() -> (u64, u64) {
85    (crate::render::build_count(), crate::live::present_count())
86}
87
88/// Layouts re-run for container queries, and query containers whose size moved, since start.
89pub fn container_query_counts() -> (u64, u64) {
90    crate::containers::counts()
91}
92
93pub use crate::resample::ImageStats;
94pub use crate::tree::TreeMem;
95
96pub fn tree_mem() -> TreeMem {
97    tree::read_tree(|t| t.mem_estimate())
98}
99
100pub fn image_stats() -> ImageStats {
101    crate::resample::image_stats()
102}
103
104pub use crate::img::{KeptFull, ResidencyStats};
105
106pub fn residency_stats() -> ResidencyStats {
107    crate::img::residency_stats()
108}
109
110pub fn set_image_tracking(on: bool) {
111    crate::resample::set_tracking(on);
112}
113
114pub fn side_stats() -> Vec<(&'static str, u64)> {
115    let (memos, src_bytes, images, image_bytes, backgrounds) = crate::img::mem_stats();
116    let (canvases, canvas_bytes) = crate::render::canvas::mem_stats();
117    let (svg_docs, svg_rasters, svg_bytes) = crate::svg::mem_stats();
118    let (log_entries, log_bytes) = crate::log::mem_stats();
119    let (declared, waiting, waiting_bytes, registered, registered_bytes) =
120        crate::fonts::mem_stats();
121    let (boundaries, entities, cached_ids) = crate::cache::mem_stats();
122    let (focus, inputs, scrolls, bounds) = crate::render::side_state_counts();
123    let (stickers, sticker_tiles, sticker_tile_bytes) = crate::render::sticker::mem_stats();
124    let u = |v: usize| v as u64;
125    vec![
126        ("imgMemos", u(memos)),
127        ("imgSrcBytes", u(src_bytes)),
128        ("imgEncodedInMemory", u(images)),
129        ("imgEncodedInMemoryBytes", u(image_bytes)),
130        ("cssBackgroundLayers", u(backgrounds)),
131        ("canvases", u(canvases)),
132        ("canvasHostCopyBytes", u(canvas_bytes)),
133        ("svgDocs", u(svg_docs)),
134        ("svgColourRasters", u(svg_rasters)),
135        ("svgColourRasterBytes", u(svg_bytes)),
136        ("videos", u(crate::video::count())),
137        ("videosAudible", u(crate::video::audible_count())),
138        ("lotties", u(crate::lottie::count())),
139        ("stickers", u(stickers)),
140        ("stickerTiles", u(sticker_tiles)),
141        ("stickerTileBytes", u(sticker_tile_bytes)),
142        ("logRingEntries", u(log_entries)),
143        ("logRingBytes", u(log_bytes)),
144        ("fontFacesDeclared", u(declared)),
145        ("fontFacesLoadedNotRegistered", u(waiting)),
146        ("fontFacesLoadedNotRegisteredBytes", u(waiting_bytes)),
147        ("fontFacesRegistered", registered),
148        ("fontFacesRegisteredBytes", registered_bytes),
149        ("cacheBoundaries", u(boundaries)),
150        ("cacheBoundaryEntities", u(entities)),
151        ("cacheBoundaryNodeIds", u(cached_ids)),
152        ("focusHandles", u(focus)),
153        ("inputStates", u(inputs)),
154        ("scrollHandles", u(scrolls)),
155        ("boundsEntries", u(bounds)),
156    ]
157}
158
159pub fn scroll_chain_count() -> u32 {
160    sk_elements::scrollbar::chain_count() as u32
161}
162
163pub fn node_info(id: u32) -> Option<NodeInfo> {
164    tree::read_tree(|t| {
165        let n = t.node(id)?;
166        Some(NodeInfo {
167            id,
168            kind: match n.kind {
169                Kind::Element => "element",
170                Kind::Text => "text",
171                Kind::Anchor => "anchor",
172            },
173            tag: t.name(n.tag).to_string(),
174            classes: n.classes.clone(),
175            scopes: n.scopes.clone(),
176            props: n
177                .props
178                .iter()
179                .map(|(k, v, _)| (t.name(*k).to_string(), v.clone()))
180                .collect(),
181            text: n.text.clone(),
182            parent: n.parent,
183            children: n.children.clone(),
184            listeners: event_names(n.listeners),
185            bounds: crate::render::bounds_of(id),
186            group_anchor: t.is_group_anchor(id),
187        })
188    })
189}
190
191pub fn text_content(id: u32) -> Option<String> {
192    tree::read_tree(|t| {
193        t.node(id)?;
194        let mut out = String::new();
195        fn walk(t: &Tree, id: u32, out: &mut String) {
196            let Some(n) = t.node(id) else { return };
197            // An element's own `text` is set by `setElementText`, which is exclusive with children
198            // — so this never double-counts.
199            out.push_str(&n.text);
200            for &c in &n.children {
201                walk(t, c, out);
202            }
203        }
204        walk(t, id, &mut out);
205        Some(out)
206    })
207}
208
209pub fn input_value(id: u32, cx: &App) -> Option<String> {
210    crate::render::input_value(id, cx)
211}
212
213/// A text field's IME, as the platform drives the field's input handler: `text` becomes the
214/// composition's pre-edit (`""` cancels it), or with `commit` its committed text.
215pub fn ime(
216    id: u32,
217    text: &str,
218    commit: bool,
219    window: &mut Window,
220    cx: &mut App,
221) -> Result<(), String> {
222    crate::render::ime(id, text, commit, window, cx)
223}
224
225/// See [`tree::is_hovered`] for the one case that answers `false` while a browser would say `true`.
226pub fn is_hovered(id: u32) -> bool {
227    tree::is_hovered(id)
228}
229
230pub fn computed_styles(id: u32) -> Option<Vec<(&'static str, String)>> {
231    // Hoisted out of the closure below: `live_style` reads the tree itself, and a reader that only
232    // works while nothing else is reading is a trap.
233    let live = tree::live_style(id);
234    tree::read_tree(|t| {
235        let cs = t.node(id)?.computed.as_ref()?;
236        let mut out = vec![("base", prune(&format!("{:#?}", cs.base)))];
237        if let Some(live) = &live {
238            out.push(("live", prune(&format!("{live:#?}"))));
239        }
240        for (name, slot) in [
241            ("hover", &cs.hover),
242            ("active", &cs.active),
243            ("focus", &cs.focus),
244            ("focus-visible", &cs.focus_visible),
245        ] {
246            if let Some(r) = slot {
247                out.push((name, prune(&format!("{r:#?}"))));
248            }
249        }
250        // `.group:hover .this` — the ancestor is named, because "which element am I watching" is
251        // the half of a group rule that can be wrong.
252        let group_focus = cs.group_focus.as_deref();
253        for (name, slot) in [
254            ("group-hover", &cs.group_hover),
255            ("group-active", &cs.group_active),
256            ("group-focus", &group_focus.and_then(|g| g.focus.clone())),
257            (
258                "group-focus-visible",
259                &group_focus.and_then(|g| g.focus_visible.clone()),
260            ),
261            (
262                "group-focus-within",
263                &group_focus.and_then(|g| g.focus_within.clone()),
264            ),
265        ] {
266            if let Some((anchor, r)) = slot {
267                out.push((
268                    name,
269                    format!("watching node {anchor}\n{}", prune(&format!("{r:#?}"))),
270                ));
271            }
272        }
273        if !cs.transitions.is_empty() {
274            out.push(("transitions", format!("{:#?}", cs.transitions)));
275        }
276        if !cs.animations.is_empty() {
277            out.push(("animations", format!("{:#?}", cs.animations)));
278        }
279        if cs.extras != sk_css::Extras::default() {
280            out.push(("extras", format!("{:#?}", cs.extras)));
281        }
282        Some(out)
283    })
284}
285
286/// The `--shading` effect each state of `id` resolved to, `base` first; `none` is left out.
287pub fn shading(id: u32) -> Vec<(&'static str, gpui::EffectSpec)> {
288    tree::read_tree(|t| {
289        t.node(id)
290            .and_then(|n| n.computed.as_ref())
291            .map(shading_states)
292            .unwrap_or_default()
293    })
294}
295
296fn shading_states(cs: &sk_css::ComputedStates) -> Vec<(&'static str, gpui::EffectSpec)> {
297    let mut out = Vec::new();
298    let mut push = |name: &'static str, r: Option<&gpui::StyleRefinement>| {
299        if let Some(spec) = r.and_then(|r| r.vn_effect).filter(|s| s.is_some()) {
300            out.push((name, spec));
301        }
302    };
303    push("base", Some(&cs.base));
304    push("hover", cs.hover.as_deref());
305    push("active", cs.active.as_deref());
306    push("focus", cs.focus.as_deref());
307    push("focus-visible", cs.focus_visible.as_deref());
308    push("focus-within", cs.focus_within.as_deref());
309    push("group-hover", cs.group_hover.as_ref().map(|(_, r)| &**r));
310    push("group-active", cs.group_active.as_ref().map(|(_, r)| &**r));
311    out
312}
313
314/// Elements in document order whose computed style paints a `--shading` effect in some state, or
315/// whose inline style declares one.
316pub fn shading_nodes() -> Vec<u32> {
317    tree::read_tree(|t| {
318        elements_in_document_order(t)
319            .into_iter()
320            .filter(|&id| {
321                t.node(id).is_some_and(|n| {
322                    n.computed
323                        .as_ref()
324                        .is_some_and(|cs| !shading_states(cs).is_empty())
325                }) || t.style_value(id, "--shading").is_some()
326            })
327            .collect()
328    })
329}
330
331/// One inline declaration as `(value, important)`.
332pub fn inline_style(id: u32, name: &str) -> Option<(String, bool)> {
333    tree::read_tree(|t| t.style_value(id, name).map(|(v, i)| (v.to_string(), i)))
334}
335
336/// Writes one inline declaration (`None` removes it) as `style.setProperty` would, minus the
337/// mutation observers: the inspector's edits are not the app's.
338pub fn set_inline_style(id: u32, name: &str, value: Option<(&str, bool)>) -> bool {
339    tree::with_tree(|t| match value {
340        Some((value, important)) => t.style_write(id, name, value.trim(), important),
341        None => t.style_remove(id, name).is_some(),
342    })
343}
344
345pub fn matched_rules(id: u32) -> Option<Vec<sk_css::MatchedRule>> {
346    let env = crate::env();
347    tree::read_tree(|t| {
348        t.node(id)?;
349        tree::with_engine(|engine| Some(engine?.matched_rules(NodeRef { tree: t, id }, &env)))
350    })
351}
352
353pub fn overlay_bounds(id: u32) -> Option<(f32, f32, f32, f32)> {
354    crate::render::painted_bounds(id)
355}
356
357/// The deepest ELEMENT gpui would hit at `(x, y)`, as the path from the root down (empty over
358/// nothing): gpui's own hit test (every element gets a hitbox tagged with its node id in a dev host),
359/// so transforms, paint order and masks are exact. Ties go to the deepest, then the last in document order.
360pub fn hit_test(x: f32, y: f32, window: &Window) -> Vec<u32> {
361    hit_test_in(0, x, y, window)
362}
363
364/// [`hit_test`] restricted to the window that paints `root` (0 = primary): hitboxes live in the
365/// painting window's frame. The path is still root-first from the document root.
366pub fn hit_test_in(root: u32, x: f32, y: f32, window: &Window) -> Vec<u32> {
367    let point = gpui::Point::new(gpui::px(x), gpui::px(y));
368    tree::read_tree(|t| {
369        fn walk(
370            t: &Tree,
371            window_root: u32,
372            id: u32,
373            depth: usize,
374            point: gpui::Point<gpui::Pixels>,
375            window: &Window,
376            best: &mut Option<(usize, u32)>,
377        ) {
378            let Some(node) = t.node(id) else { return };
379            if node.kind == Kind::Element
380                && crate::render::pick_hitbox(window, id)
381                    .is_some_and(|h| h.is_hovered_at(point, window))
382                && best.is_none_or(|(d, _)| depth >= d)
383            {
384                *best = Some((depth, id));
385            }
386            for &c in &node.children {
387                // A popped-out subtree is painted by a DIFFERENT window; its hitboxes are not in
388                // this window's frame, so descending into it can only waste time.
389                if window_root == 0 && crate::render::popped_out(c) {
390                    continue;
391                }
392                walk(t, window_root, c, depth + 1, point, window, best);
393            }
394        }
395        let mut best = None;
396        let start = if root == 0 { t.root } else { root };
397        if start != 0 && t.node(start).is_some() {
398            walk(t, root, start, 0, point, window, &mut best);
399        }
400        let Some((_, mut id)) = best else {
401            return Vec::new();
402        };
403        let mut path = vec![id];
404        for _ in 0..1024 {
405            let Some(node) = t.node(id) else { break };
406            if node.parent == 0 {
407                break;
408            }
409            id = node.parent;
410            path.push(id);
411        }
412        path.reverse();
413        path
414    })
415}
416
417pub fn aim_point(id: u32, window: &Window) -> Option<(f32, f32)> {
418    let (x, y, w, h) = crate::render::bounds_here(window, id)?;
419    let centre = gpui::Point::new(gpui::px(x + w / 2.0), gpui::px(y + h / 2.0));
420    let hitbox = crate::render::pick_hitbox(window, id)?;
421    let scale = window.scale_factor();
422    let point = if hitbox.transformation.is_unit() {
423        centre
424    } else {
425        let d = hitbox.transformation.apply(gpui::Point::new(
426            gpui::px(f32::from(centre.x) * scale),
427            gpui::px(f32::from(centre.y) * scale),
428        ));
429        gpui::Point::new(
430            gpui::px(f32::from(d.x) / scale),
431            gpui::px(f32::from(d.y) / scale),
432        )
433    };
434    hitbox
435        .is_hovered_at(point, window)
436        .then(|| (f32::from(point.x), f32::from(point.y)))
437}
438
439fn prune(dump: &str) -> String {
440    let mut lines: Vec<String> = dump
441        .lines()
442        .filter(|l| !l.trim_end().ends_with(": None,") && l.trim() != "None,")
443        .map(str::to_string)
444        .collect();
445    loop {
446        let mut removed = false;
447        let mut i = 0;
448        while i + 1 < lines.len() {
449            let open = lines[i].trim_end().ends_with('{');
450            let close = matches!(lines[i + 1].trim(), "}" | "}," | ")" | "),");
451            if open && close {
452                lines.drain(i..=i + 1);
453                removed = true;
454            } else {
455                i += 1;
456            }
457        }
458        if !removed {
459            break;
460        }
461    }
462    lines.join("\n")
463}
464
465pub fn focus(id: u32, window: &mut Window, cx: &mut App) -> Result<(), String> {
466    crate::render::focus_node(id, window, cx)
467}
468
469pub fn is_focused(id: u32, window: &Window, cx: &App) -> bool {
470    crate::render::is_node_focused(id, window, cx)
471}
472
473pub fn focused_node(window: &Window, cx: &App) -> Option<u32> {
474    crate::render::focused_node(window, cx)
475}
476
477pub fn scroll(
478    id: u32,
479    dx: f32,
480    dy: f32,
481    window: &mut Window,
482    cx: &mut App,
483) -> Result<(f32, f32), String> {
484    crate::render::scroll_node(id, dx, dy, window, cx)
485}
486
487pub fn click(id: u32, x: f32, y: f32, button: f64, window: &mut Window, cx: &mut App) -> bool {
488    let payload = |b: f64| EventPayload {
489        a: x as f64,
490        b: y as f64,
491        c: b,
492        ..Default::default()
493    };
494    crate::render::synth_event(id, tree::EV_MOUSEDOWN, &payload(button), window, cx);
495    crate::render::synth_event(id, tree::EV_MOUSEUP, &payload(button), window, cx);
496    // A browser's `click` carries button 0 whatever `MouseEvent.button` the press had (a right
497    // press produces `contextmenu`, never `click`).
498    let proceed = crate::render::synth_event(id, tree::EV_CLICK, &payload(0.0), window, cx);
499    window.refresh();
500    proceed
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506
507    /// `tag: 0` means "this node has no tag" — `create_text` and `create_anchor` both set it.
508    #[test]
509    fn text_and_anchor_nodes_have_no_tag_name() {
510        let (root, div, text, anchor) = tree::with_tree(|t| {
511            let root = t.create_root();
512            let div_tag = t.intern("div");
513            let div = t.create_element(div_tag);
514            let text = t.create_text();
515            let anchor = t.create_anchor();
516            t.insert(div, root, 0);
517            t.insert(text, div, 0);
518            t.insert(anchor, div, 0);
519            (root, div, text, anchor)
520        });
521
522        let info = |id: u32| node_info(id).expect("node exists");
523        assert_eq!(tree::read_tree(|t| t.name(0).to_string()), "");
524
525        assert_eq!(info(root).kind, "element");
526        assert_eq!(info(root).tag, "root");
527        assert_eq!(info(div).kind, "element");
528        assert_eq!(info(div).tag, "div");
529
530        assert_eq!(info(text).kind, "text");
531        assert_eq!(info(text).tag, "", "a text node has no tag name");
532        assert_eq!(info(anchor).kind, "anchor");
533        assert_eq!(info(anchor).tag, "", "a fragment anchor has no tag name");
534    }
535}
536
537#[cfg(feature = "webgpu")]
538pub fn gpu_canvas_presentation_stats() -> (u64, u64) {
539    crate::render::canvas::native_stats()
540}