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::{SceneCommand, 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_kind(command).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#[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
610pub 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 command_kind(command: &SceneCommand) -> &'static str {
1025 match command {
1026 SceneCommand::Clear(_) => "Clear",
1027 SceneCommand::FillRect { .. } => "FillRect",
1028 SceneCommand::StrokeRect { .. } => "StrokeRect",
1029 SceneCommand::FillPath { .. } => "FillPath",
1030 SceneCommand::StrokePath { .. } => "StrokePath",
1031 SceneCommand::DrawText(_) => "DrawText",
1032 SceneCommand::DrawShapedText(_) => "DrawShapedText",
1033 SceneCommand::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
1034 SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => "DrawImage",
1035 SceneCommand::DrawShaderRect { .. } => "DrawShaderRect",
1036 SceneCommand::PushClip { .. } => "PushClip",
1037 SceneCommand::PushClipPath { .. } => "PushClipPath",
1038 SceneCommand::PopClip => "PopClip",
1039 SceneCommand::PushTransform { .. } => "PushTransform",
1040 SceneCommand::PopTransform => "PopTransform",
1041 SceneCommand::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
1042 SceneCommand::PopTextRenderPolicy => "PopTextRenderPolicy",
1043 SceneCommand::Layer(_) => "Layer",
1044 SceneCommand::FillRoundedRect { .. } => "FillRoundedRect",
1045 SceneCommand::Label { .. } => "Label",
1046 }
1047}
1048
1049fn build_graph_tree_items(graph: &WidgetGraphSnapshot) -> Vec<TreeItem> {
1050 let nodes = graph
1051 .nodes
1052 .iter()
1053 .map(|node| (node.id, node))
1054 .collect::<HashMap<_, _>>();
1055
1056 nodes
1057 .get(&graph.root)
1058 .map(|root| vec![graph_tree_item(root, &nodes)])
1059 .unwrap_or_default()
1060}
1061
1062fn graph_tree_item(
1063 node: &WidgetNodeSnapshot,
1064 nodes: &HashMap<WidgetId, &WidgetNodeSnapshot>,
1065) -> TreeItem {
1066 let mut detail = format!(
1067 "layout={} input={} paint={} host=#{} surface=#{} owner={} order={} host_node={} surface_node={} policy={:?} focusable={} focused={}",
1068 format_rect(node.geometry.layout_bounds),
1069 format_rect(node.geometry.input_bounds),
1070 format_rect(node.geometry.paint_bounds),
1071 node.stack_host.get(),
1072 node.stack_surface.get(),
1073 format_optional_widget_id(node.transient_owner_surface),
1074 node.stack_surface_order,
1075 yes_no(node.is_stack_host),
1076 yes_no(node.is_stack_surface),
1077 node.stack_order_policy,
1078 yes_no(node.accepts_focus),
1079 yes_no(node.focused),
1080 );
1081
1082 if let Some(parent) = node.parent {
1083 detail.push_str(&format!(" parent=#{}", parent.get()));
1084 }
1085
1086 let mut item = TreeItem::new(format!(
1087 "{} #{}",
1088 short_type_name(node.widget_name),
1089 node.id.get()
1090 ))
1091 .detail(detail);
1092 if !node.children.is_empty() {
1093 item = item.expanded(true);
1094 for child in &node.children {
1095 if let Some(child_node) = nodes.get(child) {
1096 item = item.item(graph_tree_item(child_node, nodes));
1097 }
1098 }
1099 }
1100
1101 item
1102}
1103
1104fn format_optional_widget_id(widget_id: Option<WidgetId>) -> String {
1105 widget_id
1106 .map(|id| format!("#{}", id.get()))
1107 .unwrap_or_else(|| "none".to_string())
1108}
1109
1110fn format_schedule(schedule: FrameSchedule) -> String {
1111 let mut pending = Vec::new();
1112 if schedule.measure {
1113 pending.push("measure");
1114 }
1115 if schedule.arrange {
1116 pending.push("arrange");
1117 }
1118 if schedule.paint {
1119 pending.push("paint");
1120 }
1121 if schedule.semantics {
1122 pending.push("semantics");
1123 }
1124 if schedule.hit_test {
1125 pending.push("hit-test");
1126 }
1127 if schedule.text {
1128 pending.push("text");
1129 }
1130 if schedule.resources {
1131 pending.push("resources");
1132 }
1133
1134 if pending.is_empty() {
1135 "idle".to_string()
1136 } else {
1137 pending.join(", ")
1138 }
1139}
1140
1141fn format_semantics_value(value: &SemanticsValue) -> String {
1142 match value {
1143 SemanticsValue::Text(text) => text.clone(),
1144 SemanticsValue::Number(value) => format!("{value:.2}"),
1145 SemanticsValue::Range { value, min, max } => format!("{value:.2} [{min:.2}..{max:.2}]"),
1146 }
1147}
1148
1149fn format_rect(rect: Rect) -> String {
1150 format!(
1151 "({:.0}, {:.0}, {:.0}, {:.0})",
1152 rect.x(),
1153 rect.y(),
1154 rect.width(),
1155 rect.height(),
1156 )
1157}
1158
1159fn format_size(size: Size) -> String {
1160 format!("{:.0} x {:.0}", size.width, size.height)
1161}
1162
1163fn yes_no(value: bool) -> &'static str {
1164 if value { "yes" } else { "no" }
1165}
1166
1167#[cfg(test)]
1168#[allow(clippy::items_after_test_module)]
1169mod tests {
1170 use super::SceneDebugSummary;
1171 use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, WindowId};
1172 use sui_scene::{SceneCommand, SceneFrame};
1173
1174 #[test]
1175 fn scene_summary_counts_commands_and_dirty_regions() {
1176 let mut frame = SceneFrame::new(WindowId::new(7), sui_core::Size::new(640.0, 360.0));
1177 frame.dirty_regions.push(DirtyRegion::new(
1178 Rect::new(12.0, 24.0, 100.0, 80.0),
1179 InvalidationKind::Paint,
1180 ));
1181 frame
1182 .scene
1183 .push(SceneCommand::Clear(Color::rgba(1.0, 1.0, 1.0, 1.0)));
1184 frame
1185 .scene
1186 .push(SceneCommand::Clear(Color::rgba(0.0, 0.0, 0.0, 1.0)));
1187 frame.scene.push(SceneCommand::Label {
1188 rect: Rect::new(0.0, 0.0, 120.0, 24.0),
1189 text: "stats".to_string(),
1190 color: Color::rgba(0.1, 0.1, 0.1, 1.0),
1191 });
1192
1193 let summary = SceneDebugSummary::from(&frame);
1194
1195 assert_eq!(summary.viewport, sui_core::Size::new(640.0, 360.0));
1196 assert_eq!(summary.command_count, 3);
1197 assert_eq!(summary.dirty_regions.len(), 1);
1198 assert!(
1199 summary
1200 .command_breakdown
1201 .contains(&("Clear".to_string(), 2))
1202 );
1203 assert!(
1204 summary
1205 .command_breakdown
1206 .contains(&("Label".to_string(), 1))
1207 );
1208 }
1209}
1210
1211pub fn performance_snapshot_view(snapshot: WindowPerformanceSnapshot) -> impl Widget {
1212 if !snapshot.scene.detail_mode.is_detailed() {
1213 let fps = snapshot
1214 .frame_interval_ms
1215 .filter(|interval| interval.is_finite() && *interval > 0.0)
1216 .map(|interval| format!("{:.0} fps", 1000.0 / interval))
1217 .unwrap_or_else(|| "-- fps".to_string());
1218
1219 return Stack::vertical()
1220 .gap(10.0)
1221 .alignment(Alignment::Stretch)
1222 .with_child(debug_metric_grid([
1223 DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
1224 .detail("Wall time across event handling, runtime, and renderer")
1225 .tone(duration_tone(snapshot.total_time_ms)),
1226 DebugMetric::new("FPS", fps)
1227 .detail("Completed host frames per second, including pacing and idle time")
1228 .tone(DebugTone::Neutral),
1229 DebugMetric::new(
1230 "Event -> present",
1231 format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
1232 )
1233 .detail("Time from the latest non-redraw event to the end of the present call")
1234 .tone(latency_tone(
1235 snapshot.presentation_latency.event_to_present_ms,
1236 )),
1237 DebugMetric::new(
1238 "Redraw wait",
1239 format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
1240 )
1241 .detail("Time spent waiting between request_redraw and RedrawRequested")
1242 .tone(latency_tone(
1243 snapshot.presentation_latency.redraw_request_to_callback_ms,
1244 )),
1245 ]))
1246 .with_child(debug_key_values([
1247 DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
1248 DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
1249 ]));
1250 }
1251
1252 let slowest_phase = snapshot.slowest_phase();
1253 let slowest_label = slowest_phase
1254 .map(|sample| sample.phase.label())
1255 .unwrap_or("No measured work");
1256 let slowest_duration_ms = slowest_phase
1257 .map(|sample| sample.duration_ms)
1258 .unwrap_or(0.0);
1259 let renderer_submission = snapshot.renderer_submission;
1260 let renderer_work_ms: f64 = snapshot
1261 .phase_timings
1262 .iter()
1263 .filter(|sample| sample.phase == FramePhase::Renderer)
1264 .map(|sample| sample.duration_ms)
1265 .sum();
1266 let surface_wait_ms: f64 = snapshot
1267 .phase_timings
1268 .iter()
1269 .filter(|sample| sample.phase == FramePhase::SurfaceWait)
1270 .map(|sample| sample.duration_ms)
1271 .sum();
1272
1273 let metrics = debug_metric_grid([
1274 DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
1275 .detail("Wall time across event handling, runtime, and renderer")
1276 .tone(duration_tone(snapshot.total_time_ms)),
1277 DebugMetric::new(
1278 "Event -> render",
1279 format_latency_ms(snapshot.presentation_latency.event_to_render_start_ms),
1280 )
1281 .detail("Time from the latest non-redraw event to the start of runtime render work")
1282 .tone(latency_tone(
1283 snapshot.presentation_latency.event_to_render_start_ms,
1284 )),
1285 DebugMetric::new(
1286 "Event -> present",
1287 format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
1288 )
1289 .detail("Time from the latest non-redraw event to the end of the present call")
1290 .tone(latency_tone(
1291 snapshot.presentation_latency.event_to_present_ms,
1292 )),
1293 DebugMetric::new(
1294 "Redraw wait",
1295 format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
1296 )
1297 .detail("Time spent waiting between request_redraw and RedrawRequested")
1298 .tone(latency_tone(
1299 snapshot.presentation_latency.redraw_request_to_callback_ms,
1300 )),
1301 DebugMetric::new("Slowest phase", slowest_label)
1302 .detail(format_duration_ms(slowest_duration_ms))
1303 .tone(duration_tone(slowest_duration_ms)),
1304 DebugMetric::new("Renderer work", format_duration_ms(renderer_work_ms))
1305 .detail("Renderer wall time after subtracting surface acquire and present waits")
1306 .tone(duration_tone(renderer_work_ms)),
1307 DebugMetric::new("Surface wait", format_duration_ms(surface_wait_ms))
1308 .detail(format!(
1309 "acquire {} | present {}",
1310 format_duration_ms(renderer_submission.surface_acquire_time_us as f64 / 1000.0),
1311 format_duration_ms(renderer_submission.surface_present_time_us as f64 / 1000.0),
1312 ))
1313 .tone(latency_tone(surface_wait_ms)),
1314 DebugMetric::new("Commands", snapshot.scene.command_count.to_string())
1315 .detail("Renderer-neutral draw commands in the current scene")
1316 .tone(DebugTone::Neutral),
1317 DebugMetric::new(
1318 "Dirty coverage",
1319 format!("{:.1}%", snapshot.scene.dirty_coverage),
1320 )
1321 .detail(format!(
1322 "{:.0} px^2 invalidated in this frame",
1323 snapshot.scene.dirty_area
1324 ))
1325 .tone(if snapshot.scene.dirty_regions.is_empty() {
1326 DebugTone::Success
1327 } else {
1328 DebugTone::Warning
1329 }),
1330 DebugMetric::new("Render passes", renderer_submission.pass_count.to_string())
1331 .detail("Render passes submitted for the frame")
1332 .tone(DebugTone::Neutral),
1333 DebugMetric::new("Draw calls", renderer_submission.draw_count.to_string())
1334 .detail("All GPU draw calls, including clip-mask submission")
1335 .tone(DebugTone::Neutral),
1336 DebugMetric::new(
1337 "Vertex upload",
1338 format_byte_size(renderer_submission.uploaded_vertex_bytes),
1339 )
1340 .detail(format!(
1341 "{} bytes written into scene and clip vertex buffers",
1342 renderer_submission.uploaded_vertex_bytes,
1343 ))
1344 .tone(upload_tone(renderer_submission.uploaded_vertex_bytes)),
1345 DebugMetric::new(
1346 "Visible layers",
1347 renderer_submission.visible_layer_count.to_string(),
1348 )
1349 .detail(format!(
1350 "{} retained direct packets composed across visible widget layers this frame",
1351 renderer_submission.direct_packet_count,
1352 ))
1353 .tone(DebugTone::Neutral),
1354 DebugMetric::new(
1355 "Direct packets",
1356 renderer_submission.direct_packet_count.to_string(),
1357 )
1358 .detail("Retained packet fragments submitted directly from explicit scene-layer boundaries")
1359 .tone(DebugTone::Neutral),
1360 DebugMetric::new(
1361 "State update",
1362 format_duration_ms(renderer_submission.retained_state_update_time_us as f64 / 1000.0),
1363 )
1364 .detail("Time spent reconciling retained compositor state before composition")
1365 .tone(duration_tone(
1366 renderer_submission.retained_state_update_time_us as f64 / 1000.0,
1367 )),
1368 DebugMetric::new(
1369 "Compose",
1370 format_duration_ms(renderer_submission.composition_time_us as f64 / 1000.0),
1371 )
1372 .detail("Time spent assembling the final retained composition draw list")
1373 .tone(duration_tone(
1374 renderer_submission.composition_time_us as f64 / 1000.0,
1375 )),
1376 ]);
1377
1378 let phase_rows = snapshot
1379 .phase_timings
1380 .iter()
1381 .map(|sample| {
1382 let share = if snapshot.total_time_ms > 0.0 {
1383 (sample.duration_ms / snapshot.total_time_ms) * 100.0
1384 } else {
1385 0.0
1386 };
1387
1388 TableRow::new([
1389 sample.phase.label().to_string(),
1390 format_duration_ms(sample.duration_ms),
1391 format!("{share:.1}%"),
1392 ])
1393 })
1394 .collect::<Vec<_>>();
1395 let command_trace_height =
1396 (52.0 + snapshot.command_dispatches.len().min(6) as f32 * 30.0).clamp(82.0, 232.0);
1397 let command_rows = snapshot
1398 .command_dispatches
1399 .iter()
1400 .rev()
1401 .take(64)
1402 .map(|sample| {
1403 let outcome = if !sample.delivered {
1404 "not delivered".to_string()
1405 } else if sample.handled {
1406 format!("handled by {}", sample.handlers.join(", "))
1407 } else if sample.handlers.is_empty() {
1408 "no matching handler".to_string()
1409 } else {
1410 format!("observed by {}", sample.handlers.join(", "))
1411 };
1412 TableRow::new([
1413 format!("#{} {}", sample.sequence, sample.name),
1414 format!("{:?} / {:?}", sample.target, sample.delivery),
1415 outcome,
1416 ])
1417 })
1418 .collect::<Vec<_>>();
1419 let invalidation_trace_height =
1420 (52.0 + snapshot.invalidations.len().min(6) as f32 * 30.0).clamp(82.0, 232.0);
1421 let invalidation_rows = snapshot
1422 .invalidations
1423 .iter()
1424 .rev()
1425 .take(64)
1426 .map(|sample| {
1427 TableRow::new([
1428 sample.source.clone(),
1429 format!("{:?} / {:?}", sample.target, sample.kind),
1430 sample.reason.clone().unwrap_or_else(|| {
1431 sample
1432 .region
1433 .map(|region| format!("region {region:?}"))
1434 .unwrap_or_default()
1435 }),
1436 ])
1437 })
1438 .collect::<Vec<_>>();
1439
1440 Stack::vertical()
1441 .gap(10.0)
1442 .alignment(Alignment::Stretch)
1443 .with_child(metrics)
1444 .with_child(debug_key_values([
1445 DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
1446 DebugKeyValue::new(
1447 "Dirty regions",
1448 snapshot.scene.dirty_region_count.to_string(),
1449 ),
1450 DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
1451 DebugKeyValue::new(
1452 "Text commands",
1453 snapshot.scene.text_command_count.to_string(),
1454 ),
1455 DebugKeyValue::new(
1456 "Image commands",
1457 snapshot.scene.image_command_count.to_string(),
1458 ),
1459 DebugKeyValue::new(
1460 "Clip commands",
1461 snapshot.scene.clip_command_count.to_string(),
1462 ),
1463 DebugKeyValue::new(
1464 "Transform commands",
1465 snapshot.scene.transform_command_count.to_string(),
1466 ),
1467 ]))
1468 .with_child(debug_key_values([
1469 DebugKeyValue::new(
1470 "Runtime text layout cache total",
1471 format_cache_metrics(snapshot.text_caches.runtime_layout),
1472 ),
1473 DebugKeyValue::new(
1474 "Renderer text layout cache total",
1475 format_cache_metrics(snapshot.text_caches.renderer_layout),
1476 ),
1477 DebugKeyValue::new(
1478 "Renderer glyph cache total",
1479 format_cache_metrics(snapshot.text_caches.renderer_glyph),
1480 ),
1481 DebugKeyValue::new(
1482 "Renderer path cache total",
1483 format_cache_metrics(snapshot.text_caches.renderer_path),
1484 ),
1485 ]))
1486 .with_child(debug_key_values([
1487 DebugKeyValue::new(
1488 "Runtime text layout cache frame delta",
1489 format_cache_delta_metrics(snapshot.text_cache_deltas.runtime_layout),
1490 ),
1491 DebugKeyValue::new(
1492 "Renderer text layout cache frame delta",
1493 format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_layout),
1494 ),
1495 DebugKeyValue::new(
1496 "Renderer glyph cache frame delta",
1497 format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_glyph),
1498 ),
1499 DebugKeyValue::new(
1500 "Renderer path cache frame delta",
1501 format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_path),
1502 ),
1503 ]))
1504 .with_child(
1505 SizedBox::new().height(156.0).child(
1506 Table::new("Frame phase timings")
1507 .columns([
1508 TableColumn::new("Phase").min_width(180.0),
1509 TableColumn::new("Duration").width(110.0),
1510 TableColumn::new("Share").width(90.0),
1511 ])
1512 .rows(phase_rows),
1513 ),
1514 )
1515 .with_child(
1516 SizedBox::new().height(command_trace_height).child(
1517 Table::new("Command routing trace")
1518 .columns([
1519 TableColumn::new("Command").min_width(180.0),
1520 TableColumn::new("Scope").min_width(180.0),
1521 TableColumn::new("Delivery").min_width(220.0),
1522 ])
1523 .rows(command_rows),
1524 ),
1525 )
1526 .with_child(
1527 SizedBox::new().height(invalidation_trace_height).child(
1528 Table::new("Invalidation trace")
1529 .columns([
1530 TableColumn::new("Source").min_width(180.0),
1531 TableColumn::new("Target / kind").min_width(210.0),
1532 TableColumn::new("Reason").min_width(220.0),
1533 ])
1534 .rows(invalidation_rows),
1535 ),
1536 )
1537 .with_child(scene_summary_view(SceneDebugSummary::from(&snapshot.scene)))
1538}
1539
1540fn duration_tone(duration_ms: f64) -> DebugTone {
1541 if duration_ms >= 33.0 {
1542 DebugTone::Danger
1543 } else if duration_ms >= 16.7 {
1544 DebugTone::Warning
1545 } else if duration_ms > 0.0 {
1546 DebugTone::Success
1547 } else {
1548 DebugTone::Neutral
1549 }
1550}
1551
1552fn latency_tone(duration_ms: f64) -> DebugTone {
1553 if duration_ms <= 0.0 {
1554 DebugTone::Neutral
1555 } else {
1556 duration_tone(duration_ms)
1557 }
1558}
1559
1560fn upload_tone(bytes: u64) -> DebugTone {
1561 if bytes >= 1_048_576 {
1562 DebugTone::Danger
1563 } else if bytes >= 262_144 {
1564 DebugTone::Warning
1565 } else if bytes > 0 {
1566 DebugTone::Info
1567 } else {
1568 DebugTone::Neutral
1569 }
1570}
1571
1572fn format_duration_ms(duration_ms: f64) -> String {
1573 format!("{duration_ms:.2} ms")
1574}
1575
1576fn format_latency_ms(duration_ms: f64) -> String {
1577 if duration_ms <= 0.0 {
1578 "n/a".to_string()
1579 } else {
1580 format_duration_ms(duration_ms)
1581 }
1582}
1583
1584fn format_byte_size(bytes: u64) -> String {
1585 const KIB: u64 = 1024;
1586 const MIB: u64 = 1024 * 1024;
1587
1588 if bytes >= MIB {
1589 format!("{:.1} MiB", bytes as f64 / MIB as f64)
1590 } else if bytes >= KIB {
1591 format!("{:.1} KiB", bytes as f64 / KIB as f64)
1592 } else {
1593 format!("{bytes} B")
1594 }
1595}
1596
1597fn format_cache_metrics(metrics: CacheMetrics) -> String {
1598 let requests = metrics.requests();
1599 if requests == 0 {
1600 format!("{} entries, no lookups yet", metrics.entries)
1601 } else {
1602 format!(
1603 "{} entries, {:.1}% hit rate ({} hits / {} lookups)",
1604 metrics.entries,
1605 metrics.hit_rate() * 100.0,
1606 metrics.hits,
1607 requests,
1608 )
1609 }
1610}
1611
1612fn format_cache_delta_metrics(delta: CacheMetricsDelta) -> String {
1613 let requests = delta.requests();
1614 let entry_delta = match delta.entries_delta.cmp(&0) {
1615 std::cmp::Ordering::Greater => format!("+{} entries", delta.entries_delta),
1616 std::cmp::Ordering::Less => format!("{} entries", delta.entries_delta),
1617 std::cmp::Ordering::Equal => "no entry change".to_string(),
1618 };
1619
1620 if requests == 0 {
1621 format!("{}, no cache lookups this frame", entry_delta)
1622 } else {
1623 format!(
1624 "{}, {:.1}% hit rate this frame ({} hits / {} lookups)",
1625 entry_delta,
1626 delta.hit_rate() * 100.0,
1627 delta.hits,
1628 requests,
1629 )
1630 }
1631}
1632
1633fn stack_host_snapshot_view(graph: WidgetGraphSnapshot) -> impl Widget {
1634 let nodes = graph
1635 .nodes
1636 .iter()
1637 .map(|node| (node.id, node))
1638 .collect::<HashMap<_, _>>();
1639
1640 let rows = graph
1641 .stack_hosts
1642 .iter()
1643 .map(|host| {
1644 let transient_count = host
1645 .surfaces
1646 .iter()
1647 .filter(|surface| {
1648 nodes
1649 .get(surface)
1650 .is_some_and(|node| node.transient_owner_surface.is_some())
1651 })
1652 .count();
1653 TableRow::new([
1654 format!("#{}", host.host.get()),
1655 format!("{:?}", host.order_policy),
1656 host.surfaces.len().to_string(),
1657 transient_count.to_string(),
1658 ])
1659 })
1660 .collect::<Vec<_>>();
1661 let rows = if rows.is_empty() {
1662 vec![TableRow::new([
1663 "none".to_string(),
1664 "n/a".to_string(),
1665 "0".to_string(),
1666 "0".to_string(),
1667 ])]
1668 } else {
1669 rows
1670 };
1671
1672 SizedBox::new().height(156.0).child(
1673 Table::new("Stack hosts")
1674 .columns([
1675 TableColumn::new("Host").min_width(100.0),
1676 TableColumn::new("Policy").min_width(120.0),
1677 TableColumn::new("Surfaces").width(84.0),
1678 TableColumn::new("Transient").width(84.0),
1679 ])
1680 .rows(rows),
1681 )
1682}
1683
1684fn layer_update_kind(kind: sui_scene::SceneLayerUpdateKind) -> &'static str {
1685 match kind {
1686 sui_scene::SceneLayerUpdateKind::Ordering => "Ordering",
1687 sui_scene::SceneLayerUpdateKind::Content => "Content",
1688 sui_scene::SceneLayerUpdateKind::Transform => "Transform",
1689 sui_scene::SceneLayerUpdateKind::Clip => "Clip",
1690 sui_scene::SceneLayerUpdateKind::Effect => "Effect",
1691 sui_scene::SceneLayerUpdateKind::Visibility => "Visibility",
1692 sui_scene::SceneLayerUpdateKind::Resources => "Resources",
1693 }
1694}