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    pub output_color_primaries: WindowOutputColorPrimaries,
713    pub dynamic_range_mode: WindowDynamicRangeMode,
714    pub tone_mapping_mode: WindowToneMappingMode,
715    pub color_management_mode: WindowColorManagementMode,
716    pub sdr_content_brightness_nits: f32,
717    pub use_system_sdr_content_brightness: bool,
718}
719
720impl WindowRenderOptions {
721    pub const fn new(feathering_enabled: bool, feather_width: f32) -> Self {
722        Self {
723            feathering_enabled,
724            feather_width,
725            optical_vertical_text_alignment_enabled: true,
726            text_hinting: WindowTextHinting::Slight {
727                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM,
728            },
729            stem_darkening: WindowStemDarkening::None,
730            text_coverage_policy: WindowTextCoveragePolicy::Perceptual,
731            text_subpixel_order: WindowTextSubpixelOrder::None,
732            output_color_primaries: WindowOutputColorPrimaries::Automatic,
733            dynamic_range_mode: WindowDynamicRangeMode::Automatic,
734            tone_mapping_mode: WindowToneMappingMode::Automatic,
735            color_management_mode: WindowColorManagementMode::Automatic,
736            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
737            use_system_sdr_content_brightness: true,
738        }
739    }
740
741    pub const fn with_optical_vertical_text_alignment_enabled(mut self, enabled: bool) -> Self {
742        self.optical_vertical_text_alignment_enabled = enabled;
743        self
744    }
745
746    pub const fn with_text_hinting(mut self, hinting: WindowTextHinting) -> Self {
747        self.text_hinting = hinting;
748        self
749    }
750
751    pub const fn with_stem_darkening(mut self, darkening: WindowStemDarkening) -> Self {
752        self.stem_darkening = darkening;
753        self
754    }
755
756    pub const fn with_text_coverage_policy(mut self, policy: WindowTextCoveragePolicy) -> Self {
757        self.text_coverage_policy = policy;
758        self
759    }
760
761    pub const fn with_text_subpixel_order(mut self, order: WindowTextSubpixelOrder) -> Self {
762        self.text_subpixel_order = order;
763        self
764    }
765
766    pub const fn with_output_color_primaries(
767        mut self,
768        primaries: WindowOutputColorPrimaries,
769    ) -> Self {
770        self.output_color_primaries = primaries;
771        self
772    }
773
774    pub const fn with_dynamic_range_mode(mut self, mode: WindowDynamicRangeMode) -> Self {
775        self.dynamic_range_mode = mode;
776        self
777    }
778
779    pub const fn with_tone_mapping_mode(mut self, mode: WindowToneMappingMode) -> Self {
780        self.tone_mapping_mode = mode;
781        self
782    }
783
784    pub const fn with_color_management_mode(mut self, mode: WindowColorManagementMode) -> Self {
785        self.color_management_mode = mode;
786        self
787    }
788
789    pub const fn with_sdr_content_brightness_nits(mut self, brightness_nits: f32) -> Self {
790        self.sdr_content_brightness_nits = brightness_nits;
791        self
792    }
793
794    pub const fn with_system_sdr_content_brightness_enabled(mut self, enabled: bool) -> Self {
795        self.use_system_sdr_content_brightness = enabled;
796        self
797    }
798
799    pub fn clamped(self) -> Self {
800        Self {
801            feathering_enabled: self.feathering_enabled,
802            feather_width: self.feather_width.max(0.0),
803            optical_vertical_text_alignment_enabled: self.optical_vertical_text_alignment_enabled,
804            text_hinting: self.text_hinting.normalized(),
805            stem_darkening: self.stem_darkening.normalized(),
806            text_coverage_policy: self.text_coverage_policy.normalized(),
807            text_subpixel_order: self.text_subpixel_order,
808            output_color_primaries: self.output_color_primaries,
809            dynamic_range_mode: self.dynamic_range_mode,
810            tone_mapping_mode: self.tone_mapping_mode,
811            color_management_mode: self.color_management_mode,
812            sdr_content_brightness_nits: if self.sdr_content_brightness_nits.is_finite()
813                && self.sdr_content_brightness_nits > 0.0
814            {
815                self.sdr_content_brightness_nits
816            } else {
817                DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
818            },
819            use_system_sdr_content_brightness: self.use_system_sdr_content_brightness,
820        }
821    }
822}
823
824#[derive(Debug, Clone, Copy, PartialEq, Default)]
825pub struct WindowPerformanceSummary {
826    pub window_id: WindowId,
827    pub frame_index: u64,
828    pub total_time_ms: f64,
829    pub frame_interval_ms: Option<f64>,
830    pub slowest_phase: Option<FramePhaseSample>,
831    pub presentation_latency: PresentationLatencyDiagnostics,
832    pub renderer_submission: RendererSubmissionDiagnostics,
833    pub text_caches: TextCacheDiagnostics,
834    pub total_widget_count: usize,
835    pub active_animated_widget_count: usize,
836    pub animation_frame_wake_count: usize,
837    pub animation_repaint_frame_count: usize,
838    pub animation_transform_effect_only_frame_count: usize,
839    pub repaint_boundary_count: usize,
840    pub scene_layer_count: usize,
841    pub stack_surface_count: usize,
842    pub overlay_layer_count: usize,
843    pub dirty_region_count: usize,
844    pub dirty_coverage: f32,
845    pub command_count: usize,
846}
847
848#[derive(Debug, Clone, PartialEq)]
849pub struct SceneStatistics {
850    pub detail_mode: SceneStatisticsDetailMode,
851    pub viewport: Size,
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 dirty_region_count: usize,
858    pub dirty_regions: Vec<DirtyRegion>,
859    pub dirty_area: f32,
860    pub dirty_coverage: f32,
861    pub command_count: usize,
862    pub command_breakdown: Vec<(String, usize)>,
863    /// Current repaint granularity as observed by the runtime today.
864    ///
865    /// During the layer-boundary transition this still tracks emitted scene
866    /// layers, because the runtime has not yet decoupled explicit repaint
867    /// boundaries from per-widget `SceneLayer` emission.
868    pub repaint_boundary_count: usize,
869    pub scene_layer_count: usize,
870    pub stack_surface_count: usize,
871    pub overlay_layer_count: usize,
872    pub layer_update_count: usize,
873    pub layer_update_breakdown: Vec<(String, usize)>,
874    pub text_command_count: usize,
875    pub image_command_count: usize,
876    pub clip_command_count: usize,
877    pub transform_command_count: usize,
878}
879
880impl SceneStatistics {
881    pub fn with_animation_counters(
882        mut self,
883        active_animated_widget_count: usize,
884        animation_frame_wake_count: usize,
885        animation_repaint_frame_count: usize,
886        animation_transform_effect_only_frame_count: usize,
887    ) -> Self {
888        self.active_animated_widget_count = active_animated_widget_count;
889        self.animation_frame_wake_count = animation_frame_wake_count;
890        self.animation_repaint_frame_count = animation_repaint_frame_count;
891        self.animation_transform_effect_only_frame_count =
892            animation_transform_effect_only_frame_count;
893        self
894    }
895
896    pub fn from_frame(frame: &SceneFrame, total_widget_count: usize) -> Self {
897        Self::from_frame_with_mode(
898            frame,
899            total_widget_count,
900            SceneStatisticsDetailMode::Lightweight,
901        )
902    }
903
904    pub fn minimal(
905        frame: &SceneFrame,
906        total_widget_count: usize,
907        detail_mode: SceneStatisticsDetailMode,
908    ) -> Self {
909        let layer_totals = scene_layer_totals(frame);
910        Self {
911            detail_mode,
912            viewport: frame.viewport,
913            total_widget_count,
914            active_animated_widget_count: 0,
915            animation_frame_wake_count: 0,
916            animation_repaint_frame_count: 0,
917            animation_transform_effect_only_frame_count: 0,
918            dirty_region_count: 0,
919            dirty_regions: Vec::new(),
920            dirty_area: 0.0,
921            dirty_coverage: 0.0,
922            command_count: 0,
923            command_breakdown: Vec::new(),
924            repaint_boundary_count: layer_totals.repaint_boundary_count,
925            scene_layer_count: layer_totals.scene_layer_count,
926            stack_surface_count: layer_totals.stack_surface_count,
927            overlay_layer_count: layer_totals.overlay_layer_count,
928            layer_update_count: 0,
929            layer_update_breakdown: Vec::new(),
930            text_command_count: 0,
931            image_command_count: 0,
932            clip_command_count: 0,
933            transform_command_count: 0,
934        }
935    }
936
937    pub fn from_frame_with_mode(
938        frame: &SceneFrame,
939        total_widget_count: usize,
940        detail_mode: SceneStatisticsDetailMode,
941    ) -> Self {
942        let detailed = detail_mode.is_detailed();
943        let mut command_breakdown = detailed.then(BTreeMap::<String, usize>::new);
944        let mut text_command_count = 0usize;
945        let mut image_command_count = 0usize;
946        let mut clip_command_count = 0usize;
947        let mut transform_command_count = 0usize;
948        let mut command_count = 0usize;
949
950        frame.scene.visit_commands(&mut |command| {
951            command_count += 1;
952            if let Some(breakdown) = &mut command_breakdown {
953                *breakdown
954                    .entry(command_kind(command).to_string())
955                    .or_default() += 1;
956            }
957
958            match command {
959                SceneCommand::DrawText(_)
960                | SceneCommand::DrawShapedText(_)
961                | SceneCommand::DrawShapedTextWindow(_)
962                | SceneCommand::Label { .. } => {
963                    text_command_count += 1;
964                }
965                SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => {
966                    image_command_count += 1;
967                }
968                SceneCommand::PushClip { .. }
969                | SceneCommand::PushClipPath { .. }
970                | SceneCommand::PopClip => {
971                    clip_command_count += 1;
972                }
973                SceneCommand::PushTransform { .. } | SceneCommand::PopTransform => {
974                    transform_command_count += 1;
975                }
976                SceneCommand::Clear(_)
977                | SceneCommand::FillRect { .. }
978                | SceneCommand::StrokeRect { .. }
979                | SceneCommand::FillPath { .. }
980                | SceneCommand::StrokePath { .. }
981                | SceneCommand::DrawShaderRect { .. }
982                | SceneCommand::FillRoundedRect { .. }
983                | SceneCommand::PushTextRenderPolicy { .. }
984                | SceneCommand::PopTextRenderPolicy
985                | SceneCommand::Layer(_) => {}
986            }
987        });
988
989        let mut layer_update_breakdown = detailed.then(BTreeMap::<String, usize>::new);
990        if let Some(breakdown) = &mut layer_update_breakdown {
991            for update in &frame.layer_updates {
992                *breakdown
993                    .entry(layer_update_kind(update.kind).to_string())
994                    .or_default() += 1;
995            }
996        }
997
998        let dirty_area: f32 = frame
999            .dirty_regions
1000            .iter()
1001            .map(|region| region.area.width().max(0.0) * region.area.height().max(0.0))
1002            .sum();
1003        let viewport_area = frame.viewport.width.max(0.0) * frame.viewport.height.max(0.0);
1004        let dirty_coverage = if viewport_area > 0.0 {
1005            ((dirty_area / viewport_area) * 100.0).min(100.0)
1006        } else {
1007            0.0
1008        };
1009        let dirty_region_count = frame.dirty_regions.len();
1010        let layer_totals = scene_layer_totals(frame);
1011
1012        Self {
1013            detail_mode,
1014            viewport: frame.viewport,
1015            total_widget_count,
1016            active_animated_widget_count: 0,
1017            animation_frame_wake_count: 0,
1018            animation_repaint_frame_count: 0,
1019            animation_transform_effect_only_frame_count: 0,
1020            dirty_region_count,
1021            dirty_regions: if detailed {
1022                frame.dirty_regions.clone()
1023            } else {
1024                Vec::new()
1025            },
1026            dirty_area,
1027            dirty_coverage,
1028            command_count,
1029            command_breakdown: command_breakdown
1030                .map(|breakdown| breakdown.into_iter().collect())
1031                .unwrap_or_default(),
1032            repaint_boundary_count: layer_totals.repaint_boundary_count,
1033            scene_layer_count: layer_totals.scene_layer_count,
1034            stack_surface_count: layer_totals.stack_surface_count,
1035            overlay_layer_count: layer_totals.overlay_layer_count,
1036            layer_update_count: frame.layer_updates.len(),
1037            layer_update_breakdown: layer_update_breakdown
1038                .map(|breakdown| breakdown.into_iter().collect())
1039                .unwrap_or_default(),
1040            text_command_count,
1041            image_command_count,
1042            clip_command_count,
1043            transform_command_count,
1044        }
1045    }
1046}
1047
1048#[derive(Debug, Clone, Copy, Default)]
1049struct SceneLayerTotals {
1050    repaint_boundary_count: usize,
1051    scene_layer_count: usize,
1052    stack_surface_count: usize,
1053    overlay_layer_count: usize,
1054}
1055
1056fn scene_layer_totals(frame: &SceneFrame) -> SceneLayerTotals {
1057    let mut totals = SceneLayerTotals::default();
1058    frame.scene.visit_layers(&mut |layer| {
1059        totals.scene_layer_count += 1;
1060        if layer.descriptor.is_stack_surface {
1061            totals.stack_surface_count += 1;
1062        }
1063        if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
1064            totals.overlay_layer_count += 1;
1065        }
1066    });
1067    // Current runtime behavior still uses emitted scene layers as repaint
1068    // granularity. Keep the two metrics separate in the API so later slices can
1069    // decouple them without another diagnostics rename, but document the
1070    // equality clearly for this transitional phase.
1071    totals.repaint_boundary_count = totals.scene_layer_count;
1072    totals
1073}
1074
1075#[derive(Debug, Clone, PartialEq)]
1076pub struct WindowPerformanceSnapshot {
1077    pub window_id: WindowId,
1078    pub frame_index: u64,
1079    pub total_time_ms: f64,
1080    /// Wall time between completed host frames, including pacing and idle time.
1081    /// This measures host frame cadence, not GPU execution or physical scanout.
1082    /// Unavailable for the first frame or after the frame counter restarts.
1083    pub frame_interval_ms: Option<f64>,
1084    pub phase_timings: Vec<FramePhaseSample>,
1085    pub presentation_latency: PresentationLatencyDiagnostics,
1086    pub renderer_submission: RendererSubmissionDiagnostics,
1087    pub text_caches: TextCacheDiagnostics,
1088    pub text_cache_deltas: TextCacheDeltaDiagnostics,
1089    pub runtime_text_timing: RuntimeTextTimingDiagnostics,
1090    pub widget_timings: Vec<WidgetTimingSample>,
1091    pub command_dispatches: Vec<CommandDispatchSample>,
1092    pub invalidations: Vec<InvalidationTraceSample>,
1093    pub retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
1094    pub scene: SceneStatistics,
1095}
1096
1097impl WindowPerformanceSnapshot {
1098    pub fn new(
1099        window_id: WindowId,
1100        frame_index: u64,
1101        phase_timings: Vec<FramePhaseSample>,
1102        renderer_submission: RendererSubmissionDiagnostics,
1103        text_caches: TextCacheDiagnostics,
1104        text_cache_deltas: TextCacheDeltaDiagnostics,
1105        scene: SceneStatistics,
1106    ) -> Self {
1107        let total_time_ms = phase_timings.iter().map(|sample| sample.duration_ms).sum();
1108
1109        Self::with_total_time_ms(
1110            window_id,
1111            frame_index,
1112            total_time_ms,
1113            phase_timings,
1114            renderer_submission,
1115            text_caches,
1116            text_cache_deltas,
1117            scene,
1118        )
1119    }
1120
1121    pub fn with_total_time_ms(
1122        window_id: WindowId,
1123        frame_index: u64,
1124        total_time_ms: f64,
1125        phase_timings: Vec<FramePhaseSample>,
1126        renderer_submission: RendererSubmissionDiagnostics,
1127        text_caches: TextCacheDiagnostics,
1128        text_cache_deltas: TextCacheDeltaDiagnostics,
1129        scene: SceneStatistics,
1130    ) -> Self {
1131        Self {
1132            window_id,
1133            frame_index,
1134            total_time_ms,
1135            frame_interval_ms: None,
1136            phase_timings,
1137            presentation_latency: PresentationLatencyDiagnostics::default(),
1138            renderer_submission,
1139            text_caches,
1140            text_cache_deltas,
1141            runtime_text_timing: RuntimeTextTimingDiagnostics::default(),
1142            widget_timings: Vec::new(),
1143            command_dispatches: Vec::new(),
1144            invalidations: Vec::new(),
1145            retained_packet_hotspot: None,
1146            scene,
1147        }
1148    }
1149
1150    pub fn with_presentation_latency(
1151        mut self,
1152        presentation_latency: PresentationLatencyDiagnostics,
1153    ) -> Self {
1154        self.presentation_latency = presentation_latency;
1155        self
1156    }
1157
1158    pub fn with_widget_timings(mut self, widget_timings: Vec<WidgetTimingSample>) -> Self {
1159        self.widget_timings = widget_timings;
1160        self
1161    }
1162
1163    pub fn with_event_traces(
1164        mut self,
1165        command_dispatches: Vec<CommandDispatchSample>,
1166        invalidations: Vec<InvalidationTraceSample>,
1167    ) -> Self {
1168        self.command_dispatches = command_dispatches;
1169        self.invalidations = invalidations;
1170        self
1171    }
1172
1173    pub fn with_runtime_text_timing(
1174        mut self,
1175        runtime_text_timing: RuntimeTextTimingDiagnostics,
1176    ) -> Self {
1177        self.runtime_text_timing = runtime_text_timing;
1178        self
1179    }
1180
1181    pub fn with_retained_packet_hotspot(
1182        mut self,
1183        retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
1184    ) -> Self {
1185        self.retained_packet_hotspot = retained_packet_hotspot;
1186        self
1187    }
1188
1189    pub fn slowest_phase(&self) -> Option<FramePhaseSample> {
1190        self.phase_timings
1191            .iter()
1192            .copied()
1193            .max_by(|left, right| left.duration_ms.total_cmp(&right.duration_ms))
1194    }
1195
1196    pub fn summary(&self) -> WindowPerformanceSummary {
1197        WindowPerformanceSummary {
1198            window_id: self.window_id,
1199            frame_index: self.frame_index,
1200            total_time_ms: self.total_time_ms,
1201            frame_interval_ms: self.frame_interval_ms,
1202            slowest_phase: self.slowest_phase(),
1203            presentation_latency: self.presentation_latency,
1204            renderer_submission: self.renderer_submission,
1205            text_caches: self.text_caches,
1206            total_widget_count: self.scene.total_widget_count,
1207            active_animated_widget_count: self.scene.active_animated_widget_count,
1208            animation_frame_wake_count: self.scene.animation_frame_wake_count,
1209            animation_repaint_frame_count: self.scene.animation_repaint_frame_count,
1210            animation_transform_effect_only_frame_count: self
1211                .scene
1212                .animation_transform_effect_only_frame_count,
1213            repaint_boundary_count: self.scene.repaint_boundary_count,
1214            scene_layer_count: self.scene.scene_layer_count,
1215            stack_surface_count: self.scene.stack_surface_count,
1216            overlay_layer_count: self.scene.overlay_layer_count,
1217            dirty_region_count: self.scene.dirty_region_count,
1218            dirty_coverage: self.scene.dirty_coverage,
1219            command_count: self.scene.command_count,
1220        }
1221    }
1222}
1223
1224struct WindowPerformanceRecord {
1225    snapshot: WindowPerformanceSnapshot,
1226    completed_at: Instant,
1227}
1228
1229impl WindowPerformanceRecord {
1230    fn new(mut snapshot: WindowPerformanceSnapshot, completed_at: Instant) -> Self {
1231        snapshot.frame_interval_ms = None;
1232        Self {
1233            snapshot,
1234            completed_at,
1235        }
1236    }
1237
1238    fn update(&mut self, mut snapshot: WindowPerformanceSnapshot, completed_at: Instant) {
1239        if snapshot.frame_index == self.snapshot.frame_index {
1240            // Refreshing diagnostics for one frame must not advance the clock.
1241            snapshot.frame_interval_ms = self.snapshot.frame_interval_ms;
1242        } else {
1243            snapshot.frame_interval_ms = (snapshot.frame_index > self.snapshot.frame_index)
1244                .then(|| {
1245                    completed_at.duration_since(self.completed_at).as_secs_f64() * 1000.0
1246                        / (snapshot.frame_index - self.snapshot.frame_index) as f64
1247                })
1248                .filter(|interval| *interval > 0.0);
1249            self.completed_at = completed_at;
1250        }
1251        self.snapshot = snapshot;
1252    }
1253}
1254
1255static WINDOW_PERFORMANCE_SNAPSHOTS: OnceLock<RwLock<HashMap<WindowId, WindowPerformanceRecord>>> =
1256    OnceLock::new();
1257static WINDOW_SCENE_STATISTICS_DETAIL_MODES: OnceLock<
1258    RwLock<HashMap<WindowId, SceneStatisticsDetailMode>>,
1259> = OnceLock::new();
1260static WINDOW_RENDER_OPTIONS: OnceLock<RwLock<HashMap<WindowId, WindowRenderOptions>>> =
1261    OnceLock::new();
1262
1263pub fn publish_window_performance_snapshot(snapshot: WindowPerformanceSnapshot) {
1264    let completed_at = Instant::now();
1265    let mut store = window_performance_store()
1266        .write()
1267        .expect("window performance snapshot store lock should not be poisoned");
1268    match store.entry(snapshot.window_id) {
1269        std::collections::hash_map::Entry::Occupied(mut entry) => {
1270            entry.get_mut().update(snapshot, completed_at);
1271        }
1272        std::collections::hash_map::Entry::Vacant(entry) => {
1273            entry.insert(WindowPerformanceRecord::new(snapshot, completed_at));
1274        }
1275    }
1276}
1277
1278pub fn window_performance_snapshot(window_id: WindowId) -> Option<WindowPerformanceSnapshot> {
1279    let store = window_performance_store()
1280        .read()
1281        .expect("window performance snapshot store lock should not be poisoned");
1282    store.get(&window_id).map(|record| record.snapshot.clone())
1283}
1284
1285pub fn window_performance_summary(window_id: WindowId) -> Option<WindowPerformanceSummary> {
1286    let store = window_performance_store()
1287        .read()
1288        .expect("window performance snapshot store lock should not be poisoned");
1289    store
1290        .get(&window_id)
1291        .map(|record| record.snapshot.summary())
1292}
1293
1294pub fn window_performance_text_caches(window_id: WindowId) -> Option<TextCacheDiagnostics> {
1295    let store = window_performance_store()
1296        .read()
1297        .expect("window performance snapshot store lock should not be poisoned");
1298    store
1299        .get(&window_id)
1300        .map(|record| record.snapshot.text_caches)
1301}
1302
1303pub fn set_window_scene_statistics_detail_mode(
1304    window_id: WindowId,
1305    detail_mode: SceneStatisticsDetailMode,
1306) {
1307    let mut store = window_scene_statistics_detail_mode_store()
1308        .write()
1309        .expect("scene statistics detail mode store lock should not be poisoned");
1310    if detail_mode == SceneStatisticsDetailMode::Lightweight {
1311        store.remove(&window_id);
1312    } else {
1313        store.insert(window_id, detail_mode);
1314    }
1315}
1316
1317pub fn window_scene_statistics_detail_mode(window_id: WindowId) -> SceneStatisticsDetailMode {
1318    let store = window_scene_statistics_detail_mode_store()
1319        .read()
1320        .expect("scene statistics detail mode store lock should not be poisoned");
1321    store.get(&window_id).copied().unwrap_or_default()
1322}
1323
1324pub fn set_window_render_options(window_id: WindowId, options: WindowRenderOptions) {
1325    let mut store = window_render_options_store()
1326        .write()
1327        .expect("window render options store lock should not be poisoned");
1328    store.insert(window_id, options.clamped());
1329}
1330
1331pub fn window_render_options(window_id: WindowId) -> Option<WindowRenderOptions> {
1332    let store = window_render_options_store()
1333        .read()
1334        .expect("window render options store lock should not be poisoned");
1335    store.get(&window_id).copied()
1336}
1337
1338pub fn clear_window_render_options(window_id: WindowId) {
1339    let mut store = window_render_options_store()
1340        .write()
1341        .expect("window render options store lock should not be poisoned");
1342    store.remove(&window_id);
1343}
1344
1345pub fn clear_window_performance_snapshot(window_id: WindowId) {
1346    let mut store = window_performance_store()
1347        .write()
1348        .expect("window performance snapshot store lock should not be poisoned");
1349    store.remove(&window_id);
1350
1351    let mut detail_modes = window_scene_statistics_detail_mode_store()
1352        .write()
1353        .expect("scene statistics detail mode store lock should not be poisoned");
1354    detail_modes.remove(&window_id);
1355
1356    clear_window_render_options(window_id);
1357    crate::output_range::clear_window_output_color_range(window_id);
1358    crate::command_history::clear_window_command_dispatches(window_id);
1359}
1360
1361pub fn clear_window_performance_snapshots() {
1362    let mut store = window_performance_store()
1363        .write()
1364        .expect("window performance snapshot store lock should not be poisoned");
1365    store.clear();
1366
1367    let mut detail_modes = window_scene_statistics_detail_mode_store()
1368        .write()
1369        .expect("scene statistics detail mode store lock should not be poisoned");
1370    detail_modes.clear();
1371
1372    let mut render_options = window_render_options_store()
1373        .write()
1374        .expect("window render options store lock should not be poisoned");
1375    render_options.clear();
1376    drop(render_options);
1377    crate::output_range::clear_window_output_color_ranges();
1378}
1379
1380fn window_performance_store() -> &'static RwLock<HashMap<WindowId, WindowPerformanceRecord>> {
1381    WINDOW_PERFORMANCE_SNAPSHOTS.get_or_init(|| RwLock::new(HashMap::new()))
1382}
1383
1384fn window_scene_statistics_detail_mode_store()
1385-> &'static RwLock<HashMap<WindowId, SceneStatisticsDetailMode>> {
1386    WINDOW_SCENE_STATISTICS_DETAIL_MODES.get_or_init(|| RwLock::new(HashMap::new()))
1387}
1388
1389fn window_render_options_store() -> &'static RwLock<HashMap<WindowId, WindowRenderOptions>> {
1390    WINDOW_RENDER_OPTIONS.get_or_init(|| RwLock::new(HashMap::new()))
1391}
1392
1393fn command_kind(command: &SceneCommand) -> &'static str {
1394    match command {
1395        SceneCommand::Clear(_) => "Clear",
1396        SceneCommand::FillRect { .. } => "FillRect",
1397        SceneCommand::StrokeRect { .. } => "StrokeRect",
1398        SceneCommand::FillPath { .. } => "FillPath",
1399        SceneCommand::StrokePath { .. } => "StrokePath",
1400        SceneCommand::DrawText(_) => "DrawText",
1401        SceneCommand::DrawShapedText(_) => "DrawShapedText",
1402        SceneCommand::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
1403        SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => "DrawImage",
1404        SceneCommand::DrawShaderRect { .. } => "DrawShaderRect",
1405        SceneCommand::PushClip { .. } => "PushClip",
1406        SceneCommand::PushClipPath { .. } => "PushClipPath",
1407        SceneCommand::PopClip => "PopClip",
1408        SceneCommand::PushTransform { .. } => "PushTransform",
1409        SceneCommand::PopTransform => "PopTransform",
1410        SceneCommand::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
1411        SceneCommand::PopTextRenderPolicy => "PopTextRenderPolicy",
1412        SceneCommand::Layer(_) => "Layer",
1413        SceneCommand::FillRoundedRect { .. } => "FillRoundedRect",
1414        SceneCommand::Label { .. } => "Label",
1415    }
1416}
1417
1418fn layer_update_kind(kind: SceneLayerUpdateKind) -> &'static str {
1419    match kind {
1420        SceneLayerUpdateKind::Ordering => "Ordering",
1421        SceneLayerUpdateKind::Content => "Content",
1422        SceneLayerUpdateKind::Transform => "Transform",
1423        SceneLayerUpdateKind::Clip => "Clip",
1424        SceneLayerUpdateKind::Effect => "Effect",
1425        SceneLayerUpdateKind::Visibility => "Visibility",
1426        SceneLayerUpdateKind::Resources => "Resources",
1427    }
1428}
1429
1430#[cfg(test)]
1431mod tests {
1432    use super::{
1433        CacheMetrics, DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM, FramePhase, FramePhaseSample,
1434        RendererSubmissionDiagnostics, RetainedPacketRebuildDiagnostics, SceneStatistics,
1435        SceneStatisticsDetailMode, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
1436        WindowColorManagementMode, WindowDynamicRangeMode, WindowOutputColorPrimaries,
1437        WindowPerformanceSnapshot, WindowRenderOptions, WindowTextCoveragePolicy,
1438        WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
1439        clear_window_performance_snapshot, set_window_render_options,
1440        set_window_scene_statistics_detail_mode, window_render_options,
1441        window_scene_statistics_detail_mode,
1442    };
1443    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, Size, WidgetId, WindowId};
1444    use sui_scene::{
1445        LayerCompositionMode, Scene, SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor,
1446    };
1447
1448    #[test]
1449    fn frame_cadence_includes_pacing_and_ignores_duplicate_publications() {
1450        let window_id = WindowId::new(12);
1451        let snapshot = |frame_index| {
1452            WindowPerformanceSnapshot::new(
1453                window_id,
1454                frame_index,
1455                vec![FramePhaseSample::new(FramePhase::Renderer, 2.0)],
1456                RendererSubmissionDiagnostics::default(),
1457                TextCacheDiagnostics::default(),
1458                TextCacheDeltaDiagnostics::default(),
1459                SceneStatistics::minimal(
1460                    &SceneFrame::new(window_id, Size::new(320.0, 180.0)),
1461                    1,
1462                    SceneStatisticsDetailMode::Lightweight,
1463                ),
1464            )
1465        };
1466        let start = web_time::Instant::now();
1467        let at = |milliseconds| start + std::time::Duration::from_millis(milliseconds);
1468        let mut record = super::WindowPerformanceRecord::new(snapshot(1), start);
1469        assert_eq!(record.snapshot.frame_interval_ms, None);
1470        record.update(snapshot(2), at(50));
1471        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
1472        assert_eq!(
1473            record.snapshot.total_time_ms, 2.0,
1474            "render work remains separate from cadence"
1475        );
1476        assert_eq!(record.snapshot.summary().frame_interval_ms, Some(50.0));
1477        record.update(snapshot(2), at(60));
1478        record.update(snapshot(3), at(100));
1479        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
1480        record.update(snapshot(1), at(150));
1481        assert_eq!(
1482            record.snapshot.frame_interval_ms, None,
1483            "a restarted window needs a fresh baseline"
1484        );
1485        record.update(snapshot(4), at(300));
1486        assert_eq!(
1487            record.snapshot.frame_interval_ms,
1488            Some(50.0),
1489            "skipped publications use the frame-count delta"
1490        );
1491    }
1492
1493    #[test]
1494    fn text_cache_deltas_are_derived_from_prior_counters() {
1495        let previous = TextCacheDiagnostics {
1496            runtime_layout: CacheMetrics::new(2, 10, 4),
1497            renderer_layout: CacheMetrics::new(3, 6, 2),
1498            renderer_glyph: CacheMetrics::new(5, 12, 3),
1499            renderer_path: CacheMetrics::new(7, 14, 5),
1500        };
1501        let current = TextCacheDiagnostics {
1502            runtime_layout: CacheMetrics::new(4, 15, 6),
1503            renderer_layout: CacheMetrics::new(3, 9, 3),
1504            renderer_glyph: CacheMetrics::new(7, 18, 5),
1505            renderer_path: CacheMetrics::new(8, 21, 6),
1506        };
1507
1508        let delta = current.delta_from(&previous);
1509
1510        assert_eq!(delta.runtime_layout.entries_delta, 2);
1511        assert_eq!(delta.runtime_layout.hits, 5);
1512        assert_eq!(delta.runtime_layout.misses, 2);
1513        assert_eq!(delta.renderer_layout.entries_delta, 0);
1514        assert_eq!(delta.renderer_layout.hits, 3);
1515        assert_eq!(delta.renderer_layout.misses, 1);
1516        assert_eq!(delta.renderer_glyph.entries_delta, 2);
1517        assert_eq!(delta.renderer_glyph.hits, 6);
1518        assert_eq!(delta.renderer_glyph.misses, 2);
1519        assert_eq!(delta.renderer_path.entries_delta, 1);
1520        assert_eq!(delta.renderer_path.hits, 7);
1521        assert_eq!(delta.renderer_path.misses, 1);
1522    }
1523
1524    #[test]
1525    fn scene_statistics_diagnostics_minimal_preserves_split_count_totals() {
1526        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1527        frame
1528            .scene
1529            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1530                SceneLayerDescriptor::new(
1531                    WidgetId::new(10).into(),
1532                    WidgetId::new(10),
1533                    Rect::new(0.0, 0.0, 120.0, 80.0),
1534                )
1535                .with_is_stack_surface(true),
1536                Scene::new(),
1537            )));
1538        frame
1539            .scene
1540            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1541                SceneLayerDescriptor::new(
1542                    WidgetId::new(11).into(),
1543                    WidgetId::new(11),
1544                    Rect::new(12.0, 10.0, 80.0, 48.0),
1545                )
1546                .with_composition_mode(LayerCompositionMode::Overlay),
1547                Scene::new(),
1548            )));
1549
1550        let stats = SceneStatistics::minimal(&frame, 5, SceneStatisticsDetailMode::Lightweight);
1551
1552        assert_eq!(stats.total_widget_count, 5);
1553        assert_eq!(stats.repaint_boundary_count, 2);
1554        assert_eq!(stats.scene_layer_count, 2);
1555        assert_eq!(stats.stack_surface_count, 1);
1556        assert_eq!(stats.overlay_layer_count, 1);
1557        assert!(stats.command_breakdown.is_empty());
1558        assert!(stats.layer_update_breakdown.is_empty());
1559    }
1560
1561    #[test]
1562    fn window_performance_snapshot_preserves_renderer_submission_stats() {
1563        let snapshot = WindowPerformanceSnapshot::new(
1564            WindowId::new(5),
1565            17,
1566            vec![FramePhaseSample::new(FramePhase::Renderer, 2.5)],
1567            RendererSubmissionDiagnostics::new(
1568                3,
1569                9,
1570                4096,
1571                128,
1572                3584,
1573                4,
1574                7,
1575                230,
1576                90,
1577                310,
1578                120,
1579                2,
1580                RetainedPacketRebuildDiagnostics::new(1, 0, 1, 1, 0),
1581                5,
1582                80,
1583                440,
1584                210,
1585                130,
1586                15,
1587                95,
1588                4,
1589                32768,
1590                115,
1591                85,
1592                22,
1593                16384,
1594                920,
1595                640,
1596                180,
1597                70,
1598                560,
1599            ),
1600            TextCacheDiagnostics::default(),
1601            TextCacheDeltaDiagnostics::default(),
1602            SceneStatistics {
1603                detail_mode: SceneStatisticsDetailMode::Lightweight,
1604                viewport: Size::new(640.0, 360.0),
1605                total_widget_count: 9,
1606                active_animated_widget_count: 2,
1607                animation_frame_wake_count: 1,
1608                animation_repaint_frame_count: 1,
1609                animation_transform_effect_only_frame_count: 0,
1610                dirty_region_count: 0,
1611                dirty_regions: Vec::new(),
1612                dirty_area: 0.0,
1613                dirty_coverage: 0.0,
1614                command_count: 0,
1615                command_breakdown: Vec::new(),
1616                repaint_boundary_count: 4,
1617                scene_layer_count: 4,
1618                stack_surface_count: 1,
1619                overlay_layer_count: 1,
1620                layer_update_count: 0,
1621                layer_update_breakdown: Vec::new(),
1622                text_command_count: 0,
1623                image_command_count: 0,
1624                clip_command_count: 0,
1625                transform_command_count: 0,
1626            },
1627        );
1628
1629        assert_eq!(snapshot.renderer_submission.pass_count, 3);
1630        assert_eq!(snapshot.renderer_submission.draw_count, 9);
1631        assert_eq!(snapshot.renderer_submission.uploaded_vertex_bytes, 4096);
1632        assert_eq!(snapshot.renderer_submission.direct_packet_count, 7);
1633        assert_eq!(
1634            snapshot.renderer_submission.retained_state_update_time_us,
1635            230
1636        );
1637        assert_eq!(
1638            snapshot
1639                .renderer_submission
1640                .retained_scene_traversal_time_us,
1641            310
1642        );
1643        assert_eq!(
1644            snapshot.renderer_submission.retained_packet_build_time_us,
1645            120
1646        );
1647        assert_eq!(snapshot.renderer_submission.retained_packet_build_count, 2);
1648        assert_eq!(
1649            snapshot
1650                .renderer_submission
1651                .retained_packet_rebuilds
1652                .total_count(),
1653            3
1654        );
1655        assert_eq!(
1656            snapshot
1657                .renderer_submission
1658                .retained_packet_rebuilds
1659                .new_count,
1660            1
1661        );
1662        assert_eq!(
1663            snapshot
1664                .renderer_submission
1665                .retained_packet_rebuilds
1666                .signature_count,
1667            1
1668        );
1669        assert_eq!(
1670            snapshot
1671                .renderer_submission
1672                .retained_packet_rebuilds
1673                .scene_count,
1674            1
1675        );
1676        assert_eq!(snapshot.renderer_submission.text_atlas_miss_count, 5);
1677        assert_eq!(snapshot.renderer_submission.text_atlas_miss_time_us, 80);
1678        assert_eq!(snapshot.renderer_submission.surface_acquire_time_us, 440);
1679        assert_eq!(
1680            snapshot.renderer_submission.resource_collection_time_us,
1681            210
1682        );
1683        assert_eq!(snapshot.renderer_submission.bind_group_prepare_time_us, 130);
1684        assert_eq!(snapshot.renderer_submission.image_bind_group_time_us, 15);
1685        assert_eq!(
1686            snapshot
1687                .renderer_submission
1688                .analytic_path_bind_group_time_us,
1689            95
1690        );
1691        assert_eq!(
1692            snapshot
1693                .renderer_submission
1694                .analytic_path_bind_group_miss_count,
1695            4
1696        );
1697        assert_eq!(
1698            snapshot
1699                .renderer_submission
1700                .analytic_path_bind_group_upload_bytes,
1701            32768
1702        );
1703        assert_eq!(
1704            snapshot.renderer_submission.text_atlas_bind_group_time_us,
1705            115
1706        );
1707        assert_eq!(
1708            snapshot.renderer_submission.text_atlas_upload_copy_time_us,
1709            85
1710        );
1711        assert_eq!(
1712            snapshot.renderer_submission.text_atlas_upload_write_time_us,
1713            22
1714        );
1715        assert_eq!(snapshot.renderer_submission.text_atlas_upload_bytes, 16384);
1716        assert_eq!(snapshot.renderer_submission.batch_prepare_time_us, 920);
1717        assert_eq!(snapshot.renderer_submission.gpu_upload_time_us, 640);
1718        assert_eq!(snapshot.renderer_submission.pass_encode_time_us, 180);
1719        assert_eq!(snapshot.renderer_submission.queue_submit_time_us, 70);
1720        assert_eq!(snapshot.renderer_submission.surface_present_time_us, 560);
1721        assert_eq!(snapshot.total_time_ms, 2.5);
1722
1723        let summary = snapshot.summary();
1724        assert_eq!(summary.total_widget_count, 9);
1725        assert_eq!(summary.active_animated_widget_count, 2);
1726        assert_eq!(summary.animation_frame_wake_count, 1);
1727        assert_eq!(summary.animation_repaint_frame_count, 1);
1728        assert_eq!(summary.animation_transform_effect_only_frame_count, 0);
1729        assert_eq!(summary.repaint_boundary_count, 4);
1730        assert_eq!(summary.scene_layer_count, 4);
1731        assert_eq!(summary.stack_surface_count, 1);
1732        assert_eq!(summary.overlay_layer_count, 1);
1733    }
1734
1735    #[test]
1736    fn animation_frame_counters_distinguish_repaint_from_transform_only_frames() {
1737        let base_scene = SceneStatistics::minimal(
1738            &SceneFrame::new(WindowId::new(12), Size::new(320.0, 180.0)),
1739            3,
1740            SceneStatisticsDetailMode::Detailed,
1741        );
1742
1743        let repaint_summary = WindowPerformanceSnapshot::new(
1744            WindowId::new(12),
1745            3,
1746            vec![FramePhaseSample::new(FramePhase::Paint, 0.8)],
1747            RendererSubmissionDiagnostics::default(),
1748            TextCacheDiagnostics::default(),
1749            TextCacheDeltaDiagnostics::default(),
1750            base_scene.clone().with_animation_counters(2, 1, 1, 0),
1751        )
1752        .summary();
1753        let transform_only_summary = WindowPerformanceSnapshot::new(
1754            WindowId::new(12),
1755            4,
1756            vec![FramePhaseSample::new(FramePhase::Renderer, 0.4)],
1757            RendererSubmissionDiagnostics::default(),
1758            TextCacheDiagnostics::default(),
1759            TextCacheDeltaDiagnostics::default(),
1760            base_scene.with_animation_counters(1, 1, 0, 1),
1761        )
1762        .summary();
1763
1764        assert_eq!(repaint_summary.active_animated_widget_count, 2);
1765        assert_eq!(repaint_summary.animation_frame_wake_count, 1);
1766        assert_eq!(repaint_summary.animation_repaint_frame_count, 1);
1767        assert_eq!(
1768            repaint_summary.animation_transform_effect_only_frame_count,
1769            0
1770        );
1771        assert_eq!(transform_only_summary.active_animated_widget_count, 1);
1772        assert_eq!(transform_only_summary.animation_frame_wake_count, 1);
1773        assert_eq!(transform_only_summary.animation_repaint_frame_count, 0);
1774        assert_eq!(
1775            transform_only_summary.animation_transform_effect_only_frame_count,
1776            1
1777        );
1778    }
1779
1780    #[test]
1781    fn retained_packet_rebuild_diagnostics_total_count_sums_reasons() {
1782        let rebuilds = RetainedPacketRebuildDiagnostics::new(2, 3, 5, 7, 11);
1783
1784        assert_eq!(rebuilds.total_count(), 28);
1785    }
1786
1787    #[test]
1788    fn scene_statistics_skip_expensive_breakdowns_in_lightweight_mode() {
1789        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1790        frame.dirty_regions.push(DirtyRegion::new(
1791            Rect::new(0.0, 0.0, 64.0, 48.0),
1792            InvalidationKind::Paint,
1793        ));
1794        frame.scene.push(SceneCommand::Clear(Color::BLACK));
1795        frame.scene.push(SceneCommand::Label {
1796            rect: Rect::new(12.0, 12.0, 96.0, 24.0),
1797            text: "frame".to_string(),
1798            color: Color::WHITE,
1799        });
1800
1801        let lightweight = SceneStatistics::from_frame(&frame, 2);
1802        assert_eq!(
1803            lightweight.detail_mode,
1804            SceneStatisticsDetailMode::Lightweight
1805        );
1806        assert_eq!(lightweight.dirty_region_count, 1);
1807        assert_eq!(lightweight.command_count, 2);
1808        assert_eq!(lightweight.total_widget_count, 2);
1809        assert!(lightweight.dirty_regions.is_empty());
1810        assert!(lightweight.command_breakdown.is_empty());
1811
1812        let detailed =
1813            SceneStatistics::from_frame_with_mode(&frame, 2, SceneStatisticsDetailMode::Detailed);
1814        assert_eq!(detailed.detail_mode, SceneStatisticsDetailMode::Detailed);
1815        assert_eq!(detailed.dirty_region_count, 1);
1816        assert_eq!(detailed.dirty_regions.len(), 1);
1817        assert!(
1818            detailed
1819                .command_breakdown
1820                .contains(&("Clear".to_string(), 1))
1821        );
1822        assert!(
1823            detailed
1824                .command_breakdown
1825                .contains(&("Label".to_string(), 1))
1826        );
1827    }
1828
1829    #[test]
1830    fn scene_statistics_diagnostics_split_widget_boundary_and_scene_layer_counts() {
1831        let mut frame = SceneFrame::new(WindowId::new(18), Size::new(320.0, 180.0));
1832        frame.scene.push(SceneCommand::Layer(SceneLayer::new(
1833            WidgetId::new(20),
1834            Rect::new(0.0, 0.0, 120.0, 80.0),
1835            Scene::new(),
1836        )));
1837        frame
1838            .scene
1839            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1840                SceneLayerDescriptor::new(
1841                    WidgetId::new(21).into(),
1842                    WidgetId::new(21),
1843                    Rect::new(12.0, 10.0, 80.0, 48.0),
1844                )
1845                .with_is_stack_surface(true),
1846                Scene::new(),
1847            )));
1848        frame
1849            .scene
1850            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1851                SceneLayerDescriptor::new(
1852                    WidgetId::new(22).into(),
1853                    WidgetId::new(22),
1854                    Rect::new(24.0, 20.0, 64.0, 40.0),
1855                )
1856                .with_composition_mode(LayerCompositionMode::Overlay),
1857                Scene::new(),
1858            )));
1859
1860        let stats =
1861            SceneStatistics::from_frame_with_mode(&frame, 7, SceneStatisticsDetailMode::Detailed);
1862
1863        assert_eq!(stats.total_widget_count, 7);
1864        assert_eq!(stats.repaint_boundary_count, 3);
1865        assert_eq!(stats.scene_layer_count, 3);
1866        assert_eq!(stats.stack_surface_count, 1);
1867        assert_eq!(stats.overlay_layer_count, 1);
1868        assert!(stats.command_breakdown.contains(&("Layer".to_string(), 3)));
1869    }
1870
1871    #[test]
1872    fn scene_statistics_detail_mode_defaults_to_lightweight() {
1873        let window_id = WindowId::new(77);
1874        assert_eq!(
1875            window_scene_statistics_detail_mode(window_id),
1876            SceneStatisticsDetailMode::Lightweight
1877        );
1878
1879        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
1880        assert_eq!(
1881            window_scene_statistics_detail_mode(window_id),
1882            SceneStatisticsDetailMode::Detailed
1883        );
1884
1885        clear_window_performance_snapshot(window_id);
1886        assert_eq!(
1887            window_scene_statistics_detail_mode(window_id),
1888            SceneStatisticsDetailMode::Lightweight
1889        );
1890    }
1891
1892    #[test]
1893    fn window_render_options_are_clamped_and_cleared_with_window_state() {
1894        let window_id = WindowId::new(91);
1895
1896        set_window_render_options(
1897            window_id,
1898            WindowRenderOptions::new(false, -2.0)
1899                .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1900                .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1901                .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1902                .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1903                .with_text_coverage_policy(WindowTextCoveragePolicy::Gamma(-2.0))
1904                .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1905                .with_sdr_content_brightness_nits(-25.0),
1906        );
1907
1908        assert_eq!(
1909            window_render_options(window_id),
1910            Some(
1911                WindowRenderOptions::new(false, 0.0)
1912                    .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1913                    .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1914                    .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1915                    .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1916                    .with_text_coverage_policy(WindowTextCoveragePolicy::Linear)
1917                    .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1918                    .with_sdr_content_brightness_nits(203.0)
1919            )
1920        );
1921
1922        set_window_render_options(
1923            window_id,
1924            WindowRenderOptions::new(true, 1.0)
1925                .with_optical_vertical_text_alignment_enabled(false)
1926                .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1927                .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1928                .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1929                .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1930                .with_text_coverage_policy(WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq),
1931        );
1932
1933        assert_eq!(
1934            window_render_options(window_id),
1935            Some(
1936                WindowRenderOptions::new(true, 1.0)
1937                    .with_optical_vertical_text_alignment_enabled(false)
1938                    .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1939                    .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1940                    .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1941                    .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1942                    .with_text_coverage_policy(
1943                        WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq
1944                    )
1945            )
1946        );
1947
1948        clear_window_performance_snapshot(window_id);
1949
1950        assert_eq!(window_render_options(window_id), None);
1951    }
1952
1953    #[test]
1954    fn window_render_options_default_to_slight_text_hinting() {
1955        let options = WindowRenderOptions::new(true, 1.0);
1956        assert_eq!(
1957            options.text_hinting,
1958            WindowTextHinting::Slight {
1959                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM
1960            }
1961        );
1962        assert_eq!(
1963            options.text_coverage_policy,
1964            WindowTextCoveragePolicy::Perceptual
1965        );
1966        assert_eq!(options.text_subpixel_order, WindowTextSubpixelOrder::None);
1967    }
1968}