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