cranpose-ui-graphics 0.12.0

Geometry, units, paths and render data for Cranpose UI
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
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
//! Geometric primitives: Point, Size, Rect, Insets, Path

use std::{ops::AddAssign, rc::Rc};

use crate::{
    ArcRecordArgs, Brush, Color, ColorFilter, CommandRecorder, CommandRecording, ImageBitmap,
    ImageSampling, PathFillRule, Trapezoid, normalized_band,
    path::{DrawStyle, Path},
    stroke::{LineGeometry, Stroke},
    typography::{
        DrawTextMeasurer, DrawTextStyle, TextAlign, TextMeasurement, TextVerticalAlign,
        estimate_text_measurement,
    },
};

const VECTOR_PATH_MASK_CACHE_ENTRIES: usize = 96;
const VECTOR_PATH_MASK_CACHE_BYTES: usize = 8 * 1024 * 1024;

pub(crate) struct VectorPathMaskCache {
    entries: Vec<(u64, ImageBitmap)>,
    bytes: usize,
}

impl VectorPathMaskCache {
    pub(crate) const fn new() -> Self {
        Self {
            entries: Vec::new(),
            bytes: 0,
        }
    }

    fn get(&mut self, key: u64) -> Option<ImageBitmap> {
        let index = self.entries.iter().position(|(seen, _)| *seen == key)?;
        let entry = self.entries.remove(index);
        let image = entry.1.clone();
        self.entries.push(entry);
        Some(image)
    }

    fn put(&mut self, key: u64, image: ImageBitmap) {
        let bytes = image.pixels().len();
        if bytes > VECTOR_PATH_MASK_CACHE_BYTES {
            return;
        }
        self.bytes += bytes;
        self.entries.push((key, image));
        while self.entries.len() > VECTOR_PATH_MASK_CACHE_ENTRIES
            || self.bytes > VECTOR_PATH_MASK_CACHE_BYTES
        {
            let (_, dropped) = self.entries.remove(0);
            self.bytes = self.bytes.saturating_sub(dropped.pixels().len());
        }
    }
}

fn vector_path_mask_key(
    path: &crate::VectorPath,
    origin: Point,
    mask_size: (usize, usize),
    rgb: [u8; 3],
    alpha: f32,
) -> u64 {
    use std::hash::Hasher;
    let mut hasher = crate::fx_hash::FxHasher::default();
    hasher.write_u8(path.fill_rule() as u8);
    hasher.write_u32(origin.x.to_bits());
    hasher.write_u32(origin.y.to_bits());
    hasher.write_usize(mask_size.0);
    hasher.write_usize(mask_size.1);
    hasher.write(&rgb);
    hasher.write_u32(alpha.to_bits());
    for subpath in path.subpaths() {
        hasher.write_usize(subpath.len());
        for point in subpath {
            hasher.write_u32(point.x.to_bits());
            hasher.write_u32(point.y.to_bits());
        }
    }
    hasher.finish()
}

fn vector_path_mask_cache_get(key: u64) -> Option<ImageBitmap> {
    crate::thread_state::with(|state| state.vector_path_masks.borrow_mut().get(key))
}

fn vector_path_mask_cache_put(key: u64, image: ImageBitmap) {
    crate::thread_state::with(|state| state.vector_path_masks.borrow_mut().put(key, image));
}

/// A position in two dimensions, in logical pixels. Compose's `Offset`.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Point {
    /// Horizontal coordinate, in logical pixels, growing to the right.
    pub x: f32,
    /// Vertical coordinate, in logical pixels, growing downward.
    pub y: f32,
}

impl Point {
    /// Creates a point from its coordinates.
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    /// The origin point `(0.0, 0.0)`.
    pub const ZERO: Point = Point { x: 0.0, y: 0.0 };
}

/// A width and a height, in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Size {
    /// Width, in logical pixels.
    pub width: f32,
    /// Height, in logical pixels.
    pub height: f32,
}

impl Size {
    /// Creates a size from a width and a height.
    pub const fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }

    /// A size of zero width and zero height.
    pub const ZERO: Size = Size {
        width: 0.0,
        height: 0.0,
    };
}

/// An axis-aligned rectangle given by its top-left corner and its size, in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rect {
    /// Left edge, in logical pixels.
    pub x: f32,
    /// Top edge, in logical pixels.
    pub y: f32,
    /// Width, in logical pixels.
    pub width: f32,
    /// Height, in logical pixels.
    pub height: f32,
}

impl Rect {
    /// The rect that holds nothing: what two clips that do not overlap
    /// resolve to, so a clip that meets nothing stays a clip instead of
    /// lifting.
    pub const EMPTY: Rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 0.0,
        height: 0.0,
    };

    /// Creates a rectangle with its top-left corner at `origin` and the given `size`.
    pub fn from_origin_size(origin: Point, size: Size) -> Self {
        Self {
            x: origin.x,
            y: origin.y,
            width: size.width,
            height: size.height,
        }
    }

    /// Creates a rectangle of `size` with its top-left corner at the origin.
    pub fn from_size(size: Size) -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            width: size.width,
            height: size.height,
        }
    }

    /// Returns the rectangle moved by `dx` horizontally and `dy` vertically.
    pub fn translate(&self, dx: f32, dy: f32) -> Self {
        Self {
            x: self.x + dx,
            y: self.y + dy,
            width: self.width,
            height: self.height,
        }
    }

    /// Whether the point `(x, y)` lies inside the rectangle, edges included.
    pub fn contains(&self, x: f32, y: f32) -> bool {
        x >= self.x && y >= self.y && x <= self.x + self.width && y <= self.y + self.height
    }

    /// Whether the rect covers no area, so nothing clipped to it can paint.
    pub fn is_empty(&self) -> bool {
        self.width <= 0.0 || self.height <= 0.0
    }

    /// Returns the intersection of two rectangles, or `None` if they don't overlap.
    pub fn intersect(&self, other: Rect) -> Option<Rect> {
        let left = self.x.max(other.x);
        let top = self.y.max(other.y);
        let right = (self.x + self.width).min(other.x + other.width);
        let bottom = (self.y + self.height).min(other.y + other.height);
        let width = right - left;
        let height = bottom - top;
        if width <= 0.0 || height <= 0.0 {
            None
        } else {
            Some(Rect {
                x: left,
                y: top,
                width,
                height,
            })
        }
    }

    /// Returns the smallest rectangle that contains both rectangles.
    pub fn union(&self, other: Rect) -> Rect {
        let left = self.x.min(other.x);
        let top = self.y.min(other.y);
        let right = (self.x + self.width).max(other.x + other.width);
        let bottom = (self.y + self.height).max(other.y + other.height);
        Rect {
            x: left,
            y: top,
            width: (right - left).max(0.0),
            height: (bottom - top).max(0.0),
        }
    }
}

/// Padding values for each edge of a rectangle.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct EdgeInsets {
    /// Inset on the left edge, in logical pixels.
    pub left: f32,
    /// Inset on the top edge, in logical pixels.
    pub top: f32,
    /// Inset on the right edge, in logical pixels.
    pub right: f32,
    /// Inset on the bottom edge, in logical pixels.
    pub bottom: f32,
}

impl EdgeInsets {
    /// Creates insets with `all` on every edge.
    pub fn uniform(all: f32) -> Self {
        Self {
            left: all,
            top: all,
            right: all,
            bottom: all,
        }
    }

    /// Creates insets with `horizontal` on the left and right and 0.0 on the top and bottom.
    pub fn horizontal(horizontal: f32) -> Self {
        Self {
            left: horizontal,
            right: horizontal,
            ..Self::default()
        }
    }

    /// Creates insets with `vertical` on the top and bottom and 0.0 on the left and right.
    pub fn vertical(vertical: f32) -> Self {
        Self {
            top: vertical,
            bottom: vertical,
            ..Self::default()
        }
    }

    /// Creates insets with `horizontal` on the left and right and `vertical` on the top and bottom.
    pub fn symmetric(horizontal: f32, vertical: f32) -> Self {
        Self {
            left: horizontal,
            right: horizontal,
            top: vertical,
            bottom: vertical,
        }
    }

