pdfrum-doc 0.1.0

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

mod border;
mod da;
pub(crate) mod emit;
pub mod field_body;
pub(crate) mod fmt;
pub mod font_map;
pub mod freetext;
mod markup;
pub(crate) mod popup;
mod shapes;
pub mod widget;

use kurbo::{Affine, Rect};
use pdfrum_common::{DiagKind, Diagnostics, Severity};
use pdfrum_object::{Array, Dict, Name, Object, Resolve, names as obj_names};

use crate::annot::{Subtype, appearance, quad};
use crate::names;
use crate::vt;

/// One generated appearance and the dictionary edits it implies.
///
/// ```
/// use pdfrum_common::Diagnostics;
/// use pdfrum_doc::ap::generate_appearances;
/// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
///
/// let square = Dict::from_pairs([
///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
///     (
///         Name::from("Rect"),
///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
///     ),
/// ]);
/// let page = Dict::from_pairs([(
///     Name::from("Annots"),
///     Object::Array(Array::of([Object::Dict(square)])),
/// )]);
///
/// let mut diags = Diagnostics::default();
/// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
/// let generated = overlay.get(0).expect("a square has a generator");
///
/// // The matrix these generators produce is always the identity.
/// assert_eq!(generated.matrix, kurbo::Affine::IDENTITY);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct GeneratedAp {
    /// The content-stream bytes.
    pub stream: Vec<u8>,
    /// The form `XObject`'s bounding box.
    pub bbox: Rect,
    /// Its matrix, which these generators always leave as the identity.
    pub matrix: Affine,
    /// Its resource dictionary.
    pub resources: Dict,
    /// A rewritten `/Rect`, when generation moved one.
    pub rect_override: Option<Rect>,
    /// A copied-down `/AS`, for the `/NeedAppearances` widget path.
    pub as_override: Option<Name>,
}

/// What an overlay says about one annotation.
///
/// Three states, not two, and the third is why this is an enum rather than an
/// `Option`. "Nothing was generated" and "this annotation draws nothing" are
/// different instructions: the first falls through to whatever `/AP` the file
/// carries, the second **suppresses** it. A field whose appearance has been
/// cleared — focus left it and it went back to drawing nothing — needs the
/// second, and expressing it as the absence of an entry would make it
/// indistinguishable from the first.
///
/// ```
/// use pdfrum_doc::{AnnotOverlay, ap::Appearance};
///
/// let mut overlay = AnnotOverlay::with_capacity(2);
/// assert_eq!(overlay.appearance(0), &Appearance::Untouched);
///
/// // Suppressed is not the same as untouched: it says "draw nothing",
/// // even for an annotation the file gave an `/AP`.
/// overlay.set_appearance(0, Appearance::Suppressed);
/// assert!(overlay.get(0).is_none());
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub enum Appearance {
    /// Nothing to say. The file's own `/AP` is used, if it has one.
    #[default]
    Untouched,
    /// Draw this instead of the file's `/AP`.
    Generated(GeneratedAp),
    /// Draw nothing at all, even if the file carries an `/AP`.
    ///
    /// Nothing sets this yet. It exists so a cleared appearance has a
    /// spelling that is not "absent", which is what keeps the merge below
    /// able to express one later without changing shape.
    Suppressed,
}

/// The shape a focused widget's focus rectangle takes.
///
/// A widget being edited has a live control behind it, and what that control
/// answers when asked for a focus rectangle depends on which control it is —
/// three answers, not one, and two of the three are *no rectangle at all*:
///
/// - A **text field** and a **combo box** — editable or not — answer an empty
///   rectangle outright, so nothing is stroked over them. This is the common
///   case and it is why the focused text-field goldens carry a caret and
///   glyphs but no outline. Editability does **not** enter into it: a caller
///   that inflates a read-only combo strokes a box that must not be drawn.
/// - A **check box**, a **radio button** and a **single-select list box**
///   answer their window rectangle inflated by one unit on every side, which
///   is [`FocusBox::Inflated`]. A list box falls through to that answer when
///   it is not multi-select.
/// - A **multi-select list box** answers the rectangle of the item its caret
///   sits on, clipped to the client area — a rectangle only the list control's
///   own scroll and caret state can name, so a caller that has it supplies it
///   as [`FocusBox::Rect`].
///
/// `annot_render`'s own table says the same thing; the two are kept in step
/// deliberately, because this is the one a `pdfrum-form` caller reads.
///
/// [`FocusBox::None`] is the empty answer and the default: a focused entry
/// that names it is still *focused* — it draws no tint — and simply strokes
/// nothing.
///
/// ```
/// use pdfrum_doc::{FocusBox, geom};
///
/// // A text field and an editable combo box stroke nothing.
/// assert_eq!(FocusBox::default(), FocusBox::None);
/// // A multi-select list box names the rectangle only it can compute.
/// let explicit = FocusBox::Rect(geom::rect(0.0, 0.0, 100.0, 20.0));
/// assert_ne!(explicit, FocusBox::Inflated);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum FocusBox {
    /// No rectangle: nothing is stroked. A text field and an editable combo
    /// box always answer this.
    #[default]
    None,
    /// The annotation's own rectangle, inflated by one unit on every side.
    Inflated,
    /// An explicit rectangle in page space, already in its final position.
    Rect(Rect),
}

/// Which annotation on the page holds the keyboard focus, and what its focus
/// rectangle is.
///
/// Both halves are needed and they are independent. The *index* alone decides
/// the tint: a widget with a live control is never tinted, focused or not, and
/// the focused one is the only widget a live control reaches in a
/// single-focus session. The *box* decides whether anything is stroked in its
/// place, which most field types answer with nothing.
///
/// ```
/// use pdfrum_doc::{AnnotOverlay, Focus, FocusBox, geom};
///
/// let mut overlay = AnnotOverlay::with_capacity(2);
/// overlay.set_focus(Focus {
///     annot: 1,
///     box_: FocusBox::Rect(geom::rect(0.0, 0.0, 100.0, 20.0)),
/// });
/// assert_eq!(overlay.focus().map(|f| f.annot), Some(1));
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Focus {
    /// The raw `/Annots` index of the focused annotation — the same key space
    /// [`AnnotOverlay::set`] uses.
    pub annot: usize,
    /// The rectangle to stroke, in page space.
    pub box_: FocusBox,
}

impl Focus {
    /// Focus on one annotation with no rectangle to stroke — the answer a
    /// text field and an editable combo box give.
    ///
    /// ```
    /// use pdfrum_doc::{Focus, FocusBox};
    ///
    /// let focus = Focus::at(2);
    /// assert_eq!(focus.annot, 2);
    /// // No rectangle to stroke, which is what a text field answers.
    /// assert_eq!(focus.box_, FocusBox::None);
    /// ```
    #[must_use]
    pub fn at(annot: usize) -> Focus {
        Focus {
            annot,
            box_: FocusBox::None,
        }
    }
}

/// Per-annotation generated appearances, keyed by `/Annots` index.
///
/// Besides the per-annotation entries the overlay carries at most one
/// [`Focus`], because a session focuses one field at a time. It travels here
/// rather than as another parameter on the annotation pass for two reasons:
/// it is set by the same session that sets the appearances, from the same
/// index space, and adding it here left every existing caller compiling
/// unchanged.
///
/// ```
/// use pdfrum_common::Diagnostics;
/// use pdfrum_doc::ap::generate_appearances;
/// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
///
/// let square = Dict::from_pairs([
///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
///     (
///         Name::from("Rect"),
///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
///     ),
/// ]);
/// let page = Dict::from_pairs([(
///     Name::from("Annots"),
///     Object::Array(Array::of([Object::Dict(square)])),
/// )]);
///
/// // Every reader in this crate takes the overlay and consults it
/// // before the raw dictionary.
/// let mut diags = Diagnostics::default();
/// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
/// assert!(overlay.get(0).is_some());
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AnnotOverlay {
    entries: Vec<Appearance>,
    focus: Option<Focus>,
    hover: Option<usize>,
    live_edit: Option<usize>,
}

impl AnnotOverlay {
    /// An overlay with room for `count` annotations and nothing generated.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, ap::Appearance};
    ///
    /// let overlay = AnnotOverlay::with_capacity(3);
    /// assert_eq!(overlay.len(), 3);
    /// assert_eq!(overlay.appearance(0), &Appearance::Untouched);
    /// ```
    #[must_use]
    pub fn with_capacity(count: usize) -> AnnotOverlay {
        AnnotOverlay {
            entries: vec![Appearance::Untouched; count],
            focus: None,
            hover: None,
            live_edit: None,
        }
    }

    /// Records which annotation holds the focus, and what to stroke over it.
    ///
    /// The index is a raw `/Annots` index. It is **not** bounded by the
    /// overlay's length: an overlay sized for the appearances it carries can
    /// still name a focused annotation past its end, and the annotation pass
    /// keys on the index rather than on an entry.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, Focus};
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(2);
    /// // The index is a raw `/Annots` index and is not bounded by the length.
    /// overlay.set_focus(Focus::at(7));
    /// assert_eq!(overlay.focus().map(|f| f.annot), Some(7));
    /// ```
    pub fn set_focus(&mut self, focus: Focus) {
        self.focus = Some(focus);
    }

