quickgui 0.1.0

A damage-driven, GPU-accelerated desktop GUI foundation
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
use std::sync::{Arc, LazyLock};

use glyphon::{Style as GlyphStyle, Weight};

use crate::{
    Background, Color, CustomShader, Font, FontFallbacks, FontFamily, FontFeatures, Image, Path,
    Rect, ShaderParameters, Svg, SvgTransform, TextHighlight, TextUnderline, Vector,
    font::{assert_valid_font_family, normalize_fallbacks},
    paint_order::{BoundsOrderTree, valid_bounds},
};

const MAX_RETAINED_PAINT_LAYERS: usize = 16;
/// Largest accepted analytic shadow blur in logical pixels.
pub const MAX_BOX_SHADOW_BLUR_RADIUS: f32 = 4096.0;
/// Largest absolute shadow offset or spread in logical pixels.
pub const MAX_BOX_SHADOW_EXTENT: f32 = 1_000_000.0;

/// A stable identity used to retain shaped text across frames.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TextId(u64);

impl TextId {
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Deterministic FNV-1a identity for static names and compound keys.
    pub fn named(value: &str) -> Self {
        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
        for byte in value.bytes() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
        Self(hash)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TextWrap {
    None,
    Word,
    Glyph,
}

/// CSS-like whitespace handling for text descendants.
///
/// QuickGUI keeps [`TextWrap`] as the lower-level shaping control. This enum provides the GPUI and
/// web-facing vocabulary without duplicating state in the retained style.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum WhiteSpace {
    #[default]
    Normal,
    Nowrap,
}

impl From<WhiteSpace> for TextWrap {
    fn from(value: WhiteSpace) -> Self {
        match value {
            WhiteSpace::Normal => Self::Word,
            WhiteSpace::Nowrap => Self::None,
        }
    }
}

/// How overflowing text is replaced inside its assigned width.
///
/// The affix is commonly an ellipsis, but remains application-defined to match GPUI. Truncation
/// is performed at Unicode grapheme boundaries and becomes part of the bounded retained text
/// layout, so it adds no per-frame work once the width and style are stable.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum TextOverflow {
    /// Preserve the start and replace the omitted tail with the supplied affix.
    Truncate(Arc<str>),
    /// Preserve the end and replace the omitted start with the supplied affix.
    TruncateStart(Arc<str>),
    /// Preserve both ends and replace the omitted middle with the supplied affix.
    TruncateMiddle(Arc<str>),
}

impl TextOverflow {
    /// End truncation using the single-character Unicode ellipsis.
    pub fn ellipsis() -> Self {
        static ELLIPSIS: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("…"));
        Self::Truncate(Arc::clone(&ELLIPSIS))
    }

    /// Start truncation using the single-character Unicode ellipsis.
    pub fn ellipsis_start() -> Self {
        static ELLIPSIS: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("…"));
        Self::TruncateStart(Arc::clone(&ELLIPSIS))
    }

    /// Middle truncation using the single-character Unicode ellipsis.
    pub fn ellipsis_middle() -> Self {
        static ELLIPSIS: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("…"));
        Self::TruncateMiddle(Arc::clone(&ELLIPSIS))
    }
}

/// Horizontal alignment of text lines within their element bounds.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum TextAlign {
    #[default]
    Left,
    Center,
    Right,
    Justify,
}

/// Text shaping strategy.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TextShaping {
    /// Full script shaping, ligatures, and system-font fallback.
    Advanced,
    /// Cheap one-glyph-per-character shaping for app-controlled text and fonts.
    ///
    /// This does not provide complex-script shaping or general font fallback. It is intended for
    /// known ASCII/code/log content where the selected font contains every required glyph.
    Basic,
}

/// Text metrics and shaping properties. The ordinary foreground color does not invalidate
/// shaping; explicit decoration colors remain part of the retained attribute key.
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
    pub font_size: f32,
    pub line_height: f32,
    pub family: FontFamily,
    pub features: FontFeatures,
    pub fallbacks: Option<FontFallbacks>,
    pub weight: Weight,
    pub font_style: GlyphStyle,
    pub underline: TextUnderline,
    pub underline_color: Option<Color>,
    /// Whether underlines use a spell-checker-style wave instead of a solid line.
    pub underline_wavy: bool,
    /// Logical-pixel underline thickness. Zero intentionally suppresses underline paint.
    pub underline_thickness: f32,
    pub strikethrough: bool,
    pub strikethrough_color: Option<Color>,
    pub align: TextAlign,
    pub wrap: TextWrap,
    pub text_overflow: Option<TextOverflow>,
    pub line_clamp: Option<usize>,
    pub shaping: TextShaping,
    pub color: Color,
}

impl TextStyle {
    pub fn new(font_size: f32, color: Color) -> Self {
        Self {
            font_size,
            line_height: font_size * 1.35,
            family: FontFamily::SansSerif,
            features: FontFeatures::new(),
            fallbacks: None,
            weight: Weight::NORMAL,
            font_style: GlyphStyle::Normal,
            underline: TextUnderline::None,
            underline_color: None,
            underline_wavy: false,
            underline_thickness: 1.0,
            strikethrough: false,
            strikethrough_color: None,
            align: TextAlign::Left,
            wrap: TextWrap::Word,
            text_overflow: None,
            line_clamp: None,
            shaping: TextShaping::Advanced,
            color,
        }
    }

    pub fn line_height(mut self, line_height: f32) -> Self {
        self.line_height = line_height;
        self
    }

    pub fn family(mut self, family: impl Into<FontFamily>) -> Self {
        let family = family.into();
        assert_valid_font_family(&family);
        self.family = family;
        self
    }

    pub fn font_features(mut self, features: FontFeatures) -> Self {
        self.features = features;
        self
    }

    pub fn font_fallbacks(mut self, fallbacks: FontFallbacks) -> Self {
        self.fallbacks = (!fallbacks.is_empty()).then_some(fallbacks);
        self
    }