    /// Creates insets from separate left, top, right and bottom values.
    pub fn from_components(left: f32, top: f32, right: f32, bottom: f32) -> Self {
        Self {
            left,
            top,
            right,
            bottom,
        }
    }

    /// Whether all four insets are 0.0.
    pub fn is_zero(&self) -> bool {
        self.left == 0.0 && self.top == 0.0 && self.right == 0.0 && self.bottom == 0.0
    }

    /// The sum of the left and right insets.
    pub fn horizontal_sum(&self) -> f32 {
        self.left + self.right
    }

    /// The sum of the top and bottom insets.
    pub fn vertical_sum(&self) -> f32 {
        self.top + self.bottom
    }

    /// The part of a `size` rect these insets leave, at the leading insets;
    /// it never shrinks below zero.
    pub fn inset_rect(&self, size: Size) -> Rect {
        Rect {
            x: self.left,
            y: self.top,
            width: (size.width - self.horizontal_sum()).max(0.0),
            height: (size.height - self.vertical_sum()).max(0.0),
        }
    }
}

impl AddAssign for EdgeInsets {
    fn add_assign(&mut self, rhs: Self) {
        self.left += rhs.left;
        self.top += rhs.top;
        self.right += rhs.right;
        self.bottom += rhs.bottom;
    }
}

/// The radius of each corner of a rounded rectangle, in logical pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CornerRadii {
    /// Radius of the top-left corner, in logical pixels.
    pub top_left: f32,
    /// Radius of the top-right corner, in logical pixels.
    pub top_right: f32,
    /// Radius of the bottom-right corner, in logical pixels.
    pub bottom_right: f32,
    /// Radius of the bottom-left corner, in logical pixels.
    pub bottom_left: f32,
}

impl CornerRadii {
    /// Creates radii with the same value on all four corners.
    pub fn uniform(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }
}

/// A rectangle shape with rounded corners. Compose's `RoundedCornerShape`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RoundedCornerShape {
    radii: CornerRadii,
}

impl RoundedCornerShape {
    /// Creates a shape with a separate radius for each corner, in logical pixels.
    pub fn new(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> Self {
        Self {
            radii: CornerRadii {
                top_left,
                top_right,
                bottom_right,
                bottom_left,
            },
        }
    }

    /// Creates a shape with the same radius on all four corners.
    pub fn uniform(radius: f32) -> Self {
        Self {
            radii: CornerRadii::uniform(radius),
        }
    }

    /// Creates a shape from a `CornerRadii` value.
    pub fn with_radii(radii: CornerRadii) -> Self {
        Self { radii }
    }

    /// Returns the radii for a rectangle of `width` by `height`, with each radius limited to half
    /// the width and half the height so the corners fit.
    pub fn resolve(&self, width: f32, height: f32) -> CornerRadii {
        let mut resolved = self.radii;
        let max_width = (width / 2.0).max(0.0);
        let max_height = (height / 2.0).max(0.0);
        resolved.top_left = resolved.top_left.clamp(0.0, max_width).min(max_height);
        resolved.top_right = resolved.top_right.clamp(0.0, max_width).min(max_height);
        resolved.bottom_right = resolved.bottom_right.clamp(0.0, max_width).min(max_height);
        resolved.bottom_left = resolved.bottom_left.clamp(0.0, max_width).min(max_height);
        resolved
    }

    /// The radii as given, before any clamping to a size.
    pub fn radii(&self) -> CornerRadii {
        self.radii
    }
}

/// The pivot point for scaling and rotating a layer, given as fractions of its size. Compose's
/// `TransformOrigin`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TransformOrigin {
    /// Horizontal pivot as a fraction of the layer's width, from 0.0 (left) to 1.0 (right).
    pub pivot_fraction_x: f32,
    /// Vertical pivot as a fraction of the layer's height, from 0.0 (top) to 1.0 (bottom).
    pub pivot_fraction_y: f32,
}

impl TransformOrigin {
    /// Creates an origin from fractions of the layer's width and height.
    pub const fn new(pivot_fraction_x: f32, pivot_fraction_y: f32) -> Self {
        Self {
            pivot_fraction_x,
            pivot_fraction_y,
        }
    }

    /// Pivot at the center of the layer.
    pub const CENTER: TransformOrigin = TransformOrigin::new(0.5, 0.5);
}

impl Default for TransformOrigin {
    fn default() -> Self {
        Self::CENTER
    }
}

/// The outline of a graphics layer, used for clipping and for its shadow.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum LayerShape {
    /// Square corners.
    #[default]
    Rectangle,
    /// Corners rounded by the given shape.
    Rounded(RoundedCornerShape),
}

/// The transform, opacity, clip, shadow and effect properties of a layer. Compose's
/// `GraphicsLayerScope`.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphicsLayer {
    /// Opacity of the layer, from 0.0 (transparent) to 1.0 (opaque).
    pub alpha: f32,
    /// Uniform scale factor for both axes. 1.0 leaves the size unchanged.
    pub scale: f32,
    /// Horizontal scale factor, multiplied with `scale`. 1.0 leaves the width unchanged.
    pub scale_x: f32,
    /// Vertical scale factor, multiplied with `scale`. 1.0 leaves the height unchanged.
    pub scale_y: f32,
    /// Rotation around the x axis, in degrees.
    pub rotation_x: f32,
    /// Rotation around the y axis, in degrees.
    pub rotation_y: f32,
    /// Rotation around the z axis, in degrees. Positive values turn clockwise on screen.
    pub rotation_z: f32,
    /// Distance of the camera from the layer plane. It sets the strength of the perspective for
    /// `rotation_x` and `rotation_y`; larger values flatten it.
    pub camera_distance: f32,
    /// The point that scaling and rotation turn around, as fractions of the layer's size.
    pub transform_origin: TransformOrigin,
    /// Horizontal translation, in layout coordinates.
    pub translation_x: f32,
    /// Vertical translation, in layout coordinates.
    pub translation_y: f32,
    /// Shadow elevation in layout units. A value of 0.0 or less draws no shadow.
    pub shadow_elevation: f32,
    /// Color of the ambient shadow.
    pub ambient_shadow_color: Color,
    /// Color of the spot shadow.
    pub spot_shadow_color: Color,
    /// Outline used for clipping and for the shadow.
    pub shape: LayerShape,
    /// Whether content is clipped to `shape`.
    pub clip: bool,
    /// Whether the layer renders offscreen before it is composited.
    pub compositing_strategy: CompositingStrategy,
    /// How the layer's content combines with what is already drawn behind it.
    pub blend_mode: BlendMode,
    /// Color filter applied to the layer's content, or `None` for none.
    pub color_filter: Option<ColorFilter>,
    /// Filter applied to the layer's rendered content as a whole, such as a blur. `None` applies
    /// none.
    pub render_effect: Option<crate::render_effect::RenderEffect>,
    /// Filters the pixels behind this layer. The result shares the layer's
    /// group opacity and blend mode with its content; `ModulateAlpha` applies
    /// opacity independently to the backdrop and each content draw.
    pub backdrop_effect: Option<crate::render_effect::RenderEffect>,
}

impl GraphicsLayer {
    /// Default properties for an untransformed, opaque layer without effects.
    pub const DEFAULT: Self = Self {
        alpha: 1.0,
        scale: 1.0,
        scale_x: 1.0,
        scale_y: 1.0,
        rotation_x: 0.0,
        rotation_y: 0.0,
        rotation_z: 0.0,
        camera_distance: 8.0,
        transform_origin: TransformOrigin::CENTER,
        translation_x: 0.0,
        translation_y: 0.0,
        shadow_elevation: 0.0,
        ambient_shadow_color: Color::BLACK,
        spot_shadow_color: Color::BLACK,
        shape: LayerShape::Rectangle,
        clip: false,
        compositing_strategy: CompositingStrategy::Auto,
        blend_mode: BlendMode::SrcOver,
        color_filter: None,
        render_effect: None,
        backdrop_effect: None,
    };