    /// Which annotation holds the focus, if any.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, Focus};
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(2);
    /// assert!(overlay.focus().is_none());
    /// overlay.set_focus(Focus::at(1));
    /// assert_eq!(overlay.focus().map(|f| f.annot), Some(1));
    /// ```
    #[must_use]
    pub fn focus(&self) -> Option<Focus> {
        self.focus
    }

    /// Records which annotation the pointer is inside.
    ///
    /// A raw `/Annots` index, like [`Self::set_focus`]'s, and equally
    /// unbounded by the overlay's length. Hover is a separate fact from focus
    /// and the two move independently: a pointer resting on an annotation
    /// leaves the keyboard focus wherever it was, and the annotation under the
    /// pointer need not be focusable at all — a highlight is the case that
    /// matters, since it is *only* reachable this way.
    ///
    /// What it decides is whether that annotation's synthesized pop-up note is
    /// **open**. A note card is drawn only while the pointer is inside its
    /// parent, and nothing a file can say opens one, so this is the whole of
    /// the signal.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(4);
    /// overlay.set_hover(1);
    /// assert_eq!(overlay.hover(), Some(1));
    /// // Hover and focus move independently.
    /// assert!(overlay.focus().is_none());
    /// ```
    pub fn set_hover(&mut self, annot: usize) {
        self.hover = Some(annot);
    }

    /// Which annotation the pointer is inside, if any.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(4);
    /// assert!(overlay.hover().is_none());
    /// overlay.set_hover(0);
    /// assert_eq!(overlay.hover(), Some(0));
    /// ```
    #[must_use]
    pub fn hover(&self) -> Option<usize> {
        self.hover
    }

    /// Records that one annotation's supplied appearance is a **live edit's**
    /// — the field the session is currently typing in.
    ///
    /// A raw `/Annots` index, like [`Self::set_focus`]'s and equally unbounded
    /// by the overlay's length. At most one annotation can be under live edit,
    /// because a session focuses one field at a time; a second call replaces
    /// the first rather than accumulating.
    ///
    /// It is a separate signal from focus, and the two are **not**
    /// interchangeable. A field can hold the focus without being edited — it
    /// was tabbed to and nothing has been typed — in which case the session
    /// generates no appearance for it and there is nothing to mark. What this
    /// records is that the appearance carried at this index came from an
    /// editor, which is what makes the oracle draw its text with `ClearType`.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(4);
    /// overlay.set_live_edit(1);
    /// // A second call replaces the first: one field is edited at a time.
    /// overlay.set_live_edit(2);
    /// assert_eq!(overlay.live_edit(), Some(2));
    /// ```
    pub fn set_live_edit(&mut self, annot: usize) {
        self.live_edit = Some(annot);
    }

    /// Which annotation's appearance is a live edit's, if any.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(4);
    /// assert!(overlay.live_edit().is_none());
    /// overlay.set_live_edit(3);
    /// assert_eq!(overlay.live_edit(), Some(3));
    /// ```
    #[must_use]
    pub fn live_edit(&self) -> Option<usize> {
        self.live_edit
    }

    /// Whether the appearance at one `/Annots` index came from a live edit.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(4);
    /// overlay.set_live_edit(1);
    /// assert!(overlay.is_live_edit(1));
    /// assert!(!overlay.is_live_edit(0));
    /// ```
    #[must_use]
    pub fn is_live_edit(&self, index: usize) -> bool {
        self.live_edit == Some(index)
    }

    /// Records a generated appearance at one `/Annots` index.
    ///
    /// ```
    /// use pdfrum_common::Diagnostics;
    /// use pdfrum_doc::ap::generate_appearances;
    /// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
    ///
    /// let square = Dict::from_pairs([
    ///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
    ///     (
    ///         Name::from("Rect"),
    ///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
    ///     ),
    ///     (
    ///         Name::from("IC"),
    ///         Object::Array(Array::of([1, 0, 0].map(Object::from))),
    ///     ),
    /// ]);
    /// let page = Dict::from_pairs([(
    ///     Name::from("Annots"),
    ///     Object::Array(Array::of([Object::Dict(square)])),
    /// )]);
    ///
    /// let mut diags = Diagnostics::default();
    /// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
    ///
    /// // The walk sets index 0; a caller can set any index the same way.
    /// let generated = overlay.get(0).expect("a square has a generator").clone();
    /// let mut mine = pdfrum_doc::AnnotOverlay::with_capacity(2);
    /// mine.set(1, generated);
    /// assert!(mine.get(1).is_some());
    /// ```
    pub fn set(&mut self, index: usize, generated: GeneratedAp) {
        self.set_appearance(index, Appearance::Generated(generated));
    }

    /// Records any of the three states at one `/Annots` index.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, ap::Appearance};
    ///
    /// let mut overlay = AnnotOverlay::with_capacity(2);
    /// overlay.set_appearance(0, Appearance::Suppressed);
    /// assert_eq!(overlay.appearance(0), &Appearance::Suppressed);
    /// // A suppressed entry has no stream to draw.
    /// assert!(overlay.get(0).is_none());
    /// ```
    pub fn set_appearance(&mut self, index: usize, appearance: Appearance) {
        if let Some(slot) = self.entries.get_mut(index) {
            *slot = appearance;
        }
    }

    /// What was generated at one `/Annots` index, if anything.
    ///
    /// A suppressed entry answers [`None`], the same as an untouched one —
    /// callers that only want a stream to draw need not distinguish them.
    /// [`AnnotOverlay::appearance`] is what tells them apart.
    ///
    /// ```
    /// use pdfrum_common::Diagnostics;
    /// use pdfrum_doc::ap::generate_appearances;
    /// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
    ///
    /// let square = Dict::from_pairs([
    ///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
    ///     (
    ///         Name::from("Rect"),
    ///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
    ///     ),
    ///     (
    ///         Name::from("IC"),
    ///         Object::Array(Array::of([1, 0, 0].map(Object::from))),
    ///     ),
    /// ]);
    /// let page = Dict::from_pairs([(
    ///     Name::from("Annots"),
    ///     Object::Array(Array::of([Object::Dict(square)])),
    /// )]);
    ///
    /// let mut diags = Diagnostics::default();
    /// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
    ///
    /// assert!(overlay.get(0).is_some());
    /// // Past the end is `None`, not a panic.
    /// assert!(overlay.get(9).is_none());
    /// ```
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&GeneratedAp> {
        match self.appearance(index) {
            Appearance::Generated(generated) => Some(generated),
            Appearance::Untouched | Appearance::Suppressed => None,
        }
    }

    /// The full state at one `/Annots` index, suppression included.
    ///
    /// An index past the overlay's end reads as [`Appearance::Untouched`],
    /// which is what makes a short overlay safe to consult for any index.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, ap::Appearance};
    ///
    /// let overlay = AnnotOverlay::with_capacity(1);
    /// // An index past the end reads as untouched, so a short overlay is
    /// // safe to consult for any index.
    /// assert_eq!(overlay.appearance(99), &Appearance::Untouched);
    /// ```
    #[must_use]
    pub fn appearance(&self, index: usize) -> &Appearance {
        self.entries.get(index).unwrap_or(&Appearance::Untouched)
    }

    /// Lays `other`'s entries over this one's.
    ///
    /// Every entry `other` has anything to say about — generated **or**
    /// suppressed — replaces this overlay's, and its [`Appearance::Untouched`]
    /// entries leave this one's alone. So a caller-supplied overlay wins
    /// wherever it speaks and defers everywhere else, which is the merge a
    /// live edit needs: the session has an opinion about the one field being
    /// edited and none about the rest of the page.
    ///
    /// Indices are raw `/Annots` indices in both overlays. An entry of
    /// `other` past this overlay's end is dropped, because there is no
    /// annotation for it to apply to.
    ///
    /// `other`'s [`Focus`] and its hover each replace this overlay's when it
    /// has one, and leave it alone when it does not — the same "wins wherever
    /// it speaks" rule the entries follow. Unlike an entry, either one past
    /// this overlay's end survives: both name an annotation, not a slot.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, ap::Appearance};
    ///
    /// let mut page = AnnotOverlay::with_capacity(2);
    /// page.set_appearance(0, Appearance::Suppressed);
    ///
    /// // The session speaks about index 1 only.
    /// let mut session = AnnotOverlay::with_capacity(2);
    /// session.set_appearance(1, Appearance::Suppressed);
    /// page.merge_over(&session);
    ///
    /// assert_eq!(page.appearance(0), &Appearance::Suppressed);
    /// assert_eq!(page.appearance(1), &Appearance::Suppressed);
    /// ```
    pub fn merge_over(&mut self, other: &AnnotOverlay) {
        for (index, entry) in other.entries.iter().enumerate() {
            if matches!(entry, Appearance::Untouched) {
                continue;
            }
            self.set_appearance(index, entry.clone());
        }
        if let Some(focus) = other.focus {
            self.focus = Some(focus);
        }
        if let Some(hover) = other.hover {
            self.hover = Some(hover);
        }
        if let Some(live_edit) = other.live_edit {
            self.live_edit = Some(live_edit);
        }
    }