    pub fn font(mut self, font: Font) -> Self {
        assert_valid_font_family(&font.family);
        self.family = font.family;
        self.features = font.features;
        self.fallbacks = normalize_fallbacks(font.fallbacks);
        self.weight = font.weight;
        self.font_style = font.style;
        self
    }

    pub fn weight(mut self, weight: Weight) -> Self {
        self.weight = weight;
        self
    }

    pub fn font_style(mut self, style: GlyphStyle) -> Self {
        self.font_style = style;
        self
    }

    pub fn underline(mut self) -> Self {
        self.underline = TextUnderline::Single;
        self.underline_wavy = false;
        self.underline_thickness = 1.0;
        self
    }

    pub fn double_underline(mut self) -> Self {
        self.underline = TextUnderline::Double;
        self.underline_wavy = false;
        self.underline_thickness = 1.0;
        self
    }

    pub fn underline_color(mut self, color: Color) -> Self {
        if self.underline == TextUnderline::None {
            self.underline = TextUnderline::Single;
            self.underline_wavy = false;
            self.underline_thickness = 1.0;
        }
        self.underline_color = Some(color);
        self
    }

    pub fn text_decoration_none(mut self) -> Self {
        self.underline = TextUnderline::None;
        self.underline_color = None;
        self.underline_wavy = false;
        self.underline_thickness = 1.0;
        self.strikethrough = false;
        self.strikethrough_color = None;
        self
    }

    pub fn text_decoration_solid(mut self) -> Self {
        if self.underline == TextUnderline::None {
            self.underline = TextUnderline::Single;
        }
        self.underline_wavy = false;
        self
    }

    pub fn text_decoration_wavy(mut self) -> Self {
        if self.underline == TextUnderline::None {
            self.underline = TextUnderline::Single;
        }
        self.underline_wavy = true;
        self
    }

    fn text_decoration_thickness(mut self, thickness: f32) -> Self {
        if self.underline == TextUnderline::None {
            self.underline = TextUnderline::Single;
        }
        self.underline_thickness = thickness;
        self
    }

    pub fn text_decoration_0(self) -> Self {
        self.text_decoration_thickness(0.0)
    }

    pub fn text_decoration_1(self) -> Self {
        self.text_decoration_thickness(1.0)
    }

    pub fn text_decoration_2(self) -> Self {
        self.text_decoration_thickness(2.0)
    }

    pub fn text_decoration_4(self) -> Self {
        self.text_decoration_thickness(4.0)
    }

    pub fn text_decoration_8(self) -> Self {
        self.text_decoration_thickness(8.0)
    }

    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    pub fn strikethrough_color(mut self, color: Color) -> Self {
        self.strikethrough = true;
        self.strikethrough_color = Some(color);
        self
    }

    pub(crate) fn has_decorations(&self) -> bool {
        (self.underline != TextUnderline::None && self.underline_thickness > 0.0)
            || self.strikethrough
    }

    pub fn align(mut self, align: TextAlign) -> Self {
        self.align = align;
        self
    }

    pub fn wrap(mut self, wrap: TextWrap) -> Self {
        self.wrap = wrap;
        self
    }

    pub fn white_space(mut self, white_space: WhiteSpace) -> Self {
        self.wrap = white_space.into();
        self
    }

    pub fn text_overflow(mut self, overflow: TextOverflow) -> Self {
        self.text_overflow = Some(overflow);
        self
    }

    pub fn line_clamp(mut self, lines: usize) -> Self {
        self.line_clamp = Some(lines.max(1));
        self
    }

    pub fn shaping(mut self, shaping: TextShaping) -> Self {
        self.shaping = shaping;
        self
    }
}

/// A filled rounded rectangle with an optional inside border and clip.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Quad {
    pub rect: Rect,
    pub fill: Color,
    pub radius: f32,
    pub border_width: f32,
    pub border_color: Color,
    pub clip: Option<Rect>,
}

impl Quad {
    pub fn new(rect: Rect, fill: Color) -> Self {
        Self {
            rect,
            fill,
            radius: 0.0,
            border_width: 0.0,
            border_color: Color::TRANSPARENT,
            clip: None,
        }
    }

    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = radius.max(0.0);
        self
    }

    pub fn border(mut self, width: f32, color: Color) -> Self {
        self.border_width = width.max(0.0);
        self.border_color = color;
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }
}

/// One underline wave evaluated analytically by the shared instanced-shape shader.
///
/// Keeping a whole visual span in one instance avoids generating or retaining a CPU-side path for
/// every wave crest. The geometry is already clipped to visible text lines before it reaches the
/// scene.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WavyUnderline {
    pub rect: Rect,
    pub baseline: f32,
    pub amplitude: f32,
    pub thickness: f32,
    pub wavelength: f32,
    pub color: Color,
    pub clip: Option<Rect>,
}

impl WavyUnderline {
    pub fn new(
        rect: Rect,
        baseline: f32,
        amplitude: f32,
        thickness: f32,
        wavelength: f32,
        color: Color,
    ) -> Self {
        Self {
            rect,
            baseline,
            amplitude,
            thickness,
            wavelength,
            color,
            clip: None,
        }
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }
}

/// A CSS-like shadow attached to an element's rounded border box.
///
/// Multiple shadows are painted in declaration order, with the first shadow on top. Drop
/// shadows paint behind the element; inset shadows paint above its background and border.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxShadow {
    color: Color,
    offset: Vector,
    blur_radius: f32,
    spread_radius: f32,
    inset: bool,
}

impl BoxShadow {
    pub fn new(offset_x: f32, offset_y: f32, color: Color) -> Self {
        Self {
            color,
            offset: Vector::new(
                finite_or_zero(offset_x).clamp(-MAX_BOX_SHADOW_EXTENT, MAX_BOX_SHADOW_EXTENT),
                finite_or_zero(offset_y).clamp(-MAX_BOX_SHADOW_EXTENT, MAX_BOX_SHADOW_EXTENT),
            ),
            blur_radius: 0.0,
            spread_radius: 0.0,
            inset: false,
        }
    }

    pub fn blur_radius(mut self, radius: f32) -> Self {
        self.blur_radius = finite_or_zero(radius).clamp(0.0, MAX_BOX_SHADOW_BLUR_RADIUS);
        self
    }

