frus-core 0.4.0

frus — shared foundation types (geometry, colour)
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
//! The **box decoration** model: the vocabulary for painting a rectangle
//! (background, gradient, border, rounded corners, shadow), independent of any
//! widget or theme.
//!
//! A [`BoxDecoration`] is a pure `Copy` value that a widget assembles at paint
//! time, then **lowers** into [`Scene`] primitives through
//! [`BoxDecoration::paint_into`], in a **fixed order**: shadow → background
//! (colour or gradient) → picture → border. It feeds layout too:
//! [`BoxDecoration::content_padding`] reserves room for the border on taffy's
//! behalf.

use crate::{
    BlurStyle, BorderSide, ClipShape, Color, DecorationImage, Insets, Path, Point, Primitive, Rect,
    Scene, ShapeBorder, TextDirection,
};

/// Corner radii, **per corner** (logical px). `From<f32>` covers the uniform case:
/// anywhere a radius is expected, a plain `10.0` still works.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BorderRadius {
    /// The top-left corner's radius, in logical pixels.
    pub top_left: f32,
    /// The top-right corner's radius, in logical pixels.
    pub top_right: f32,
    /// The bottom-right corner's radius, in logical pixels.
    pub bottom_right: f32,
    /// The bottom-left corner's radius, in logical pixels.
    pub bottom_left: f32,
}

/// **A corner radius named by the reading direction rather than by the wall**
/// (`border_radius.dart:621`).
///
/// A [`BorderRadius`] says *top left*. This says *top start* — the corner where the text
/// begins, which is the left one in English and the right one in Arabic. [`resolve`] turns
/// one into the other once the direction is known.
///
/// The distinction is not decorative. A drawer rounds its **inner** edge, the one facing
/// the page: for a leading drawer that is the *end* side in either direction, and a radius
/// written as *right* is correct in English and wrong in Arabic. Every asymmetric radius
/// in an interface that mirrors has this question, and answering it by hand at each site
/// is how one of them ends up answered differently.
///
/// The reference has one type hierarchy for this (`BorderRadiusGeometry`, with a resolved
/// and an unresolved subclass); this is two plain types and a `resolve`, because a widget
/// here is handed a `&Theme` and so always has a direction available when it needs one.
///
/// [`resolve`]: Self::resolve
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BorderRadiusDirectional {
    /// The corner at the top of the line's **beginning**.
    pub top_start: f32,
    /// The corner at the top of the line's **end**.
    pub top_end: f32,
    /// The corner at the bottom of the line's **end**.
    pub bottom_end: f32,
    /// The corner at the bottom of the line's **beginning**.
    pub bottom_start: f32,
}

impl BorderRadiusDirectional {
    /// No rounding at all.
    pub const ZERO: Self = Self::uniform(0.0);

    /// The same radius on all four corners — which needs no direction, and is here so a
    /// caller can write one without changing type halfway through an expression.
    pub const fn uniform(radius: f32) -> Self {
        Self {
            top_start: radius,
            top_end: radius,
            bottom_end: radius,
            bottom_start: radius,
        }
    }

    /// The two corners at the line's **beginning** — the left pair in English, the right
    /// pair in Arabic.
    pub const fn start(radius: f32) -> Self {
        Self {
            top_start: radius,
            top_end: 0.0,
            bottom_end: 0.0,
            bottom_start: radius,
        }
    }

    /// The two corners at the line's **end**.
    pub const fn end(radius: f32) -> Self {
        Self {
            top_start: 0.0,
            top_end: radius,
            bottom_end: radius,
            bottom_start: 0.0,
        }
    }

    /// Both sides at once, each with its own radius — the reference's
    /// `BorderRadiusDirectional.horizontal`.
    pub const fn horizontal(start: f32, end: f32) -> Self {
        Self {
            top_start: start,
            top_end: end,
            bottom_end: end,
            bottom_start: start,
        }
    }

    /// The top pair and the bottom pair. Neither depends on the direction, so this is the
    /// same as [`BorderRadius`]'s — and is here for the same reason as
    /// [`uniform`](Self::uniform).
    pub const fn vertical(top: f32, bottom: f32) -> Self {
        Self {
            top_start: top,
            top_end: top,
            bottom_end: bottom,
            bottom_start: bottom,
        }
    }

    /// **The concrete radius**, once the direction is known: `start` becomes left where
    /// the text runs left to right, and right where it does not.
    pub const fn resolve(self, direction: TextDirection) -> BorderRadius {
        match direction {
            TextDirection::Ltr => BorderRadius {
                top_left: self.top_start,
                top_right: self.top_end,
                bottom_right: self.bottom_end,
                bottom_left: self.bottom_start,
            },
            TextDirection::Rtl => BorderRadius {
                top_left: self.top_end,
                top_right: self.top_start,
                bottom_right: self.bottom_start,
                bottom_left: self.bottom_end,
            },
        }
    }
}

impl From<f32> for BorderRadiusDirectional {
    fn from(radius: f32) -> Self {
        Self::uniform(radius)
    }
}

impl BorderRadius {
    /// Each corner `t` of the way from `self` to `other`.
    ///
    /// Not clamped: a corner past its target is what a spring asks for at the end of its
    /// travel, and the one rule for a radius in flight is this one — an animated container
    /// and a decoration transition both go through it.
    #[must_use]
    pub fn lerp(self, other: BorderRadius, t: f32) -> BorderRadius {
        let mix = |a: f32, b: f32| a + (b - a) * t;
        BorderRadius {
            top_left: mix(self.top_left, other.top_left),
            top_right: mix(self.top_right, other.top_right),
            bottom_right: mix(self.bottom_right, other.bottom_right),
            bottom_left: mix(self.bottom_left, other.bottom_left),
        }
    }

    /// No rounding at all.
    pub const ZERO: Self = Self::uniform(0.0);

    /// The same radius on all four corners.
    pub const fn uniform(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    /// Only the **top** corners rounded (headers, rising sheets).
    pub const fn top(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: 0.0,
            bottom_left: 0.0,
        }
    }

    /// Only the **bottom** corners rounded.
    pub const fn bottom(radius: f32) -> Self {
        Self {
            top_left: 0.0,
            top_right: 0.0,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    /// Only the **left** corners rounded.
    pub const fn left(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: 0.0,
            bottom_right: 0.0,
            bottom_left: radius,
        }
    }

    /// Only the **right** corners rounded.
    ///
    /// With [`left`](Self::left) this completes the set: a shape rounded on one
    /// **vertical** edge is what a side panel wants — square where it meets the window,
    /// round where it meets the content — and until now only the horizontal pair
    /// ([`top`](Self::top), [`bottom`](Self::bottom)) existed.
    pub const fn right(radius: f32) -> Self {
        Self {
            top_left: 0.0,
            top_right: radius,
            bottom_right: radius,
            bottom_left: 0.0,
        }
    }

    /// Radii **clamped at zero** — a negative radius is meaningless when painting.
    pub fn clamped(self) -> Self {
        Self {
            top_left: self.top_left.max(0.0),
            top_right: self.top_right.max(0.0),
            bottom_right: self.bottom_right.max(0.0),
            bottom_left: self.bottom_left.max(0.0),
        }
    }

    /// Every corner grown by `by` — the envelope of a blurred shadow.
    pub fn inflate(self, by: f32) -> Self {
        Self {
            top_left: self.top_left + by,
            top_right: self.top_right + by,
            bottom_right: self.bottom_right + by,
            bottom_left: self.bottom_left + by,
        }
    }

    /// Every radius multiplied by `factor` (DPI scaling).
    pub fn scale(self, factor: f32) -> Self {
        Self {
            top_left: self.top_left * factor,
            top_right: self.top_right * factor,
            bottom_right: self.bottom_right * factor,
            bottom_left: self.bottom_left * factor,
        }
    }

    /// `[tl, tr, br, bl]`, ready for the GPU.
    pub fn to_array(self) -> [f32; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
    }
}

impl From<f32> for BorderRadius {
    fn from(radius: f32) -> Self {
        Self::uniform(radius)
    }
}

/// **The shape a box decoration paints** — the reference's `BoxShape`
/// (`box_border.dart:26`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BoxShape {
    /// A rectangle, its corners rounded by the decoration's radius.
    #[default]
    Rectangle,
    /// A circle, centred in the box, as wide as the box's shorter side. The decoration's
    /// radius means nothing to it.
    Circle,
}

/// One side of a [`BorderSide`] pair, the same on both sides of a lerp.
fn lerp_side(a: BorderSide, b: BorderSide, t: f32) -> BorderSide {
    // A side on one end only arrives by thickening, in its own colour.
    match (a.width > 0.0, b.width > 0.0) {
        (true, true) => {
            BorderSide::new(a.color.lerp(b.color, t), a.width + (b.width - a.width) * t)
        }
        (true, false) => BorderSide::new(a.color, a.width * (1.0 - t)),
        (false, true) => BorderSide::new(b.color, b.width * t),
        (false, false) => BorderSide::NONE,
    }
}

/// **A box's border, side by side** — the reference's `Border` (`box_border.dart:431`):
/// each of the four sides its own colour and width.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Border {
    /// The top side.
    pub top: BorderSide,
    /// The right side.
    pub right: BorderSide,
    /// The bottom side.
    pub bottom: BorderSide,
    /// The left side.
    pub left: BorderSide,
}