    /// The rectangle an annotation should be read as having.
    ///
    /// ```
    /// use pdfrum_doc::{AnnotOverlay, geom};
    ///
    /// let overlay = AnnotOverlay::with_capacity(1);
    /// let raw = geom::rect(0.0, 0.0, 100.0, 50.0);
    /// // Nothing generated: the annotation keeps the rectangle it declared.
    /// assert_eq!(overlay.rect(0, raw), raw);
    /// ```
    #[must_use]
    pub fn rect(&self, index: usize, raw: Rect) -> Rect {
        self.get(index)
            .and_then(|generated| generated.rect_override)
            .unwrap_or(raw)
    }

    /// How many annotations the overlay covers.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// assert_eq!(AnnotOverlay::with_capacity(3).len(), 3);
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the overlay covers no annotations at all.
    ///
    /// ```
    /// use pdfrum_doc::AnnotOverlay;
    ///
    /// assert!(AnnotOverlay::with_capacity(0).is_empty());
    /// assert!(!AnnotOverlay::with_capacity(1).is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// The font a text-bearing generator sets its text with.
///
/// Threaded in rather than loaded here, because loading one needs a font
/// cache the caller already owns, and because the layout engine is a pure
/// function of these numbers — which is what lets it be tested against a stub.
///
/// ```
/// use pdfrum_doc::ap::FormFonts;
/// use pdfrum_object::{Dict, NoResolve};
///
/// // A catalog with no `/AcroForm` still yields the stock fallback face.
/// let mut ctx = pdfrum_page::BuildContext::new();
/// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
/// use pdfrum_doc::ap::TextFont;
///
/// let font = fonts.face(b"Helv").expect("the fallback face");
/// let width = |code: u32| TextFont::char_width(font, code);
/// let text = fonts.text_font(b"Helv", &width).expect("a face to set text with");
///
/// // The ascent the layout engine stacks lines by.
/// assert!(text.metrics.ascent > 0);
/// ```
pub struct TextFont<'a> {
    /// The loaded font.
    pub font: &'a pdfrum_font::Font,
    /// Metrics derived from it, for the layout engine.
    pub metrics: vt::Metrics<'a>,
}

impl std::fmt::Debug for TextFont<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextFont")
            .field("metrics", &self.metrics)
            .finish_non_exhaustive()
    }
}

/// The character code a code point the face cannot map is written as.
///
/// A simple font's codes are one byte and `Font::append_char` truncates to
/// one, so the code the stream ends up carrying is the code point's **low
/// byte** — and the width has to be looked up under that same byte or the
/// layout advances by a glyph the stream does not name. A composite font
/// keeps the whole value, because its CMap decides the width itself.
fn unmapped_code(font: &pdfrum_font::Font, code: u32) -> pdfrum_font::CharCode {
    match font {
        pdfrum_font::Font::Type0(_) => pdfrum_font::CharCode(code),
        pdfrum_font::Font::Simple(_) | pdfrum_font::Font::Type3(_) => {
            pdfrum_font::CharCode(code & 0xff)
        }
    }
}

impl TextFont<'_> {
    /// How one code point is written into a content stream.
    ///
    /// A `Symbol` or `ZapfDingbats` font takes the code point's **low byte**
    /// verbatim, relying on the font's built-in encoding: there is no
    /// named-glyph table and no `/Encoding` consultation anywhere in this
    /// path. Anything else goes through the reverse `ToUnicode` mapping.
    ///
    /// **A code point the font cannot represent is still written**, as its own
    /// value taken for a character code. The glyph that draws is whatever that
    /// code happens to name in the chosen face and is usually wrong — but the
    /// text object exists, occupies the layout, and is what a reader sees.
    /// Dropping the character instead loses the object entirely, which on
    /// `bug_725389` — three Hebrew characters in a `/DA` naming Times-Roman —
    /// is the difference between six text objects and three.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// use pdfrum_doc::ap::TextFont;
    ///
    /// let font = fonts.face(b"Helv").expect("the fallback face");
    /// let width = |code: u32| TextFont::char_width(font, code);
    /// let text = fonts.text_font(b"Helv", &width).expect("a face");
    ///
    /// // `A` writes as one byte in a simple font.
    /// assert_eq!(text.encode(u32::from('A')), b"A");
    /// ```
    // The oracle reaches the same place by a longer road: CPDF_BAFontMap
    // first looks for a second face that knows the character, and only
    // CPWL_EditImpl::GetPDFWordString's fallthrough appends the raw value
    // when none does. On a hermetic font set no second face is found, so the
    // fallthrough is the whole of the observable behaviour — which is why no
    // N-slot map is built here for a result it would not change.
    #[must_use]
    pub fn encode(&self, code: u32) -> Vec<u8> {
        let name = self.font.base_font_name();
        if name == b"Symbol" || name == b"ZapfDingbats" {
            return vec![u8::try_from(code & 0xff).unwrap_or(0)];
        }
        let mut out = Vec::new();
        let mapped = char::from_u32(code)
            .and_then(|ch| self.font.char_code_from_unicode(ch))
            .unwrap_or_else(|| unmapped_code(self.font, code));
        self.font.append_char(&mut out, mapped);
        out
    }

    /// One code point's width, in thousandths of an em.
    ///
    /// The width is the one the face gives whatever [`Self::encode`] wrote, so
    /// an unrepresentable code point measures the glyph its raw value names
    /// rather than nothing — the two have to agree or the layout advances past
    /// characters the stream still contains, and the line comes out the wrong
    /// length.
    ///
    /// A free function rather than a method because [`Self::metrics_of`] wants
    /// it as a `&dyn Fn` borrowed for the same lifetime as the font, which a
    /// closure over `self` cannot supply before `self` exists.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// use pdfrum_doc::ap::TextFont;
    ///
    /// let font = fonts.face(b"Helv").expect("the fallback face");
    /// // Thousandths of an em, for whatever `encode` wrote.
    /// assert!(TextFont::char_width(font, u32::from('A')) > 0);
    /// ```
    #[must_use]
    pub fn char_width(font: &pdfrum_font::Font, code: u32) -> i32 {
        let charcode = char::from_u32(code)
            .and_then(|ch| font.char_code_from_unicode(ch))
            .unwrap_or_else(|| unmapped_code(font, code));
        #[allow(clippy::cast_possible_truncation)]
        {
            font.char_width(charcode) as i32
        }
    }

    /// The layout metrics a loaded font supplies.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// use pdfrum_doc::ap::TextFont;
    ///
    /// let font = fonts.face(b"Helv").expect("the fallback face");
    /// let width = |code: u32| TextFont::char_width(font, code);
    /// let metrics = TextFont::metrics_of(font, &width);
    /// assert!(metrics.ascent > metrics.descent);
    /// ```
    #[must_use]
    pub fn metrics_of<'a>(
        font: &'a pdfrum_font::Font,
        width: &'a dyn Fn(u32) -> i32,
    ) -> vt::Metrics<'a> {
        vt::Metrics {
            width,
            ascent: font.type_ascent(),
            descent: font.type_descent(),
        }
    }
}

/// One second face: the resource name it is filed under, the dictionary the
/// appearance's `/Resources /Font` carries, and the loaded face itself.
///
/// A borrow of what [`FormFonts`] already holds. The three travel together
/// because a generator needs all three to write one character — the alias for
/// the `Tf`, the face for the width, and the dictionary so the name resolves
/// when the stream is drawn.
///
/// ```
/// use pdfrum_doc::ap::FormFonts;
/// use pdfrum_object::{Dict, NoResolve};
///
/// // A catalog with no `/AcroForm` still yields the stock fallback face.
/// let mut ctx = pdfrum_page::BuildContext::new();
/// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
/// use pdfrum_font::Charset;
///
/// // A second face for the characters the `/DA` font cannot write.
/// if let Some(substitute) = fonts.substitute(Charset::ShiftJis) {
///     // The alias is the `Tf` name and the key in the appearance's
///     // own `/Resources /Font`.
///     assert!(!substitute.alias.as_bytes().is_empty());
/// }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Substitute<'a> {
    /// The `Tf` name, and the key in the appearance's font resources.
    pub alias: &'a Name,
    /// The font dictionary that key maps to.
    pub dict: &'a Dict,
    /// The loaded face, for widths and for the codes it can write.
    pub font: &'a pdfrum_font::Font,
}