    /// The alpha an isolated layer is composited at: an **eight-bit** one,
    /// truncated.
    ///
    /// The platform never composites a layer at a float alpha. HWUI hands an
    /// isolated `RenderNode` to the rasterizer as
    /// `canvas->saveLayerAlpha(&bounds, (int)(properties.getAlpha() * 255))`
    /// (`frameworks/base/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp`,
    /// `setViewProperties`), and `(int)` truncates — 0.5 composites at 127/255,
    /// not at 128/255. The fraction below that byte is gone before a single pixel
    /// is blended, so anything that keeps it lands a level out wherever the byte
    /// and the float fall on opposite sides of a half.
    ///
    /// The sibling branch is a float on purpose: where `getHasOverlappingRendering()`
    /// is false HWUI takes `*alphaMultiplier = properties.getAlpha()` and folds it
    /// into each draw without ever making a byte of it. That is what
    /// `CompositingStrategy::ModulateAlpha` names.
    ///
    /// Truncating here and **rounding** in [`Color::srgb_8bit`] is not an
    /// inconsistency: they are different call sites in the platform. A colour's own
    /// alpha is snapped by `Color`'s constructor, which adds the half; a layer's
    /// alpha is snapped by HWUI's cast, which does not. Anything modelling a faded
    /// layer without allocating one — a canvas drawing a list row's fade by hand,
    /// say — wants this rule and not the other.
    pub fn composite_alpha_8bit(alpha: f32) -> f32 {
        (alpha.clamp(0.0, 1.0) * 255.0).floor() / 255.0
    }
}

impl Default for GraphicsLayer {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Blend mode used for draw primitives.
///
/// This mirrors Jetpack Compose's blend-mode vocabulary while the renderer
/// currently guarantees `SrcOver` and `DstOut` behavior.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BlendMode {
    /// Clears the destination to transparent where the source draws.
    Clear,
    /// Replaces the destination with the source.
    Src,
    /// Keeps the destination and discards the source.
    Dst,
    /// Draws the source over the destination. This is the default.
    #[default]
    SrcOver,
    /// Draws the destination over the source.
    DstOver,
    /// Keeps the source only where the destination is opaque.
    SrcIn,
    /// Keeps the destination only where the source is opaque.
    DstIn,
    /// Keeps the source only where the destination is transparent.
    SrcOut,
    /// Keeps the destination only where the source is transparent.
    DstOut,
    /// Draws the source over the destination, only where the destination is opaque.
    SrcAtop,
    /// Draws the destination over the source, only where the source is opaque.
    DstAtop,
    /// Keeps the source and the destination where the other is transparent.
    Xor,
    /// Adds the source and destination colors and alphas.
    Plus,
    /// Multiplies the source and destination colors and alphas.
    Modulate,
    /// Inverts, multiplies and inverts again, which lightens the result.
    Screen,
    /// Multiplies or screens depending on the destination color, which raises contrast.
    Overlay,
    /// Keeps the darker color of each channel.
    Darken,
    /// Keeps the lighter color of each channel.
    Lighten,
    /// Brightens the destination by the source color.
    ColorDodge,
    /// Darkens the destination by the source color.
    ColorBurn,
    /// Multiplies or screens depending on the source color.
    HardLight,
    /// A softer version of `HardLight`: darkens or lightens depending on the source color.
    SoftLight,
    /// Subtracts the darker color from the lighter one in each channel.
    Difference,
    /// Like `Difference` with lower contrast.
    Exclusion,
    /// Multiplies the source and destination colors, which darkens the result.
    Multiply,
    /// Takes the hue of the source with the saturation and luminosity of the destination.
    Hue,
    /// Takes the saturation of the source with the hue and luminosity of the destination.
    Saturation,
    /// Takes the hue and saturation of the source with the luminosity of the destination.
    Color,
    /// Takes the luminosity of the source with the hue and saturation of the destination.
    Luminosity,
}

impl BlendMode {
    /// Every mode in declaration order, so `mode as u32` indexes it.
    pub const ALL: [BlendMode; 29] = [
        BlendMode::Clear,
        BlendMode::Src,
        BlendMode::Dst,
        BlendMode::SrcOver,
        BlendMode::DstOver,
        BlendMode::SrcIn,
        BlendMode::DstIn,
        BlendMode::SrcOut,
        BlendMode::DstOut,
        BlendMode::SrcAtop,
        BlendMode::DstAtop,
        BlendMode::Xor,
        BlendMode::Plus,
        BlendMode::Modulate,
        BlendMode::Screen,
        BlendMode::Overlay,
        BlendMode::Darken,
        BlendMode::Lighten,
        BlendMode::ColorDodge,
        BlendMode::ColorBurn,
        BlendMode::HardLight,
        BlendMode::SoftLight,
        BlendMode::Difference,
        BlendMode::Exclusion,
        BlendMode::Multiply,
        BlendMode::Hue,
        BlendMode::Saturation,
        BlendMode::Color,
        BlendMode::Luminosity,
    ];
}

/// How a [`GraphicsLayer`] is composited into its parent. Compose's `CompositingStrategy`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CompositingStrategy {
    /// Use renderer heuristics (default).
    #[default]
    Auto,
    /// Render this layer to an offscreen target, then composite.
    Offscreen,
    /// Multiply alpha on source colors without allocating an offscreen layer.
    ModulateAlpha,
}

/// One recorded draw operation, in scope coordinates. Renderers consume these in draw order.
#[derive(Clone, Debug, PartialEq)]
pub enum DrawPrimitive {
    /// Marker emitted by `draw_content()` inside `draw_with_content`.
    /// This is consumed by the modifier pipeline and never rendered directly.
    Content,
    /// Wrapper to associate a draw primitive with a non-default blend mode.
    Blend {
        /// The primitive drawn with `blend_mode`.
        primitive: Box<DrawPrimitive>,
        /// How the wrapped primitive combines with what is already drawn.
        blend_mode: BlendMode,
    },
    /// A rectangle, filled or stroked.
    Rect {
        /// The rectangle in scope coordinates.
        rect: Rect,
        /// Paint for the fill or the stroke.
        brush: Brush,
        /// `None` fills the rect; `Some` strokes its outline, centered on the
        /// edge (so it bleeds `width / 2` outside `rect`).
        stroke: Option<Stroke>,
    },
    /// A rectangle with rounded corners, filled or stroked.
    RoundRect {
        /// The rectangle in scope coordinates.
        rect: Rect,
        /// Paint for the fill or the stroke.
        brush: Brush,
        /// Corner radii of the rectangle, in logical pixels.
        radii: CornerRadii,
        /// `None` fills the rounded rect; `Some` strokes its outline, centered
        /// on the edge.
        stroke: Option<Stroke>,
    },
    /// A circular band: a stroked arc, or a filled annular sector / pie wedge.
    ///
    /// Angles are radians, `0` = +X, increasing **clockwise** on screen (see
    /// `crate::stroke` for the full convention).
    ///
    /// * `stroke = Some(_)` — the band is `radius ± width/2`, its ends shaped
    ///   by the stroke cap. `inner_radius` is ignored.
    /// * `stroke = None` — the band is `inner_radius ..= radius` with flat
    ///   (butt) radial ends; `inner_radius = 0` is a filled pie wedge.
    Arc {
        /// Tight bounding box of the rendered band, caps included. Kept as the
        /// first field (like every other variant) so bbox/culling/clip logic
        /// treats an arc exactly like any other primitive.
        rect: Rect,
        /// Paint for the arc.
        brush: Brush,
        /// Center of the circle the arc lies on, in scope coordinates.
        center: Point,
        /// Radius of the stroked centerline, or the outer radius of a filled sector, in logical
        /// pixels.
        radius: f32,
        /// Where the arc starts, in radians. `0` points along +X and angles increase clockwise on
        /// screen.
        start_angle: f32,
        /// Angle swept from `start_angle`, in radians. A negative value sweeps counter-clockwise.
        sweep_angle: f32,
        /// `Some` strokes the arc; `None` fills the sector between `inner_radius` and `radius`.
        stroke: Option<Stroke>,
        /// `> 0` turns a filled wedge into an annular sector.
        inner_radius: f32,
    },
    /// A stroked straight segment from `start` to `end`, its ends shaped by
    /// the stroke's cap: Compose's `drawLine`.
    Line {
        /// The box of the two ends; the stroke reaches half its width past
        /// it, as a stroked rect's does past its rect.
        rect: Rect,
        /// Paint for the line.
        brush: Brush,
        /// Start of the segment, in scope coordinates.
        start: Point,
        /// End of the segment, in scope coordinates.
        end: Point,
        /// Width and cap of the line.
        stroke: Stroke,
    },
    /// One slice of a filled path, which the draw scope cuts a fill into
    /// so the GPU draws it: see [`Trapezoid`].
    Trapezoid {
        /// The rect `brush` resolves against: the draw scope's own, as a
        /// path's brush resolves in Compose.
        rect: Rect,
        /// Paint for the slice.
        brush: Brush,
        /// The slice to fill.
        trapezoid: Trapezoid,
    },
    /// An image drawn into a destination rectangle.
    Image {
        /// Destination rectangle in scope coordinates. The image is stretched to fill it.
        rect: Rect,
        /// The image to draw.
        image: ImageBitmap,
        /// Opacity from 0.0 (transparent) to 1.0 (opaque).
        alpha: f32,
        /// Color filter applied to the image, or `None` for none.
        color_filter: Option<ColorFilter>,
        /// How pixels are sampled when the image is scaled.
        sampling: ImageSampling,
        /// Optional source rectangle in image-pixel coordinates.
        /// When `None`, the entire image is drawn. When `Some`, only the
        /// specified sub-region of the source image is sampled.
        src_rect: Option<Rect>,
    },
    /// A laid-out run of text. See [`TextPrimitive`].
    Text(Box<TextPrimitive>),
    /// Shadow that requires blur processing. The renderer decides technique
    /// (GPU blur, CPU approximation, etc.).
    Shadow(ShadowPrimitive),
}

