xa11y-core 0.14.0

Core types, traits, and selector engine for xa11y cross-platform accessibility
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
//! Drawing annotations onto a capture: boxes, tag badges, and the bitmap font
//! that writes the tags.
//!
//! This module is the *pure pixel* half of the annotated-screenshot feature.
//! It takes rectangles in logical screen coordinates, a short tag string, and
//! a colour, and it writes RGBA bytes. It knows nothing about selectors,
//! providers, or platforms — the `xa11y` umbrella crate resolves elements into
//! [`Annotation`]s and owns the legend that maps a tag back to an element.
//!
//! Everything here is testable and fuzzable with no display, no application,
//! and no permissions, which is where essentially all of the arithmetic risk
//! in the feature lives.
//!
//! # No new dependency
//!
//! Boxes and badges are written straight into the RGBA buffer with no
//! blending, and tags are drawn from an embedded 5×7 bitmap font covering
//! `0-9` and `A-Z` — 36 glyphs, one `const` table. A TrueType rasteriser plus an
//! embedded font file would cost a few hundred KB in every binary and both
//! wheels for two character classes.
//!
//! # Overflow
//!
//! [`Rect`] is `i32`, [`Screenshot::scale`] is `f32`, and the products index a
//! `Vec<u8>`. Every coordinate is widened to `i64` before any arithmetic, and
//! every write goes through one `set_px`, which range-checks against the
//! image and then converts to a buffer index with `checked_*`. Nothing in this
//! module panics or writes out of bounds for any input; `annotate_ops` in
//! `xa11y/fuzz/fuzz_targets/` asserts that against arbitrary input.

use crate::element::{sane_scale, Rect};
use crate::error::{Error, Result};
use crate::input::Point;
use crate::screenshot::Screenshot;

// ── Public surface ───────────────────────────────────────────────────────

/// Colour-blind-safe qualitative palette (Okabe–Ito, minus black).
///
/// Eight colours in the original; black is dropped because a black box is
/// indistinguishable from dark UI chrome and from the badge foreground.
/// Every entry clears WCAG AA (4.5:1) against the black or white that
/// [`Annotation`]'s badge picks for it — asserted by a unit test in this
/// module.
///
/// Callers assign by group order and wrap with `% ANNOTATION_PALETTE.len()`.
pub const ANNOTATION_PALETTE: [[u8; 3]; 7] = [
    [0xE6, 0x9F, 0x00], // orange          #E69F00
    [0x56, 0xB4, 0xE9], // sky blue        #56B4E9
    [0x00, 0x9E, 0x73], // bluish green    #009E73
    [0xF0, 0xE4, 0x42], // yellow          #F0E442
    [0x00, 0x72, 0xB2], // blue            #0072B2
    [0xD5, 0x5E, 0x00], // vermillion      #D55E00
    [0xCC, 0x79, 0xA7], // reddish purple  #CC79A7
];

/// One box to draw: where, what to write in it, and in what colour.
///
/// `rect` is in **logical** screen coordinates, the same space as
/// `Element::bounds`. [`Screenshot::annotate`] translates it by the capture's
/// origin and converts it to physical pixels.
///
/// `#[non_exhaustive]`: an annotation is built in another crate (the `xa11y`
/// umbrella resolves locators into these), so it owes callers a constructor
/// and a chained setter rather than a struct literal — the same shape as
/// `ClickOptions`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Annotation {
    /// Where to draw, in **logical** screen coordinates.
    pub rect: Rect,
    /// The text drawn in the badge — `"B7"`. See [`tag_for`].
    ///
    /// Characters outside `0-9` and `A-Z` (after ASCII uppercasing) have no
    /// glyph in the embedded font and are not drawn. A tag with no drawable
    /// character gets no badge at all, only the box.
    pub tag: String,
    /// Box and badge colour, RGB. Defaults to `ANNOTATION_PALETTE[0]`.
    pub color: [u8; 3],
}

impl Annotation {
    /// An annotation in the first palette colour. Chain [`Annotation::color`]
    /// to pick another.
    pub fn new(rect: Rect, tag: impl Into<String>) -> Self {
        Self {
            rect,
            tag: tag.into(),
            color: ANNOTATION_PALETTE[0],
        }
    }

    /// Set the box and badge colour.
    #[must_use]
    pub fn color(mut self, rgb: [u8; 3]) -> Self {
        self.color = rgb;
        self
    }
}

/// The tag drawn in an annotation box: a letter for the group, a 1-based
/// number within it — `A1`, `B7`, `C12`.
///
/// **This function is the single place the tag format is decided.** Every
/// other surface (the CLI legend, the MCP result, both bindings) formats tags
/// by calling it, so a change here is a change everywhere and the tests in
/// this module are the only other place it lands.
///
/// A letter followed by digits is *self-delimiting*: there is no separator to
/// lose to compression or downscaling, so no two distinct tags can render to
/// the same glyph sequence. `A12` and `AB2` stay distinct; `1-12` and `11-2`
/// do not. The number is exactly the `:nth(n)` argument for the element.
///
/// Both arguments are **1-based**. Groups past 26 continue `AA`, `AB`, … in
/// the bijective base-26 everyone knows from spreadsheet columns. A `group`
/// or `index` of `0` is read as `1`: this function has no failure channel,
/// and every index in xa11y counts from one.
///
/// ```
/// use xa11y_core::screenshot::tag_for;
///
/// assert_eq!(tag_for(1, 1), "A1");
/// assert_eq!(tag_for(2, 7), "B7");
/// assert_eq!(tag_for(27, 3), "AA3");
/// ```
pub fn tag_for(group: usize, index: usize) -> String {
    let mut n = group.max(1);
    let mut letters = Vec::new();
    while n > 0 {
        let rem = (n - 1) % 26;
        // `rem` is 0..=25, so the sum stays inside `b'A'..=b'Z'`.
        letters.push(char::from(b'A' + rem as u8));
        n = (n - 1) / 26;
    }

    let mut tag: String = letters.into_iter().rev().collect();
    tag.push_str(&index.max(1).to_string());
    tag
}

// ── Screenshot::annotate ─────────────────────────────────────────────────