/// The faces a form's default resources name, loaded once for a page.
///
/// # Why the fonts are loaded rather than substituted for
///
/// A generator wants *metrics*, and it was tempting to hand every generator
/// one stock Helvetica on the reasoning that a non-embedded `/DA` font
/// substitutes to that face anyway. The metrics do not agree with that
/// reasoning, and the disagreement is visible: an ascent and descent taken
/// from the base-14 metric tables are 718 and −219, while the ones taken from
/// the **substituted face** — the size the layout engine actually stacks lines
/// by — are the face's own, and for the hermetic corpus's metric-compatible
/// Helvetica that is 905 and −211. On a list box the difference is the row
/// pitch: 11.24 units per row against 13.39, which is two extra rows in a
/// thirty-unit box.
///
/// So the font a widget's `/DA` names is loaded from the form's `/DR /Font`,
/// through the same loader and the same substitution options every other font
/// on the page goes through. A name the resources do not carry gets a stock
/// Helvetica, which is what the fallback is actually for.
///
/// ```
/// use pdfrum_doc::ap::FormFonts;
/// use pdfrum_object::{Dict, NoResolve};
///
/// // A catalog with no `/AcroForm` still yields the stock fallback face.
/// let mut ctx = pdfrum_page::BuildContext::new();
/// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
///
/// // A name the resources do not carry falls back rather than failing.
/// assert!(fonts.face(b"NoSuchFace").is_some());
/// ```
pub struct FormFonts {
    /// Resource name and the face loaded under it, in `/DR /Font` order with
    /// the fallback last.
    entries: Vec<(Name, pdfrum_font::Font)>,
    /// The faces added for characters no declared font's charset covers, one
    /// per charset, keyed by the alias they are filed under.
    ///
    /// These are not in `/DR`, and no `/DA` names one: they are added when a
    /// field is asked to write a character its own font cannot, and they go
    /// into the **appearance stream's** own `/Resources /Font` rather than the
    /// form's. See [`font_map`].
    substitutes: Vec<(Name, Dict, pdfrum_font::Font)>,
}

impl std::fmt::Debug for FormFonts {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FormFonts")
            .field(
                "names",
                &self.entries.iter().map(|(n, _)| n).collect::<Vec<_>>(),
            )
            .finish_non_exhaustive()
    }
}

impl FormFonts {
    /// Loads every font a document's interactive form declares, plus the
    /// fallback a name outside them resolves to.
    ///
    /// The fallback is loaded unconditionally and stored under an empty name,
    /// so a `/DA` naming nothing — or naming a font the resources lack — still
    /// has a face to measure with. That is the same substitution a viewer
    /// performs; it is only the *metric source* that this fixes.
    ///
    /// # Memoized on the context
    ///
    /// The faces are a pure function of the form's `/DR /Font`, and building
    /// them is expensive — the `/DR` walk constructs every font the form
    /// declares, encoding tables and substitution ladder included. The
    /// annotation overlay asks for them **once per page per render**, so the
    /// result is cached in the [`BuildContext`](pdfrum_page::BuildContext)
    /// beside the rest of the per-document font state. A caller threading one
    /// context through many renders of one document pays for this once.
    ///
    /// Nothing about *what* is built changed when the cache was added, which
    /// is what makes the appearance streams identical: the fallback still
    /// goes through the same loader, and the second faces are still loaded
    /// here rather than where a field discovers it needs one. Only the number
    /// of times moved.
    ///
    /// # What the key names, and why it is not the `/AcroForm`
    ///
    /// Building the faces reads exactly one thing out of the document — the
    /// `/AcroForm`'s `/DR /Font` dictionary — and takes everything else from
    /// dictionaries written in this crate. So the *faces* are a function of
    /// that dictionary alone, and keying on the `/AcroForm` instead threw
    /// away every form written as a direct dictionary, which has no reference
    /// to name it by.
    ///
    /// A direct `/AcroForm` is not the rarity it reads as. An empty
    /// `<</Fields[]>>` is what a producer writes when it declares a form and
    /// then puts no fields in it, and six of this corpus's 44 documents carry
    /// one — none of them a form document. Every one of those was rebuilding
    /// the fallback face and the substitute face once per page per render, for
    /// a form with no fields, and on four of them it was the single largest
    /// line in the render.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    ///
    /// // Loaded once per document and shared: a second load hits the cache.
    /// let again = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// assert!(std::sync::Arc::ptr_eq(&fonts, &again));
    /// ```
    #[must_use]
    pub fn load<R: Resolve>(
        catalog: &Dict,
        r: &R,
        ctx: &mut pdfrum_page::BuildContext,
    ) -> std::sync::Arc<FormFonts> {
        ctx.form_fonts(FormFonts::key(catalog, r), |ctx| {
            FormFonts::build(catalog, r, ctx)
        })
    }

    /// The cache slot this catalog's faces belong in.
    ///
    /// Split out from [`Self::load`] so the four cases can be asserted
    /// directly; the walk is `/AcroForm` then `/DR` then `/Font`, resolving
    /// references at every step except the last, whose *spelling* is the
    /// answer.
    fn key<R: Resolve>(catalog: &Dict, r: &R) -> pdfrum_page::FormFontsKey {
        match catalog.raw(names::ACRO_FORM) {
            // A real form: the reference names it, as it names every other
            // per-document cache on the context.
            Some(Object::Ref(reference)) => return pdfrum_page::FormFontsKey::Form(*reference),
            Some(_) => {}
            // No form at all, so no `/DR /Font`: the constants alone.
            None => return pdfrum_page::FormFontsKey::None,
        }
        // A direct `/AcroForm`. Its faces are its `/DR /Font`'s, so that is
        // what has to be identified — the same walk `build` makes, stopping
        // one step earlier and reading the spelling rather than the value.
        let fonts = catalog
            .dict(names::ACRO_FORM, r)
            .and_then(|form| form.dict(names::DR, r))
            .and_then(|resources| resources.raw(names::FONT).cloned());
        match fonts {
            // Written as a reference, which is the ordinary spelling even
            // inside a direct form: as good an identity as the form's own.
            Some(Object::Ref(reference)) => pdfrum_page::FormFontsKey::DirectResources(reference),
            // Written out in full. Nothing to key on, so it is rebuilt.
            Some(_) => pdfrum_page::FormFontsKey::Direct,
            // No default resources: the constants alone, exactly as a
            // document with no form at all.
            None => pdfrum_page::FormFontsKey::None,
        }
    }

    /// [`Self::load`] without the cache: the faces, built now.
    #[must_use]
    fn build<R: Resolve>(catalog: &Dict, r: &R, ctx: &mut pdfrum_page::BuildContext) -> FormFonts {
        let (limits, mut diags) = (
            pdfrum_common::Limits::default(),
            pdfrum_common::Diagnostics::default(),
        );
        let mut load = |dict: &Dict| {
            pdfrum_font::load_with_options(
                dict,
                r,
                &ctx.fonts,
                &ctx.substitution,
                &limits,
                &mut diags,
            )
        };

        let mut entries = Vec::new();
        let fonts = catalog
            .dict(names::ACRO_FORM, r)
            .and_then(|form| form.dict(names::DR, r))
            .and_then(|resources| resources.dict(names::FONT, r));
        if let Some(fonts) = fonts {
            for key in fonts.keys() {
                let Some(dict) = fonts.dict(key, r) else {
                    continue;
                };
                if let Some(font) = load(&dict) {
                    entries.push((key.clone(), font));
                }
            }
        }
        // The fallback goes through the **same loader**, not the stock-metrics
        // constructor: the point of this type is that the ascent and descent
        // come from the face that is actually substituted, and a font built
        // from the base-14 tables would answer 718 and −219 where the face
        // answers its own. A field with no `/DR` at all is exactly where that
        // shows, because there is nothing else for it to measure with.
        entries.extend(load(&freetext::fallback_font()).map(|font| (Name::new(Vec::new()), font)));

        // The second faces, loaded here rather than where a field discovers it
        // needs one: loading needs the page's font cache, and the generators
        // are pure functions of the faces they are handed. There is one per
        // charset the font map can add for, which is one — see [`font_map`].
        let mut substitutes = Vec::new();
        for charset in font_map::SUBSTITUTABLE_CHARSETS {
            let Some(dict) = font_map::substitute_font_dict(*charset) else {
                continue;
            };
            if let Some(font) = load(&dict) {
                substitutes.push((Name::new(font_map::substitute_alias(*charset)), dict, font));
            }
        }
        FormFonts {
            entries,
            substitutes,
        }
    }