/// A run of text, positioned and ready to rasterize.
///
/// `rect` is *already resolved*: [`DrawScope::draw_text_at`] measures the
/// string, applies [`DrawTextStyle::align`] / [`DrawTextStyle::vertical_align`] inside
/// the requested box, and stores the result here. Renderers therefore lay the
/// glyphs out from `rect`'s top-left and never re-align — which is what keeps
/// what [`DrawScope::measure_text`] reported and what lands on screen the same
/// geometry.
#[derive(Clone, Debug, PartialEq)]
pub struct TextPrimitive {
    /// Tight block box: origin is the top-left of the first line's slot, size
    /// is the measured size.
    pub rect: Rect,
    /// Shared so redrawing an unchanged string each frame clones a pointer
    /// rather than the characters.
    pub text: std::rc::Rc<str>,
    /// Font, size, alignment and other styling the glyphs are laid out and drawn with.
    pub style: DrawTextStyle,
    /// Text is filled with a single color: the glyph atlas path modulates one
    /// vertex color per glyph. Gradient brushes are resolved to their first
    /// stop by the draw scope, exactly like [`DrawScope::draw_vector_path`].
    pub color: Color,
}

/// Returns a shared `Rc<str>` for `text`, reusing the copy made on an earlier
/// frame when the content matches.
///
/// Apps hand `draw_text*` a `&str` every frame, and a score counter or label
/// is the same characters frame after frame — without this pool every call
/// copied them into a fresh `Rc<str>` anyway, defeating the sharing
/// [`TextPrimitive::text`] exists for. Hits are verified by content, so a hash
/// collision costs one fresh copy, never the wrong text. The pool clears
/// itself when full; a live scene re-warms within one frame.
fn shared_text_str(text: &str) -> Rc<str> {
    use std::hash::{Hash, Hasher};

    const POOL_CAPACITY: usize = 256;

    let mut hasher = crate::FxHasher::default();
    text.hash(&mut hasher);
    let key = hasher.finish();

    crate::thread_state::with(|state| {
        let mut pool = state.shared_texts.borrow_mut();
        if let Some(shared) = pool.get(&key)
            && &**shared == text
        {
            return Rc::clone(shared);
        }
        let shared: Rc<str> = Rc::from(text);
        if pool.len() >= POOL_CAPACITY {
            pool.clear();
        }
        pool.insert(key, Rc::clone(&shared));
        shared
    })
}

impl DrawPrimitive {
    /// The primitive moved by `dx`, `dy`. Brush geometry is relative to the
    /// primitive's rect, so it moves along.
    pub fn translate(self, dx: f32, dy: f32) -> Self {
        match self {
            DrawPrimitive::Content => DrawPrimitive::Content,
            DrawPrimitive::Blend {
                primitive,
                blend_mode,
            } => DrawPrimitive::Blend {
                primitive: Box::new(primitive.translate(dx, dy)),
                blend_mode,
            },
            DrawPrimitive::Rect {
                rect,
                brush,
                stroke,
            } => DrawPrimitive::Rect {
                rect: rect.translate(dx, dy),
                brush,
                stroke,
            },
            DrawPrimitive::RoundRect {
                rect,
                brush,
                radii,
                stroke,
            } => DrawPrimitive::RoundRect {
                rect: rect.translate(dx, dy),
                brush,
                radii,
                stroke,
            },
            DrawPrimitive::Arc {
                rect,
                brush,
                center,
                radius,
                start_angle,
                sweep_angle,
                stroke,
                inner_radius,
            } => DrawPrimitive::Arc {
                rect: rect.translate(dx, dy),
                brush,
                center: Point::new(center.x + dx, center.y + dy),
                radius,
                start_angle,
                sweep_angle,
                stroke,
                inner_radius,
            },
            DrawPrimitive::Line {
                rect,
                brush,
                start,
                end,
                stroke,
            } => DrawPrimitive::Line {
                rect: rect.translate(dx, dy),
                brush,
                start: Point::new(start.x + dx, start.y + dy),
                end: Point::new(end.x + dx, end.y + dy),
                stroke,
            },
            DrawPrimitive::Trapezoid {
                rect,
                brush,
                trapezoid,
            } => DrawPrimitive::Trapezoid {
                rect: rect.translate(dx, dy),
                brush,
                trapezoid: trapezoid.translate(dx, dy),
            },
            DrawPrimitive::Image {
                rect,
                image,
                alpha,
                color_filter,
                sampling,
                src_rect,
            } => DrawPrimitive::Image {
                rect: rect.translate(dx, dy),
                image,
                alpha,
                color_filter,
                sampling,
                src_rect,
            },
            DrawPrimitive::Text(mut text) => {
                text.rect = text.rect.translate(dx, dy);
                DrawPrimitive::Text(text)
            }
            DrawPrimitive::Shadow(ShadowPrimitive::Drop {
                shape,
                cutout,
                blur_radius,
                blend_mode,
            }) => DrawPrimitive::Shadow(ShadowPrimitive::Drop {
                shape: Box::new(shape.translate(dx, dy)),
                cutout: cutout.map(|cutout| Box::new(cutout.translate(dx, dy))),
                blur_radius,
                blend_mode,
            }),
            DrawPrimitive::Shadow(ShadowPrimitive::Inner {
                fill,
                cutout,
                blur_radius,
                blend_mode,
                clip_rect,
            }) => DrawPrimitive::Shadow(ShadowPrimitive::Inner {
                fill: Box::new(fill.translate(dx, dy)),
                cutout: Box::new(cutout.translate(dx, dy)),
                blur_radius,
                blend_mode,
                clip_rect: clip_rect.translate(dx, dy),
            }),
        }
    }
}

/// A shadow that needs blur processing. Each renderer chooses how to blur. See
/// [`DrawPrimitive::Shadow`].
#[derive(Clone, Debug, PartialEq)]
pub enum ShadowPrimitive {
    /// Drop shadow: render shape behind content, blurred. `cutout` knocks
    /// the element's own (unoffset) shape out of the silhouette before the
    /// blur so translucent surfaces never sample their own shadow.
    Drop {
        /// The shape drawn and blurred behind the content.
        shape: Box<DrawPrimitive>,
        /// `Some` cuts the element's own unoffset shape out of the silhouette before the blur.
        cutout: Option<Box<DrawPrimitive>>,
        /// Blur radius of the shadow, in logical pixels.
        blur_radius: f32,
        /// How the shadow combines with what is already drawn.
        blend_mode: BlendMode,
    },
    /// Inner shadow: render fill + cutout to offscreen, blur, clip to bounds.
    Inner {
        /// The shape drawn and blurred to make the shadow.
        fill: Box<DrawPrimitive>,
        /// The shape cut out of the shadow's silhouette, so it appears only outside that shape.
        cutout: Box<DrawPrimitive>,
        /// Blur radius of the shadow, in logical pixels.
        blur_radius: f32,
        /// How the shadow combines with what is already drawn.
        blend_mode: BlendMode,
        /// Element bounds — blurred result must be clipped here.
        clip_rect: Rect,
    },
}

