Skip to main content

cranpose_app_shell/
shell_debug.rs

1use super::*;
2
3#[cfg(any(test, feature = "test-support"))]
4type SubcomposeScopeIds = Vec<(NodeId, Vec<(u64, Vec<usize>)>)>;
5#[cfg(any(test, feature = "test-support"))]
6type SlotGroupEntry = (usize, cranpose_core::Key, Option<usize>, usize);
7
8#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
9impl<R> AppShell<R>
10where
11    R: Renderer,
12    R::Error: Debug,
13{
14    /// Returns a text report of the first surface: its layout tree, its headless render scene and a
15    /// summary.
16    pub fn debug_info_report(&mut self) -> String {
17        debug_info_report(&mut self.app, &mut self.surfaces[0])
18    }
19
20    /// Logs the report from `debug_info_report` at info level under `cranpose::debug::screen` and
21    /// returns it.
22    pub fn log_debug_info(&mut self) -> String {
23        let report = self.debug_info_report();
24        log::info!(target: "cranpose::debug::screen", "\n{report}");
25        report
26    }
27
28    /// Sets how long a frame composes before pausable content waits for a
29    /// later frame, as [`cranpose_core::Composition::set_pausable_budget`]
30    /// does: tests that compare frames give `None`, so content that a change
31    /// brings composes in its frame whatever the machine's speed.
32    #[cfg(any(test, feature = "test-support"))]
33    pub fn set_pausable_budget(&mut self, budget: Option<std::time::Duration>) {
34        self.app.composition.set_pausable_budget(budget);
35    }
36
37    /// Get the current layout tree (for robot/testing)
38    pub fn layout_tree(&mut self) -> Option<&LayoutTree> {
39        let _app_context = self.app.app_context.enter_scope();
40        self.surfaces[0].layout_tree_in_context(&mut self.app)
41    }
42
43    #[doc(hidden)]
44    pub fn with_layout_tree<T>(&mut self, block: impl FnOnce(Option<&LayoutTree>) -> T) -> T {
45        let _app_context = self.app.app_context.enter_scope();
46        let layout_tree = self.surfaces[0].layout_tree_in_context(&mut self.app);
47        block(layout_tree)
48    }
49
50    /// Whether a semantics snapshot could contain anything at all. Reading the
51    /// flag costs nothing, unlike collecting the layout-bounds map only to find
52    /// semantics tracking disabled.
53    pub fn semantics_active(&self) -> bool {
54        self.app.semantics_enabled
55    }
56
57    /// Monotonic revision of the accessibility-relevant state. It moves when a
58    /// layout pass invalidated the cached snapshots, when semantics tracking is
59    /// toggled, when any node marked its semantics dirty since the last look,
60    /// and when a scene update moved a layer, which moves where the nodes in it
61    /// show. A bridge that stored the revision it last projected can skip the
62    /// whole snapshot-and-compare while this still reads the same — which on a
63    /// frame that only draws is every frame.
64    #[inline(never)]
65    pub fn semantics_snapshot_revision(&mut self) -> u64 {
66        if self.app.semantics_enabled
67            || self
68                .surfaces
69                .iter()
70                .any(|surface| surface.inspector.state.open)
71        {
72            let semantics_dirty = {
73                let _app_context = self.app.app_context.enter_scope();
74                self.app.flush_semantics_invalidations();
75                self.app.composition.root().is_some_and(|root| {
76                    let mut applier = self.app.composition.applier_mut();
77                    cranpose_ui::tree_needs_semantics(&mut *applier, root).unwrap_or(true)
78                })
79            };
80            let mut layers_moved = false;
81            for surface in &mut self.surfaces {
82                layers_moved |= surface.layers_moved_since_look();
83            }
84            if semantics_dirty || layers_moved {
85                self.app.semantics_snapshot_revision =
86                    self.app.semantics_snapshot_revision.wrapping_add(1);
87            }
88        }
89        self.app.semantics_snapshot_revision
90    }
91
92    /// Get the current semantics tree (for robot/testing)
93    pub fn semantics_tree(&mut self) -> Option<&SemanticsTree> {
94        let _app_context = self.app.app_context.enter_scope();
95        self.surfaces[0].semantics_tree_in_context(&mut self.app)
96    }
97
98    /// Returns the width and height of the first surface's root layout box in logical pixels, or
99    /// `None` before a layout exists.
100    pub fn root_layout_size(&mut self) -> Option<(f32, f32)> {
101        self.layout_tree().map(|tree| {
102            let root = tree.root();
103            (root.rect.width, root.rect.height)
104        })
105    }
106
107    /// Returns `(x, y, width, height)` of the layout box of `target` in logical pixels, or `None`
108    /// when the node is not in the layout tree.
109    pub fn node_layout_bounds(&mut self, target: NodeId) -> Option<(f32, f32, f32, f32)> {
110        self.layout_tree()
111            .and_then(|tree| find_layout_box(tree.root(), target))
112            .map(layout_box_bounds)
113    }
114
115    #[cfg(any(test, feature = "test-support"))]
116    #[doc(hidden)]
117    pub fn debug_runtime_leak_stats(&mut self) -> RuntimeLeakDebugStats {
118        let runtime = self.app.composition.runtime_handle();
119        let (applier_stats, live_node_heap_bytes, recycled_node_heap_bytes) = {
120            let applier = self.app.composition.applier_mut();
121            (
122                applier.debug_stats(),
123                applier.debug_live_node_heap_bytes(),
124                applier.debug_recycled_node_heap_bytes(),
125            )
126        };
127        RuntimeLeakDebugStats {
128            applier_stats,
129            live_node_heap_bytes,
130            recycled_node_heap_bytes,
131            slot_table_heap_bytes: self.app.composition.slot_table_heap_bytes(),
132            pass_stats: self.app.composition.debug_last_pass_stats(),
133            slot_stats: self.app.composition.debug_slot_table_stats(),
134            runtime_stats: runtime.debug_stats(),
135            state_arena_stats: runtime.state_arena_debug_stats(),
136            recompose_scope_stats: debug_recompose_scope_registry_stats(),
137            snapshot_v2_stats: debug_snapshot_v2_stats(),
138            snapshot_pinning_stats: debug_snapshot_pinning_stats(),
139        }
140    }
141
142    #[cfg(any(test, feature = "test-support"))]
143    #[doc(hidden)]
144    pub fn debug_slot_table_groups(&self) -> Vec<SlotGroupEntry> {
145        self.app.composition.debug_dump_slot_table_groups()
146    }
147
148    #[cfg(any(test, feature = "test-support"))]
149    #[doc(hidden)]
150    pub fn debug_slot_entries(&self) -> Vec<cranpose_core::SlotDebugEntry> {
151        self.app.composition.debug_dump_slot_entries()
152    }
153
154    #[cfg(any(test, feature = "test-support"))]
155    #[doc(hidden)]
156    pub fn runtime_handle(&self) -> cranpose_core::RuntimeHandle {
157        self.app.composition.runtime_handle()
158    }
159
160    #[cfg(any(test, feature = "test-support"))]
161    #[doc(hidden)]
162    pub fn debug_live_subcompose_scope_ids(&mut self) -> SubcomposeScopeIds {
163        fn collect_node_ids(layout: &LayoutBox, out: &mut Vec<NodeId>) {
164            out.push(layout.node_id);
165            for child in &layout.children {
166                collect_node_ids(child, out);
167            }
168        }
169
170        let mut node_ids = Vec::new();
171        if let Some(tree) = self.layout_tree() {
172            collect_node_ids(tree.root(), &mut node_ids);
173        }
174
175        let mut applier = self.app.composition.applier_mut();
176        let mut result = Vec::new();
177        for node_id in node_ids {
178            if let Ok(scope_ids) = applier.with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
179                node.debug_scope_ids_by_slot()
180            }) {
181                result.push((node_id, scope_ids));
182            }
183        }
184        result
185    }
186
187    #[cfg(any(test, feature = "test-support"))]
188    #[doc(hidden)]
189    pub fn debug_subcompose_slot_table(
190        &mut self,
191        node_id: NodeId,
192        slot_id: u64,
193    ) -> Option<Vec<cranpose_core::SlotDebugEntry>> {
194        let mut applier = self.app.composition.applier_mut();
195        applier
196            .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
197                node.debug_slot_table_for_slot(SlotId::new(slot_id))
198            })
199            .ok()
200            .flatten()
201    }
202
203    #[cfg(any(test, feature = "test-support"))]
204    #[doc(hidden)]
205    pub fn debug_subcompose_slot_groups(
206        &mut self,
207        node_id: NodeId,
208        slot_id: u64,
209    ) -> Option<Vec<SlotGroupEntry>> {
210        let mut applier = self.app.composition.applier_mut();
211        applier
212            .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
213                node.debug_slot_table_groups_for_slot(SlotId::new(slot_id))
214            })
215            .ok()
216            .flatten()
217    }
218}
219
220fn find_layout_box(layout_box: &LayoutBox, target: NodeId) -> Option<&LayoutBox> {
221    if layout_box.node_id == target {
222        return Some(layout_box);
223    }
224
225    layout_box
226        .children
227        .iter()
228        .find_map(|child| find_layout_box(child, target))
229}
230
231fn layout_box_bounds(layout_box: &LayoutBox) -> (f32, f32, f32, f32) {
232    (
233        layout_box.rect.x,
234        layout_box.rect.y,
235        layout_box.rect.width,
236        layout_box.rect.height,
237    )
238}
239
240fn debug_info_report<R: Renderer>(app: &mut ShellApp, surface: &mut RootSurface<R>) -> String {
241    let _app_context = app.app_context.enter_scope();
242    let mut report = String::new();
243    writeln!(report, "=== DEBUG: CURRENT SCREEN STATE ===").ok();
244    if let Some(layout_tree) = surface.layout_tree_in_context(app) {
245        let renderer = HeadlessRenderer::new();
246        let render_scene = renderer.render(layout_tree);
247        writeln!(report, "{}", format_layout_tree(layout_tree)).ok();
248        writeln!(report, "{}", format_render_scene(&render_scene)).ok();
249        writeln!(
250            report,
251            "{}",
252            format_screen_summary(layout_tree, &render_scene)
253        )
254        .ok();
255    } else {
256        writeln!(report, "No layout available").ok();
257    }
258    report
259}