impl Screenshot {
    /// Draw `annotations` onto a copy of this capture.
    ///
    /// `origin` is the logical top-left of what this capture covers, and the
    /// caller takes it from whichever call produced the pixels. For
    /// [`crate::ScreenshotProvider::capture_region`] it is the rect that was
    /// passed in, by that method's contract. For a full capture it is the
    /// [`Point`] returned alongside the image by
    /// [`crate::ScreenshotProvider::capture_full`], which is **not** reliably
    /// `(0, 0)`: Windows captures the virtual desktop, whose top-left goes
    /// negative as soon as a monitor sits left of or above the primary one,
    /// and macOS captures a display that need not be the one at the
    /// coordinate-space origin.
    ///
    /// Each annotation's rect is translated by `-origin` and then scaled to
    /// physical pixels by [`Screenshot::scale`]. Passing `(0, 0)` for a
    /// capture that does not start there shifts every box by the difference,
    /// and nothing here can detect it: the shifted rects still land inside a
    /// capture that wide, so they are drawn over the wrong pixels.
    ///
    /// Returns a **new** [`Screenshot`] (the pixels are cloned; `self` is
    /// never mutated) and the indices of the annotations that were not drawn.
    ///
    /// An annotation whose physical rect does not intersect the image is
    /// **skipped, not clamped**, and its index is in the returned `Vec`. A box
    /// clamped to the edge would claim the wrong pixels, and a zero-area rect
    /// covers nothing at all, so it is skipped for the same reason. An
    /// annotation that is only partly inside is drawn clipped.
    ///
    /// Nothing is deduplicated: two annotations with the same rect are two
    /// boxes, because two selectors matching one element is information the
    /// caller asked for.
    ///
    /// # Drawing
    ///
    /// Boxes are a `stroke`-px outline drawn inside the rect, where `stroke`
    /// is `clamp(round(scale), 1, 4)`. The tag goes in a filled badge in the
    /// same colour, written in whichever of black or white has the higher
    /// WCAG contrast ratio against that colour, and outlined in that same
    /// colour so the badge reads against busy UI. Glyphs are drawn at
    /// `2 × stroke`, so a tag is ten by fourteen *logical* pixels on every
    /// display rather than the five by seven that is illegible at 1×.
    ///
    /// The badge is placed **outside** the box — by preference immediately
    /// above its top-left corner, bottom edge touching the box's top edge —
    /// so it never covers the content the box points at. See [`badge_spot`]
    /// for the fallback order; a badge only lands inside the box when no
    /// outside position is visible, and is clamped into the box's on-image
    /// part when no position at all is — which is what happens to a box that
    /// extends past every edge of the capture.
    ///
    /// Annotations are drawn largest-area-first so small elements land on top
    /// of the containers that hold them, and a badge that would cover one
    /// already placed moves to another position rather than hiding it.
    ///
    /// A badge may fall outside the image even when its box is visible; it is
    /// clipped like everything else, and it never moves the box or turns a
    /// drawn annotation into a skipped one.
    ///
    /// # Errors
    ///
    /// [`Error::Platform`] when `pixels` does not hold exactly
    /// `width * height * 4` bytes — the same check [`Screenshot::to_png`]
    /// makes, reported here rather than drawn into a buffer whose shape is
    /// unknown.
    pub fn annotate(
        &self,
        annotations: &[Annotation],
        origin: Point,
    ) -> Result<(Screenshot, Vec<usize>)> {
        let expected = (self.width as usize)
            .checked_mul(self.height as usize)
            .and_then(|n| n.checked_mul(4))
            .ok_or_else(|| Error::Platform {
                code: -1,
                message: "annotate: screenshot dimensions overflow".into(),
            })?;
        if self.pixels.len() != expected {
            return Err(Error::Platform {
                code: -1,
                message: format!(
                    "annotate: screenshot pixel buffer size {} does not match {}x{} RGBA ({} bytes)",
                    self.pixels.len(),
                    self.width,
                    self.height,
                    expected
                ),
            });
        }

        // `sane_scale` collapses a non-finite or non-positive scale to 1.0,
        // the same treatment `Rect::to_physical` applies internally — taking
        // it here keeps the stroke width consistent with the geometry.
        let scale = sane_scale(f64::from(self.scale));
        // In 1.0..=4.0 after the clamp, so the cast is exact.
        let unit = scale.round().clamp(1.0, 4.0) as i64;
        // Badge glyphs are drawn at twice the stroke unit — floor 2, so a tag
        // is 10×14 px on a 1× display instead of the 5×7 that is legible only
        // zoomed in, and the apparent size stays constant as `scale` grows.
        // `unit` is 1..=4, so this is 2..=8 with no risk of overflow.
        let glyph_unit = unit * 2;

        let mut canvas = Canvas {
            width: i64::from(self.width),
            height: i64::from(self.height),
            pixels: self.pixels.clone(),
        };
        let bounds = canvas.bounds();

        let mut skipped = Vec::new();
        let mut visible: Vec<(usize, &Annotation, PxRect)> = Vec::new();
        for (i, ann) in annotations.iter().enumerate() {
            // Saturating: a rect at `i32::MIN` translated by a positive
            // origin stays at `i32::MIN`, which is still far outside any
            // image, so saturation cannot pull an off-screen box into view.
            let translated = Rect {
                x: ann.rect.x.saturating_sub(origin.x),
                y: ann.rect.y.saturating_sub(origin.y),
                width: ann.rect.width,
                height: ann.rect.height,
            };
            let physical = PxRect::from_rect(translated.to_physical(scale));
            if physical.overlaps(bounds) {
                visible.push((i, ann, physical));
            } else {
                skipped.push(i);
            }
        }

        // Largest first, so a small element's box and badge land on top of the
        // window or group that contains it. Ties keep input order.
        visible.sort_by(|(ai, _, ar), (bi, _, br)| br.area().cmp(&ar.area()).then(ai.cmp(bi)));

        let mut placed: Vec<PxRect> = Vec::new();
        for (_, ann, rect) in visible {
            draw_box(&mut canvas, rect, unit, ann.color);
            if let Some(badge) = BadgeMetrics::for_tag(&ann.tag, glyph_unit, unit) {
                let spot = badge_spot(rect, badge.width, badge.height, unit, bounds, &placed);
                let fg = foreground_for(ann.color);
                // Outline first, then the fill inset into it: two rectangles
                // rather than four bands, and `fill` clips both.
                canvas.fill(spot, fg);
                canvas.fill(badge.fill_area(spot), ann.color);
                draw_tag(
                    &mut canvas,
                    &ann.tag,
                    spot.x0.saturating_add(badge.inset),
                    spot.y0.saturating_add(badge.inset),
                    badge.unit,
                    fg,
                );
                placed.push(spot);
            }
        }

        Ok((
            Screenshot::new(self.width, self.height, canvas.pixels, self.scale),
            skipped,
        ))
    }
}

// ── Geometry ─────────────────────────────────────────────────────────────

/// A half-open rectangle in physical pixels, widened to `i64`.
///
/// Every coordinate in this module lives here rather than in [`Rect`]: `i32`
/// positions plus `u32` sizes plus a scale factor overflow `i32` easily, and
/// `i64` holds any product of them without a checked operation per line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PxRect {
    x0: i64,
    y0: i64,
    x1: i64,
    y1: i64,
}

impl PxRect {
    fn from_rect(r: Rect) -> Self {
        let x0 = i64::from(r.x);
        let y0 = i64::from(r.y);
        // i32 + u32 both widened: the sums cannot overflow i64.
        Self {
            x0,
            y0,
            x1: x0 + i64::from(r.width),
            y1: y0 + i64::from(r.height),
        }
    }

    fn at(x0: i64, y0: i64, width: i64, height: i64) -> Self {
        Self {
            x0,
            y0,
            x1: x0.saturating_add(width),
            y1: y0.saturating_add(height),
        }
    }

    fn is_empty(self) -> bool {
        self.x1 <= self.x0 || self.y1 <= self.y0
    }

    fn area(self) -> i64 {
        if self.is_empty() {
            0
        } else {
            (self.x1 - self.x0).saturating_mul(self.y1 - self.y0)
        }
    }

    /// The part of `self` inside `clip`, empty when they do not meet.
    fn clipped_to(self, clip: Self) -> Self {
        Self {
            x0: self.x0.max(clip.x0),
            y0: self.y0.max(clip.y0),
            x1: self.x1.min(clip.x1),
            y1: self.y1.min(clip.y1),
        }
    }

    /// True when every pixel of `self` is inside `other`. An empty rectangle
    /// has no pixels outside anything, so it is contained.
    fn contained_by(self, other: Self) -> bool {
        self.is_empty()
            || (self.x0 >= other.x0
                && self.y0 >= other.y0
                && self.x1 <= other.x1
                && self.y1 <= other.y1)
    }

    /// True when the two rectangles share at least one pixel. An empty
    /// rectangle overlaps nothing, which is what makes a zero-area annotation
    /// skipped rather than drawn.
    fn overlaps(self, other: Self) -> bool {
        !self.is_empty()
            && !other.is_empty()
            && self.x0 < other.x1
            && other.x0 < self.x1
            && self.y0 < other.y1
            && other.y0 < self.y1
    }
}

// ── Canvas ───────────────────────────────────────────────────────────────

/// The RGBA8 buffer being drawn into, plus its dimensions as `i64`.
struct Canvas {
    width: i64,
    height: i64,
    pixels: Vec<u8>,
}

impl Canvas {
    fn bounds(&self) -> PxRect {
        PxRect {
            x0: 0,
            y0: 0,
            x1: self.width,
            y1: self.height,
        }
    }

    /// Write one opaque pixel. Out-of-range coordinates, an index that does
    /// not fit `usize`, and a buffer shorter than the index all return without
    /// writing — this is the one place bytes are stored, so it is the one
    /// place that has to be right.
    fn set_px(&mut self, x: i64, y: i64, rgb: [u8; 3]) {
        if x < 0 || y < 0 || x >= self.width || y >= self.height {
            return;
        }
        let Some(index) = y
            .checked_mul(self.width)
            .and_then(|row| row.checked_add(x))
            .and_then(|offset| offset.checked_mul(4))
        else {
            return;
        };
        let Ok(index) = usize::try_from(index) else {
            return;
        };
        let Some(end) = index.checked_add(4) else {
            return;
        };
        if end > self.pixels.len() {
            return;
        }
        self.pixels[index..end].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]);
    }

    /// Fill `rect`, clipped to the image. A rect entirely outside costs one
    /// comparison, so a caller may pass wildly out-of-range geometry.
    fn fill(&mut self, rect: PxRect, rgb: [u8; 3]) {
        let x0 = rect.x0.max(0);
        let y0 = rect.y0.max(0);
        let x1 = rect.x1.min(self.width);
        let y1 = rect.y1.min(self.height);
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        for y in y0..y1 {
            for x in x0..x1 {
                self.set_px(x, y, rgb);
            }
        }
    }
}