/// The drawing surface passed to draw modifiers. Compose's `DrawScope`. Every method records a
/// primitive in scope coordinates, with the origin at the top-left corner of the node, and the
/// `_blend` forms composite with a given blend mode instead of `SrcOver`.
pub trait DrawScope {
    /// Size of the drawing area, in logical pixels.
    fn size(&self) -> Size;
    /// Marks where the node's own content draws, as Compose's `drawContent()` does in
    /// `drawWithContent`. Draws recorded before the marker paint under the content and draws after
    /// it paint over it.
    fn draw_content(&mut self);
    /// Fills the whole scope rect with `brush`.
    fn draw_rect(&mut self, brush: Brush);
    /// As `draw_rect`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_rect_blend(&mut self, brush: Brush, blend_mode: BlendMode);
    /// Draws a rectangle at the specified position and size.
    fn draw_rect_at(&mut self, rect: Rect, brush: Brush);
    /// As `draw_rect_at`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_rect_at_blend(&mut self, rect: Rect, brush: Brush, blend_mode: BlendMode);
    /// Fills the whole scope rect with rounded corners of `radii`.
    fn draw_round_rect(&mut self, brush: Brush, radii: CornerRadii);
    /// As `draw_round_rect`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_round_rect_blend(&mut self, brush: Brush, radii: CornerRadii, blend_mode: BlendMode);
    /// Draws a rounded rectangle at the specified position and size.
    fn draw_round_rect_at(&mut self, rect: Rect, brush: Brush, radii: CornerRadii);
    /// Fills a circle of `radius` around `center`, in scope coordinates.
    fn draw_circle(&mut self, brush: Brush, center: Point, radius: f32);
    /// As `draw_circle`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_circle_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        blend_mode: BlendMode,
    );

    /// Strokes the outline of the whole scope rect.
    fn draw_rect_stroked(&mut self, brush: Brush, stroke: Stroke);
    /// As `draw_rect_stroked`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_rect_stroked_blend(&mut self, brush: Brush, stroke: Stroke, blend_mode: BlendMode);
    /// Strokes the outline of `rect`.
    fn draw_rect_at_stroked(&mut self, rect: Rect, brush: Brush, stroke: Stroke);
    /// As `draw_rect_at_stroked`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_rect_at_stroked_blend(
        &mut self,
        rect: Rect,
        brush: Brush,
        stroke: Stroke,
        blend_mode: BlendMode,
    );
    /// Strokes the outline of the whole scope rect with rounded corners.
    fn draw_round_rect_stroked(&mut self, brush: Brush, radii: CornerRadii, stroke: Stroke);
    /// As `draw_round_rect_stroked`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_round_rect_stroked_blend(
        &mut self,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
        blend_mode: BlendMode,
    );
    /// Strokes the outline of `rect` with rounded corners.
    fn draw_round_rect_at_stroked(
        &mut self,
        rect: Rect,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
    );
    /// As `draw_round_rect_at_stroked`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_round_rect_at_stroked_blend(
        &mut self,
        rect: Rect,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
        blend_mode: BlendMode,
    );
    /// Strokes a circle outline. Lowers to a stroked rounded rect, so it shares
    /// the fill pipeline and batches with every other shape.
    fn draw_circle_stroked(&mut self, brush: Brush, center: Point, radius: f32, stroke: Stroke);
    /// As `draw_circle_stroked`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_circle_stroked_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        stroke: Stroke,
        blend_mode: BlendMode,
    );

    /// Strokes a circular arc.
    ///
    /// Angles are in **radians**, `0` points along **+X**, and increasing
    /// angles sweep **clockwise on screen** (Cranpose uses y-down device
    /// coordinates, so this matches `atan2(dy, dx)` and the sweep-gradient
    /// brush). A negative `sweep_angle` sweeps counter-clockwise; `|sweep| >=
    /// 2Ï€` draws a closed ring.
    ///
    /// The stroke is centered on `radius`, so the band covers
    /// `radius ± width/2`. [`StrokeCap`](crate::StrokeCap) shapes the two ends.
    /// Nothing is drawn for a zero sweep, a non-positive width, or non-finite
    /// input.
    fn draw_arc(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        stroke: Stroke,
    );
    /// As `draw_arc`, composited with `blend_mode` instead of `SrcOver`.
    #[expect(clippy::too_many_arguments)]
    fn draw_arc_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        stroke: Stroke,
        blend_mode: BlendMode,
    );

    /// Strokes the straight segment from `start` to `end`, centred on it and
    /// `stroke.width` wide, its ends shaped by `stroke.cap`: Compose's
    /// `drawLine(brush, start, end, strokeWidth, cap)`. Nothing is drawn
    /// for a non-positive width, a non-finite end, or a segment of no length
    /// between butt caps; round and square caps draw a dot there.
    fn draw_line(&mut self, brush: Brush, start: Point, end: Point, stroke: Stroke);
    /// As `draw_line`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_line_blend(
        &mut self,
        brush: Brush,
        start: Point,
        end: Point,
        stroke: Stroke,
        blend_mode: BlendMode,
    );

    /// Fills or strokes `path` with `brush`: Compose's
    /// `drawPath(path, brush, style)`. A fill closes every contour and
    /// rasterizes it as [`draw_vector_path`](Self::draw_vector_path) does. A
    /// stroke draws each flattened edge as a line on the GPU, capped at an
    /// open contour's ends and joined at its corners as
    /// [`crate::for_each_stroke_line`] describes; a dashed stroke draws the
    /// dashes its effect cuts. Where edges meet, a translucent stroke is
    /// painted twice.
    fn draw_path(&mut self, path: &Path, brush: Brush, style: DrawStyle);
    /// As `draw_path`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_path_blend(
        &mut self,
        path: &Path,
        brush: Brush,
        style: DrawStyle,
        blend_mode: BlendMode,
    );

    /// Fills an annular sector — the region between `inner_radius` and
    /// `outer_radius`, limited to an angular sweep, with **flat radial ends**.
    ///
    /// This is the shape a stroked arc cannot express: its ends are straight
    /// lines through the center, not caps. `inner_radius = 0` fills a pie
    /// wedge. Angle convention is identical to [`draw_arc`](Self::draw_arc).
    /// Nothing is drawn when `inner_radius >= outer_radius`, the sweep is zero,
    /// or any input is non-finite.
    fn draw_annular_sector(
        &mut self,
        brush: Brush,
        center: Point,
        inner_radius: f32,
        outer_radius: f32,
        start_angle: f32,
        sweep_angle: f32,
    );
    /// As `draw_annular_sector`, composited with `blend_mode` instead of `SrcOver`.
    #[expect(clippy::too_many_arguments)]
    fn draw_annular_sector_blend(
        &mut self,
        brush: Brush,
        center: Point,
        inner_radius: f32,
        outer_radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        blend_mode: BlendMode,
    );

    /// Draws `image` stretched over the whole scope rect.
    fn draw_image(&mut self, image: ImageBitmap);
    /// As `draw_image`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_image_blend(&mut self, image: ImageBitmap, blend_mode: BlendMode);
    /// Draws `image` stretched into `rect`, with `alpha` from 0.0 to 1.0 and an optional
    /// `color_filter`.
    fn draw_image_at(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
    );
    /// As `draw_image_at`, sampling the image with `sampling` instead of nearest-neighbor.
    fn draw_image_at_sampled(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        sampling: ImageSampling,
    );
    /// As `draw_image_at`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_image_at_blend(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        blend_mode: BlendMode,
    );
    /// Draws a sub-region of an image. `src_rect` is in image-pixel
    /// coordinates; `dst_rect` is in scope coordinates.
    fn draw_image_src(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
    );
    /// As `draw_image_src`, sampling the source region with `sampling` instead of nearest-neighbor.
    fn draw_image_src_sampled(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        sampling: ImageSampling,
    );
    /// As `draw_image_src_sampled`, composited with `blend_mode` instead of `SrcOver`.
    fn draw_image_src_blend(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        blend_mode: BlendMode,
    );
    /// Fills a parsed SVG path in scope coordinates (path units are dp).
    ///
    /// The fill is rasterized on the CPU into a supersampled, anti-aliased
    /// bitmap covering the path bounds and drawn as an image primitive, so
    /// it works on every render backend. Parse the path once with
    /// [`crate::VectorPath::parse`] and redraw it per frame. Solid brushes
    /// are honored exactly; gradient brushes currently fall back to their
    /// first stop color.
    fn draw_vector_path(&mut self, path: &crate::VectorPath, brush: Brush);
    /// Parses SVG path data (the `d` attribute syntax: `M/m L/l H/h V/v
    /// C/c S/s Q/q T/t A/a Z/z`) and fills it. Invalid path data draws
    /// nothing. Prefer [`crate::VectorPath::parse`] +
    /// [`draw_vector_path`](Self::draw_vector_path) to avoid re-parsing
    /// and to surface parse errors.
    fn draw_svg_path(&mut self, d: &str, brush: Brush) {
        if let Ok(path) = crate::VectorPath::parse(d) {
            self.draw_vector_path(&path, brush);
        }
    }

    /// The block size, line height and first baseline `text` would occupy in
    /// `style`.
    ///
    /// Free to call repeatedly: the underlying text stack caches metrics on
    /// `(text, style)`, so a game can measure every label every frame to center
    /// it without touching a font file more than once.
    fn measure_text(&self, text: &str, style: &DrawTextStyle) -> TextMeasurement;

    /// Draws `text` inside the whole scope rect, positioned by
    /// [`DrawTextStyle::align`] and [`DrawTextStyle::vertical_align`].
    fn draw_text(&mut self, brush: Brush, text: &str, style: &DrawTextStyle) {
        self.draw_text_at(Rect::from_size(self.size()), brush, text, style);
    }

    /// Draws `text` inside `rect`, positioned by [`DrawTextStyle::align`] and
    /// [`DrawTextStyle::vertical_align`].
    ///
    /// The glyphs are *not* clipped to `rect` — it is an alignment box, not a
    /// viewport. A `rect` narrower than the measured text overflows in the
    /// direction the alignment implies; clip the layer if that matters.
    fn draw_text_at(&mut self, rect: Rect, brush: Brush, text: &str, style: &DrawTextStyle);

    /// Draws `text` with the top-left corner of its block at `top_left`.
    ///
    /// Alignment is a no-op here because the box is the measurement — this is
    /// the "I already know where it goes" form, and the one to pair with
    /// [`measure_text`](Self::measure_text) for hand-rolled centering.
    fn draw_text_from(&mut self, top_left: Point, brush: Brush, text: &str, style: &DrawTextStyle) {
        if text.is_empty() {
            return;
        }
        let measurement = self.measure_text(text, style);
        self.draw_text_at(
            Rect::from_origin_size(top_left, measurement.size),
            brush,
            text,
            &DrawTextStyle {
                align: TextAlign::Left,
                vertical_align: TextVerticalAlign::Top,
                ..style.clone()
            },
        );
    }

    /// Consumes the scope and returns the recorded primitives in draw order, including the
    /// `Content` markers.
    fn into_primitives(self) -> Vec<DrawPrimitive>;
}

