sinomo-ui-runtime 0.4.0

Retained runtime and widget contracts for SUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
#![allow(clippy::too_many_arguments)]

use std::{
    cell::RefCell,
    collections::{BTreeMap, HashMap},
    sync::{Mutex, OnceLock, RwLock},
    time::Duration,
};

use sui_core::{DirtyRegion, InvalidationKind, InvalidationTarget, Rect, Size, WidgetId, WindowId};
use sui_reactive::SourceId;
use sui_scene::{LayerCompositionMode, SceneCommand, SceneFrame, SceneLayerUpdateKind};
use sui_text::RuntimeTextTimingDiagnostics;
use web_time::Instant;

use crate::{CommandDelivery, CommandTarget};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FramePhase {
    Event,
    Redraw,
    MeasureArrange,
    HitTest,
    Paint,
    Semantics,
    Renderer,
    SurfaceWait,
    Diagnostics,
}

impl FramePhase {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Event => "Event handling",
            Self::Redraw => "Redraw callback",
            Self::MeasureArrange => "Measure and arrange",
            Self::HitTest => "Graph and hit test",
            Self::Paint => "Paint",
            Self::Semantics => "Semantics",
            Self::Renderer => "Renderer work",
            Self::SurfaceWait => "Surface wait",
            Self::Diagnostics => "Diagnostics",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FramePhaseSample {
    pub phase: FramePhase,
    pub duration_ms: f64,
}

impl FramePhaseSample {
    pub const fn new(phase: FramePhase, duration_ms: f64) -> Self {
        Self { phase, duration_ms }
    }