// ── Boxes and badges ─────────────────────────────────────────────────────

/// Draw a `stroke`-px outline *inside* `rect`. On a box thinner than the
/// stroke the bands collapse onto each other and the box is drawn solid,
/// which is the honest rendering of a 2px-wide element at 4× stroke.
fn draw_box(canvas: &mut Canvas, rect: PxRect, stroke: i64, rgb: [u8; 3]) {
    if rect.is_empty() {
        return;
    }
    let sx = stroke.min(rect.x1 - rect.x0);
    let sy = stroke.min(rect.y1 - rect.y0);

    canvas.fill(PxRect::at(rect.x0, rect.y0, rect.x1 - rect.x0, sy), rgb);
    canvas.fill(
        PxRect::at(rect.x0, rect.y1 - sy, rect.x1 - rect.x0, sy),
        rgb,
    );
    canvas.fill(PxRect::at(rect.x0, rect.y0, sx, rect.y1 - rect.y0), rgb);
    canvas.fill(
        PxRect::at(rect.x1 - sx, rect.y0, sx, rect.y1 - rect.y0),
        rgb,
    );
}

/// The size of one tag badge and where its glyphs sit inside it.
///
/// A badge is an `outline`-px border in the tag's foreground colour, then
/// `unit` px of padding, then the glyphs. The border is what separates a badge
/// from whatever UI it lands on: the fill alone is one flat colour that a
/// screenshot of a colourful toolbar can swallow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct BadgeMetrics {
    width: i64,
    height: i64,
    /// Glyph pixel size.
    unit: i64,
    /// Border thickness, drawn in the foreground colour.
    outline: i64,
    /// `outline + padding`: the glyph origin, relative to the badge's
    /// top-left.
    inset: i64,
}

impl BadgeMetrics {
    /// Metrics for `tag`, or `None` when the tag has no drawable glyph — an
    /// empty tag gets a box and no badge rather than an empty coloured square.
    fn for_tag(tag: &str, unit: i64, outline: i64) -> Option<Self> {
        // Saturating rather than fallible: a tag longer than `i64::MAX` glyphs
        // is a width the badge clips to the image anyway, so there is no
        // failure to report — only a number too large to represent.
        let glyphs = i64::try_from(tag.chars().filter_map(glyph_index).count()).unwrap_or(i64::MAX);
        if glyphs == 0 {
            return None;
        }
        // Glyphs, one `unit` of tracking between them, one `unit` of padding
        // and `outline` px of border on every side. Saturating because
        // `glyphs` is caller-controlled; `unit` is 2..=8 and `outline` 1..=4,
        // so every other product here is small and exact.
        let text_w = glyphs
            .saturating_mul(GLYPH_W * unit)
            .saturating_add((glyphs - 1).saturating_mul(unit));
        let inset = unit + outline;
        Some(Self {
            width: text_w.saturating_add(2 * inset),
            height: GLYPH_H * unit + 2 * inset,
            unit,
            outline,
            inset,
        })
    }

    /// The coloured fill inside the outline, for a badge placed at `spot`.
    fn fill_area(self, spot: PxRect) -> PxRect {
        PxRect {
            x0: spot.x0.saturating_add(self.outline),
            y0: spot.y0.saturating_add(self.outline),
            x1: spot.x1.saturating_sub(self.outline),
            y1: spot.y1.saturating_sub(self.outline),
        }
    }
}

/// Pick where a badge goes, preferring **outside** the box so it never covers
/// the element it points at.
///
/// The badge used to sit at the box's inner top-left, which on a toolbar
/// button put `A1` squarely on top of the button's own label — the annotation
/// destroying the content it exists to point at. Candidates are now tried in
/// this order:
///
/// 1. above the box, left-aligned (bottom edge touching the box's top edge),
/// 2. above the box, right-aligned,
/// 3. below the box, left-aligned, then right-aligned,
/// 4. beside the box, to its left, then to its right,
/// 5. the four inner corners, as a last resort.
///
/// Each candidate is scored `(is visible at all, covers no placed badge, is
/// wholly on-image, visible area)`, compared in that order, and the first
/// candidate holding the best score wins. So an off-image preferred position
/// yields to the next one that fits, and a box filling the capture — which has
/// no outside position on the image at all — falls through to the inner
/// corners. A box that extends past *every* edge has no on-image candidate at
/// all, and is clamped by [`clamped_spot`] so a badge still lands somewhere
/// visible rather than nowhere.
///
/// Collision avoidance is why the *placed* badges are consulted: nested
/// elements (window ⊃ group ⊃ button) share corners, and without it every
/// badge in a stack but the last would be unreadable.
fn badge_spot(
    rect: PxRect,
    width: i64,
    height: i64,
    stroke: i64,
    image: PxRect,
    placed: &[PxRect],
) -> PxRect {
    let outer_left = rect.x0;
    let outer_right = rect.x1.saturating_sub(width);
    let above = rect.y0.saturating_sub(height);
    let below = rect.y1;
    let inner_left = rect.x0.saturating_add(stroke);
    let inner_top = rect.y0.saturating_add(stroke);
    let inner_right = rect.x1.saturating_sub(stroke).saturating_sub(width);
    let inner_bottom = rect.y1.saturating_sub(stroke).saturating_sub(height);

    let candidates = [
        PxRect::at(outer_left, above, width, height),
        PxRect::at(outer_right, above, width, height),
        PxRect::at(outer_left, below, width, height),
        PxRect::at(outer_right, below, width, height),
        PxRect::at(rect.x0.saturating_sub(width), rect.y0, width, height),
        PxRect::at(rect.x1, rect.y0, width, height),
        PxRect::at(inner_left, inner_top, width, height),
        PxRect::at(inner_right, inner_top, width, height),
        PxRect::at(inner_left, inner_bottom, width, height),
        PxRect::at(inner_right, inner_bottom, width, height),
    ];

    let mut best: Option<((bool, bool, bool, i64), PxRect)> = None;
    for candidate in candidates {
        let visible = candidate.clipped_to(image).area();
        let free = !placed.iter().any(|p| p.overlaps(candidate));
        let key = (visible > 0, free, candidate.contained_by(image), visible);
        // Strictly greater, so an earlier candidate keeps a tied score and the
        // preference order above decides.
        if best.is_none_or(|(best_key, _)| key > best_key) {
            best = Some((key, candidate));
        }
    }

    match best {
        // At least one candidate is on-image: the preference order decided.
        Some((key, spot)) if key.0 => spot,
        // None of the ten is on-image. That happens whenever the box extends
        // past *every* edge by more than a badge — a `window` group on a
        // cropped capture, or any maximised element. Every candidate then
        // scores `(false, true, false, 0)`, the strict `>` keeps the first,
        // and the badge is drawn entirely outside the buffer: zero pixels
        // written, but the caller still gets a legend entry and no omission.
        // That is exactly the "legend disagreeing with the picture with no way
        // to find out why" that `Omission` exists to prevent, so clamp into
        // the visible part of the box instead of placing nothing.
        _ => clamped_spot(rect, width, height, stroke, image),
    }
}

/// A badge position inside the on-image part of `rect`, for a box that has no
/// on-image candidate position of its own.
///
/// The box is known to intersect the image (non-overlapping boxes are dropped
/// before placement), so the clip is non-empty and the inset start is pulled
/// back far enough to keep the badge on-image even when the visible sliver is
/// narrower than the badge.
fn clamped_spot(rect: PxRect, width: i64, height: i64, stroke: i64, image: PxRect) -> PxRect {
    let visible = rect.clipped_to(image);
    let start_x = visible.x0.saturating_add(stroke);
    let start_y = visible.y0.saturating_add(stroke);
    // `image.x1 - width` can precede `image.x0` on an image narrower than a
    // badge; `max` then wins and the badge is clipped by `draw_badge` as usual.
    let x = start_x.min(image.x1.saturating_sub(width)).max(image.x0);
    let y = start_y.min(image.y1.saturating_sub(height)).max(image.y0);
    PxRect::at(x, y, width, height)
}