    pub fn spread_radius(mut self, radius: f32) -> Self {
        self.spread_radius =
            finite_or_zero(radius).clamp(-MAX_BOX_SHADOW_EXTENT, MAX_BOX_SHADOW_EXTENT);
        self
    }

    pub fn inset(mut self, inset: bool) -> Self {
        self.inset = inset;
        self
    }

    pub const fn color(self) -> Color {
        self.color
    }

    pub const fn offset(self) -> Vector {
        self.offset
    }

    pub const fn blur(self) -> f32 {
        self.blur_radius
    }

    pub const fn spread(self) -> f32 {
        self.spread_radius
    }

    pub const fn is_inset(self) -> bool {
        self.inset
    }

    fn multiply_alpha(mut self, opacity: f32) -> Self {
        self.color = self.color.multiply_alpha(opacity);
        self
    }
}

fn finite_or_zero(value: f32) -> f32 {
    if value.is_finite() { value } else { 0.0 }
}

/// A lower-level shadow display-list primitive.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Shadow {
    pub element_rect: Rect,
    pub radius: f32,
    pub style: BoxShadow,
    pub clip: Option<Rect>,
}

impl Shadow {
    pub fn new(element_rect: Rect, style: BoxShadow) -> Self {
        Self {
            element_rect,
            radius: 0.0,
            style,
            clip: None,
        }
    }

    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = finite_or_zero(radius).max(0.0);
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }
}

/// One sampled image rectangle with normalized source coordinates and a rounded content mask.
#[derive(Clone, Debug, PartialEq)]
pub struct ImagePrimitive {
    pub image: Image,
    pub destination: Rect,
    pub source_uv: Rect,
    pub mask: Rect,
    pub radius: f32,
    pub grayscale: bool,
    pub opacity: f32,
    pub clip: Option<Rect>,
}

impl ImagePrimitive {
    pub fn new(image: Image, destination: Rect) -> Self {
        Self {
            image,
            destination,
            source_uv: Rect::new(0.0, 0.0, 1.0, 1.0),
            mask: destination,
            radius: 0.0,
            grayscale: false,
            opacity: 1.0,
            clip: None,
        }
    }

    pub fn source_uv(mut self, source_uv: Rect) -> Self {
        self.source_uv = source_uv;
        self
    }

    pub fn mask(mut self, mask: Rect) -> Self {
        self.mask = mask;
        self
    }

    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = radius.max(0.0);
        self
    }

    pub fn grayscale(mut self, grayscale: bool) -> Self {
        self.grayscale = grayscale;
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = sanitize_opacity(opacity);
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }
}

/// One tinted SVG mask with normalized source coordinates and a rounded content mask.
#[derive(Clone, Debug, PartialEq)]
pub struct SvgPrimitive {
    pub svg: Svg,
    pub destination: Rect,
    pub source_uv: Rect,
    pub mask: Rect,
    pub radius: f32,
    pub color: Color,
    pub transform: SvgTransform,
    pub clip: Option<Rect>,
}

/// One retained tessellated path with a paint, affine scale/translation, and logical clip.
#[derive(Clone, Debug, PartialEq)]
pub struct PathPrimitive {
    pub path: Path,
    pub background: Background,
    scale: [f32; 2],
    translation: Vector,
    pub clip: Option<Rect>,
}

impl PathPrimitive {
    pub fn new(path: impl Into<Path>, background: impl Into<Background>) -> Self {
        Self {
            path: path.into(),
            background: background.into(),
            scale: [1.0, 1.0],
            translation: Vector::ZERO,
            clip: None,
        }
    }

    pub fn translate(mut self, x: f32, y: f32) -> Self {
        self.translation = Vector::new(sanitize_path_translation(x), sanitize_path_translation(y));
        self
    }

    pub fn scale(mut self, scale: f32) -> Self {
        let scale = sanitize_path_scale(scale);
        self.scale = [scale, scale];
        self
    }

    pub fn scale_xy(mut self, x: f32, y: f32) -> Self {
        self.scale = [sanitize_path_scale(x), sanitize_path_scale(y)];
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }

    pub(crate) const fn scale_factors(&self) -> [f32; 2] {
        self.scale
    }

    pub(crate) const fn translation(&self) -> Vector {
        self.translation
    }

    pub(crate) fn render_bounds(&self) -> Rect {
        let bounds = self.path.bounds();
        let first_x = bounds.x * self.scale[0] + self.translation.x;
        let second_x = bounds.right() * self.scale[0] + self.translation.x;
        let first_y = bounds.y * self.scale[1] + self.translation.y;
        let second_y = bounds.bottom() * self.scale[1] + self.translation.y;
        Rect::new(
            first_x.min(second_x),
            first_y.min(second_y),
            (second_x - first_x).abs(),
            (second_y - first_y).abs(),
        )
    }
}

/// One retained rectangle painted by validated application WGSL.
#[derive(Clone, Debug, PartialEq)]
pub struct CustomShaderPrimitive {
    pub shader: CustomShader,
    pub rect: Rect,
    pub parameters: ShaderParameters,
    pub opacity: f32,
    pub clip: Option<Rect>,
}

impl CustomShaderPrimitive {
    pub fn new(shader: impl Into<CustomShader>, rect: Rect) -> Self {
        Self {
            shader: shader.into(),
            rect,
            parameters: ShaderParameters::default(),
            opacity: 1.0,
            clip: None,
        }
    }

    pub fn parameters(mut self, parameters: impl Into<ShaderParameters>) -> Self {
        self.parameters = parameters.into();
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = sanitize_opacity(opacity);
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }
}

const MAX_PATH_PRIMITIVE_SCALE: f32 = 1_024.0;

fn sanitize_path_scale(value: f32) -> f32 {
    if value.is_finite() {
        value.clamp(-MAX_PATH_PRIMITIVE_SCALE, MAX_PATH_PRIMITIVE_SCALE)
    } else {
        1.0
    }
}