    /// The second face a character of `charset` is written in, with the alias
    /// it is filed under and the dictionary that goes into the appearance's
    /// own resources.
    ///
    /// Answers nothing for a charset with no encoding table, and for one whose
    /// face would not load — in both cases the caller leaves the character to
    /// the `/DA` font, which is the behaviour that predates this.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// use pdfrum_font::Charset;
    ///
    /// // Nothing for a charset with no encoding table, or whose face will
    /// // not load: the caller then leaves the character to the `/DA` font.
    /// let _ = fonts.substitute(Charset::ShiftJis);
    /// ```
    #[must_use]
    pub fn substitute(&self, charset: pdfrum_font::Charset) -> Option<Substitute<'_>> {
        let alias = font_map::substitute_alias(charset);
        self.substitutes
            .iter()
            .find(|(name, _, _)| name.as_bytes() == alias)
            .map(|(name, dict, font)| Substitute {
                alias: name,
                dict,
                font,
            })
    }

    /// The face filed under one resource name, or the fallback.
    ///
    /// Answers nothing only if the fallback itself is missing, which
    /// [`Self::load`] makes impossible — the caller then generates chrome
    /// alone rather than being told a face exists that does not.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    ///
    /// assert!(fonts.face(b"Helv").is_some());
    /// // Answers the fallback rather than nothing for an unknown name.
    /// assert!(fonts.face(b"NoSuchFace").is_some());
    /// ```
    #[must_use]
    pub fn face(&self, name: &[u8]) -> Option<&pdfrum_font::Font> {
        self.entries
            .iter()
            .find(|(key, _)| key.as_bytes() == name)
            .or_else(|| self.entries.last())
            .map(|(_, font)| font)
    }

    /// A [`TextFont`] over one resource name, with `width` borrowed for the
    /// same lifetime.
    ///
    /// The width closure cannot live inside the returned value — it has to be
    /// borrowed for the font's lifetime, which a closure over `self` cannot
    /// supply before `self` exists — so the caller keeps it and passes it in,
    /// the same shape [`TextFont::metrics_of`] already has.
    ///
    /// ```
    /// use pdfrum_doc::ap::FormFonts;
    /// use pdfrum_object::{Dict, NoResolve};
    ///
    /// // A catalog with no `/AcroForm` still yields the stock fallback face.
    /// let mut ctx = pdfrum_page::BuildContext::new();
    /// let fonts = FormFonts::load(&Dict::default(), &NoResolve, &mut ctx);
    /// use pdfrum_doc::ap::TextFont;
    ///
    /// // The width closure is borrowed for the font's lifetime, so the
    /// // caller keeps it and passes it in.
    /// let font = fonts.face(b"Helv").expect("the fallback face");
    /// let width = |code: u32| TextFont::char_width(font, code);
    /// assert!(fonts.text_font(b"Helv", &width).is_some());
    /// ```
    #[must_use]
    pub fn text_font<'a>(
        &'a self,
        name: &[u8],
        width: &'a dyn Fn(u32) -> i32,
    ) -> Option<TextFont<'a>> {
        let font = self.face(name)?;
        Some(TextFont {
            metrics: TextFont::metrics_of(font, width),
            font,
        })
    }
}

/// Generates appearances for every annotation on a page that wants one.
///
/// The walk mirrors what a viewer does when it opens a page, because that
/// ordering is what the `--annot` contract describes: pop-ups written into
/// the file are skipped, everything else is offered to its generator, and the
/// results are keyed by position in `/Annots`.
///
/// The text-bearing generators are skipped here; [`generate_appearances_with_text`]
/// is the walk that enables them.
///
/// ```
/// use pdfrum_common::Diagnostics;
/// use pdfrum_doc::ap::generate_appearances;
/// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
///
/// let square = Dict::from_pairs([
///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
///     (
///         Name::from("Rect"),
///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
///     ),
///     (
///         Name::from("IC"),
///         Object::Array(Array::of([1, 0, 0].map(Object::from))),
///     ),
/// ]);
/// let page = Dict::from_pairs([(
///     Name::from("Annots"),
///     Object::Array(Array::of([Object::Dict(square)])),
/// )]);
///
/// let mut diags = Diagnostics::default();
/// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
///
/// // One entry per `/Annots` index; the square got a stream.
/// assert_eq!(overlay.len(), 1);
/// assert!(!overlay.get(0).expect("generated").stream.is_empty());
/// ```
#[must_use]
pub fn generate_appearances<R: Resolve>(
    page: &Dict,
    r: &R,
    diags: &mut Diagnostics,
) -> AnnotOverlay {
    let Some(annots) = page.array(obj_names::ANNOTS, r) else {
        return AnnotOverlay::default();
    };
    let mut overlay = AnnotOverlay::with_capacity(annots.len());
    for index in 0..annots.len() {
        let Some(dict) = annots.dict_at(index, r) else {
            continue;
        };
        if crate::annot::is_popup(&dict, r) {
            continue;
        }
        if let Some(generated) = generate_one(&dict, r, diags) {
            overlay.set(index, generated);
        } else if let Some(generated) = widget::generate(&dict, r) {
            // A widget with no appearance dictionary gets its chrome built
            // when the page opens, whatever the form says about regenerating
            // appearances. See `widget` for how far that goes.
            diags.record(Severity::Recovered, DiagKind::AppearanceGenerated, None);
            overlay.set(index, generated);
        }
    }
    overlay
}

/// The same walk, with the text-bearing generators enabled.
///
/// The generators only produce an appearance when a font is in hand, so a
/// caller without one gets the same result as [`generate_appearances`].
///
/// Each annotation is measured with the face **its own** `/DA` names, looked
/// up in the form's default resources — not with one page-wide font. A page
/// whose fields name two different faces stacks their lines by two different
/// ascents, which is what a viewer does.
///
/// ```
/// use pdfrum_common::Diagnostics;
/// use pdfrum_doc::ap::generate_appearances;
/// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
///
/// let square = Dict::from_pairs([
///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
///     (
///         Name::from("Rect"),
///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
///     ),
///     (
///         Name::from("IC"),
///         Object::Array(Array::of([1, 0, 0].map(Object::from))),
///     ),
/// ]);
/// let page = Dict::from_pairs([(
///     Name::from("Annots"),
///     Object::Array(Array::of([Object::Dict(square)])),
/// )]);
///
/// let mut diags = Diagnostics::default();
/// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
/// use pdfrum_doc::ap::generate_appearances_with_text;
///
/// let catalog = Dict::default();
/// // With no fonts in hand the text-bearing generators stay off, so the
/// // result matches the plain walk.
/// let mut diags = Diagnostics::default();
/// let with_text =
///     generate_appearances_with_text(&page, &catalog, None, &NoResolve, &mut diags);
/// assert_eq!(with_text.get(0), overlay.get(0));
/// ```
#[must_use]
pub fn generate_appearances_with_text<R: Resolve>(
    page: &Dict,
    catalog: &Dict,
    fonts: Option<&FormFonts>,
    r: &R,
    diags: &mut Diagnostics,
) -> AnnotOverlay {
    let Some(annots) = page.array(obj_names::ANNOTS, r) else {
        return AnnotOverlay::default();
    };
    let mut overlay = AnnotOverlay::with_capacity(annots.len());
    for index in 0..annots.len() {
        let Some(dict) = annots.dict_at(index, r) else {
            continue;
        };
        if crate::annot::is_popup(&dict, r) {
            continue;
        }
        // The width closure has to outlive the `TextFont` that borrows it, so
        // it is built here rather than inside the lookup.
        let named = fonts.and_then(|fonts| fonts.face(&font_name_of(&dict, catalog, r)));
        // A second face, for the characters this one's charset does not cover.
        // The **widths** have to know about it as well as the bytes: a run set
        // in two faces advances by two faces' metrics, and measuring it all
        // with the first gives a line the wrong length wherever the second one
        // writes. So the substitute enters through the width closure the
        // layout is built from, not only through the encoder.
        let da_charset = named.map_or(pdfrum_font::Charset::Ansi, font_map::font_charset);
        let substitute = fonts.and_then(|fonts| {
            font_map::SUBSTITUTABLE_CHARSETS
                .iter()
                .find(|charset| **charset != da_charset)
                .and_then(|charset| fonts.substitute(*charset))
        });
        let width = named.map(|font| {
            move |code: u32| match substitute {
                Some(sub) if !font_map::da_font_writes(font, da_charset, code) => {
                    font_map::substitute_width(sub.font, code)
                }
                _ => TextFont::char_width(font, code),
            }
        });
        let text_font = named.zip(width.as_ref()).map(|(font, width)| TextFont {
            metrics: TextFont::metrics_of(font, width),
            font,
        });
        let generated = generate_one(&dict, r, diags)
            .or_else(|| generate_text_bearing(&dict, catalog, text_font.as_ref(), r, diags))
            .or_else(|| {
                // A widget's own body needs the same font the free-text
                // generator wanted, so a caller with one gets the field's
                // value laid out and a caller without one gets the chrome
                // alone.
                match text_font.as_ref() {
                    Some(font) => widget::generate_with_text(&dict, catalog, font, substitute, r),
                    None => widget::generate(&dict, r),
                }
                .inspect(|_| {
                    diags.record(Severity::Recovered, DiagKind::AppearanceGenerated, None);
                })
            });
        if let Some(generated) = generated {
            overlay.set(index, generated);
        }
    }
    overlay
}

/// The `/DR /Font` resource name one annotation's default appearance names.
///
/// Falls back to the form's own `/DA`, then to nothing — and nothing resolves
/// to [`FormFonts`]'s fallback face rather than declining.
fn font_name_of<R: Resolve>(dict: &Dict, catalog: &Dict, r: &R) -> Vec<u8> {
    let form = catalog.dict(names::ACRO_FORM, r).unwrap_or_default();
    freetext::default_appearance(dict, &form, r)
        .map(|appearance| appearance.font_name)
        .unwrap_or_default()
}