impl Border {
    /// No border on any side.
    pub const NONE: Self = Self {
        top: BorderSide::NONE,
        right: BorderSide::NONE,
        bottom: BorderSide::NONE,
        left: BorderSide::NONE,
    };

    /// The same width and colour on all four sides.
    pub const fn new(width: f32, color: Color) -> Self {
        Self::all(BorderSide::new(color, width))
    }

    /// `side` on all four sides — the reference's `Border.all` and `fromBorderSide`.
    pub const fn all(side: BorderSide) -> Self {
        Self {
            top: side,
            right: side,
            bottom: side,
            left: side,
        }
    }

    /// `vertical` on the left and the right, `horizontal` on the top and the bottom — the
    /// reference's `Border.symmetric`.
    pub const fn symmetric(vertical: BorderSide, horizontal: BorderSide) -> Self {
        Self {
            top: horizontal,
            right: vertical,
            bottom: horizontal,
            left: vertical,
        }
    }

    /// The four sides, top, right, bottom, left.
    fn sides(&self) -> [BorderSide; 4] {
        [self.top, self.right, self.bottom, self.left]
    }

    /// Whether the four sides are the same.
    pub fn is_uniform(&self) -> bool {
        let [t, r, b, l] = self.sides();
        t == r && r == b && b == l
    }

    /// `true` when some side is visible — non-zero width and non-zero alpha.
    pub fn is_visible(&self) -> bool {
        self.sides().iter().any(BorderSide::is_drawn)
    }

    /// The room the border takes inside the box, side by side.
    pub fn dimensions(&self) -> Insets {
        let w = |s: BorderSide| if s.is_drawn() { s.width } else { 0.0 };
        Insets::new(w(self.top), w(self.right), w(self.bottom), w(self.left))
    }

    /// The border `t` of the way to `other`, side by side.
    #[must_use]
    pub fn lerp(self, other: Border, t: f32) -> Border {
        Border {
            top: lerp_side(self.top, other.top, t),
            right: lerp_side(self.right, other.right, t),
            bottom: lerp_side(self.bottom, other.bottom, t),
            left: lerp_side(self.left, other.left, t),
        }
    }
}

/// **A box's border, by the line's start and end** — the reference's `BorderDirectional`
/// (`box_border.dart:799`): the start side is the left in a left-to-right script and the
/// right in a right-to-left one.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BorderDirectional {
    /// The top side.
    pub top: BorderSide,
    /// The side where a line of text starts.
    pub start: BorderSide,
    /// The side where a line of text ends.
    pub end: BorderSide,
    /// The bottom side.
    pub bottom: BorderSide,
}

impl BorderDirectional {
    /// The sides on the screen, for `direction`.
    pub fn resolve(&self, direction: TextDirection) -> Border {
        let (left, right) = match direction {
            TextDirection::Ltr => (self.start, self.end),
            TextDirection::Rtl => (self.end, self.start),
        };
        Border {
            top: self.top,
            right,
            bottom: self.bottom,
            left,
        }
    }
}

/// A box's border, by its physical sides or by the line's start and end.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BoxBorder {
    /// Left, right, top, bottom.
    Physical(Border),
    /// Start, end, top, bottom.
    Directional(BorderDirectional),
}

impl BoxBorder {
    /// The sides on the screen, for `direction`.
    pub fn resolve(&self, direction: TextDirection) -> Border {
        match self {
            BoxBorder::Physical(border) => *border,
            BoxBorder::Directional(border) => border.resolve(direction),
        }
    }
}

impl From<Border> for BoxBorder {
    fn from(border: Border) -> Self {
        BoxBorder::Physical(border)
    }
}

impl From<BorderDirectional> for BoxBorder {
    fn from(border: BorderDirectional) -> Self {
        BoxBorder::Directional(border)
    }
}

/// A soft drop shadow.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxShadow {
    /// Colour; its alpha sets the intensity.
    pub color: Color,
    /// Offset `(dx, dy)`, in logical pixels.
    pub offset: (f32, f32),
    /// Blur radius.
    pub blur: f32,
    /// How far the shadow grows beyond the box, before blurring.
    pub spread: f32,
    /// Which side of the shadow's edge the blur keeps (milestone 645): both, by default.
    pub blur_style: BlurStyle,
}

impl BoxShadow {
    /// A shadow offset by `(dx, dy)` with `blur`, and no spread.
    pub const fn new(dx: f32, dy: f32, blur: f32, color: Color) -> Self {
        Self {
            color,
            offset: (dx, dy),
            blur,
            spread: 0.0,
            blur_style: BlurStyle::Normal,
        }
    }

    /// Sets the `spread`.
    pub const fn spread(mut self, spread: f32) -> Self {
        self.spread = spread;
        self
    }

    /// Sets which side of the edge the blur keeps: a solid shadow with a soft edge, a
    /// glow outside the box only, a shading inside it.
    pub const fn blur_style(mut self, style: BlurStyle) -> Self {
        self.blur_style = style;
        self
    }

    /// **The three shadows a surface `elevation` high casts**, in `color`: a sharp one close
    /// under it, a softer one further down, and a wide faint one all round. The reference's
    /// own table, and its three strengths — a fifth, a seventh and an eighth of `color`'s
    /// opacity — so `color` is the shadow's colour at full strength, black by default
    /// (milestone 606).
    ///
    /// Between two heights of the table the shadows are interpolated, so a height that
    /// animates moves smoothly; past twenty-four, it is twenty-four.
    pub fn for_elevation(elevation: f32, color: Color) -> [BoxShadow; 3] {
        let e = elevation.clamp(0.0, 24.0);
        let upper = ELEVATION_TABLE
            .iter()
            .position(|(level, _)| *level >= e)
            .unwrap_or(ELEVATION_TABLE.len() - 1);
        let lower = upper.saturating_sub(1);
        let (a, b) = (ELEVATION_TABLE[lower], ELEVATION_TABLE[upper]);
        let t = if b.0 > a.0 {
            (e - a.0) / (b.0 - a.0)
        } else {
            1.0
        };
        let lerp = |x: f32, y: f32| x + (y - x) * t;
        let layer = |i: usize, strength: f32| {
            let (ya, blur_a, spread_a) = a.1[i];
            let (yb, blur_b, spread_b) = b.1[i];
            // A surface on the page casts nothing: its shadows fade in as it lifts.
            let fade = if e < 1.0 { e } else { 1.0 };
            BoxShadow {
                color: color.with_alpha(color.a * strength * fade),
                offset: (0.0, lerp(ya, yb)),
                blur: lerp(blur_a, blur_b),
                spread: lerp(spread_a, spread_b),
                blur_style: BlurStyle::Normal,
            }
        };
        [layer(0, 0.2), layer(1, 0.14), layer(2, 0.12)]
    }

    /// The rectangle the shadow occupies around `rect` (offset + blur + spread).
    pub fn bounds(&self, rect: Rect) -> Rect {
        let grow = self.blur + self.spread;
        Rect::new(
            rect.x + self.offset.0 - grow,
            rect.y + self.offset.1 - grow,
            rect.width + 2.0 * grow,
            rect.height + 2.0 * grow,
        )
    }
}

/// The reference's shadows per height: `(height, [(drop, blur, spread); 3])`, the key light's
/// umbra, its penumbra, then the ambient light.
/// One shadow of a height: its drop, its blur and its spread.
type Layer = (f32, f32, f32);
/// A height and its three shadows.
type Height = (f32, [Layer; 3]);

const ELEVATION_TABLE: [Height; 11] = [
    (0.0, [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]),
    (1.0, [(2.0, 1.0, -1.0), (1.0, 1.0, 0.0), (1.0, 3.0, 0.0)]),
    (2.0, [(3.0, 1.0, -2.0), (2.0, 2.0, 0.0), (1.0, 5.0, 0.0)]),
    (3.0, [(3.0, 3.0, -2.0), (3.0, 4.0, 0.0), (1.0, 8.0, 0.0)]),
    (4.0, [(2.0, 4.0, -1.0), (4.0, 5.0, 0.0), (1.0, 10.0, 0.0)]),
    (6.0, [(3.0, 5.0, -1.0), (6.0, 10.0, 0.0), (1.0, 18.0, 0.0)]),
    (8.0, [(5.0, 5.0, -3.0), (8.0, 10.0, 1.0), (3.0, 14.0, 2.0)]),
    (9.0, [(5.0, 6.0, -3.0), (9.0, 12.0, 1.0), (3.0, 16.0, 2.0)]),
    (
        12.0,
        [(7.0, 8.0, -4.0), (12.0, 17.0, 2.0), (5.0, 22.0, 4.0)],
    ),
    (
        16.0,
        [(8.0, 10.0, -5.0), (16.0, 24.0, 2.0), (6.0, 30.0, 5.0)],
    ),
    (
        24.0,
        [(11.0, 15.0, -7.0), (24.0, 38.0, 3.0), (9.0, 46.0, 8.0)],
    ),
];

