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