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