/// Paints the shadows of a surface `elevation` high, with corners `radius`, behind `rect`:
/// [`BoxShadow::for_elevation`]'s three, each as [`BoxDecoration`] paints one. Nothing at
/// a height of nought or in a colour with no opacity (milestone 606).
pub fn paint_elevation(
    scene: &mut Scene,
    rect: Rect,
    radius: BorderRadius,
    elevation: f32,
    color: Color,
) {
    if elevation <= 0.0 || color.a <= 0.0 {
        return;
    }
    for shadow in BoxShadow::for_elevation(elevation, color) {
        let grow = (shadow.blur + shadow.spread).max(0.0);
        scene.shadow(
            shadow.bounds(rect),
            shadow.color,
            radius.inflate(grow),
            shadow.blur,
        );
    }
}

/// The complete decoration of a box — the reference's `BoxDecoration`
/// (`box_decoration.dart:81`).
///
/// The paint order is **fixed**, the reference's (`box_decoration.dart:571`): the shadows,
/// in order, then the background, then the picture, then the border. The background is
/// either flat (`color`) or a gradient, which replaces the colour. A border with no
/// background paints an outline over transparency; a wholly empty decoration paints nothing
/// at all.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BoxDecoration {
    /// Background colour.
    pub color: Option<Color>,
    /// A gradient filling the background, in place of `color` — linear, radial or sweep
    /// (milestone 644).
    pub gradient: Option<crate::Gradient>,
    /// The border, side by side.
    pub border: Option<BoxBorder>,
    /// Corner radii, per corner. A [`BoxShape::Circle`] has none.
    pub radius: BorderRadius,
    /// The shadows, painted in order, behind the box (`box_decoration.dart:448`).
    pub shadows: Vec<BoxShadow>,
    /// A rectangle or a circle.
    pub shape: BoxShape,
    /// A picture over the background, under the border, clipped to the shape
    /// (milestone 645).
    pub image: Option<DecorationImage>,
    /// How the background — the colour or the gradient — meets what is painted under
    /// the box (milestone 646): `None` paints it over. Nothing else of the decoration
    /// is blended, and with no colour or gradient it has nothing to do.
    pub background_blend_mode: Option<crate::BlendMode>,
}

/// A colour that may be absent on either side, `t` of the way across.
///
/// Absent means **nothing painted**, so a colour on one side only fades: it keeps its hue
/// and only its alpha travels. Interpolating towards `Color::TRANSPARENT` instead would be
/// interpolating towards transparent *black* — a red fill fading out would go dark red on
/// the way, in a movement that was only ever about disappearing.
fn fade_between(a: Option<Color>, b: Option<Color>, t: f32) -> Option<Color> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.lerp(b, t)),
        (Some(a), None) => Some(a.fade(1.0 - t)),
        (None, Some(b)) => Some(b.fade(t)),
        (None, None) => None,
    }
}

impl BoxDecoration {
    /// The decoration `t` of the way from `self` to `other` — what a decoration transition
    /// paints mid-flight. Each part has its own rule, and the rules are the point:
    ///
    /// - **Colours mix** where both sides have one, in the space colours are stated in,
    ///   as every animated colour in this framework does.
    /// - **A part on one side only arrives or leaves; it does not come from nowhere.** A
    ///   fill fades, keeping its hue. A border thickens from nought in its own colour. A
    ///   shadow grows from under the box as it fades in. Each is the part scaled by how far
    ///   along it is, which is also what the reference does with a part one side lacks.
    /// - **A flat fill is a gradient whose two ends agree**, so flat to graded spreads the
    ///   far end out of the fill rather than laying a gradient over it. Here a gradient
    ///   *starts* at the fill colour, so the two always arrive and leave together.
    /// - **Corners** travel one by one.
    ///
    /// The absent colour here is **not** the absent colour of a text style, and the two
    /// rules differ for that reason. A text style that names no colour is asking the theme
    /// for one — a real, visible colour — so it holds still rather than fade. A decoration
    /// that names no fill paints nothing, so fading is exactly what reaching it means.
    ///
    /// `t` is clamped to `0..=1`, and a `t` that is not a number is no progress: past its
    /// ends a colour has nowhere to go, and a decoration whose colours stopped at the end
    /// while its corners kept going would be two clocks. At `0` and `1` the answer is the
    /// end itself, exactly.
    #[must_use]
    pub fn lerp(self, other: BoxDecoration, t: f32) -> BoxDecoration {
        if t.is_nan() || t <= 0.0 {
            return self;
        }
        if t >= 1.0 {
            return other;
        }
        // A rectangle and a circle do not blend: the shape changes half way, as the
        // reference's does (`box_decoration.dart:301`).
        let shape = if t < 0.5 { self.shape } else { other.shape };
        let mix = |a: f32, b: f32| a + (b - a) * t;
        // The reference's `Gradient.lerp` (`box_decoration.dart:309`).
        let gradient = crate::Gradient::lerp(self.gradient.as_ref(), other.gradient.as_ref(), t);
        // Side by side, each arriving or leaving by thickening in its own colour. A
        // directional border is read left to right here; two directional ones stay so.
        let border = match (self.border, other.border) {
            (Some(BoxBorder::Directional(a)), Some(BoxBorder::Directional(b))) => {
                Some(BoxBorder::Directional(BorderDirectional {
                    top: lerp_side(a.top, b.top, t),
                    start: lerp_side(a.start, b.start, t),
                    end: lerp_side(a.end, b.end, t),
                    bottom: lerp_side(a.bottom, b.bottom, t),
                }))
            }
            (Some(a), Some(b)) => Some(BoxBorder::Physical(
                a.resolve(TextDirection::Ltr)
                    .lerp(b.resolve(TextDirection::Ltr), t),
            )),
            (Some(a), None) => Some(BoxBorder::Physical(
                a.resolve(TextDirection::Ltr).lerp(Border::NONE, t),
            )),
            (None, Some(b)) => Some(BoxBorder::Physical(
                Border::NONE.lerp(b.resolve(TextDirection::Ltr), t),
            )),
            (None, None) => None,
        };
        // A shadow on one side only, scaled: it grows out from under the box as it fades
        // in. Scaling the geometry alone would leave a hard-edged block of shadow colour
        // under a box whose own fill may be fading too.
        let grown = |s: BoxShadow, f: f32| BoxShadow {
            color: s.color.fade(f),
            offset: (s.offset.0 * f, s.offset.1 * f),
            blur: s.blur * f,
            spread: s.spread * f,
            blur_style: s.blur_style,
        };
        // The shadows pair by pair, and those one list has more of grow or shrink — the
        // reference's `BoxShadow.lerpList` (`box_shadow.dart`).
        let longest = self.shadows.len().max(other.shadows.len());
        let shadows = (0..longest)
            .map(|i| match (self.shadows.get(i), other.shadows.get(i)) {
                (Some(a), Some(b)) => BoxShadow {
                    color: a.color.lerp(b.color, t),
                    offset: (mix(a.offset.0, b.offset.0), mix(a.offset.1, b.offset.1)),
                    blur: mix(a.blur, b.blur),
                    spread: mix(a.spread, b.spread),
                    // The reference's rule: a plain blur takes the other's style.
                    blur_style: if a.blur_style == BlurStyle::Normal {
                        b.blur_style
                    } else {
                        a.blur_style
                    },
                },
                (Some(a), None) => grown(*a, 1.0 - t),
                (None, Some(b)) => grown(*b, t),
                (None, None) => unreachable!("within the longer list"),
            })
            .collect();
        BoxDecoration {
            color: fade_between(self.color, other.color, t),
            gradient,
            border,
            radius: self.radius.lerp(other.radius, t),
            shadows,
            shape,
            // Two pictures cross over; one alone fades.
            image: DecorationImage::lerp(self.image.as_ref(), other.image.as_ref(), t),
            // A mode does not blend into another: it changes half way, as the shape
            // does. The reference's lerp drops it, so a blended box painted plainly
            // through every transition.
            background_blend_mode: if t < 0.5 {
                self.background_blend_mode
            } else {
                other.background_blend_mode
            },
        }
    }
}

impl BoxDecoration {
    /// A decoration with a flat background.
    pub fn filled(color: Color) -> Self {
        Self {
            color: Some(color),
            ..Default::default()
        }
    }