fn sanitize_path_translation(value: f32) -> f32 {
    if value.is_finite() {
        value.clamp(-crate::MAX_PATH_COORDINATE, crate::MAX_PATH_COORDINATE)
    } else {
        0.0
    }
}

impl SvgPrimitive {
    pub fn new(svg: Svg, destination: Rect, color: Color) -> Self {
        Self {
            svg,
            destination,
            source_uv: Rect::new(0.0, 0.0, 1.0, 1.0),
            mask: destination,
            radius: 0.0,
            color,
            transform: SvgTransform::IDENTITY,
            clip: None,
        }
    }

    pub fn source_uv(mut self, source_uv: Rect) -> Self {
        self.source_uv = source_uv;
        self
    }

    pub fn mask(mut self, mask: Rect) -> Self {
        self.mask = mask;
        self
    }

    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = finite_or_zero(radius).max(0.0);
        self
    }

    pub fn transform(mut self, transform: SvgTransform) -> Self {
        self.transform = transform;
        self
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }

    pub(crate) fn render_bounds(&self) -> Rect {
        self.transform.transformed_bounds(self.destination)
    }
}

/// A retained text command. Reuse `id` and the same `Arc<str>` to avoid shaping and allocation.
#[derive(Clone, Debug, PartialEq)]
pub struct TextRun {
    pub id: TextId,
    pub content: Arc<str>,
    pub bounds: Rect,
    pub style: TextStyle,
    pub opacity: f32,
    pub clip: Option<Rect>,
    pub(crate) highlights: Option<Arc<[TextHighlight]>>,
}

impl TextRun {
    pub fn new(id: TextId, content: Arc<str>, bounds: Rect, style: TextStyle) -> Self {
        Self {
            id,
            content,
            bounds,
            style,
            opacity: 1.0,
            clip: None,
            highlights: None,
        }
    }

    pub fn clip(mut self, clip: Rect) -> Self {
        self.clip = Some(clip);
        self
    }

    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = sanitize_opacity(opacity);
        self
    }

    pub(crate) fn with_highlights(mut self, highlights: Arc<[TextHighlight]>) -> Self {
        if !highlights.is_empty() {
            self.highlights = Some(highlights);
        }
        self
    }

    fn has_visible_paint(&self) -> bool {
        self.opacity > 0.0
            && (self.style.color.a > 0.0
                || (self.style.underline != TextUnderline::None
                    && self.style.underline_thickness > 0.0
                    && self
                        .style
                        .underline_color
                        .is_some_and(|color| color.a > 0.0))
                || self
                    .style
                    .strikethrough_color
                    .is_some_and(|color| self.style.strikethrough && color.a > 0.0)
                || self.highlights.as_deref().is_some_and(|highlights| {
                    highlights.iter().any(|highlight| {
                        let style = &highlight.style;
                        style.color.is_some_and(|color| color.a > 0.0)
                            || style.background.is_some_and(|color| color.a > 0.0)
                            || (style.underline != TextUnderline::None
                                && style.underline_thickness != Some(0.0)
                                && style.underline_color.is_some_and(|color| color.a > 0.0))
                            || (style.strikethrough
                                && style.strikethrough_color.is_some_and(|color| color.a > 0.0))
                    })
                }))
    }
}

/// The two framework-rendered planes around platform-native child content.
///
/// Without native children, both planes share the window's WGPU surface. When a macOS `NSView` is
/// mounted, QuickGUI lazily presents the overlay plane through a transparent second WGPU surface,
/// placing AppKit content between the two GPU planes without changing application view code.
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum ScenePlane {
    #[default]
    Base,
    Overlay,
}

#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct PaintLayerKey {
    pub plane: ScenePlane,
    pub z_index: i16,
}