/// Resolves the top-left corner a text block of `measurement` gets when it is
/// aligned inside `rect`.
///
/// Split out so the placement rule is stated once and can be unit-tested
/// against the measurement it is derived from.
pub fn align_text_block(rect: Rect, measurement: TextMeasurement, style: &DrawTextStyle) -> Point {
    let x = match style.align {
        TextAlign::Left => rect.x,
        TextAlign::Center => rect.x + (rect.width - measurement.size.width) * 0.5,
        TextAlign::Right => rect.x + rect.width - measurement.size.width,
    };
    let y = match style.vertical_align {
        TextVerticalAlign::Top => rect.y,
        TextVerticalAlign::Center => rect.y + (rect.height - measurement.size.height) * 0.5,
        TextVerticalAlign::Bottom => rect.y + rect.height - measurement.size.height,
        TextVerticalAlign::Baseline => rect.y - measurement.first_baseline,
    };
    Point::new(x, y)
}

/// The `DrawScope` the framework passes to draw closures. It records the primitives drawn in draw
/// order.
#[derive(Default)]
pub struct DrawScopeDefault {
    size: Size,
    recording: CommandRecorder,
    text_measurer: Option<Rc<dyn DrawTextMeasurer>>,
}

impl DrawScopeDefault {
    /// Creates a scope of `size` without a text measurer, so text is measured by an estimate.
    pub fn new(size: Size) -> Self {
        Self::with_storage(size, None, CommandRecording::default())
    }

    /// A scope that measures text with the app's fonts.
    ///
    /// The framework calls this for every draw closure it runs; `new` exists
    /// for callers that never draw text.
    pub fn with_text_measurer(size: Size, text_measurer: Rc<dyn DrawTextMeasurer>) -> Self {
        Self::with_storage(size, Some(text_measurer), CommandRecording::default())
    }

    /// A scope recording into `storage`, a recording the caller kept from an
    /// earlier frame so its buffers keep the capacity they earned.
    pub fn with_text_measurer_reusing(
        size: Size,
        text_measurer: Rc<dyn DrawTextMeasurer>,
        storage: CommandRecording,
    ) -> Self {
        Self::with_storage(size, Some(text_measurer), storage)
    }

    fn with_storage(
        size: Size,
        text_measurer: Option<Rc<dyn DrawTextMeasurer>>,
        recording: CommandRecording,
    ) -> Self {
        let recording = CommandRecorder::reusing(recording);
        Self {
            size,
            recording,
            text_measurer,
        }
    }

    /// How many `draw_content` markers this scope has recorded.
    pub fn content_marker_count(&self) -> u32 {
        self.recording.content_markers()
    }

    /// Runs `draw` in this scope's rect shrunk by `insets`, where a draw
    /// modifier placed after layout padding draws: `draw` sees the inner
    /// size, and what it records lands offset by the leading insets.
    pub fn inset(&mut self, insets: EdgeInsets, draw: impl FnOnce(&mut DrawScopeDefault)) {
        let inner = insets.inset_rect(self.size);
        let mut scope = Self::with_storage(
            Size {
                width: inner.width,
                height: inner.height,
            },
            self.text_measurer.clone(),
            CommandRecording::default(),
        );
        draw(&mut scope);
        let recording = scope.finish();
        self.push_recorded(
            recording
                .primitives_with_markers()
                .map(|primitive| primitive.translate(inner.x, inner.y)),
        );
    }

    /// Records primitives already built, as if each had been drawn here.
    pub fn push_recorded(&mut self, primitives: impl IntoIterator<Item = DrawPrimitive>) {
        for primitive in primitives {
            self.recording.push_primitive(primitive);
        }
    }

    /// The recording, in the storage it was recorded into, so the caller
    /// can lend it to the same command's next recording.
    pub fn finish(self) -> CommandRecording {
        self.recording.finish()
    }

    fn push_blended_primitive(&mut self, primitive: DrawPrimitive, blend_mode: BlendMode) {
        if blend_mode != BlendMode::SrcOver {
            self.recording.push_other(DrawPrimitive::Blend {
                primitive: Box::new(primitive),
                blend_mode,
            });
            return;
        }
        self.recording.push_other(primitive);
    }

    #[expect(clippy::too_many_arguments)]
    #[inline]
    fn push_arc(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        stroke: Option<Stroke>,
        inner_radius: f32,
        blend_mode: BlendMode,
    ) {
        let args = ArcRecordArgs {
            brush: &brush,
            center,
            radius,
            start_angle,
            sweep_angle,
            stroke,
            inner_radius,
            blend_mode,
        };
        let geometry = normalized_band(&args);
        if geometry.is_degenerate() {
            return;
        }
        self.recording.push_scope_arc(&args, &geometry);
    }