/// The free-text generator, when its preconditions and a font allow.
fn generate_text_bearing<R: Resolve>(
    dict: &Dict,
    catalog: &Dict,
    text_font: Option<&TextFont<'_>>,
    r: &R,
    diags: &mut Diagnostics,
) -> Option<GeneratedAp> {
    if !should_generate(dict, r) {
        return None;
    }
    let subtype = Subtype::from_bytes(&dict.byte_string(obj_names::SUBTYPE, r).unwrap_or_default());
    if subtype != Subtype::FreeText {
        return None;
    }
    let font = text_font?;
    let generated = freetext::free_text(
        dict,
        catalog,
        r,
        &font.metrics,
        &|code| font.encode(code),
        diags,
    )?;
    diags.record(Severity::Recovered, DiagKind::AppearanceGenerated, None);
    Some(GeneratedAp {
        stream: generated.stream,
        bbox: dict.rect(obj_names::RECT, r),
        matrix: Affine::IDENTITY,
        resources: resources_dict(
            ext_gstate_dict(dict, false, r),
            generated.font_resources.clone(),
        ),
        rect_override: None,
        as_override: None,
    })
}

/// Generates one annotation's appearance, if it should have one.
#[must_use]
pub(crate) fn generate_one<R: Resolve>(
    dict: &Dict,
    r: &R,
    diags: &mut Diagnostics,
) -> Option<GeneratedAp> {
    if !should_generate(dict, r) {
        return None;
    }
    let subtype = Subtype::from_bytes(&dict.byte_string(obj_names::SUBTYPE, r).unwrap_or_default());
    let generated = match subtype {
        Subtype::Circle => markup::circle(dict, r),
        Subtype::Highlight => markup::highlight(dict, r),
        Subtype::Ink => markup::ink(dict, r, diags)?,
        Subtype::Square => markup::square(dict, r),
        Subtype::Squiggly => markup::squiggly(dict, r),
        Subtype::StrikeOut => markup::strike_out(dict, r),
        Subtype::Text => markup::text(dict, r),
        Subtype::Underline => markup::underline(dict, r),
        // Everything else has no generator. The two text-bearing subtypes —
        // free text and pop-ups — do have one upstream, but it needs the
        // layout engine and is built on top of this dispatch rather than
        // inside it, so they answer the same way here.
        _ => return None,
    };
    diags.record(Severity::Recovered, DiagKind::AppearanceGenerated, None);

    // The bounding box is the annotation's rectangle **as it stands after
    // this generator ran** — so a sticky note's is the 20×20 box it just
    // produced, not the one the file declared.
    let rect = generated
        .rect_override
        .unwrap_or_else(|| dict.rect(obj_names::RECT, r));
    let bbox = if generated.is_text_markup {
        quad::bounding_rect_from_quad_points(dict.array(names::QUAD_POINTS, r).as_ref())
    } else {
        rect
    };
    Some(GeneratedAp {
        stream: generated.stream,
        bbox,
        matrix: Affine::IDENTITY,
        resources: resources_dict(
            ext_gstate_dict(dict, generated.blend_multiply, r),
            generated.font_resources.clone(),
        ),
        rect_override: generated.rect_override,
        as_override: None,
    })
}

/// Whether an annotation is eligible for a generated appearance.
///
/// Two gates. A **dictionary-valued** `/AP /N` suppresses generation, and a
/// stream answers as its own dictionary — so the common "it already has an
/// appearance" case and the multi-state checkbox case are the same test. And
/// a hidden annotation never generates.
#[must_use]
pub(crate) fn should_generate<R: Resolve>(dict: &Dict, r: &R) -> bool {
    if appearance::has_appearance(dict, r) {
        return false;
    }
    let flags = crate::annot::AnnotFlags::from_bits(dict.int(names::F, r).unwrap_or(0));
    !flags.is_hidden()
}

/// The graphics-state dictionary a generated appearance names.
///
/// Both alphas take the annotation's `/CA` when the key is present, whatever
/// its type reads as, and one otherwise. Only the highlight generator asks
/// for a blend mode other than normal.
#[must_use]
pub(crate) fn ext_gstate_dict<R: Resolve>(dict: &Dict, multiply: bool, r: &R) -> Dict {
    let opacity = if dict.contains_key(names::CA) {
        dict.number(names::CA, r).unwrap_or(0.0)
    } else {
        1.0
    };
    let blend = if multiply {
        names::MULTIPLY
    } else {
        obj_names::NORMAL
    };
    let state = Dict::from_pairs([
        (
            obj_names::TYPE.clone(),
            Object::Name(names::EXT_G_STATE.clone()),
        ),
        (names::CA.clone(), Object::Real(opacity)),
        (names::CA_LOWER.clone(), Object::Real(opacity)),
        (names::AIS.clone(), Object::Bool(false)),
        (names::BM.clone(), Object::Name(blend.clone())),
    ]);
    Dict::from_pairs([(names::GS.clone(), Object::Dict(state))])
}

/// The appearance stream's `/Resources`, omitting either half when absent.
#[must_use]
pub(crate) fn resources_dict(ext_gstate: Dict, font: Option<Dict>) -> Dict {
    let mut resources = Dict::new();
    resources.push(names::EXT_G_STATE.clone(), Object::Dict(ext_gstate));
    if let Some(font) = font {
        resources.push(names::FONT.clone(), Object::Dict(font));
    }
    resources
}

/// The stream dictionary a generated appearance is stored under.
///
/// ```
/// use pdfrum_common::Diagnostics;
/// use pdfrum_doc::ap::generate_appearances;
/// use pdfrum_object::{Array, Dict, Name, NoResolve, Object};
///
/// let square = Dict::from_pairs([
///     (Name::from("Subtype"), Object::Name(Name::from("Square"))),
///     (
///         Name::from("Rect"),
///         Object::Array(Array::of([0, 0, 100, 50].map(Object::from))),
///     ),
///     (
///         Name::from("IC"),
///         Object::Array(Array::of([1, 0, 0].map(Object::from))),
///     ),
/// ]);
/// let page = Dict::from_pairs([(
///     Name::from("Annots"),
///     Object::Array(Array::of([Object::Dict(square)])),
/// )]);
///
/// let mut diags = Diagnostics::default();
/// let overlay = generate_appearances(&page, &NoResolve, &mut diags);
/// use pdfrum_doc::ap::stream_dict;
/// use pdfrum_object::names;
///
/// let dict = stream_dict(overlay.get(0).expect("generated"));
/// assert_eq!(dict.name(names::SUBTYPE).map(|n| n.as_bytes().to_vec()),
///     Some(b"Form".to_vec()));
/// ```
#[must_use]
pub fn stream_dict(generated: &GeneratedAp) -> Dict {
    Dict::from_pairs([
        (names::FORM_TYPE.clone(), Object::Int(1)),
        (
            obj_names::TYPE.clone(),
            Object::Name(names::XOBJECT.clone()),
        ),
        (
            obj_names::SUBTYPE.clone(),
            Object::Name(names::FORM.clone()),
        ),
        (
            names::MATRIX.clone(),
            Object::Array(matrix_array(generated.matrix)),
        ),
        (
            names::BBOX.clone(),
            Object::Array(rect_array(generated.bbox)),
        ),
        (
            names::RESOURCES.clone(),
            Object::Dict(generated.resources.clone()),
        ),
        (
            names::LENGTH.clone(),
            Object::Int(i64::try_from(generated.stream.len()).unwrap_or(0)),
        ),
    ])
}

/// A transform as its six numbers.
///
/// Narrowed to single precision because that is what a PDF real is; the
/// transforms these generators write are all exactly representable anyway.
#[allow(clippy::cast_possible_truncation)]
fn matrix_array(matrix: Affine) -> Array {
    Array::of(
        matrix
            .as_coeffs()
            .into_iter()
            .map(|value| Object::Real(value as f32)),
    )
}

/// A rectangle as its four corner numbers, in PDF's ordering.
fn rect_array(rect: Rect) -> Array {
    use crate::geom;
    Array::of(
        [
            geom::left(rect),
            geom::bottom(rect),
            geom::right(rect),
            geom::top(rect),
        ]
        .map(Object::Real),
    )
}

#[cfg(test)]
mod tests {
    use super::{
        AnnotOverlay, Appearance, GeneratedAp, ext_gstate_dict, generate_appearances, generate_one,
        should_generate,
    };
    use crate::geom;
    use pdfrum_common::Diagnostics;
    use pdfrum_object::{Array, ByteSpan, Dict, Name, NoResolve, Object, Resolve, Stream};

    fn dict(pairs: &[(&str, Object)]) -> Dict {
        Dict::from_pairs(
            pairs
                .iter()
                .map(|(k, v)| (Name::from(*k), v.clone()))
                .collect::<Vec<_>>(),
        )
    }

    fn numbers(values: &[f32]) -> Object {
        Object::Array(Array::of(values.iter().copied().map(Object::from)))
    }

    /// A map-backed [`Resolve`], for the key tests: what a font dictionary
    /// *resolves to* is irrelevant to the slot it is filed under, but the
    /// walk to it goes through `/AcroForm` and `/DR`, so the references on
    /// the way have to lead somewhere.
    struct Store(std::collections::HashMap<u32, std::sync::Arc<Object>>);

    impl Store {
        fn of(pairs: impl IntoIterator<Item = (u32, Object)>) -> Store {
            Store(
                pairs
                    .into_iter()
                    .map(|(num, obj)| (num, std::sync::Arc::new(obj)))
                    .collect(),
            )
        }
    }