#[derive(Debug)]
pub(crate) struct PaintLayer {
    key: PaintLayerKey,
    quads: Vec<Quad>,
    wavy_underlines: Vec<WavyUnderline>,
    shadows: Vec<Shadow>,
    shapes: Vec<ShapeRef>,
    images: Vec<ImagePrimitive>,
    svgs: Vec<SvgPrimitive>,
    paths: Vec<PathPrimitive>,
    custom_shaders: Vec<CustomShaderPrimitive>,
    text: Vec<TextRun>,
    paint: Vec<PaintItem>,
    order_tree: BoundsOrderTree,
    max_order: u32,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ShapeRef {
    Quad(usize),
    WavyUnderline(usize),
    Shadow(usize),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PrimitiveRef {
    Shape(ShapeRef),
    Image(usize),
    Svg(usize),
    Path(usize),
    CustomShader(usize),
    Text(usize),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct PaintItem {
    pub order: u32,
    pub primitive: PrimitiveRef,
}

impl PaintLayer {
    fn new(key: PaintLayerKey) -> Self {
        Self {
            key,
            quads: Vec::new(),
            wavy_underlines: Vec::new(),
            shadows: Vec::new(),
            shapes: Vec::new(),
            images: Vec::new(),
            svgs: Vec::new(),
            paths: Vec::new(),
            custom_shaders: Vec::new(),
            text: Vec::new(),
            paint: Vec::new(),
            order_tree: BoundsOrderTree::default(),
            max_order: 0,
        }
    }

    pub(crate) fn key(&self) -> PaintLayerKey {
        self.key
    }

    pub(crate) fn quads(&self) -> &[Quad] {
        &self.quads
    }

    pub(crate) fn wavy_underlines(&self) -> &[WavyUnderline] {
        &self.wavy_underlines
    }

    pub(crate) fn shadows(&self) -> &[Shadow] {
        &self.shadows
    }

    #[cfg(test)]
    pub(crate) fn shapes(&self) -> &[ShapeRef] {
        &self.shapes
    }

    pub(crate) fn images(&self) -> &[ImagePrimitive] {
        &self.images
    }

    pub(crate) fn svgs(&self) -> &[SvgPrimitive] {
        &self.svgs
    }

    pub(crate) fn paths(&self) -> &[PathPrimitive] {
        &self.paths
    }

    pub(crate) fn custom_shaders(&self) -> &[CustomShaderPrimitive] {
        &self.custom_shaders
    }

    pub(crate) fn text_runs(&self) -> &[TextRun] {
        &self.text
    }

    pub(crate) fn paint(&self) -> &[PaintItem] {
        &self.paint
    }

    pub(crate) fn max_order(&self) -> u32 {
        self.max_order
    }

    fn push_paint(&mut self, bounds: Rect, primitive: PrimitiveRef) {
        debug_assert!(valid_bounds(bounds));
        let order = self.order_tree.insert(bounds);
        self.max_order = self.max_order.max(order);
        self.paint.push(PaintItem { order, primitive });
    }

    fn clear(&mut self) {
        self.quads.clear();
        self.wavy_underlines.clear();
        self.shadows.clear();
        self.shapes.clear();
        self.images.clear();
        self.svgs.clear();
        self.paths.clear();
        self.custom_shaders.clear();
        self.text.clear();
        self.paint.clear();
        self.order_tree.clear();
        self.max_order = 0;
    }
}

/// A reusable display list. [`Scene::clear`] retains its allocations.
#[derive(Debug)]
pub struct Scene {
    background: Color,
    layers: Vec<PaintLayer>,
    used_layers: usize,
    opacity: f32,
}

impl Scene {
    pub fn new() -> Self {
        Self {
            background: Color::BLACK,
            layers: vec![PaintLayer {
                key: PaintLayerKey::default(),
                quads: Vec::with_capacity(256),
                wavy_underlines: Vec::with_capacity(32),
                shadows: Vec::with_capacity(64),
                shapes: Vec::with_capacity(320),
                images: Vec::with_capacity(64),
                svgs: Vec::with_capacity(64),
                paths: Vec::with_capacity(64),
                custom_shaders: Vec::with_capacity(16),
                text: Vec::with_capacity(128),
                paint: Vec::with_capacity(512),
                order_tree: BoundsOrderTree::with_capacity(512),
                max_order: 0,
            }],
            used_layers: 1,
            opacity: 1.0,
        }
    }

    pub fn clear(&mut self, background: Color) {
        self.background = background;
        if self.layers.len() > MAX_RETAINED_PAINT_LAYERS {
            self.layers.truncate(MAX_RETAINED_PAINT_LAYERS);
        }
        for layer in &mut self.layers {
            layer.clear();
        }
        if self.layers.is_empty() {
            self.layers.push(PaintLayer::new(PaintLayerKey::default()));
        }
        self.layers[0].key = PaintLayerKey::default();
        self.used_layers = 1;
        self.opacity = 1.0;
    }

    pub fn push_quad(&mut self, quad: Quad) {
        self.push_quad_in(PaintLayerKey::default(), quad);
    }

    pub(crate) fn push_quad_in(&mut self, key: PaintLayerKey, mut quad: Quad) {
        quad.fill = quad.fill.multiply_alpha(self.opacity);
        quad.border_color = quad.border_color.multiply_alpha(self.opacity);
        if (quad.fill.a > 0.0 || quad.border_color.a > 0.0)
            && let Some(bounds) = clipped_paint_bounds(quad.rect, [quad.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.quads.len();
            layer.quads.push(quad);
            let shape = ShapeRef::Quad(index);
            layer.shapes.push(shape);
            layer.push_paint(bounds, PrimitiveRef::Shape(shape));
        }
    }

    pub(crate) fn push_wavy_underline_in(
        &mut self,
        key: PaintLayerKey,
        mut underline: WavyUnderline,
    ) {
        underline.color = underline.color.multiply_alpha(self.opacity);
        if underline.color.a > 0.0
            && underline.thickness > 0.0
            && underline.amplitude >= 0.0
            && underline.wavelength > 0.0
            && underline.baseline.is_finite()
            && let Some(bounds) = clipped_paint_bounds(underline.rect, [underline.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.wavy_underlines.len();
            layer.wavy_underlines.push(underline);
            let shape = ShapeRef::WavyUnderline(index);
            layer.shapes.push(shape);
            layer.push_paint(bounds, PrimitiveRef::Shape(shape));
        }
    }

    pub fn push_shadow(&mut self, shadow: Shadow) {
        self.push_shadow_in(PaintLayerKey::default(), shadow);
    }

    pub(crate) fn push_shadow_in(&mut self, key: PaintLayerKey, mut shadow: Shadow) {
        shadow.style = shadow.style.multiply_alpha(self.opacity);
        if shadow.style.color().a > 0.0
            && let Some(bounds) = shadow_render_bounds(&shadow)
            && let Some(bounds) = clipped_paint_bounds(bounds, [shadow.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.shadows.len();
            layer.shadows.push(shadow);
            let shape = ShapeRef::Shadow(index);
            layer.shapes.push(shape);
            layer.push_paint(bounds, PrimitiveRef::Shape(shape));
        }
    }

    pub fn fill(&mut self, rect: Rect, color: Color) {
        self.push_quad(Quad::new(rect, color));
    }

    pub fn push_image(&mut self, image: ImagePrimitive) {
        self.push_image_in(PaintLayerKey::default(), image);
    }

    pub(crate) fn push_image_in(&mut self, key: PaintLayerKey, mut image: ImagePrimitive) {
        image.opacity = sanitize_opacity(image.opacity * self.opacity);
        if image.opacity > 0.0
            && valid_bounds(image.source_uv)
            && let Some(bounds) =
                clipped_paint_bounds(image.destination, [Some(image.mask), image.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.images.len();
            layer.images.push(image);
            layer.push_paint(bounds, PrimitiveRef::Image(index));
        }
    }

    pub fn push_svg(&mut self, svg: SvgPrimitive) {
        self.push_svg_in(PaintLayerKey::default(), svg);
    }

    pub fn push_path(&mut self, path: PathPrimitive) {
        self.push_path_in(PaintLayerKey::default(), path);
    }

    pub(crate) fn push_path_in(&mut self, key: PaintLayerKey, mut path: PathPrimitive) {
        path.background = path.background.multiply_alpha(self.opacity);
        if !path.path.is_empty()
            && path.background.is_visible()
            && let Some(bounds) = clipped_paint_bounds(path.render_bounds(), [path.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.paths.len();
            layer.paths.push(path);
            layer.push_paint(bounds, PrimitiveRef::Path(index));
        }
    }

    pub fn push_custom_shader(&mut self, shader: CustomShaderPrimitive) {
        self.push_custom_shader_in(PaintLayerKey::default(), shader);
    }

    pub(crate) fn push_custom_shader_in(
        &mut self,
        key: PaintLayerKey,
        mut shader: CustomShaderPrimitive,
    ) {
        shader.opacity = sanitize_opacity(shader.opacity * self.opacity);
        if shader.opacity > 0.0
            && let Some(bounds) = clipped_paint_bounds(shader.rect, [shader.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.custom_shaders.len();
            layer.custom_shaders.push(shader);
            layer.push_paint(bounds, PrimitiveRef::CustomShader(index));
        }
    }

    pub(crate) fn push_svg_in(&mut self, key: PaintLayerKey, mut svg: SvgPrimitive) {
        svg.color = svg.color.multiply_alpha(self.opacity);
        if !svg.destination.is_empty()
            && !svg.source_uv.is_empty()
            && !svg.mask.is_empty()
            && svg.color.a > 0.0
            && let Some(bounds) =
                clipped_paint_bounds(svg.render_bounds(), [Some(svg.mask), svg.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.svgs.len();
            layer.svgs.push(svg);
            layer.push_paint(bounds, PrimitiveRef::Svg(index));
        }
    }

    pub fn push_text(&mut self, text: TextRun) {
        self.push_text_in(PaintLayerKey::default(), text);
    }

    pub(crate) fn push_text_in(&mut self, key: PaintLayerKey, mut text: TextRun) {
        text.opacity = sanitize_opacity(text.opacity * self.opacity);
        if text.has_visible_paint()
            && let Some(bounds) = clipped_paint_bounds(text.bounds, [text.clip])
        {
            let layer = self.layer_mut(key);
            let index = layer.text.len();
            layer.text.push(text);
            layer.push_paint(bounds, PrimitiveRef::Text(index));
        }
    }

    pub fn background(&self) -> Color {
        self.background
    }

    pub(crate) fn multiply_opacity(&mut self, opacity: f32) -> f32 {
        let previous = self.opacity;
        self.opacity = sanitize_opacity(previous * sanitize_opacity(opacity));
        previous
    }

    pub(crate) fn restore_opacity(&mut self, opacity: f32) {
        self.opacity = sanitize_opacity(opacity);
    }

    pub(crate) fn current_opacity(&self) -> f32 {
        self.opacity
    }

    pub fn quads(&self) -> &[Quad] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::quads)
            .unwrap_or_default()
    }

    pub fn text_runs(&self) -> &[TextRun] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::text_runs)
            .unwrap_or_default()
    }

    pub fn shadows(&self) -> &[Shadow] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::shadows)
            .unwrap_or_default()
    }

    pub fn images(&self) -> &[ImagePrimitive] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::images)
            .unwrap_or_default()
    }

    pub fn svgs(&self) -> &[SvgPrimitive] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::svgs)
            .unwrap_or_default()
    }

