Skip to main content

sui_runtime/
diagnostics.rs

1#![allow(clippy::too_many_arguments)]
2
3use std::{
4    cell::RefCell,
5    collections::{BTreeMap, HashMap},
6    sync::{OnceLock, RwLock},
7    time::Duration,
8};
9
10use sui_core::{DirtyRegion, Size, WidgetId, WindowId};
11use sui_scene::{LayerCompositionMode, SceneCommand, SceneFrame, SceneLayerUpdateKind};
12use sui_text::RuntimeTextTimingDiagnostics;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum FramePhase {
16    Event,
17    Redraw,
18    MeasureArrange,
19    HitTest,
20    Paint,
21    Semantics,
22    Renderer,
23    SurfaceWait,
24    Diagnostics,
25}
26
27impl FramePhase {
28    pub const fn label(self) -> &'static str {
29        match self {
30            Self::Event => "Event handling",
31            Self::Redraw => "Redraw callback",
32            Self::MeasureArrange => "Measure and arrange",
33            Self::HitTest => "Graph and hit test",
34            Self::Paint => "Paint",
35            Self::Semantics => "Semantics",
36            Self::Renderer => "Renderer work",
37            Self::SurfaceWait => "Surface wait",
38            Self::Diagnostics => "Diagnostics",
39        }
40    }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct FramePhaseSample {
45    pub phase: FramePhase,
46    pub duration_ms: f64,
47}
48
49impl FramePhaseSample {
50    pub const fn new(phase: FramePhase, duration_ms: f64) -> Self {
51        Self { phase, duration_ms }
52    }
53
54    pub fn from_duration(phase: FramePhase, duration: Duration) -> Self {
55        Self::new(phase, duration.as_secs_f64() * 1000.0)
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
60pub enum WidgetTimingPhase {
61    Measure,
62    Arrange,
63    Paint,
64    Semantics,
65}
66
67impl WidgetTimingPhase {
68    pub const fn label(self) -> &'static str {
69        match self {
70            Self::Measure => "Measure",
71            Self::Arrange => "Arrange",
72            Self::Paint => "Paint",
73            Self::Semantics => "Semantics",
74        }
75    }
76}
77
78#[derive(Debug, Clone, PartialEq)]
79pub struct WidgetTimingSample {
80    pub widget_id: WidgetId,
81    pub widget_name: &'static str,
82    pub phase: WidgetTimingPhase,
83    pub duration_ms: f64,
84    pub calls: usize,
85}
86
87#[derive(Debug, Clone, PartialEq, Default)]
88pub struct RenderDiagnostics {
89    pub phase_timings: Vec<FramePhaseSample>,
90    pub text_caches: TextCacheDiagnostics,
91    pub runtime_text_timing: RuntimeTextTimingDiagnostics,
92    pub widget_timings: Vec<WidgetTimingSample>,
93    pub widget_count: usize,
94    pub active_animated_widget_count: usize,
95    pub animation_frame_wake_count: usize,
96    pub animation_repaint_frame_count: usize,
97    pub animation_transform_effect_only_frame_count: usize,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
101struct WidgetTimingKey {
102    widget_id: WidgetId,
103    widget_name: &'static str,
104    phase: WidgetTimingPhase,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Default)]
108struct WidgetTimingAccum {
109    duration_ms: f64,
110    calls: usize,
111}
112
113thread_local! {
114    static WIDGET_TIMING_COLLECTOR: RefCell<Option<BTreeMap<WidgetTimingKey, WidgetTimingAccum>>> =
115        const { RefCell::new(None) };
116}
117
118fn widget_timing_enabled() -> bool {
119    static ENABLED: OnceLock<bool> = OnceLock::new();
120    *ENABLED.get_or_init(|| std::env::var_os("SUI_PROFILE_WIDGET_TIMINGS").is_some())
121}
122
123pub(crate) fn begin_widget_timing_collection() {
124    if !widget_timing_enabled() {
125        return;
126    }
127
128    WIDGET_TIMING_COLLECTOR.with(|collector| {
129        *collector.borrow_mut() = Some(BTreeMap::new());
130    });
131}
132
133pub(crate) fn record_widget_timing(
134    widget_id: WidgetId,
135    widget_name: &'static str,
136    phase: WidgetTimingPhase,
137    duration: Duration,
138) {
139    if !widget_timing_enabled() {
140        return;
141    }
142
143    let duration_ms = duration.as_secs_f64() * 1000.0;
144    WIDGET_TIMING_COLLECTOR.with(|collector| {
145        let mut collector = collector.borrow_mut();
146        let Some(entries) = collector.as_mut() else {
147            return;
148        };
149
150        let entry = entries
151            .entry(WidgetTimingKey {
152                widget_id,
153                widget_name,
154                phase,
155            })
156            .or_default();
157        entry.duration_ms += duration_ms;
158        entry.calls += 1;
159    });
160}
161
162pub(crate) fn take_widget_timing_collection() -> Vec<WidgetTimingSample> {
163    if !widget_timing_enabled() {
164        return Vec::new();
165    }
166
167    let mut samples = WIDGET_TIMING_COLLECTOR
168        .with(|collector| collector.borrow_mut().take())
169        .unwrap_or_default()
170        .into_iter()
171        .map(|(key, accum)| WidgetTimingSample {
172            widget_id: key.widget_id,
173            widget_name: key.widget_name,
174            phase: key.phase,
175            duration_ms: accum.duration_ms,
176            calls: accum.calls,
177        })
178        .collect::<Vec<_>>();
179    samples.sort_by(|left, right| {
180        right
181            .duration_ms
182            .total_cmp(&left.duration_ms)
183            .then_with(|| left.phase.cmp(&right.phase))
184            .then_with(|| left.widget_id.get().cmp(&right.widget_id.get()))
185    });
186    samples
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
190pub struct RetainedPacketRebuildDiagnostics {
191    pub new_count: usize,
192    pub coordinate_space_count: usize,
193    pub signature_count: usize,
194    pub scene_count: usize,
195    pub state_count: usize,
196}
197
198impl RetainedPacketRebuildDiagnostics {
199    pub const fn new(
200        new_count: usize,
201        coordinate_space_count: usize,
202        signature_count: usize,
203        scene_count: usize,
204        state_count: usize,
205    ) -> Self {
206        Self {
207            new_count,
208            coordinate_space_count,
209            signature_count,
210            scene_count,
211            state_count,
212        }
213    }
214
215    pub const fn total_count(&self) -> usize {
216        self.new_count
217            + self.coordinate_space_count
218            + self.signature_count
219            + self.scene_count
220            + self.state_count
221    }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
225pub struct RendererSubmissionDiagnostics {
226    pub pass_count: usize,
227    pub draw_count: usize,
228    pub uploaded_vertex_bytes: u64,
229    pub text_glyph_instance_count: usize,
230    pub text_vertex_bytes: u64,
231    pub visible_layer_count: usize,
232    pub direct_packet_count: usize,
233    pub retained_state_update_time_us: u64,
234    pub composition_time_us: u64,
235    pub retained_scene_traversal_time_us: u64,
236    pub retained_packet_build_time_us: u64,
237    pub retained_packet_build_count: usize,
238    pub retained_packet_rebuilds: RetainedPacketRebuildDiagnostics,
239    pub retained_packet_normalize_time_us: u64,
240    pub retained_packet_signature_time_us: u64,
241    pub retained_packet_raster_state_init_time_us: u64,
242    pub retained_packet_scene_build_time_us: u64,
243    pub retained_packet_command_count: usize,
244    pub retained_packet_text_command_count: usize,
245    pub retained_packet_path_command_count: usize,
246    pub retained_packet_clip_path_command_count: usize,
247    pub retained_packet_image_command_count: usize,
248    pub retained_packet_rect_command_count: usize,
249    pub retained_packet_text_command_time_us: u64,
250    pub retained_packet_path_command_time_us: u64,
251    pub retained_packet_clip_path_command_time_us: u64,
252    pub retained_packet_image_command_time_us: u64,
253    pub retained_packet_rect_command_time_us: u64,
254    pub text_atlas_miss_count: usize,
255    pub text_atlas_miss_time_us: u64,
256    pub surface_acquire_time_us: u64,
257    pub resource_collection_time_us: u64,
258    pub bind_group_prepare_time_us: u64,
259    pub image_bind_group_time_us: u64,
260    pub analytic_path_bind_group_time_us: u64,
261    pub analytic_path_bind_group_miss_count: usize,
262    pub analytic_path_bind_group_upload_bytes: u64,
263    pub text_atlas_bind_group_time_us: u64,
264    pub text_atlas_upload_copy_time_us: u64,
265    pub text_atlas_upload_write_time_us: u64,
266    pub text_atlas_upload_bytes: u64,
267    pub batch_prepare_time_us: u64,
268    pub gpu_upload_time_us: u64,
269    pub pass_encode_time_us: u64,
270    pub queue_submit_time_us: u64,
271    pub surface_present_time_us: u64,
272}
273
274#[derive(Debug, Clone, PartialEq, Eq, Default)]
275pub struct RetainedPacketHotspotDiagnostics {
276    pub container_layer_id: Option<u64>,
277    pub owner_widget_id: Option<u64>,
278    pub segment_index: u32,
279    pub total_time_us: u64,
280    pub scene_build_time_us: u64,
281    pub command_count: usize,
282    pub text_command_count: usize,
283    pub path_command_count: usize,
284    pub rect_command_count: usize,
285    pub text_command_time_us: u64,
286    pub path_command_time_us: u64,
287    pub rect_command_time_us: u64,
288    pub text_sample: Option<String>,
289}
290
291impl RendererSubmissionDiagnostics {
292    pub const fn new(
293        pass_count: usize,
294        draw_count: usize,
295        uploaded_vertex_bytes: u64,
296        text_glyph_instance_count: usize,
297        text_vertex_bytes: u64,
298        visible_layer_count: usize,
299        direct_packet_count: usize,
300        retained_state_update_time_us: u64,
301        composition_time_us: u64,
302        retained_scene_traversal_time_us: u64,
303        retained_packet_build_time_us: u64,
304        retained_packet_build_count: usize,
305        retained_packet_rebuilds: RetainedPacketRebuildDiagnostics,
306        text_atlas_miss_count: usize,
307        text_atlas_miss_time_us: u64,
308        surface_acquire_time_us: u64,
309        resource_collection_time_us: u64,
310        bind_group_prepare_time_us: u64,
311        image_bind_group_time_us: u64,
312        analytic_path_bind_group_time_us: u64,
313        analytic_path_bind_group_miss_count: usize,
314        analytic_path_bind_group_upload_bytes: u64,
315        text_atlas_bind_group_time_us: u64,
316        text_atlas_upload_copy_time_us: u64,
317        text_atlas_upload_write_time_us: u64,
318        text_atlas_upload_bytes: u64,
319        batch_prepare_time_us: u64,
320        gpu_upload_time_us: u64,
321        pass_encode_time_us: u64,
322        queue_submit_time_us: u64,
323        surface_present_time_us: u64,
324    ) -> Self {
325        Self {
326            pass_count,
327            draw_count,
328            uploaded_vertex_bytes,
329            text_glyph_instance_count,
330            text_vertex_bytes,
331            visible_layer_count,
332            direct_packet_count,
333            retained_state_update_time_us,
334            composition_time_us,
335            retained_scene_traversal_time_us,
336            retained_packet_build_time_us,
337            retained_packet_build_count,
338            retained_packet_rebuilds,
339            retained_packet_normalize_time_us: 0,
340            retained_packet_signature_time_us: 0,
341            retained_packet_raster_state_init_time_us: 0,
342            retained_packet_scene_build_time_us: 0,
343            retained_packet_command_count: 0,
344            retained_packet_text_command_count: 0,
345            retained_packet_path_command_count: 0,
346            retained_packet_clip_path_command_count: 0,
347            retained_packet_image_command_count: 0,
348            retained_packet_rect_command_count: 0,
349            retained_packet_text_command_time_us: 0,
350            retained_packet_path_command_time_us: 0,
351            retained_packet_clip_path_command_time_us: 0,
352            retained_packet_image_command_time_us: 0,
353            retained_packet_rect_command_time_us: 0,
354            text_atlas_miss_count,
355            text_atlas_miss_time_us,
356            surface_acquire_time_us,
357            resource_collection_time_us,
358            bind_group_prepare_time_us,
359            image_bind_group_time_us,
360            analytic_path_bind_group_time_us,
361            analytic_path_bind_group_miss_count,
362            analytic_path_bind_group_upload_bytes,
363            text_atlas_bind_group_time_us,
364            text_atlas_upload_copy_time_us,
365            text_atlas_upload_write_time_us,
366            text_atlas_upload_bytes,
367            batch_prepare_time_us,
368            gpu_upload_time_us,
369            pass_encode_time_us,
370            queue_submit_time_us,
371            surface_present_time_us,
372        }
373    }
374
375    pub fn with_retained_packet_breakdown(
376        mut self,
377        retained_packet_normalize_time_us: u64,
378        retained_packet_signature_time_us: u64,
379        retained_packet_raster_state_init_time_us: u64,
380        retained_packet_scene_build_time_us: u64,
381        retained_packet_command_count: usize,
382        retained_packet_text_command_count: usize,
383        retained_packet_path_command_count: usize,
384        retained_packet_clip_path_command_count: usize,
385        retained_packet_image_command_count: usize,
386        retained_packet_rect_command_count: usize,
387        retained_packet_text_command_time_us: u64,
388        retained_packet_path_command_time_us: u64,
389        retained_packet_clip_path_command_time_us: u64,
390        retained_packet_image_command_time_us: u64,
391        retained_packet_rect_command_time_us: u64,
392    ) -> Self {
393        self.retained_packet_normalize_time_us = retained_packet_normalize_time_us;
394        self.retained_packet_signature_time_us = retained_packet_signature_time_us;
395        self.retained_packet_raster_state_init_time_us = retained_packet_raster_state_init_time_us;
396        self.retained_packet_scene_build_time_us = retained_packet_scene_build_time_us;
397        self.retained_packet_command_count = retained_packet_command_count;
398        self.retained_packet_text_command_count = retained_packet_text_command_count;
399        self.retained_packet_path_command_count = retained_packet_path_command_count;
400        self.retained_packet_clip_path_command_count = retained_packet_clip_path_command_count;
401        self.retained_packet_image_command_count = retained_packet_image_command_count;
402        self.retained_packet_rect_command_count = retained_packet_rect_command_count;
403        self.retained_packet_text_command_time_us = retained_packet_text_command_time_us;
404        self.retained_packet_path_command_time_us = retained_packet_path_command_time_us;
405        self.retained_packet_clip_path_command_time_us = retained_packet_clip_path_command_time_us;
406        self.retained_packet_image_command_time_us = retained_packet_image_command_time_us;
407        self.retained_packet_rect_command_time_us = retained_packet_rect_command_time_us;
408        self
409    }
410}
411
412#[derive(Debug, Clone, Copy, PartialEq, Default)]
413pub struct PresentationLatencyDiagnostics {
414    pub event_to_render_start_ms: f64,
415    pub event_to_present_ms: f64,
416    pub redraw_request_to_callback_ms: f64,
417}
418
419impl PresentationLatencyDiagnostics {
420    pub const fn new(
421        event_to_render_start_ms: f64,
422        event_to_present_ms: f64,
423        redraw_request_to_callback_ms: f64,
424    ) -> Self {
425        Self {
426            event_to_render_start_ms,
427            event_to_present_ms,
428            redraw_request_to_callback_ms,
429        }
430    }
431}
432
433impl RenderDiagnostics {
434    pub fn push(&mut self, phase: FramePhase, duration: Duration) {
435        self.phase_timings
436            .push(FramePhaseSample::from_duration(phase, duration));
437    }
438
439    pub fn total_time_ms(&self) -> f64 {
440        self.phase_timings
441            .iter()
442            .map(|sample| sample.duration_ms)
443            .sum()
444    }
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
448pub struct CacheMetrics {
449    pub entries: usize,
450    pub hits: usize,
451    pub misses: usize,
452}
453
454impl CacheMetrics {
455    pub const fn new(entries: usize, hits: usize, misses: usize) -> Self {
456        Self {
457            entries,
458            hits,
459            misses,
460        }
461    }
462
463    pub const fn requests(self) -> usize {
464        self.hits + self.misses
465    }
466
467    pub fn hit_rate(self) -> f64 {
468        let requests = self.requests();
469        if requests == 0 {
470            0.0
471        } else {
472            self.hits as f64 / requests as f64
473        }
474    }
475}
476
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
478pub struct CacheMetricsDelta {
479    pub entries_delta: isize,
480    pub hits: usize,
481    pub misses: usize,
482}
483
484impl CacheMetricsDelta {
485    pub fn from_counters(current: CacheMetrics, previous: CacheMetrics) -> Self {
486        Self {
487            entries_delta: current.entries as isize - previous.entries as isize,
488            hits: current.hits.saturating_sub(previous.hits),
489            misses: current.misses.saturating_sub(previous.misses),
490        }
491    }
492
493    pub const fn requests(self) -> usize {
494        self.hits + self.misses
495    }
496
497    pub fn hit_rate(self) -> f64 {
498        let requests = self.requests();
499        if requests == 0 {
500            0.0
501        } else {
502            self.hits as f64 / requests as f64
503        }
504    }
505}
506
507#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
508pub struct TextCacheDiagnostics {
509    pub runtime_layout: CacheMetrics,
510    pub renderer_layout: CacheMetrics,
511    pub renderer_glyph: CacheMetrics,
512    pub renderer_path: CacheMetrics,
513}
514
515impl TextCacheDiagnostics {
516    pub fn delta_from(&self, previous: &Self) -> TextCacheDeltaDiagnostics {
517        TextCacheDeltaDiagnostics {
518            runtime_layout: CacheMetricsDelta::from_counters(
519                self.runtime_layout,
520                previous.runtime_layout,
521            ),
522            renderer_layout: CacheMetricsDelta::from_counters(
523                self.renderer_layout,
524                previous.renderer_layout,
525            ),
526            renderer_glyph: CacheMetricsDelta::from_counters(
527                self.renderer_glyph,
528                previous.renderer_glyph,
529            ),
530            renderer_path: CacheMetricsDelta::from_counters(
531                self.renderer_path,
532                previous.renderer_path,
533            ),
534        }
535    }
536}
537
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
539pub struct TextCacheDeltaDiagnostics {
540    pub runtime_layout: CacheMetricsDelta,
541    pub renderer_layout: CacheMetricsDelta,
542    pub renderer_glyph: CacheMetricsDelta,
543    pub renderer_path: CacheMetricsDelta,
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
547pub enum SceneStatisticsDetailMode {
548    #[default]
549    Lightweight,
550    Detailed,
551}
552
553impl SceneStatisticsDetailMode {
554    pub const fn is_detailed(self) -> bool {
555        matches!(self, Self::Detailed)
556    }
557
558    pub const fn label(self) -> &'static str {
559        match self {
560            Self::Lightweight => "lightweight",
561            Self::Detailed => "detailed",
562        }
563    }
564}
565
566#[derive(Debug, Clone, Copy, PartialEq)]
567pub enum WindowTextHinting {
568    None,
569    Slight { max_ppem: f32 },
570}
571
572pub const DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM: f32 = 96.0;
573
574impl Default for WindowTextHinting {
575    fn default() -> Self {
576        Self::Slight {
577            max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM,
578        }
579    }
580}
581
582impl WindowTextHinting {
583    pub fn normalized(self) -> Self {
584        match self {
585            Self::None => Self::None,
586            Self::Slight { max_ppem } if max_ppem.is_finite() && max_ppem > 0.0 => {
587                Self::Slight { max_ppem }
588            }
589            Self::Slight { .. } => Self::None,
590        }
591    }
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Default)]
595pub enum WindowStemDarkening {
596    #[default]
597    None,
598    Enabled {
599        max_ppem: f32,
600        amount: f32,
601    },
602}
603
604impl WindowStemDarkening {
605    pub fn normalized(self) -> Self {
606        match self {
607            Self::None => Self::None,
608            Self::Enabled { max_ppem, amount }
609                if max_ppem.is_finite() && max_ppem > 0.0 && amount.is_finite() && amount > 0.0 =>
610            {
611                Self::Enabled {
612                    max_ppem,
613                    amount: amount.clamp(0.0, 1.0),
614                }
615            }
616            Self::Enabled { .. } => Self::None,
617        }
618    }
619}
620
621#[derive(Debug, Clone, Copy, PartialEq, Default)]
622pub enum WindowTextCoveragePolicy {
623    #[default]
624    Perceptual,
625    Linear,
626    Gamma(f32),
627    CoverageBoost(f32),
628    TwoCoverageMinusCoverageSq,
629}
630
631impl WindowTextCoveragePolicy {
632    pub fn normalized(self) -> Self {
633        match self {
634            Self::Perceptual => Self::Perceptual,
635            Self::Linear => Self::Linear,
636            Self::Gamma(gamma) if gamma.is_finite() && gamma > 0.0 => Self::Gamma(gamma),
637            Self::Gamma(_) => Self::Linear,
638            Self::CoverageBoost(amount) if amount.is_finite() && amount > 0.0 => {
639                Self::CoverageBoost(amount.clamp(0.0, 1.0))
640            }
641            Self::CoverageBoost(_) => Self::Linear,
642            Self::TwoCoverageMinusCoverageSq => Self::TwoCoverageMinusCoverageSq,
643        }
644    }
645}
646
647#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
648pub enum WindowTextSubpixelOrder {
649    #[default]
650    None,
651    Rgb,
652    Bgr,
653}
654
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
656pub enum WindowOutputColorPrimaries {
657    #[default]
658    Automatic,
659    Srgb,
660    DisplayP3,
661}
662
663#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
664pub enum WindowDynamicRangeMode {
665    #[default]
666    Automatic,
667    StandardDynamicRange,
668    HighDynamicRange,
669}
670
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
672pub enum WindowToneMappingMode {
673    #[default]
674    Automatic,
675    Clamp,
676    Reinhard,
677}
678
679#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
680pub enum WindowColorManagementMode {
681    #[default]
682    Automatic,
683    ForceSdr,
684    PreferWideGamut,
685    PreferHdr,
686}
687
688pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
689
690#[derive(Debug, Clone, Copy, PartialEq)]
691pub struct WindowRenderOptions {
692    pub feathering_enabled: bool,
693    pub feather_width: f32,
694    pub optical_vertical_text_alignment_enabled: bool,
695    pub text_hinting: WindowTextHinting,
696    pub stem_darkening: WindowStemDarkening,
697    pub text_coverage_policy: WindowTextCoveragePolicy,
698    pub text_subpixel_order: WindowTextSubpixelOrder,
699    pub output_color_primaries: WindowOutputColorPrimaries,
700    pub dynamic_range_mode: WindowDynamicRangeMode,
701    pub tone_mapping_mode: WindowToneMappingMode,
702    pub color_management_mode: WindowColorManagementMode,
703    pub sdr_content_brightness_nits: f32,
704    pub use_system_sdr_content_brightness: bool,
705}
706
707impl WindowRenderOptions {
708    pub const fn new(feathering_enabled: bool, feather_width: f32) -> Self {
709        Self {
710            feathering_enabled,
711            feather_width,
712            optical_vertical_text_alignment_enabled: true,
713            text_hinting: WindowTextHinting::Slight {
714                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM,
715            },
716            stem_darkening: WindowStemDarkening::None,
717            text_coverage_policy: WindowTextCoveragePolicy::Perceptual,
718            text_subpixel_order: WindowTextSubpixelOrder::None,
719            output_color_primaries: WindowOutputColorPrimaries::Automatic,
720            dynamic_range_mode: WindowDynamicRangeMode::Automatic,
721            tone_mapping_mode: WindowToneMappingMode::Automatic,
722            color_management_mode: WindowColorManagementMode::Automatic,
723            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
724            use_system_sdr_content_brightness: true,
725        }
726    }
727
728    pub const fn with_optical_vertical_text_alignment_enabled(mut self, enabled: bool) -> Self {
729        self.optical_vertical_text_alignment_enabled = enabled;
730        self
731    }
732
733    pub const fn with_text_hinting(mut self, hinting: WindowTextHinting) -> Self {
734        self.text_hinting = hinting;
735        self
736    }
737
738    pub const fn with_stem_darkening(mut self, darkening: WindowStemDarkening) -> Self {
739        self.stem_darkening = darkening;
740        self
741    }
742
743    pub const fn with_text_coverage_policy(mut self, policy: WindowTextCoveragePolicy) -> Self {
744        self.text_coverage_policy = policy;
745        self
746    }
747
748    pub const fn with_text_subpixel_order(mut self, order: WindowTextSubpixelOrder) -> Self {
749        self.text_subpixel_order = order;
750        self
751    }
752
753    pub const fn with_output_color_primaries(
754        mut self,
755        primaries: WindowOutputColorPrimaries,
756    ) -> Self {
757        self.output_color_primaries = primaries;
758        self
759    }
760
761    pub const fn with_dynamic_range_mode(mut self, mode: WindowDynamicRangeMode) -> Self {
762        self.dynamic_range_mode = mode;
763        self
764    }
765
766    pub const fn with_tone_mapping_mode(mut self, mode: WindowToneMappingMode) -> Self {
767        self.tone_mapping_mode = mode;
768        self
769    }
770
771    pub const fn with_color_management_mode(mut self, mode: WindowColorManagementMode) -> Self {
772        self.color_management_mode = mode;
773        self
774    }
775
776    pub const fn with_sdr_content_brightness_nits(mut self, brightness_nits: f32) -> Self {
777        self.sdr_content_brightness_nits = brightness_nits;
778        self
779    }
780
781    pub const fn with_system_sdr_content_brightness_enabled(mut self, enabled: bool) -> Self {
782        self.use_system_sdr_content_brightness = enabled;
783        self
784    }
785
786    pub fn clamped(self) -> Self {
787        Self {
788            feathering_enabled: self.feathering_enabled,
789            feather_width: self.feather_width.max(0.0),
790            optical_vertical_text_alignment_enabled: self.optical_vertical_text_alignment_enabled,
791            text_hinting: self.text_hinting.normalized(),
792            stem_darkening: self.stem_darkening.normalized(),
793            text_coverage_policy: self.text_coverage_policy.normalized(),
794            text_subpixel_order: self.text_subpixel_order,
795            output_color_primaries: self.output_color_primaries,
796            dynamic_range_mode: self.dynamic_range_mode,
797            tone_mapping_mode: self.tone_mapping_mode,
798            color_management_mode: self.color_management_mode,
799            sdr_content_brightness_nits: if self.sdr_content_brightness_nits.is_finite()
800                && self.sdr_content_brightness_nits > 0.0
801            {
802                self.sdr_content_brightness_nits
803            } else {
804                DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
805            },
806            use_system_sdr_content_brightness: self.use_system_sdr_content_brightness,
807        }
808    }
809}
810
811#[derive(Debug, Clone, Copy, PartialEq, Default)]
812pub struct WindowPerformanceSummary {
813    pub window_id: WindowId,
814    pub frame_index: u64,
815    pub total_time_ms: f64,
816    pub slowest_phase: Option<FramePhaseSample>,
817    pub presentation_latency: PresentationLatencyDiagnostics,
818    pub renderer_submission: RendererSubmissionDiagnostics,
819    pub text_caches: TextCacheDiagnostics,
820    pub total_widget_count: usize,
821    pub active_animated_widget_count: usize,
822    pub animation_frame_wake_count: usize,
823    pub animation_repaint_frame_count: usize,
824    pub animation_transform_effect_only_frame_count: usize,
825    pub repaint_boundary_count: usize,
826    pub scene_layer_count: usize,
827    pub stack_surface_count: usize,
828    pub overlay_layer_count: usize,
829    pub dirty_region_count: usize,
830    pub dirty_coverage: f32,
831    pub command_count: usize,
832}
833
834#[derive(Debug, Clone, PartialEq)]
835pub struct SceneStatistics {
836    pub detail_mode: SceneStatisticsDetailMode,
837    pub viewport: Size,
838    pub total_widget_count: usize,
839    pub active_animated_widget_count: usize,
840    pub animation_frame_wake_count: usize,
841    pub animation_repaint_frame_count: usize,
842    pub animation_transform_effect_only_frame_count: usize,
843    pub dirty_region_count: usize,
844    pub dirty_regions: Vec<DirtyRegion>,
845    pub dirty_area: f32,
846    pub dirty_coverage: f32,
847    pub command_count: usize,
848    pub command_breakdown: Vec<(String, usize)>,
849    /// Current repaint granularity as observed by the runtime today.
850    ///
851    /// During the layer-boundary transition this still tracks emitted scene
852    /// layers, because the runtime has not yet decoupled explicit repaint
853    /// boundaries from per-widget `SceneLayer` emission.
854    pub repaint_boundary_count: usize,
855    pub scene_layer_count: usize,
856    pub stack_surface_count: usize,
857    pub overlay_layer_count: usize,
858    pub layer_update_count: usize,
859    pub layer_update_breakdown: Vec<(String, usize)>,
860    pub text_command_count: usize,
861    pub image_command_count: usize,
862    pub clip_command_count: usize,
863    pub transform_command_count: usize,
864}
865
866impl SceneStatistics {
867    pub fn with_animation_counters(
868        mut self,
869        active_animated_widget_count: usize,
870        animation_frame_wake_count: usize,
871        animation_repaint_frame_count: usize,
872        animation_transform_effect_only_frame_count: usize,
873    ) -> Self {
874        self.active_animated_widget_count = active_animated_widget_count;
875        self.animation_frame_wake_count = animation_frame_wake_count;
876        self.animation_repaint_frame_count = animation_repaint_frame_count;
877        self.animation_transform_effect_only_frame_count =
878            animation_transform_effect_only_frame_count;
879        self
880    }
881
882    pub fn from_frame(frame: &SceneFrame, total_widget_count: usize) -> Self {
883        Self::from_frame_with_mode(
884            frame,
885            total_widget_count,
886            SceneStatisticsDetailMode::Lightweight,
887        )
888    }
889
890    pub fn minimal(
891        frame: &SceneFrame,
892        total_widget_count: usize,
893        detail_mode: SceneStatisticsDetailMode,
894    ) -> Self {
895        let layer_totals = scene_layer_totals(frame);
896        Self {
897            detail_mode,
898            viewport: frame.viewport,
899            total_widget_count,
900            active_animated_widget_count: 0,
901            animation_frame_wake_count: 0,
902            animation_repaint_frame_count: 0,
903            animation_transform_effect_only_frame_count: 0,
904            dirty_region_count: 0,
905            dirty_regions: Vec::new(),
906            dirty_area: 0.0,
907            dirty_coverage: 0.0,
908            command_count: 0,
909            command_breakdown: Vec::new(),
910            repaint_boundary_count: layer_totals.repaint_boundary_count,
911            scene_layer_count: layer_totals.scene_layer_count,
912            stack_surface_count: layer_totals.stack_surface_count,
913            overlay_layer_count: layer_totals.overlay_layer_count,
914            layer_update_count: 0,
915            layer_update_breakdown: Vec::new(),
916            text_command_count: 0,
917            image_command_count: 0,
918            clip_command_count: 0,
919            transform_command_count: 0,
920        }
921    }
922
923    pub fn from_frame_with_mode(
924        frame: &SceneFrame,
925        total_widget_count: usize,
926        detail_mode: SceneStatisticsDetailMode,
927    ) -> Self {
928        let detailed = detail_mode.is_detailed();
929        let mut command_breakdown = detailed.then(BTreeMap::<String, usize>::new);
930        let mut text_command_count = 0usize;
931        let mut image_command_count = 0usize;
932        let mut clip_command_count = 0usize;
933        let mut transform_command_count = 0usize;
934        let mut command_count = 0usize;
935
936        frame.scene.visit_commands(&mut |command| {
937            command_count += 1;
938            if let Some(breakdown) = &mut command_breakdown {
939                *breakdown
940                    .entry(command_kind(command).to_string())
941                    .or_default() += 1;
942            }
943
944            match command {
945                SceneCommand::DrawText(_)
946                | SceneCommand::DrawShapedText(_)
947                | SceneCommand::DrawShapedTextWindow(_)
948                | SceneCommand::Label { .. } => {
949                    text_command_count += 1;
950                }
951                SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => {
952                    image_command_count += 1;
953                }
954                SceneCommand::PushClip { .. }
955                | SceneCommand::PushClipPath { .. }
956                | SceneCommand::PopClip => {
957                    clip_command_count += 1;
958                }
959                SceneCommand::PushTransform { .. } | SceneCommand::PopTransform => {
960                    transform_command_count += 1;
961                }
962                SceneCommand::Clear(_)
963                | SceneCommand::FillRect { .. }
964                | SceneCommand::StrokeRect { .. }
965                | SceneCommand::FillPath { .. }
966                | SceneCommand::StrokePath { .. }
967                | SceneCommand::DrawShaderRect { .. }
968                | SceneCommand::FillRoundedRect { .. }
969                | SceneCommand::PushTextRenderPolicy { .. }
970                | SceneCommand::PopTextRenderPolicy
971                | SceneCommand::Layer(_) => {}
972            }
973        });
974
975        let mut layer_update_breakdown = detailed.then(BTreeMap::<String, usize>::new);
976        if let Some(breakdown) = &mut layer_update_breakdown {
977            for update in &frame.layer_updates {
978                *breakdown
979                    .entry(layer_update_kind(update.kind).to_string())
980                    .or_default() += 1;
981            }
982        }
983
984        let dirty_area: f32 = frame
985            .dirty_regions
986            .iter()
987            .map(|region| region.area.width().max(0.0) * region.area.height().max(0.0))
988            .sum();
989        let viewport_area = frame.viewport.width.max(0.0) * frame.viewport.height.max(0.0);
990        let dirty_coverage = if viewport_area > 0.0 {
991            ((dirty_area / viewport_area) * 100.0).min(100.0)
992        } else {
993            0.0
994        };
995        let dirty_region_count = frame.dirty_regions.len();
996        let layer_totals = scene_layer_totals(frame);
997
998        Self {
999            detail_mode,
1000            viewport: frame.viewport,
1001            total_widget_count,
1002            active_animated_widget_count: 0,
1003            animation_frame_wake_count: 0,
1004            animation_repaint_frame_count: 0,
1005            animation_transform_effect_only_frame_count: 0,
1006            dirty_region_count,
1007            dirty_regions: if detailed {
1008                frame.dirty_regions.clone()
1009            } else {
1010                Vec::new()
1011            },
1012            dirty_area,
1013            dirty_coverage,
1014            command_count,
1015            command_breakdown: command_breakdown
1016                .map(|breakdown| breakdown.into_iter().collect())
1017                .unwrap_or_default(),
1018            repaint_boundary_count: layer_totals.repaint_boundary_count,
1019            scene_layer_count: layer_totals.scene_layer_count,
1020            stack_surface_count: layer_totals.stack_surface_count,
1021            overlay_layer_count: layer_totals.overlay_layer_count,
1022            layer_update_count: frame.layer_updates.len(),
1023            layer_update_breakdown: layer_update_breakdown
1024                .map(|breakdown| breakdown.into_iter().collect())
1025                .unwrap_or_default(),
1026            text_command_count,
1027            image_command_count,
1028            clip_command_count,
1029            transform_command_count,
1030        }
1031    }
1032}
1033
1034#[derive(Debug, Clone, Copy, Default)]
1035struct SceneLayerTotals {
1036    repaint_boundary_count: usize,
1037    scene_layer_count: usize,
1038    stack_surface_count: usize,
1039    overlay_layer_count: usize,
1040}
1041
1042fn scene_layer_totals(frame: &SceneFrame) -> SceneLayerTotals {
1043    let mut totals = SceneLayerTotals::default();
1044    frame.scene.visit_layers(&mut |layer| {
1045        totals.scene_layer_count += 1;
1046        if layer.descriptor.is_stack_surface {
1047            totals.stack_surface_count += 1;
1048        }
1049        if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
1050            totals.overlay_layer_count += 1;
1051        }
1052    });
1053    // Current runtime behavior still uses emitted scene layers as repaint
1054    // granularity. Keep the two metrics separate in the API so later slices can
1055    // decouple them without another diagnostics rename, but document the
1056    // equality clearly for this transitional phase.
1057    totals.repaint_boundary_count = totals.scene_layer_count;
1058    totals
1059}
1060
1061#[derive(Debug, Clone, PartialEq)]
1062pub struct WindowPerformanceSnapshot {
1063    pub window_id: WindowId,
1064    pub frame_index: u64,
1065    pub total_time_ms: f64,
1066    pub phase_timings: Vec<FramePhaseSample>,
1067    pub presentation_latency: PresentationLatencyDiagnostics,
1068    pub renderer_submission: RendererSubmissionDiagnostics,
1069    pub text_caches: TextCacheDiagnostics,
1070    pub text_cache_deltas: TextCacheDeltaDiagnostics,
1071    pub runtime_text_timing: RuntimeTextTimingDiagnostics,
1072    pub widget_timings: Vec<WidgetTimingSample>,
1073    pub retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
1074    pub scene: SceneStatistics,
1075}
1076
1077impl WindowPerformanceSnapshot {
1078    pub fn new(
1079        window_id: WindowId,
1080        frame_index: u64,
1081        phase_timings: Vec<FramePhaseSample>,
1082        renderer_submission: RendererSubmissionDiagnostics,
1083        text_caches: TextCacheDiagnostics,
1084        text_cache_deltas: TextCacheDeltaDiagnostics,
1085        scene: SceneStatistics,
1086    ) -> Self {
1087        let total_time_ms = phase_timings.iter().map(|sample| sample.duration_ms).sum();
1088
1089        Self::with_total_time_ms(
1090            window_id,
1091            frame_index,
1092            total_time_ms,
1093            phase_timings,
1094            renderer_submission,
1095            text_caches,
1096            text_cache_deltas,
1097            scene,
1098        )
1099    }
1100
1101    pub fn with_total_time_ms(
1102        window_id: WindowId,
1103        frame_index: u64,
1104        total_time_ms: f64,
1105        phase_timings: Vec<FramePhaseSample>,
1106        renderer_submission: RendererSubmissionDiagnostics,
1107        text_caches: TextCacheDiagnostics,
1108        text_cache_deltas: TextCacheDeltaDiagnostics,
1109        scene: SceneStatistics,
1110    ) -> Self {
1111        Self {
1112            window_id,
1113            frame_index,
1114            total_time_ms,
1115            phase_timings,
1116            presentation_latency: PresentationLatencyDiagnostics::default(),
1117            renderer_submission,
1118            text_caches,
1119            text_cache_deltas,
1120            runtime_text_timing: RuntimeTextTimingDiagnostics::default(),
1121            widget_timings: Vec::new(),
1122            retained_packet_hotspot: None,
1123            scene,
1124        }
1125    }
1126
1127    pub fn with_presentation_latency(
1128        mut self,
1129        presentation_latency: PresentationLatencyDiagnostics,
1130    ) -> Self {
1131        self.presentation_latency = presentation_latency;
1132        self
1133    }
1134
1135    pub fn with_widget_timings(mut self, widget_timings: Vec<WidgetTimingSample>) -> Self {
1136        self.widget_timings = widget_timings;
1137        self
1138    }
1139
1140    pub fn with_runtime_text_timing(
1141        mut self,
1142        runtime_text_timing: RuntimeTextTimingDiagnostics,
1143    ) -> Self {
1144        self.runtime_text_timing = runtime_text_timing;
1145        self
1146    }
1147
1148    pub fn with_retained_packet_hotspot(
1149        mut self,
1150        retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
1151    ) -> Self {
1152        self.retained_packet_hotspot = retained_packet_hotspot;
1153        self
1154    }
1155
1156    pub fn slowest_phase(&self) -> Option<FramePhaseSample> {
1157        self.phase_timings
1158            .iter()
1159            .copied()
1160            .max_by(|left, right| left.duration_ms.total_cmp(&right.duration_ms))
1161    }
1162
1163    pub fn summary(&self) -> WindowPerformanceSummary {
1164        WindowPerformanceSummary {
1165            window_id: self.window_id,
1166            frame_index: self.frame_index,
1167            total_time_ms: self.total_time_ms,
1168            slowest_phase: self.slowest_phase(),
1169            presentation_latency: self.presentation_latency,
1170            renderer_submission: self.renderer_submission,
1171            text_caches: self.text_caches,
1172            total_widget_count: self.scene.total_widget_count,
1173            active_animated_widget_count: self.scene.active_animated_widget_count,
1174            animation_frame_wake_count: self.scene.animation_frame_wake_count,
1175            animation_repaint_frame_count: self.scene.animation_repaint_frame_count,
1176            animation_transform_effect_only_frame_count: self
1177                .scene
1178                .animation_transform_effect_only_frame_count,
1179            repaint_boundary_count: self.scene.repaint_boundary_count,
1180            scene_layer_count: self.scene.scene_layer_count,
1181            stack_surface_count: self.scene.stack_surface_count,
1182            overlay_layer_count: self.scene.overlay_layer_count,
1183            dirty_region_count: self.scene.dirty_region_count,
1184            dirty_coverage: self.scene.dirty_coverage,
1185            command_count: self.scene.command_count,
1186        }
1187    }
1188}
1189
1190static WINDOW_PERFORMANCE_SNAPSHOTS: OnceLock<
1191    RwLock<HashMap<WindowId, WindowPerformanceSnapshot>>,
1192> = OnceLock::new();
1193static WINDOW_SCENE_STATISTICS_DETAIL_MODES: OnceLock<
1194    RwLock<HashMap<WindowId, SceneStatisticsDetailMode>>,
1195> = OnceLock::new();
1196static WINDOW_RENDER_OPTIONS: OnceLock<RwLock<HashMap<WindowId, WindowRenderOptions>>> =
1197    OnceLock::new();
1198
1199pub fn publish_window_performance_snapshot(snapshot: WindowPerformanceSnapshot) {
1200    let mut store = window_performance_store()
1201        .write()
1202        .expect("window performance snapshot store lock should not be poisoned");
1203    store.insert(snapshot.window_id, snapshot);
1204}
1205
1206pub fn window_performance_snapshot(window_id: WindowId) -> Option<WindowPerformanceSnapshot> {
1207    let store = window_performance_store()
1208        .read()
1209        .expect("window performance snapshot store lock should not be poisoned");
1210    store.get(&window_id).cloned()
1211}
1212
1213pub fn window_performance_summary(window_id: WindowId) -> Option<WindowPerformanceSummary> {
1214    let store = window_performance_store()
1215        .read()
1216        .expect("window performance snapshot store lock should not be poisoned");
1217    store
1218        .get(&window_id)
1219        .map(WindowPerformanceSnapshot::summary)
1220}
1221
1222pub fn window_performance_text_caches(window_id: WindowId) -> Option<TextCacheDiagnostics> {
1223    let store = window_performance_store()
1224        .read()
1225        .expect("window performance snapshot store lock should not be poisoned");
1226    store.get(&window_id).map(|snapshot| snapshot.text_caches)
1227}
1228
1229pub fn set_window_scene_statistics_detail_mode(
1230    window_id: WindowId,
1231    detail_mode: SceneStatisticsDetailMode,
1232) {
1233    let mut store = window_scene_statistics_detail_mode_store()
1234        .write()
1235        .expect("scene statistics detail mode store lock should not be poisoned");
1236    if detail_mode == SceneStatisticsDetailMode::Lightweight {
1237        store.remove(&window_id);
1238    } else {
1239        store.insert(window_id, detail_mode);
1240    }
1241}
1242
1243pub fn window_scene_statistics_detail_mode(window_id: WindowId) -> SceneStatisticsDetailMode {
1244    let store = window_scene_statistics_detail_mode_store()
1245        .read()
1246        .expect("scene statistics detail mode store lock should not be poisoned");
1247    store.get(&window_id).copied().unwrap_or_default()
1248}
1249
1250pub fn set_window_render_options(window_id: WindowId, options: WindowRenderOptions) {
1251    let mut store = window_render_options_store()
1252        .write()
1253        .expect("window render options store lock should not be poisoned");
1254    store.insert(window_id, options.clamped());
1255}
1256
1257pub fn window_render_options(window_id: WindowId) -> Option<WindowRenderOptions> {
1258    let store = window_render_options_store()
1259        .read()
1260        .expect("window render options store lock should not be poisoned");
1261    store.get(&window_id).copied()
1262}
1263
1264pub fn clear_window_render_options(window_id: WindowId) {
1265    let mut store = window_render_options_store()
1266        .write()
1267        .expect("window render options store lock should not be poisoned");
1268    store.remove(&window_id);
1269}
1270
1271pub fn clear_window_performance_snapshot(window_id: WindowId) {
1272    let mut store = window_performance_store()
1273        .write()
1274        .expect("window performance snapshot store lock should not be poisoned");
1275    store.remove(&window_id);
1276
1277    let mut detail_modes = window_scene_statistics_detail_mode_store()
1278        .write()
1279        .expect("scene statistics detail mode store lock should not be poisoned");
1280    detail_modes.remove(&window_id);
1281
1282    clear_window_render_options(window_id);
1283}
1284
1285pub fn clear_window_performance_snapshots() {
1286    let mut store = window_performance_store()
1287        .write()
1288        .expect("window performance snapshot store lock should not be poisoned");
1289    store.clear();
1290
1291    let mut detail_modes = window_scene_statistics_detail_mode_store()
1292        .write()
1293        .expect("scene statistics detail mode store lock should not be poisoned");
1294    detail_modes.clear();
1295
1296    let mut render_options = window_render_options_store()
1297        .write()
1298        .expect("window render options store lock should not be poisoned");
1299    render_options.clear();
1300}
1301
1302fn window_performance_store() -> &'static RwLock<HashMap<WindowId, WindowPerformanceSnapshot>> {
1303    WINDOW_PERFORMANCE_SNAPSHOTS.get_or_init(|| RwLock::new(HashMap::new()))
1304}
1305
1306fn window_scene_statistics_detail_mode_store()
1307-> &'static RwLock<HashMap<WindowId, SceneStatisticsDetailMode>> {
1308    WINDOW_SCENE_STATISTICS_DETAIL_MODES.get_or_init(|| RwLock::new(HashMap::new()))
1309}
1310
1311fn window_render_options_store() -> &'static RwLock<HashMap<WindowId, WindowRenderOptions>> {
1312    WINDOW_RENDER_OPTIONS.get_or_init(|| RwLock::new(HashMap::new()))
1313}
1314
1315fn command_kind(command: &SceneCommand) -> &'static str {
1316    match command {
1317        SceneCommand::Clear(_) => "Clear",
1318        SceneCommand::FillRect { .. } => "FillRect",
1319        SceneCommand::StrokeRect { .. } => "StrokeRect",
1320        SceneCommand::FillPath { .. } => "FillPath",
1321        SceneCommand::StrokePath { .. } => "StrokePath",
1322        SceneCommand::DrawText(_) => "DrawText",
1323        SceneCommand::DrawShapedText(_) => "DrawShapedText",
1324        SceneCommand::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
1325        SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => "DrawImage",
1326        SceneCommand::DrawShaderRect { .. } => "DrawShaderRect",
1327        SceneCommand::PushClip { .. } => "PushClip",
1328        SceneCommand::PushClipPath { .. } => "PushClipPath",
1329        SceneCommand::PopClip => "PopClip",
1330        SceneCommand::PushTransform { .. } => "PushTransform",
1331        SceneCommand::PopTransform => "PopTransform",
1332        SceneCommand::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
1333        SceneCommand::PopTextRenderPolicy => "PopTextRenderPolicy",
1334        SceneCommand::Layer(_) => "Layer",
1335        SceneCommand::FillRoundedRect { .. } => "FillRoundedRect",
1336        SceneCommand::Label { .. } => "Label",
1337    }
1338}
1339
1340fn layer_update_kind(kind: SceneLayerUpdateKind) -> &'static str {
1341    match kind {
1342        SceneLayerUpdateKind::Ordering => "Ordering",
1343        SceneLayerUpdateKind::Content => "Content",
1344        SceneLayerUpdateKind::Transform => "Transform",
1345        SceneLayerUpdateKind::Clip => "Clip",
1346        SceneLayerUpdateKind::Effect => "Effect",
1347        SceneLayerUpdateKind::Visibility => "Visibility",
1348        SceneLayerUpdateKind::Resources => "Resources",
1349    }
1350}
1351
1352#[cfg(test)]
1353mod tests {
1354    use super::{
1355        CacheMetrics, DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM, FramePhase, FramePhaseSample,
1356        RendererSubmissionDiagnostics, RetainedPacketRebuildDiagnostics, SceneStatistics,
1357        SceneStatisticsDetailMode, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
1358        WindowColorManagementMode, WindowDynamicRangeMode, WindowOutputColorPrimaries,
1359        WindowPerformanceSnapshot, WindowRenderOptions, WindowTextCoveragePolicy,
1360        WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
1361        clear_window_performance_snapshot, set_window_render_options,
1362        set_window_scene_statistics_detail_mode, window_render_options,
1363        window_scene_statistics_detail_mode,
1364    };
1365    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, Size, WidgetId, WindowId};
1366    use sui_scene::{
1367        LayerCompositionMode, Scene, SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor,
1368    };
1369
1370    #[test]
1371    fn text_cache_deltas_are_derived_from_prior_counters() {
1372        let previous = TextCacheDiagnostics {
1373            runtime_layout: CacheMetrics::new(2, 10, 4),
1374            renderer_layout: CacheMetrics::new(3, 6, 2),
1375            renderer_glyph: CacheMetrics::new(5, 12, 3),
1376            renderer_path: CacheMetrics::new(7, 14, 5),
1377        };
1378        let current = TextCacheDiagnostics {
1379            runtime_layout: CacheMetrics::new(4, 15, 6),
1380            renderer_layout: CacheMetrics::new(3, 9, 3),
1381            renderer_glyph: CacheMetrics::new(7, 18, 5),
1382            renderer_path: CacheMetrics::new(8, 21, 6),
1383        };
1384
1385        let delta = current.delta_from(&previous);
1386
1387        assert_eq!(delta.runtime_layout.entries_delta, 2);
1388        assert_eq!(delta.runtime_layout.hits, 5);
1389        assert_eq!(delta.runtime_layout.misses, 2);
1390        assert_eq!(delta.renderer_layout.entries_delta, 0);
1391        assert_eq!(delta.renderer_layout.hits, 3);
1392        assert_eq!(delta.renderer_layout.misses, 1);
1393        assert_eq!(delta.renderer_glyph.entries_delta, 2);
1394        assert_eq!(delta.renderer_glyph.hits, 6);
1395        assert_eq!(delta.renderer_glyph.misses, 2);
1396        assert_eq!(delta.renderer_path.entries_delta, 1);
1397        assert_eq!(delta.renderer_path.hits, 7);
1398        assert_eq!(delta.renderer_path.misses, 1);
1399    }
1400
1401    #[test]
1402    fn scene_statistics_diagnostics_minimal_preserves_split_count_totals() {
1403        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1404        frame
1405            .scene
1406            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1407                SceneLayerDescriptor::new(
1408                    WidgetId::new(10).into(),
1409                    WidgetId::new(10),
1410                    Rect::new(0.0, 0.0, 120.0, 80.0),
1411                )
1412                .with_is_stack_surface(true),
1413                Scene::new(),
1414            )));
1415        frame
1416            .scene
1417            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1418                SceneLayerDescriptor::new(
1419                    WidgetId::new(11).into(),
1420                    WidgetId::new(11),
1421                    Rect::new(12.0, 10.0, 80.0, 48.0),
1422                )
1423                .with_composition_mode(LayerCompositionMode::Overlay),
1424                Scene::new(),
1425            )));
1426
1427        let stats = SceneStatistics::minimal(&frame, 5, SceneStatisticsDetailMode::Lightweight);
1428
1429        assert_eq!(stats.total_widget_count, 5);
1430        assert_eq!(stats.repaint_boundary_count, 2);
1431        assert_eq!(stats.scene_layer_count, 2);
1432        assert_eq!(stats.stack_surface_count, 1);
1433        assert_eq!(stats.overlay_layer_count, 1);
1434        assert!(stats.command_breakdown.is_empty());
1435        assert!(stats.layer_update_breakdown.is_empty());
1436    }
1437
1438    #[test]
1439    fn window_performance_snapshot_preserves_renderer_submission_stats() {
1440        let snapshot = WindowPerformanceSnapshot::new(
1441            WindowId::new(5),
1442            17,
1443            vec![FramePhaseSample::new(FramePhase::Renderer, 2.5)],
1444            RendererSubmissionDiagnostics::new(
1445                3,
1446                9,
1447                4096,
1448                128,
1449                3584,
1450                4,
1451                7,
1452                230,
1453                90,
1454                310,
1455                120,
1456                2,
1457                RetainedPacketRebuildDiagnostics::new(1, 0, 1, 1, 0),
1458                5,
1459                80,
1460                440,
1461                210,
1462                130,
1463                15,
1464                95,
1465                4,
1466                32768,
1467                115,
1468                85,
1469                22,
1470                16384,
1471                920,
1472                640,
1473                180,
1474                70,
1475                560,
1476            ),
1477            TextCacheDiagnostics::default(),
1478            TextCacheDeltaDiagnostics::default(),
1479            SceneStatistics {
1480                detail_mode: SceneStatisticsDetailMode::Lightweight,
1481                viewport: Size::new(640.0, 360.0),
1482                total_widget_count: 9,
1483                active_animated_widget_count: 2,
1484                animation_frame_wake_count: 1,
1485                animation_repaint_frame_count: 1,
1486                animation_transform_effect_only_frame_count: 0,
1487                dirty_region_count: 0,
1488                dirty_regions: Vec::new(),
1489                dirty_area: 0.0,
1490                dirty_coverage: 0.0,
1491                command_count: 0,
1492                command_breakdown: Vec::new(),
1493                repaint_boundary_count: 4,
1494                scene_layer_count: 4,
1495                stack_surface_count: 1,
1496                overlay_layer_count: 1,
1497                layer_update_count: 0,
1498                layer_update_breakdown: Vec::new(),
1499                text_command_count: 0,
1500                image_command_count: 0,
1501                clip_command_count: 0,
1502                transform_command_count: 0,
1503            },
1504        );
1505
1506        assert_eq!(snapshot.renderer_submission.pass_count, 3);
1507        assert_eq!(snapshot.renderer_submission.draw_count, 9);
1508        assert_eq!(snapshot.renderer_submission.uploaded_vertex_bytes, 4096);
1509        assert_eq!(snapshot.renderer_submission.direct_packet_count, 7);
1510        assert_eq!(
1511            snapshot.renderer_submission.retained_state_update_time_us,
1512            230
1513        );
1514        assert_eq!(
1515            snapshot
1516                .renderer_submission
1517                .retained_scene_traversal_time_us,
1518            310
1519        );
1520        assert_eq!(
1521            snapshot.renderer_submission.retained_packet_build_time_us,
1522            120
1523        );
1524        assert_eq!(snapshot.renderer_submission.retained_packet_build_count, 2);
1525        assert_eq!(
1526            snapshot
1527                .renderer_submission
1528                .retained_packet_rebuilds
1529                .total_count(),
1530            3
1531        );
1532        assert_eq!(
1533            snapshot
1534                .renderer_submission
1535                .retained_packet_rebuilds
1536                .new_count,
1537            1
1538        );
1539        assert_eq!(
1540            snapshot
1541                .renderer_submission
1542                .retained_packet_rebuilds
1543                .signature_count,
1544            1
1545        );
1546        assert_eq!(
1547            snapshot
1548                .renderer_submission
1549                .retained_packet_rebuilds
1550                .scene_count,
1551            1
1552        );
1553        assert_eq!(snapshot.renderer_submission.text_atlas_miss_count, 5);
1554        assert_eq!(snapshot.renderer_submission.text_atlas_miss_time_us, 80);
1555        assert_eq!(snapshot.renderer_submission.surface_acquire_time_us, 440);
1556        assert_eq!(
1557            snapshot.renderer_submission.resource_collection_time_us,
1558            210
1559        );
1560        assert_eq!(snapshot.renderer_submission.bind_group_prepare_time_us, 130);
1561        assert_eq!(snapshot.renderer_submission.image_bind_group_time_us, 15);
1562        assert_eq!(
1563            snapshot
1564                .renderer_submission
1565                .analytic_path_bind_group_time_us,
1566            95
1567        );
1568        assert_eq!(
1569            snapshot
1570                .renderer_submission
1571                .analytic_path_bind_group_miss_count,
1572            4
1573        );
1574        assert_eq!(
1575            snapshot
1576                .renderer_submission
1577                .analytic_path_bind_group_upload_bytes,
1578            32768
1579        );
1580        assert_eq!(
1581            snapshot.renderer_submission.text_atlas_bind_group_time_us,
1582            115
1583        );
1584        assert_eq!(
1585            snapshot.renderer_submission.text_atlas_upload_copy_time_us,
1586            85
1587        );
1588        assert_eq!(
1589            snapshot.renderer_submission.text_atlas_upload_write_time_us,
1590            22
1591        );
1592        assert_eq!(snapshot.renderer_submission.text_atlas_upload_bytes, 16384);
1593        assert_eq!(snapshot.renderer_submission.batch_prepare_time_us, 920);
1594        assert_eq!(snapshot.renderer_submission.gpu_upload_time_us, 640);
1595        assert_eq!(snapshot.renderer_submission.pass_encode_time_us, 180);
1596        assert_eq!(snapshot.renderer_submission.queue_submit_time_us, 70);
1597        assert_eq!(snapshot.renderer_submission.surface_present_time_us, 560);
1598        assert_eq!(snapshot.total_time_ms, 2.5);
1599
1600        let summary = snapshot.summary();
1601        assert_eq!(summary.total_widget_count, 9);
1602        assert_eq!(summary.active_animated_widget_count, 2);
1603        assert_eq!(summary.animation_frame_wake_count, 1);
1604        assert_eq!(summary.animation_repaint_frame_count, 1);
1605        assert_eq!(summary.animation_transform_effect_only_frame_count, 0);
1606        assert_eq!(summary.repaint_boundary_count, 4);
1607        assert_eq!(summary.scene_layer_count, 4);
1608        assert_eq!(summary.stack_surface_count, 1);
1609        assert_eq!(summary.overlay_layer_count, 1);
1610    }
1611
1612    #[test]
1613    fn animation_frame_counters_distinguish_repaint_from_transform_only_frames() {
1614        let base_scene = SceneStatistics::minimal(
1615            &SceneFrame::new(WindowId::new(12), Size::new(320.0, 180.0)),
1616            3,
1617            SceneStatisticsDetailMode::Detailed,
1618        );
1619
1620        let repaint_summary = WindowPerformanceSnapshot::new(
1621            WindowId::new(12),
1622            3,
1623            vec![FramePhaseSample::new(FramePhase::Paint, 0.8)],
1624            RendererSubmissionDiagnostics::default(),
1625            TextCacheDiagnostics::default(),
1626            TextCacheDeltaDiagnostics::default(),
1627            base_scene.clone().with_animation_counters(2, 1, 1, 0),
1628        )
1629        .summary();
1630        let transform_only_summary = WindowPerformanceSnapshot::new(
1631            WindowId::new(12),
1632            4,
1633            vec![FramePhaseSample::new(FramePhase::Renderer, 0.4)],
1634            RendererSubmissionDiagnostics::default(),
1635            TextCacheDiagnostics::default(),
1636            TextCacheDeltaDiagnostics::default(),
1637            base_scene.with_animation_counters(1, 1, 0, 1),
1638        )
1639        .summary();
1640
1641        assert_eq!(repaint_summary.active_animated_widget_count, 2);
1642        assert_eq!(repaint_summary.animation_frame_wake_count, 1);
1643        assert_eq!(repaint_summary.animation_repaint_frame_count, 1);
1644        assert_eq!(
1645            repaint_summary.animation_transform_effect_only_frame_count,
1646            0
1647        );
1648        assert_eq!(transform_only_summary.active_animated_widget_count, 1);
1649        assert_eq!(transform_only_summary.animation_frame_wake_count, 1);
1650        assert_eq!(transform_only_summary.animation_repaint_frame_count, 0);
1651        assert_eq!(
1652            transform_only_summary.animation_transform_effect_only_frame_count,
1653            1
1654        );
1655    }
1656
1657    #[test]
1658    fn retained_packet_rebuild_diagnostics_total_count_sums_reasons() {
1659        let rebuilds = RetainedPacketRebuildDiagnostics::new(2, 3, 5, 7, 11);
1660
1661        assert_eq!(rebuilds.total_count(), 28);
1662    }
1663
1664    #[test]
1665    fn scene_statistics_skip_expensive_breakdowns_in_lightweight_mode() {
1666        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1667        frame.dirty_regions.push(DirtyRegion::new(
1668            Rect::new(0.0, 0.0, 64.0, 48.0),
1669            InvalidationKind::Paint,
1670        ));
1671        frame.scene.push(SceneCommand::Clear(Color::BLACK));
1672        frame.scene.push(SceneCommand::Label {
1673            rect: Rect::new(12.0, 12.0, 96.0, 24.0),
1674            text: "frame".to_string(),
1675            color: Color::WHITE,
1676        });
1677
1678        let lightweight = SceneStatistics::from_frame(&frame, 2);
1679        assert_eq!(
1680            lightweight.detail_mode,
1681            SceneStatisticsDetailMode::Lightweight
1682        );
1683        assert_eq!(lightweight.dirty_region_count, 1);
1684        assert_eq!(lightweight.command_count, 2);
1685        assert_eq!(lightweight.total_widget_count, 2);
1686        assert!(lightweight.dirty_regions.is_empty());
1687        assert!(lightweight.command_breakdown.is_empty());
1688
1689        let detailed =
1690            SceneStatistics::from_frame_with_mode(&frame, 2, SceneStatisticsDetailMode::Detailed);
1691        assert_eq!(detailed.detail_mode, SceneStatisticsDetailMode::Detailed);
1692        assert_eq!(detailed.dirty_region_count, 1);
1693        assert_eq!(detailed.dirty_regions.len(), 1);
1694        assert!(
1695            detailed
1696                .command_breakdown
1697                .contains(&("Clear".to_string(), 1))
1698        );
1699        assert!(
1700            detailed
1701                .command_breakdown
1702                .contains(&("Label".to_string(), 1))
1703        );
1704    }
1705
1706    #[test]
1707    fn scene_statistics_diagnostics_split_widget_boundary_and_scene_layer_counts() {
1708        let mut frame = SceneFrame::new(WindowId::new(18), Size::new(320.0, 180.0));
1709        frame.scene.push(SceneCommand::Layer(SceneLayer::new(
1710            WidgetId::new(20),
1711            Rect::new(0.0, 0.0, 120.0, 80.0),
1712            Scene::new(),
1713        )));
1714        frame
1715            .scene
1716            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1717                SceneLayerDescriptor::new(
1718                    WidgetId::new(21).into(),
1719                    WidgetId::new(21),
1720                    Rect::new(12.0, 10.0, 80.0, 48.0),
1721                )
1722                .with_is_stack_surface(true),
1723                Scene::new(),
1724            )));
1725        frame
1726            .scene
1727            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1728                SceneLayerDescriptor::new(
1729                    WidgetId::new(22).into(),
1730                    WidgetId::new(22),
1731                    Rect::new(24.0, 20.0, 64.0, 40.0),
1732                )
1733                .with_composition_mode(LayerCompositionMode::Overlay),
1734                Scene::new(),
1735            )));
1736
1737        let stats =
1738            SceneStatistics::from_frame_with_mode(&frame, 7, SceneStatisticsDetailMode::Detailed);
1739
1740        assert_eq!(stats.total_widget_count, 7);
1741        assert_eq!(stats.repaint_boundary_count, 3);
1742        assert_eq!(stats.scene_layer_count, 3);
1743        assert_eq!(stats.stack_surface_count, 1);
1744        assert_eq!(stats.overlay_layer_count, 1);
1745        assert!(stats.command_breakdown.contains(&("Layer".to_string(), 3)));
1746    }
1747
1748    #[test]
1749    fn scene_statistics_detail_mode_defaults_to_lightweight() {
1750        let window_id = WindowId::new(77);
1751        assert_eq!(
1752            window_scene_statistics_detail_mode(window_id),
1753            SceneStatisticsDetailMode::Lightweight
1754        );
1755
1756        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
1757        assert_eq!(
1758            window_scene_statistics_detail_mode(window_id),
1759            SceneStatisticsDetailMode::Detailed
1760        );
1761
1762        clear_window_performance_snapshot(window_id);
1763        assert_eq!(
1764            window_scene_statistics_detail_mode(window_id),
1765            SceneStatisticsDetailMode::Lightweight
1766        );
1767    }
1768
1769    #[test]
1770    fn window_render_options_are_clamped_and_cleared_with_window_state() {
1771        let window_id = WindowId::new(91);
1772
1773        set_window_render_options(
1774            window_id,
1775            WindowRenderOptions::new(false, -2.0)
1776                .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1777                .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1778                .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1779                .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1780                .with_text_coverage_policy(WindowTextCoveragePolicy::Gamma(-2.0))
1781                .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1782                .with_sdr_content_brightness_nits(-25.0),
1783        );
1784
1785        assert_eq!(
1786            window_render_options(window_id),
1787            Some(
1788                WindowRenderOptions::new(false, 0.0)
1789                    .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1790                    .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1791                    .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1792                    .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1793                    .with_text_coverage_policy(WindowTextCoveragePolicy::Linear)
1794                    .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1795                    .with_sdr_content_brightness_nits(203.0)
1796            )
1797        );
1798
1799        set_window_render_options(
1800            window_id,
1801            WindowRenderOptions::new(true, 1.0)
1802                .with_optical_vertical_text_alignment_enabled(false)
1803                .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1804                .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1805                .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1806                .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1807                .with_text_coverage_policy(WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq),
1808        );
1809
1810        assert_eq!(
1811            window_render_options(window_id),
1812            Some(
1813                WindowRenderOptions::new(true, 1.0)
1814                    .with_optical_vertical_text_alignment_enabled(false)
1815                    .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1816                    .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1817                    .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1818                    .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1819                    .with_text_coverage_policy(
1820                        WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq
1821                    )
1822            )
1823        );
1824
1825        clear_window_performance_snapshot(window_id);
1826
1827        assert_eq!(window_render_options(window_id), None);
1828    }
1829
1830    #[test]
1831    fn window_render_options_default_to_slight_text_hinting() {
1832        let options = WindowRenderOptions::new(true, 1.0);
1833        assert_eq!(
1834            options.text_hinting,
1835            WindowTextHinting::Slight {
1836                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM
1837            }
1838        );
1839        assert_eq!(
1840            options.text_coverage_policy,
1841            WindowTextCoveragePolicy::Perceptual
1842        );
1843        assert_eq!(options.text_subpixel_order, WindowTextSubpixelOrder::None);
1844    }
1845}