// ── Contrast ─────────────────────────────────────────────────────────────

const BLACK: [u8; 3] = [0, 0, 0];
const WHITE: [u8; 3] = [255, 255, 255];

/// WCAG relative luminance: sRGB channels linearised, then weighted
/// `0.2126 R + 0.7152 G + 0.0722 B`.
fn relative_luminance(rgb: [u8; 3]) -> f64 {
    fn linear(channel: u8) -> f64 {
        let c = f64::from(channel) / 255.0;
        if c <= 0.03928 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    }
    0.2126 * linear(rgb[0]) + 0.7152 * linear(rgb[1]) + 0.0722 * linear(rgb[2])
}

/// WCAG contrast ratio `(L1 + 0.05) / (L2 + 0.05)`, lighter over darker.
fn contrast_ratio(a: [u8; 3], b: [u8; 3]) -> f64 {
    let (la, lb) = (relative_luminance(a), relative_luminance(b));
    let (lighter, darker) = if la >= lb { (la, lb) } else { (lb, la) };
    (lighter + 0.05) / (darker + 0.05)
}

/// Black or white, whichever reads better on `background`.
fn foreground_for(background: [u8; 3]) -> [u8; 3] {
    if contrast_ratio(BLACK, background) >= contrast_ratio(WHITE, background) {
        BLACK
    } else {
        WHITE
    }
}

// ── Text ─────────────────────────────────────────────────────────────────

/// Glyph width in font pixels.
const GLYPH_W: i64 = 5;
/// Glyph height in font pixels.
const GLYPH_H: i64 = 7;

/// Index into [`FONT`] for a character, or `None` when the font has no glyph.
///
/// `0-9` map to `0..10` and `A-Z` to `10..36`; lowercase ASCII is uppercased
/// first. Tags come from [`tag_for`], which only ever produces those.
fn glyph_index(c: char) -> Option<usize> {
    let c = c.to_ascii_uppercase();
    match c {
        '0'..='9' => Some(c as usize - '0' as usize),
        'A'..='Z' => Some(10 + c as usize - 'A' as usize),
        _ => None,
    }
}

/// Draw `tag` with its top-left at (`x`, `y`), each font pixel an
/// `unit`×`unit` square.
fn draw_tag(canvas: &mut Canvas, tag: &str, x: i64, y: i64, unit: i64, rgb: [u8; 3]) {
    let advance = GLYPH_W * unit + unit;
    let mut pen = x;
    for glyph in tag.chars().filter_map(glyph_index) {
        if pen >= canvas.width {
            // Glyphs only advance rightwards, so nothing after this is visible.
            break;
        }
        draw_glyph(canvas, glyph, pen, y, unit, rgb);
        pen = pen.saturating_add(advance);
    }
}

fn draw_glyph(canvas: &mut Canvas, glyph: usize, x: i64, y: i64, unit: i64, rgb: [u8; 3]) {
    let Some(rows) = FONT.get(glyph) else {
        return;
    };
    for (row, bits) in rows.iter().enumerate() {
        for col in 0..GLYPH_W {
            // Bit `GLYPH_W - 1` is the leftmost column.
            if *bits & (1_u8 << (GLYPH_W - 1 - col)) == 0 {
                continue;
            }
            let px = x.saturating_add(col * unit);
            let py = y.saturating_add(row as i64 * unit);
            canvas.fill(PxRect::at(px, py, unit, unit), rgb);
        }
    }
}

/// A 5×7 bitmap font: `0-9` then `A-Z`, one `u8` per row with bit 4 the
/// leftmost column. Indexed by [`glyph_index`].
///
/// Deliberately the whole typographic story of this module. Rendering two
/// character classes does not justify a TrueType rasteriser and an embedded
/// font file in every binary and both wheels.
#[rustfmt::skip]
const FONT: [[u8; 7]; 36] = [
    // '0'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10011, // #..##
        0b10101, // #.#.#
        0b11001, // ##..#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // '1'
    [
        0b00100, // ..#..
        0b01100, // .##..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b01110, // .###.
    ],
    // '2'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b00001, // ....#
        0b00010, // ...#.
        0b00100, // ..#..
        0b01000, // .#...
        0b11111, // #####
    ],
    // '3'
    [
        0b11111, // #####
        0b00010, // ...#.
        0b00100, // ..#..
        0b00010, // ...#.
        0b00001, // ....#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // '4'
    [
        0b00010, // ...#.
        0b00110, // ..##.
        0b01010, // .#.#.
        0b10010, // #..#.
        0b11111, // #####
        0b00010, // ...#.
        0b00010, // ...#.
    ],
    // '5'
    [
        0b11111, // #####
        0b10000, // #....
        0b11110, // ####.
        0b00001, // ....#
        0b00001, // ....#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // '6'
    [
        0b00110, // ..##.
        0b01000, // .#...
        0b10000, // #....
        0b11110, // ####.
        0b10001, // #...#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // '7'
    [
        0b11111, // #####
        0b00001, // ....#
        0b00010, // ...#.
        0b00100, // ..#..
        0b01000, // .#...
        0b01000, // .#...
        0b01000, // .#...
    ],
    // '8'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // '9'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b01111, // .####
        0b00001, // ....#
        0b00010, // ...#.
        0b01100, // .##..
    ],
    // 'A'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b11111, // #####
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
    ],
    // 'B'
    [
        0b11110, // ####.
        0b10001, // #...#
        0b10001, // #...#
        0b11110, // ####.
        0b10001, // #...#
        0b10001, // #...#
        0b11110, // ####.
    ],
    // 'C'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
        0b10001, // #...#
        0b01110, // .###.
    ],
    // 'D'
    [
        0b11100, // ###..
        0b10010, // #..#.
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10010, // #..#.
        0b11100, // ###..
    ],
    // 'E'
    [
        0b11111, // #####
        0b10000, // #....
        0b10000, // #....
        0b11110, // ####.
        0b10000, // #....
        0b10000, // #....
        0b11111, // #####
    ],
    // 'F'
    [
        0b11111, // #####
        0b10000, // #....
        0b10000, // #....
        0b11110, // ####.
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
    ],
    // 'G'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10000, // #....
        0b10111, // #.###
        0b10001, // #...#
        0b10001, // #...#
        0b01111, // .####
    ],
    // 'H'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b11111, // #####
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
    ],
    // 'I'
    [
        0b01110, // .###.
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b01110, // .###.
    ],
    // 'J'
    [
        0b00111, // ..###
        0b00010, // ...#.
        0b00010, // ...#.
        0b00010, // ...#.
        0b00010, // ...#.
        0b10010, // #..#.
        0b01100, // .##..
    ],
    // 'K'
    [
        0b10001, // #...#
        0b10010, // #..#.
        0b10100, // #.#..
        0b11000, // ##...
        0b10100, // #.#..
        0b10010, // #..#.
        0b10001, // #...#
    ],
    // 'L'
    [
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
        0b11111, // #####
    ],
    // 'M'
    [
        0b10001, // #...#
        0b11011, // ##.##
        0b10101, // #.#.#
        0b10101, // #.#.#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
    ],
    // 'N'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b11001, // ##..#
        0b10101, // #.#.#
        0b10011, // #..##
        0b10001, // #...#
        0b10001, // #...#
    ],
    // 'O'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // 'P'
    [
        0b11110, // ####.
        0b10001, // #...#
        0b10001, // #...#
        0b11110, // ####.
        0b10000, // #....
        0b10000, // #....
        0b10000, // #....
    ],
    // 'Q'
    [
        0b01110, // .###.
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10101, // #.#.#
        0b10010, // #..#.
        0b01101, // .##.#
    ],
    // 'R'
    [
        0b11110, // ####.
        0b10001, // #...#
        0b10001, // #...#
        0b11110, // ####.
        0b10100, // #.#..
        0b10010, // #..#.
        0b10001, // #...#
    ],
    // 'S'
    [
        0b01111, // .####
        0b10000, // #....
        0b10000, // #....
        0b01110, // .###.
        0b00001, // ....#
        0b00001, // ....#
        0b11110, // ####.
    ],
    // 'T'
    [
        0b11111, // #####
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
    ],
    // 'U'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b01110, // .###.
    ],
    // 'V'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b01010, // .#.#.
        0b00100, // ..#..
    ],
    // 'W'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b10001, // #...#
        0b10101, // #.#.#
        0b10101, // #.#.#
        0b11011, // ##.##
        0b10001, // #...#
    ],
    // 'X'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b01010, // .#.#.
        0b00100, // ..#..
        0b01010, // .#.#.
        0b10001, // #...#
        0b10001, // #...#
    ],
    // 'Y'
    [
        0b10001, // #...#
        0b10001, // #...#
        0b01010, // .#.#.
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
        0b00100, // ..#..
    ],
    // 'Z'
    [
        0b11111, // #####
        0b00001, // ....#
        0b00010, // ...#.
        0b00100, // ..#..
        0b01000, // .#...
        0b10000, // #....
        0b11111, // #####
    ],
];