    pub fn paths(&self) -> &[PathPrimitive] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::paths)
            .unwrap_or_default()
    }

    pub fn custom_shaders(&self) -> &[CustomShaderPrimitive] {
        self.layers
            .iter()
            .take(self.used_layers)
            .find(|layer| layer.key == PaintLayerKey::default())
            .map(PaintLayer::custom_shaders)
            .unwrap_or_default()
    }

    pub(crate) fn finish(&mut self) {
        self.layers[..self.used_layers].sort_by_key(PaintLayer::key);
    }

    pub(crate) fn paint_layers(&self) -> &[PaintLayer] {
        &self.layers[..self.used_layers]
    }

    pub(crate) fn has_content_in_plane(&self, plane: ScenePlane) -> bool {
        self.paint_layers()
            .iter()
            .any(|layer| layer.key.plane == plane && !layer.paint.is_empty())
    }

    fn layer_mut(&mut self, key: PaintLayerKey) -> &mut PaintLayer {
        if let Some(index) = self.layers[..self.used_layers]
            .iter()
            .position(|layer| layer.key == key)
        {
            return &mut self.layers[index];
        }

        let index = self.used_layers;
        self.used_layers += 1;
        if index == self.layers.len() {
            self.layers.push(PaintLayer::new(key));
        } else {
            self.layers[index].key = key;
            self.layers[index].clear();
        }
        &mut self.layers[index]
    }
}

const SHADOW_SIGMA_PER_BLUR_RADIUS: f32 = 0.5;
const SHADOW_MARGIN_SIGMAS: f32 = 3.0;

pub(crate) fn shadow_render_bounds(shadow: &Shadow) -> Option<Rect> {
    let style = shadow.style;
    let geometry = if style.is_inset() {
        shadow.element_rect
    } else {
        let subject = dilate_rect(
            shadow.element_rect.translate(style.offset()),
            style.spread(),
        );
        if !valid_bounds(subject) {
            return None;
        }
        let margin = style.blur() * SHADOW_SIGMA_PER_BLUR_RADIUS * SHADOW_MARGIN_SIGMAS + 1.0;
        dilate_rect(subject, margin)
    };
    valid_bounds(geometry).then_some(geometry)
}

fn clipped_paint_bounds<const N: usize>(
    mut bounds: Rect,
    clips: [Option<Rect>; N],
) -> Option<Rect> {
    if !valid_bounds(bounds) {
        return None;
    }
    for clip in clips.into_iter().flatten() {
        if !valid_bounds(clip) {
            return None;
        }
        bounds = bounds.intersection(clip)?;
    }
    Some(bounds)
}

fn sanitize_opacity(opacity: f32) -> f32 {
    if opacity.is_finite() {
        opacity.clamp(0.0, 1.0)
    } else {
        1.0
    }
}

