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