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