// ── Tests ────────────────────────────────────────────────────────────────

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

    const BG: [u8; 4] = [0, 0, 0, 0];
    const RED: [u8; 3] = [255, 0, 0];
    const BLUE: [u8; 3] = [0, 0, 255];

    /// A fully transparent capture, so any written pixel is visible as a
    /// change from `BG`.
    fn blank(width: u32, height: u32, scale: f32) -> Screenshot {
        let len = (width as usize) * (height as usize) * 4;
        Screenshot::new(width, height, vec![0; len], scale)
    }

    fn px(shot: &Screenshot, x: u32, y: u32) -> [u8; 4] {
        let i = ((y as usize) * (shot.width as usize) + x as usize) * 4;
        [
            shot.pixels[i],
            shot.pixels[i + 1],
            shot.pixels[i + 2],
            shot.pixels[i + 3],
        ]
    }

    fn opaque(rgb: [u8; 3]) -> [u8; 4] {
        [rgb[0], rgb[1], rgb[2], 255]
    }

    fn rect(x: i32, y: i32, width: u32, height: u32) -> Rect {
        Rect {
            x,
            y,
            width,
            height,
        }
    }

    /// An annotation with no tag draws a box and no badge, which is what lets
    /// the stroke tests assert on an otherwise untouched interior.
    fn boxed(r: Rect, color: [u8; 3]) -> Annotation {
        Annotation::new(r, "").color(color)
    }

    fn annotate(shot: &Screenshot, anns: &[Annotation]) -> (Screenshot, Vec<usize>) {
        shot.annotate(anns, Point::new(0, 0))
            .expect("annotate on a well-formed capture")
    }

    // ── Annotation / palette / tag_for ───────────────────────────────────

    #[test]
    fn new_takes_the_first_palette_colour_and_color_overrides_it() {
        let a = Annotation::new(rect(1, 2, 3, 4), "A1");
        assert_eq!(a.color, ANNOTATION_PALETTE[0]);
        assert_eq!(a.tag, "A1");
        assert_eq!(a.rect, rect(1, 2, 3, 4));

        let b = a.color(RED);
        assert_eq!(b.color, RED);
    }

    #[test]
    fn tag_for_letters_the_group_and_numbers_the_index() {
        assert_eq!(tag_for(1, 1), "A1");
        assert_eq!(tag_for(2, 7), "B7");
        assert_eq!(tag_for(1, 12), "A12");
        assert_eq!(tag_for(3, 999), "C999");
    }

    #[test]
    fn tag_for_group_boundaries_roll_over_like_spreadsheet_columns() {
        assert_eq!(tag_for(1, 1), "A1");
        assert_eq!(tag_for(26, 1), "Z1");
        assert_eq!(tag_for(27, 1), "AA1");
        assert_eq!(tag_for(28, 1), "AB1");
        assert_eq!(tag_for(52, 1), "AZ1");
        assert_eq!(tag_for(53, 1), "BA1");
        assert_eq!(tag_for(702, 1), "ZZ1");
        assert_eq!(tag_for(703, 1), "AAA1");
    }

    #[test]
    fn tag_for_reads_zero_as_one_since_every_index_is_one_based() {
        assert_eq!(tag_for(0, 0), "A1");
        assert_eq!(tag_for(0, 5), "A5");
        assert_eq!(tag_for(2, 0), "B1");
    }

    #[test]
    fn tag_for_never_produces_a_separator_that_could_be_lost() {
        // The property the format exists for: no two (group, index) pairs
        // render to the same glyph sequence.
        let mut seen = std::collections::HashSet::new();
        for group in 1..=30_usize {
            for index in 1..=30_usize {
                assert!(
                    seen.insert(tag_for(group, index)),
                    "collision at group {group}, index {index}"
                );
            }
        }
    }

    #[test]
    fn every_palette_colour_clears_wcag_aa_against_its_foreground() {
        for (i, &color) in ANNOTATION_PALETTE.iter().enumerate() {
            let fg = foreground_for(color);
            let ratio = contrast_ratio(fg, color);
            assert!(
                ratio >= 4.5,
                "ANNOTATION_PALETTE[{i}] {color:?} against {fg:?} is {ratio:.2}:1, below 4.5:1"
            );
        }
    }

    #[test]
    fn foreground_picks_black_on_light_and_white_on_dark() {
        assert_eq!(foreground_for([0xF0, 0xE4, 0x42]), BLACK); // yellow
        assert_eq!(foreground_for([0x00, 0x72, 0xB2]), WHITE); // blue
    }

    #[test]
    fn relative_luminance_matches_the_wcag_endpoints() {
        assert!((relative_luminance(WHITE) - 1.0).abs() < 1e-9);
        assert!(relative_luminance(BLACK).abs() < 1e-9);
        // Pure blue: 0.0722 × 1.0, the B coefficient exactly.
        assert!((relative_luminance(BLUE) - 0.0722).abs() < 1e-9);
        assert!((contrast_ratio(WHITE, BLACK) - 21.0).abs() < 1e-9);
    }

    // ── Stroke geometry ──────────────────────────────────────────────────

    #[test]
    fn stroke_lands_on_the_box_edges_and_nowhere_else() {
        let shot = blank(16, 16, 1.0);
        // Physical box spans x 2..8, y 3..8 at scale 1.
        let (out, skipped) = annotate(&shot, &[boxed(rect(2, 3, 6, 5), RED)]);
        assert!(skipped.is_empty());

        for x in 2..8 {
            assert_eq!(px(&out, x, 3), opaque(RED), "top edge at x={x}");
            assert_eq!(px(&out, x, 7), opaque(RED), "bottom edge at x={x}");
        }
        for y in 3..8 {
            assert_eq!(px(&out, 2, y), opaque(RED), "left edge at y={y}");
            assert_eq!(px(&out, 7, y), opaque(RED), "right edge at y={y}");
        }
        for y in 4..7 {
            for x in 3..7 {
                assert_eq!(px(&out, x, y), BG, "interior at ({x}, {y})");
            }
        }
        assert_eq!(px(&out, 1, 3), BG, "one left of the box");
        assert_eq!(px(&out, 8, 3), BG, "one right of the box");
        assert_eq!(px(&out, 2, 2), BG, "one above the box");
        assert_eq!(px(&out, 2, 8), BG, "one below the box");
    }

    #[test]
    fn origin_translates_the_rect_into_capture_space() {
        let shot = blank(16, 16, 1.0);
        // Same box as above, expressed in screen coordinates for a capture
        // whose top-left is (10, 10).
        let (out, skipped) = shot
            .annotate(&[boxed(rect(12, 13, 6, 5), RED)], Point::new(10, 10))
            .expect("annotate");
        assert!(skipped.is_empty());

        assert_eq!(px(&out, 2, 3), opaque(RED), "translated top-left corner");
        assert_eq!(
            px(&out, 7, 7),
            opaque(RED),
            "translated bottom-right corner"
        );
        assert_eq!(px(&out, 12, 13), BG, "untranslated position must be clean");
    }

    #[test]
    fn scale_converts_logical_coordinates_and_thickens_the_stroke() {
        let shot = blank(16, 16, 2.0);
        // Logical (1, 1, 4, 4) → physical (2, 2, 8, 8); stroke = round(2) = 2.
        let (out, skipped) = annotate(&shot, &[boxed(rect(1, 1, 4, 4), RED)]);
        assert!(skipped.is_empty());

        for x in 2..10 {
            assert_eq!(px(&out, x, 2), opaque(RED), "outer top row at x={x}");
            assert_eq!(px(&out, x, 3), opaque(RED), "inner top row at x={x}");
            assert_eq!(px(&out, x, 8), opaque(RED), "inner bottom row at x={x}");
            assert_eq!(px(&out, x, 9), opaque(RED), "outer bottom row at x={x}");
        }
        for y in 2..10 {
            assert_eq!(px(&out, 2, y), opaque(RED), "outer left col at y={y}");
            assert_eq!(px(&out, 3, y), opaque(RED), "inner left col at y={y}");
            assert_eq!(px(&out, 8, y), opaque(RED), "inner right col at y={y}");
            assert_eq!(px(&out, 9, y), opaque(RED), "outer right col at y={y}");
        }
        for y in 4..8 {
            for x in 4..8 {
                assert_eq!(px(&out, x, y), BG, "interior at ({x}, {y})");
            }
        }
        assert_eq!(px(&out, 1, 2), BG, "one left of the scaled box");
        assert_eq!(px(&out, 10, 2), BG, "one right of the scaled box");
    }

    // ── Clipping ─────────────────────────────────────────────────────────

    #[test]
    fn a_box_straddling_the_left_edge_is_clipped_not_moved() {
        let shot = blank(8, 8, 1.0);
        // x -3..3: the left stroke is off-image, the right stroke is at x=2.
        let (out, skipped) = annotate(&shot, &[boxed(rect(-3, 2, 6, 4), RED)]);
        assert!(skipped.is_empty(), "partly visible must not be skipped");

        assert_eq!(px(&out, 0, 2), opaque(RED), "top edge survives clipping");
        assert_eq!(px(&out, 2, 2), opaque(RED), "right stroke stays at x=2");
        assert_eq!(px(&out, 3, 2), BG, "nothing drawn past the box");
        assert_eq!(px(&out, 0, 3), BG, "no left stroke pulled to the edge");
    }

    #[test]
    fn a_box_straddling_the_right_edge_is_clipped_not_moved() {
        let shot = blank(8, 8, 1.0);
        // x 5..11: the left stroke is at x=5, the right stroke is off-image.
        let (out, skipped) = annotate(&shot, &[boxed(rect(5, 2, 6, 4), RED)]);
        assert!(skipped.is_empty());

        assert_eq!(px(&out, 5, 2), opaque(RED), "top edge survives clipping");
        assert_eq!(
            px(&out, 7, 2),
            opaque(RED),
            "top edge reaches the last column"
        );
        assert_eq!(px(&out, 7, 3), BG, "no right stroke pulled to the edge");
        assert_eq!(px(&out, 4, 2), BG, "nothing drawn left of the box");
    }

    #[test]
    fn a_box_straddling_the_top_edge_is_clipped_not_moved() {
        let shot = blank(8, 8, 1.0);
        // y -3..3: the top stroke is off-image, the bottom stroke is at y=2.
        let (out, skipped) = annotate(&shot, &[boxed(rect(2, -3, 4, 6), RED)]);
        assert!(skipped.is_empty());

        assert_eq!(px(&out, 2, 0), opaque(RED), "left edge survives clipping");
        assert_eq!(px(&out, 2, 2), opaque(RED), "bottom stroke stays at y=2");
        assert_eq!(px(&out, 3, 0), BG, "no top stroke pulled to the edge");
        assert_eq!(px(&out, 2, 3), BG, "nothing drawn below the box");
    }

    #[test]
    fn a_box_straddling_the_bottom_edge_is_clipped_not_moved() {
        let shot = blank(8, 8, 1.0);
        // y 5..11: the top stroke is at y=5, the bottom stroke is off-image.
        let (out, skipped) = annotate(&shot, &[boxed(rect(2, 5, 4, 6), RED)]);
        assert!(skipped.is_empty());

        assert_eq!(px(&out, 2, 5), opaque(RED), "top stroke stays at y=5");
        assert_eq!(
            px(&out, 2, 7),
            opaque(RED),
            "left edge reaches the last row"
        );
        assert_eq!(px(&out, 3, 7), BG, "no bottom stroke pulled to the edge");
        assert_eq!(px(&out, 2, 4), BG, "nothing drawn above the box");
    }

    // ── Skipping ─────────────────────────────────────────────────────────

    #[test]
    fn rects_outside_the_image_are_reported_not_clamped() {
        let shot = blank(8, 8, 1.0);
        let anns = [
            boxed(rect(100, 0, 4, 4), RED), // 0: right of the image
            boxed(rect(0, 0, 4, 4), RED),   // 1: visible
            boxed(rect(-50, 0, 4, 4), RED), // 2: left of the image
            boxed(rect(0, -50, 4, 4), RED), // 3: above the image
            boxed(rect(0, 200, 4, 4), RED), // 4: below the image
            boxed(rect(8, 8, 4, 4), RED),   // 5: one pixel past the corner
        ];
        let (out, skipped) = annotate(&shot, &anns);

        assert_eq!(skipped, vec![0, 2, 3, 4, 5]);
        assert_eq!(
            px(&out, 0, 0),
            opaque(RED),
            "the visible one is still drawn"
        );
        // Nothing was clamped onto an edge it does not belong to.
        assert_eq!(px(&out, 7, 7), BG);
        assert_eq!(px(&out, 7, 0), BG);
    }

    #[test]
    fn zero_area_rects_are_skipped() {
        let shot = blank(8, 8, 1.0);
        let anns = [
            boxed(rect(2, 2, 0, 4), RED),
            boxed(rect(2, 2, 4, 0), RED),
            boxed(rect(2, 2, 0, 0), RED),
        ];
        let (out, skipped) = annotate(&shot, &anns);

        assert_eq!(skipped, vec![0, 1, 2]);
        assert_eq!(out.pixels, shot.pixels, "nothing drawn at all");
    }

    // ── Badges and glyphs ────────────────────────────────────────────────

    #[test]
    fn a_tag_glyph_renders_in_the_contrasting_foreground() {
        let shot = blank(40, 20, 1.0);
        // Blue box: white is the higher-contrast foreground. The box fills the
        // capture, so no outside position is on-image and the badge falls back
        // to the box's inner top-left.
        let (out, skipped) = annotate(
            &shot,
            &[Annotation::new(rect(0, 0, 40, 20), "A").color(BLUE)],
        );
        assert!(skipped.is_empty());

        // Badge: 1px stroke, so its top-left is (1, 1); a 1px outline plus 2px
        // of padding puts the glyph's top-left at (4, 4), each font pixel a
        // 2×2 square. 'A' is:
        //   .###.  #...#  #...#  #####  #...#  #...#  #...#
        assert_eq!(
            px(&out, 1, 1),
            opaque(WHITE),
            "badge outline is the foreground colour"
        );
        assert_eq!(
            px(&out, 2, 2),
            opaque(BLUE),
            "inside the outline, the badge is the box colour"
        );
        for x in 6..12 {
            assert_eq!(px(&out, x, 4), opaque(WHITE), "top bar of 'A' at x={x}");
            assert_eq!(px(&out, x, 5), opaque(WHITE), "top bar, second row, x={x}");
        }
        assert_eq!(px(&out, 5, 4), opaque(BLUE), "left of the top bar is unset");
        assert_eq!(
            px(&out, 12, 4),
            opaque(BLUE),
            "right of the top bar is unset"
        );
        for x in 4..14 {
            assert_eq!(px(&out, x, 10), opaque(WHITE), "crossbar of 'A' at x={x}");
        }
        assert_eq!(px(&out, 4, 6), opaque(WHITE), "left stem of 'A'");
        assert_eq!(px(&out, 12, 6), opaque(WHITE), "right stem of 'A'");
        assert_eq!(px(&out, 8, 6), opaque(BLUE), "counter of 'A' is not filled");
        assert_eq!(px(&out, 4, 16), opaque(WHITE), "last row, left stem");
        assert_eq!(
            px(&out, 16, 4),
            opaque(WHITE),
            "the badge's right outline column"
        );
        assert_eq!(
            px(&out, 17, 4),
            BG,
            "the badge is only as wide as one glyph"
        );
    }

    #[test]
    fn a_tag_with_no_drawable_glyph_gets_no_badge() {
        let shot = blank(20, 20, 1.0);
        let (with_tag, _) = annotate(
            &shot,
            &[Annotation::new(rect(0, 0, 20, 20), "!?-").color(RED)],
        );
        let (no_tag, _) = annotate(&shot, &[boxed(rect(0, 0, 20, 20), RED)]);
        assert_eq!(with_tag.pixels, no_tag.pixels);
    }

    #[test]
    fn a_colliding_badge_moves_to_another_corner() {
        let shot = blank(60, 40, 1.0);
        let outer = Annotation::new(rect(0, 0, 60, 40), "A1").color(BLUE);
        let inner = Annotation::new(rect(0, 0, 30, 20), "B1").color(RED);
        let (out, skipped) = annotate(&shot, &[outer, inner]);
        assert!(skipped.is_empty());

        // A two-glyph badge is 2×10 + 2 tracking + 2×(2 padding + 1 outline)
        // = 28 wide and 7×2 + 6 = 20 tall. The outer box fills the capture, so
        // it has no outside position on-image and lands at its inner top-left,
        // (1, 1)..(29, 21).
        assert_eq!(
            px(&out, 1, 1),
            opaque(WHITE),
            "outer badge's outline holds the corner"
        );
        assert_eq!(px(&out, 2, 2), opaque(BLUE), "outer badge's fill");
        assert_eq!(
            px(&out, 28, 1),
            opaque(WHITE),
            "outer badge's right outline column"
        );

        // The inner box has room below, but that would cover the outer badge,
        // so the inner badge takes the next free position: beside the box, to
        // its right, at (30, 0)..(58, 20).
        assert_eq!(
            px(&out, 30, 0),
            opaque(BLACK),
            "inner badge's outline, beside the box"
        );
        assert_eq!(px(&out, 31, 1), opaque(RED), "inner badge's fill");
        assert_eq!(
            px(&out, 57, 19),
            opaque(BLACK),
            "inner badge's far outline corner"
        );
        assert_eq!(
            px(&out, 29, 1),
            opaque(RED),
            "the inner box's own right stroke, not the badge"
        );
    }

    #[test]
    fn identical_rects_are_both_drawn_never_deduplicated() {
        let shot = blank(60, 40, 1.0);
        let first = Annotation::new(rect(0, 0, 60, 40), "A1").color(BLUE);
        let second = Annotation::new(rect(0, 0, 60, 40), "B1").color(RED);
        let (out, skipped) = annotate(&shot, &[first, second]);

        assert!(skipped.is_empty(), "a duplicate rect is not a skip");
        // Both boxes fill the capture, so both badges fall inside. Equal area:
        // input order breaks the tie, so A1 keeps the inner top-left and B1 is
        // nudged to the inner top-right, x = 60 - 1 - 28 = 31.
        assert_eq!(px(&out, 1, 1), opaque(WHITE), "first badge's outline");
        assert_eq!(px(&out, 2, 2), opaque(BLUE), "first badge's fill");
        assert_eq!(
            px(&out, 31, 1),
            opaque(BLACK),
            "second badge's outline, nudged"
        );
        assert_eq!(px(&out, 32, 2), opaque(RED), "second badge's fill");
    }

    // ── Badge placement ──────────────────────────────────────────────────

    #[test]
    fn a_badge_sits_outside_the_box_so_it_cannot_cover_the_element() {
        let shot = blank(60, 60, 1.0);
        // A small control with room on every side: the badge goes above it,
        // left-aligned, its bottom edge touching the box's top edge.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(10, 30, 20, 10), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (10, 10)..(38, 30).
        assert_eq!(px(&out, 10, 10), opaque(BLACK), "badge's top-left outline");
        assert_eq!(px(&out, 11, 11), opaque(color), "badge's fill");
        assert_eq!(
            px(&out, 20, 29),
            opaque(BLACK),
            "badge's bottom outline touches the box's top edge"
        );
        assert_eq!(px(&out, 20, 30), opaque(color), "the box's own top stroke");
        assert_eq!(px(&out, 39, 29), BG, "nothing right of the badge");

        // The point of the whole change: the element's own pixels are clean.
        for y in 31..39 {
            for x in 11..29 {
                assert_eq!(px(&out, x, y), BG, "box interior at ({x}, {y})");
            }
        }
    }

    #[test]
    fn a_badge_with_no_room_above_drops_below_the_box() {
        let shot = blank(60, 60, 1.0);
        // Flush against the top edge: both above-positions are off-image.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(10, 0, 20, 10), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (10, 10)..(38, 30), below the box.
        assert_eq!(px(&out, 10, 10), opaque(BLACK), "badge's top-left outline");
        assert_eq!(px(&out, 11, 11), opaque(color), "badge's fill");
        assert_eq!(px(&out, 11, 5), BG, "box interior is untouched");
    }

    #[test]
    fn a_badge_wider_than_the_room_to_its_right_is_right_aligned() {
        let shot = blank(60, 60, 1.0);
        // x 40..58: above-left would run to x = 68, off the right edge, so
        // above-right (aligned to the box's right edge) wins.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(40, 30, 18, 10), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (30, 10)..(58, 30).
        assert_eq!(px(&out, 30, 10), opaque(BLACK), "badge's top-left outline");
        assert_eq!(px(&out, 31, 11), opaque(color), "badge's fill");
        assert_eq!(
            px(&out, 57, 29),
            opaque(BLACK),
            "badge's far outline corner"
        );
        assert_eq!(px(&out, 58, 29), BG, "the badge stops at the box's right");
    }

    #[test]
    fn a_badge_with_no_room_above_or_below_goes_beside_the_box() {
        let shot = blank(40, 24, 1.0);
        // Full-height box at the left edge: nothing above, nothing below, and
        // nothing to the left, so the badge takes the position to its right.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(0, 0, 10, 24), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (10, 0)..(38, 20).
        assert_eq!(px(&out, 10, 0), opaque(BLACK), "badge's top-left outline");
        assert_eq!(px(&out, 11, 1), opaque(color), "badge's fill");
        assert_eq!(px(&out, 5, 5), BG, "box interior is untouched");
        assert_eq!(px(&out, 38, 1), BG, "nothing past the badge");
    }

    #[test]
    fn a_badge_falls_inside_the_box_only_when_nothing_outside_is_on_image() {
        let shot = blank(40, 30, 1.0);
        // The box fills the capture: every outside position is entirely
        // off-image, so the last-resort inner top-left is used.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(0, 0, 40, 30), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (1, 1)..(29, 21), inside the 1px box stroke.
        assert_eq!(px(&out, 1, 1), opaque(BLACK), "badge's top-left outline");
        assert_eq!(px(&out, 2, 2), opaque(color), "badge's fill");
        assert_eq!(px(&out, 29, 21), BG, "the badge ends inside the box");
    }

    #[test]
    fn a_box_in_the_image_corner_still_gets_a_readable_badge() {
        let shot = blank(60, 60, 1.0);
        // (0, 0) is the worst case for an outside badge: above and to the left
        // are both off-image, so it lands below the box.
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(0, 0, 10, 10), "A1")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // Badge 28×20 at (0, 10)..(28, 30); glyphs start at (3, 13).
        assert_eq!(px(&out, 0, 10), opaque(BLACK), "badge's top-left outline");
        // The 'A' is drawn, in full, on-image: top bar then crossbar.
        for x in 5..11 {
            assert_eq!(px(&out, x, 13), opaque(BLACK), "top bar of 'A' at x={x}");
        }
        assert_eq!(px(&out, 4, 13), opaque(color), "left of the top bar");
        for x in 3..13 {
            assert_eq!(px(&out, x, 19), opaque(BLACK), "crossbar of 'A' at x={x}");
        }
        assert_eq!(px(&out, 5, 5), BG, "box interior is untouched");
    }

    #[test]
    fn a_badge_that_falls_off_the_image_is_clipped_not_a_skip() {
        let shot = blank(20, 40, 1.0);
        // The badge is wider than the whole capture, so wherever it goes part
        // of it is off-image. That must not skip the annotation or move the box.
        let (out, skipped) = annotate(
            &shot,
            &[Annotation::new(rect(4, 0, 16, 8), "A1").color(RED)],
        );

        assert!(skipped.is_empty(), "a clipped badge is not a skipped box");
        assert_eq!(px(&out, 4, 0), opaque(RED), "the box's top-left stroke");
        assert_eq!(
            px(&out, 19, 7),
            opaque(RED),
            "the box's bottom-right stroke"
        );
        // Best visible position is below-right, at (-8, 8): the right part of
        // its outline row lands on-image.
        assert_eq!(px(&out, 0, 8), opaque(BLACK), "clipped badge's top row");
        assert_eq!(px(&out, 19, 8), opaque(BLACK), "…all the way across");
        assert_eq!(px(&out, 0, 9), opaque(RED), "and its fill below that");
    }

    #[test]
    fn badge_spot_prefers_sitting_on_top_of_the_box_top_edge() {
        let box_rect = PxRect::at(100, 100, 50, 20);
        let image = PxRect::at(0, 0, 1000, 1000);
        let spot = badge_spot(box_rect, 28, 20, 1, image, &[]);

        assert_eq!(spot.x0, box_rect.x0, "left-aligned with the box");
        assert_eq!(spot.y1, box_rect.y0, "bottom edge touches the box's top");
        assert!(!spot.overlaps(box_rect), "and covers none of the box");
    }

    #[test]
    fn a_tag_is_drawn_at_twice_the_stroke_unit_so_it_is_legible_at_1x() {
        let shot = blank(60, 60, 1.0);
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(10, 30, 20, 10), "A")]);
        assert!(skipped.is_empty());
        let color = ANNOTATION_PALETTE[0];

        // One glyph: badge 16×20 at (10, 10)..(26, 30), glyphs at (13, 13).
        // A 5×7 font at unit 2 is 10×14 physical pixels.
        assert_eq!(px(&out, 13, 19), opaque(BLACK), "crossbar, first row");
        assert_eq!(px(&out, 22, 20), opaque(BLACK), "crossbar, second row");
        assert_eq!(px(&out, 13, 25), opaque(BLACK), "last glyph row, left stem");
        assert_eq!(px(&out, 13, 26), opaque(BLACK), "…which is two pixels tall");
        assert_eq!(px(&out, 13, 27), opaque(color), "and ends after 14 rows");
    }

    #[test]
    fn smaller_boxes_draw_on_top_of_larger_ones() {
        let shot = blank(20, 20, 1.0);
        let big = boxed(rect(0, 0, 20, 20), BLUE);
        let small = boxed(rect(0, 0, 4, 4), RED);
        // Input order puts the small one first; area order must still win.
        let (out, _) = annotate(&shot, &[small, big]);

        assert_eq!(px(&out, 0, 0), opaque(RED), "the small box overwrites");
        assert_eq!(px(&out, 19, 19), opaque(BLUE), "the big box is still there");
    }

    // ── Purity and errors ────────────────────────────────────────────────

    #[test]
    fn annotate_never_mutates_the_receiver() {
        let shot = blank(16, 16, 1.0);
        let before = shot.pixels.clone();
        let (out, _) = annotate(&shot, &[Annotation::new(rect(0, 0, 16, 16), "A1")]);

        assert_eq!(shot.pixels, before, "self must be untouched");
        assert_ne!(out.pixels, before, "the copy must have been drawn on");
        assert_eq!(out.width, shot.width);
        assert_eq!(out.height, shot.height);
        assert!((out.scale - shot.scale).abs() < f32::EPSILON);
    }

    #[test]
    fn no_annotations_returns_an_identical_copy() {
        let shot = blank(8, 8, 1.0);
        let (out, skipped) = annotate(&shot, &[]);

        assert!(skipped.is_empty());
        assert_eq!(out.pixels, shot.pixels);
    }

    #[test]
    fn a_pixel_buffer_that_disagrees_with_the_dimensions_is_an_error() {
        let shot = Screenshot::new(4, 4, vec![0; 10], 1.0);
        let err = shot
            .annotate(&[], Point::new(0, 0))
            .expect_err("a short buffer must be reported, not drawn into");

        match err {
            Error::Platform { message, .. } => {
                assert!(message.contains("does not match"), "message was {message}");
            }
            other => panic!("expected Error::Platform, got {other:?}"),
        }
    }

    // ── Degenerate input ─────────────────────────────────────────────────

    #[test]
    fn extreme_coordinates_scales_and_dimensions_do_not_panic() {
        let rects = [
            rect(0, 0, 0, 0),
            rect(i32::MIN, i32::MIN, u32::MAX, u32::MAX),
            rect(i32::MAX, i32::MAX, u32::MAX, u32::MAX),
            rect(i32::MIN, i32::MAX, 1, 1),
            rect(i32::MAX, i32::MIN, u32::MAX, 1),
            rect(-1, -1, 3, 3),
            rect(0, 0, u32::MAX, 1),
            rect(2, 2, 1, 1),
        ];
        let origins = [
            Point::new(0, 0),
            Point::new(i32::MIN, i32::MIN),
            Point::new(i32::MAX, i32::MAX),
            Point::new(-7, 9),
        ];
        let scales = [
            1.0_f32,
            0.0,
            -1.0,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MIN_POSITIVE,
            f32::MAX,
            1.5,
            2.0,
            4.0,
            1e30,
        ];
        let dims = [(0_u32, 0_u32), (1, 1), (0, 8), (8, 0), (9, 5)];

        for &(w, h) in &dims {
            for &scale in &scales {
                let shot = blank(w, h, scale);
                for &r in &rects {
                    let anns = [
                        Annotation::new(r, "A1"),
                        Annotation::new(r, ""),
                        Annotation::new(r, "!!"),
                        Annotation::new(r, "zz09"),
                        Annotation::new(r, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW"),
                    ];
                    for &origin in &origins {
                        let (out, skipped) = shot
                            .annotate(&anns, origin)
                            .expect("a well-formed capture must annotate");
                        assert_eq!(
                            out.pixels.len(),
                            shot.pixels.len(),
                            "{w}x{h} scale {scale} rect {r:?} origin {origin:?}"
                        );
                        assert!(skipped.len() <= anns.len());
                        assert!(skipped.iter().all(|&i| i < anns.len()));
                    }
                }
            }
        }
    }

    #[test]
    fn a_zero_sized_image_draws_nothing_and_skips_everything() {
        let shot = blank(0, 0, 1.0);
        let (out, skipped) = annotate(&shot, &[Annotation::new(rect(0, 0, 10, 10), "A1")]);

        assert!(out.pixels.is_empty());
        assert_eq!(skipped, vec![0]);
    }

    #[test]
    fn a_box_larger_than_the_image_shows_only_its_interior() {
        let shot = blank(4, 4, 1.0);
        let (out, skipped) = annotate(&shot, &[boxed(rect(-10, -10, 100, 100), RED)]);

        assert!(skipped.is_empty());
        for y in 0..4 {
            for x in 0..4 {
                // Every stroke band is off-image, so what shows through the
                // 4×4 window is the box's interior and nothing else.
                assert_eq!(px(&out, x, y), BG, "interior at ({x}, {y})");
            }
        }
    }

    /// A tagged box that swallows the whole capture used to write **nothing**:
    /// every stroke band and all ten badge candidates were off-image, so the
    /// caller got a legend entry pointing at a picture with no mark in it and
    /// no `Omission` explaining the absence.
    ///
    /// `a_box_larger_than_the_image_shows_only_its_interior` sits one pixel
    /// inside this case and passed throughout, because `boxed()` carries an
    /// empty tag and so never placed a badge at all.
    #[test]
    fn a_box_swallowing_the_capture_still_draws_its_badge() {
        for inset in [30, 40, 1_000] {
            let shot = blank(100, 100, 1.0);
            let ann = Annotation::new(
                rect(
                    -inset,
                    -inset,
                    100 + 2 * inset as u32,
                    100 + 2 * inset as u32,
                ),
                "A1",
            )
            .color(RED);
            let (out, skipped) = annotate(&shot, &[ann]);

            assert!(
                skipped.is_empty(),
                "inset {inset}: box intersects the image"
            );
            let drawn = (0..100)
                .flat_map(|y| (0..100).map(move |x| (x, y)))
                .filter(|&(x, y)| px(&out, x, y) != BG)
                .count();
            assert!(
                drawn > 0,
                "inset {inset}: a legend entry with nothing drawn is the failure \
                 `omitted` exists to prevent"
            );
        }
    }

    #[test]
    fn a_box_thinner_than_the_stroke_is_drawn_solid() {
        let shot = blank(8, 8, 4.0);
        // Logical 1×1 at scale 4 → physical 4×4, stroke 4: the four bands
        // cover the whole box.
        let (out, skipped) = annotate(&shot, &[boxed(rect(0, 0, 1, 1), RED)]);

        assert!(skipped.is_empty());
        for y in 0..4 {
            for x in 0..4 {
                assert_eq!(px(&out, x, y), opaque(RED), "({x}, {y})");
            }
        }
        assert_eq!(px(&out, 4, 0), BG, "and nothing past it");
    }
}