    /// Sets the corner radii — uniform through `f32`, per corner through
    /// [`BorderRadius`].
    pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
        self.radius = radius.into();
        self
    }

    /// Sets the border, side by side or by the line's start and end.
    pub fn border(mut self, border: impl Into<BoxBorder>) -> Self {
        self.border = Some(border.into());
        self
    }

    /// Adds a shadow, after (so over) those already there.
    pub fn shadow(mut self, shadow: BoxShadow) -> Self {
        self.shadows.push(shadow);
        self
    }

    /// Sets the shadows, painted in order.
    pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
        self.shadows = shadows.into_iter().collect();
        self
    }

    /// Paints a rectangle or a circle.
    pub fn shape(mut self, shape: BoxShape) -> Self {
        self.shape = shape;
        self
    }

    /// Fills the background with a gradient — linear, radial or sweep — in place of the
    /// colour.
    pub fn gradient(mut self, gradient: impl Into<crate::Gradient>) -> Self {
        self.gradient = Some(gradient.into());
        self
    }

    /// Paints a picture over the background, under the border.
    pub fn image(mut self, image: DecorationImage) -> Self {
        self.image = Some(image);
        self
    }

    /// Blends the background — the colour or the gradient — with what is under the
    /// box by `mode`, rather than painting it over.
    pub fn background_blend_mode(mut self, mode: crate::BlendMode) -> Self {
        self.background_blend_mode = Some(mode);
        self
    }

    /// The inner margin the border needs — add it to the padding so the content is
    /// not eaten by the line. This is what feeds taffy. A directional border is read
    /// left to right; see [`Self::content_padding_in`].
    pub fn content_padding(&self) -> Insets {
        self.content_padding_in(TextDirection::Ltr)
    }

    /// The inner margin the border needs, for a box in `direction`.
    pub fn content_padding_in(&self, direction: TextDirection) -> Insets {
        self.border
            .map(|b| b.resolve(direction).dimensions())
            .unwrap_or(Insets::ZERO)
    }

    /// The box the decoration paints in `rect`: `rect` itself, or the square a circle is
    /// inscribed in (`box_decoration.dart:436`).
    fn painted(&self, rect: Rect) -> (Rect, BorderRadius) {
        match self.shape {
            BoxShape::Rectangle => (rect, self.radius),
            BoxShape::Circle => {
                let side = rect.width.min(rect.height);
                let square = Rect::new(
                    rect.x + (rect.width - side) * 0.5,
                    rect.y + (rect.height - side) * 0.5,
                    side,
                    side,
                );
                (square, BorderRadius::uniform(side * 0.5))
            }
        }
    }

    /// Lowers the decoration into `scene` primitives, in the fixed order
    /// shadows → background → picture → border, for a box read left to right. See
    /// [`Self::paint_into_in`].
    pub fn paint_into(&self, scene: &mut Scene, rect: Rect, opacity: f32) {
        self.paint_into_in(scene, rect, opacity, TextDirection::Ltr);
    }

    /// Lowers the decoration into `scene` primitives, in the fixed order
    /// shadows → background → picture → border. `opacity` (`0..=1`) modulates **every** colour,
    /// which is how a fade-in works. `rect` is the box in absolute coordinates;
    /// `direction` places a directional border's start and end.
    pub fn paint_into_in(
        &self,
        scene: &mut Scene,
        rect: Rect,
        opacity: f32,
        direction: TextDirection,
    ) {
        let (shape_rect, radius) = self.painted(rect);

        // 1) The shadows, in order, behind everything else.
        for shadow in &self.shadows {
            scene.styled_shadow(
                shadow.bounds(shape_rect),
                shadow.color.fade(opacity),
                radius.inflate(shadow.blur + shadow.spread),
                shadow.blur,
                shadow.blur_style,
            );
        }

        // 2/3) Background (flat or gradient), and a uniform border in the same primitive
        // — unless a picture goes between them.
        let border = self.border.map(|b| b.resolve(direction));
        let uniform = border.filter(|b| b.is_uniform());
        let (border_width, border_color) = match uniform {
            Some(b) if b.top.width > 0.0 => (b.top.width, b.top.color.fade(opacity)),
            _ => (0.0, Color::TRANSPARENT),
        };
        let has_border = uniform.is_some_and(|b| b.is_visible());
        let image = self.image.as_ref();
        let has_background = self.color.is_some() || self.gradient.is_some();
        // A blend other than painting over: the background goes in a group of its own.
        let blend = self
            .background_blend_mode
            .filter(|m| *m != crate::BlendMode::SrcOver && has_background);
        // Anything between the fill and the border takes the line off the fill.
        let apart = image.is_some() || blend.is_some();
        let (fill_border_width, fill_border_color) = if apart {
            (0.0, Color::TRANSPARENT)
        } else {
            (border_width, border_color)
        };
        let fill = |scene: &mut Scene, radius: BorderRadius| match (self.color, &self.gradient) {
            (_, Some(gradient)) => scene.shaded_rect(
                shape_rect,
                gradient.resolve(direction),
                opacity,
                radius,
                fill_border_width,
                fill_border_color,
            ),
            (Some(color), None) => scene.draw_rect(
                shape_rect,
                color.fade(opacity),
                radius,
                fill_border_width,
                fill_border_color,
            ),
            // Border only, with no background: an outline over transparency.
            (None, _) if has_border && !apart => scene.draw_rect(
                shape_rect,
                Color::TRANSPARENT,
                radius,
                border_width,
                border_color,
            ),
            // Nothing to paint.
            (None, _) => {}
        };

        match blend {
            // The background blended with what is under the box (`box_decoration.dart:413`),
            // square, in a group whose shape is the box's: its edge is the group's
            // coverage, so what the shape leaves out keeps what was there.
            Some(mode) => {
                let outer = scene.current_clip();
                let (clip, shape) = self
                    .shape_clip(outer, shape_rect, radius)
                    .unwrap_or((outer.intersect(shape_rect), ClipShape::Rect));
                scene.set_clip(clip);
                scene.blended_in(mode, shape, |scene| fill(scene, BorderRadius::ZERO));
                scene.set_clip(outer);
            }
            None => fill(scene, radius),
        }

        // The picture, over the background and clipped to the shape
        // (`box_decoration.dart:476`).
        if let Some(image) = image {
            self.paint_image(scene, image, rect, shape_rect, radius, direction, opacity);
        }
        // Then the uniform border, when something came between it and the fill.
        if apart && has_border {
            scene.draw_rect(
                shape_rect,
                Color::TRANSPARENT,
                radius,
                border_width,
                border_color,
            );
        }

        // 3) A border whose sides differ.
        if let Some(border) = border.filter(|b| !b.is_uniform() && b.is_visible()) {
            paint_sides(scene, shape_rect, radius, self.shape, &border, opacity);
        }
    }

    /// The picture painted into the whole box, clipped to the circle or the rounded
    /// corners when there are any — the reference's `_paintBackgroundImage`.
    #[allow(clippy::too_many_arguments)]
    fn paint_image(
        &self,
        scene: &mut Scene,
        image: &DecorationImage,
        rect: Rect,
        shape_rect: Rect,
        radius: BorderRadius,
        direction: TextDirection,
        opacity: f32,
    ) {
        let start = scene.primitives().len();
        image.paint(scene, rect, direction, opacity);
        let Some((clip, clip_shape)) = self.shape_clip(scene.current_clip(), shape_rect, radius)
        else {
            return;
        };
        if scene.primitives().len() == start {
            return;
        }
        let primitives = scene.split_off(start);
        let owner = scene.current_owner();
        scene.push_primitive(Primitive::Layer {
            primitives,
            opacity: 1.0,
            clip,
            clip_shape,
            transform: None,
            filter: crate::LayerFilter::NONE,
            owner,
        });
    }

    /// The clip a layer takes to be the box's circle or rounded corners, within the
    /// `outer` clip; `None` for square corners, which clip nothing.
    ///
    /// A layer's shape is inscribed in its clip, so it is exact only when the clip is
    /// the whole shape. A box partly clipped away is clipped by its outline instead.
    fn shape_clip(
        &self,
        outer: Rect,
        shape_rect: Rect,
        radius: BorderRadius,
    ) -> Option<(Rect, ClipShape)> {
        let shape = match self.shape {
            BoxShape::Circle => ClipShape::Oval,
            BoxShape::Rectangle if radius != BorderRadius::ZERO => {
                ClipShape::RRect(radius.clamped())
            }
            BoxShape::Rectangle => return None,
        };
        Some(if outer.intersect(shape_rect) == shape_rect {
            (shape_rect, shape)
        } else {
            (
                outer.intersect(shape_rect),
                ClipShape::Path(ShapeBorder::rounded(radius).outline(shape_rect)),
            )
        })
    }
}

