Skip to main content

sui_debug/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::collections::{HashMap, HashSet};
4
5use sui_core::{Color, DirtyRegion, Rect, SemanticsValue, Size, WidgetId, WindowId};
6use sui_layout::Alignment;
7use sui_platform::AccessibilitySnapshot;
8use sui_runtime::{
9    CacheMetrics, CacheMetricsDelta, FocusState, FramePhase, FrameSchedule, SceneStatistics,
10    Widget, WidgetGraphSnapshot, WidgetNodeSnapshot, WindowPerformanceSnapshot,
11};
12use sui_scene::{SceneCommand, SceneFrame};
13use sui_widgets::{
14    Background, Label, ListItem, ListView, Padding, ScrollView, Separator, SizedBox, Stack, Table,
15    TableColumn, TableRow, TreeItem, TreeView,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum DebugTone {
20    Neutral,
21    Info,
22    Success,
23    Warning,
24    Danger,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct DebugMetric {
29    pub label: String,
30    pub value: String,
31    pub detail: Option<String>,
32    pub tone: DebugTone,
33}
34
35impl DebugMetric {
36    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
37        Self {
38            label: label.into(),
39            value: value.into(),
40            detail: None,
41            tone: DebugTone::Neutral,
42        }
43    }
44
45    pub fn detail(mut self, detail: impl Into<String>) -> Self {
46        self.detail = Some(detail.into());
47        self
48    }
49
50    pub const fn tone(mut self, tone: DebugTone) -> Self {
51        self.tone = tone;
52        self
53    }
54}
55
56#[derive(Debug, Clone, PartialEq)]
57pub struct DebugKeyValue {
58    pub label: String,
59    pub value: String,
60}
61
62impl DebugKeyValue {
63    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
64        Self {
65            label: label.into(),
66            value: value.into(),
67        }
68    }
69}
70
71#[derive(Debug, Clone, PartialEq)]
72pub struct SceneDebugSummary {
73    pub viewport: Size,
74    pub dirty_region_count: usize,
75    pub dirty_regions: Vec<DirtyRegion>,
76    pub command_count: usize,
77    pub command_breakdown: Vec<(String, usize)>,
78    pub layer_update_count: usize,
79    pub layer_update_breakdown: Vec<(String, usize)>,
80    pub stack_host_count: usize,
81    pub stack_surface_count: usize,
82    pub transient_surface_count: usize,
83    pub detail_collected: bool,
84}
85
86impl From<&SceneFrame> for SceneDebugSummary {
87    fn from(frame: &SceneFrame) -> Self {
88        let mut command_breakdown = HashMap::<String, usize>::new();
89        let mut command_count = 0usize;
90        frame.scene.visit_commands(&mut |command| {
91            command_count += 1;
92            *command_breakdown
93                .entry(command_kind(command).to_string())
94                .or_default() += 1;
95        });
96
97        let mut command_breakdown: Vec<_> = command_breakdown.into_iter().collect();
98        command_breakdown.sort_by(|left, right| left.0.cmp(&right.0));
99
100        let mut layer_update_breakdown = HashMap::<String, usize>::new();
101        for update in &frame.layer_updates {
102            *layer_update_breakdown
103                .entry(layer_update_kind(update.kind).to_string())
104                .or_default() += 1;
105        }
106        let mut layer_update_breakdown: Vec<_> = layer_update_breakdown.into_iter().collect();
107        layer_update_breakdown.sort_by(|left, right| left.0.cmp(&right.0));
108
109        let mut stack_hosts = HashSet::new();
110        let mut stack_surface_count = 0usize;
111        let mut transient_surface_count = 0usize;
112        frame.scene.visit_layers(&mut |layer| {
113            if layer.descriptor.is_stack_surface {
114                stack_surface_count += 1;
115                stack_hosts.insert(layer.descriptor.stack_host);
116                if layer.descriptor.transient_owner_surface.is_some() {
117                    transient_surface_count += 1;
118                }
119            }
120        });
121
122        Self {
123            viewport: frame.viewport,
124            dirty_region_count: frame.dirty_regions.len(),
125            dirty_regions: frame.dirty_regions.clone(),
126            command_count,
127            command_breakdown,
128            layer_update_count: frame.layer_updates.len(),
129            layer_update_breakdown,
130            stack_host_count: stack_hosts.len(),
131            stack_surface_count,
132            transient_surface_count,
133            detail_collected: true,
134        }
135    }
136}
137
138impl From<&SceneStatistics> for SceneDebugSummary {
139    fn from(scene: &SceneStatistics) -> Self {
140        Self {
141            viewport: scene.viewport,
142            dirty_region_count: scene.dirty_region_count,
143            dirty_regions: scene.dirty_regions.clone(),
144            command_count: scene.command_count,
145            command_breakdown: scene.command_breakdown.clone(),
146            layer_update_count: scene.layer_update_count,
147            layer_update_breakdown: scene.layer_update_breakdown.clone(),
148            stack_host_count: 0,
149            stack_surface_count: 0,
150            transient_surface_count: 0,
151            detail_collected: scene.detail_mode.is_detailed(),
152        }
153    }
154}
155
156#[derive(Debug, Clone, PartialEq)]
157pub struct WindowDebugSnapshot {
158    pub title: String,
159    pub window_id: WindowId,
160    pub focus_state: FocusState,
161    pub schedule: Option<FrameSchedule>,
162    pub accessibility: AccessibilitySnapshot,
163    pub widget_graph: WidgetGraphSnapshot,
164    pub scene_summary: Option<SceneDebugSummary>,
165}
166
167impl WindowDebugSnapshot {
168    pub fn new(
169        title: impl Into<String>,
170        window_id: WindowId,
171        focus_state: FocusState,
172        accessibility: AccessibilitySnapshot,
173        widget_graph: WidgetGraphSnapshot,
174    ) -> Self {
175        Self {
176            title: title.into(),
177            window_id,
178            focus_state,
179            schedule: None,
180            accessibility,
181            widget_graph,
182            scene_summary: None,
183        }
184    }
185
186    pub const fn with_schedule(mut self, schedule: FrameSchedule) -> Self {
187        self.schedule = Some(schedule);
188        self
189    }
190
191    pub fn with_scene_summary(mut self, scene_summary: SceneDebugSummary) -> Self {
192        self.scene_summary = Some(scene_summary);
193        self
194    }
195}
196
197pub fn debug_panel<W>(title: impl Into<String>, subtitle: impl Into<String>, body: W) -> impl Widget
198where
199    W: Widget + 'static,
200{
201    let title = title.into();
202    let subtitle = subtitle.into();
203
204    Background::new(
205        Color::rgba(0.984, 0.989, 0.997, 1.0),
206        Padding::all(
207            14.0,
208            Stack::vertical()
209                .spacing(8.0)
210                .alignment(Alignment::Stretch)
211                .with_child(
212                    Label::new(title)
213                        .font_size(18.0)
214                        .line_height(22.0)
215                        .color(Color::rgba(0.10, 0.14, 0.20, 1.0)),
216                )
217                .with_child(
218                    Label::new(subtitle)
219                        .font_size(12.0)
220                        .line_height(16.0)
221                        .color(Color::rgba(0.42, 0.49, 0.58, 1.0)),
222                )
223                .with_child(Separator::horizontal())
224                .with_child(body),
225        ),
226    )
227}
228
229pub fn debug_metric_grid<I>(metrics: I) -> impl Widget
230where
231    I: IntoIterator<Item = DebugMetric>,
232{
233    let metrics: Vec<_> = metrics.into_iter().collect();
234    let mut column = Stack::vertical()
235        .spacing(10.0)
236        .alignment(Alignment::Stretch);
237
238    for chunk in metrics.chunks(4) {
239        let mut row = Stack::horizontal()
240            .spacing(10.0)
241            .alignment(Alignment::Stretch);
242        for metric in chunk {
243            row = row.with_child(
244                SizedBox::new()
245                    .width(156.0)
246                    .with_child(metric_card(metric.clone())),
247            );
248        }
249        column = column.with_child(row);
250    }
251
252    column
253}
254
255pub fn debug_key_values<I>(entries: I) -> impl Widget
256where
257    I: IntoIterator<Item = DebugKeyValue>,
258{
259    let mut column = Stack::vertical().spacing(6.0).alignment(Alignment::Stretch);
260
261    for (index, entry) in entries.into_iter().enumerate() {
262        let background = if index % 2 == 0 {
263            Color::rgba(0.971, 0.978, 0.989, 1.0)
264        } else {
265            Color::rgba(0.957, 0.968, 0.983, 1.0)
266        };
267        column = column.with_child(Background::new(
268            background,
269            Padding::all(
270                8.0,
271                Stack::horizontal()
272                    .spacing(10.0)
273                    .alignment(Alignment::Center)
274                    .with_child(
275                        SizedBox::new().width(160.0).with_child(
276                            Label::new(entry.label)
277                                .font_size(11.0)
278                                .line_height(15.0)
279                                .color(Color::rgba(0.38, 0.46, 0.55, 1.0)),
280                        ),
281                    )
282                    .with_child(
283                        Label::new(entry.value)
284                            .font_size(12.0)
285                            .line_height(16.0)
286                            .color(Color::rgba(0.12, 0.17, 0.24, 1.0)),
287                    ),
288            ),
289        ));
290    }
291
292    column
293}
294
295pub fn accessibility_snapshot_view(snapshot: AccessibilitySnapshot) -> impl Widget {
296    let items = snapshot
297        .nodes
298        .iter()
299        .map(|node| {
300            let mut detail = format!(
301                "role={:?} parent={} bounds={} focus={} hidden={}",
302                node.role,
303                format_optional_widget_id(node.parent),
304                format_rect(node.bounds),
305                yes_no(node.state.focused),
306                yes_no(node.state.hidden),
307            );
308
309            if let Some(name) = &node.name {
310                detail.push_str(&format!(" name={name}"));
311            }
312            if let Some(value) = &node.value {
313                detail.push_str(&format!(" value={}", format_semantics_value(value)));
314            }
315
316            let mut item =
317                ListItem::new(format!("#{} {:?}", node.id.get(), node.role)).detail(detail);
318            if node.state.focused {
319                item = item.accent(Color::rgba(0.88, 0.33, 0.19, 1.0));
320            } else if node.state.hidden {
321                item = item.accent(Color::rgba(0.54, 0.60, 0.68, 1.0));
322            } else {
323                item = item.accent(Color::rgba(0.16, 0.56, 0.87, 1.0));
324            }
325            item
326        })
327        .collect::<Vec<_>>();
328
329    SizedBox::new()
330        .height(220.0)
331        .with_child(ListView::new("Accessibility snapshot").items(items))
332}
333
334pub fn widget_graph_snapshot_view(graph: WidgetGraphSnapshot) -> impl Widget {
335    let items = build_graph_tree_items(&graph);
336    SizedBox::new()
337        .height(240.0)
338        .with_child(TreeView::new("Widget graph").items(items))
339}
340
341pub fn scene_summary_view(scene: SceneDebugSummary) -> impl Widget {
342    let metrics = debug_metric_grid([
343        DebugMetric::new("Viewport", format_size(scene.viewport))
344            .detail("Logical render target size")
345            .tone(DebugTone::Info),
346        DebugMetric::new("Dirty regions", scene.dirty_region_count.to_string())
347            .detail("Invalidated rectangles queued into the scene")
348            .tone(if scene.dirty_region_count == 0 {
349                DebugTone::Success
350            } else {
351                DebugTone::Warning
352            }),
353        DebugMetric::new("Commands", scene.command_count.to_string())
354            .detail("Scene commands emitted by the runtime")
355            .tone(DebugTone::Neutral),
356        DebugMetric::new("Layer updates", scene.layer_update_count.to_string())
357            .detail("Per-layer update records for this frame")
358            .tone(if scene.layer_update_count == 0 {
359                DebugTone::Success
360            } else {
361                DebugTone::Info
362            }),
363        DebugMetric::new("Stack surfaces", scene.stack_surface_count.to_string())
364            .detail(format!(
365                "{} hosts, {} transient surfaces",
366                scene.stack_host_count, scene.transient_surface_count
367            ))
368            .tone(if scene.stack_surface_count == 0 {
369                DebugTone::Neutral
370            } else {
371                DebugTone::Info
372            }),
373    ]);
374
375    let dirty_region_entries = if !scene.detail_collected {
376        vec![DebugKeyValue::new(
377            "Region state",
378            "Detailed dirty-region rectangles were not collected for this frame",
379        )]
380    } else if scene.dirty_regions.is_empty() {
381        vec![DebugKeyValue::new(
382            "Region state",
383            "No dirty regions in the captured frame",
384        )]
385    } else {
386        scene
387            .dirty_regions
388            .iter()
389            .enumerate()
390            .map(|(index, region)| {
391                DebugKeyValue::new(
392                    format!("Region {}", index + 1),
393                    format!("{:?} {}", region.kind, format_rect(region.area)),
394                )
395            })
396            .collect()
397    };
398
399    let rows = scene
400        .command_breakdown
401        .iter()
402        .map(|(kind, count)| TableRow::new([kind.clone(), count.to_string()]))
403        .collect::<Vec<_>>();
404    let rows = if rows.is_empty() && !scene.detail_collected {
405        vec![TableRow::new([
406            "detail disabled".to_string(),
407            "n/a".to_string(),
408        ])]
409    } else {
410        rows
411    };
412
413    let layer_update_rows = scene
414        .layer_update_breakdown
415        .iter()
416        .map(|(kind, count)| TableRow::new([kind.clone(), count.to_string()]))
417        .collect::<Vec<_>>();
418    let layer_update_rows = if layer_update_rows.is_empty() && !scene.detail_collected {
419        vec![TableRow::new([
420            "detail disabled".to_string(),
421            "n/a".to_string(),
422        ])]
423    } else if layer_update_rows.is_empty() {
424        vec![TableRow::new(["none".to_string(), "0".to_string()])]
425    } else {
426        layer_update_rows
427    };
428
429    Stack::vertical()
430        .spacing(10.0)
431        .alignment(Alignment::Stretch)
432        .with_child(metrics)
433        .with_child(debug_key_values(dirty_region_entries))
434        .with_child(
435            SizedBox::new().height(140.0).with_child(
436                Table::new("Scene layer update breakdown")
437                    .columns([
438                        TableColumn::new("Update kind").min_width(180.0),
439                        TableColumn::new("Count").width(90.0),
440                    ])
441                    .rows(layer_update_rows),
442            ),
443        )
444        .with_child(
445            SizedBox::new().height(172.0).with_child(
446                Table::new("Scene command breakdown")
447                    .columns([
448                        TableColumn::new("Command").min_width(180.0),
449                        TableColumn::new("Count").width(90.0),
450                    ])
451                    .rows(rows),
452            ),
453        )
454}
455
456pub fn window_snapshot_view(snapshot: WindowDebugSnapshot) -> impl Widget {
457    let WindowDebugSnapshot {
458        title,
459        window_id,
460        focus_state,
461        schedule,
462        accessibility,
463        widget_graph,
464        scene_summary,
465    } = snapshot;
466
467    let root_name = accessibility
468        .root
469        .map(|id| format!("#{}", id.get()))
470        .unwrap_or_else(|| "none".to_string());
471    let focused_name = focus_state
472        .focused_widget
473        .map(|id| format!("#{}", id.get()))
474        .unwrap_or_else(|| "none".to_string());
475
476    let summary = debug_panel(
477        "Runtime summary",
478        "High-level counts and identifiers for the captured SUI window state.",
479        debug_metric_grid([
480            DebugMetric::new("Window", title)
481                .detail(format!("window id #{}", window_id.get()))
482                .tone(DebugTone::Info),
483            DebugMetric::new("Focused widget", focused_name)
484                .detail(format!(
485                    "window focused={}",
486                    yes_no(focus_state.window_focused)
487                ))
488                .tone(if focus_state.focused_widget.is_some() {
489                    DebugTone::Warning
490                } else {
491                    DebugTone::Neutral
492                }),
493            DebugMetric::new("Semantics nodes", accessibility.nodes.len().to_string())
494                .detail(format!("root={root_name}"))
495                .tone(DebugTone::Neutral),
496            DebugMetric::new("Widget nodes", widget_graph.nodes.len().to_string())
497                .detail(format!("graph root #{}", widget_graph.root.get()))
498                .tone(DebugTone::Neutral),
499            DebugMetric::new("Stack hosts", widget_graph.stack_hosts.len().to_string())
500                .detail("Host-local surface ordering groups")
501                .tone(DebugTone::Info),
502            DebugMetric::new(
503                "Scene frame",
504                if scene_summary.is_some() {
505                    "available"
506                } else {
507                    "missing"
508                },
509            )
510            .detail("Present when a captured render summary exists")
511            .tone(if scene_summary.is_some() {
512                DebugTone::Success
513            } else {
514                DebugTone::Danger
515            }),
516        ]),
517    );
518
519    let mut body = Stack::vertical()
520        .spacing(12.0)
521        .alignment(Alignment::Stretch);
522    body.push(summary);
523    body.push(debug_panel(
524        "Focus and scheduling",
525        "The runtime focus state is often the fastest way to explain why keyboard input is landing in the wrong place.",
526        debug_key_values([
527            DebugKeyValue::new("Focused widget", format_optional_widget_id(focus_state.focused_widget)),
528            DebugKeyValue::new("Window focused", yes_no(focus_state.window_focused)),
529            DebugKeyValue::new(
530                "Pending invalidation kinds",
531                schedule
532                    .map(format_schedule)
533                    .unwrap_or_else(|| "not captured".to_string()),
534            ),
535        ]),
536    ));
537    body.push(debug_panel(
538        "Accessibility snapshot",
539        "Accessible names, roles, and state are shared infrastructure for accessibility, testing, and automation.",
540        accessibility_snapshot_view(accessibility),
541    ));
542    body.push(debug_panel(
543        "Stack hosts",
544        "Host-local ordering metadata makes floating and popup behavior inspectable without guessing from overlay layers.",
545        stack_host_snapshot_view(widget_graph.clone()),
546    ));
547    body.push(debug_panel(
548        "Widget graph",
549        "Tree inspection should expose retained widget identity and bounds without leaking runtime internals.",
550        widget_graph_snapshot_view(widget_graph),
551    ));
552
553    if let Some(scene_summary) = scene_summary {
554        body.push(debug_panel(
555            "Scene summary",
556            "Renderer-neutral scene data makes frame generation debuggable before it reaches the backend.",
557            scene_summary_view(scene_summary),
558        ));
559    }
560
561    ScrollView::vertical(body)
562}
563
564fn metric_card(metric: DebugMetric) -> impl Widget {
565    let (background, label_color, value_color) = tone_palette(metric.tone);
566    let mut column = Stack::vertical().spacing(6.0).alignment(Alignment::Stretch);
567    column.push(
568        Label::new(metric.label)
569            .font_size(11.0)
570            .line_height(15.0)
571            .color(label_color),
572    );
573    column.push(
574        Label::new(metric.value)
575            .font_size(19.0)
576            .line_height(23.0)
577            .color(value_color),
578    );
579    if let Some(detail) = metric.detail {
580        column.push(
581            Label::new(detail)
582                .font_size(11.0)
583                .line_height(15.0)
584                .color(Color::rgba(0.40, 0.47, 0.56, 1.0)),
585        );
586    }
587
588    Background::new(background, Padding::all(10.0, column))
589}
590
591fn tone_palette(tone: DebugTone) -> (Color, Color, Color) {
592    match tone {
593        DebugTone::Neutral => (
594            Color::rgba(0.958, 0.968, 0.983, 1.0),
595            Color::rgba(0.35, 0.43, 0.52, 1.0),
596            Color::rgba(0.10, 0.15, 0.21, 1.0),
597        ),
598        DebugTone::Info => (
599            Color::rgba(0.928, 0.962, 0.993, 1.0),
600            Color::rgba(0.16, 0.42, 0.67, 1.0),
601            Color::rgba(0.09, 0.27, 0.42, 1.0),
602        ),
603        DebugTone::Success => (
604            Color::rgba(0.938, 0.978, 0.950, 1.0),
605            Color::rgba(0.14, 0.44, 0.24, 1.0),
606            Color::rgba(0.10, 0.30, 0.17, 1.0),
607        ),
608        DebugTone::Warning => (
609            Color::rgba(0.995, 0.964, 0.910, 1.0),
610            Color::rgba(0.67, 0.39, 0.06, 1.0),
611            Color::rgba(0.48, 0.29, 0.05, 1.0),
612        ),
613        DebugTone::Danger => (
614            Color::rgba(0.994, 0.938, 0.934, 1.0),
615            Color::rgba(0.69, 0.20, 0.19, 1.0),
616            Color::rgba(0.48, 0.16, 0.15, 1.0),
617        ),
618    }
619}
620
621fn command_kind(command: &SceneCommand) -> &'static str {
622    match command {
623        SceneCommand::Clear(_) => "Clear",
624        SceneCommand::FillRect { .. } => "FillRect",
625        SceneCommand::StrokeRect { .. } => "StrokeRect",
626        SceneCommand::FillPath { .. } => "FillPath",
627        SceneCommand::StrokePath { .. } => "StrokePath",
628        SceneCommand::DrawText(_) => "DrawText",
629        SceneCommand::DrawShapedText(_) => "DrawShapedText",
630        SceneCommand::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
631        SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => "DrawImage",
632        SceneCommand::DrawShaderRect { .. } => "DrawShaderRect",
633        SceneCommand::PushClip { .. } => "PushClip",
634        SceneCommand::PushClipPath { .. } => "PushClipPath",
635        SceneCommand::PopClip => "PopClip",
636        SceneCommand::PushTransform { .. } => "PushTransform",
637        SceneCommand::PopTransform => "PopTransform",
638        SceneCommand::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
639        SceneCommand::PopTextRenderPolicy => "PopTextRenderPolicy",
640        SceneCommand::Layer(_) => "Layer",
641        SceneCommand::FillRoundedRect { .. } => "FillRoundedRect",
642        SceneCommand::Label { .. } => "Label",
643    }
644}
645
646fn build_graph_tree_items(graph: &WidgetGraphSnapshot) -> Vec<TreeItem> {
647    let nodes = graph
648        .nodes
649        .iter()
650        .map(|node| (node.id, node))
651        .collect::<HashMap<_, _>>();
652
653    nodes
654        .get(&graph.root)
655        .map(|root| vec![graph_tree_item(root, &nodes)])
656        .unwrap_or_default()
657}
658
659fn graph_tree_item(
660    node: &WidgetNodeSnapshot,
661    nodes: &HashMap<WidgetId, &WidgetNodeSnapshot>,
662) -> TreeItem {
663    let mut detail = format!(
664        "layout={} input={} paint={} host=#{} surface=#{} owner={} order={} host_node={} surface_node={} policy={:?} focusable={} focused={}",
665        format_rect(node.geometry.layout_bounds),
666        format_rect(node.geometry.input_bounds),
667        format_rect(node.geometry.paint_bounds),
668        node.stack_host.get(),
669        node.stack_surface.get(),
670        format_optional_widget_id(node.transient_owner_surface),
671        node.stack_surface_order,
672        yes_no(node.is_stack_host),
673        yes_no(node.is_stack_surface),
674        node.stack_order_policy,
675        yes_no(node.accepts_focus),
676        yes_no(node.focused),
677    );
678
679    if let Some(parent) = node.parent {
680        detail.push_str(&format!(" parent=#{}", parent.get()));
681    }
682
683    let mut item = TreeItem::new(format!("Widget #{}", node.id.get())).detail(detail);
684    if !node.children.is_empty() {
685        item = item.expanded(true);
686        for child in &node.children {
687            if let Some(child_node) = nodes.get(child) {
688                item = item.with_child(graph_tree_item(child_node, nodes));
689            }
690        }
691    }
692
693    item
694}
695
696fn format_optional_widget_id(widget_id: Option<WidgetId>) -> String {
697    widget_id
698        .map(|id| format!("#{}", id.get()))
699        .unwrap_or_else(|| "none".to_string())
700}
701
702fn format_schedule(schedule: FrameSchedule) -> String {
703    let mut pending = Vec::new();
704    if schedule.measure {
705        pending.push("measure");
706    }
707    if schedule.arrange {
708        pending.push("arrange");
709    }
710    if schedule.paint {
711        pending.push("paint");
712    }
713    if schedule.semantics {
714        pending.push("semantics");
715    }
716    if schedule.hit_test {
717        pending.push("hit-test");
718    }
719    if schedule.text {
720        pending.push("text");
721    }
722    if schedule.resources {
723        pending.push("resources");
724    }
725
726    if pending.is_empty() {
727        "idle".to_string()
728    } else {
729        pending.join(", ")
730    }
731}
732
733fn format_semantics_value(value: &SemanticsValue) -> String {
734    match value {
735        SemanticsValue::Text(text) => text.clone(),
736        SemanticsValue::Number(value) => format!("{value:.2}"),
737        SemanticsValue::Range { value, min, max } => format!("{value:.2} [{min:.2}..{max:.2}]"),
738    }
739}
740
741fn format_rect(rect: Rect) -> String {
742    format!(
743        "({:.0}, {:.0}, {:.0}, {:.0})",
744        rect.x(),
745        rect.y(),
746        rect.width(),
747        rect.height(),
748    )
749}
750
751fn format_size(size: Size) -> String {
752    format!("{:.0} x {:.0}", size.width, size.height)
753}
754
755fn yes_no(value: bool) -> &'static str {
756    if value { "yes" } else { "no" }
757}
758
759#[cfg(test)]
760#[allow(clippy::items_after_test_module)]
761mod tests {
762    use super::SceneDebugSummary;
763    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, WindowId};
764    use sui_scene::{SceneCommand, SceneFrame};
765
766    #[test]
767    fn scene_summary_counts_commands_and_dirty_regions() {
768        let mut frame = SceneFrame::new(WindowId::new(7), sui_core::Size::new(640.0, 360.0));
769        frame.dirty_regions.push(DirtyRegion::new(
770            Rect::new(12.0, 24.0, 100.0, 80.0),
771            InvalidationKind::Paint,
772        ));
773        frame
774            .scene
775            .push(SceneCommand::Clear(Color::rgba(1.0, 1.0, 1.0, 1.0)));
776        frame
777            .scene
778            .push(SceneCommand::Clear(Color::rgba(0.0, 0.0, 0.0, 1.0)));
779        frame.scene.push(SceneCommand::Label {
780            rect: Rect::new(0.0, 0.0, 120.0, 24.0),
781            text: "stats".to_string(),
782            color: Color::rgba(0.1, 0.1, 0.1, 1.0),
783        });
784
785        let summary = SceneDebugSummary::from(&frame);
786
787        assert_eq!(summary.viewport, sui_core::Size::new(640.0, 360.0));
788        assert_eq!(summary.command_count, 3);
789        assert_eq!(summary.dirty_regions.len(), 1);
790        assert!(
791            summary
792                .command_breakdown
793                .contains(&("Clear".to_string(), 2))
794        );
795        assert!(
796            summary
797                .command_breakdown
798                .contains(&("Label".to_string(), 1))
799        );
800    }
801}
802
803pub fn performance_snapshot_view(snapshot: WindowPerformanceSnapshot) -> impl Widget {
804    if !snapshot.scene.detail_mode.is_detailed() {
805        let fps = if snapshot.total_time_ms > 0.0 {
806            format!("{:.0} fps", 1000.0 / snapshot.total_time_ms)
807        } else {
808            "0 fps".to_string()
809        };
810
811        return Stack::vertical()
812            .spacing(10.0)
813            .alignment(Alignment::Stretch)
814            .with_child(debug_metric_grid([
815                DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
816                    .detail("Wall time across event handling, runtime, and renderer")
817                    .tone(duration_tone(snapshot.total_time_ms)),
818                DebugMetric::new("FPS", fps)
819                    .detail("Live overlay detail is off; detailed analytics are disabled")
820                    .tone(DebugTone::Neutral),
821                DebugMetric::new(
822                    "Event -> present",
823                    format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
824                )
825                .detail("Time from the latest non-redraw event to the end of the present call")
826                .tone(latency_tone(
827                    snapshot.presentation_latency.event_to_present_ms,
828                )),
829                DebugMetric::new(
830                    "Redraw wait",
831                    format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
832                )
833                .detail("Time spent waiting between request_redraw and RedrawRequested")
834                .tone(latency_tone(
835                    snapshot.presentation_latency.redraw_request_to_callback_ms,
836                )),
837            ]))
838            .with_child(debug_key_values([
839                DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
840                DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
841            ]));
842    }
843
844    let slowest_phase = snapshot.slowest_phase();
845    let slowest_label = slowest_phase
846        .map(|sample| sample.phase.label())
847        .unwrap_or("No measured work");
848    let slowest_duration_ms = slowest_phase
849        .map(|sample| sample.duration_ms)
850        .unwrap_or(0.0);
851    let renderer_submission = snapshot.renderer_submission;
852    let renderer_work_ms: f64 = snapshot
853        .phase_timings
854        .iter()
855        .filter(|sample| sample.phase == FramePhase::Renderer)
856        .map(|sample| sample.duration_ms)
857        .sum();
858    let surface_wait_ms: f64 = snapshot
859        .phase_timings
860        .iter()
861        .filter(|sample| sample.phase == FramePhase::SurfaceWait)
862        .map(|sample| sample.duration_ms)
863        .sum();
864
865    let metrics = debug_metric_grid([
866        DebugMetric::new("Frame", format_duration_ms(snapshot.total_time_ms))
867            .detail("Wall time across event handling, runtime, and renderer")
868            .tone(duration_tone(snapshot.total_time_ms)),
869        DebugMetric::new(
870            "Event -> render",
871            format_latency_ms(snapshot.presentation_latency.event_to_render_start_ms),
872        )
873        .detail("Time from the latest non-redraw event to the start of runtime render work")
874        .tone(latency_tone(
875            snapshot.presentation_latency.event_to_render_start_ms,
876        )),
877        DebugMetric::new(
878            "Event -> present",
879            format_latency_ms(snapshot.presentation_latency.event_to_present_ms),
880        )
881        .detail("Time from the latest non-redraw event to the end of the present call")
882        .tone(latency_tone(
883            snapshot.presentation_latency.event_to_present_ms,
884        )),
885        DebugMetric::new(
886            "Redraw wait",
887            format_latency_ms(snapshot.presentation_latency.redraw_request_to_callback_ms),
888        )
889        .detail("Time spent waiting between request_redraw and RedrawRequested")
890        .tone(latency_tone(
891            snapshot.presentation_latency.redraw_request_to_callback_ms,
892        )),
893        DebugMetric::new("Slowest phase", slowest_label)
894            .detail(format_duration_ms(slowest_duration_ms))
895            .tone(duration_tone(slowest_duration_ms)),
896        DebugMetric::new("Renderer work", format_duration_ms(renderer_work_ms))
897            .detail("Renderer wall time after subtracting surface acquire and present waits")
898            .tone(duration_tone(renderer_work_ms)),
899        DebugMetric::new("Surface wait", format_duration_ms(surface_wait_ms))
900            .detail(format!(
901                "acquire {} | present {}",
902                format_duration_ms(renderer_submission.surface_acquire_time_us as f64 / 1000.0),
903                format_duration_ms(renderer_submission.surface_present_time_us as f64 / 1000.0),
904            ))
905            .tone(latency_tone(surface_wait_ms)),
906        DebugMetric::new("Commands", snapshot.scene.command_count.to_string())
907            .detail("Renderer-neutral draw commands in the current scene")
908            .tone(DebugTone::Neutral),
909        DebugMetric::new(
910            "Dirty coverage",
911            format!("{:.1}%", snapshot.scene.dirty_coverage),
912        )
913        .detail(format!(
914            "{:.0} px^2 invalidated in this frame",
915            snapshot.scene.dirty_area
916        ))
917        .tone(if snapshot.scene.dirty_regions.is_empty() {
918            DebugTone::Success
919        } else {
920            DebugTone::Warning
921        }),
922        DebugMetric::new("Render passes", renderer_submission.pass_count.to_string())
923            .detail("Render passes submitted for the frame")
924            .tone(DebugTone::Neutral),
925        DebugMetric::new("Draw calls", renderer_submission.draw_count.to_string())
926            .detail("All GPU draw calls, including clip-mask submission")
927            .tone(DebugTone::Neutral),
928        DebugMetric::new(
929            "Vertex upload",
930            format_byte_size(renderer_submission.uploaded_vertex_bytes),
931        )
932        .detail(format!(
933            "{} bytes written into scene and clip vertex buffers",
934            renderer_submission.uploaded_vertex_bytes,
935        ))
936        .tone(upload_tone(renderer_submission.uploaded_vertex_bytes)),
937        DebugMetric::new(
938            "Visible layers",
939            renderer_submission.visible_layer_count.to_string(),
940        )
941        .detail(format!(
942            "{} retained direct packets composed across visible widget layers this frame",
943            renderer_submission.direct_packet_count,
944        ))
945        .tone(DebugTone::Neutral),
946        DebugMetric::new(
947            "Direct packets",
948            renderer_submission.direct_packet_count.to_string(),
949        )
950        .detail("Retained packet fragments submitted directly from explicit scene-layer boundaries")
951        .tone(DebugTone::Neutral),
952        DebugMetric::new(
953            "State update",
954            format_duration_ms(renderer_submission.retained_state_update_time_us as f64 / 1000.0),
955        )
956        .detail("Time spent reconciling retained compositor state before composition")
957        .tone(duration_tone(
958            renderer_submission.retained_state_update_time_us as f64 / 1000.0,
959        )),
960        DebugMetric::new(
961            "Compose",
962            format_duration_ms(renderer_submission.composition_time_us as f64 / 1000.0),
963        )
964        .detail("Time spent assembling the final retained composition draw list")
965        .tone(duration_tone(
966            renderer_submission.composition_time_us as f64 / 1000.0,
967        )),
968    ]);
969
970    let phase_rows = snapshot
971        .phase_timings
972        .iter()
973        .map(|sample| {
974            let share = if snapshot.total_time_ms > 0.0 {
975                (sample.duration_ms / snapshot.total_time_ms) * 100.0
976            } else {
977                0.0
978            };
979
980            TableRow::new([
981                sample.phase.label().to_string(),
982                format_duration_ms(sample.duration_ms),
983                format!("{share:.1}%"),
984            ])
985        })
986        .collect::<Vec<_>>();
987
988    Stack::vertical()
989        .spacing(10.0)
990        .alignment(Alignment::Stretch)
991        .with_child(metrics)
992        .with_child(debug_key_values([
993            DebugKeyValue::new("Frame index", snapshot.frame_index.to_string()),
994            DebugKeyValue::new(
995                "Dirty regions",
996                snapshot.scene.dirty_region_count.to_string(),
997            ),
998            DebugKeyValue::new("Scene detail", snapshot.scene.detail_mode.label()),
999            DebugKeyValue::new(
1000                "Text commands",
1001                snapshot.scene.text_command_count.to_string(),
1002            ),
1003            DebugKeyValue::new(
1004                "Image commands",
1005                snapshot.scene.image_command_count.to_string(),
1006            ),
1007            DebugKeyValue::new(
1008                "Clip commands",
1009                snapshot.scene.clip_command_count.to_string(),
1010            ),
1011            DebugKeyValue::new(
1012                "Transform commands",
1013                snapshot.scene.transform_command_count.to_string(),
1014            ),
1015        ]))
1016        .with_child(debug_key_values([
1017            DebugKeyValue::new(
1018                "Runtime text layout cache total",
1019                format_cache_metrics(snapshot.text_caches.runtime_layout),
1020            ),
1021            DebugKeyValue::new(
1022                "Renderer text layout cache total",
1023                format_cache_metrics(snapshot.text_caches.renderer_layout),
1024            ),
1025            DebugKeyValue::new(
1026                "Renderer glyph cache total",
1027                format_cache_metrics(snapshot.text_caches.renderer_glyph),
1028            ),
1029            DebugKeyValue::new(
1030                "Renderer path cache total",
1031                format_cache_metrics(snapshot.text_caches.renderer_path),
1032            ),
1033        ]))
1034        .with_child(debug_key_values([
1035            DebugKeyValue::new(
1036                "Runtime text layout cache frame delta",
1037                format_cache_delta_metrics(snapshot.text_cache_deltas.runtime_layout),
1038            ),
1039            DebugKeyValue::new(
1040                "Renderer text layout cache frame delta",
1041                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_layout),
1042            ),
1043            DebugKeyValue::new(
1044                "Renderer glyph cache frame delta",
1045                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_glyph),
1046            ),
1047            DebugKeyValue::new(
1048                "Renderer path cache frame delta",
1049                format_cache_delta_metrics(snapshot.text_cache_deltas.renderer_path),
1050            ),
1051        ]))
1052        .with_child(
1053            SizedBox::new().height(156.0).with_child(
1054                Table::new("Frame phase timings")
1055                    .columns([
1056                        TableColumn::new("Phase").min_width(180.0),
1057                        TableColumn::new("Duration").width(110.0),
1058                        TableColumn::new("Share").width(90.0),
1059                    ])
1060                    .rows(phase_rows),
1061            ),
1062        )
1063        .with_child(scene_summary_view(SceneDebugSummary::from(&snapshot.scene)))
1064}
1065
1066fn duration_tone(duration_ms: f64) -> DebugTone {
1067    if duration_ms >= 33.0 {
1068        DebugTone::Danger
1069    } else if duration_ms >= 16.7 {
1070        DebugTone::Warning
1071    } else if duration_ms > 0.0 {
1072        DebugTone::Success
1073    } else {
1074        DebugTone::Neutral
1075    }
1076}
1077
1078fn latency_tone(duration_ms: f64) -> DebugTone {
1079    if duration_ms <= 0.0 {
1080        DebugTone::Neutral
1081    } else {
1082        duration_tone(duration_ms)
1083    }
1084}
1085
1086fn upload_tone(bytes: u64) -> DebugTone {
1087    if bytes >= 1_048_576 {
1088        DebugTone::Danger
1089    } else if bytes >= 262_144 {
1090        DebugTone::Warning
1091    } else if bytes > 0 {
1092        DebugTone::Info
1093    } else {
1094        DebugTone::Neutral
1095    }
1096}
1097
1098fn format_duration_ms(duration_ms: f64) -> String {
1099    format!("{duration_ms:.2} ms")
1100}
1101
1102fn format_latency_ms(duration_ms: f64) -> String {
1103    if duration_ms <= 0.0 {
1104        "n/a".to_string()
1105    } else {
1106        format_duration_ms(duration_ms)
1107    }
1108}
1109
1110fn format_byte_size(bytes: u64) -> String {
1111    const KIB: u64 = 1024;
1112    const MIB: u64 = 1024 * 1024;
1113
1114    if bytes >= MIB {
1115        format!("{:.1} MiB", bytes as f64 / MIB as f64)
1116    } else if bytes >= KIB {
1117        format!("{:.1} KiB", bytes as f64 / KIB as f64)
1118    } else {
1119        format!("{bytes} B")
1120    }
1121}
1122
1123fn format_cache_metrics(metrics: CacheMetrics) -> String {
1124    let requests = metrics.requests();
1125    if requests == 0 {
1126        format!("{} entries, no lookups yet", metrics.entries)
1127    } else {
1128        format!(
1129            "{} entries, {:.1}% hit rate ({} hits / {} lookups)",
1130            metrics.entries,
1131            metrics.hit_rate() * 100.0,
1132            metrics.hits,
1133            requests,
1134        )
1135    }
1136}
1137
1138fn format_cache_delta_metrics(delta: CacheMetricsDelta) -> String {
1139    let requests = delta.requests();
1140    let entry_delta = match delta.entries_delta.cmp(&0) {
1141        std::cmp::Ordering::Greater => format!("+{} entries", delta.entries_delta),
1142        std::cmp::Ordering::Less => format!("{} entries", delta.entries_delta),
1143        std::cmp::Ordering::Equal => "no entry change".to_string(),
1144    };
1145
1146    if requests == 0 {
1147        format!("{}, no cache lookups this frame", entry_delta)
1148    } else {
1149        format!(
1150            "{}, {:.1}% hit rate this frame ({} hits / {} lookups)",
1151            entry_delta,
1152            delta.hit_rate() * 100.0,
1153            delta.hits,
1154            requests,
1155        )
1156    }
1157}
1158
1159fn stack_host_snapshot_view(graph: WidgetGraphSnapshot) -> impl Widget {
1160    let nodes = graph
1161        .nodes
1162        .iter()
1163        .map(|node| (node.id, node))
1164        .collect::<HashMap<_, _>>();
1165
1166    let rows = graph
1167        .stack_hosts
1168        .iter()
1169        .map(|host| {
1170            let transient_count = host
1171                .surfaces
1172                .iter()
1173                .filter(|surface| {
1174                    nodes
1175                        .get(surface)
1176                        .is_some_and(|node| node.transient_owner_surface.is_some())
1177                })
1178                .count();
1179            TableRow::new([
1180                format!("#{}", host.host.get()),
1181                format!("{:?}", host.order_policy),
1182                host.surfaces.len().to_string(),
1183                transient_count.to_string(),
1184            ])
1185        })
1186        .collect::<Vec<_>>();
1187    let rows = if rows.is_empty() {
1188        vec![TableRow::new([
1189            "none".to_string(),
1190            "n/a".to_string(),
1191            "0".to_string(),
1192            "0".to_string(),
1193        ])]
1194    } else {
1195        rows
1196    };
1197
1198    SizedBox::new().height(156.0).with_child(
1199        Table::new("Stack hosts")
1200            .columns([
1201                TableColumn::new("Host").min_width(100.0),
1202                TableColumn::new("Policy").min_width(120.0),
1203                TableColumn::new("Surfaces").width(84.0),
1204                TableColumn::new("Transient").width(84.0),
1205            ])
1206            .rows(rows),
1207    )
1208}
1209
1210fn layer_update_kind(kind: sui_scene::SceneLayerUpdateKind) -> &'static str {
1211    match kind {
1212        sui_scene::SceneLayerUpdateKind::Ordering => "Ordering",
1213        sui_scene::SceneLayerUpdateKind::Content => "Content",
1214        sui_scene::SceneLayerUpdateKind::Transform => "Transform",
1215        sui_scene::SceneLayerUpdateKind::Clip => "Clip",
1216        sui_scene::SceneLayerUpdateKind::Effect => "Effect",
1217        sui_scene::SceneLayerUpdateKind::Visibility => "Visibility",
1218        sui_scene::SceneLayerUpdateKind::Resources => "Resources",
1219    }
1220}