    /// Records the fill of `path` as the slices the GPU draws, its brush
    /// resolved against the scope's rect; a path that cannot be sliced is
    /// rasterized into a mask instead.
    fn push_path_fill(&mut self, path: &Path, brush: &Brush, blend_mode: BlendMode) {
        let brush_rect = Rect::from_size(self.size);
        let recording = &mut self.recording;
        let sliced = crate::thread_state::with(|state| {
            let mut slicer = state.path_slicer.borrow_mut();
            let contours = path
                .contours()
                .iter()
                .map(|contour| contour.points.as_slice());
            slicer
                .slice(contours, PathFillRule::NonZero)
                .map(|slices| recording.push_trapezoids(brush_rect, slices, brush, blend_mode))
                .is_some()
        });
        if !sliced {
            self.push_vector_path(
                &path.to_vector_path(PathFillRule::NonZero),
                brush,
                blend_mode,
            );
        }
    }

    /// Rasterizes the fill of `path` into a cached coverage image and
    /// records it, blended by `blend_mode`.
    fn push_vector_path(&mut self, path: &crate::VectorPath, brush: &Brush, blend_mode: BlendMode) {
        const SUPERSAMPLE: f32 = 2.0;
        const MAX_MASK_PIXELS: f32 = 4096.0;

        if path.is_empty() {
            return;
        }
        let bounds = path.bounds();
        if bounds.width <= 0.0 || bounds.height <= 0.0 {
            return;
        }

        let color = match brush {
            Brush::Solid(color) => *color,
            Brush::LinearGradient { colors, .. }
            | Brush::RadialGradient { colors, .. }
            | Brush::SweepGradient { colors, .. } => match colors.first() {
                Some(color) => *color,
                None => return,
            },
        };
        if color.3 <= 0.0 {
            return;
        }

        let origin = Point::new(bounds.x.floor() - 1.0, bounds.y.floor() - 1.0);
        let rect_width = (bounds.x + bounds.width).ceil() - origin.x + 1.0;
        let rect_height = (bounds.y + bounds.height).ceil() - origin.y + 1.0;
        let mask_width = (rect_width * SUPERSAMPLE)
            .ceil()
            .clamp(1.0, MAX_MASK_PIXELS) as usize;
        let mask_height = (rect_height * SUPERSAMPLE)
            .ceil()
            .clamp(1.0, MAX_MASK_PIXELS) as usize;

        let red = (color.0.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
        let green = (color.1.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
        let blue = (color.2.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
        let alpha = color.3.clamp(0.0, 1.0);
        let key = vector_path_mask_key(
            path,
            origin,
            (mask_width, mask_height),
            [red, green, blue],
            alpha,
        );
        let cached = vector_path_mask_cache_get(key);
        let image = match cached {
            Some(image) => image,
            None => {
                let mask = path.coverage_mask(mask_width, mask_height, origin, SUPERSAMPLE, alpha);
                let Ok(image) = ImageBitmap::from_alpha8(
                    mask_width as u32,
                    mask_height as u32,
                    [red, green, blue],
                    mask,
                ) else {
                    return;
                };
                vector_path_mask_cache_put(key, image.clone());
                image
            }
        };

        let image = DrawPrimitive::Image {
            rect: Rect {
                x: origin.x,
                y: origin.y,
                width: rect_width,
                height: rect_height,
            },
            image,
            alpha: 1.0,
            color_filter: None,
            sampling: ImageSampling::Linear,
            src_rect: None,
        };
        self.recording
            .push_other(if blend_mode == BlendMode::SrcOver {
                image
            } else {
                DrawPrimitive::Blend {
                    primitive: Box::new(image),
                    blend_mode,
                }
            });
    }
}

impl DrawScope for DrawScopeDefault {
    fn size(&self) -> Size {
        self.size
    }

    fn draw_content(&mut self) {
        self.recording.push_content();
    }

    fn draw_rect(&mut self, brush: Brush) {
        self.draw_rect_blend(brush, BlendMode::SrcOver);
    }

    fn draw_rect_blend(&mut self, brush: Brush, blend_mode: BlendMode) {
        self.recording
            .push_rect(Rect::from_size(self.size), &brush, None, blend_mode);
    }

    fn draw_rect_at(&mut self, rect: Rect, brush: Brush) {
        self.draw_rect_at_blend(rect, brush, BlendMode::SrcOver);
    }

    fn draw_rect_at_blend(&mut self, rect: Rect, brush: Brush, blend_mode: BlendMode) {
        self.recording.push_rect(rect, &brush, None, blend_mode);
    }

    fn draw_round_rect(&mut self, brush: Brush, radii: CornerRadii) {
        self.draw_round_rect_blend(brush, radii, BlendMode::SrcOver);
    }

    fn draw_round_rect_blend(&mut self, brush: Brush, radii: CornerRadii, blend_mode: BlendMode) {
        self.recording
            .push_round_rect(Rect::from_size(self.size), &brush, radii, None, blend_mode);
    }

    fn draw_round_rect_at(&mut self, rect: Rect, brush: Brush, radii: CornerRadii) {
        self.recording
            .push_round_rect(rect, &brush, radii, None, BlendMode::SrcOver);
    }

    fn draw_rect_stroked(&mut self, brush: Brush, stroke: Stroke) {
        self.draw_rect_stroked_blend(brush, stroke, BlendMode::SrcOver);
    }

    fn draw_rect_stroked_blend(&mut self, brush: Brush, stroke: Stroke, blend_mode: BlendMode) {
        self.draw_rect_at_stroked_blend(Rect::from_size(self.size), brush, stroke, blend_mode);
    }

    fn draw_rect_at_stroked(&mut self, rect: Rect, brush: Brush, stroke: Stroke) {
        self.draw_rect_at_stroked_blend(rect, brush, stroke, BlendMode::SrcOver);
    }

    fn draw_rect_at_stroked_blend(
        &mut self,
        rect: Rect,
        brush: Brush,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        if !stroke.is_visible() {
            return;
        }
        self.recording
            .push_rect(rect, &brush, Some(stroke), blend_mode);
    }

    fn draw_round_rect_stroked(&mut self, brush: Brush, radii: CornerRadii, stroke: Stroke) {
        self.draw_round_rect_stroked_blend(brush, radii, stroke, BlendMode::SrcOver);
    }

    fn draw_round_rect_stroked_blend(
        &mut self,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        self.draw_round_rect_at_stroked_blend(
            Rect::from_size(self.size),
            brush,
            radii,
            stroke,
            blend_mode,
        );
    }

    fn draw_round_rect_at_stroked(
        &mut self,
        rect: Rect,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
    ) {
        self.draw_round_rect_at_stroked_blend(rect, brush, radii, stroke, BlendMode::SrcOver);
    }

    fn draw_round_rect_at_stroked_blend(
        &mut self,
        rect: Rect,
        brush: Brush,
        radii: CornerRadii,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        if !stroke.is_visible() {
            return;
        }
        self.recording
            .push_round_rect(rect, &brush, radii, Some(stroke), blend_mode);
    }

    fn draw_circle_stroked(&mut self, brush: Brush, center: Point, radius: f32, stroke: Stroke) {
        self.draw_circle_stroked_blend(brush, center, radius, stroke, BlendMode::SrcOver);
    }

    fn draw_circle_stroked_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        if !stroke.is_visible() || !radius.is_finite() {
            return;
        }
        let radius = radius.max(0.0);
        let diameter = radius * 2.0;
        self.draw_round_rect_at_stroked_blend(
            Rect {
                x: center.x - radius,
                y: center.y - radius,
                width: diameter,
                height: diameter,
            },
            brush,
            CornerRadii::uniform(radius),
            stroke,
            blend_mode,
        );
    }

    fn draw_arc(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        stroke: Stroke,
    ) {
        self.draw_arc_blend(
            brush,
            center,
            radius,
            start_angle,
            sweep_angle,
            stroke,
            BlendMode::SrcOver,
        );
    }

    fn draw_arc_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        if !stroke.is_visible() {
            return;
        }
        self.push_arc(
            brush,
            center,
            radius,
            start_angle,
            sweep_angle,
            Some(stroke),
            0.0,
            blend_mode,
        );
    }

    fn draw_line(&mut self, brush: Brush, start: Point, end: Point, stroke: Stroke) {
        self.draw_line_blend(brush, start, end, stroke, BlendMode::SrcOver);
    }

    fn draw_line_blend(
        &mut self,
        brush: Brush,
        start: Point,
        end: Point,
        stroke: Stroke,
        blend_mode: BlendMode,
    ) {
        let line = LineGeometry::new(start, end, stroke);
        if line.is_degenerate() {
            return;
        }
        self.recording.push_line(&line, &brush, stroke, blend_mode);
    }

    fn draw_path(&mut self, path: &Path, brush: Brush, style: DrawStyle) {
        self.draw_path_blend(path, brush, style, BlendMode::SrcOver);
    }

    fn draw_path_blend(
        &mut self,
        path: &Path,
        brush: Brush,
        style: DrawStyle,
        blend_mode: BlendMode,
    ) {
        let (stroke, dash) = match style {
            DrawStyle::Fill => {
                self.push_path_fill(path, &brush, blend_mode);
                return;
            }
            DrawStyle::Stroke(stroke) => (stroke, None),
            DrawStyle::DashedStroke(stroke, dash) => (stroke, Some(dash)),
        };
        if !stroke.is_visible() {
            return;
        }
        let recording = &mut self.recording;
        let mut push = |line: LineGeometry| {
            if !line.is_degenerate() {
                let stroke = Stroke {
                    cap: line.cap,
                    ..stroke
                };
                recording.push_line(&line, &brush, stroke, blend_mode);
            }
        };
        for contour in path.contours() {
            let Some(dash) = dash else {
                crate::for_each_stroke_line(&contour.points, contour.closed, stroke, &mut push);
                continue;
            };
            let closing = contour
                .closed
                .then(|| contour.points.first().copied())
                .flatten();
            let points: std::borrow::Cow<'_, [Point]> = match closing {
                Some(first) => {
                    std::borrow::Cow::Owned(contour.points.iter().copied().chain([first]).collect())
                }
                None => std::borrow::Cow::Borrowed(&contour.points),
            };
            dash.for_each_dash(&points, |piece| {
                crate::for_each_stroke_line(piece, false, stroke, &mut push);
            });
        }
    }