    impl Resolve for Store {
        fn fetch(
            &self,
            r: pdfrum_object::ObjRef,
        ) -> Result<std::sync::Arc<Object>, pdfrum_object::Error> {
            self.0
                .get(&r.num)
                .map(std::sync::Arc::clone)
                .ok_or(pdfrum_object::Error::UnresolvedRef(r))
        }
    }

    fn reference(num: u32) -> Object {
        Object::Ref(pdfrum_object::ObjRef::new(num, 0))
    }

    fn sticky_note() -> Dict {
        dict(&[
            ("Subtype", Object::Name(Name::from("Text"))),
            ("Rect", numbers(&[10.0, 20.0, 200.0, 300.0])),
        ])
    }

    #[test]
    fn an_annotation_with_an_appearance_stream_generates_nothing() {
        let with_ap = dict(&[
            ("Subtype", Object::Name(Name::from("Text"))),
            (
                "AP",
                Object::Dict(dict(&[(
                    "N",
                    Object::Stream(Box::new(Stream::new(
                        Dict::new(),
                        ByteSpan::from(b"x".to_vec()),
                    ))),
                )])),
            ),
        ]);
        assert!(!should_generate(&with_ap, &NoResolve));
        assert!(should_generate(&sticky_note(), &NoResolve));
    }

    #[test]
    fn a_hidden_annotation_never_generates() {
        let mut hidden = sticky_note();
        hidden.push(Name::from("F"), Object::Int(2));
        assert!(!should_generate(&hidden, &NoResolve));
    }

    #[test]
    fn a_character_the_face_cannot_map_is_still_written() {
        // `bug_725389` shows three Hebrew characters through a `/DA` naming
        // Times-Roman, which has no glyph for any of them. Dropping them loses
        // the text objects entirely — six become three — where the oracle
        // writes the raw code point as a character code and draws whatever it
        // names. Wrong glyph, right object count, right layout.
        let font = pdfrum_font::Font::load_standard(
            pdfrum_font::StandardFont::Times,
            &pdfrum_font::FontCache::new(),
        );
        let width = |code: u32| super::TextFont::char_width(&font, code);
        let text = super::TextFont {
            metrics: super::TextFont::metrics_of(&font, &width),
            font: &font,
        };
        // Hebrew bet, which no standard Latin face encodes.
        assert_eq!(text.encode(0x05D1), vec![0xD1]);
        // And a character it does encode still round-trips through the
        // `ToUnicode` mapping rather than through the fallthrough.
        assert_eq!(text.encode(u32::from('A')), vec![b'A']);
        // The width follows whatever `encode` wrote, so the layout advances by
        // the same glyph the stream names.
        assert_eq!(
            super::TextFont::char_width(&font, 0x05D1),
            super::TextFont::char_width(&font, 0xD1)
        );
    }

    #[test]
    fn a_sticky_notes_rectangle_override_reaches_the_overlay() {
        let page = dict(&[(
            "Annots",
            Object::Array(Array::of([Object::Dict(sticky_note())])),
        )]);
        let mut diags = Diagnostics::default();
        let overlay = generate_appearances(&page, &NoResolve, &mut diags);
        assert_eq!(overlay.len(), 1);
        let raw = geom::rect(10.0, 20.0, 200.0, 300.0);
        assert_eq!(overlay.rect(0, raw), geom::rect(10.0, 20.0, 30.0, 40.0));
        // The bounding box follows the rewritten rectangle, not the file's.
        assert_eq!(
            overlay.get(0).map(|generated| generated.bbox),
            Some(geom::rect(10.0, 20.0, 30.0, 40.0))
        );
    }

    #[test]
    fn a_pop_up_written_into_the_file_is_skipped_by_the_walk() {
        let page = dict(&[(
            "Annots",
            Object::Array(Array::of([Object::Dict(dict(&[(
                "Subtype",
                Object::Name(Name::from("Popup")),
            )]))])),
        )]);
        let mut diags = Diagnostics::default();
        let overlay = generate_appearances(&page, &NoResolve, &mut diags);
        // The slot still exists — indices stay aligned with `/Annots` — but
        // nothing was generated into it.
        assert_eq!(overlay.len(), 1);
        assert!(overlay.get(0).is_none());
    }

    #[test]
    fn a_subtype_with_no_generator_produces_nothing() {
        let stamp = dict(&[("Subtype", Object::Name(Name::from("Stamp")))]);
        let mut diags = Diagnostics::default();
        assert!(generate_one(&stamp, &NoResolve, &mut diags).is_none());
    }

    #[test]
    fn a_text_markup_bounding_box_comes_from_the_quadrilaterals() {
        let highlight = dict(&[
            ("Subtype", Object::Name(Name::from("Highlight"))),
            ("Rect", numbers(&[0.0, 0.0, 5.0, 5.0])),
            (
                "QuadPoints",
                numbers(&[10.0, 20.0, 30.0, 20.0, 10.0, 10.0, 30.0, 10.0]),
            ),
        ]);
        let mut diags = Diagnostics::default();
        let got = generate_one(&highlight, &NoResolve, &mut diags).expect("generates");
        assert_eq!(got.bbox, geom::rect(10.0, 10.0, 30.0, 20.0));
    }

    #[test]
    fn the_graphics_state_takes_its_alpha_from_the_opacity_key() {
        let opaque = ext_gstate_dict(&Dict::new(), false, &NoResolve);
        let state = opaque
            .dict(&Name::from("GS"), &NoResolve)
            .expect("one entry");
        assert_eq!(state.number(&Name::from("CA"), &NoResolve), Some(1.0));
        assert_eq!(
            state.name(&Name::from("BM")).map(Name::as_bytes),
            Some(&b"Normal"[..])
        );

        let half = dict(&[("CA", Object::from(0.5_f32))]);
        let state = ext_gstate_dict(&half, true, &NoResolve)
            .dict(&Name::from("GS"), &NoResolve)
            .expect("one entry");
        assert_eq!(state.number(&Name::from("ca"), &NoResolve), Some(0.5));
        assert_eq!(
            state.name(&Name::from("BM")).map(Name::as_bytes),
            Some(&b"Multiply"[..])
        );
    }

    /// A generated appearance, distinguishable by its stream.
    fn made(stream: &str) -> GeneratedAp {
        GeneratedAp {
            stream: stream.as_bytes().to_vec(),
            bbox: geom::rect(0.0, 0.0, 1.0, 1.0),
            matrix: kurbo::Affine::IDENTITY,
            resources: Dict::default(),
            rect_override: None,
            as_override: None,
        }
    }

    /// The merge's whole contract in one test: the supplied overlay wins
    /// where it speaks, defers where it does not, and can say "draw nothing"
    /// as a value rather than as an absence.
    #[test]
    fn a_supplied_overlay_wins_only_where_it_has_something_to_say() {
        let mut base = AnnotOverlay::with_capacity(4);
        base.set(0, made("base zero"));
        base.set(1, made("base one"));
        base.set(2, made("base two"));

        let mut supplied = AnnotOverlay::with_capacity(4);
        supplied.set(1, made("live one"));
        supplied.set_appearance(2, Appearance::Suppressed);
        // Index 0 and 3 are untouched and must not disturb the base.

        base.merge_over(&supplied);

        assert_eq!(
            base.get(0).map(|g| g.stream.clone()),
            Some(b"base zero".to_vec()),
            "an untouched entry leaves the generated one alone"
        );
        assert_eq!(
            base.get(1).map(|g| g.stream.clone()),
            Some(b"live one".to_vec()),
            "a supplied entry replaces the generated one"
        );
        assert_eq!(
            base.appearance(2),
            &Appearance::Suppressed,
            "suppression survives the merge as a value"
        );
        assert_eq!(base.get(2), None, "a suppressed entry has no stream");
        assert_eq!(base.appearance(3), &Appearance::Untouched);
    }

    /// Suppression and absence read the same to `get` and differently to
    /// `appearance` — which is the distinction the enum exists to carry.
    #[test]
    fn suppressed_and_untouched_differ_only_where_it_matters() {
        let mut overlay = AnnotOverlay::with_capacity(2);
        overlay.set_appearance(0, Appearance::Suppressed);
        assert_eq!(overlay.get(0), None);
        assert_eq!(overlay.get(1), None);
        assert_ne!(overlay.appearance(0), overlay.appearance(1));
        // An index past the end is untouched rather than a panic, so a short
        // overlay is safe to consult for any annotation.
        assert_eq!(overlay.appearance(99), &Appearance::Untouched);
    }

    /// An entry past the end of the overlay being merged into is dropped:
    /// there is no annotation for it to apply to.
    #[test]
    fn a_supplied_entry_past_the_end_is_dropped() {
        let mut base = AnnotOverlay::with_capacity(1);
        let mut supplied = AnnotOverlay::with_capacity(5);
        supplied.set(4, made("nowhere"));
        base.merge_over(&supplied);
        assert_eq!(base.len(), 1);
        assert_eq!(base.get(4), None);
    }

