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.diagnostic_name().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 layer_update_kind(kind: SceneLayerUpdateKind) -> &'static str {
1412    match kind {
1413        SceneLayerUpdateKind::Ordering => "Ordering",
1414        SceneLayerUpdateKind::Content => "Content",
1415        SceneLayerUpdateKind::Transform => "Transform",
1416        SceneLayerUpdateKind::Clip => "Clip",
1417        SceneLayerUpdateKind::Effect => "Effect",
1418        SceneLayerUpdateKind::Visibility => "Visibility",
1419        SceneLayerUpdateKind::Resources => "Resources",
1420    }
1421}
1422
1423#[cfg(test)]
1424mod tests {
1425    use super::{
1426        CacheMetrics, DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM, FramePhase, FramePhaseSample,
1427        RendererSubmissionDiagnostics, RetainedPacketRebuildDiagnostics, SceneStatistics,
1428        SceneStatisticsDetailMode, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
1429        WindowColorManagementMode, WindowDynamicRangeMode, WindowOutputColorPrimaries,
1430        WindowPerformanceSnapshot, WindowRenderOptions, WindowTextCoveragePolicy,
1431        WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
1432        clear_window_performance_snapshot, set_window_render_options,
1433        set_window_scene_statistics_detail_mode, window_render_options,
1434        window_scene_statistics_detail_mode,
1435    };
1436    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, Size, WidgetId, WindowId};
1437    use sui_scene::{
1438        LayerCompositionMode, Scene, SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor,
1439    };
1440
1441    #[test]
1442    fn frame_cadence_includes_pacing_and_ignores_duplicate_publications() {
1443        let window_id = WindowId::new(12);
1444        let snapshot = |frame_index| {
1445            WindowPerformanceSnapshot::new(
1446                window_id,
1447                frame_index,
1448                vec![FramePhaseSample::new(FramePhase::Renderer, 2.0)],
1449                RendererSubmissionDiagnostics::default(),
1450                TextCacheDiagnostics::default(),
1451                TextCacheDeltaDiagnostics::default(),
1452                SceneStatistics::minimal(
1453                    &SceneFrame::new(window_id, Size::new(320.0, 180.0)),
1454                    1,
1455                    SceneStatisticsDetailMode::Lightweight,
1456                ),
1457            )
1458        };
1459        let start = web_time::Instant::now();
1460        let at = |milliseconds| start + std::time::Duration::from_millis(milliseconds);
1461        let mut record = super::WindowPerformanceRecord::new(snapshot(1), start);
1462        assert_eq!(record.snapshot.frame_interval_ms, None);
1463        record.update(snapshot(2), at(50));
1464        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
1465        assert_eq!(
1466            record.snapshot.total_time_ms, 2.0,
1467            "render work remains separate from cadence"
1468        );
1469        assert_eq!(record.snapshot.summary().frame_interval_ms, Some(50.0));
1470        record.update(snapshot(2), at(60));
1471        record.update(snapshot(3), at(100));
1472        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
1473        record.update(snapshot(1), at(150));
1474        assert_eq!(
1475            record.snapshot.frame_interval_ms, None,
1476            "a restarted window needs a fresh baseline"
1477        );
1478        record.update(snapshot(4), at(300));
1479        assert_eq!(
1480            record.snapshot.frame_interval_ms,
1481            Some(50.0),
1482            "skipped publications use the frame-count delta"
1483        );
1484    }
1485
1486    #[test]
1487    fn text_cache_deltas_are_derived_from_prior_counters() {
1488        let previous = TextCacheDiagnostics {
1489            runtime_layout: CacheMetrics::new(2, 10, 4),
1490            renderer_layout: CacheMetrics::new(3, 6, 2),
1491            renderer_glyph: CacheMetrics::new(5, 12, 3),
1492            renderer_path: CacheMetrics::new(7, 14, 5),
1493        };
1494        let current = TextCacheDiagnostics {
1495            runtime_layout: CacheMetrics::new(4, 15, 6),
1496            renderer_layout: CacheMetrics::new(3, 9, 3),
1497            renderer_glyph: CacheMetrics::new(7, 18, 5),
1498            renderer_path: CacheMetrics::new(8, 21, 6),
1499        };
1500
1501        let delta = current.delta_from(&previous);
1502
1503        assert_eq!(delta.runtime_layout.entries_delta, 2);
1504        assert_eq!(delta.runtime_layout.hits, 5);
1505        assert_eq!(delta.runtime_layout.misses, 2);
1506        assert_eq!(delta.renderer_layout.entries_delta, 0);
1507        assert_eq!(delta.renderer_layout.hits, 3);
1508        assert_eq!(delta.renderer_layout.misses, 1);
1509        assert_eq!(delta.renderer_glyph.entries_delta, 2);
1510        assert_eq!(delta.renderer_glyph.hits, 6);
1511        assert_eq!(delta.renderer_glyph.misses, 2);
1512        assert_eq!(delta.renderer_path.entries_delta, 1);
1513        assert_eq!(delta.renderer_path.hits, 7);
1514        assert_eq!(delta.renderer_path.misses, 1);
1515    }
1516
1517    #[test]
1518    fn scene_statistics_diagnostics_minimal_preserves_split_count_totals() {
1519        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1520        frame
1521            .scene
1522            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1523                SceneLayerDescriptor::new(
1524                    WidgetId::new(10).into(),
1525                    WidgetId::new(10),
1526                    Rect::new(0.0, 0.0, 120.0, 80.0),
1527                )
1528                .with_is_stack_surface(true),
1529                Scene::new(),
1530            )));
1531        frame
1532            .scene
1533            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1534                SceneLayerDescriptor::new(
1535                    WidgetId::new(11).into(),
1536                    WidgetId::new(11),
1537                    Rect::new(12.0, 10.0, 80.0, 48.0),
1538                )
1539                .with_composition_mode(LayerCompositionMode::Overlay),
1540                Scene::new(),
1541            )));
1542
1543        let stats = SceneStatistics::minimal(&frame, 5, SceneStatisticsDetailMode::Lightweight);
1544
1545        assert_eq!(stats.total_widget_count, 5);
1546        assert_eq!(stats.repaint_boundary_count, 2);
1547        assert_eq!(stats.scene_layer_count, 2);
1548        assert_eq!(stats.stack_surface_count, 1);
1549        assert_eq!(stats.overlay_layer_count, 1);
1550        assert!(stats.command_breakdown.is_empty());
1551        assert!(stats.layer_update_breakdown.is_empty());
1552    }
1553
1554    #[test]
1555    fn window_performance_snapshot_preserves_renderer_submission_stats() {
1556        let snapshot = WindowPerformanceSnapshot::new(
1557            WindowId::new(5),
1558            17,
1559            vec![FramePhaseSample::new(FramePhase::Renderer, 2.5)],
1560            RendererSubmissionDiagnostics::new(
1561                3,
1562                9,
1563                4096,
1564                128,
1565                3584,
1566                4,
1567                7,
1568                230,
1569                90,
1570                310,
1571                120,
1572                2,
1573                RetainedPacketRebuildDiagnostics::new(1, 0, 1, 1, 0),
1574                5,
1575                80,
1576                440,
1577                210,
1578                130,
1579                15,
1580                95,
1581                4,
1582                32768,
1583                115,
1584                85,
1585                22,
1586                16384,
1587                920,
1588                640,
1589                180,
1590                70,
1591                560,
1592            ),
1593            TextCacheDiagnostics::default(),
1594            TextCacheDeltaDiagnostics::default(),
1595            SceneStatistics {
1596                detail_mode: SceneStatisticsDetailMode::Lightweight,
1597                viewport: Size::new(640.0, 360.0),
1598                total_widget_count: 9,
1599                active_animated_widget_count: 2,
1600                animation_frame_wake_count: 1,
1601                animation_repaint_frame_count: 1,
1602                animation_transform_effect_only_frame_count: 0,
1603                dirty_region_count: 0,
1604                dirty_regions: Vec::new(),
1605                dirty_area: 0.0,
1606                dirty_coverage: 0.0,
1607                command_count: 0,
1608                command_breakdown: Vec::new(),
1609                repaint_boundary_count: 4,
1610                scene_layer_count: 4,
1611                stack_surface_count: 1,
1612                overlay_layer_count: 1,
1613                layer_update_count: 0,
1614                layer_update_breakdown: Vec::new(),
1615                text_command_count: 0,
1616                image_command_count: 0,
1617                clip_command_count: 0,
1618                transform_command_count: 0,
1619            },
1620        );
1621
1622        assert_eq!(snapshot.renderer_submission.pass_count, 3);
1623        assert_eq!(snapshot.renderer_submission.draw_count, 9);
1624        assert_eq!(snapshot.renderer_submission.uploaded_vertex_bytes, 4096);
1625        assert_eq!(snapshot.renderer_submission.direct_packet_count, 7);
1626        assert_eq!(
1627            snapshot.renderer_submission.retained_state_update_time_us,
1628            230
1629        );
1630        assert_eq!(
1631            snapshot
1632                .renderer_submission
1633                .retained_scene_traversal_time_us,
1634            310
1635        );
1636        assert_eq!(
1637            snapshot.renderer_submission.retained_packet_build_time_us,
1638            120
1639        );
1640        assert_eq!(snapshot.renderer_submission.retained_packet_build_count, 2);
1641        assert_eq!(
1642            snapshot
1643                .renderer_submission
1644                .retained_packet_rebuilds
1645                .total_count(),
1646            3
1647        );
1648        assert_eq!(
1649            snapshot
1650                .renderer_submission
1651                .retained_packet_rebuilds
1652                .new_count,
1653            1
1654        );
1655        assert_eq!(
1656            snapshot
1657                .renderer_submission
1658                .retained_packet_rebuilds
1659                .signature_count,
1660            1
1661        );
1662        assert_eq!(
1663            snapshot
1664                .renderer_submission
1665                .retained_packet_rebuilds
1666                .scene_count,
1667            1
1668        );
1669        assert_eq!(snapshot.renderer_submission.text_atlas_miss_count, 5);
1670        assert_eq!(snapshot.renderer_submission.text_atlas_miss_time_us, 80);
1671        assert_eq!(snapshot.renderer_submission.surface_acquire_time_us, 440);
1672        assert_eq!(
1673            snapshot.renderer_submission.resource_collection_time_us,
1674            210
1675        );
1676        assert_eq!(snapshot.renderer_submission.bind_group_prepare_time_us, 130);
1677        assert_eq!(snapshot.renderer_submission.image_bind_group_time_us, 15);
1678        assert_eq!(
1679            snapshot
1680                .renderer_submission
1681                .analytic_path_bind_group_time_us,
1682            95
1683        );
1684        assert_eq!(
1685            snapshot
1686                .renderer_submission
1687                .analytic_path_bind_group_miss_count,
1688            4
1689        );
1690        assert_eq!(
1691            snapshot
1692                .renderer_submission
1693                .analytic_path_bind_group_upload_bytes,
1694            32768
1695        );
1696        assert_eq!(
1697            snapshot.renderer_submission.text_atlas_bind_group_time_us,
1698            115
1699        );
1700        assert_eq!(
1701            snapshot.renderer_submission.text_atlas_upload_copy_time_us,
1702            85
1703        );
1704        assert_eq!(
1705            snapshot.renderer_submission.text_atlas_upload_write_time_us,
1706            22
1707        );
1708        assert_eq!(snapshot.renderer_submission.text_atlas_upload_bytes, 16384);
1709        assert_eq!(snapshot.renderer_submission.batch_prepare_time_us, 920);
1710        assert_eq!(snapshot.renderer_submission.gpu_upload_time_us, 640);
1711        assert_eq!(snapshot.renderer_submission.pass_encode_time_us, 180);
1712        assert_eq!(snapshot.renderer_submission.queue_submit_time_us, 70);
1713        assert_eq!(snapshot.renderer_submission.surface_present_time_us, 560);
1714        assert_eq!(snapshot.total_time_ms, 2.5);
1715
1716        let summary = snapshot.summary();
1717        assert_eq!(summary.total_widget_count, 9);
1718        assert_eq!(summary.active_animated_widget_count, 2);
1719        assert_eq!(summary.animation_frame_wake_count, 1);
1720        assert_eq!(summary.animation_repaint_frame_count, 1);
1721        assert_eq!(summary.animation_transform_effect_only_frame_count, 0);
1722        assert_eq!(summary.repaint_boundary_count, 4);
1723        assert_eq!(summary.scene_layer_count, 4);
1724        assert_eq!(summary.stack_surface_count, 1);
1725        assert_eq!(summary.overlay_layer_count, 1);
1726    }
1727
1728    #[test]
1729    fn animation_frame_counters_distinguish_repaint_from_transform_only_frames() {
1730        let base_scene = SceneStatistics::minimal(
1731            &SceneFrame::new(WindowId::new(12), Size::new(320.0, 180.0)),
1732            3,
1733            SceneStatisticsDetailMode::Detailed,
1734        );
1735
1736        let repaint_summary = WindowPerformanceSnapshot::new(
1737            WindowId::new(12),
1738            3,
1739            vec![FramePhaseSample::new(FramePhase::Paint, 0.8)],
1740            RendererSubmissionDiagnostics::default(),
1741            TextCacheDiagnostics::default(),
1742            TextCacheDeltaDiagnostics::default(),
1743            base_scene.clone().with_animation_counters(2, 1, 1, 0),
1744        )
1745        .summary();
1746        let transform_only_summary = WindowPerformanceSnapshot::new(
1747            WindowId::new(12),
1748            4,
1749            vec![FramePhaseSample::new(FramePhase::Renderer, 0.4)],
1750            RendererSubmissionDiagnostics::default(),
1751            TextCacheDiagnostics::default(),
1752            TextCacheDeltaDiagnostics::default(),
1753            base_scene.with_animation_counters(1, 1, 0, 1),
1754        )
1755        .summary();
1756
1757        assert_eq!(repaint_summary.active_animated_widget_count, 2);
1758        assert_eq!(repaint_summary.animation_frame_wake_count, 1);
1759        assert_eq!(repaint_summary.animation_repaint_frame_count, 1);
1760        assert_eq!(
1761            repaint_summary.animation_transform_effect_only_frame_count,
1762            0
1763        );
1764        assert_eq!(transform_only_summary.active_animated_widget_count, 1);
1765        assert_eq!(transform_only_summary.animation_frame_wake_count, 1);
1766        assert_eq!(transform_only_summary.animation_repaint_frame_count, 0);
1767        assert_eq!(
1768            transform_only_summary.animation_transform_effect_only_frame_count,
1769            1
1770        );
1771    }
1772
1773    #[test]
1774    fn retained_packet_rebuild_diagnostics_total_count_sums_reasons() {
1775        let rebuilds = RetainedPacketRebuildDiagnostics::new(2, 3, 5, 7, 11);
1776
1777        assert_eq!(rebuilds.total_count(), 28);
1778    }
1779
1780    #[test]
1781    fn scene_statistics_skip_expensive_breakdowns_in_lightweight_mode() {
1782        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
1783        frame.dirty_regions.push(DirtyRegion::new(
1784            Rect::new(0.0, 0.0, 64.0, 48.0),
1785            InvalidationKind::Paint,
1786        ));
1787        frame.scene.push(SceneCommand::Clear(Color::BLACK));
1788        frame.scene.push(SceneCommand::Label {
1789            rect: Rect::new(12.0, 12.0, 96.0, 24.0),
1790            text: "frame".to_string(),
1791            color: Color::WHITE,
1792        });
1793
1794        let lightweight = SceneStatistics::from_frame(&frame, 2);
1795        assert_eq!(
1796            lightweight.detail_mode,
1797            SceneStatisticsDetailMode::Lightweight
1798        );
1799        assert_eq!(lightweight.dirty_region_count, 1);
1800        assert_eq!(lightweight.command_count, 2);
1801        assert_eq!(lightweight.total_widget_count, 2);
1802        assert!(lightweight.dirty_regions.is_empty());
1803        assert!(lightweight.command_breakdown.is_empty());
1804
1805        let detailed =
1806            SceneStatistics::from_frame_with_mode(&frame, 2, SceneStatisticsDetailMode::Detailed);
1807        assert_eq!(detailed.detail_mode, SceneStatisticsDetailMode::Detailed);
1808        assert_eq!(detailed.dirty_region_count, 1);
1809        assert_eq!(detailed.dirty_regions.len(), 1);
1810        assert!(
1811            detailed
1812                .command_breakdown
1813                .contains(&("Clear".to_string(), 1))
1814        );
1815        assert!(
1816            detailed
1817                .command_breakdown
1818                .contains(&("Label".to_string(), 1))
1819        );
1820    }
1821
1822    #[test]
1823    fn scene_statistics_diagnostics_split_widget_boundary_and_scene_layer_counts() {
1824        let mut frame = SceneFrame::new(WindowId::new(18), Size::new(320.0, 180.0));
1825        frame.scene.push(SceneCommand::Layer(SceneLayer::new(
1826            WidgetId::new(20),
1827            Rect::new(0.0, 0.0, 120.0, 80.0),
1828            Scene::new(),
1829        )));
1830        frame
1831            .scene
1832            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1833                SceneLayerDescriptor::new(
1834                    WidgetId::new(21).into(),
1835                    WidgetId::new(21),
1836                    Rect::new(12.0, 10.0, 80.0, 48.0),
1837                )
1838                .with_is_stack_surface(true),
1839                Scene::new(),
1840            )));
1841        frame
1842            .scene
1843            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
1844                SceneLayerDescriptor::new(
1845                    WidgetId::new(22).into(),
1846                    WidgetId::new(22),
1847                    Rect::new(24.0, 20.0, 64.0, 40.0),
1848                )
1849                .with_composition_mode(LayerCompositionMode::Overlay),
1850                Scene::new(),
1851            )));
1852
1853        let stats =
1854            SceneStatistics::from_frame_with_mode(&frame, 7, SceneStatisticsDetailMode::Detailed);
1855
1856        assert_eq!(stats.total_widget_count, 7);
1857        assert_eq!(stats.repaint_boundary_count, 3);
1858        assert_eq!(stats.scene_layer_count, 3);
1859        assert_eq!(stats.stack_surface_count, 1);
1860        assert_eq!(stats.overlay_layer_count, 1);
1861        assert!(stats.command_breakdown.contains(&("Layer".to_string(), 3)));
1862    }
1863
1864    #[test]
1865    fn scene_statistics_detail_mode_defaults_to_lightweight() {
1866        let window_id = WindowId::new(77);
1867        assert_eq!(
1868            window_scene_statistics_detail_mode(window_id),
1869            SceneStatisticsDetailMode::Lightweight
1870        );
1871
1872        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
1873        assert_eq!(
1874            window_scene_statistics_detail_mode(window_id),
1875            SceneStatisticsDetailMode::Detailed
1876        );
1877
1878        clear_window_performance_snapshot(window_id);
1879        assert_eq!(
1880            window_scene_statistics_detail_mode(window_id),
1881            SceneStatisticsDetailMode::Lightweight
1882        );
1883    }
1884
1885    #[test]
1886    fn window_render_options_are_clamped_and_cleared_with_window_state() {
1887        let window_id = WindowId::new(91);
1888
1889        set_window_render_options(
1890            window_id,
1891            WindowRenderOptions::new(false, -2.0)
1892                .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1893                .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1894                .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1895                .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1896                .with_text_coverage_policy(WindowTextCoveragePolicy::Gamma(-2.0))
1897                .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1898                .with_sdr_content_brightness_nits(-25.0),
1899        );
1900
1901        assert_eq!(
1902            window_render_options(window_id),
1903            Some(
1904                WindowRenderOptions::new(false, 0.0)
1905                    .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
1906                    .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
1907                    .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
1908                    .with_color_management_mode(WindowColorManagementMode::PreferHdr)
1909                    .with_text_coverage_policy(WindowTextCoveragePolicy::Linear)
1910                    .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
1911                    .with_sdr_content_brightness_nits(203.0)
1912            )
1913        );
1914
1915        set_window_render_options(
1916            window_id,
1917            WindowRenderOptions::new(true, 1.0)
1918                .with_optical_vertical_text_alignment_enabled(false)
1919                .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1920                .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1921                .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1922                .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1923                .with_text_coverage_policy(WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq),
1924        );
1925
1926        assert_eq!(
1927            window_render_options(window_id),
1928            Some(
1929                WindowRenderOptions::new(true, 1.0)
1930                    .with_optical_vertical_text_alignment_enabled(false)
1931                    .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
1932                    .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
1933                    .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
1934                    .with_color_management_mode(WindowColorManagementMode::ForceSdr)
1935                    .with_text_coverage_policy(
1936                        WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq
1937                    )
1938            )
1939        );
1940
1941        clear_window_performance_snapshot(window_id);
1942
1943        assert_eq!(window_render_options(window_id), None);
1944    }
1945
1946    #[test]
1947    fn window_render_options_default_to_slight_text_hinting() {
1948        let options = WindowRenderOptions::new(true, 1.0);
1949        assert_eq!(
1950            options.text_hinting,
1951            WindowTextHinting::Slight {
1952                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM
1953            }
1954        );
1955        assert_eq!(
1956            options.text_coverage_policy,
1957            WindowTextCoveragePolicy::Perceptual
1958        );
1959        assert_eq!(options.text_subpixel_order, WindowTextSubpixelOrder::None);
1960    }
1961}