fn dilate_rect(rect: Rect, amount: f32) -> Rect {
    let left = rect.x - amount;
    let top = rect.y - amount;
    let right = rect.right() + amount;
    let bottom = rect.bottom() + amount;
    let width = (right - left).max(0.0);
    let height = (bottom - top).max(0.0);
    Rect::new(
        if width > 0.0 {
            left
        } else {
            (left + right) * 0.5
        },
        if height > 0.0 {
            top
        } else {
            (top + bottom) * 0.5
        },
        width,
        height,
    )
}

impl Default for Scene {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Point;

    #[test]
    fn named_text_ids_are_stable_and_distinct() {
        assert_eq!(TextId::named("row:42"), TextId::named("row:42"));
        assert_ne!(TextId::named("row:42"), TextId::named("row:43"));
    }

    #[test]
    fn transparent_primitives_are_dropped() {
        let mut scene = Scene::new();
        scene.fill(Rect::new(0.0, 0.0, 10.0, 10.0), Color::TRANSPARENT);
        assert!(scene.quads().is_empty());
    }

    #[test]
    fn scoped_opacity_multiplies_retained_primitives_and_restores_exactly() {
        let mut scene = Scene::new();
        let previous = scene.multiply_opacity(0.5);
        assert_eq!(previous, 1.0);
        let parent = scene.multiply_opacity(0.5);
        assert_eq!(parent, 0.5);

        scene.push_quad(
            Quad::new(Rect::new(0.0, 0.0, 10.0, 10.0), Color::WHITE).border(1.0, Color::WHITE),
        );
        scene.push_shadow(Shadow::new(
            Rect::new(0.0, 0.0, 10.0, 10.0),
            BoxShadow::new(0.0, 1.0, Color::WHITE),
        ));
        scene.push_text(
            TextRun::new(
                TextId::new(91),
                Arc::from("faded"),
                Rect::new(0.0, 0.0, 40.0, 20.0),
                TextStyle::new(14.0, Color::WHITE),
            )
            .opacity(0.5),
        );
        let shader = CustomShader::new(
            "fn quickgui_fragment(input: QuickGuiShaderInput) -> vec4<f32> { return vec4<f32>(1.0, 1.0, 1.0, 1.0 + input.uv.x * 0.0); }",
        )
        .unwrap();
        scene.push_custom_shader(
            CustomShaderPrimitive::new(shader, Rect::new(0.0, 0.0, 10.0, 10.0)).opacity(0.5),
        );

        assert_eq!(scene.quads()[0].fill.a, 0.25);
        assert_eq!(scene.quads()[0].border_color.a, 0.25);
        assert_eq!(scene.shadows()[0].style.color().a, 0.25);
        assert_eq!(scene.text_runs()[0].opacity, 0.125);
        assert_eq!(scene.custom_shaders()[0].opacity, 0.125);

        scene.restore_opacity(parent);
        scene.restore_opacity(previous);
        scene.push_quad(Quad::new(Rect::new(20.0, 0.0, 10.0, 10.0), Color::WHITE));
        assert_eq!(scene.quads()[1].fill.a, 1.0);

        scene.multiply_opacity(0.0);
        scene.clear(Color::BLACK);
        assert_eq!(scene.current_opacity(), 1.0);
    }

    #[test]
    fn text_wraps_by_default_and_can_opt_out() {
        let style = TextStyle::new(14.0, Color::WHITE);
        assert_eq!(style.align, TextAlign::Left);
        assert_eq!(style.wrap, TextWrap::Word);
        assert_eq!(style.wrap(TextWrap::None).wrap, TextWrap::None);
    }

    #[test]
    fn box_shadow_sanitizes_non_finite_and_negative_blur_values() {
        let shadow = BoxShadow::new(f32::NAN, f32::INFINITY, Color::WHITE)
            .blur_radius(-8.0)
            .spread_radius(f32::NEG_INFINITY)
            .inset(true);
        assert_eq!(shadow.offset(), Vector::ZERO);
        assert_eq!(shadow.blur(), 0.0);
        assert_eq!(shadow.spread(), 0.0);
        assert!(shadow.is_inset());

        let clamped = BoxShadow::new(f32::MAX, f32::MIN, Color::WHITE)
            .blur_radius(f32::MAX)
            .spread_radius(f32::MAX);
        assert_eq!(clamped.offset().x, MAX_BOX_SHADOW_EXTENT);
        assert_eq!(clamped.offset().y, -MAX_BOX_SHADOW_EXTENT);
        assert_eq!(clamped.blur(), MAX_BOX_SHADOW_BLUR_RADIUS);
        assert_eq!(clamped.spread(), MAX_BOX_SHADOW_EXTENT);
    }

    #[test]
    fn shape_stream_preserves_quad_and_shadow_insertion_order() {
        let mut scene = Scene::new();
        let rect = Rect::new(10.0, 10.0, 40.0, 30.0);
        scene.push_shadow(Shadow::new(rect, BoxShadow::new(0.0, 4.0, Color::WHITE)));
        scene.push_quad(Quad::new(rect, Color::WHITE));
        scene.push_shadow(Shadow::new(
            rect,
            BoxShadow::new(0.0, 0.0, Color::WHITE).inset(true),
        ));

        let layer = &scene.paint_layers()[0];
        assert_eq!(layer.quads().len(), 1);
        assert_eq!(layer.shadows().len(), 2);
        assert_eq!(
            layer.shapes(),
            &[ShapeRef::Shadow(0), ShapeRef::Quad(0), ShapeRef::Shadow(1)]
        );
    }

    #[test]
    fn paint_stream_assigns_cross_primitive_overlap_depth() {
        let mut scene = Scene::new();
        scene.push_quad(Quad::new(Rect::new(0.0, 0.0, 10.0, 10.0), Color::WHITE));
        scene.push_text(TextRun::new(
            TextId::new(1),
            Arc::from("disjoint"),
            Rect::new(20.0, 0.0, 10.0, 10.0),
            TextStyle::new(12.0, Color::WHITE),
        ));
        scene.push_text(TextRun::new(
            TextId::new(2),
            Arc::from("bridge"),
            Rect::new(5.0, 0.0, 20.0, 10.0),
            TextStyle::new(12.0, Color::WHITE),
        ));
        scene.push_quad(Quad::new(Rect::new(6.0, 1.0, 2.0, 2.0), Color::WHITE));

        let layer = &scene.paint_layers()[0];
        assert_eq!(
            layer.paint(),
            &[
                PaintItem {
                    order: 0,
                    primitive: PrimitiveRef::Shape(ShapeRef::Quad(0)),
                },
                PaintItem {
                    order: 0,
                    primitive: PrimitiveRef::Text(0),
                },
                PaintItem {
                    order: 1,
                    primitive: PrimitiveRef::Text(1),
                },
                PaintItem {
                    order: 2,
                    primitive: PrimitiveRef::Shape(ShapeRef::Quad(1)),
                },
            ]
        );
        assert_eq!(layer.max_order(), 2);
    }