    #[test]
    fn only_the_named_annotation_is_a_live_edit() {
        let mut overlay = AnnotOverlay::with_capacity(3);
        overlay.set(0, made("a"));
        overlay.set(1, made("b"));
        assert_eq!(overlay.live_edit(), None);
        assert!(!overlay.is_live_edit(0));
        overlay.set_live_edit(1);
        assert_eq!(overlay.live_edit(), Some(1));
        assert!(overlay.is_live_edit(1));
        // Every other annotation's appearance is an ordinary one, which is
        // what keeps ClearType off the rest of the page.
        assert!(!overlay.is_live_edit(0));
        assert!(!overlay.is_live_edit(2));
    }

    #[test]
    fn a_session_editing_a_second_field_replaces_the_first() {
        // One field is edited at a time, so this is a replacement rather than
        // a set: a stale mark would draw a field's committed text with
        // ClearType long after the editor left it.
        let mut overlay = AnnotOverlay::with_capacity(3);
        overlay.set_live_edit(0);
        overlay.set_live_edit(2);
        assert_eq!(overlay.live_edit(), Some(2));
        assert!(!overlay.is_live_edit(0));
    }

    #[test]
    fn merging_carries_the_live_edit_mark_over() {
        // The mark has to survive `merge_over` or it would be lost exactly
        // where it matters — the supplied overlay is the session's, and the
        // base is what the annotation pass generated.
        let mut base = AnnotOverlay::with_capacity(2);
        let mut supplied = AnnotOverlay::with_capacity(2);
        supplied.set(1, made("edited"));
        supplied.set_live_edit(1);
        base.merge_over(&supplied);
        assert!(base.is_live_edit(1));
        // And a merge that says nothing about it leaves the mark alone.
        let untouched = AnnotOverlay::with_capacity(2);
        base.merge_over(&untouched);
        assert!(base.is_live_edit(1));
    }

    #[test]
    fn the_form_faces_are_built_once_per_document_and_shared() {
        // `FormFonts::load` builds `/DR` fonts, the fallback, and the
        // synthesized second faces once per document; the annotation overlay
        // calls it once per page per render.
        let catalog = dict(&[("AcroForm", Object::Ref(pdfrum_object::ObjRef::new(7, 0)))]);
        let mut ctx = pdfrum_page::BuildContext::new();
        let first = super::FormFonts::load(&catalog, &NoResolve, &mut ctx);
        let second = super::FormFonts::load(&catalog, &NoResolve, &mut ctx);
        assert!(
            std::sync::Arc::ptr_eq(&first, &second),
            "a second load of one document's form must hit the cache"
        );
    }

    #[test]
    fn a_catalog_with_no_form_shares_one_set_of_faces() {
        // The case that made this a whole-corpus regression rather than a
        // forms one: a document with an annotation but no `/AcroForm` paid
        // the fallback load and the substitute synthesis on every render.
        // With no form there is nothing document-specific to build, so one
        // slot serves every such document a context is threaded through.
        let mut ctx = pdfrum_page::BuildContext::new();
        let first = super::FormFonts::load(&dict(&[]), &NoResolve, &mut ctx);
        let second = super::FormFonts::load(
            &dict(&[("Type", Object::Name(Name::from("Catalog")))]),
            &NoResolve,
            &mut ctx,
        );
        assert!(std::sync::Arc::ptr_eq(&first, &second));
    }

    #[test]
    fn two_documents_do_not_share_one_contexts_form_faces() {
        // A `BuildContext` may legitimately be threaded through two
        // documents, so the cache keys on the `/AcroForm` reference the way
        // every other cache on it keys on the reference that named its value.
        let mut ctx = pdfrum_page::BuildContext::new();
        let one = super::FormFonts::load(
            &dict(&[("AcroForm", Object::Ref(pdfrum_object::ObjRef::new(7, 0)))]),
            &NoResolve,
            &mut ctx,
        );
        let two = super::FormFonts::load(
            &dict(&[("AcroForm", Object::Ref(pdfrum_object::ObjRef::new(8, 0)))]),
            &NoResolve,
            &mut ctx,
        );
        assert!(!std::sync::Arc::ptr_eq(&one, &two));
    }

    /// A `/DR /Font` written out in full, which is the one spelling with no
    /// reference anywhere for the key to name.
    fn wholly_direct_form() -> Dict {
        dict(&[(
            "DR",
            Object::Dict(dict(&[(
                "Font",
                Object::Dict(dict(&[("Helv", Object::Dict(dict(&[])))])),
            )])),
        )])
    }

    #[test]
    fn a_form_whose_fonts_are_written_out_in_full_is_not_cached() {
        // The one case that stays uncached: a direct `/AcroForm` whose
        // `/DR /Font` is itself direct has no reference at either level, and
        // its content *is* document-specific, so it re-derives rather than
        // risking one document's faces standing in for another's.
        let catalog = dict(&[("AcroForm", Object::Dict(wholly_direct_form()))]);
        let mut ctx = pdfrum_page::BuildContext::new();
        let first = super::FormFonts::load(&catalog, &NoResolve, &mut ctx);
        let second = super::FormFonts::load(&catalog, &NoResolve, &mut ctx);
        assert!(!std::sync::Arc::ptr_eq(&first, &second));
    }

    #[test]
    fn a_direct_form_declaring_no_fonts_is_the_no_form_case() {
        // What the corpus actually carries. `<</Fields[]>>` written straight
        // into the catalog is what a producer emits when it declares a form
        // and puts no fields in it, and six of the 44 benchmark documents
        // have one — none of them a form document. It names no `/DR /Font`,
        // so its faces are the fallback and the substitutes, built from
        // dictionaries this crate writes: the same value a catalog with no
        // `/AcroForm` at all gets, and therefore the same slot.
        let mut ctx = pdfrum_page::BuildContext::new();
        let empty_form = super::FormFonts::load(
            &dict(&[(
                "AcroForm",
                Object::Dict(dict(&[("Fields", Object::Array(Array::default()))])),
            )]),
            &NoResolve,
            &mut ctx,
        );
        let no_form = super::FormFonts::load(&dict(&[]), &NoResolve, &mut ctx);
        assert!(
            std::sync::Arc::ptr_eq(&empty_form, &no_form),
            "a form with no default resources builds nothing a form-less \
             catalog does not"
        );
    }

    #[test]
    fn a_direct_form_is_keyed_on_the_font_dictionary_it_names() {
        // The ordinary spelling of an unusual case: the `/AcroForm` is
        // direct but its `/DR /Font` is a reference, which is as good an
        // identity as the form's own reference would have been. Two catalogs
        // naming *different* font dictionaries must not share, and one
        // catalog asked twice must.
        let form = |num: u32| {
            dict(&[(
                "AcroForm",
                Object::Dict(dict(&[(
                    "DR",
                    Object::Dict(dict(&[("Font", reference(num))])),
                )])),
            )])
        };
        let store = Store::of([(7, Object::Dict(dict(&[]))), (8, Object::Dict(dict(&[])))]);
        let mut ctx = pdfrum_page::BuildContext::new();
        let first = super::FormFonts::load(&form(7), &store, &mut ctx);
        let again = super::FormFonts::load(&form(7), &store, &mut ctx);
        let other = super::FormFonts::load(&form(8), &store, &mut ctx);
        assert!(
            std::sync::Arc::ptr_eq(&first, &again),
            "one font dictionary asked twice must hit the cache"
        );
        assert!(
            !std::sync::Arc::ptr_eq(&first, &other),
            "two font dictionaries must not share a slot"
        );
    }

    #[test]
    fn the_key_reads_the_font_dictionarys_spelling_and_not_its_value() {
        // The four cases, asserted directly rather than through the ptr
        // identity the three tests above compare. This is the function's
        // whole contract: which of the four slots a catalog lands in.
        use pdfrum_page::FormFontsKey;
        let store = Store::of([(7, Object::Dict(dict(&[])))]);
        let key = |catalog: &Dict| super::FormFonts::key(catalog, &store);

        assert_eq!(key(&dict(&[])), FormFontsKey::None);
        assert_eq!(
            key(&dict(&[("AcroForm", reference(7))])),
            FormFontsKey::Form(pdfrum_object::ObjRef::new(7, 0))
        );
        assert_eq!(
            key(&dict(&[(
                "AcroForm",
                Object::Dict(dict(&[("Fields", Object::Array(Array::default()))]))
            )])),
            FormFontsKey::None,
            "a direct form with no `/DR /Font` depends on nothing"
        );
        assert_eq!(
            key(&dict(&[(
                "AcroForm",
                Object::Dict(dict(&[(
                    "DR",
                    Object::Dict(dict(&[("Font", reference(7))]))
                )]))
            )])),
            FormFontsKey::DirectResources(pdfrum_object::ObjRef::new(7, 0))
        );
        assert_eq!(
            key(&dict(&[("AcroForm", Object::Dict(wholly_direct_form()))])),
            FormFontsKey::Direct
        );
    }

    #[test]
    fn an_overlay_that_marks_no_live_edit_leaves_every_index_ordinary() {
        // The default, and the whole corpus outside the form-events rows.
        let mut overlay = AnnotOverlay::with_capacity(4);
        overlay.set(2, made("generated"));
        assert_eq!(overlay.live_edit(), None);
        for index in 0..6 {
            assert!(!overlay.is_live_edit(index), "index {index}");
        }
    }
}