/// **A border whose sides differ** (`box_border.dart:681`). In one colour, the band between
/// the box and the box inset by each side, which keeps its corners and its circle; in
/// several, on a rectangle, each side as its own trapezoid, mitred at the corners.
fn paint_sides(
    scene: &mut Scene,
    rect: Rect,
    radius: BorderRadius,
    shape: BoxShape,
    border: &Border,
    opacity: f32,
) {
    let drawn: Vec<BorderSide> = border
        .sides()
        .into_iter()
        .filter(BorderSide::is_drawn)
        .collect();
    let one_colour = drawn.windows(2).all(|w| w[0].color == w[1].color);
    let rounded = shape == BoxShape::Circle || radius != BorderRadius::ZERO;
    let w = border.dimensions();
    let inner = Rect::new(
        rect.x + w.left,
        rect.y + w.top,
        (rect.width - w.left - w.right).max(0.0),
        (rect.height - w.top - w.bottom).max(0.0),
    );
    if one_colour && rounded {
        let color = drawn.first().map_or(Color::TRANSPARENT, |s| s.color);
        // The inner corners are the outer ones less the thicker of the two sides that meet
        // there.
        let less = |r: f32, a: f32, b: f32| (r - a.max(b)).max(0.0);
        let inner_radius = BorderRadius {
            top_left: less(radius.top_left, w.top, w.left),
            top_right: less(radius.top_right, w.top, w.right),
            bottom_right: less(radius.bottom_right, w.bottom, w.right),
            bottom_left: less(radius.bottom_left, w.bottom, w.left),
        };
        let band = ShapeBorder::rounded(radius)
            .outline(rect)
            .append(ShapeBorder::rounded(inner_radius).outline(inner));
        scene.fill_path(&band, color.fade(opacity));
        return;
    }
    // Each side as a trapezoid from the outer edge to the inner one.
    let (l, t, r, b) = (rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
    let (il, it, ir, ib) = (
        inner.x,
        inner.y,
        inner.x + inner.width,
        inner.y + inner.height,
    );
    let quads = [
        (border.top, [(l, t), (r, t), (ir, it), (il, it)]),
        (border.right, [(r, t), (r, b), (ir, ib), (ir, it)]),
        (border.bottom, [(r, b), (l, b), (il, ib), (ir, ib)]),
        (border.left, [(l, b), (l, t), (il, it), (il, ib)]),
    ];
    for (side, [a, b2, c, d]) in quads {
        if !side.is_drawn() {
            continue;
        }
        let path = Path::new()
            .move_to(Point::new(a.0, a.1))
            .line_to(Point::new(b2.0, b2.1))
            .line_to(Point::new(c.0, c.1))
            .line_to(Point::new(d.0, d.1))
            .close();
        scene.fill_path(&path, side.color.fade(opacity));
    }
}

#[cfg(test)]
mod tests {
    /// **A directional radius names the corner by the line, not by the wall**
    /// (`border_radius.dart:621`), and `resolve` says which wall that is.
    #[test]
    fn a_directional_radius_follows_the_reading_direction() {
        let end = BorderRadiusDirectional::end(16.0);
        assert_eq!(
            end.resolve(TextDirection::Ltr),
            BorderRadius::right(16.0),
            "the line ends on the right in English"
        );
        assert_eq!(
            end.resolve(TextDirection::Rtl),
            BorderRadius::left(16.0),
            "and on the left in Arabic"
        );

        let start = BorderRadiusDirectional::start(16.0);
        assert_eq!(start.resolve(TextDirection::Ltr), BorderRadius::left(16.0));
        assert_eq!(start.resolve(TextDirection::Rtl), BorderRadius::right(16.0));

        // Both sides at once, each keeping its own number across the mirror.
        let both = BorderRadiusDirectional::horizontal(4.0, 12.0);
        assert_eq!(
            both.resolve(TextDirection::Ltr),
            BorderRadius {
                top_left: 4.0,
                top_right: 12.0,
                bottom_right: 12.0,
                bottom_left: 4.0,
            }
        );
        assert_eq!(
            both.resolve(TextDirection::Rtl),
            BorderRadius {
                top_left: 12.0,
                top_right: 4.0,
                bottom_right: 4.0,
                bottom_left: 12.0,
            }
        );

        // What has no side does not move.
        for direction in [TextDirection::Ltr, TextDirection::Rtl] {
            assert_eq!(
                BorderRadiusDirectional::uniform(8.0).resolve(direction),
                BorderRadius::uniform(8.0)
            );
            assert_eq!(
                BorderRadiusDirectional::vertical(8.0, 0.0).resolve(direction),
                BorderRadius::top(8.0)
            );
        }
    }
    use super::*;
    use crate::Primitive;

    fn rect() -> Rect {
        Rect::new(10.0, 20.0, 100.0, 40.0)
    }

    #[test]
    fn content_padding_reserves_the_border() {
        let deco = BoxDecoration::filled(Color::WHITE).border(Border::new(2.0, Color::BLACK));
        assert_eq!(deco.content_padding(), Insets::uniform(2.0));
        // An invisible border (zero width) → no padding.
        let none = BoxDecoration::filled(Color::WHITE).border(Border::new(0.0, Color::BLACK));
        assert_eq!(none.content_padding(), Insets::ZERO);
    }

    #[test]
    fn empty_decoration_paints_nothing() {
        let mut scene = Scene::new();
        BoxDecoration::default().paint_into(&mut scene, rect(), 1.0);
        assert!(scene.is_empty());
    }

    #[test]
    fn fixed_paint_order_shadow_then_fill() {
        let mut scene = Scene::new();
        let deco = BoxDecoration::filled(Color::WHITE)
            .radius(6.0)
            .shadow(BoxShadow::new(
                0.0,
                4.0,
                8.0,
                Color::rgba(0.0, 0.0, 0.0, 0.5),
            ));
        deco.paint_into(&mut scene, rect(), 1.0);
        // Two primitives: the shadow first, then the background.
        assert_eq!(scene.len(), 2);
        match scene.primitives()[0] {
            Primitive::Rect { blur, .. } => {
                assert!(blur > 0.0, "first primitive = the blurred shadow")
            }
            _ => panic!("expected a rectangle"),
        }
        match scene.primitives()[1] {
            Primitive::Rect { blur, color, .. } => {
                assert_eq!(blur, 0.0, "second primitive = the crisp background");
                assert_eq!(color, Color::WHITE);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn opacity_fades_all_colours() {
        let mut scene = Scene::new();
        BoxDecoration::filled(Color::rgb(1.0, 0.0, 0.0))
            .border(Border::new(2.0, Color::rgb(0.0, 1.0, 0.0)))
            .paint_into(&mut scene, rect(), 0.5);
        match scene.primitives()[0] {
            Primitive::Rect {
                color,
                border_color,
                ..
            } => {
                assert_eq!(color.a, 0.5);
                assert_eq!(border_color.a, 0.5);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn border_only_paints_transparent_fill_with_stroke() {
        let mut scene = Scene::new();
        BoxDecoration::default()
            .border(Border::new(1.0, Color::WHITE))
            .paint_into(&mut scene, rect(), 1.0);
        assert_eq!(scene.len(), 1);
        match scene.primitives()[0] {
            Primitive::Rect {
                color,
                border_width,
                ..
            } => {
                assert_eq!(color, Color::TRANSPARENT);
                assert_eq!(border_width, 1.0);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn shadow_bounds_grow_with_blur_and_spread() {
        let s = BoxShadow::new(0.0, 0.0, 4.0, Color::BLACK).spread(2.0);
        let b = s.bounds(Rect::new(0.0, 0.0, 10.0, 10.0));
        // grow = blur + spread = 6 on every side.
        assert_eq!(b, Rect::new(-6.0, -6.0, 22.0, 22.0));
    }
}

/// The decoration in flight (milestone 501): one rule per part, and the ends exact.
#[cfg(test)]
mod lerp_tests {
    use super::*;

    const RED: Color = Color {
        r: 1.0,
        g: 0.0,
        b: 0.0,
        a: 1.0,
    };
    const BLUE: Color = Color {
        r: 0.0,
        g: 0.0,
        b: 1.0,
        a: 1.0,
    };

    /// **The ends are the ends, exactly** — and past them, and at a progress that is not a
    /// number, the nearer end.
    #[test]
    fn the_ends_are_the_ends_exactly() {
        let a = BoxDecoration::filled(RED).radius(4.0);
        let b = BoxDecoration::filled(BLUE).border(Border::new(2.0, RED));
        let lerp = |t: f32| a.clone().lerp(b.clone(), t);
        assert_eq!(lerp(0.0), a);
        assert_eq!(lerp(1.0), b);
        assert_eq!(lerp(-0.5), a, "an undershoot stops at the start");
        assert_eq!(lerp(1.5), b, "an overshoot stops at the end");
        assert_eq!(lerp(f32::NAN), a, "and no progress is no progress");
    }

    /// **A fill fading out keeps its hue.** The obvious interpolation — towards
    /// `Color::TRANSPARENT` — is towards transparent *black*, and half-way there a red is a
    /// half-opaque dark red: a movement that was only about disappearing darkens on the way.
    #[test]
    fn a_fill_fading_out_does_not_pass_through_black() {
        let mid = BoxDecoration::filled(RED).lerp(BoxDecoration::default(), 0.5);
        let c = mid.color.expect("still painted, half faded");
        assert_eq!((c.r, c.g, c.b), (1.0, 0.0, 0.0), "the same red");
        assert!((c.a - 0.5).abs() < 1e-6, "at half its opacity: {c:?}");
        let naive = RED.lerp(Color::TRANSPARENT, 0.5);
        assert!(naive.r < 0.6, "the trap this avoids: {naive:?}");
    }

    /// And one fading in arrives in its own colour, only fainter.
    #[test]
    fn a_fill_fading_in_arrives_in_its_own_colour() {
        let c = BoxDecoration::default()
            .lerp(BoxDecoration::filled(BLUE), 0.25)
            .color
            .expect("already there, faintly");
        assert_eq!((c.r, c.g, c.b), (0.0, 0.0, 1.0));
        assert!((c.a - 0.25).abs() < 1e-6, "{c:?}");
    }

    /// **A gradient on one side only fades in by its opacity** over the fill, the
    /// reference's `Gradient.scale` (`box_decoration.dart:309`): its colours keep their hue.
    #[test]
    fn a_gradient_on_one_side_fades_in() {
        let flat = BoxDecoration::filled(RED);
        let graded =
            BoxDecoration::filled(RED).gradient(crate::LinearGradient::new(vec![RED, BLUE]));
        let mid = flat.lerp(graded, 0.25);
        assert_eq!(mid.color, Some(RED), "the fill does not move");
        let g = mid.gradient.expect("a gradient fading in");
        assert_eq!(g.colors()[1], BLUE.fade(0.25));
    }

    /// **A border arrives by thickening, in its own colour** — not as a colour on its way
    /// from nowhere.
    #[test]
    fn a_border_arrives_by_thickening_in_its_own_colour() {
        let lined = BoxDecoration::filled(RED).border(Border::new(4.0, BLUE));
        let quarter = BoxDecoration::filled(RED)
            .lerp(lined, 0.25)
            .border
            .expect("a line already")
            .resolve(TextDirection::Ltr);
        assert_eq!(quarter.top.width, 1.0);
        assert_eq!(quarter.top.color, BLUE);
    }

    /// **A shadow arrives by growing out from under the box as it fades in.**
    #[test]
    fn a_shadow_grows_and_fades_in() {
        let raised = BoxDecoration::filled(RED).shadow(BoxShadow::new(
            0.0,
            8.0,
            16.0,
            Color::rgba(0.0, 0.0, 0.0, 0.4),
        ));
        let half = BoxDecoration::filled(RED).lerp(raised, 0.5).shadows[0];
        assert_eq!(half.offset, (0.0, 4.0));
        assert_eq!(half.blur, 8.0);
        assert!((half.color.a - 0.2).abs() < 1e-6, "{:?}", half.color);
    }

    /// Corners travel one by one, each from its own start.
    #[test]
    fn corners_travel_one_by_one() {
        let r = BoxDecoration::default()
            .radius(BorderRadius::top(8.0))
            .lerp(BoxDecoration::default().radius(16.0), 0.5)
            .radius;
        assert_eq!((r.top_left, r.bottom_left), (12.0, 8.0));
    }

    /// **At a height of the reference's table, its three shadows exactly**, each carrying its
    /// share of the colour: a fifth, a seventh, an eighth.
    #[test]
    fn a_height_of_the_table_casts_its_three_shadows() {
        let [umbra, penumbra, ambient] = BoxShadow::for_elevation(3.0, Color::BLACK);
        assert_eq!(
            (umbra.offset, umbra.blur, umbra.spread),
            ((0.0, 3.0), 3.0, -2.0)
        );
        assert_eq!(
            (penumbra.offset, penumbra.blur, penumbra.spread),
            ((0.0, 3.0), 4.0, 0.0)
        );
        assert_eq!(
            (ambient.offset, ambient.blur, ambient.spread),
            ((0.0, 1.0), 8.0, 0.0)
        );
        assert_eq!(
            [umbra.color.a, penumbra.color.a, ambient.color.a],
            [0.2, 0.14, 0.12]
        );
        let [_, twenty_four, _] = BoxShadow::for_elevation(24.0, Color::BLACK);
        assert_eq!((twenty_four.offset, twenty_four.blur), ((0.0, 24.0), 38.0));
    }

    /// **Between two heights, between their shadows**; past twenty-four, twenty-four; and
    /// the colour's own opacity scales all three.
    #[test]
    fn heights_between_and_beyond_the_table() {
        let [_, half, _] = BoxShadow::for_elevation(5.0, Color::BLACK);
        assert_eq!(
            (half.offset.1, half.blur),
            (5.0, 7.5),
            "half way from 4 to 6"
        );
        assert_eq!(
            BoxShadow::for_elevation(40.0, Color::BLACK),
            BoxShadow::for_elevation(24.0, Color::BLACK)
        );
        let [faint, ..] = BoxShadow::for_elevation(1.0, Color::rgba(0.0, 0.0, 1.0, 0.5));
        assert_eq!(faint.color, Color::rgba(0.0, 0.0, 1.0, 0.1));
        // Lifting off the page fades in rather than jumping to a height of one.
        let [low, ..] = BoxShadow::for_elevation(0.5, Color::BLACK);
        assert!((low.color.a - 0.1).abs() < 1e-6, "{low:?}");
    }

    /// **Painted, a height is three soft shapes** grown past the box by their blur and
    /// spread, with the box's corners grown with them; at nought, or in a colour nobody can
    /// see, nothing.
    #[test]
    fn a_height_paints_three_shadows_and_nought_paints_none() {
        let rect = Rect::new(10.0, 20.0, 100.0, 40.0);
        let mut scene = Scene::new();
        paint_elevation(
            &mut scene,
            rect,
            BorderRadius::uniform(8.0),
            3.0,
            Color::BLACK,
        );
        let shadows: Vec<_> = scene
            .primitives()
            .iter()
            .filter_map(|p| match p {
                crate::Primitive::Rect {
                    rect, radius, blur, ..
                } => Some((*rect, *radius, *blur)),
                _ => None,
            })
            .collect();
        assert_eq!(shadows.len(), 3);
        let (penumbra, radius, blur) = shadows[1];
        assert_eq!(blur, 4.0);
        assert_eq!(
            penumbra,
            Rect::new(6.0, 19.0, 108.0, 48.0),
            "dropped 3, grown 4"
        );
        assert_eq!(radius, BorderRadius::uniform(12.0));

        for (height, colour) in [(0.0, Color::BLACK), (3.0, Color::TRANSPARENT)] {
            let mut none = Scene::new();
            paint_elevation(&mut none, rect, BorderRadius::ZERO, height, colour);
            assert!(none.primitives().is_empty(), "{height} {colour:?}");
        }
    }
}

/// The decoration's shape, its borders side by side, and its list of shadows
/// (milestone 641).
#[cfg(test)]
mod box_decoration_tests {
    use super::*;
    use crate::{PathVerb, Primitive};

    const RED: Color = Color::rgb(1.0, 0.0, 0.0);
    const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);
    const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);

    fn painted(deco: &BoxDecoration, rect: Rect, direction: TextDirection) -> Vec<Primitive> {
        let mut scene = Scene::new();
        deco.paint_into_in(&mut scene, rect, 1.0, direction);
        scene.primitives().to_vec()
    }

    /// **A circle is centred in the box, as wide as its shorter side**, and its shadow is a
    /// circle too (`box_decoration.dart:436`). The radius it was given is not read.
    #[test]
    fn a_circle_is_centred_on_the_shorter_side() {
        let deco = BoxDecoration::filled(RED)
            .radius(3.0)
            .shape(BoxShape::Circle)
            .shadow(BoxShadow::new(0.0, 0.0, 4.0, BLUE));
        let prims = painted(&deco, Rect::new(0.0, 0.0, 100.0, 40.0), TextDirection::Ltr);
        match &prims[1] {
            Primitive::Rect {
                rect,
                radius,
                color,
                ..
            } => {
                assert_eq!(*color, RED);
                assert_eq!(*rect, Rect::new(30.0, 0.0, 40.0, 40.0));
                assert_eq!(*radius, BorderRadius::uniform(20.0), "round, not 3");
            }
            other => panic!("the fill, not {other:?}"),
        }
        match &prims[0] {
            Primitive::Rect { radius, .. } => {
                assert_eq!(*radius, BorderRadius::uniform(24.0), "a round shadow")
            }
            other => panic!("the shadow, not {other:?}"),
        }
    }

    /// **The shadows are painted in order, behind the box** (`box_decoration.dart:452`).
    #[test]
    fn the_shadows_are_painted_in_order_behind_the_box() {
        let deco = BoxDecoration::filled(RED).shadows([
            BoxShadow::new(0.0, 1.0, 2.0, GREEN),
            BoxShadow::new(0.0, 4.0, 8.0, BLUE),
        ]);
        let prims = painted(&deco, Rect::new(0.0, 0.0, 50.0, 50.0), TextDirection::Ltr);
        let colours: Vec<Color> = prims
            .iter()
            .filter_map(|p| match p {
                Primitive::Rect { color, .. } => Some(*color),
                _ => None,
            })
            .collect();
        assert_eq!(colours, vec![GREEN, BLUE, RED]);
    }

    /// **Sides of different colours are four trapezoids**, each its own colour, mitred at
    /// the corners; a side with no width is not drawn.
    #[test]
    fn sides_of_different_colours_are_drawn_one_by_one() {
        let border = Border {
            top: BorderSide::new(RED, 2.0),
            right: BorderSide::new(GREEN, 4.0),
            bottom: BorderSide::new(BLUE, 2.0),
            left: BorderSide::NONE,
        };
        let deco = BoxDecoration::default().border(border);
        let prims = painted(&deco, Rect::new(0.0, 0.0, 50.0, 30.0), TextDirection::Ltr);
        let fills: Vec<Color> = prims
            .iter()
            .filter_map(|p| match p {
                Primitive::Path { fill, .. } => *fill,
                _ => None,
            })
            .collect();
        assert_eq!(
            fills,
            vec![RED, GREEN, BLUE],
            "three sides, the fourth has none"
        );
        assert_eq!(deco.content_padding(), Insets::new(2.0, 4.0, 2.0, 0.0));
        // With round corners as well, still side by side: one band would be one colour.
        // (The reference refuses several colours with round corners, `box_border.dart:711`.)
        let rounded = BoxDecoration::default().border(border).radius(8.0);
        let fills: Vec<Color> = painted(
            &rounded,
            Rect::new(0.0, 0.0, 50.0, 30.0),
            TextDirection::Ltr,
        )
        .iter()
        .filter_map(|p| match p {
            Primitive::Path { fill, .. } => *fill,
            _ => None,
        })
        .collect();
        assert_eq!(fills, vec![RED, GREEN, BLUE]);
    }

    /// **One colour, uneven widths, round corners: one band** between the box and the box
    /// inset by each side (`box_border.dart:686`).
    #[test]
    fn one_colour_with_corners_is_one_band() {
        let border = Border {
            top: BorderSide::new(RED, 6.0),
            ..Border::new(2.0, RED)
        };
        let deco = BoxDecoration::default().border(border).radius(8.0);
        let prims = painted(&deco, Rect::new(0.0, 0.0, 50.0, 30.0), TextDirection::Ltr);
        let bands: Vec<&Primitive> = prims
            .iter()
            .filter(|p| matches!(p, Primitive::Path { .. }))
            .collect();
        assert_eq!(bands.len(), 1, "one band");
        match bands[0] {
            Primitive::Path { path, fill, .. } => {
                assert_eq!(*fill, Some(RED));
                let moves = path
                    .verbs()
                    .iter()
                    .filter(|v| matches!(v, PathVerb::MoveTo(_)))
                    .count();
                assert_eq!(moves, 2, "the outline and the hole in it");
                // The hole's corners are the box's less the thicker side meeting there:
                // 8 less 6 at the top left, so the hole starts 2 in from its own left.
                let hole = path
                    .verbs()
                    .iter()
                    .filter_map(|v| match v {
                        PathVerb::MoveTo(p) => Some(*p),
                        _ => None,
                    })
                    .nth(1)
                    .expect("the hole");
                assert_eq!((hole.x, hole.y), (4.0, 6.0));
            }
            _ => unreachable!(),
        }
    }

    /// **A uniform border stays one primitive with the fill**, as before.
    #[test]
    fn a_uniform_border_is_drawn_with_the_fill() {
        let deco = BoxDecoration::filled(RED).border(Border::new(3.0, BLUE));
        let prims = painted(&deco, Rect::new(0.0, 0.0, 50.0, 30.0), TextDirection::Ltr);
        assert_eq!(prims.len(), 1);
        match &prims[0] {
            Primitive::Rect {
                border_width,
                border_color,
                ..
            } => assert_eq!((*border_width, *border_color), (3.0, BLUE)),
            other => panic!("{other:?}"),
        }
    }

    /// **A directional border's start is the left in a left-to-right script and the right
    /// in a right-to-left one**, for the paint and for the room it takes.
    #[test]
    fn a_directional_border_follows_the_script() {
        let border = BorderDirectional {
            start: BorderSide::new(RED, 5.0),
            ..Default::default()
        };
        let deco = BoxDecoration::default().border(border);
        assert_eq!(deco.content_padding_in(TextDirection::Ltr).left, 5.0);
        assert_eq!(deco.content_padding_in(TextDirection::Rtl).right, 5.0);
        let first_x =
            |direction| match &painted(&deco, Rect::new(0.0, 0.0, 50.0, 30.0), direction)[0] {
                Primitive::Path { path, .. } => match path.verbs()[0] {
                    PathVerb::MoveTo(p) => p.x,
                    _ => unreachable!(),
                },
                other => panic!("{other:?}"),
            };
        // The left side's trapezoid starts at the bottom left; the right side's at the top
        // right.
        assert_eq!(first_x(TextDirection::Ltr), 0.0);
        assert_eq!(first_x(TextDirection::Rtl), 50.0);
    }

    /// **Two lists of shadows pair up; the longer one's extras grow or shrink**, and a
    /// circle and a rectangle swap half way.
    #[test]
    fn shadow_lists_pair_up_and_shapes_swap_half_way() {
        let one = BoxDecoration::default().shadow(BoxShadow::new(0.0, 2.0, 4.0, BLUE));
        let two = BoxDecoration::default().shape(BoxShape::Circle).shadows([
            BoxShadow::new(0.0, 6.0, 8.0, BLUE),
            BoxShadow::new(0.0, 10.0, 20.0, RED),
        ]);
        let mid = one.clone().lerp(two.clone(), 0.5);
        assert_eq!(mid.shadows.len(), 2);
        assert_eq!(mid.shadows[0].offset, (0.0, 4.0));
        assert_eq!(
            mid.shadows[1].offset,
            (0.0, 5.0),
            "the extra grows from nothing"
        );
        assert!((mid.shadows[1].color.a - 0.5).abs() < 1e-6);
        assert_eq!(mid.shape, BoxShape::Circle);
        assert_eq!(one.lerp(two, 0.49).shape, BoxShape::Rectangle);
    }

    /// **The border's constructors** are the reference's.
    #[test]
    fn the_border_constructors() {
        let side = BorderSide::new(RED, 1.0);
        let other = BorderSide::new(BLUE, 2.0);
        assert!(Border::all(side).is_uniform());
        let sym = Border::symmetric(side, other);
        assert_eq!(
            (sym.left, sym.right, sym.top, sym.bottom),
            (side, side, other, other)
        );
        assert!(!sym.is_uniform());
        assert!(!Border::NONE.is_visible());
        let half = Border::NONE.lerp(Border::all(other), 0.5);
        assert_eq!(
            half.top,
            BorderSide::new(BLUE, 1.0),
            "thickening in its own colour"
        );
    }

    fn picture() -> crate::DecorationImage {
        let pixels = crate::ImageData::from_rgba(4, 4, vec![255; 64]).into_handle();
        crate::DecorationImage::new(pixels).fit(crate::BoxFit::Fill)
    }

    /// The kinds of primitive a decoration paints, in order, layers opened.
    fn kinds(primitives: &[Primitive]) -> Vec<String> {
        primitives
            .iter()
            .map(|p| match p {
                Primitive::Rect {
                    border_width,
                    color,
                    blur,
                    ..
                } if *blur > 0.0 => format!("shadow {color:?} {border_width}"),
                Primitive::Rect {
                    border_width,
                    color,
                    ..
                } => format!("rect {color:?} {border_width}"),
                Primitive::Image { .. } => "image".to_string(),
                Primitive::Layer { primitives, .. } => {
                    format!("layer [{}]", kinds(primitives).join(", "))
                }
                other => format!("{other:?}"),
            })
            .collect()
    }

    fn painted_clipped(decoration: &BoxDecoration, clip: Rect) -> Scene {
        let mut scene = Scene::new();
        scene.set_clip(clip);
        decoration.paint_into(&mut scene, Rect::new(0.0, 0.0, 40.0, 20.0), 1.0);
        scene
    }

    /// **The picture goes between the background and the border**
    /// (`box_decoration.dart:476`): the fill loses its line, which is drawn over the
    /// picture.
    #[test]
    fn a_picture_lies_between_the_fill_and_the_border() {
        let decoration = BoxDecoration::filled(RED)
            .border(Border::new(2.0, BLUE))
            .image(picture());
        let scene = painted_clipped(&decoration, Rect::UNBOUNDED);
        assert_eq!(
            kinds(scene.primitives()),
            vec![
                format!("rect {RED:?} 0"),
                "image".to_string(),
                format!("rect {:?} 2", Color::TRANSPARENT),
            ]
        );
        // A border alone, over the picture.
        let outline = BoxDecoration::default()
            .border(Border::new(2.0, BLUE))
            .image(picture());
        assert_eq!(
            kinds(painted_clipped(&outline, Rect::UNBOUNDED).primitives()),
            vec![
                "image".to_string(),
                format!("rect {:?} 2", Color::TRANSPARENT)
            ]
        );
        // With no picture, the fill carries its line.
        let plain = BoxDecoration::filled(RED).border(Border::new(2.0, BLUE));
        assert_eq!(
            kinds(painted_clipped(&plain, Rect::UNBOUNDED).primitives()),
            vec![format!("rect {RED:?} 2")]
        );
        // Without a background, a picture alone.
        let alone = BoxDecoration::default().image(picture());
        assert_eq!(
            kinds(painted_clipped(&alone, Rect::UNBOUNDED).primitives()),
            vec!["image"]
        );
    }

    /// **The picture is clipped to the corners or the circle**, into the whole box.
    #[test]
    fn a_picture_takes_the_shape_of_its_box() {
        let rounded = BoxDecoration::default().radius(6.0).image(picture());
        let scene = painted_clipped(&rounded, Rect::UNBOUNDED);
        let Primitive::Layer {
            clip,
            clip_shape,
            primitives,
            ..
        } = &scene.primitives()[0]
        else {
            panic!("a clipped layer");
        };
        assert_eq!(*clip, Rect::new(0.0, 0.0, 40.0, 20.0));
        assert_eq!(*clip_shape, ClipShape::RRect(BorderRadius::uniform(6.0)));
        let Primitive::Image { rect, .. } = &primitives[0] else {
            panic!("the picture");
        };
        assert_eq!(*rect, Rect::new(0.0, 0.0, 40.0, 20.0), "filling the box");

        let circle = BoxDecoration::default()
            .shape(BoxShape::Circle)
            .image(picture());
        let scene = painted_clipped(&circle, Rect::UNBOUNDED);
        let Primitive::Layer {
            clip,
            clip_shape,
            primitives,
            ..
        } = &scene.primitives()[0]
        else {
            panic!("a clipped layer");
        };
        assert_eq!(
            *clip,
            Rect::new(10.0, 0.0, 20.0, 20.0),
            "the circle's square"
        );
        assert_eq!(*clip_shape, ClipShape::Oval);
        let Primitive::Image { rect, .. } = &primitives[0] else {
            panic!("the picture");
        };
        assert_eq!(*rect, Rect::new(0.0, 0.0, 40.0, 20.0), "into the whole box");

        // Square corners clip nothing.
        let square = BoxDecoration::default().image(picture());
        assert!(matches!(
            painted_clipped(&square, Rect::UNBOUNDED).primitives()[0],
            Primitive::Image { .. }
        ));
    }

    /// **A box partly clipped away clips its picture by the outline**: a shape inscribed
    /// in what is left of the box would be the wrong shape.
    #[test]
    fn a_partly_hidden_box_clips_its_picture_by_its_outline() {
        let rounded = BoxDecoration::default().radius(6.0).image(picture());
        let scene = painted_clipped(&rounded, Rect::new(0.0, 0.0, 30.0, 100.0));
        let Primitive::Layer {
            clip, clip_shape, ..
        } = &scene.primitives()[0]
        else {
            panic!("a clipped layer");
        };
        assert_eq!(*clip, Rect::new(0.0, 0.0, 30.0, 20.0));
        let ClipShape::Path(path) = clip_shape else {
            panic!("the outline, as a path");
        };
        assert_eq!(
            *path,
            ShapeBorder::rounded(6.0).outline(Rect::new(0.0, 0.0, 40.0, 20.0))
        );
    }

    #[test]
    fn a_picture_on_one_side_fades() {
        let shown = BoxDecoration::default().image(picture());
        let mid = BoxDecoration::default().lerp(shown.clone(), 0.25);
        let scene = painted_clipped(&mid, Rect::UNBOUNDED);
        let Primitive::Image { tint, .. } = &scene.primitives()[0] else {
            panic!("the picture");
        };
        assert_eq!(tint.a, 0.25);
        assert_eq!(
            BoxDecoration::default().lerp(shown.clone(), 1.0).image,
            shown.image
        );
    }

    /// **A shadow paints with its blur style**, and the reference's lerp keeps a styled
    /// blur over a plain one.
    #[test]
    fn a_shadow_keeps_its_blur_style() {
        let glow = BoxShadow::new(0.0, 0.0, 8.0, BLUE).blur_style(BlurStyle::Outer);
        let scene = painted_clipped(&BoxDecoration::default().shadow(glow), Rect::UNBOUNDED);
        let Primitive::Rect { blur_style, .. } = &scene.primitives()[0] else {
            panic!("the shadow");
        };
        assert_eq!(*blur_style, BlurStyle::Outer);
        let plain = BoxShadow::new(0.0, 0.0, 8.0, BLUE);
        let solid = plain.blur_style(BlurStyle::Solid);
        let mix = |a: BoxShadow, b: BoxShadow| {
            BoxDecoration::default()
                .shadow(a)
                .lerp(BoxDecoration::default().shadow(b), 0.5)
                .shadows[0]
                .blur_style
        };
        assert_eq!(mix(plain, solid), BlurStyle::Solid);
        assert_eq!(mix(solid, plain), BlurStyle::Solid);
        assert_eq!(mix(glow, solid), BlurStyle::Outer);
        // One side only: the style travels with the shadow.
        let arriving = BoxDecoration::default().lerp(BoxDecoration::default().shadow(glow), 0.5);
        assert_eq!(arriving.shadows[0].blur_style, BlurStyle::Outer);
        assert_eq!(plain.blur_style, BlurStyle::Normal, "plain by default");
        assert!(BoxShadow::for_elevation(4.0, BLUE)
            .iter()
            .all(|s| s.blur_style == BlurStyle::Normal));
    }

    fn blended(mode: crate::BlendMode) -> BoxDecoration {
        BoxDecoration::filled(RED).background_blend_mode(mode)
    }

    /// The background's group, and what is in it.
    fn group(scene: &Scene) -> (Rect, ClipShape, Option<crate::BlendMode>, Vec<Primitive>) {
        match &scene.primitives()[0] {
            Primitive::Layer {
                clip,
                clip_shape,
                filter,
                primitives,
                ..
            } => (*clip, clip_shape.clone(), filter.blend, primitives.clone()),
            other => panic!("a group, not {other:?}"),
        }
    }

    /// **A blended background is a group in the box's shape** (`box_decoration.dart:413`),
    /// the fill square inside it: the shape's edge is the blend's coverage.
    #[test]
    fn a_blended_background_is_a_group_in_the_box_shape() {
        let multiply = crate::BlendMode::Multiply;
        let rounded = blended(multiply).radius(6.0);
        let (clip, shape, mode, inside) = group(&painted_clipped(&rounded, Rect::UNBOUNDED));
        assert_eq!(clip, Rect::new(0.0, 0.0, 40.0, 20.0));
        assert_eq!(shape, ClipShape::RRect(BorderRadius::uniform(6.0)));
        assert_eq!(mode, Some(multiply));
        let [Primitive::Rect {
            radius,
            color,
            border_width,
            ..
        }] = inside.as_slice()
        else {
            panic!("the fill alone");
        };
        assert_eq!(
            *radius,
            BorderRadius::ZERO,
            "square: the group gives the shape"
        );
        assert_eq!(*color, RED);
        assert_eq!(*border_width, 0.0);

        let circle = blended(multiply).shape(BoxShape::Circle);
        let (clip, shape, ..) = group(&painted_clipped(&circle, Rect::UNBOUNDED));
        assert_eq!(clip, Rect::new(10.0, 0.0, 20.0, 20.0));
        assert_eq!(shape, ClipShape::Oval);

        // Square corners: the box, held to the clip.
        let square = blended(multiply);
        let (clip, shape, ..) = group(&painted_clipped(&square, Rect::new(0.0, 0.0, 30.0, 50.0)));
        assert_eq!(clip, Rect::new(0.0, 0.0, 30.0, 20.0));
        assert_eq!(shape, ClipShape::Rect);

        // Partly clipped away: by its outline.
        let (_, shape, ..) = group(&painted_clipped(&rounded, Rect::new(0.0, 0.0, 30.0, 50.0)));
        assert!(matches!(shape, ClipShape::Path(_)), "the outline");
    }

    /// **Only the background is blended**: the border is drawn after, over it, and the
    /// scene's clip is given back.
    #[test]
    fn a_blended_background_leaves_the_border_plain() {
        let lined = blended(crate::BlendMode::Screen).border(Border::new(2.0, BLUE));
        let scene = painted_clipped(&lined, Rect::new(0.0, 0.0, 100.0, 100.0));
        assert_eq!(
            kinds(scene.primitives()),
            vec![
                format!("layer [rect {RED:?} 0]"),
                format!("rect {:?} 2", Color::TRANSPARENT),
            ]
        );
        assert_eq!(scene.current_clip(), Rect::new(0.0, 0.0, 100.0, 100.0));
    }

    /// **Painting over is no blend at all, and no background has nothing to blend.**
    #[test]
    fn an_ordinary_or_empty_background_is_not_grouped() {
        let over = blended(crate::BlendMode::SrcOver);
        assert_eq!(
            kinds(painted_clipped(&over, Rect::UNBOUNDED).primitives()),
            vec![format!("rect {RED:?} 0")]
        );
        let empty = BoxDecoration::default()
            .border(Border::new(2.0, BLUE))
            .background_blend_mode(crate::BlendMode::Multiply);
        assert_eq!(
            kinds(painted_clipped(&empty, Rect::UNBOUNDED).primitives()),
            vec![format!("rect {:?} 2", Color::TRANSPARENT)]
        );
        let graded = BoxDecoration::default()
            .gradient(crate::LinearGradient::new(vec![RED, BLUE]))
            .background_blend_mode(crate::BlendMode::Multiply);
        let (.., inside) = group(&painted_clipped(&graded, Rect::UNBOUNDED));
        assert!(
            matches!(
                &inside[0],
                Primitive::Rect {
                    shader: Some(_),
                    ..
                }
            ),
            "a gradient is a background too"
        );
    }

    /// **A blend mode changes half way**, as the shape does.
    #[test]
    fn a_blend_mode_changes_half_way() {
        let plain = BoxDecoration::filled(RED);
        let multiplied = blended(crate::BlendMode::Multiply);
        assert_eq!(
            plain
                .clone()
                .lerp(multiplied.clone(), 0.4)
                .background_blend_mode,
            None
        );
        assert_eq!(
            plain.lerp(multiplied.clone(), 0.5).background_blend_mode,
            Some(crate::BlendMode::Multiply)
        );
        assert_eq!(
            multiplied
                .lerp(BoxDecoration::filled(RED), 0.4)
                .background_blend_mode,
            Some(crate::BlendMode::Multiply)
        );
    }
}