    pub fn from_duration(phase: FramePhase, duration: Duration) -> Self {
        Self::new(phase, duration.as_secs_f64() * 1000.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WidgetTimingPhase {
    Measure,
    Arrange,
    Paint,
    Semantics,
}

impl WidgetTimingPhase {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Measure => "Measure",
            Self::Arrange => "Arrange",
            Self::Paint => "Paint",
            Self::Semantics => "Semantics",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct WidgetTimingSample {
    pub widget_id: WidgetId,
    pub widget_name: &'static str,
    pub phase: WidgetTimingPhase,
    pub duration_ms: f64,
    pub calls: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReactiveInvalidationSample {
    pub widget_id: WidgetId,
    pub source_id: SourceId,
    pub source_name: String,
    pub version: u64,
    pub kind: InvalidationKind,
    /// False when the target is currently outside the active retained graph.
    pub delivered: bool,
}

/// One application-command delivery attempt retained in the next frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandDispatchSample {
    pub sequence: u64,
    pub name: String,
    pub payload_type: String,
    pub target: CommandTarget,
    pub delivery: CommandDelivery,
    pub handlers: Vec<String>,
    pub handled: bool,
    pub delivered: bool,
}

/// The origin and optional caller explanation for a scheduled invalidation.
#[derive(Debug, Clone, PartialEq)]
pub struct InvalidationTraceSample {
    pub target: InvalidationTarget,
    pub kind: InvalidationKind,
    pub region: Option<Rect>,
    pub source: String,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetRebuildSample {
    pub widget_id: WidgetId,
    pub widget_name: &'static str,
    pub reason: String,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct RenderDiagnostics {
    pub phase_timings: Vec<FramePhaseSample>,
    pub text_caches: TextCacheDiagnostics,
    pub runtime_text_timing: RuntimeTextTimingDiagnostics,
    pub widget_timings: Vec<WidgetTimingSample>,
    pub reactive_invalidations: Vec<ReactiveInvalidationSample>,
    pub command_dispatches: Vec<CommandDispatchSample>,
    pub invalidations: Vec<InvalidationTraceSample>,
    pub widget_rebuilds: Vec<WidgetRebuildSample>,
    pub widget_count: usize,
    pub active_animated_widget_count: usize,
    pub animation_frame_wake_count: usize,
    pub animation_repaint_frame_count: usize,
    pub animation_transform_effect_only_frame_count: usize,
}

fn rebuild_diagnostics() -> &'static Mutex<HashMap<WindowId, Vec<WidgetRebuildSample>>> {
    static REBUILDS: OnceLock<Mutex<HashMap<WindowId, Vec<WidgetRebuildSample>>>> = OnceLock::new();
    REBUILDS.get_or_init(|| Mutex::new(HashMap::new()))
}

pub(crate) fn record_widget_rebuild(
    window_id: WindowId,
    widget_id: WidgetId,
    widget_name: &'static str,
    reason: impl Into<String>,
) {
    rebuild_diagnostics()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .entry(window_id)
        .or_default()
        .push(WidgetRebuildSample {
            widget_id,
            widget_name,
            reason: reason.into(),
        });
}

pub(crate) fn take_widget_rebuilds(window_id: WindowId) -> Vec<WidgetRebuildSample> {
    rebuild_diagnostics()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(&window_id)
        .unwrap_or_default()
}

pub(crate) fn clear_widget_rebuilds(window_id: WindowId) {
    rebuild_diagnostics()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(&window_id);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct WidgetTimingKey {
    widget_id: WidgetId,
    widget_name: &'static str,
    phase: WidgetTimingPhase,
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
struct WidgetTimingAccum {
    duration_ms: f64,
    calls: usize,
}

thread_local! {
    static WIDGET_TIMING_COLLECTOR: RefCell<Option<BTreeMap<WidgetTimingKey, WidgetTimingAccum>>> =
        const { RefCell::new(None) };
}

fn widget_timing_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("SUI_PROFILE_WIDGET_TIMINGS").is_some())
}

pub(crate) fn begin_widget_timing_collection() {
    if !widget_timing_enabled() {
        return;
    }

    WIDGET_TIMING_COLLECTOR.with(|collector| {
        *collector.borrow_mut() = Some(BTreeMap::new());
    });
}

pub(crate) fn record_widget_timing(
    widget_id: WidgetId,
    widget_name: &'static str,
    phase: WidgetTimingPhase,
    duration: Duration,
) {
    if !widget_timing_enabled() {
        return;
    }

    let duration_ms = duration.as_secs_f64() * 1000.0;
    WIDGET_TIMING_COLLECTOR.with(|collector| {
        let mut collector = collector.borrow_mut();
        let Some(entries) = collector.as_mut() else {
            return;
        };

        let entry = entries
            .entry(WidgetTimingKey {
                widget_id,
                widget_name,
                phase,
            })
            .or_default();
        entry.duration_ms += duration_ms;
        entry.calls += 1;
    });
}

pub(crate) fn take_widget_timing_collection() -> Vec<WidgetTimingSample> {
    if !widget_timing_enabled() {
        return Vec::new();
    }

    let mut samples = WIDGET_TIMING_COLLECTOR
        .with(|collector| collector.borrow_mut().take())
        .unwrap_or_default()
        .into_iter()
        .map(|(key, accum)| WidgetTimingSample {
            widget_id: key.widget_id,
            widget_name: key.widget_name,
            phase: key.phase,
            duration_ms: accum.duration_ms,
            calls: accum.calls,
        })
        .collect::<Vec<_>>();
    samples.sort_by(|left, right| {
        right
            .duration_ms
            .total_cmp(&left.duration_ms)
            .then_with(|| left.phase.cmp(&right.phase))
            .then_with(|| left.widget_id.get().cmp(&right.widget_id.get()))
    });
    samples
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RetainedPacketRebuildDiagnostics {
    pub new_count: usize,
    pub coordinate_space_count: usize,
    pub signature_count: usize,
    pub scene_count: usize,
    pub state_count: usize,
}

impl RetainedPacketRebuildDiagnostics {
    pub const fn new(
        new_count: usize,
        coordinate_space_count: usize,
        signature_count: usize,
        scene_count: usize,
        state_count: usize,
    ) -> Self {
        Self {
            new_count,
            coordinate_space_count,
            signature_count,
            scene_count,
            state_count,
        }
    }

    pub const fn total_count(&self) -> usize {
        self.new_count
            + self.coordinate_space_count
            + self.signature_count
            + self.scene_count
            + self.state_count
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RendererSubmissionDiagnostics {
    pub pass_count: usize,
    pub draw_count: usize,
    pub uploaded_vertex_bytes: u64,
    pub text_glyph_instance_count: usize,
    pub text_vertex_bytes: u64,
    pub visible_layer_count: usize,
    pub direct_packet_count: usize,
    pub retained_state_update_time_us: u64,
    pub composition_time_us: u64,
    pub retained_scene_traversal_time_us: u64,
    pub retained_packet_build_time_us: u64,
    pub retained_packet_build_count: usize,
    pub retained_packet_rebuilds: RetainedPacketRebuildDiagnostics,
    pub retained_packet_normalize_time_us: u64,
    pub retained_packet_signature_time_us: u64,
    pub retained_packet_raster_state_init_time_us: u64,
    pub retained_packet_scene_build_time_us: u64,
    pub retained_packet_command_count: usize,
    pub retained_packet_text_command_count: usize,
    pub retained_packet_path_command_count: usize,
    pub retained_packet_clip_path_command_count: usize,
    pub retained_packet_image_command_count: usize,
    pub retained_packet_rect_command_count: usize,
    pub retained_packet_text_command_time_us: u64,
    pub retained_packet_path_command_time_us: u64,
    pub retained_packet_clip_path_command_time_us: u64,
    pub retained_packet_image_command_time_us: u64,
    pub retained_packet_rect_command_time_us: u64,
    pub text_atlas_miss_count: usize,
    pub text_atlas_miss_time_us: u64,
    pub surface_acquire_time_us: u64,
    pub resource_collection_time_us: u64,
    pub bind_group_prepare_time_us: u64,
    pub image_bind_group_time_us: u64,
    pub analytic_path_bind_group_time_us: u64,
    pub analytic_path_bind_group_miss_count: usize,
    pub analytic_path_bind_group_upload_bytes: u64,
    pub text_atlas_bind_group_time_us: u64,
    pub text_atlas_upload_copy_time_us: u64,
    pub text_atlas_upload_write_time_us: u64,
    pub text_atlas_upload_bytes: u64,
    pub batch_prepare_time_us: u64,
    pub gpu_upload_time_us: u64,
    pub pass_encode_time_us: u64,
    pub queue_submit_time_us: u64,
    pub surface_present_time_us: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RetainedPacketHotspotDiagnostics {
    pub container_layer_id: Option<u64>,
    pub owner_widget_id: Option<u64>,
    pub segment_index: u32,
    pub total_time_us: u64,
    pub scene_build_time_us: u64,
    pub command_count: usize,
    pub text_command_count: usize,
    pub path_command_count: usize,
    pub rect_command_count: usize,
    pub text_command_time_us: u64,
    pub path_command_time_us: u64,
    pub rect_command_time_us: u64,
    pub text_sample: Option<String>,
}

impl RendererSubmissionDiagnostics {
    pub const fn new(
        pass_count: usize,
        draw_count: usize,
        uploaded_vertex_bytes: u64,
        text_glyph_instance_count: usize,
        text_vertex_bytes: u64,
        visible_layer_count: usize,
        direct_packet_count: usize,
        retained_state_update_time_us: u64,
        composition_time_us: u64,
        retained_scene_traversal_time_us: u64,
        retained_packet_build_time_us: u64,
        retained_packet_build_count: usize,
        retained_packet_rebuilds: RetainedPacketRebuildDiagnostics,
        text_atlas_miss_count: usize,
        text_atlas_miss_time_us: u64,
        surface_acquire_time_us: u64,
        resource_collection_time_us: u64,
        bind_group_prepare_time_us: u64,
        image_bind_group_time_us: u64,
        analytic_path_bind_group_time_us: u64,
        analytic_path_bind_group_miss_count: usize,
        analytic_path_bind_group_upload_bytes: u64,
        text_atlas_bind_group_time_us: u64,
        text_atlas_upload_copy_time_us: u64,
        text_atlas_upload_write_time_us: u64,
        text_atlas_upload_bytes: u64,
        batch_prepare_time_us: u64,
        gpu_upload_time_us: u64,
        pass_encode_time_us: u64,
        queue_submit_time_us: u64,
        surface_present_time_us: u64,
    ) -> Self {
        Self {
            pass_count,
            draw_count,
            uploaded_vertex_bytes,
            text_glyph_instance_count,
            text_vertex_bytes,
            visible_layer_count,
            direct_packet_count,
            retained_state_update_time_us,
            composition_time_us,
            retained_scene_traversal_time_us,
            retained_packet_build_time_us,
            retained_packet_build_count,
            retained_packet_rebuilds,
            retained_packet_normalize_time_us: 0,
            retained_packet_signature_time_us: 0,
            retained_packet_raster_state_init_time_us: 0,
            retained_packet_scene_build_time_us: 0,
            retained_packet_command_count: 0,
            retained_packet_text_command_count: 0,
            retained_packet_path_command_count: 0,
            retained_packet_clip_path_command_count: 0,
            retained_packet_image_command_count: 0,
            retained_packet_rect_command_count: 0,
            retained_packet_text_command_time_us: 0,
            retained_packet_path_command_time_us: 0,
            retained_packet_clip_path_command_time_us: 0,
            retained_packet_image_command_time_us: 0,
            retained_packet_rect_command_time_us: 0,
            text_atlas_miss_count,
            text_atlas_miss_time_us,
            surface_acquire_time_us,
            resource_collection_time_us,
            bind_group_prepare_time_us,
            image_bind_group_time_us,
            analytic_path_bind_group_time_us,
            analytic_path_bind_group_miss_count,
            analytic_path_bind_group_upload_bytes,
            text_atlas_bind_group_time_us,
            text_atlas_upload_copy_time_us,
            text_atlas_upload_write_time_us,
            text_atlas_upload_bytes,
            batch_prepare_time_us,
            gpu_upload_time_us,
            pass_encode_time_us,
            queue_submit_time_us,
            surface_present_time_us,
        }
    }

    pub fn with_retained_packet_breakdown(
        mut self,
        retained_packet_normalize_time_us: u64,
        retained_packet_signature_time_us: u64,
        retained_packet_raster_state_init_time_us: u64,
        retained_packet_scene_build_time_us: u64,
        retained_packet_command_count: usize,
        retained_packet_text_command_count: usize,
        retained_packet_path_command_count: usize,
        retained_packet_clip_path_command_count: usize,
        retained_packet_image_command_count: usize,
        retained_packet_rect_command_count: usize,
        retained_packet_text_command_time_us: u64,
        retained_packet_path_command_time_us: u64,
        retained_packet_clip_path_command_time_us: u64,
        retained_packet_image_command_time_us: u64,
        retained_packet_rect_command_time_us: u64,
    ) -> Self {
        self.retained_packet_normalize_time_us = retained_packet_normalize_time_us;
        self.retained_packet_signature_time_us = retained_packet_signature_time_us;
        self.retained_packet_raster_state_init_time_us = retained_packet_raster_state_init_time_us;
        self.retained_packet_scene_build_time_us = retained_packet_scene_build_time_us;
        self.retained_packet_command_count = retained_packet_command_count;
        self.retained_packet_text_command_count = retained_packet_text_command_count;
        self.retained_packet_path_command_count = retained_packet_path_command_count;
        self.retained_packet_clip_path_command_count = retained_packet_clip_path_command_count;
        self.retained_packet_image_command_count = retained_packet_image_command_count;
        self.retained_packet_rect_command_count = retained_packet_rect_command_count;
        self.retained_packet_text_command_time_us = retained_packet_text_command_time_us;
        self.retained_packet_path_command_time_us = retained_packet_path_command_time_us;
        self.retained_packet_clip_path_command_time_us = retained_packet_clip_path_command_time_us;
        self.retained_packet_image_command_time_us = retained_packet_image_command_time_us;
        self.retained_packet_rect_command_time_us = retained_packet_rect_command_time_us;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct PresentationLatencyDiagnostics {
    pub event_to_render_start_ms: f64,
    pub event_to_present_ms: f64,
    pub redraw_request_to_callback_ms: f64,
}

impl PresentationLatencyDiagnostics {
    pub const fn new(
        event_to_render_start_ms: f64,
        event_to_present_ms: f64,
        redraw_request_to_callback_ms: f64,
    ) -> Self {
        Self {
            event_to_render_start_ms,
            event_to_present_ms,
            redraw_request_to_callback_ms,
        }
    }
}

impl RenderDiagnostics {
    pub fn push(&mut self, phase: FramePhase, duration: Duration) {
        self.phase_timings
            .push(FramePhaseSample::from_duration(phase, duration));
    }

    pub fn total_time_ms(&self) -> f64 {
        self.phase_timings
            .iter()
            .map(|sample| sample.duration_ms)
            .sum()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CacheMetrics {
    pub entries: usize,
    pub hits: usize,
    pub misses: usize,
}

impl CacheMetrics {
    pub const fn new(entries: usize, hits: usize, misses: usize) -> Self {
        Self {
            entries,
            hits,
            misses,
        }
    }

    pub const fn requests(self) -> usize {
        self.hits + self.misses
    }

    pub fn hit_rate(self) -> f64 {
        let requests = self.requests();
        if requests == 0 {
            0.0
        } else {
            self.hits as f64 / requests as f64
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CacheMetricsDelta {
    pub entries_delta: isize,
    pub hits: usize,
    pub misses: usize,
}

impl CacheMetricsDelta {
    pub fn from_counters(current: CacheMetrics, previous: CacheMetrics) -> Self {
        Self {
            entries_delta: current.entries as isize - previous.entries as isize,
            hits: current.hits.saturating_sub(previous.hits),
            misses: current.misses.saturating_sub(previous.misses),
        }
    }

    pub const fn requests(self) -> usize {
        self.hits + self.misses
    }

    pub fn hit_rate(self) -> f64 {
        let requests = self.requests();
        if requests == 0 {
            0.0
        } else {
            self.hits as f64 / requests as f64
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TextCacheDiagnostics {
    pub runtime_layout: CacheMetrics,
    pub renderer_layout: CacheMetrics,
    pub renderer_glyph: CacheMetrics,
    pub renderer_path: CacheMetrics,
}

impl TextCacheDiagnostics {
    pub fn delta_from(&self, previous: &Self) -> TextCacheDeltaDiagnostics {
        TextCacheDeltaDiagnostics {
            runtime_layout: CacheMetricsDelta::from_counters(
                self.runtime_layout,
                previous.runtime_layout,
            ),
            renderer_layout: CacheMetricsDelta::from_counters(
                self.renderer_layout,
                previous.renderer_layout,
            ),
            renderer_glyph: CacheMetricsDelta::from_counters(
                self.renderer_glyph,
                previous.renderer_glyph,
            ),
            renderer_path: CacheMetricsDelta::from_counters(
                self.renderer_path,
                previous.renderer_path,
            ),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TextCacheDeltaDiagnostics {
    pub runtime_layout: CacheMetricsDelta,
    pub renderer_layout: CacheMetricsDelta,
    pub renderer_glyph: CacheMetricsDelta,
    pub renderer_path: CacheMetricsDelta,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SceneStatisticsDetailMode {
    #[default]
    Lightweight,
    Detailed,
}

impl SceneStatisticsDetailMode {
    pub const fn is_detailed(self) -> bool {
        matches!(self, Self::Detailed)
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::Lightweight => "lightweight",
            Self::Detailed => "detailed",
        }
    }
}

/// A window's text hinting, the scene's [`sui_scene::TextRenderHinting`].
pub type WindowTextHinting = sui_scene::TextRenderHinting;

pub const DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM: f32 = sui_scene::DEFAULT_TEXT_HINTING_MAX_PPEM;

/// A window's stem darkening, the scene's [`sui_scene::TextRenderStemDarkening`].
pub type WindowStemDarkening = sui_scene::TextRenderStemDarkening;

/// A window's text coverage policy, the scene's
/// [`sui_scene::TextRenderCoveragePolicy`].
pub type WindowTextCoveragePolicy = sui_scene::TextRenderCoveragePolicy;

/// A window's text subpixel order, the scene's [`sui_scene::TextSubpixelOrder`].
pub type WindowTextSubpixelOrder = sui_scene::TextSubpixelOrder;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowOutputColorPrimaries {
    #[default]
    Automatic,
    Srgb,
    DisplayP3,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowDynamicRangeMode {
    #[default]
    Automatic,
    StandardDynamicRange,
    HighDynamicRange,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowToneMappingMode {
    #[default]
    Automatic,
    Clamp,
    Reinhard,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowColorManagementMode {
    #[default]
    Automatic,
    ForceSdr,
    PreferWideGamut,
    PreferHdr,
}

pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WindowRenderOptions {
    pub feathering_enabled: bool,
    pub feather_width: f32,
    pub optical_vertical_text_alignment_enabled: bool,
    pub text_hinting: WindowTextHinting,
    pub stem_darkening: WindowStemDarkening,
    pub text_coverage_policy: WindowTextCoveragePolicy,
    pub text_subpixel_order: WindowTextSubpixelOrder,
    pub output_color_primaries: WindowOutputColorPrimaries,
    pub dynamic_range_mode: WindowDynamicRangeMode,
    pub tone_mapping_mode: WindowToneMappingMode,
    pub color_management_mode: WindowColorManagementMode,
    pub sdr_content_brightness_nits: f32,
    pub use_system_sdr_content_brightness: bool,
}

impl WindowRenderOptions {
    pub const fn new(feathering_enabled: bool, feather_width: f32) -> Self {
        Self {
            feathering_enabled,
            feather_width,
            optical_vertical_text_alignment_enabled: true,
            text_hinting: WindowTextHinting::Slight {
                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM,
            },
            stem_darkening: WindowStemDarkening::None,
            text_coverage_policy: WindowTextCoveragePolicy::Perceptual,
            text_subpixel_order: WindowTextSubpixelOrder::None,
            output_color_primaries: WindowOutputColorPrimaries::Automatic,
            dynamic_range_mode: WindowDynamicRangeMode::Automatic,
            tone_mapping_mode: WindowToneMappingMode::Automatic,
            color_management_mode: WindowColorManagementMode::Automatic,
            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
            use_system_sdr_content_brightness: true,
        }
    }

    pub const fn with_optical_vertical_text_alignment_enabled(mut self, enabled: bool) -> Self {
        self.optical_vertical_text_alignment_enabled = enabled;
        self
    }

    pub const fn with_text_hinting(mut self, hinting: WindowTextHinting) -> Self {
        self.text_hinting = hinting;
        self
    }

    pub const fn with_stem_darkening(mut self, darkening: WindowStemDarkening) -> Self {
        self.stem_darkening = darkening;
        self
    }

    pub const fn with_text_coverage_policy(mut self, policy: WindowTextCoveragePolicy) -> Self {
        self.text_coverage_policy = policy;
        self
    }

    pub const fn with_text_subpixel_order(mut self, order: WindowTextSubpixelOrder) -> Self {
        self.text_subpixel_order = order;
        self
    }

    pub const fn with_output_color_primaries(
        mut self,
        primaries: WindowOutputColorPrimaries,
    ) -> Self {
        self.output_color_primaries = primaries;
        self
    }

    pub const fn with_dynamic_range_mode(mut self, mode: WindowDynamicRangeMode) -> Self {
        self.dynamic_range_mode = mode;
        self
    }

    pub const fn with_tone_mapping_mode(mut self, mode: WindowToneMappingMode) -> Self {
        self.tone_mapping_mode = mode;
        self
    }

    pub const fn with_color_management_mode(mut self, mode: WindowColorManagementMode) -> Self {
        self.color_management_mode = mode;
        self
    }

    pub const fn with_sdr_content_brightness_nits(mut self, brightness_nits: f32) -> Self {
        self.sdr_content_brightness_nits = brightness_nits;
        self
    }

    pub const fn with_system_sdr_content_brightness_enabled(mut self, enabled: bool) -> Self {
        self.use_system_sdr_content_brightness = enabled;
        self
    }

    pub fn clamped(self) -> Self {
        Self {
            feathering_enabled: self.feathering_enabled,
            feather_width: self.feather_width.max(0.0),
            optical_vertical_text_alignment_enabled: self.optical_vertical_text_alignment_enabled,
            text_hinting: self.text_hinting.normalized(),
            stem_darkening: self.stem_darkening.normalized(),
            text_coverage_policy: self.text_coverage_policy.normalized(),
            text_subpixel_order: self.text_subpixel_order,
            output_color_primaries: self.output_color_primaries,
            dynamic_range_mode: self.dynamic_range_mode,
            tone_mapping_mode: self.tone_mapping_mode,
            color_management_mode: self.color_management_mode,
            sdr_content_brightness_nits: if self.sdr_content_brightness_nits.is_finite()
                && self.sdr_content_brightness_nits > 0.0
            {
                self.sdr_content_brightness_nits
            } else {
                DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
            },
            use_system_sdr_content_brightness: self.use_system_sdr_content_brightness,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct WindowPerformanceSummary {
    pub window_id: WindowId,
    pub frame_index: u64,
    pub total_time_ms: f64,
    pub frame_interval_ms: Option<f64>,
    pub slowest_phase: Option<FramePhaseSample>,
    pub presentation_latency: PresentationLatencyDiagnostics,
    pub renderer_submission: RendererSubmissionDiagnostics,
    pub text_caches: TextCacheDiagnostics,
    pub total_widget_count: usize,
    pub active_animated_widget_count: usize,
    pub animation_frame_wake_count: usize,
    pub animation_repaint_frame_count: usize,
    pub animation_transform_effect_only_frame_count: usize,
    pub repaint_boundary_count: usize,
    pub scene_layer_count: usize,
    pub stack_surface_count: usize,
    pub overlay_layer_count: usize,
    pub dirty_region_count: usize,
    pub dirty_coverage: f32,
    pub command_count: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SceneStatistics {
    pub detail_mode: SceneStatisticsDetailMode,
    pub viewport: Size,
    pub total_widget_count: usize,
    pub active_animated_widget_count: usize,
    pub animation_frame_wake_count: usize,
    pub animation_repaint_frame_count: usize,
    pub animation_transform_effect_only_frame_count: usize,
    pub dirty_region_count: usize,
    pub dirty_regions: Vec<DirtyRegion>,
    pub dirty_area: f32,
    pub dirty_coverage: f32,
    pub command_count: usize,
    pub command_breakdown: Vec<(String, usize)>,
    /// Current repaint granularity as observed by the runtime today.
    ///
    /// During the layer-boundary transition this still tracks emitted scene
    /// layers, because the runtime has not yet decoupled explicit repaint
    /// boundaries from per-widget `SceneLayer` emission.
    pub repaint_boundary_count: usize,
    pub scene_layer_count: usize,
    pub stack_surface_count: usize,
    pub overlay_layer_count: usize,
    pub layer_update_count: usize,
    pub layer_update_breakdown: Vec<(String, usize)>,
    pub text_command_count: usize,
    pub image_command_count: usize,
    pub clip_command_count: usize,
    pub transform_command_count: usize,
}

impl SceneStatistics {
    pub fn with_animation_counters(
        mut self,
        active_animated_widget_count: usize,
        animation_frame_wake_count: usize,
        animation_repaint_frame_count: usize,
        animation_transform_effect_only_frame_count: usize,
    ) -> Self {
        self.active_animated_widget_count = active_animated_widget_count;
        self.animation_frame_wake_count = animation_frame_wake_count;
        self.animation_repaint_frame_count = animation_repaint_frame_count;
        self.animation_transform_effect_only_frame_count =
            animation_transform_effect_only_frame_count;
        self
    }

    pub fn from_frame(frame: &SceneFrame, total_widget_count: usize) -> Self {
        Self::from_frame_with_mode(
            frame,
            total_widget_count,
            SceneStatisticsDetailMode::Lightweight,
        )
    }

    pub fn minimal(
        frame: &SceneFrame,
        total_widget_count: usize,
        detail_mode: SceneStatisticsDetailMode,
    ) -> Self {
        let layer_totals = scene_layer_totals(frame);
        Self {
            detail_mode,
            viewport: frame.viewport,
            total_widget_count,
            active_animated_widget_count: 0,
            animation_frame_wake_count: 0,
            animation_repaint_frame_count: 0,
            animation_transform_effect_only_frame_count: 0,
            dirty_region_count: 0,
            dirty_regions: Vec::new(),
            dirty_area: 0.0,
            dirty_coverage: 0.0,
            command_count: 0,
            command_breakdown: Vec::new(),
            repaint_boundary_count: layer_totals.repaint_boundary_count,
            scene_layer_count: layer_totals.scene_layer_count,
            stack_surface_count: layer_totals.stack_surface_count,
            overlay_layer_count: layer_totals.overlay_layer_count,
            layer_update_count: 0,
            layer_update_breakdown: Vec::new(),
            text_command_count: 0,
            image_command_count: 0,
            clip_command_count: 0,
            transform_command_count: 0,
        }
    }

    pub fn from_frame_with_mode(
        frame: &SceneFrame,
        total_widget_count: usize,
        detail_mode: SceneStatisticsDetailMode,
    ) -> Self {
        let detailed = detail_mode.is_detailed();
        let mut command_breakdown = detailed.then(BTreeMap::<String, usize>::new);
        let mut text_command_count = 0usize;
        let mut image_command_count = 0usize;
        let mut clip_command_count = 0usize;
        let mut transform_command_count = 0usize;
        let mut command_count = 0usize;

        frame.scene.visit_commands(&mut |command| {
            command_count += 1;
            if let Some(breakdown) = &mut command_breakdown {
                *breakdown
                    .entry(command_kind(command).to_string())
                    .or_default() += 1;
            }

            match command {
                SceneCommand::DrawText(_)
                | SceneCommand::DrawShapedText(_)
                | SceneCommand::DrawShapedTextWindow(_)
                | SceneCommand::Label { .. } => {
                    text_command_count += 1;
                }
                SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => {
                    image_command_count += 1;
                }
                SceneCommand::PushClip { .. }
                | SceneCommand::PushClipPath { .. }
                | SceneCommand::PopClip => {
                    clip_command_count += 1;
                }
                SceneCommand::PushTransform { .. } | SceneCommand::PopTransform => {
                    transform_command_count += 1;
                }
                SceneCommand::Clear(_)
                | SceneCommand::FillRect { .. }
                | SceneCommand::StrokeRect { .. }
                | SceneCommand::FillPath { .. }
                | SceneCommand::StrokePath { .. }
                | SceneCommand::DrawShaderRect { .. }
                | SceneCommand::FillRoundedRect { .. }
                | SceneCommand::PushTextRenderPolicy { .. }
                | SceneCommand::PopTextRenderPolicy
                | SceneCommand::Layer(_) => {}
            }
        });

        let mut layer_update_breakdown = detailed.then(BTreeMap::<String, usize>::new);
        if let Some(breakdown) = &mut layer_update_breakdown {
            for update in &frame.layer_updates {
                *breakdown
                    .entry(layer_update_kind(update.kind).to_string())
                    .or_default() += 1;
            }
        }

        let dirty_area: f32 = frame
            .dirty_regions
            .iter()
            .map(|region| region.area.width().max(0.0) * region.area.height().max(0.0))
            .sum();
        let viewport_area = frame.viewport.width.max(0.0) * frame.viewport.height.max(0.0);
        let dirty_coverage = if viewport_area > 0.0 {
            ((dirty_area / viewport_area) * 100.0).min(100.0)
        } else {
            0.0
        };
        let dirty_region_count = frame.dirty_regions.len();
        let layer_totals = scene_layer_totals(frame);

        Self {
            detail_mode,
            viewport: frame.viewport,
            total_widget_count,
            active_animated_widget_count: 0,
            animation_frame_wake_count: 0,
            animation_repaint_frame_count: 0,
            animation_transform_effect_only_frame_count: 0,
            dirty_region_count,
            dirty_regions: if detailed {
                frame.dirty_regions.clone()
            } else {
                Vec::new()
            },
            dirty_area,
            dirty_coverage,
            command_count,
            command_breakdown: command_breakdown
                .map(|breakdown| breakdown.into_iter().collect())
                .unwrap_or_default(),
            repaint_boundary_count: layer_totals.repaint_boundary_count,
            scene_layer_count: layer_totals.scene_layer_count,
            stack_surface_count: layer_totals.stack_surface_count,
            overlay_layer_count: layer_totals.overlay_layer_count,
            layer_update_count: frame.layer_updates.len(),
            layer_update_breakdown: layer_update_breakdown
                .map(|breakdown| breakdown.into_iter().collect())
                .unwrap_or_default(),
            text_command_count,
            image_command_count,
            clip_command_count,
            transform_command_count,
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct SceneLayerTotals {
    repaint_boundary_count: usize,
    scene_layer_count: usize,
    stack_surface_count: usize,
    overlay_layer_count: usize,
}

fn scene_layer_totals(frame: &SceneFrame) -> SceneLayerTotals {
    let mut totals = SceneLayerTotals::default();
    frame.scene.visit_layers(&mut |layer| {
        totals.scene_layer_count += 1;
        if layer.descriptor.is_stack_surface {
            totals.stack_surface_count += 1;
        }
        if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
            totals.overlay_layer_count += 1;
        }
    });
    // Current runtime behavior still uses emitted scene layers as repaint
    // granularity. Keep the two metrics separate in the API so later slices can
    // decouple them without another diagnostics rename, but document the
    // equality clearly for this transitional phase.
    totals.repaint_boundary_count = totals.scene_layer_count;
    totals
}

#[derive(Debug, Clone, PartialEq)]
pub struct WindowPerformanceSnapshot {
    pub window_id: WindowId,
    pub frame_index: u64,
    pub total_time_ms: f64,
    /// Wall time between completed host frames, including pacing and idle time.
    /// This measures host frame cadence, not GPU execution or physical scanout.
    /// Unavailable for the first frame or after the frame counter restarts.
    pub frame_interval_ms: Option<f64>,
    pub phase_timings: Vec<FramePhaseSample>,
    pub presentation_latency: PresentationLatencyDiagnostics,
    pub renderer_submission: RendererSubmissionDiagnostics,
    pub text_caches: TextCacheDiagnostics,
    pub text_cache_deltas: TextCacheDeltaDiagnostics,
    pub runtime_text_timing: RuntimeTextTimingDiagnostics,
    pub widget_timings: Vec<WidgetTimingSample>,
    pub command_dispatches: Vec<CommandDispatchSample>,
    pub invalidations: Vec<InvalidationTraceSample>,
    pub retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
    pub scene: SceneStatistics,
}

impl WindowPerformanceSnapshot {
    pub fn new(
        window_id: WindowId,
        frame_index: u64,
        phase_timings: Vec<FramePhaseSample>,
        renderer_submission: RendererSubmissionDiagnostics,
        text_caches: TextCacheDiagnostics,
        text_cache_deltas: TextCacheDeltaDiagnostics,
        scene: SceneStatistics,
    ) -> Self {
        let total_time_ms = phase_timings.iter().map(|sample| sample.duration_ms).sum();

        Self::with_total_time_ms(
            window_id,
            frame_index,
            total_time_ms,
            phase_timings,
            renderer_submission,
            text_caches,
            text_cache_deltas,
            scene,
        )
    }

    pub fn with_total_time_ms(
        window_id: WindowId,
        frame_index: u64,
        total_time_ms: f64,
        phase_timings: Vec<FramePhaseSample>,
        renderer_submission: RendererSubmissionDiagnostics,
        text_caches: TextCacheDiagnostics,
        text_cache_deltas: TextCacheDeltaDiagnostics,
        scene: SceneStatistics,
    ) -> Self {
        Self {
            window_id,
            frame_index,
            total_time_ms,
            frame_interval_ms: None,
            phase_timings,
            presentation_latency: PresentationLatencyDiagnostics::default(),
            renderer_submission,
            text_caches,
            text_cache_deltas,
            runtime_text_timing: RuntimeTextTimingDiagnostics::default(),
            widget_timings: Vec::new(),
            command_dispatches: Vec::new(),
            invalidations: Vec::new(),
            retained_packet_hotspot: None,
            scene,
        }
    }

    pub fn with_presentation_latency(
        mut self,
        presentation_latency: PresentationLatencyDiagnostics,
    ) -> Self {
        self.presentation_latency = presentation_latency;
        self
    }

    pub fn with_widget_timings(mut self, widget_timings: Vec<WidgetTimingSample>) -> Self {
        self.widget_timings = widget_timings;
        self
    }

    pub fn with_event_traces(
        mut self,
        command_dispatches: Vec<CommandDispatchSample>,
        invalidations: Vec<InvalidationTraceSample>,
    ) -> Self {
        self.command_dispatches = command_dispatches;
        self.invalidations = invalidations;
        self
    }

    pub fn with_runtime_text_timing(
        mut self,
        runtime_text_timing: RuntimeTextTimingDiagnostics,
    ) -> Self {
        self.runtime_text_timing = runtime_text_timing;
        self
    }

    pub fn with_retained_packet_hotspot(
        mut self,
        retained_packet_hotspot: Option<RetainedPacketHotspotDiagnostics>,
    ) -> Self {
        self.retained_packet_hotspot = retained_packet_hotspot;
        self
    }

    pub fn slowest_phase(&self) -> Option<FramePhaseSample> {
        self.phase_timings
            .iter()
            .copied()
            .max_by(|left, right| left.duration_ms.total_cmp(&right.duration_ms))
    }

    pub fn summary(&self) -> WindowPerformanceSummary {
        WindowPerformanceSummary {
            window_id: self.window_id,
            frame_index: self.frame_index,
            total_time_ms: self.total_time_ms,
            frame_interval_ms: self.frame_interval_ms,
            slowest_phase: self.slowest_phase(),
            presentation_latency: self.presentation_latency,
            renderer_submission: self.renderer_submission,
            text_caches: self.text_caches,
            total_widget_count: self.scene.total_widget_count,
            active_animated_widget_count: self.scene.active_animated_widget_count,
            animation_frame_wake_count: self.scene.animation_frame_wake_count,
            animation_repaint_frame_count: self.scene.animation_repaint_frame_count,
            animation_transform_effect_only_frame_count: self
                .scene
                .animation_transform_effect_only_frame_count,
            repaint_boundary_count: self.scene.repaint_boundary_count,
            scene_layer_count: self.scene.scene_layer_count,
            stack_surface_count: self.scene.stack_surface_count,
            overlay_layer_count: self.scene.overlay_layer_count,
            dirty_region_count: self.scene.dirty_region_count,
            dirty_coverage: self.scene.dirty_coverage,
            command_count: self.scene.command_count,
        }
    }
}

struct WindowPerformanceRecord {
    snapshot: WindowPerformanceSnapshot,
    completed_at: Instant,
}

impl WindowPerformanceRecord {
    fn new(mut snapshot: WindowPerformanceSnapshot, completed_at: Instant) -> Self {
        snapshot.frame_interval_ms = None;
        Self {
            snapshot,
            completed_at,
        }
    }

    fn update(&mut self, mut snapshot: WindowPerformanceSnapshot, completed_at: Instant) {
        if snapshot.frame_index == self.snapshot.frame_index {
            // Refreshing diagnostics for one frame must not advance the clock.
            snapshot.frame_interval_ms = self.snapshot.frame_interval_ms;
        } else {
            snapshot.frame_interval_ms = (snapshot.frame_index > self.snapshot.frame_index)
                .then(|| {
                    completed_at.duration_since(self.completed_at).as_secs_f64() * 1000.0
                        / (snapshot.frame_index - self.snapshot.frame_index) as f64
                })
                .filter(|interval| *interval > 0.0);
            self.completed_at = completed_at;
        }
        self.snapshot = snapshot;
    }
}

static WINDOW_PERFORMANCE_SNAPSHOTS: OnceLock<RwLock<HashMap<WindowId, WindowPerformanceRecord>>> =
    OnceLock::new();
static WINDOW_SCENE_STATISTICS_DETAIL_MODES: OnceLock<
    RwLock<HashMap<WindowId, SceneStatisticsDetailMode>>,
> = OnceLock::new();
static WINDOW_RENDER_OPTIONS: OnceLock<RwLock<HashMap<WindowId, WindowRenderOptions>>> =
    OnceLock::new();

pub fn publish_window_performance_snapshot(snapshot: WindowPerformanceSnapshot) {
    let completed_at = Instant::now();
    let mut store = window_performance_store()
        .write()
        .expect("window performance snapshot store lock should not be poisoned");
    match store.entry(snapshot.window_id) {
        std::collections::hash_map::Entry::Occupied(mut entry) => {
            entry.get_mut().update(snapshot, completed_at);
        }
        std::collections::hash_map::Entry::Vacant(entry) => {
            entry.insert(WindowPerformanceRecord::new(snapshot, completed_at));
        }
    }
}

pub fn window_performance_snapshot(window_id: WindowId) -> Option<WindowPerformanceSnapshot> {
    let store = window_performance_store()
        .read()
        .expect("window performance snapshot store lock should not be poisoned");
    store.get(&window_id).map(|record| record.snapshot.clone())
}

pub fn window_performance_summary(window_id: WindowId) -> Option<WindowPerformanceSummary> {
    let store = window_performance_store()
        .read()
        .expect("window performance snapshot store lock should not be poisoned");
    store
        .get(&window_id)
        .map(|record| record.snapshot.summary())
}

pub fn window_performance_text_caches(window_id: WindowId) -> Option<TextCacheDiagnostics> {
    let store = window_performance_store()
        .read()
        .expect("window performance snapshot store lock should not be poisoned");
    store
        .get(&window_id)
        .map(|record| record.snapshot.text_caches)
}

pub fn set_window_scene_statistics_detail_mode(
    window_id: WindowId,
    detail_mode: SceneStatisticsDetailMode,
) {
    let mut store = window_scene_statistics_detail_mode_store()
        .write()
        .expect("scene statistics detail mode store lock should not be poisoned");
    if detail_mode == SceneStatisticsDetailMode::Lightweight {
        store.remove(&window_id);
    } else {
        store.insert(window_id, detail_mode);
    }
}

pub fn window_scene_statistics_detail_mode(window_id: WindowId) -> SceneStatisticsDetailMode {
    let store = window_scene_statistics_detail_mode_store()
        .read()
        .expect("scene statistics detail mode store lock should not be poisoned");
    store.get(&window_id).copied().unwrap_or_default()
}

pub fn set_window_render_options(window_id: WindowId, options: WindowRenderOptions) {
    let mut store = window_render_options_store()
        .write()
        .expect("window render options store lock should not be poisoned");
    store.insert(window_id, options.clamped());
}

pub fn window_render_options(window_id: WindowId) -> Option<WindowRenderOptions> {
    let store = window_render_options_store()
        .read()
        .expect("window render options store lock should not be poisoned");
    store.get(&window_id).copied()
}

pub fn clear_window_render_options(window_id: WindowId) {
    let mut store = window_render_options_store()
        .write()
        .expect("window render options store lock should not be poisoned");
    store.remove(&window_id);
}

pub fn clear_window_performance_snapshot(window_id: WindowId) {
    let mut store = window_performance_store()
        .write()
        .expect("window performance snapshot store lock should not be poisoned");
    store.remove(&window_id);

    let mut detail_modes = window_scene_statistics_detail_mode_store()
        .write()
        .expect("scene statistics detail mode store lock should not be poisoned");
    detail_modes.remove(&window_id);

    clear_window_render_options(window_id);
    crate::output_range::clear_window_output_color_range(window_id);
    crate::command_history::clear_window_command_dispatches(window_id);
}

pub fn clear_window_performance_snapshots() {
    let mut store = window_performance_store()
        .write()
        .expect("window performance snapshot store lock should not be poisoned");
    store.clear();

    let mut detail_modes = window_scene_statistics_detail_mode_store()
        .write()
        .expect("scene statistics detail mode store lock should not be poisoned");
    detail_modes.clear();

    let mut render_options = window_render_options_store()
        .write()
        .expect("window render options store lock should not be poisoned");
    render_options.clear();
    drop(render_options);
    crate::output_range::clear_window_output_color_ranges();
}

fn window_performance_store() -> &'static RwLock<HashMap<WindowId, WindowPerformanceRecord>> {
    WINDOW_PERFORMANCE_SNAPSHOTS.get_or_init(|| RwLock::new(HashMap::new()))
}

fn window_scene_statistics_detail_mode_store()
-> &'static RwLock<HashMap<WindowId, SceneStatisticsDetailMode>> {
    WINDOW_SCENE_STATISTICS_DETAIL_MODES.get_or_init(|| RwLock::new(HashMap::new()))
}

fn window_render_options_store() -> &'static RwLock<HashMap<WindowId, WindowRenderOptions>> {
    WINDOW_RENDER_OPTIONS.get_or_init(|| RwLock::new(HashMap::new()))
}

fn command_kind(command: &SceneCommand) -> &'static str {
    match command {
        SceneCommand::Clear(_) => "Clear",
        SceneCommand::FillRect { .. } => "FillRect",
        SceneCommand::StrokeRect { .. } => "StrokeRect",
        SceneCommand::FillPath { .. } => "FillPath",
        SceneCommand::StrokePath { .. } => "StrokePath",
        SceneCommand::DrawText(_) => "DrawText",
        SceneCommand::DrawShapedText(_) => "DrawShapedText",
        SceneCommand::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
        SceneCommand::DrawImage { .. } | SceneCommand::DrawImageQuad { .. } => "DrawImage",
        SceneCommand::DrawShaderRect { .. } => "DrawShaderRect",
        SceneCommand::PushClip { .. } => "PushClip",
        SceneCommand::PushClipPath { .. } => "PushClipPath",
        SceneCommand::PopClip => "PopClip",
        SceneCommand::PushTransform { .. } => "PushTransform",
        SceneCommand::PopTransform => "PopTransform",
        SceneCommand::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
        SceneCommand::PopTextRenderPolicy => "PopTextRenderPolicy",
        SceneCommand::Layer(_) => "Layer",
        SceneCommand::FillRoundedRect { .. } => "FillRoundedRect",
        SceneCommand::Label { .. } => "Label",
    }
}

fn layer_update_kind(kind: SceneLayerUpdateKind) -> &'static str {
    match kind {
        SceneLayerUpdateKind::Ordering => "Ordering",
        SceneLayerUpdateKind::Content => "Content",
        SceneLayerUpdateKind::Transform => "Transform",
        SceneLayerUpdateKind::Clip => "Clip",
        SceneLayerUpdateKind::Effect => "Effect",
        SceneLayerUpdateKind::Visibility => "Visibility",
        SceneLayerUpdateKind::Resources => "Resources",
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CacheMetrics, DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM, FramePhase, FramePhaseSample,
        RendererSubmissionDiagnostics, RetainedPacketRebuildDiagnostics, SceneStatistics,
        SceneStatisticsDetailMode, TextCacheDeltaDiagnostics, TextCacheDiagnostics,
        WindowColorManagementMode, WindowDynamicRangeMode, WindowOutputColorPrimaries,
        WindowPerformanceSnapshot, WindowRenderOptions, WindowTextCoveragePolicy,
        WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
        clear_window_performance_snapshot, set_window_render_options,
        set_window_scene_statistics_detail_mode, window_render_options,
        window_scene_statistics_detail_mode,
    };
    use sui_core::{Color, DirtyRegion, InvalidationKind, Rect, Size, WidgetId, WindowId};
    use sui_scene::{
        LayerCompositionMode, Scene, SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor,
    };

    #[test]
    fn frame_cadence_includes_pacing_and_ignores_duplicate_publications() {
        let window_id = WindowId::new(12);
        let snapshot = |frame_index| {
            WindowPerformanceSnapshot::new(
                window_id,
                frame_index,
                vec![FramePhaseSample::new(FramePhase::Renderer, 2.0)],
                RendererSubmissionDiagnostics::default(),
                TextCacheDiagnostics::default(),
                TextCacheDeltaDiagnostics::default(),
                SceneStatistics::minimal(
                    &SceneFrame::new(window_id, Size::new(320.0, 180.0)),
                    1,
                    SceneStatisticsDetailMode::Lightweight,
                ),
            )
        };
        let start = web_time::Instant::now();
        let at = |milliseconds| start + std::time::Duration::from_millis(milliseconds);
        let mut record = super::WindowPerformanceRecord::new(snapshot(1), start);
        assert_eq!(record.snapshot.frame_interval_ms, None);
        record.update(snapshot(2), at(50));
        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
        assert_eq!(
            record.snapshot.total_time_ms, 2.0,
            "render work remains separate from cadence"
        );
        assert_eq!(record.snapshot.summary().frame_interval_ms, Some(50.0));
        record.update(snapshot(2), at(60));
        record.update(snapshot(3), at(100));
        assert_eq!(record.snapshot.frame_interval_ms, Some(50.0));
        record.update(snapshot(1), at(150));
        assert_eq!(
            record.snapshot.frame_interval_ms, None,
            "a restarted window needs a fresh baseline"
        );
        record.update(snapshot(4), at(300));
        assert_eq!(
            record.snapshot.frame_interval_ms,
            Some(50.0),
            "skipped publications use the frame-count delta"
        );
    }

    #[test]
    fn text_cache_deltas_are_derived_from_prior_counters() {
        let previous = TextCacheDiagnostics {
            runtime_layout: CacheMetrics::new(2, 10, 4),
            renderer_layout: CacheMetrics::new(3, 6, 2),
            renderer_glyph: CacheMetrics::new(5, 12, 3),
            renderer_path: CacheMetrics::new(7, 14, 5),
        };
        let current = TextCacheDiagnostics {
            runtime_layout: CacheMetrics::new(4, 15, 6),
            renderer_layout: CacheMetrics::new(3, 9, 3),
            renderer_glyph: CacheMetrics::new(7, 18, 5),
            renderer_path: CacheMetrics::new(8, 21, 6),
        };

        let delta = current.delta_from(&previous);

        assert_eq!(delta.runtime_layout.entries_delta, 2);
        assert_eq!(delta.runtime_layout.hits, 5);
        assert_eq!(delta.runtime_layout.misses, 2);
        assert_eq!(delta.renderer_layout.entries_delta, 0);
        assert_eq!(delta.renderer_layout.hits, 3);
        assert_eq!(delta.renderer_layout.misses, 1);
        assert_eq!(delta.renderer_glyph.entries_delta, 2);
        assert_eq!(delta.renderer_glyph.hits, 6);
        assert_eq!(delta.renderer_glyph.misses, 2);
        assert_eq!(delta.renderer_path.entries_delta, 1);
        assert_eq!(delta.renderer_path.hits, 7);
        assert_eq!(delta.renderer_path.misses, 1);
    }

    #[test]
    fn scene_statistics_diagnostics_minimal_preserves_split_count_totals() {
        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
        frame
            .scene
            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
                SceneLayerDescriptor::new(
                    WidgetId::new(10).into(),
                    WidgetId::new(10),
                    Rect::new(0.0, 0.0, 120.0, 80.0),
                )
                .with_is_stack_surface(true),
                Scene::new(),
            )));
        frame
            .scene
            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
                SceneLayerDescriptor::new(
                    WidgetId::new(11).into(),
                    WidgetId::new(11),
                    Rect::new(12.0, 10.0, 80.0, 48.0),
                )
                .with_composition_mode(LayerCompositionMode::Overlay),
                Scene::new(),
            )));

        let stats = SceneStatistics::minimal(&frame, 5, SceneStatisticsDetailMode::Lightweight);

        assert_eq!(stats.total_widget_count, 5);
        assert_eq!(stats.repaint_boundary_count, 2);
        assert_eq!(stats.scene_layer_count, 2);
        assert_eq!(stats.stack_surface_count, 1);
        assert_eq!(stats.overlay_layer_count, 1);
        assert!(stats.command_breakdown.is_empty());
        assert!(stats.layer_update_breakdown.is_empty());
    }

    #[test]
    fn window_performance_snapshot_preserves_renderer_submission_stats() {
        let snapshot = WindowPerformanceSnapshot::new(
            WindowId::new(5),
            17,
            vec![FramePhaseSample::new(FramePhase::Renderer, 2.5)],
            RendererSubmissionDiagnostics::new(
                3,
                9,
                4096,
                128,
                3584,
                4,
                7,
                230,
                90,
                310,
                120,
                2,
                RetainedPacketRebuildDiagnostics::new(1, 0, 1, 1, 0),
                5,
                80,
                440,
                210,
                130,
                15,
                95,
                4,
                32768,
                115,
                85,
                22,
                16384,
                920,
                640,
                180,
                70,
                560,
            ),
            TextCacheDiagnostics::default(),
            TextCacheDeltaDiagnostics::default(),
            SceneStatistics {
                detail_mode: SceneStatisticsDetailMode::Lightweight,
                viewport: Size::new(640.0, 360.0),
                total_widget_count: 9,
                active_animated_widget_count: 2,
                animation_frame_wake_count: 1,
                animation_repaint_frame_count: 1,
                animation_transform_effect_only_frame_count: 0,
                dirty_region_count: 0,
                dirty_regions: Vec::new(),
                dirty_area: 0.0,
                dirty_coverage: 0.0,
                command_count: 0,
                command_breakdown: Vec::new(),
                repaint_boundary_count: 4,
                scene_layer_count: 4,
                stack_surface_count: 1,
                overlay_layer_count: 1,
                layer_update_count: 0,
                layer_update_breakdown: Vec::new(),
                text_command_count: 0,
                image_command_count: 0,
                clip_command_count: 0,
                transform_command_count: 0,
            },
        );

        assert_eq!(snapshot.renderer_submission.pass_count, 3);
        assert_eq!(snapshot.renderer_submission.draw_count, 9);
        assert_eq!(snapshot.renderer_submission.uploaded_vertex_bytes, 4096);
        assert_eq!(snapshot.renderer_submission.direct_packet_count, 7);
        assert_eq!(
            snapshot.renderer_submission.retained_state_update_time_us,
            230
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .retained_scene_traversal_time_us,
            310
        );
        assert_eq!(
            snapshot.renderer_submission.retained_packet_build_time_us,
            120
        );
        assert_eq!(snapshot.renderer_submission.retained_packet_build_count, 2);
        assert_eq!(
            snapshot
                .renderer_submission
                .retained_packet_rebuilds
                .total_count(),
            3
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .retained_packet_rebuilds
                .new_count,
            1
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .retained_packet_rebuilds
                .signature_count,
            1
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .retained_packet_rebuilds
                .scene_count,
            1
        );
        assert_eq!(snapshot.renderer_submission.text_atlas_miss_count, 5);
        assert_eq!(snapshot.renderer_submission.text_atlas_miss_time_us, 80);
        assert_eq!(snapshot.renderer_submission.surface_acquire_time_us, 440);
        assert_eq!(
            snapshot.renderer_submission.resource_collection_time_us,
            210
        );
        assert_eq!(snapshot.renderer_submission.bind_group_prepare_time_us, 130);
        assert_eq!(snapshot.renderer_submission.image_bind_group_time_us, 15);
        assert_eq!(
            snapshot
                .renderer_submission
                .analytic_path_bind_group_time_us,
            95
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .analytic_path_bind_group_miss_count,
            4
        );
        assert_eq!(
            snapshot
                .renderer_submission
                .analytic_path_bind_group_upload_bytes,
            32768
        );
        assert_eq!(
            snapshot.renderer_submission.text_atlas_bind_group_time_us,
            115
        );
        assert_eq!(
            snapshot.renderer_submission.text_atlas_upload_copy_time_us,
            85
        );
        assert_eq!(
            snapshot.renderer_submission.text_atlas_upload_write_time_us,
            22
        );
        assert_eq!(snapshot.renderer_submission.text_atlas_upload_bytes, 16384);
        assert_eq!(snapshot.renderer_submission.batch_prepare_time_us, 920);
        assert_eq!(snapshot.renderer_submission.gpu_upload_time_us, 640);
        assert_eq!(snapshot.renderer_submission.pass_encode_time_us, 180);
        assert_eq!(snapshot.renderer_submission.queue_submit_time_us, 70);
        assert_eq!(snapshot.renderer_submission.surface_present_time_us, 560);
        assert_eq!(snapshot.total_time_ms, 2.5);

        let summary = snapshot.summary();
        assert_eq!(summary.total_widget_count, 9);
        assert_eq!(summary.active_animated_widget_count, 2);
        assert_eq!(summary.animation_frame_wake_count, 1);
        assert_eq!(summary.animation_repaint_frame_count, 1);
        assert_eq!(summary.animation_transform_effect_only_frame_count, 0);
        assert_eq!(summary.repaint_boundary_count, 4);
        assert_eq!(summary.scene_layer_count, 4);
        assert_eq!(summary.stack_surface_count, 1);
        assert_eq!(summary.overlay_layer_count, 1);
    }

    #[test]
    fn animation_frame_counters_distinguish_repaint_from_transform_only_frames() {
        let base_scene = SceneStatistics::minimal(
            &SceneFrame::new(WindowId::new(12), Size::new(320.0, 180.0)),
            3,
            SceneStatisticsDetailMode::Detailed,
        );

        let repaint_summary = WindowPerformanceSnapshot::new(
            WindowId::new(12),
            3,
            vec![FramePhaseSample::new(FramePhase::Paint, 0.8)],
            RendererSubmissionDiagnostics::default(),
            TextCacheDiagnostics::default(),
            TextCacheDeltaDiagnostics::default(),
            base_scene.clone().with_animation_counters(2, 1, 1, 0),
        )
        .summary();
        let transform_only_summary = WindowPerformanceSnapshot::new(
            WindowId::new(12),
            4,
            vec![FramePhaseSample::new(FramePhase::Renderer, 0.4)],
            RendererSubmissionDiagnostics::default(),
            TextCacheDiagnostics::default(),
            TextCacheDeltaDiagnostics::default(),
            base_scene.with_animation_counters(1, 1, 0, 1),
        )
        .summary();

        assert_eq!(repaint_summary.active_animated_widget_count, 2);
        assert_eq!(repaint_summary.animation_frame_wake_count, 1);
        assert_eq!(repaint_summary.animation_repaint_frame_count, 1);
        assert_eq!(
            repaint_summary.animation_transform_effect_only_frame_count,
            0
        );
        assert_eq!(transform_only_summary.active_animated_widget_count, 1);
        assert_eq!(transform_only_summary.animation_frame_wake_count, 1);
        assert_eq!(transform_only_summary.animation_repaint_frame_count, 0);
        assert_eq!(
            transform_only_summary.animation_transform_effect_only_frame_count,
            1
        );
    }

    #[test]
    fn retained_packet_rebuild_diagnostics_total_count_sums_reasons() {
        let rebuilds = RetainedPacketRebuildDiagnostics::new(2, 3, 5, 7, 11);

        assert_eq!(rebuilds.total_count(), 28);
    }

    #[test]
    fn scene_statistics_skip_expensive_breakdowns_in_lightweight_mode() {
        let mut frame = SceneFrame::new(WindowId::new(8), Size::new(320.0, 180.0));
        frame.dirty_regions.push(DirtyRegion::new(
            Rect::new(0.0, 0.0, 64.0, 48.0),
            InvalidationKind::Paint,
        ));
        frame.scene.push(SceneCommand::Clear(Color::BLACK));
        frame.scene.push(SceneCommand::Label {
            rect: Rect::new(12.0, 12.0, 96.0, 24.0),
            text: "frame".to_string(),
            color: Color::WHITE,
        });

        let lightweight = SceneStatistics::from_frame(&frame, 2);
        assert_eq!(
            lightweight.detail_mode,
            SceneStatisticsDetailMode::Lightweight
        );
        assert_eq!(lightweight.dirty_region_count, 1);
        assert_eq!(lightweight.command_count, 2);
        assert_eq!(lightweight.total_widget_count, 2);
        assert!(lightweight.dirty_regions.is_empty());
        assert!(lightweight.command_breakdown.is_empty());

        let detailed =
            SceneStatistics::from_frame_with_mode(&frame, 2, SceneStatisticsDetailMode::Detailed);
        assert_eq!(detailed.detail_mode, SceneStatisticsDetailMode::Detailed);
        assert_eq!(detailed.dirty_region_count, 1);
        assert_eq!(detailed.dirty_regions.len(), 1);
        assert!(
            detailed
                .command_breakdown
                .contains(&("Clear".to_string(), 1))
        );
        assert!(
            detailed
                .command_breakdown
                .contains(&("Label".to_string(), 1))
        );
    }

    #[test]
    fn scene_statistics_diagnostics_split_widget_boundary_and_scene_layer_counts() {
        let mut frame = SceneFrame::new(WindowId::new(18), Size::new(320.0, 180.0));
        frame.scene.push(SceneCommand::Layer(SceneLayer::new(
            WidgetId::new(20),
            Rect::new(0.0, 0.0, 120.0, 80.0),
            Scene::new(),
        )));
        frame
            .scene
            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
                SceneLayerDescriptor::new(
                    WidgetId::new(21).into(),
                    WidgetId::new(21),
                    Rect::new(12.0, 10.0, 80.0, 48.0),
                )
                .with_is_stack_surface(true),
                Scene::new(),
            )));
        frame
            .scene
            .push(SceneCommand::Layer(SceneLayer::from_descriptor(
                SceneLayerDescriptor::new(
                    WidgetId::new(22).into(),
                    WidgetId::new(22),
                    Rect::new(24.0, 20.0, 64.0, 40.0),
                )
                .with_composition_mode(LayerCompositionMode::Overlay),
                Scene::new(),
            )));

        let stats =
            SceneStatistics::from_frame_with_mode(&frame, 7, SceneStatisticsDetailMode::Detailed);

        assert_eq!(stats.total_widget_count, 7);
        assert_eq!(stats.repaint_boundary_count, 3);
        assert_eq!(stats.scene_layer_count, 3);
        assert_eq!(stats.stack_surface_count, 1);
        assert_eq!(stats.overlay_layer_count, 1);
        assert!(stats.command_breakdown.contains(&("Layer".to_string(), 3)));
    }

    #[test]
    fn scene_statistics_detail_mode_defaults_to_lightweight() {
        let window_id = WindowId::new(77);
        assert_eq!(
            window_scene_statistics_detail_mode(window_id),
            SceneStatisticsDetailMode::Lightweight
        );

        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
        assert_eq!(
            window_scene_statistics_detail_mode(window_id),
            SceneStatisticsDetailMode::Detailed
        );

        clear_window_performance_snapshot(window_id);
        assert_eq!(
            window_scene_statistics_detail_mode(window_id),
            SceneStatisticsDetailMode::Lightweight
        );
    }

    #[test]
    fn window_render_options_are_clamped_and_cleared_with_window_state() {
        let window_id = WindowId::new(91);

        set_window_render_options(
            window_id,
            WindowRenderOptions::new(false, -2.0)
                .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
                .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
                .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
                .with_color_management_mode(WindowColorManagementMode::PreferHdr)
                .with_text_coverage_policy(WindowTextCoveragePolicy::Gamma(-2.0))
                .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
                .with_sdr_content_brightness_nits(-25.0),
        );

        assert_eq!(
            window_render_options(window_id),
            Some(
                WindowRenderOptions::new(false, 0.0)
                    .with_output_color_primaries(WindowOutputColorPrimaries::DisplayP3)
                    .with_dynamic_range_mode(WindowDynamicRangeMode::HighDynamicRange)
                    .with_tone_mapping_mode(WindowToneMappingMode::Reinhard)
                    .with_color_management_mode(WindowColorManagementMode::PreferHdr)
                    .with_text_coverage_policy(WindowTextCoveragePolicy::Linear)
                    .with_text_subpixel_order(WindowTextSubpixelOrder::Bgr)
                    .with_sdr_content_brightness_nits(203.0)
            )
        );

        set_window_render_options(
            window_id,
            WindowRenderOptions::new(true, 1.0)
                .with_optical_vertical_text_alignment_enabled(false)
                .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
                .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
                .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
                .with_color_management_mode(WindowColorManagementMode::ForceSdr)
                .with_text_coverage_policy(WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq),
        );

        assert_eq!(
            window_render_options(window_id),
            Some(
                WindowRenderOptions::new(true, 1.0)
                    .with_optical_vertical_text_alignment_enabled(false)
                    .with_output_color_primaries(WindowOutputColorPrimaries::Srgb)
                    .with_dynamic_range_mode(WindowDynamicRangeMode::StandardDynamicRange)
                    .with_tone_mapping_mode(WindowToneMappingMode::Clamp)
                    .with_color_management_mode(WindowColorManagementMode::ForceSdr)
                    .with_text_coverage_policy(
                        WindowTextCoveragePolicy::TwoCoverageMinusCoverageSq
                    )
            )
        );

        clear_window_performance_snapshot(window_id);

        assert_eq!(window_render_options(window_id), None);
    }

    #[test]
    fn window_render_options_default_to_slight_text_hinting() {
        let options = WindowRenderOptions::new(true, 1.0);
        assert_eq!(
            options.text_hinting,
            WindowTextHinting::Slight {
                max_ppem: DEFAULT_WINDOW_TEXT_HINTING_MAX_PPEM
            }
        );
        assert_eq!(
            options.text_coverage_policy,
            WindowTextCoveragePolicy::Perceptual
        );
        assert_eq!(options.text_subpixel_order, WindowTextSubpixelOrder::None);
    }
}