    #[test]
    fn custom_shaders_participate_in_cross_primitive_paint_order() {
        let shader = CustomShader::new(
            r#"
fn quickgui_fragment(input: QuickGuiShaderInput) -> vec4<f32> {
    return vec4<f32>(input.uv, 0.0, 1.0);
}
"#,
        )
        .unwrap();
        let mut scene = Scene::new();
        scene.push_quad(Quad::new(Rect::new(0.0, 0.0, 20.0, 20.0), Color::WHITE));
        scene.push_custom_shader(CustomShaderPrimitive::new(
            shader,
            Rect::new(5.0, 5.0, 10.0, 10.0),
        ));

        let layer = &scene.paint_layers()[0];
        assert_eq!(layer.custom_shaders().len(), 1);
        assert_eq!(layer.paint()[1].order, 1);
        assert_eq!(layer.paint()[1].primitive, PrimitiveRef::CustomShader(0));
    }

    #[test]
    fn paint_order_uses_effective_clipped_bounds() {
        let mut scene = Scene::new();
        let raw = Rect::new(0.0, 0.0, 100.0, 20.0);
        scene.push_quad(Quad::new(raw, Color::WHITE).clip(Rect::new(0.0, 0.0, 10.0, 20.0)));
        scene.push_quad(Quad::new(raw, Color::WHITE).clip(Rect::new(20.0, 0.0, 10.0, 20.0)));

        let layer = &scene.paint_layers()[0];
        assert_eq!(
            layer
                .paint()
                .iter()
                .map(|item| item.order)
                .collect::<Vec<_>>(),
            vec![0, 0]
        );
    }

    #[test]
    fn paths_participate_in_cross_primitive_overlap_order() {
        let mut builder = crate::PathBuilder::fill();
        builder.move_to(Point::new(0.0, 0.0));
        builder.line_to(Point::new(10.0, 0.0));
        builder.line_to(Point::new(10.0, 10.0));
        builder.line_to(Point::new(0.0, 10.0));
        builder.close();
        let path = builder.build().unwrap();

        let mut scene = Scene::new();
        scene.push_quad(Quad::new(Rect::new(0.0, 0.0, 10.0, 10.0), Color::WHITE));
        scene.push_path(PathPrimitive::new(&path, Color::WHITE).translate(5.0, 0.0));
        scene.push_text(TextRun::new(
            TextId::new(9),
            Arc::from("above"),
            Rect::new(12.0, 0.0, 10.0, 10.0),
            TextStyle::new(12.0, Color::WHITE),
        ));

        let layer = &scene.paint_layers()[0];
        assert_eq!(scene.paths().len(), 1);
        assert_eq!(
            layer.paint(),
            &[
                PaintItem {
                    order: 0,
                    primitive: PrimitiveRef::Shape(ShapeRef::Quad(0)),
                },
                PaintItem {
                    order: 1,
                    primitive: PrimitiveRef::Path(0),
                },
                PaintItem {
                    order: 2,
                    primitive: PrimitiveRef::Text(0),
                },
            ]
        );
    }

    #[test]
    fn path_bounds_include_scale_translation_and_effective_clip() {
        let mut builder = crate::PathBuilder::fill();
        builder.move_to(Point::new(10.0, 20.0));
        builder.line_to(Point::new(30.0, 20.0));
        builder.line_to(Point::new(30.0, 40.0));
        builder.line_to(Point::new(10.0, 40.0));
        builder.close();
        let path = builder.build().unwrap();
        let primitive = PathPrimitive::new(path, Color::WHITE)
            .scale_xy(-2.0, 3.0)
            .translate(100.0, -20.0)
            .clip(Rect::new(45.0, 45.0, 20.0, 20.0));
        assert_eq!(primitive.render_bounds(), Rect::new(40.0, 40.0, 40.0, 60.0));

        let mut scene = Scene::new();
        scene.push_path(primitive);
        scene.push_quad(Quad::new(Rect::new(66.0, 45.0, 5.0, 5.0), Color::WHITE));
        assert_eq!(
            scene.paint_layers()[0]
                .paint()
                .iter()
                .map(|item| item.order)
                .collect::<Vec<_>>(),
            vec![0, 0]
        );
    }

    #[test]
    fn paint_layers_sort_base_before_overlay_and_reuse_matching_z_indices() {
        let mut scene = Scene::new();
        let overlay = PaintLayerKey {
            plane: ScenePlane::Overlay,
            z_index: -2,
        };
        let raised_base = PaintLayerKey {
            plane: ScenePlane::Base,
            z_index: 3,
        };
        scene.push_quad_in(
            overlay,
            Quad::new(Rect::new(0.0, 0.0, 2.0, 2.0), Color::WHITE),
        );
        scene.push_quad_in(
            raised_base,
            Quad::new(Rect::new(0.0, 0.0, 2.0, 2.0), Color::WHITE),
        );
        scene.push_quad_in(
            overlay,
            Quad::new(Rect::new(2.0, 2.0, 2.0, 2.0), Color::WHITE),
        );
        scene.finish();

        let layers = scene.paint_layers();
        assert_eq!(layers.len(), 3);
        assert_eq!(layers[0].key(), PaintLayerKey::default());
        assert_eq!(layers[1].key(), raised_base);
        assert_eq!(layers[2].key(), overlay);
        assert_eq!(layers[2].quads().len(), 2);
    }
}