Skip to main content

sui_debug/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{
4    cell::RefCell,
5    collections::{HashMap, HashSet},
6    rc::Rc,
7};
8
9use sui_core::{Color, DirtyRegion, Rect, SemanticsValue, Size, WidgetId, WindowId};
10use sui_layout::Alignment;
11use sui_platform::{
12    AccessibilityIssue, AccessibilityIssueSeverity, AccessibilitySnapshot,
13    validate_accessibility_snapshot,
14};
15use sui_reactive::Signal;
16use sui_runtime::{
17    CacheMetrics, CacheMetricsDelta, EventRoutePhase, FocusState, FramePhase, FrameSchedule,
18    SceneStatistics, Widget, WidgetDiagnosticsSnapshot, WidgetGraphSnapshot, WidgetNodeSnapshot,
19    WidgetPod, WindowInspectorSnapshot, WindowPerformanceSnapshot,
20};
21use sui_scene::SceneFrame;
22use sui_widgets::{
23    Background, Label, ListItem, ListView, Padding, RebuildOnChange, ScrollState, ScrollView,
24    Separator, SizedBox, Stack, Table, TableColumn, TableRow, TreeItem, TreeView,
25};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum DebugTone {
29    Neutral,
30    Info,
31    Success,
32    Warning,
33    Danger,
34}
35
36#[derive(Debug, Clone, PartialEq)]
37pub struct DebugMetric {
38    pub label: String,
39    pub value: String,
40    pub detail: Option<String>,
41    pub tone: DebugTone,
42}
43
44impl DebugMetric {
45    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
46        Self {
47            label: label.into(),
48            value: value.into(),
49            detail: None,
50            tone: DebugTone::Neutral,
51        }
52    }
53
54    pub fn detail(mut self, detail: impl Into<String>) -> Self {
55        self.detail = Some(detail.into());
56        self
57    }
58
59    pub const fn tone(mut self, tone: DebugTone) -> Self {
60        self.tone = tone;
61        self
62    }
63}
64
65#[derive(Debug, Clone, PartialEq)]
66pub struct DebugKeyValue {
67    pub label: String,
68    pub value: String,
69}
70
71impl DebugKeyValue {
72    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
73        Self {
74            label: label.into(),
75            value: value.into(),
76        }
77    }
78}
79
80#[derive(Debug, Clone, PartialEq)]
81pub struct SceneDebugSummary {
82    pub viewport: Size,
83    pub dirty_region_count: usize,
84    pub dirty_regions: Vec<DirtyRegion>,
85    pub command_count: usize,
86    pub command_breakdown: Vec<(String, usize)>,
87    pub layer_update_count: usize,
88    pub layer_update_breakdown: Vec<(String, usize)>,
89    pub stack_host_count: usize,
90    pub stack_surface_count: usize,
91    pub transient_surface_count: usize,
92    pub detail_collected: bool,
93}
94
95impl From<&SceneFrame> for SceneDebugSummary {
96    fn from(frame: &SceneFrame) -> Self {
97        let mut command_breakdown = HashMap::<String, usize>::new();
98        let mut command_count = 0usize;
99        frame.scene.visit_commands(&mut |command| {
100            command_count += 1;
101            *command_breakdown
102                .entry(command.diagnostic_name().to_string())
103                .or_default() += 1;
104        });
105
106        let mut command_breakdown: Vec<_> = command_breakdown.into_iter().collect();
107        command_breakdown.sort_by(|left, right| left.0.cmp(&right.0));
108
109        let mut layer_update_breakdown = HashMap::<String, usize>::new();
110        for update in &frame.layer_updates {
111            *layer_update_breakdown
112                .entry(layer_update_kind(update.kind).to_string())
113                .or_default() += 1;
114        }
115        let mut layer_update_breakdown: Vec<_> = layer_update_breakdown.into_iter().collect();
116        layer_update_breakdown.sort_by(|left, right| left.0.cmp(&right.0));
117
118        let mut stack_hosts = HashSet::new();
119        let mut stack_surface_count = 0usize;
120        let mut transient_surface_count = 0usize;
121        frame.scene.visit_layers(&mut |layer| {
122            if layer.descriptor.is_stack_surface {
123                stack_surface_count += 1;
124                stack_hosts.insert(layer.descriptor.stack_host);
125                if layer.descriptor.transient_owner_surface.is_some() {
126                    transient_surface_count += 1;
127                }
128            }
129        });
130
131        Self {
132            viewport: frame.viewport,
133            dirty_region_count: frame.dirty_regions.len(),
134            dirty_regions: frame.dirty_regions.clone(),
135            command_count,
136            command_breakdown,
137            layer_update_count: frame.layer_updates.len(),
138            layer_update_breakdown,
139            stack_host_count: stack_hosts.len(),
140            stack_surface_count,
141            transient_surface_count,
142            detail_collected: true,
143        }
144    }
145}
146
147impl From<&SceneStatistics> for SceneDebugSummary {
148    fn from(scene: &SceneStatistics) -> Self {
149        Self {
150            viewport: scene.viewport,
151            dirty_region_count: scene.dirty_region_count,
152            dirty_regions: scene.dirty_regions.clone(),
153            command_count: scene.command_count,
154            command_breakdown: scene.command_breakdown.clone(),
155            layer_update_count: scene.layer_update_count,
156            layer_update_breakdown: scene.layer_update_breakdown.clone(),
157            stack_host_count: 0,
158            stack_surface_count: 0,
159            transient_surface_count: 0,
160            detail_collected: scene.detail_mode.is_detailed(),
161        }
162    }
163}
164
165#[derive(Debug, Clone, PartialEq)]
166pub struct WindowDebugSnapshot {
167    pub title: String,
168    pub window_id: WindowId,
169    pub focus_state: FocusState,
170    pub schedule: Option<FrameSchedule>,
171    pub accessibility: AccessibilitySnapshot,
172    pub widget_graph: WidgetGraphSnapshot,
173    pub scene_summary: Option<SceneDebugSummary>,
174}
175
176impl WindowDebugSnapshot {
177    pub fn new(
178        title: impl Into<String>,
179        window_id: WindowId,
180        focus_state: FocusState,
181        accessibility: AccessibilitySnapshot,
182        widget_graph: WidgetGraphSnapshot,
183    ) -> Self {
184        Self {
185            title: title.into(),
186            window_id,
187            focus_state,
188            schedule: None,
189            accessibility,
190            widget_graph,
191            scene_summary: None,
192        }
193    }
194
195    pub const fn with_schedule(mut self, schedule: FrameSchedule) -> Self {
196        self.schedule = Some(schedule);
197        self
198    }
199
200    pub fn with_scene_summary(mut self, scene_summary: SceneDebugSummary) -> Self {
201        self.scene_summary = Some(scene_summary);
202        self
203    }
204}
205
206/// Shareable publisher for a live inspector window.
207///
208/// Keep this state outside the inspected widget tree (normally in a second
209/// window) and publish fresh [`WindowInspectorSnapshot`] values after frames or
210/// events. The outer scroll state is retained across snapshot refreshes.
211#[derive(Clone)]
212pub struct InspectorState {
213    snapshot: Rc<RefCell<WindowInspectorSnapshot>>,
214    revision: Signal<u64>,
215    scroll: ScrollState,
216}
217
218impl InspectorState {
219    pub fn new(snapshot: WindowInspectorSnapshot) -> Self {
220        Self {
221            snapshot: Rc::new(RefCell::new(snapshot)),
222            revision: Signal::named("SUI inspector snapshot", 0),
223            scroll: ScrollState::new(),
224        }
225    }
226
227    pub fn snapshot(&self) -> WindowInspectorSnapshot {
228        self.snapshot.borrow().clone()
229    }
230
231    pub fn publish(&self, snapshot: WindowInspectorSnapshot) -> bool {
232        if *self.snapshot.borrow() == snapshot {
233            return false;
234        }
235        *self.snapshot.borrow_mut() = snapshot;
236        let _ = self.revision.set(self.revision.get().wrapping_add(1));
237        true
238    }
239}
240
241pub fn live_inspector_view(state: InspectorState) -> impl Widget {
242    let snapshot = Rc::clone(&state.snapshot);
243    let body = RebuildOnChange::key_from(state.revision.clone(), move |_| {
244        WidgetPod::new(inspector_snapshot_body(snapshot.borrow().clone()))
245    });
246    ScrollView::vertical(body).state(state.scroll.clone())
247}
248
249pub fn debug_panel<W>(title: impl Into<String>, subtitle: impl Into<String>, body: W) -> impl Widget
250where
251    W: Widget + 'static,
252{
253    let title = title.into();
254    let subtitle = subtitle.into();
255
256    Background::new(
257        Color::rgba(0.984, 0.989, 0.997, 1.0),
258        Padding::all(
259            14.0,
260            Stack::vertical()
261                .gap(8.0)
262                .alignment(Alignment::Stretch)
263                .with_child(
264                    Label::new(title)
265                        .font_size(18.0)
266                        .line_height(22.0)
267                        .color(Color::rgba(0.10, 0.14, 0.20, 1.0)),
268                )
269                .with_child(
270                    Label::new(subtitle)
271                        .font_size(12.0)
272                        .line_height(16.0)
273                        .color(Color::rgba(0.42, 0.49, 0.58, 1.0)),
274                )
275                .with_child(Separator::horizontal())
276                .with_child(body),
277        ),
278    )
279}
280
281pub fn debug_metric_grid<I>(metrics: I) -> impl Widget
282where
283    I: IntoIterator<Item = DebugMetric>,
284{
285    let metrics: Vec<_> = metrics.into_iter().collect();
286    let mut column = Stack::vertical().gap(10.0).alignment(Alignment::Stretch);
287
288    for chunk in metrics.chunks(4) {
289        let mut row = Stack::horizontal().gap(10.0).alignment(Alignment::Stretch);
290        for metric in chunk {
291            row = row.with_child(
292                SizedBox::new()
293                    .width(156.0)
294                    .child(metric_card(metric.clone())),
295            );
296        }
297        column = column.with_child(row);
298    }
299
300    column
301}
302
303pub fn debug_key_values<I>(entries: I) -> impl Widget
304where
305    I: IntoIterator<Item = DebugKeyValue>,
306{
307    let mut column = Stack::vertical().gap(6.0).alignment(Alignment::Stretch);
308
309    for (index, entry) in entries.into_iter().enumerate() {
310        let background = if index % 2 == 0 {
311            Color::rgba(0.971, 0.978, 0.989, 1.0)
312        } else {
313            Color::rgba(0.957, 0.968, 0.983, 1.0)
314        };
315        column = column.with_child(Background::new(
316            background,
317            Padding::all(
318                8.0,
319                Stack::horizontal()
320                    .gap(10.0)
321                    .alignment(Alignment::Center)
322                    .with_child(
323                        SizedBox::new().width(160.0).child(
324                            Label::new(entry.label)
325                                .font_size(11.0)
326                                .line_height(15.0)
327                                .color(Color::rgba(0.38, 0.46, 0.55, 1.0)),
328                        ),
329                    )
330                    .with_child(
331                        Label::new(entry.value)
332                            .font_size(12.0)
333                            .line_height(16.0)
334                            .color(Color::rgba(0.12, 0.17, 0.24, 1.0)),
335                    ),
336            ),
337        ));
338    }
339
340    column
341}
342
343pub fn accessibility_snapshot_view(snapshot: AccessibilitySnapshot) -> impl Widget {
344    let items = snapshot
345        .nodes
346        .iter()
347        .map(|node| {
348            let mut detail = format!(
349                "role={:?} parent={} bounds={} focus={} hidden={}",
350                node.role,
351                format_optional_widget_id(node.parent),
352                format_rect(node.bounds),
353                yes_no(node.state.focused),
354                yes_no(node.state.hidden),
355            );
356
357            if let Some(name) = &node.name {
358                detail.push_str(&format!(" name={name}"));
359            }
360            if let Some(value) = &node.value {
361                detail.push_str(&format!(" value={}", format_semantics_value(value)));
362            }
363
364            let mut item =
365                ListItem::new(format!("#{} {:?}", node.id.get(), node.role)).detail(detail);
366            if node.state.focused {
367                item = item.accent(Color::rgba(0.88, 0.33, 0.19, 1.0));
368            } else if node.state.hidden {
369                item = item.accent(Color::rgba(0.54, 0.60, 0.68, 1.0));
370            } else {
371                item = item.accent(Color::rgba(0.16, 0.56, 0.87, 1.0));
372            }
373            item
374        })
375        .collect::<Vec<_>>();
376
377    SizedBox::new()
378        .height(220.0)
379        .child(ListView::new("Accessibility snapshot").items(items))
380}
381
382pub fn widget_graph_snapshot_view(graph: WidgetGraphSnapshot) -> impl Widget {
383    let items = build_graph_tree_items(&graph);
384    SizedBox::new()
385        .height(240.0)
386        .child(TreeView::new("Widget graph").items(items))
387}
388
389pub fn scene_summary_view(scene: SceneDebugSummary) -> impl Widget {
390    let metrics = debug_metric_grid([
391        DebugMetric::new("Viewport", format_size(scene.viewport))
392            .detail("Logical render target size")
393            .tone(DebugTone::Info),
394        DebugMetric::new("Dirty regions", scene.dirty_region_count.to_string())
395            .detail("Invalidated rectangles queued into the scene")
396            .tone(if scene.dirty_region_count == 0 {
397                DebugTone::Success
398            } else {
399                DebugTone::Warning
400            }),
401        DebugMetric::new("Commands", scene.command_count.to_string())
402            .detail("Scene commands emitted by the runtime")
403            .tone(DebugTone::Neutral),
404        DebugMetric::new("Layer updates", scene.layer_update_count.to_string())
405            .detail("Per-layer update records for this frame")
406            .tone(if scene.layer_update_count == 0 {
407                DebugTone::Success
408            } else {
409                DebugTone::Info
410            }),
411        DebugMetric::new("Stack surfaces", scene.stack_surface_count.to_string())
412            .detail(format!(
413                "{} hosts, {} transient surfaces",
414                scene.stack_host_count, scene.transient_surface_count
415            ))
416            .tone(if scene.stack_surface_count == 0 {
417                DebugTone::Neutral
418            } else {
419                DebugTone::Info
420            }),
421    ]);
422
423    let dirty_region_entries = if !scene.detail_collected {
424        vec![DebugKeyValue::new(
425            "Region state",
426            "Detailed dirty-region rectangles were not collected for this frame",
427        )]
428    } else if scene.dirty_regions.is_empty() {
429        vec![DebugKeyValue::new(
430            "Region state",
431            "No dirty regions in the captured frame",
432        )]
433    } else {
434        scene
435            .dirty_regions
436            .iter()
437            .enumerate()
438            .map(|(index, region)| {
439                DebugKeyValue::new(
440                    format!("Region {}", index + 1),
441                    format!("{:?} {}", region.kind, format_rect(region.area)),
442                )
443            })
444            .collect()
445    };
446
447    let rows = scene
448        .command_breakdown
449        .iter()
450        .map(|(kind, count)| TableRow::new([kind.clone(), count.to_string()]))
451        .collect::<Vec<_>>();
452    let rows = if rows.is_empty() && !scene.detail_collected {
453        vec![TableRow::new([
454            "detail disabled".to_string(),
455            "n/a".to_string(),
456        ])]
457    } else {
458        rows
459    };
460
461    let layer_update_rows = scene
462        .layer_update_breakdown
463        .iter()
464        .map(|(kind, count)| TableRow::new([kind.clone(), count.to_string()]))
465        .collect::<Vec<_>>();
466    let layer_update_rows = if layer_update_rows.is_empty() && !scene.detail_collected {
467        vec![TableRow::new([
468            "detail disabled".to_string(),
469            "n/a".to_string(),
470        ])]
471    } else if layer_update_rows.is_empty() {
472        vec![TableRow::new(["none".to_string(), "0".to_string()])]
473    } else {
474        layer_update_rows
475    };
476
477    Stack::vertical()
478        .gap(10.0)
479        .alignment(Alignment::Stretch)
480        .with_child(metrics)
481        .with_child(debug_key_values(dirty_region_entries))
482        .with_child(
483            SizedBox::new().height(140.0).child(
484                Table::new("Scene layer update breakdown")
485                    .columns([
486                        TableColumn::new("Update kind").min_width(180.0),
487                        TableColumn::new("Count").width(90.0),
488                    ])
489                    .rows(layer_update_rows),
490            ),
491        )
492        .with_child(
493            SizedBox::new().height(172.0).child(
494                Table::new("Scene command breakdown")
495                    .columns([
496                        TableColumn::new("Command").min_width(180.0),
497                        TableColumn::new("Count").width(90.0),
498                    ])
499                    .rows(rows),
500            ),
501        )
502}
503
504pub fn window_snapshot_view(snapshot: WindowDebugSnapshot) -> impl Widget {
505    let WindowDebugSnapshot {
506        title,
507        window_id,
508        focus_state,
509        schedule,
510        accessibility,
511        widget_graph,
512        scene_summary,
513    } = snapshot;
514
515    let root_name = accessibility
516        .root
517        .map(|id| format!("#{}", id.get()))
518        .unwrap_or_else(|| "none".to_string());
519    let focused_name = focus_state
520        .focused_widget
521        .map(|id| format!("#{}", id.get()))
522        .unwrap_or_else(|| "none".to_string());
523
524    let summary = debug_panel(
525        "Runtime summary",
526        "High-level counts and identifiers for the captured SUI window state.",
527        debug_metric_grid([
528            DebugMetric::new("Window", title)
529                .detail(format!("window id #{}", window_id.get()))
530                .tone(DebugTone::Info),
531            DebugMetric::new("Focused widget", focused_name)
532                .detail(format!(
533                    "window focused={}",
534                    yes_no(focus_state.window_focused)
535                ))
536                .tone(if focus_state.focused_widget.is_some() {
537                    DebugTone::Warning
538                } else {
539                    DebugTone::Neutral
540                }),
541            DebugMetric::new("Semantics nodes", accessibility.nodes.len().to_string())
542                .detail(format!("root={root_name}"))
543                .tone(DebugTone::Neutral),
544            DebugMetric::new("Widget nodes", widget_graph.nodes.len().to_string())
545                .detail(format!("graph root #{}", widget_graph.root.get()))
546                .tone(DebugTone::Neutral),
547            DebugMetric::new("Stack hosts", widget_graph.stack_hosts.len().to_string())
548                .detail("Host-local surface ordering groups")
549                .tone(DebugTone::Info),
550            DebugMetric::new(
551                "Scene frame",
552                if scene_summary.is_some() {
553                    "available"
554                } else {
555                    "missing"
556                },
557            )
558            .detail("Present when a captured render summary exists")
559            .tone(if scene_summary.is_some() {
560                DebugTone::Success
561            } else {
562                DebugTone::Danger
563            }),
564        ]),
565    );
566
567    let mut body = Stack::vertical().gap(12.0).alignment(Alignment::Stretch);
568    body.push(summary);
569    body.push(debug_panel(
570        "Focus and scheduling",
571        "The runtime focus state is often the fastest way to explain why keyboard input is landing in the wrong place.",
572        debug_key_values([
573            DebugKeyValue::new("Focused widget", format_optional_widget_id(focus_state.focused_widget)),
574            DebugKeyValue::new("Window focused", yes_no(focus_state.window_focused)),
575            DebugKeyValue::new(
576                "Pending invalidation kinds",
577                schedule
578                    .map(format_schedule)
579                    .unwrap_or_else(|| "not captured".to_string()),
580            ),
581        ]),
582    ));
583    body.push(debug_panel(
584        "Accessibility snapshot",
585        "Accessible names, roles, and state are shared infrastructure for accessibility, testing, and automation.",
586        accessibility_snapshot_view(accessibility),
587    ));
588    body.push(debug_panel(
589        "Stack hosts",
590        "Host-local ordering metadata makes floating and popup behavior inspectable without guessing from overlay layers.",
591        stack_host_snapshot_view(widget_graph.clone()),
592    ));
593    body.push(debug_panel(
594        "Widget graph",
595        "Tree inspection should expose retained widget identity and bounds without leaking runtime internals.",
596        widget_graph_snapshot_view(widget_graph),
597    ));
598
599    if let Some(scene_summary) = scene_summary {
600        body.push(debug_panel(
601            "Scene summary",
602            "Renderer-neutral scene data makes frame generation debuggable before it reaches the backend.",
603            scene_summary_view(scene_summary),
604        ));
605    }
606
607    ScrollView::vertical(body)
608}
609
610/// Render the unified runtime inspector snapshot as a standalone scrollable
611/// view. Use [`live_inspector_view`] when snapshots will be refreshed in place.
612pub fn inspector_snapshot_view(snapshot: WindowInspectorSnapshot) -> impl Widget {
613    ScrollView::vertical(inspector_snapshot_body(snapshot))
614}
615
616fn inspector_snapshot_body(snapshot: WindowInspectorSnapshot) -> Stack {
617    let accessibility = AccessibilitySnapshot::new(snapshot.window_id, snapshot.semantics.clone());
618    let accessibility_issues = validate_accessibility_snapshot(&accessibility);
619    let accessibility_errors = accessibility_issues
620        .iter()
621        .filter(|issue| issue.severity == AccessibilityIssueSeverity::Error)
622        .count();
623    let scheduler = snapshot.scheduler.clone();
624    let history = snapshot.history.clone();
625
626    let mut body = Stack::vertical().gap(12.0).alignment(Alignment::Stretch);
627    body.push(debug_panel(
628        "Application inspector",
629        "A renderer-neutral snapshot of retained UI structure, routing, scheduling, accessibility, and damage.",
630        debug_metric_grid([
631            DebugMetric::new("Window", snapshot.title.clone())
632                .detail(format!("window #{}", snapshot.window_id.get()))
633                .tone(DebugTone::Info),
634            DebugMetric::new("Widgets", snapshot.widget_graph.nodes.len().to_string())
635                .detail(format!("root #{}", snapshot.widget_graph.root.get())),
636            DebugMetric::new("Semantics", accessibility.nodes.len().to_string())
637                .detail(format!("{} accessibility issues", accessibility_issues.len()))
638                .tone(if accessibility_errors == 0 {
639                    DebugTone::Success
640                } else {
641                    DebugTone::Danger
642                }),
643            DebugMetric::new("Event routes", history.event_routes.len().to_string())
644                .detail(if snapshot.tracing_enabled {
645                    "Bounded history; payloads are not retained"
646                } else {
647                    "Tracing disabled; structural snapshot only"
648                })
649                .tone(if snapshot.tracing_enabled {
650                    DebugTone::Info
651                } else {
652                    DebugTone::Neutral
653                }),
654            DebugMetric::new("Timers", scheduler.timers.len().to_string())
655                .detail(format!("{} async registrations", scheduler.async_tasks.len())),
656            DebugMetric::new(
657                "Animations",
658                (scheduler.requested_animation_frames.len()
659                    + scheduler.delivering_animation_frames.len())
660                    .to_string(),
661            )
662            .detail("Requested and currently delivering animation frames"),
663            DebugMetric::new(
664                "Invalidations",
665                history.invalidations.len().to_string(),
666            )
667            .detail(format!(
668                "{} reactive, {} rebuilds",
669                history.reactive_invalidations.len(),
670                history.widget_rebuilds.len()
671            ))
672            .tone(if history.invalidations.is_empty() {
673                DebugTone::Success
674            } else {
675                DebugTone::Warning
676            }),
677            DebugMetric::new(
678                "Paint damage",
679                snapshot
680                    .scene
681                    .as_ref()
682                    .map_or(0, |scene| scene.dirty_region_count)
683                    .to_string(),
684            )
685            .detail(snapshot.scene.as_ref().map_or_else(
686                || "No rendered frame captured".to_string(),
687                |scene| format!("{:.1}% dirty coverage", scene.dirty_coverage),
688            )),
689        ]),
690    ));
691
692    body.push(debug_panel(
693        "Focus and scheduling",
694        "Focus identity and pending work are captured independently of the paint tree.",
695        debug_key_values([
696            DebugKeyValue::new(
697                "Focused widget",
698                format_optional_widget_id(snapshot.focus_state.focused_widget),
699            ),
700            DebugKeyValue::new(
701                "Window focused",
702                yes_no(snapshot.focus_state.window_focused),
703            ),
704            DebugKeyValue::new("Pending frame work", format_schedule(snapshot.schedule)),
705            DebugKeyValue::new(
706                "Animation clock",
707                scheduler
708                    .last_animation_frame_time
709                    .map_or_else(|| "idle".to_string(), |time| format!("{time:.4}s")),
710            ),
711        ]),
712    ));
713
714    body.push(debug_panel(
715        "Timers, animations, and async tasks",
716        "Runtime registrations remain visible even when they have not invalidated the current frame.",
717        debug_key_values(scheduler_entries(&scheduler)),
718    ));
719    body.push(debug_panel(
720        "Event routes",
721        "Capture, target, and bubble handlers are retained without event payloads or typed text.",
722        debug_key_values(event_route_entries(&history.event_routes)),
723    ));
724    body.push(debug_panel(
725        "Invalidations and rebuilds",
726        "Bounded history connects observable changes and application commands to frame work and structural replacement.",
727        debug_key_values(invalidation_entries(&history)),
728    ));
729    body.push(debug_panel(
730        "Widget diagnostics",
731        "Widgets may publish operational counters on demand; normal frames do not call this hook.",
732        debug_key_values(widget_diagnostic_entries(&snapshot.widget_diagnostics)),
733    ));
734    body.push(debug_panel(
735        "Accessibility warnings",
736        "The same semantic validation used by the terminal and test tooling is applied to this snapshot.",
737        debug_key_values(accessibility_issue_entries(&accessibility_issues)),
738    ));
739    body.push(debug_panel(
740        "Accessibility tree",
741        "Names, roles, values, relationships, focus, and bounds exposed to assistive technology.",
742        accessibility_snapshot_view(accessibility),
743    ));
744    body.push(debug_panel(
745        "Overlays",
746        "Logical overlay ownership and ordering remain separate from ordinary paint ancestry.",
747        debug_key_values(overlay_entries(&snapshot.overlays)),
748    ));
749    body.push(debug_panel(
750        "Widget tree",
751        "Lifetime-stable widget IDs, concrete type names, layout, input, and paint bounds.",
752        widget_graph_snapshot_view(snapshot.widget_graph),
753    ));
754    if let Some(scene) = snapshot.scene {
755        body.push(debug_panel(
756            "Scene and paint damage",
757            "Renderer-neutral dirty regions, commands, and layer updates for the last captured frame.",
758            scene_summary_view(SceneDebugSummary::from(&scene)),
759        ));
760    }
761    body
762}
763
764fn scheduler_entries(snapshot: &sui_runtime::SchedulerInspectorSnapshot) -> Vec<DebugKeyValue> {
765    let mut entries = snapshot
766        .timers
767        .iter()
768        .map(|timer| {
769            DebugKeyValue::new(
770                format!("Timer #{}", timer.token.get()),
771                format!(
772                    "target #{} deadline {:.4}s{}",
773                    timer.target.get(),
774                    timer.deadline,
775                    if timer.delivering { " delivering" } else { "" }
776                ),
777            )
778        })
779        .collect::<Vec<_>>();
780    entries.extend(snapshot.async_tasks.iter().map(|task| {
781        DebugKeyValue::new(
782            format!("Async #{}", task.token.get()),
783            format!(
784                "target #{}{}",
785                task.target.get(),
786                if task.pending_wake {
787                    " pending wake"
788                } else {
789                    ""
790                }
791            ),
792        )
793    }));
794    entries.extend(
795        snapshot
796            .requested_animation_frames
797            .iter()
798            .map(|id| DebugKeyValue::new("Animation requested", format!("widget #{}", id.get()))),
799    );
800    entries.extend(
801        snapshot
802            .delivering_animation_frames
803            .iter()
804            .map(|id| DebugKeyValue::new("Animation delivering", format!("widget #{}", id.get()))),
805    );
806    if entries.is_empty() {
807        entries.push(DebugKeyValue::new("Scheduler", "No active registrations"));
808    }
809    entries
810}
811
812fn event_route_entries(routes: &[sui_runtime::EventRouteTraceSample]) -> Vec<DebugKeyValue> {
813    if routes.is_empty() {
814        return vec![DebugKeyValue::new(
815            "Routes",
816            "No routes captured; enable runtime inspector tracing",
817        )];
818    }
819    routes
820        .iter()
821        .rev()
822        .take(48)
823        .map(|route| {
824            let steps = route
825                .steps
826                .iter()
827                .map(|step| {
828                    let phase = match step.phase {
829                        EventRoutePhase::Capture => "C",
830                        EventRoutePhase::Target => "T",
831                        EventRoutePhase::Bubble => "B",
832                    };
833                    format!(
834                        "{phase}#{}{}",
835                        step.widget_id.get(),
836                        if step.handled { "!" } else { "" }
837                    )
838                })
839                .collect::<Vec<_>>()
840                .join(" -> ");
841            DebugKeyValue::new(
842                format!("{} {}", route.sequence, route.event_kind),
843                format!("target #{} | {steps}", route.target.get()),
844            )
845        })
846        .collect()
847}
848
849fn invalidation_entries(history: &sui_runtime::InspectorHistorySnapshot) -> Vec<DebugKeyValue> {
850    let mut entries = history
851        .widget_rebuilds
852        .iter()
853        .rev()
854        .take(20)
855        .map(|sample| {
856            DebugKeyValue::new(
857                format!("Rebuild #{}", sample.widget_id.get()),
858                format!("{}: {}", short_type_name(sample.widget_name), sample.reason),
859            )
860        })
861        .collect::<Vec<_>>();
862    entries.extend(history.invalidations.iter().rev().take(40).map(|sample| {
863        DebugKeyValue::new(
864            format!("{:?} {:?}", sample.kind, sample.target),
865            sample.reason.as_ref().map_or_else(
866                || sample.source.clone(),
867                |reason| format!("{}: {reason}", sample.source),
868            ),
869        )
870    }));
871    entries.extend(
872        history
873            .command_dispatches
874            .iter()
875            .rev()
876            .take(20)
877            .map(|sample| {
878                DebugKeyValue::new(
879                    format!("Command {}", sample.name),
880                    format!(
881                        "{:?} {:?}; handlers={:?}",
882                        sample.delivery, sample.target, sample.handlers
883                    ),
884                )
885            }),
886    );
887    if entries.is_empty() {
888        entries.push(DebugKeyValue::new(
889            "History",
890            "No invalidations or rebuilds captured",
891        ));
892    }
893    entries
894}
895
896fn widget_diagnostic_entries(snapshots: &[WidgetDiagnosticsSnapshot]) -> Vec<DebugKeyValue> {
897    let entries = snapshots
898        .iter()
899        .flat_map(|snapshot| {
900            snapshot.entries.iter().map(move |entry| {
901                DebugKeyValue::new(
902                    format!(
903                        "{} #{} / {}",
904                        short_type_name(snapshot.widget_name),
905                        snapshot.widget_id.get(),
906                        entry.name
907                    ),
908                    entry.value.clone(),
909                )
910            })
911        })
912        .collect::<Vec<_>>();
913    if entries.is_empty() {
914        vec![DebugKeyValue::new(
915            "Widgets",
916            "No widgets published custom diagnostics",
917        )]
918    } else {
919        entries
920    }
921}
922
923fn accessibility_issue_entries(issues: &[AccessibilityIssue]) -> Vec<DebugKeyValue> {
924    if issues.is_empty() {
925        return vec![DebugKeyValue::new("Validation", "No warnings")];
926    }
927    issues
928        .iter()
929        .map(|issue| {
930            DebugKeyValue::new(
931                format!("{:?} {:?}", issue.severity, issue.target),
932                issue.message.clone(),
933            )
934        })
935        .collect()
936}
937
938fn overlay_entries(snapshot: &sui_runtime::OverlayManagerSnapshot) -> Vec<DebugKeyValue> {
939    if snapshot.overlays.is_empty() {
940        return vec![DebugKeyValue::new("Overlays", "No active overlays")];
941    }
942    snapshot
943        .overlays
944        .iter()
945        .map(|overlay| {
946            DebugKeyValue::new(
947                format!("{:?} #{}", overlay.options.kind, overlay.owner.get()),
948                format!(
949                    "order={} parent={} surfaces={:?}",
950                    overlay.order,
951                    format_optional_widget_id(overlay.parent),
952                    overlay
953                        .surfaces
954                        .iter()
955                        .map(|id| id.get())
956                        .collect::<Vec<_>>()
957                ),
958            )
959        })
960        .collect()
961}
962
963fn short_type_name(name: &'static str) -> &'static str {
964    name.rsplit("::").next().unwrap_or(name)
965}
966
967fn metric_card(metric: DebugMetric) -> impl Widget {
968    let (background, label_color, value_color) = tone_palette(metric.tone);
969    let mut column = Stack::vertical().gap(6.0).alignment(Alignment::Stretch);
970    column.push(
971        Label::new(metric.label)
972            .font_size(11.0)
973            .line_height(15.0)
974            .color(label_color),
975    );
976    column.push(
977        Label::new(metric.value)
978            .font_size(19.0)
979            .line_height(23.0)
980            .color(value_color),
981    );
982    if let Some(detail) = metric.detail {
983        column.push(
984            Label::new(detail)
985                .font_size(11.0)
986                .line_height(15.0)
987                .color(Color::rgba(0.40, 0.47, 0.56, 1.0)),
988        );
989    }
990
991    Background::new(background, Padding::all(10.0, column))
992}
993
994fn tone_palette(tone: DebugTone) -> (Color, Color, Color) {
995    match tone {
996        DebugTone::Neutral => (
997            Color::rgba(0.958, 0.968, 0.983, 1.0),
998            Color::rgba(0.35, 0.43, 0.52, 1.0),
999            Color::rgba(0.10, 0.15, 0.21, 1.0),
1000        ),
1001        DebugTone::Info => (
1002            Color::rgba(0.928, 0.962, 0.993, 1.0),
1003            Color::rgba(0.16, 0.42, 0.67, 1.0),
1004            Color::rgba(0.09, 0.27, 0.42, 1.0),
1005        ),
1006        DebugTone::Success => (
1007            Color::rgba(0.938, 0.978, 0.950, 1.0),
1008            Color::rgba(0.14, 0.44, 0.24, 1.0),
1009            Color::rgba(0.10, 0.30, 0.17, 1.0),
1010        ),
1011        DebugTone::Warning => (
1012            Color::rgba(0.995, 0.964, 0.910, 1.0),
1013            Color::rgba(0.67, 0.39, 0.06, 1.0),
1014            Color::rgba(0.48, 0.29, 0.05, 1.0),
1015        ),
1016        DebugTone::Danger => (
1017            Color::rgba(0.994, 0.938, 0.934, 1.0),
1018            Color::rgba(0.69, 0.20, 0.19, 1.0),
1019            Color::rgba(0.48, 0.16, 0.15, 1.0),
1020        ),
1021    }
1022}
1023
1024fn build_graph_tree_items(graph: &WidgetGraphSnapshot) -> Vec<TreeItem> {
1025    let nodes = graph
1026        .nodes
1027        .iter()
1028        .map(|node| (node.id, node))
1029        .collect::<HashMap<_, _>>();
1030
1031    nodes
1032        .get(&graph.root)
1033        .map(|root| vec![graph_tree_item(root, &nodes)])
1034        .unwrap_or_default()
1035}
1036
1037fn graph_tree_item(
1038    node: &WidgetNodeSnapshot,
1039    nodes: &HashMap<WidgetId, &WidgetNodeSnapshot>,
1040) -> TreeItem {
1041    let mut detail = format!(
1042        "layout={} input={} paint={} host=#{} surface=#{} owner={} order={} host_node={} surface_node={} policy={:?} focusable={} focused={}",
1043        format_rect(node.geometry.layout_bounds),
1044        format_rect(node.geometry.input_bounds),
1045        format_rect(node.geometry.paint_bounds),
1046        node.stack_host.get(),
1047        node.stack_surface.get(),
1048        format_optional_widget_id(node.transient_owner_surface),
1049        node.stack_surface_order,
1050        yes_no(node.is_stack_host),
1051        yes_no(node.is_stack_surface),
1052        node.stack_order_policy,
1053        yes_no(node.accepts_focus),
1054        yes_no(node.focused),
1055    );
1056
1057    if let Some(parent) = node.parent {
1058        detail.push_str(&format!(" parent=#{}", parent.get()));
1059    }
1060
1061    let mut item = TreeItem::new(format!(
1062        "{} #{}",
1063        short_type_name(node.widget_name),
1064        node.id.get()
1065    ))
1066    .detail(detail);
1067    if !node.children.is_empty() {
1068        item = item.expanded(true);
1069        for child in &node.children {
1070            if let Some(child_node) = nodes.get(child) {
1071                item = item.item(graph_tree_item(child_node, nodes));
1072            }
1073        }
1074    }
1075
1076    item
1077}
1078
1079fn format_optional_widget_id(widget_id: Option<WidgetId>) -> String {
1080    widget_id
1081        .map(|id| format!("#{}", id.get()))
1082        .unwrap_or_else(|| "none".to_string())
1083}
1084
1085fn format_schedule(schedule: FrameSchedule) -> String {
1086    let mut pending = Vec::new();
1087    if schedule.measure {
1088        pending.push("measure");
1089    }
1090    if schedule.arrange {
1091        pending.push("arrange");
1092    }
1093    if schedule.paint {
1094        pending.push("paint");
1095    }
1096    if schedule.semantics {
1097        pending.push("semantics");
1098    }
1099    if schedule.hit_test {
1100        pending.push("hit-test");
1101    }
1102    if schedule.text {
1103        pending.push("text");
1104    }
1105    if schedule.resources {
1106        pending.push("resources");
1107    }
1108
1109    if pending.is_empty() {
1110        "idle".to_string()
1111    } else {
1112        pending.join(", ")
1113    }
1114}
1115
1116fn format_semantics_value(value: &SemanticsValue) -> String {
1117    match value {
1118        SemanticsValue::Text(text) => text.clone(),
1119        SemanticsValue::Number(value) => format!("{value:.2}"),
1120        SemanticsValue::Range { value, min, max } => format!("{value:.2} [{min:.2}..{max:.2}]"),
1121    }
1122}
1123
1124fn format_rect(rect: Rect) -> String {
1125    format!(
1126        "({:.0}, {:.0}, {:.0}, {:.0})",
1127        rect.x(),
1128        rect.y(),
1129        rect.width(),
1130        rect.height(),
1131    )
1132}
1133
1134fn format_size(size: Size) -> String {
1135    format!("{:.0} x {:.0}", size.width, size.height)
1136}
1137
1138fn yes_no(value: bool) -> &'static str {
1139    if value { "yes" } else { "no" }
1140}
1141
1142#[cfg(test)]
1143#[allow(clippy::items_after_test_module)]
1144mod tests {
1145    use super::SceneDebugSummary;
1146    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, WindowId};
1147    use sui_scene::{SceneCommand, SceneFrame};
1148
1149    #[test]
1150    fn scene_summary_counts_commands_and_dirty_regions() {
1151        let mut frame = SceneFrame::new(WindowId::new(7), sui_core::Size::new(640.0, 360.0));
1152        frame.dirty_regions.push(DirtyRegion::new(
1153            Rect::new(12.0, 24.0, 100.0, 80.0),
1154            InvalidationKind::Paint,
1155        ));
1156        frame
1157            .scene
1158            .push(SceneCommand::Clear(Color::rgba(1.0, 1.0, 1.0, 1.0)));
1159        frame
1160            .scene
1161            .push(SceneCommand::Clear(Color::rgba(0.0, 0.0, 0.0, 1.0)));
1162        frame.scene.push(SceneCommand::Label {
1163            rect: Rect::new(0.0, 0.0, 120.0, 24.0),
1164            text: "stats".to_string(),
1165            color: Color::rgba(0.1, 0.1, 0.1, 1.0),
1166        });
1167
1168        let summary = SceneDebugSummary::from(&frame);
1169
1170        assert_eq!(summary.viewport, sui_core::Size::new(640.0, 360.0));
1171        assert_eq!(summary.command_count, 3);
1172        assert_eq!(summary.dirty_regions.len(), 1);
1173        assert!(
1174            summary
1175                .command_breakdown
1176                .contains(&("Clear".to_string(), 2))
1177        );
1178        assert!(
1179            summary
1180                .command_breakdown
1181                .contains(&("Label".to_string(), 1))
1182        );
1183    }
1184}
1185
1186pub fn performance_snapshot_view(snapshot: WindowPerformanceSnapshot) -> impl Widget {
1187    if !snapshot.scene.detail_mode.is_detailed() {
1188        let fps = snapshot
1189            .frame_interval_ms
1190            .filter(|interval| interval.is_finite() && *interval > 0.0)
1191            .map(|interval| format!("{:.0} fps", 1000.0 / interval))
1192            .unwrap_or_else(|| "-- fps".to_string());
1193
1194        return Stack::vertical()
1195            .gap(10.0)
1196            .alignment(Alignment::Stretch)
1197            .with_child(debug_metric_grid([
1198                DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
1199                    .detail("Wall time across event handling, runtime, and renderer")
1200                    .tone(duration_tone(snapshot.total_time_ms)),
1201                DebugMetric::new("FPS", fps)
1202                    .detail("Completed host frames per second, including pacing and idle time")
1203                    .tone(DebugTone::Neutral),
1204                DebugMetric::new(
1205                    "Event -> present",
1206                    format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
1207                )
1208                .detail("Time from the latest non-redraw event to the end of the present call")
1209                .tone(latency_tone(
1210                    snapshot.presentation_latency.event_to_present_ms,
1211                )),
1212                DebugMetric::new(
1213                    "Redraw wait",
1214                    format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
1215                )
1216                .detail("Time spent waiting between request_redraw and RedrawRequested")
1217                .tone(latency_tone(
1218                    snapshot.presentation_latency.redraw_request_to_callback_ms,
1219                )),
1220            ]))
1221            .with_child(debug_key_values([
1222                DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
1223                DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
1224            ]));
1225    }
1226
1227    let slowest_phase = snapshot.slowest_phase();
1228    let slowest_label = slowest_phase
1229        .map(|sample| sample.phase.label())
1230        .unwrap_or("No measured work");
1231    let slowest_duration_ms = slowest_phase
1232        .map(|sample| sample.duration_ms)
1233        .unwrap_or(0.0);
1234    let renderer_submission = snapshot.renderer_submission;
1235    let renderer_work_ms: f64 = snapshot
1236        .phase_timings
1237        .iter()
1238        .filter(|sample| sample.phase == FramePhase::Renderer)
1239        .map(|sample| sample.duration_ms)
1240        .sum();
1241    let surface_wait_ms: f64 = snapshot
1242        .phase_timings
1243        .iter()
1244        .filter(|sample| sample.phase == FramePhase::SurfaceWait)
1245        .map(|sample| sample.duration_ms)
1246        .sum();
1247
1248    let metrics = debug_metric_grid([
1249        DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
1250            .detail("Wall time across event handling, runtime, and renderer")
1251            .tone(duration_tone(snapshot.total_time_ms)),
1252        DebugMetric::new(
1253            "Event -> render",
1254            format_latency_ms(snapshot.presentation_latency.event_to_render_start_ms),
1255        )
1256        .detail("Time from the latest non-redraw event to the start of runtime render work")
1257        .tone(latency_tone(
1258            snapshot.presentation_latency.event_to_render_start_ms,
1259        )),
1260        DebugMetric::new(
1261            "Event -> present",
1262            format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
1263        )
1264        .detail("Time from the latest non-redraw event to the end of the present call")
1265        .tone(latency_tone(
1266            snapshot.presentation_latency.event_to_present_ms,
1267        )),
1268        DebugMetric::new(
1269            "Redraw wait",
1270            format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
1271        )
1272        .detail("Time spent waiting between request_redraw and RedrawRequested")
1273        .tone(latency_tone(
1274            snapshot.presentation_latency.redraw_request_to_callback_ms,
1275        )),
1276        DebugMetric::new("Slowest phase", slowest_label)
1277            .detail(format_duration_ms(slowest_duration_ms))
1278            .tone(duration_tone(slowest_duration_ms)),
1279        DebugMetric::new("Renderer work", format_duration_ms(renderer_work_ms))
1280            .detail("Renderer wall time after subtracting surface acquire and present waits")
1281            .tone(duration_tone(renderer_work_ms)),
1282        DebugMetric::new("Surface wait", format_duration_ms(surface_wait_ms))
1283            .detail(format!(
1284                "acquire {} | present {}",
1285                format_duration_ms(renderer_submission.surface_acquire_time_us as f64 / 1000.0),
1286                format_duration_ms(renderer_submission.surface_present_time_us as f64 / 1000.0),
1287            ))
1288            .tone(latency_tone(surface_wait_ms)),
1289        DebugMetric::new("Commands", snapshot.scene.command_count.to_string())
1290            .detail("Renderer-neutral draw commands in the current scene")
1291            .tone(DebugTone::Neutral),
1292        DebugMetric::new(
1293            "Dirty coverage",
1294            format!("{:.1}%", snapshot.scene.dirty_coverage),
1295        )
1296        .detail(format!(
1297            "{:.0} px^2 invalidated in this frame",
1298            snapshot.scene.dirty_area
1299        ))
1300        .tone(if snapshot.scene.dirty_regions.is_empty() {
1301            DebugTone::Success
1302        } else {
1303            DebugTone::Warning
1304        }),
1305        DebugMetric::new("Render passes", renderer_submission.pass_count.to_string())
1306            .detail("Render passes submitted for the frame")
1307            .tone(DebugTone::Neutral),
1308        DebugMetric::new("Draw calls", renderer_submission.draw_count.to_string())
1309            .detail("All GPU draw calls, including clip-mask submission")
1310            .tone(DebugTone::Neutral),
1311        DebugMetric::new(
1312            "Vertex upload",
1313            format_byte_size(renderer_submission.uploaded_vertex_bytes),
1314        )
1315        .detail(format!(
1316            "{} bytes written into scene and clip vertex buffers",
1317            renderer_submission.uploaded_vertex_bytes,
1318        ))
1319        .tone(upload_tone(renderer_submission.uploaded_vertex_bytes)),
1320        DebugMetric::new(
1321            "Visible layers",
1322            renderer_submission.visible_layer_count.to_string(),
1323        )
1324        .detail(format!(
1325            "{} retained direct packets composed across visible widget layers this frame",
1326            renderer_submission.direct_packet_count,
1327        ))
1328        .tone(DebugTone::Neutral),
1329        DebugMetric::new(
1330            "Direct packets",
1331            renderer_submission.direct_packet_count.to_string(),
1332        )
1333        .detail("Retained packet fragments submitted directly from explicit scene-layer boundaries")
1334        .tone(DebugTone::Neutral),
1335        DebugMetric::new(
1336            "State update",
1337            format_duration_ms(renderer_submission.retained_state_update_time_us as f64 / 1000.0),
1338        )
1339        .detail("Time spent reconciling retained compositor state before composition")
1340        .tone(duration_tone(
1341            renderer_submission.retained_state_update_time_us as f64 / 1000.0,
1342        )),
1343        DebugMetric::new(
1344            "Compose",
1345            format_duration_ms(renderer_submission.composition_time_us as f64 / 1000.0),
1346        )
1347        .detail("Time spent assembling the final retained composition draw list")
1348        .tone(duration_tone(
1349            renderer_submission.composition_time_us as f64 / 1000.0,
1350        )),
1351    ]);
1352
1353    let phase_rows = snapshot
1354        .phase_timings
1355        .iter()
1356        .map(|sample| {
1357            let share = if snapshot.total_time_ms > 0.0 {
1358                (sample.duration_ms / snapshot.total_time_ms) * 100.0
1359            } else {
1360                0.0
1361            };
1362
1363            TableRow::new([
1364                sample.phase.label().to_string(),
1365                format_duration_ms(sample.duration_ms),
1366                format!("{share:.1}%"),
1367            ])
1368        })
1369        .collect::<Vec<_>>();
1370    let command_trace_height =
1371        (52.0 + snapshot.command_dispatches.len().min(6) as f32 * 30.0).clamp(82.0, 232.0);
1372    let command_rows = snapshot
1373        .command_dispatches
1374        .iter()
1375        .rev()
1376        .take(64)
1377        .map(|sample| {
1378            let outcome = if !sample.delivered {
1379                "not delivered".to_string()
1380            } else if sample.handled {
1381                format!("handled by {}", sample.handlers.join(", "))
1382            } else if sample.handlers.is_empty() {
1383                "no matching handler".to_string()
1384            } else {
1385                format!("observed by {}", sample.handlers.join(", "))
1386            };
1387            TableRow::new([
1388                format!("#{} {}", sample.sequence, sample.name),
1389                format!("{:?} / {:?}", sample.target, sample.delivery),
1390                outcome,
1391            ])
1392        })
1393        .collect::<Vec<_>>();
1394    let invalidation_trace_height =
1395        (52.0 + snapshot.invalidations.len().min(6) as f32 * 30.0).clamp(82.0, 232.0);
1396    let invalidation_rows = snapshot
1397        .invalidations
1398        .iter()
1399        .rev()
1400        .take(64)
1401        .map(|sample| {
1402            TableRow::new([
1403                sample.source.clone(),
1404                format!("{:?} / {:?}", sample.target, sample.kind),
1405                sample.reason.clone().unwrap_or_else(|| {
1406                    sample
1407                        .region
1408                        .map(|region| format!("region {region:?}"))
1409                        .unwrap_or_default()
1410                }),
1411            ])
1412        })
1413        .collect::<Vec<_>>();
1414
1415    Stack::vertical()
1416        .gap(10.0)
1417        .alignment(Alignment::Stretch)
1418        .with_child(metrics)
1419        .with_child(debug_key_values([
1420            DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
1421            DebugKeyValue::new(
1422                "Dirty regions",
1423                snapshot.scene.dirty_region_count.to_string(),
1424            ),
1425            DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
1426            DebugKeyValue::new(
1427                "Text commands",
1428                snapshot.scene.text_command_count.to_string(),
1429            ),
1430            DebugKeyValue::new(
1431                "Image commands",
1432                snapshot.scene.image_command_count.to_string(),
1433            ),
1434            DebugKeyValue::new(
1435                "Clip commands",
1436                snapshot.scene.clip_command_count.to_string(),
1437            ),
1438            DebugKeyValue::new(
1439                "Transform commands",
1440                snapshot.scene.transform_command_count.to_string(),
1441            ),
1442        ]))
1443        .with_child(debug_key_values([
1444            DebugKeyValue::new(
1445                "Runtime text layout cache total",
1446                format_cache_metrics(snapshot.text_caches.runtime_layout),
1447            ),
1448            DebugKeyValue::new(
1449                "Renderer text layout cache total",
1450                format_cache_metrics(snapshot.text_caches.renderer_layout),
1451            ),
1452            DebugKeyValue::new(
1453                "Renderer glyph cache total",
1454                format_cache_metrics(snapshot.text_caches.renderer_glyph),
1455            ),
1456            DebugKeyValue::new(
1457                "Renderer path cache total",
1458                format_cache_metrics(snapshot.text_caches.renderer_path),
1459            ),
1460        ]))
1461        .with_child(debug_key_values([
1462            DebugKeyValue::new(
1463                "Runtime text layout cache frame delta",
1464                format_cache_delta_metrics(snapshot.text_cache_deltas.runtime_layout),
1465            ),
1466            DebugKeyValue::new(
1467                "Renderer text layout cache frame delta",
1468                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_layout),
1469            ),
1470            DebugKeyValue::new(
1471                "Renderer glyph cache frame delta",
1472                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_glyph),
1473            ),
1474            DebugKeyValue::new(
1475                "Renderer path cache frame delta",
1476                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_path),
1477            ),
1478        ]))
1479        .with_child(
1480            SizedBox::new().height(156.0).child(
1481                Table::new("Frame phase timings")
1482                    .columns([
1483                        TableColumn::new("Phase").min_width(180.0),
1484                        TableColumn::new("Duration").width(110.0),
1485                        TableColumn::new("Share").width(90.0),
1486                    ])
1487                    .rows(phase_rows),
1488            ),
1489        )
1490        .with_child(
1491            SizedBox::new().height(command_trace_height).child(
1492                Table::new("Command routing trace")
1493                    .columns([
1494                        TableColumn::new("Command").min_width(180.0),
1495                        TableColumn::new("Scope").min_width(180.0),
1496                        TableColumn::new("Delivery").min_width(220.0),
1497                    ])
1498                    .rows(command_rows),
1499            ),
1500        )
1501        .with_child(
1502            SizedBox::new().height(invalidation_trace_height).child(
1503                Table::new("Invalidation trace")
1504                    .columns([
1505                        TableColumn::new("Source").min_width(180.0),
1506                        TableColumn::new("Target / kind").min_width(210.0),
1507                        TableColumn::new("Reason").min_width(220.0),
1508                    ])
1509                    .rows(invalidation_rows),
1510            ),
1511        )
1512        .with_child(scene_summary_view(SceneDebugSummary::from(&snapshot.scene)))
1513}
1514
1515fn duration_tone(duration_ms: f64) -> DebugTone {
1516    if duration_ms >= 33.0 {
1517        DebugTone::Danger
1518    } else if duration_ms >= 16.7 {
1519        DebugTone::Warning
1520    } else if duration_ms > 0.0 {
1521        DebugTone::Success
1522    } else {
1523        DebugTone::Neutral
1524    }
1525}
1526
1527fn latency_tone(duration_ms: f64) -> DebugTone {
1528    if duration_ms <= 0.0 {
1529        DebugTone::Neutral
1530    } else {
1531        duration_tone(duration_ms)
1532    }
1533}
1534
1535fn upload_tone(bytes: u64) -> DebugTone {
1536    if bytes >= 1_048_576 {
1537        DebugTone::Danger
1538    } else if bytes >= 262_144 {
1539        DebugTone::Warning
1540    } else if bytes > 0 {
1541        DebugTone::Info
1542    } else {
1543        DebugTone::Neutral
1544    }
1545}
1546
1547fn format_duration_ms(duration_ms: f64) -> String {
1548    format!("{duration_ms:.2} ms")
1549}
1550
1551fn format_latency_ms(duration_ms: f64) -> String {
1552    if duration_ms <= 0.0 {
1553        "n/a".to_string()
1554    } else {
1555        format_duration_ms(duration_ms)
1556    }
1557}
1558
1559fn format_byte_size(bytes: u64) -> String {
1560    const KIB: u64 = 1024;
1561    const MIB: u64 = 1024 * 1024;
1562
1563    if bytes >= MIB {
1564        format!("{:.1} MiB", bytes as f64 / MIB as f64)
1565    } else if bytes >= KIB {
1566        format!("{:.1} KiB", bytes as f64 / KIB as f64)
1567    } else {
1568        format!("{bytes} B")
1569    }
1570}
1571
1572fn format_cache_metrics(metrics: CacheMetrics) -> String {
1573    let requests = metrics.requests();
1574    if requests == 0 {
1575        format!("{} entries, no lookups yet", metrics.entries)
1576    } else {
1577        format!(
1578            "{} entries, {:.1}% hit rate ({} hits / {} lookups)",
1579            metrics.entries,
1580            metrics.hit_rate() * 100.0,
1581            metrics.hits,
1582            requests,
1583        )
1584    }
1585}
1586
1587fn format_cache_delta_metrics(delta: CacheMetricsDelta) -> String {
1588    let requests = delta.requests();
1589    let entry_delta = match delta.entries_delta.cmp(&0) {
1590        std::cmp::Ordering::Greater => format!("+{} entries", delta.entries_delta),
1591        std::cmp::Ordering::Less => format!("{} entries", delta.entries_delta),
1592        std::cmp::Ordering::Equal => "no entry change".to_string(),
1593    };
1594
1595    if requests == 0 {
1596        format!("{}, no cache lookups this frame", entry_delta)
1597    } else {
1598        format!(
1599            "{}, {:.1}% hit rate this frame ({} hits / {} lookups)",
1600            entry_delta,
1601            delta.hit_rate() * 100.0,
1602            delta.hits,
1603            requests,
1604        )
1605    }
1606}
1607
1608fn stack_host_snapshot_view(graph: WidgetGraphSnapshot) -> impl Widget {
1609    let nodes = graph
1610        .nodes
1611        .iter()
1612        .map(|node| (node.id, node))
1613        .collect::<HashMap<_, _>>();
1614
1615    let rows = graph
1616        .stack_hosts
1617        .iter()
1618        .map(|host| {
1619            let transient_count = host
1620                .surfaces
1621                .iter()
1622                .filter(|surface| {
1623                    nodes
1624                        .get(surface)
1625                        .is_some_and(|node| node.transient_owner_surface.is_some())
1626                })
1627                .count();
1628            TableRow::new([
1629                format!("#{}", host.host.get()),
1630                format!("{:?}", host.order_policy),
1631                host.surfaces.len().to_string(),
1632                transient_count.to_string(),
1633            ])
1634        })
1635        .collect::<Vec<_>>();
1636    let rows = if rows.is_empty() {
1637        vec![TableRow::new([
1638            "none".to_string(),
1639            "n/a".to_string(),
1640            "0".to_string(),
1641            "0".to_string(),
1642        ])]
1643    } else {
1644        rows
1645    };
1646
1647    SizedBox::new().height(156.0).child(
1648        Table::new("Stack hosts")
1649            .columns([
1650                TableColumn::new("Host").min_width(100.0),
1651                TableColumn::new("Policy").min_width(120.0),
1652                TableColumn::new("Surfaces").width(84.0),
1653                TableColumn::new("Transient").width(84.0),
1654            ])
1655            .rows(rows),
1656    )
1657}
1658
1659fn layer_update_kind(kind: sui_scene::SceneLayerUpdateKind) -> &'static str {
1660    match kind {
1661        sui_scene::SceneLayerUpdateKind::Ordering => "Ordering",
1662        sui_scene::SceneLayerUpdateKind::Content => "Content",
1663        sui_scene::SceneLayerUpdateKind::Transform => "Transform",
1664        sui_scene::SceneLayerUpdateKind::Clip => "Clip",
1665        sui_scene::SceneLayerUpdateKind::Effect => "Effect",
1666        sui_scene::SceneLayerUpdateKind::Visibility => "Visibility",
1667        sui_scene::SceneLayerUpdateKind::Resources => "Resources",
1668    }
1669}