    fn draw_annular_sector(
        &mut self,
        brush: Brush,
        center: Point,
        inner_radius: f32,
        outer_radius: f32,
        start_angle: f32,
        sweep_angle: f32,
    ) {
        self.draw_annular_sector_blend(
            brush,
            center,
            inner_radius,
            outer_radius,
            start_angle,
            sweep_angle,
            BlendMode::SrcOver,
        );
    }

    fn draw_annular_sector_blend(
        &mut self,
        brush: Brush,
        center: Point,
        inner_radius: f32,
        outer_radius: f32,
        start_angle: f32,
        sweep_angle: f32,
        blend_mode: BlendMode,
    ) {
        self.push_arc(
            brush,
            center,
            outer_radius,
            start_angle,
            sweep_angle,
            None,
            inner_radius,
            blend_mode,
        );
    }

    fn draw_circle(&mut self, brush: Brush, center: Point, radius: f32) {
        self.draw_circle_blend(brush, center, radius, BlendMode::SrcOver);
    }

    fn draw_circle_blend(
        &mut self,
        brush: Brush,
        center: Point,
        radius: f32,
        blend_mode: BlendMode,
    ) {
        let radius = radius.max(0.0);
        let diameter = radius * 2.0;
        self.recording.push_round_rect(
            Rect {
                x: center.x - radius,
                y: center.y - radius,
                width: diameter,
                height: diameter,
            },
            &brush,
            CornerRadii::uniform(radius),
            None,
            blend_mode,
        );
    }

    fn draw_image(&mut self, image: ImageBitmap) {
        self.draw_image_blend(image, BlendMode::SrcOver);
    }

    fn draw_image_blend(&mut self, image: ImageBitmap, blend_mode: BlendMode) {
        self.push_blended_primitive(
            DrawPrimitive::Image {
                rect: Rect::from_size(self.size),
                image,
                alpha: 1.0,
                color_filter: None,
                sampling: ImageSampling::Nearest,
                src_rect: None,
            },
            blend_mode,
        );
    }

    fn draw_image_at(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
    ) {
        self.draw_image_at_sampled(rect, image, alpha, color_filter, ImageSampling::Nearest);
    }

    fn draw_image_at_sampled(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        sampling: ImageSampling,
    ) {
        self.push_blended_primitive(
            DrawPrimitive::Image {
                rect,
                image,
                alpha: alpha.clamp(0.0, 1.0),
                color_filter,
                sampling,
                src_rect: None,
            },
            BlendMode::SrcOver,
        );
    }

    fn draw_image_at_blend(
        &mut self,
        rect: Rect,
        image: ImageBitmap,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        blend_mode: BlendMode,
    ) {
        self.push_blended_primitive(
            DrawPrimitive::Image {
                rect,
                image,
                alpha: alpha.clamp(0.0, 1.0),
                color_filter,
                sampling: ImageSampling::Nearest,
                src_rect: None,
            },
            blend_mode,
        );
    }

    fn draw_image_src(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
    ) {
        self.draw_image_src_blend(
            image,
            src_rect,
            dst_rect,
            alpha,
            color_filter,
            BlendMode::SrcOver,
        );
    }

    fn draw_image_src_sampled(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        sampling: ImageSampling,
    ) {
        self.push_blended_primitive(
            DrawPrimitive::Image {
                rect: dst_rect,
                image,
                alpha: alpha.clamp(0.0, 1.0),
                color_filter,
                sampling,
                src_rect: Some(src_rect),
            },
            BlendMode::SrcOver,
        );
    }

    fn draw_image_src_blend(
        &mut self,
        image: ImageBitmap,
        src_rect: Rect,
        dst_rect: Rect,
        alpha: f32,
        color_filter: Option<ColorFilter>,
        blend_mode: BlendMode,
    ) {
        self.push_blended_primitive(
            DrawPrimitive::Image {
                rect: dst_rect,
                image,
                alpha: alpha.clamp(0.0, 1.0),
                color_filter,
                sampling: ImageSampling::Nearest,
                src_rect: Some(src_rect),
            },
            blend_mode,
        );
    }

    fn draw_vector_path(&mut self, path: &crate::VectorPath, brush: Brush) {
        self.push_vector_path(path, &brush, BlendMode::SrcOver);
    }

    fn measure_text(&self, text: &str, style: &DrawTextStyle) -> TextMeasurement {
        match &self.text_measurer {
            Some(measurer) => measurer.measure_text(text, style),
            None => estimate_text_measurement(text, style),
        }
    }

    fn draw_text_at(&mut self, rect: Rect, brush: Brush, text: &str, style: &DrawTextStyle) {
        if text.is_empty() {
            return;
        }
        let Some(color) = solid_fill_color(&brush) else {
            return;
        };
        if color.3 <= 0.0 {
            return;
        }
        let measurement = self.measure_text(text, style);
        if !(measurement.size.width > 0.0 && measurement.size.height > 0.0) {
            return;
        }
        let origin = align_text_block(rect, measurement, style);
        if !origin.x.is_finite() || !origin.y.is_finite() {
            return;
        }
        self.recording
            .push_other(DrawPrimitive::Text(Box::new(TextPrimitive {
                rect: Rect::from_origin_size(origin, measurement.size),
                text: shared_text_str(text),
                style: style.clone(),
                color,
            })));
    }

    fn into_primitives(self) -> Vec<DrawPrimitive> {
        self.finish().into_primitives_with_markers()
    }
}

/// The single color a brush paints with, or its first stop for a gradient.
///
/// Text is filled per glyph from one vertex color, so a gradient cannot be
/// honored; this mirrors the fallback [`DrawScope::draw_vector_path`] documents.
fn solid_fill_color(brush: &Brush) -> Option<Color> {
    match brush {
        Brush::Solid(color) => Some(*color),
        Brush::LinearGradient { colors, .. }
        | Brush::RadialGradient { colors, .. }
        | Brush::SweepGradient { colors, .. } => colors.first().copied(),
    }
}

#[cfg(test)]
#[path = "tests/geometry_tests.rs"]
mod tests;