flpdf 0.2.1

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
//! Overlay/underlay annotation copy, mirroring qpdf 11.9.0's
//! `QPDFPageObjectHelper::copyAnnotations` +
//! `QPDFAcroFormDocumentHelper::transformAnnotations` +
//! `QPDFAcroFormDocumentHelper::addAndRenameFormFields`
//! (`libqpdf/QPDFPageObjectHelper.cc:991-1039`,
//! `libqpdf/QPDFAcroFormDocumentHelper.cc:698-1014`,
//! `libqpdf/QPDFAcroFormDocumentHelper.cc:61-110`).
//!
//! Split into two phases so the cross-document copy runs exactly once per
//! source document (unioned with the Form XObject closure), matching qpdf's
//! per-document `copyForeignObject` foreign→local map:
//!
//! 1. [`survey_source_annotations`] — walk the source page's `/Annots` in
//!    source space and return the reachable-ref closure to add to the batch
//!    [`copy_objects`](crate::object_copy::copy_objects) call, alongside a
//!    survey describing the per-annot top-level field and (when present) the
//!    source `/AcroForm/DR` ref.
//! 2. [`template_from_survey`] — after the batch copy returns its map, remap
//!    the survey's source-space refs into dest-space refs.
//! 3. [`apply_placement`] — per placement, shallow-duplicate each annotation
//!    (and its field-tree top) so that repeated placements of the same source
//!    page do NOT share (transformation would otherwise cumulate), transform
//!    `/Rect` and each `/AP` stream's `/Matrix` by `cm`, reset field `/DR`
//!    references to the dest AcroForm `/DR`, and append the transformed annots
//!    to the destination page `/Annots`. Returns the list of new top-level
//!    field dest refs added by this placement.
//! 4. [`add_and_rename_form_fields`] — once per destination page after all
//!    placements: BFS the collected new top-level fields, rename `/T` on
//!    fully-qualified-name collision with existing dest fields, and append to
//!    `/AcroForm/Fields`.

use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};

use crate::acroform_document_helper::{collect_reachable_refs, collect_refs_in_object};
use crate::overlay_appearance_stream::adjust_appearance_stream;
use crate::parser::{is_delimiter, is_ws, Parser};
use crate::{Error, Object, ObjectRef, Pdf, Result};

/// Bound field-tree /Parent walks (widget → top-level field). Mirrors the
/// `DEFAULT_MAX_ACROFORM_DEPTH` cap used elsewhere in the crate (review rule 4:
/// graph traversals must have a depth cap against hostile input).
const MAX_PARENT_WALK_DEPTH: usize = 100;

/// Per-placement inherited-field override plan derived from the source and
/// dest `/AcroForm`'s `/DA` and `/Q` defaults, consumed by
/// [`adjust_inherited_field`] during the field-tree BFS. See qpdf
/// `transformAnnotations` line 737-767 (flag computation) and
/// `adjustInheritedFields` (`libqpdf/QPDFAcroFormDocumentHelper.cc:442-484`).
///
/// When `override_da` is false, `/DA` is left untouched on every field even
/// if `from_default_da` is set; same for `/Q`.
struct InheritedOverrides {
    override_da: bool,
    from_default_da: Vec<u8>,
    override_q: bool,
    from_default_q: i64,
}

/// Survey of a source page's annotation graph, in SOURCE object space,
/// computed BEFORE the cross-document copy.
#[derive(Debug, Default)]
pub(crate) struct AnnotationSurvey {
    /// One entry per source annotation in `/Annots` array order:
    /// `(annot_ref, Option<top_level_field_ref>)`. `None` when the annot is
    /// not a widget or is a widget without an associated form field.
    pub annots: Vec<(ObjectRef, Option<ObjectRef>)>,
    /// Source `/AcroForm/DR` ref, if present.
    pub source_dr: Option<ObjectRef>,
    /// Source `/AcroForm/DA` (raw string bytes) — feeds
    /// `adjustInheritedFields` on the dest side.
    pub source_default_da: Option<Vec<u8>>,
    /// Source `/AcroForm/Q` integer — same as above.
    pub source_default_q: Option<i64>,
}

/// Dest-space refs derived from an [`AnnotationSurvey`] after cross-doc copy;
/// consumed by [`apply_placement`] once per placement.
#[derive(Debug, Default, Clone)]
pub(crate) struct AnnotationCopyTemplate {
    /// Dest-space per-annot pairs, in the same order as the survey.
    pub annots: Vec<(ObjectRef, Option<ObjectRef>)>,
    /// Dest-space source `/DR` ref, if the source had one.
    pub source_dr: Option<ObjectRef>,
    /// Source `/AcroForm/DA` bytes (verbatim from the source).
    pub source_default_da: Option<Vec<u8>>,
    /// Source `/AcroForm/Q` integer.
    pub source_default_q: Option<i64>,
}

/// Walk a source page's `/Annots` and return:
/// - the [`AnnotationSurvey`] (source-space refs and inherited defaults),
/// - the reachable-ref closure to add to a batch
///   [`copy_objects`](crate::object_copy::copy_objects) call so the annots,
///   their fields, appearance streams, and the source `/AcroForm/DR` fonts
///   are copied into the destination in one pass (advisor: one shared
///   foreign→local map per source document prevents duplicated fonts).
///
/// Returns `Ok(None)` when the source page has no `/Annots` array (nothing to
/// copy) — the caller should skip the placement's annotation phase entirely.
///
/// # Errors
///
/// Propagates any error from [`Pdf::resolve`] or from
/// [`collect_reachable_refs`] (excessive graph depth on hostile input).
pub(crate) fn survey_source_annotations<R: Read + Seek>(
    source: &mut Pdf<R>,
    source_page_ref: ObjectRef,
) -> Result<Option<(AnnotationSurvey, BTreeSet<ObjectRef>)>> {
    // 1. Read the page's /Annots (may be inline array or an indirect ref to one).
    // cov:ignore-start: /Annots shape guards. The exercised shapes are
    // "direct array" (primary target) and "no /Annots" (implicit via page
    // without annots); the remaining arms (non-dict page, missing/Null
    // /Annots, indirect Reference→array, indirect Reference→non-array,
    // /Annots is neither Array/Reference/Null) are malformed-input
    // branches without a corresponding qpdf-oracle golden.
    let annots_val = {
        let obj = source.resolve_borrowed(source_page_ref)?;
        let Some(dict) = obj.as_dict() else {
            return Ok(None);
        };
        dict.get("Annots").cloned()
    };
    let annots_array = match annots_val {
        None | Some(Object::Null) => return Ok(None),
        Some(Object::Array(arr)) => arr,
        Some(Object::Reference(r)) => match source.resolve(r)? {
            Object::Array(arr) => arr,
            _ => return Ok(None),
        },
        _ => return Ok(None),
    };
    if annots_array.is_empty() {
        return Ok(None);
    }
    // cov:ignore-end

    // 2. Enumerate annot refs. Indirect refs are used verbatim. Direct annot
    //    dictionaries and streams are materialized into fresh source-doc
    //    indirect objects (qpdf transformAnnotations line 954-956:
    //    `annot = from_qpdf->makeIndirectObject(annot)`) so the downstream
    //    copy path can treat every annot uniformly. Values that are neither
    //    a reference nor a dict/stream (Null padding, malformed entries) are
    //    silently skipped, matching qpdf's `annot.warnIfPossible("... stream")`
    //    branch behaviour of dropping the entry rather than aborting.
    let mut annots: Vec<(ObjectRef, Option<ObjectRef>)> = Vec::new();
    for item in annots_array {
        let annot_ref = match item {
            Object::Reference(r) => r,
            direct @ (Object::Dictionary(_) | Object::Stream(_)) => {
                let new_ref = allocate_next_ref(source)?;
                source.set_object(new_ref, direct);
                new_ref
            }
            _ => continue, // cov:ignore: /Annots entry is neither ref nor dict/stream — malformed
        };
        let top_field = top_level_field_for_annot(source, annot_ref)?;
        annots.push((annot_ref, top_field));
    }
    if annots.is_empty() {
        return Ok(None); // cov:ignore: every entry in a non-empty /Annots was malformed
    }

    // 3. Read the source /AcroForm/DR ref (added to the copy set below) and
    //    the inherited /DA / /Q defaults, used by `adjust_inherited_fields`
    //    on the dest side (qpdf QPDFAcroFormDocumentHelper.cc:442-484,
    //    called from transformAnnotations line 914-917). For the primary
    //    target (fxo-red + form-fields-and-annotations) the source /AcroForm
    //    has neither /DA nor /Q, so both defaults are `None` and the dest-side
    //    override is a no-op — the byte gate is unaffected.
    let (source_dr, source_default_da, source_default_q) = read_source_acroform_defaults(source)?;

    // 4. Build the reachable-ref closure to feed the batch copy_objects call.
    //    Every annot ref is seeded (with /P skipped, since a widget's /P is a
    //    page back-pointer that must not drag the source page into the copy
    //    closure). Every top-level field ref is seeded the same way. The
    //    source /DR value is seeded with /P collection ENABLED because a
    //    resource may legitimately be named /P.
    let mut closure: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
    for (annot_ref, top_field) in &annots {
        collect_reachable_refs(source, *annot_ref, &mut closure, &mut seen, 0, true)?;
        if let Some(tf) = top_field {
            collect_reachable_refs(source, *tf, &mut closure, &mut seen, 0, true)?;
        }
    }
    if let Some(dr_ref) = source_dr {
        // Same call shape as page_merge / source_field_copy_set for /DR: /P is
        // a resource name inside /DR, not a back-pointer, so skip_parent_key
        // is false.
        // cov:ignore-start: trailing `)?;` on a multi-line call — llvm-cov
        // attributes it to the Err path, defensive on collect_refs_in_object
        // failure that no shipped fixture reaches.
        collect_refs_in_object(
            source,
            &Object::Reference(dr_ref),
            &mut closure,
            &mut seen,
            0,
            0,
            false,
        )?;
        // cov:ignore-end
    }

    Ok(Some((
        AnnotationSurvey {
            annots,
            source_dr,
            source_default_da,
            source_default_q,
        },
        closure,
    )))
}

/// Walk `annot_ref`'s `/Parent` chain in source space to find its top-level
/// AcroForm field. Returns `None` when:
/// - `annot_ref` is not a widget (has no `/Subtype /Widget`), OR
/// - the annot is a widget but is not part of the field tree (no `/Parent`
///   AND its own `/T` is absent — it is a "self-field" so it is its own top),
///   in which case we DO return `Some(annot_ref)` when it looks like a field
///   itself (has any of `/T`, `/FT`, `/Kids`), matching qpdf's
///   `getFieldForAnnotation` + `getTopLevelField` composition.
///
/// Cycle-guarded by `visited` and depth-capped by [`MAX_PARENT_WALK_DEPTH`].
fn top_level_field_for_annot<R: Read + Seek>(
    source: &mut Pdf<R>,
    annot_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
    // Read the annot dict, deciding whether it is a widget and whether it
    // itself is a field.
    let (is_widget, is_field, parent_ref) = {
        let obj = source.resolve_borrowed(annot_ref)?;
        let Some(dict) = obj.as_dict() else {
            return Ok(None); // cov:ignore: annot ref resolves to non-dict — malformed source
        };
        let is_widget = matches!(
            dict.get("Subtype"),
            Some(Object::Name(name)) if name == b"Widget"
        );
        let is_field =
            dict.get("T").is_some() || dict.get("FT").is_some() || dict.get("Kids").is_some();
        let parent_ref = dict.get_ref("Parent");
        (is_widget, is_field, parent_ref)
    };
    if !is_widget {
        return Ok(None);
    }
    let mut current = if let Some(p) = parent_ref {
        p
    } else if is_field {
        // Widget IS its own field (self-field, no /Parent) — it is the top.
        return Ok(Some(annot_ref));
    } else {
        return Ok(None); // cov:ignore: widget without /Parent and without any field key — not a form field
    };
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    visited.insert(annot_ref);
    // cov:ignore-start: the loop body's defensive arms (cycle guard,
    // non-dict parent, depth overflow, unreachable `Some(p)` continuation
    // artifact) are hostile-input / llvm-cov artifacts; the "return
    // Ok(Some(current))" completion IS exercised by every widget with a
    // parent chain in the primary target.
    for _ in 0..MAX_PARENT_WALK_DEPTH {
        if !visited.insert(current) {
            return Ok(None); // /Parent cycle — malformed input
        }
        let parent_of_current = {
            let obj = source.resolve_borrowed(current)?;
            let Some(dict) = obj.as_dict() else {
                return Ok(None);
            };
            dict.get_ref("Parent")
        };
        match parent_of_current {
            Some(p) => current = p,
            None => return Ok(Some(current)),
        }
    }
    Err(Error::Unsupported(format!(
        "AcroForm /Parent chain from {annot_ref} exceeds maximum depth of {MAX_PARENT_WALK_DEPTH}"
    )))
    // cov:ignore-end
}

/// Read source `/AcroForm`'s `/DR` ref plus the inherited `/DA` and `/Q`
/// defaults. Returns `(None, None, None)` when the source has no
/// `/AcroForm`; missing individual keys stay `None`.
///
/// The defaults feed `adjust_inherited_fields` (qpdf
/// `QPDFAcroFormDocumentHelper::adjustInheritedFields`,
/// `libqpdf/QPDFAcroFormDocumentHelper.cc:442-484`, called from
/// `transformAnnotations` line 914-917) so a copied field that inherits
/// `/DA` or `/Q` from the source doc keeps rendering the same way when
/// the destination doc's defaults differ.
#[allow(clippy::type_complexity)]
fn read_source_acroform_defaults<R: Read + Seek>(
    source: &mut Pdf<R>,
) -> Result<(Option<ObjectRef>, Option<Vec<u8>>, Option<i64>)> {
    // cov:ignore-start: defensive AcroForm-shape guards — the exercised
    // shapes (missing AcroForm, direct dict, indirect Reference→dict) are
    // covered by primary/no-acroform/direct-DR fixtures; the remaining
    // arms (no /Root, catalog non-dict, /AcroForm non-Reference-non-Dict,
    // Reference resolving to non-dict) are malformed-input branches
    // without a corresponding qpdf-oracle golden.
    let Some(root_ref) = source.root_ref() else {
        return Ok((None, None, None));
    };
    let acroform_val = {
        let obj = source.resolve_borrowed(root_ref)?;
        let Some(dict) = obj.as_dict() else {
            return Ok((None, None, None));
        };
        dict.get("AcroForm").cloned()
    };
    let acroform_dict = match acroform_val {
        None | Some(Object::Null) => return Ok((None, None, None)),
        Some(Object::Dictionary(d)) => d,
        Some(Object::Reference(r)) => match source.resolve(r)? {
            Object::Dictionary(d) => d,
            _ => return Ok((None, None, None)),
        },
        _ => return Ok((None, None, None)),
    };
    // cov:ignore-end
    // /DR may be indirect (a Reference) or direct. Direct dicts get
    // materialized into a fresh source-doc indirect object so downstream
    // closure collection and `copy_objects` can treat every /DR uniformly
    // (mirrors qpdf transformAnnotations line 750-752, which promotes
    // from_dr with `from_qpdf->makeIndirectObject(from_dr)` before
    // `copyForeignObject`).
    let dr = match acroform_dict.get("DR").cloned() {
        Some(Object::Reference(r)) => Some(r),
        Some(dr_val @ (Object::Dictionary(_) | Object::Stream(_))) => {
            let new_ref = allocate_next_ref(source)?;
            source.set_object(new_ref, dr_val);
            Some(new_ref)
        }
        _ => None, // cov:ignore: fallback match arm — defensive/malformed input
    };
    let da = match acroform_dict.get("DA") {
        Some(Object::String(s)) => Some(s.clone()),
        _ => None,
    };
    let q = match acroform_dict.get("Q") {
        Some(Object::Integer(n)) => Some(*n),
        _ => None,
    };
    Ok((dr, da, q))
}

/// Materialize an [`AnnotationSurvey`]'s source-space refs into dest-space
/// refs using the `copy_map` returned by the batch cross-document copy.
///
/// Panics-free by construction: any survey ref that has no entry in `copy_map`
/// is dropped from the template (a widget without a mapped top-level field
/// falls back to `None`). This is a safety net — the survey and the copy
/// closure are built together, so a missing entry indicates a caller error.
///
pub(crate) fn template_from_survey(
    survey: &AnnotationSurvey,
    copy_map: &BTreeMap<ObjectRef, ObjectRef>,
) -> AnnotationCopyTemplate {
    let annots = survey
        .annots
        .iter()
        .filter_map(|(annot_ref, top_field)| {
            // A survey ref that is missing from the map indicates the closure
            // computation missed it; skip rather than panic (defensive).
            let dest_annot = *copy_map.get(annot_ref)?;
            let dest_top_field = top_field.and_then(|tf| copy_map.get(&tf).copied());
            Some((dest_annot, dest_top_field))
        })
        .collect();
    AnnotationCopyTemplate {
        annots,
        source_dr: survey.source_dr.and_then(|r| copy_map.get(&r).copied()),
        source_default_da: survey.source_default_da.clone(),
        source_default_q: survey.source_default_q,
    }
}

/// Per-destination record of resource-name renames, populated by
/// [`merge_resources_shallow`] when a source `/DR` sub-dictionary key
/// collides with an existing dest entry of the same name that resolves to a
/// *different* object.
///
/// Holds two internally-consistent views:
///
/// - `by_name`: outer key is the resource category (`Font`, `XObject`, ...);
///   inner map is `old_source_name -> new_dest_name`. Consumed by
///   [`adjust_default_appearance`] to rewrite the copied field's `/DA`
///   string (name-indexed because `/DA` operators reference names).
///   Overwritten across multi-source merges — reflects the most recent
///   merge's mappings (which is precisely what the current placement's
///   field-tree walk needs, because that walk immediately follows the
///   merge that populated the map).
///
/// - `by_source_ref`: (category, source `ObjectRef`) -> new dest name.
///   Stable across every merge into the same destination. Consulted by
///   [`merge_resources_shallow`]'s collision branch to reuse an existing
///   rename when the SAME source object recurs (across pages or across
///   overlay specs), even if `by_name` was overwritten by an intervening
///   merge with a different source that collided under the same old name.
///
/// Mirrors qpdf's per-destination `dr_map`, populated by
/// `QPDFObjectHandle::mergeResources`'s `conflicts` out-parameter and driven
/// by `QPDFAcroFormDocumentHelper::init_dr_map`
/// (`libqpdf/QPDFAcroFormDocumentHelper.cc:775-800`, called from
/// `transformAnnotations`). qpdf's reuse logic is source-object-identity
/// based, matching `by_source_ref` here.
#[derive(Debug, Default, Clone)]
pub(crate) struct DrMap {
    /// old source name -> new dest name, per resource category. Overwritten
    /// across merges of different sources that collide under the same name;
    /// consumers must use it before the next merge is called on the same
    /// destination.
    by_name: BTreeMap<Vec<u8>, BTreeMap<Vec<u8>, Vec<u8>>>,
    /// (category, source `ObjectRef`) -> dest name. Stable across every
    /// merge into the same destination; used to reuse a rename when the
    /// same source object recurs.
    by_source_ref: BTreeMap<(Vec<u8>, ObjectRef), Vec<u8>>,
}

impl DrMap {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Returns `true` when no rename has been recorded — the fast-path
    /// gate every consumer uses to skip work entirely.
    pub(crate) fn is_empty(&self) -> bool {
        self.by_name.is_empty()
    }

    /// The `old_name -> new_name` map for the given resource category, as
    /// populated by the most recent merge. Returned as a reference so
    /// callers (notably [`adjust_default_appearance`]) can look names up
    /// without needing internal mutation.
    pub(crate) fn category(&self, category: &[u8]) -> Option<&BTreeMap<Vec<u8>, Vec<u8>>> {
        self.by_name.get(category)
    }

    /// Every resource-type category with at least one recorded rename, as
    /// populated by the most recent merge. Mirrors qpdf iterating `dr_map`'s
    /// top-level keys in `AcroForm::adjustAppearanceStream`
    /// (`libqpdf/QPDFAcroFormDocumentHelper.cc:770-777`) to force each
    /// category's sub-dictionary to exist (unshared) in an appearance
    /// stream's own `/Resources` before renaming; see
    /// [`crate::overlay_appearance_stream::adjust_appearance_stream`].
    pub(crate) fn categories(&self) -> impl Iterator<Item = &Vec<u8>> {
        self.by_name.keys()
    }

    /// Record an additional `old -> new` rename under `category`, alongside
    /// whatever that category already holds. Used by
    /// [`crate::overlay_appearance_stream::adjust_appearance_stream`] to
    /// extend a **per-call, cloned** copy of this map (never the shared one
    /// threaded through every placement on a destination page) with the
    /// extra rename produced when privatizing one appearance stream's own
    /// `/Resources` uncovers a second-order name collision — mirroring
    /// qpdf's `dr_map` parameter to `AcroForm::adjustAppearanceStream` being
    /// passed **by value** (`libqpdf/QPDFAcroFormDocumentHelper.cc:752`), so
    /// mutations for one stream never leak into another placement's shared
    /// [`DrMap`].
    pub(crate) fn insert_rename(&mut self, category: &[u8], old: Vec<u8>, new: Vec<u8>) {
        self.by_name
            .entry(category.to_vec())
            .or_default()
            .insert(old, new);
    }
}

#[cfg(test)]
impl DrMap {
    /// Test-only constructor: a `DrMap` with exactly one category
    /// containing one `old -> new` rename, for unit tests elsewhere in the
    /// crate (notably `overlay_appearance_stream`'s `resource_replacer`
    /// tests) that need a populated map without driving a full
    /// [`merge_resources_shallow`] call through a real `Pdf`. `by_name` is
    /// otherwise private to this module.
    pub(crate) fn for_test(category: &[u8], old: &[u8], new: &[u8]) -> Self {
        let mut map = Self::new();
        map.by_name
            .entry(category.to_vec())
            .or_default()
            .insert(old.to_vec(), new.to_vec());
        map
    }
}

/// Per-placement annotation application:
/// - shallow-dup each templated annot (new indirect object) and any
///   associated top-level field / kid path (so repeated placements of the
///   same source page do not share cumulative /Rect transforms);
/// - shallow-dup each `/AP` stream and concatenate `cm` into its `/Matrix`
///   (identity when the stream had no /Matrix);
/// - transform the annot's `/Rect` by `cm`;
/// - if the source top-level field had a `/DR`, replace it with the
///   destination AcroForm `/DR` (lazy-initialized on the first placement AND
///   the first field-bearing annot within a placement, merging into a
///   pre-existing dest `/DR` with conflict renaming recorded into `dr_map`);
/// - append the dup'd annots to the destination page `/Annots`.
///
/// `dr_map` is document-scoped: ONE map created by the caller
/// (`apply_aggregated_sources` in `overlay.rs`) and threaded by `&mut`
/// through every placement on every destination page, so [`DrMap`]'s
/// `by_source_ref` cache can keep reusing the same renamed name for a
/// recurring source object across pages. Its `by_name` table, by contrast,
/// is reset at the top of every call to this function and repopulated only
/// for THIS placement — see the reset at the top of the function body.
/// `dest_acroform_dr`, unlike `dr_map`, is page-scoped: a fresh `None`
/// created by the caller for each destination page.
///
/// Returns the newly-added top-level field dest refs (one per distinct top
/// field observed in this placement), to be collected across all placements
/// on the dest page and passed to [`add_and_rename_form_fields`] once at the
/// end.
///
pub(crate) fn apply_placement<R: Read + Seek>(
    dest: &mut Pdf<R>,
    dest_page_ref: ObjectRef,
    template: &AnnotationCopyTemplate,
    cm: [f64; 6],
    dest_acroform_dr: &mut Option<ObjectRef>,
    dr_map: &mut DrMap,
) -> Result<Vec<ObjectRef>> {
    if template.annots.is_empty() {
        return Ok(Vec::new()); // cov:ignore: defensive early return
    }

    // Per-placement orig_to_copy map, mirroring qpdf's `orig_to_copy` local in
    // transformAnnotations (per-call, per-placement). Every mutable node
    // (annot, top-level field, field-tree kid, appearance stream) gets a
    // per-placement shallow dup here so multiple placements of the same source
    // don't share mutated /Rect / /Parent / AP /Matrix state.
    let mut per_placement_dup: BTreeMap<ObjectRef, ObjectRef> = BTreeMap::new();

    // `dr_map.by_name` is reset UNCONDITIONALLY at the top of every
    // placement, before deciding whether to repopulate it — mirrors qpdf's
    // `dr_map` being a local variable freshly created at the top of every
    // `AcroForm::transformAnnotations` call (verified via deepwiki against
    // `libqpdf/QPDFAcroFormDocumentHelper.cc`), never persisted across
    // calls. flpdf threads the SAME `DrMap` by `&mut` through every
    // placement on the whole destination document so `by_source_ref` (a
    // genuinely dest-scoped cache — see [`DrMap`]) can keep reusing the same
    // rename for a recurring source object, but `by_name` — the per-call
    // rename table [`adjust_default_appearance`] and
    // `crate::overlay_appearance_stream::adjust_appearance_stream` consult
    // for THIS placement's fields/AP streams — must not leak from a prior
    // placement into one that never repopulates it below. An
    // annotation-only placement (no top-level field at all, so the
    // first-field trigger inside the per-annot loop below never fires)
    // previously left a PRIOR placement's `by_name` renames in place,
    // wrongly applied to this placement's AP streams (roborev PR #490
    // iter-3 finding 2).
    dr_map.by_name.clear();

    // Trigger the source /DR merge for THIS placement the first time the
    // per-annot loop below (step 1) encounters an annot with a top-level
    // field — even when `dest_acroform_dr` is already Some. The merge
    // repopulates `dr_map.by_name` with just this source's mappings, so a
    // subsequent placement's field-tree walk (which reads `dr_map.by_name`
    // via [`adjust_default_appearance`]) sees THIS source's renames rather
    // than a prior source's stale entries. The `dest_acroform_dr` cache
    // stays: the ref itself does not change once installed. When the
    // placement has fields but NO source /DR (a valid shape: source has
    // annotations without an /AcroForm), no merge ever fires, so `by_name`
    // simply stays cleared (from above) — there is nothing to repopulate it
    // with.
    //
    // MUST be lazy (triggered per-annot, not once before the loop): qpdf's
    // `dr_map` starts EMPTY for the whole `transformAnnotations` call and is
    // populated only inside `traverse_field` via `init_dr_map` (an
    // `if (!dr)`-guarded, run-once closure) — which fires ONLY for
    // field-bearing annots, and only once the per-annot loop actually
    // reaches the FIRST one. An annot with NO field that precedes the first
    // field-bearing annot in `/Annots` order therefore sees `dr_map` still
    // empty when ITS `adjustAppearanceStream` call runs a few lines later
    // (guarded by `!dr_map.empty()` at
    // `libqpdf/QPDFAcroFormDocumentHelper.cc` in `transformAnnotations`,
    // fetched and verified against the live source for roborev PR #490
    // iter-4 finding 2) — its AP stream is left untouched. Populating
    // `dr_map` unconditionally before the loop (the prior version of this
    // function) gave every annot in the placement, including ones ordered
    // before the first field, the fully-populated map: a source/dest /DR
    // collision could then rewrite an AP stream qpdf leaves alone,
    // producing non-qpdf-matching bytes.
    let mut dr_map_ready = false;

    // Compute the inherited-field overrides (qpdf transformAnnotations
    // line 737-767): when the source /AcroForm's /DA or /Q differs from the
    // dest's, each foreign-copied field that inherits its value from the
    // source /AcroForm must be pinned to the source value so it does not
    // silently inherit the (different) dest default. For the primary target
    // (fxo-red + form-fields-and-annotations) neither doc has /DA or /Q, so
    // both flags come out false and the BFS reset is a no-op — the byte
    // gate is unaffected.
    let overrides = compute_inherited_overrides(dest, template)?;

    let mut new_top_fields: Vec<ObjectRef> = Vec::new();
    let mut added_top_field_set: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut new_annot_refs: Vec<ObjectRef> = Vec::new();

    for (dest_annot_ref, dest_top_field) in &template.annots {
        // 0. Lazily trigger the source /DR merge (see the doc comment
        //    above `dr_map_ready`) on the FIRST field-bearing annot this
        //    loop reaches — mirrors qpdf's `init_dr_map()` call at the top
        //    of `traverse_field`'s per-node loop, which only ever executes
        //    (its body, past the `if (!dr)` guard) on that same first
        //    field. Runs BEFORE step 1's `duplicate_field_tree` so that
        //    call's own `/DA` rewrite (mirroring qpdf's
        //    `adjustDefaultAppearances`, called right after
        //    `init_dr_map()` inside the SAME per-node loop) sees the
        //    freshly-populated map when THIS annot is itself the trigger.
        if dest_top_field.is_some() && !dr_map_ready {
            dr_map_ready = true;
            if let Some(source_dr) = template.source_dr {
                let dr_ref = ensure_dest_acroform_dr(dest, source_dr, dr_map)?;
                if dest_acroform_dr.is_none() {
                    *dest_acroform_dr = Some(dr_ref);
                }
            } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact; the body above is exercised by every field+/DR fixture (e.g. overlay_pipeline_renames_colliding_dr_font_end_to_end)
        }

        // 1. Duplicate the field tree (top → kids) into per-placement copies,
        //    patching /Parent back-pointers and resetting field /DR (top and
        //    every kid, matching qpdf's per-BFS-iteration line 928-930). If
        //    the widget IS the field (self-field), the annot ref equals the
        //    top-level ref, so this call also dups the annot as a side effect.
        let new_top_field_ref = if let Some(top_ref) = dest_top_field {
            let new_top = duplicate_field_tree(
                dest,
                *top_ref,
                &mut per_placement_dup,
                *dest_acroform_dr,
                overrides.as_ref(),
                dr_map,
            )?; // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
            if added_top_field_set.insert(new_top) {
                new_top_fields.push(new_top);
            }
            Some(new_top)
        } else {
            None
        };
        let _ = new_top_field_ref;

        // 2. Duplicate the annot itself if the field-tree walk did not already.
        let new_annot_ref = match per_placement_dup.get(dest_annot_ref) {
            Some(&existing) => existing,
            None => {
                let new = shallow_dup_indirect(dest, *dest_annot_ref)?;
                per_placement_dup.insert(*dest_annot_ref, new);
                new
            }
        };

        // 3. Duplicate and cm-transform each /AP appearance stream. Streams
        //    are shared across placements otherwise, so a cm concat here would
        //    accumulate across placements. Per-annot dup guarantees isolation.
        transform_annot_ap_streams(dest, new_annot_ref, cm, dr_map)?;

        // 4. Transform the annot's /Rect by cm.
        transform_annot_rect(dest, new_annot_ref, cm)?;

        // 5. Drop the annot's `/P` back-pointer when it is `Null` after copy.
        //    survey excluded `/P` from the copy closure (so the source page is
        //    not dragged into dest), which leaves `/P null` for annots that
        //    had one; qpdf's oracle removes the key entirely rather than
        //    repointing at dest_page_ref. Annots that never had /P (the
        //    primary target) are untouched.
        set_annot_page_ref_if_null(dest, new_annot_ref)?;

        new_annot_refs.push(new_annot_ref);
    }

    // 5. Append the dup'd annots to the destination page /Annots array.
    append_page_annots(dest, dest_page_ref, &new_annot_refs)?;

    Ok(new_top_fields)
}

/// Shallow-copy the object at `src_ref` into a new indirect object in `dest`
/// and return the new ref. The value's references are unchanged (shallow):
/// only the top-level dict/stream/array node is a fresh clone. Callers that
/// want to isolate a mutation to this placement's copy set must run this
/// per node they will mutate.
fn shallow_dup_indirect<R: Read + Seek>(
    dest: &mut Pdf<R>,
    src_ref: ObjectRef,
) -> Result<ObjectRef> {
    let obj = dest.resolve(src_ref)?;
    let new_ref = allocate_next_ref(dest)?;
    dest.set_object(new_ref, obj);
    Ok(new_ref)
}

/// Allocate a fresh indirect object ref (`max(numbers) + 1`, gen 0). Duplicate
/// of the crate-local helpers in overlay.rs / page_form_xobject.rs — kept
/// module-local so this file has no dep on overlay.rs's private surface.
fn allocate_next_ref<R: Read + Seek>(dest: &Pdf<R>) -> Result<ObjectRef> {
    let n = dest
        .object_refs()
        .iter()
        .map(|r| r.number)
        .max()
        .unwrap_or(0)
        .checked_add(1)
        .ok_or_else(|| Error::Unsupported("object-number space exhausted".to_string()))?;
    Ok(ObjectRef::new(n, 0))
}

/// BFS the field tree rooted at `top_ref`, shallow-dup'ing every visited node
/// into `per_placement_dup` and rewriting the `/Parent` back-pointer of each
/// kid to point at the dup of its parent (qpdf transformAnnotations
/// line 887-912 pattern). Returns the ref of the dup'd top-level field.
///
/// The dup of `top_ref` is added to `per_placement_dup` first, then kids are
/// discovered by reading each dup's `/Kids`; any kid that is not yet in the
/// map is dup'd and enqueued.
///
/// If `dest_dr` is `Some`, every field visited in the BFS has its `/DR` reset
/// to that ref (qpdf transformAnnotations line 928-930 — inside the BFS, so
/// both the top-level field and every kid receive the reset). Radio button
/// kids are self-field annotations and each carry an inline `/DR` in the
/// source, so kid-level reset is required for parity.
///
/// When `dr_map` is non-empty, every visited field's `/DA` (if present) is
/// additionally rewritten via [`adjust_default_appearance`] (qpdf
/// `adjustDefaultAppearances`, called from `transformAnnotations` line
/// 932-934) so a `/DA` referencing a source `/DR/Font` name that collided
/// during the merge points at the renamed dest name instead.
fn duplicate_field_tree<R: Read + Seek>(
    dest: &mut Pdf<R>,
    top_ref: ObjectRef,
    per_placement_dup: &mut BTreeMap<ObjectRef, ObjectRef>,
    dest_dr: Option<ObjectRef>,
    overrides: Option<&InheritedOverrides>,
    dr_map: &DrMap,
) -> Result<ObjectRef> {
    let new_top = match per_placement_dup.get(&top_ref) {
        Some(&existing) => return Ok(existing),
        None => {
            let new = shallow_dup_indirect(dest, top_ref)?;
            per_placement_dup.insert(top_ref, new);
            new
        }
    };

    // Pre-resolve, per category recorded in `dr_map`, the corresponding
    // sub-dict of the dest `/DR`. Every field visited by this BFS that still
    // carries a `/DR` key gets it reset to `dest_dr` below, and a field
    // without one inherits `/AcroForm/DR` (also `dest_dr`) — so `dest_dr`'s
    // per-category sub-dicts are the correct `/DA` resource-lookup surface
    // for every node in this walk. `dr_map` is only ever populated inside
    // `ensure_dest_acroform_dr` (via `merge_resources_shallow`), which
    // always sets the caller's `dest_acroform_dr` to `Some` before
    // returning, so `dr_map` non-empty implies `dest_dr` is `Some` here;
    // the `None` arm is a defensive fallback for that invariant, not a
    // path any shipped fixture reaches.
    //
    // A category entry (e.g. `/Font`) may itself be indirect
    // (`/DR << /Font 4 0 R >>`) — a PDF-permitted shape that
    // `merge_resources_shallow` supports and therefore this lookup must
    // handle. Directly matching only `Object::Dictionary` here would
    // silently drop the rewrite and leave `/F1` in place while
    // `/DR/Font` was actually renamed to `/F1_1`.
    //
    // `/DA` also references non-Font resources (`/CS1 cs`, `/GS1 gs`,
    // `/Pat1 scn`, etc.); mirroring qpdf's `ResourceFinder`,
    // [`adjust_default_appearance`] consults every category recorded in
    // `dr_map`, so pre-resolve them all here rather than only `/Font`.
    let per_category_resources: BTreeMap<Vec<u8>, crate::Dictionary> = if dr_map.is_empty() {
        BTreeMap::new()
    } else {
        // cov:ignore-start: dr_map non-empty implies dest_dr Some (see
        // comment above) and its resolve returns a dict. The Some/Some
        // arm is exercised by every rename byte-gate; the None arms are
        // defensive fallbacks the invariant precludes.
        let dr_dict = match dest_dr {
            Some(dr_ref) => dest.resolve(dr_ref)?.into_dict(),
            None => None,
        };
        // cov:ignore-end
        let mut resolved: BTreeMap<Vec<u8>, crate::Dictionary> = BTreeMap::new();
        if let Some(dr_dict) = dr_dict.as_ref() {
            for category in dr_map.by_name.keys() {
                let sub = match dr_dict.get(category).cloned() {
                    Some(Object::Dictionary(d)) => Some(d),
                    Some(Object::Reference(r)) => dest.resolve(r)?.into_dict(), // cov:ignore: indirect /DR/<Category> — no shipped byte-gate fixture supplies this shape (Layer 1 fixture uses direct sub-dicts), kept for robustness matching merge_resources_shallow's indirect handling.
                    // cov:ignore-start: /DR missing this category, or a non-dict/-ref value — no shipped fixture supplies this shape.
                    _ => None,
                    // cov:ignore-end
                };
                if let Some(d) = sub {
                    resolved.insert(category.clone(), d);
                }
            }
        } // cov:ignore: closing brace of `if let Some(dr_dict)` — llvm-cov instrumentation artifact on the block close; the body is exercised by every rename byte-gate.
        resolved
    };

    // BFS: queue holds (source_ref, dup_ref) pairs. `seen` prevents revisiting
    // (a cycle in a hostile PDF or a shared kid across mutliple parents).
    let mut queue: std::collections::VecDeque<(ObjectRef, ObjectRef)> =
        std::collections::VecDeque::new();
    queue.push_back((top_ref, new_top));
    let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
    seen.insert(top_ref);

    while let Some((_src_ref, dup_ref)) = queue.pop_front() {
        // Read the dup's current dictionary (which is a shallow-copy of the
        // source's dict at the time of shallow_dup_indirect, so /Parent and
        // /Kids still hold source refs).
        let Some(mut dict) = dest.resolve(dup_ref)?.into_dict() else {
            continue; // cov:ignore: dup ref resolved to non-dict — malformed
        };

        // Patch /Parent to point at THIS placement's dup of the parent (if
        // the parent has already been dup'd; a well-formed field tree visits
        // the parent before its kids, so this always holds).
        if let Some(parent_ref) = dict.get_ref("Parent") {
            if let Some(&parent_dup) = per_placement_dup.get(&parent_ref) {
                dict.insert("Parent", Object::Reference(parent_dup));
            }
            // else: /Parent points OUTSIDE the tree we're dup'ing (e.g. a
            // malformed structure); leave it, qpdf just warns and moves on.
        }

        // Walk /Kids: shallow-dup each kid, rewrite the /Kids entry to point
        // at the dup, and enqueue the (src, dup) pair.
        if let Some(kids_val) = dict.get("Kids").cloned() {
            let kids_array = match kids_val {
                Object::Array(arr) => Some(arr),
                // cov:ignore-start: indirect /Kids resolution — defensive shape
                Object::Reference(kr) => match dest.resolve(kr)? {
                    Object::Array(arr) => Some(arr),
                    _ => None,
                },
                _ => None,
                // cov:ignore-end
            };
            if let Some(mut kids) = kids_array {
                for entry in kids.iter_mut() {
                    if let Object::Reference(kid_ref) = *entry {
                        let kid_dup = match per_placement_dup.get(&kid_ref) {
                            Some(&existing) => existing, // cov:ignore: match arm — defensive on unexpected shape
                            None => {
                                let new = shallow_dup_indirect(dest, kid_ref)?;
                                per_placement_dup.insert(kid_ref, new);
                                new
                            }
                        };
                        *entry = Object::Reference(kid_dup);
                        if seen.insert(kid_ref) {
                            queue.push_back((kid_ref, kid_dup));
                        }
                    } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
                }
                dict.insert("Kids", Object::Array(kids));
            } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
        }

        // Reset field-level /DR to the dest /AcroForm/DR ref (qpdf
        // transformAnnotations line 928-930). Runs for every visited node
        // (top-level field and every kid), matching qpdf's per-iteration BFS
        // reset — required for radio button kids that carry inline /DR in the
        // source.
        if let Some(dr) = dest_dr {
            if dict.get("DR").is_some() {
                dict.insert("DR", Object::Reference(dr));
            }
        } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact

        // Override inherited /DA and /Q on this field when the source doc's
        // defaults differ from the dest's (qpdf transformAnnotations
        // line 914-917 → adjustInheritedFields at line 442-484). Only pin the
        // value when this field does not already carry an explicit /DA or /Q
        // (either on itself or on an ancestor visited earlier in the BFS —
        // parents come before kids), and only when the field's currently
        // inherited value would differ from `from_default`. `dict` at this
        // point already has its /Parent rewritten to the dup, so the walk
        // stays inside `per_placement_dup`.
        if let Some(ov) = overrides {
            adjust_inherited_field(dest, dup_ref, &mut dict, ov, per_placement_dup)?;
        }

        // Rewrite this field's /DA to reference the renamed dest resource
        // name (qpdf transformAnnotations line 932-934 →
        // adjustDefaultAppearances). Runs after adjust_inherited_field so a
        // /DA that was just pinned from the source /AcroForm default above
        // is also covered. `remove` (not `get().cloned()`) moves the value
        // out since `dict` is owned here — see pdf-rust-review-patterns.md
        // rule 1.
        //
        // `/DA` is permitted as either a direct string or an indirect ref
        // to a string (see `crate::appearance` for how the reader handles
        // both). Convert an indirect ref to a direct string on the copied
        // field: replacing the value inline keeps every foreign-copied
        // field independent of the source string object, so a subsequent
        // rewrite on the same source field ref reads the pre-rewrite
        // bytes instead of accumulating rewrites.
        if !per_category_resources.is_empty() {
            match dict.remove("DA") {
                Some(Object::String(da)) => {
                    let new_da = adjust_default_appearance(&da, dr_map, &per_category_resources);
                    dict.insert("DA", Object::String(new_da));
                }
                // cov:ignore-start: indirect /DA — form-fields-and-
                // annotations.pdf and every shipped source fixture uses
                // a direct /DA string, so this arm needs a source with
                // `/DA <ref>` to reach.
                Some(Object::Reference(da_ref)) => {
                    match dest.resolve(da_ref)? {
                        Object::String(da) => {
                            let new_da =
                                adjust_default_appearance(&da, dr_map, &per_category_resources);
                            dict.insert("DA", Object::String(new_da));
                        }
                        _ => {
                            dict.insert("DA", Object::Reference(da_ref));
                        }
                    }
                    // cov:ignore-end
                }
                // cov:ignore-start: malformed /DA (non-string, non-ref) —
                // no shipped fixture supplies this shape.
                Some(other) => {
                    dict.insert("DA", other);
                }
                // cov:ignore-end
                None => {}
            }
        }

        dest.set_object(dup_ref, Object::Dictionary(dict));
    }

    Ok(new_top)
}

/// Rewrite renamed resource names in a `/DA` string according to `dr_map`,
/// matching qpdf `QPDFAcroFormDocumentHelper::adjustDefaultAppearances`
/// (`libqpdf/QPDFAcroFormDocumentHelper.cc`, called from
/// `transformAnnotations` line 932-934).
///
/// `/DA` is a content-stream fragment (ISO 32000-2 12.7.3.3), typically
/// `0 0.4 0 rg /F1 18 Tf` for a Font-only field, but also permitted to use
/// non-Font operators such as `/CS1 cs`, `/GS1 gs`, or `/Pat1 scn`. This
/// scans the fragment for the name token most recently seen before each
/// operator that maps to a resource category (mirroring qpdf's
/// `ResourceFinder`, which tracks a single `last_name` overwritten by
/// every name token and consulted whenever an operator maps to a resource
/// type) and rewrites that name's bytes to `dr_map[category][name]` when
/// BOTH:
/// - `dr_map` records a rename for that name under the operator's
///   category, AND
/// - `per_category_resources[category]` still carries that ORIGINAL name
///   as a key — a defensive guard against renaming a name that happens to
///   collide with a `dr_map` key from an unrelated context. In practice
///   this is a no-op superset check: `merge_resources_shallow` always
///   keeps the original colliding name in the merged dest sub-dict
///   alongside the `{name}_N` rename.
///
/// Operator table (mirrors qpdf's `libqpdf/ResourceFinder.cc`):
/// - `Tf` → `Font`
/// - `Do` → `XObject`
/// - `gs` → `ExtGState`
/// - `sh` → `Shading`
/// - `cs` / `CS` → `ColorSpace`
/// - `SCN` / `scn` → `Pattern`
/// - `BDC` / `DP` → `Properties` (using the SECOND name arg — the tag
///   argument leaves the tracked `last_name` set to itself, so the
///   presence guard on `/DR/Properties` prevents a spurious rewrite when
///   the operator's properties operand is a dictionary literal instead).
///
/// `per_category_resources` maps a category name to its resolved sub-dict
/// (indirect refs pre-resolved by the caller); passing the resolved dicts
/// lets this function stay free of `&mut Pdf<R>` while still handling the
/// PDF-permitted `/DR << /Font <ref> >>` shape.
///
/// Every other byte — whitespace, unrelated names, other operators, string
/// and numeric operands — is copied through unchanged, so the result is
/// byte-identical to `da` except at the rewritten name's exact span.
///
/// This is an inline tokenizer scoped to the `/DA` subset (delegates operand
/// lexing to the shared [`Parser`] but does not use the general
/// [`crate::content_stream::ContentStreamParser`], which does not track
/// per-token byte offsets).
///
/// Returns `da.to_vec()` verbatim, without scanning, when `dr_map` is empty
/// (the common case: no placement recorded a rename on this dest page).
fn adjust_default_appearance(
    da: &[u8],
    dr_map: &DrMap,
    per_category_resources: &BTreeMap<Vec<u8>, crate::Dictionary>,
) -> Vec<u8> {
    if dr_map.is_empty() {
        return da.to_vec();
    }

    let mut out: Vec<u8> = Vec::with_capacity(da.len());
    // Byte span of the most recently seen name token WITHIN `out` (not
    // `da` — needed so `Vec::splice` can replace it in place) plus its
    // decoded value. Overwritten by every subsequent name token; consumed
    // (reset to `None`) only when a resource operator actually applies it,
    // so a later stray operator cannot re-splice an already-rewritten span.
    let mut last_name: Option<(usize, usize, Vec<u8>)> = None;
    let mut pos = 0usize;
    while pos < da.len() {
        let byte = da[pos];
        if is_ws(byte) {
            let start = pos;
            while pos < da.len() && is_ws(da[pos]) {
                pos += 1;
            }
            out.extend_from_slice(&da[start..pos]);
            continue;
        }
        if byte == b'%' {
            // `%` comment: copied verbatim to end of line. `/DA` fragments
            // rarely carry comments, but the token grammar permits them
            // (ISO 32000-2 7.8.2).
            let start = pos;
            while pos < da.len() && !matches!(da[pos], b'\n' | b'\r') {
                pos += 1;
            }
            out.extend_from_slice(&da[start..pos]);
            continue;
        }
        if byte == b'/'
            || byte == b'('
            || byte == b'<'
            || byte == b'['
            || matches!(byte, b'+' | b'-' | b'.' | b'0'..=b'9')
        {
            // Operand: delegate to the shared object lexer (numbers,
            // strings, names, arrays, dictionaries) that
            // `crate::content_stream` also reuses verbatim, so name/string
            // escaping matches the rest of the crate exactly rather than
            // reimplementing it here.
            let mut parser = Parser::new_no_reference(&da[pos..]);
            match parser.parse_one_object() {
                Ok(obj) => {
                    let end = pos + parser.position();
                    let out_start = out.len();
                    out.extend_from_slice(&da[pos..end]);
                    if let Object::Name(name) = obj {
                        last_name = Some((out_start, out.len(), name));
                    }
                    pos = end;
                }
                Err(_) => {
                    // Malformed operand: copy one byte verbatim and resume
                    // (tolerant scanning — mirrors `/DA` parsing elsewhere in
                    // the crate, which also recovers from bad tokens rather
                    // than aborting the whole string).
                    out.push(byte);
                    pos += 1;
                }
            }
            continue;
        }
        // Operator keyword: bytes up to the next whitespace/delimiter.
        let start = pos;
        while pos < da.len() && !is_ws(da[pos]) && !is_delimiter(da[pos]) {
            pos += 1;
        }
        if pos == start {
            // Stray delimiter that did not start a recognised operand (e.g.
            // an unmatched `)`); copy the single byte verbatim and resume.
            out.push(da[pos]);
            pos += 1;
            continue;
        }
        out.extend_from_slice(&da[start..pos]);
        if let Some(category) = da_operator_category(&da[start..pos]) {
            if let Some((out_start, out_end, name)) = last_name.take() {
                let renamed = dr_map
                    .category(category)
                    .and_then(|m| m.get(name.as_slice()));
                if let Some(new_name) = renamed {
                    let present = per_category_resources
                        .get(category)
                        .is_some_and(|d| d.get(name.as_slice()).is_some());
                    if present {
                        // Escape the replacement bytes so a name containing
                        // delimiters or non-printable bytes serializes back
                        // to a valid PDF name token (e.g. decoded `F A_1`
                        // must emit as `/F#20A_1`, not `/F A_1` which the
                        // parser would tokenize as `/F` followed by an
                        // operand run). qpdf routes every name write
                        // through `QPDF_Name::normalizeName` for the same
                        // reason.
                        let mut replacement = Vec::with_capacity(new_name.len() + 1);
                        replacement.push(b'/');
                        crate::object::write_name_escaped(&mut replacement, new_name);
                        out.splice(out_start..out_end, replacement);
                    }
                }
            }
        }
    }
    out
}

/// Map a `/DA` content-stream operator keyword to the resource category
/// its NAME operand consumes. Mirrors qpdf's operator → resource-type
/// map in `libqpdf/ResourceFinder.cc`. Operators that do not take a
/// name-typed resource operand (`Tj`, `TJ`, `rg`, `RG`, `w`, ...) map to
/// `None` and their preceding name token is discarded.
///
/// `BDC` and `DP` consume the LAST name token that preceded the operator
/// as their second (properties) argument: `/Span /MC1 BDC` picks up
/// `/MC1` from the tracked `last_name`. If the properties operand is a
/// dictionary literal rather than a name, `last_name` will hold the tag
/// (`/Span`) — which is never in `/DR/Properties`, so the presence guard
/// in the caller keeps that from firing a spurious rewrite.
fn da_operator_category(op: &[u8]) -> Option<&'static [u8]> {
    match op {
        b"Tf" => Some(b"Font"),
        b"Do" => Some(b"XObject"),
        b"gs" => Some(b"ExtGState"),
        b"sh" => Some(b"Shading"),
        b"cs" | b"CS" => Some(b"ColorSpace"),
        b"SCN" | b"scn" => Some(b"Pattern"),
        b"BDC" | b"DP" => Some(b"Properties"),
        _ => None,
    }
}

/// Duplicate each `/AP` appearance stream referenced from the annot at
/// `annot_ref`, concatenate `cm` into the stream's `/Matrix` (qpdf
/// transformAnnotations line 992-1010), and rewrite the annot's `/AP` entries
/// to point at the dup'd streams. Only walked at `/AP/{N,R,D}` and one nested
/// dictionary level, matching qpdf's `apdict` traversal.
///
/// When `dr_map` is non-empty, each dup'd stream is additionally passed to
/// [`crate::overlay_appearance_stream::adjust_appearance_stream`] (qpdf
/// `AcroForm::adjustAppearanceStream`, called from `transformAnnotations`
/// line 1156-1161) so a `/Resources` name that collided during the `/DR`
/// merge is privatized, renamed, and rewritten in the stream's own content —
/// every nested per-state stream (`/N/1`, `/N/Off`, ...) is adjusted
/// independently, matching qpdf's per-stream loop at the same call site.
fn transform_annot_ap_streams<R: Read + Seek>(
    dest: &mut Pdf<R>,
    annot_ref: ObjectRef,
    cm: [f64; 6],
    dr_map: &DrMap,
) -> Result<()> {
    let Some(mut annot_dict) = dest.resolve(annot_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let Some(ap_val) = annot_dict.get("AP").cloned() else {
        return Ok(());
    };
    let Some(mut apdict) = (match ap_val {
        Object::Dictionary(d) => Some(d),
        Object::Reference(r) => dest.resolve(r)?.into_dict(), // cov:ignore: function signature — llvm-cov instrumentation artifact
        _ => None, // cov:ignore: fallback match arm — defensive/malformed input
    }) else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let ap_keys: Vec<Vec<u8>> = apdict.iter().map(|(k, _)| k.to_vec()).collect();
    for key in ap_keys {
        let val = apdict.get(&key).cloned();
        let Some(val) = val else { continue };
        match val {
            Object::Reference(stream_ref) => {
                if let Some(new_ref) = dup_and_transform_ap_stream(dest, stream_ref, cm)? {
                    if !dr_map.is_empty() {
                        adjust_appearance_stream(dest, new_ref, dr_map)?;
                    }
                    apdict.insert(&key, Object::Reference(new_ref));
                }
            }
            Object::Dictionary(sub) => {
                // Nested per-state dict (e.g. /N << /1 stream_ref /Off stream_ref >>).
                let mut sub = sub;
                let sub_keys: Vec<Vec<u8>> = sub.iter().map(|(k, _)| k.to_vec()).collect();
                for sub_key in sub_keys {
                    let Some(sub_val) = sub.get(&sub_key).cloned() else {
                        continue; // cov:ignore: key vanished mid-iteration — impossible with BTreeMap
                    };
                    if let Object::Reference(stream_ref) = sub_val {
                        if let Some(new_ref) = dup_and_transform_ap_stream(dest, stream_ref, cm)? {
                            if !dr_map.is_empty() {
                                adjust_appearance_stream(dest, new_ref, dr_map)?;
                            }
                            sub.insert(&sub_key, Object::Reference(new_ref));
                        }
                    } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
                }
                apdict.insert(&key, Object::Dictionary(sub));
            }
            _ => {} // cov:ignore: fallback match arm — defensive/malformed input
        }
    }
    annot_dict.insert("AP", Object::Dictionary(apdict));
    dest.set_object(annot_ref, Object::Dictionary(annot_dict));
    Ok(())
}

/// Shallow-copy the appearance stream at `stream_ref`, concatenate `cm` into
/// its `/Matrix` (identity if absent, matching qpdf), and return the new ref.
/// Returns `Ok(None)` when the ref does not resolve to a stream.
fn dup_and_transform_ap_stream<R: Read + Seek>(
    dest: &mut Pdf<R>,
    stream_ref: ObjectRef,
    cm: [f64; 6],
) -> Result<Option<ObjectRef>> {
    let obj = dest.resolve(stream_ref)?;
    let Object::Stream(mut stream) = obj else {
        return Ok(None); // cov:ignore: defensive early return
    };
    // Read the existing /Matrix (identity when absent — qpdf apcm defaults
    // to QPDFMatrix() before optional matrix.concat(cm) at line 1001).
    let old_matrix = read_matrix_array(&stream.dict, b"Matrix");
    // qpdf: apcm.concat(cm)  →  apcm := apcm * cm  →  overlay uses qpdf_concat
    // (in overlay.rs) with (this, other) = (apcm, cm).
    let had_matrix = old_matrix.is_some();
    let apcm = old_matrix.unwrap_or(IDENTITY);
    let new_matrix = concat_matrices(apcm, cm);
    // Only write /Matrix if the source had one or the result is non-identity
    // (qpdf line 1003 same guard).
    if had_matrix || new_matrix != IDENTITY {
        stream.dict.insert("Matrix", matrix_to_object(new_matrix));
    }
    let new_ref = allocate_next_ref(dest)?;
    dest.set_object(new_ref, Object::Stream(stream));
    Ok(Some(new_ref))
}

/// Read a 6-element `/Matrix` from `dict[key]`, if present and well-formed.
fn read_matrix_array(dict: &crate::Dictionary, key: &[u8]) -> Option<[f64; 6]> {
    let arr = match dict.get(key)? {
        Object::Array(a) if a.len() == 6 => a,
        _ => return None, // cov:ignore: fallback match arm — defensive/malformed input
    };
    let mut out = [0.0f64; 6];
    for (i, item) in arr.iter().enumerate() {
        out[i] = match item {
            Object::Integer(n) => *n as f64,
            Object::Real(x) | Object::RealLiteral { value: x, .. } => *x, // cov:ignore: function signature — llvm-cov instrumentation artifact
            _ => return None, // cov:ignore: fallback match arm — defensive/malformed input
        };
    }
    Some(out)
}

/// Serialize a 6-element matrix as an `Object::Array` of `Object::Real`,
/// matching qpdf's `QPDFObjectHandle::newFromMatrix` output shape.
fn matrix_to_object(m: [f64; 6]) -> Object {
    Object::Array(m.iter().map(|&x| qpdf_real(x)).collect())
}

/// Pre-round `v` so `Object::Real(rounded).write_pdf(...)` (which formats f64
/// via Rust's shortest-roundtrip algorithm) yields the same string as qpdf's
/// `QUtil::double_to_string(v, 6, trim=true)` (six decimal places, trailing
/// zeros/point stripped) — used by qpdf's `newReal(double)` default and thus
/// by every `newFromRectangle` / `newFromMatrix` array element.
///
/// Round-trip trick: format `v` as `%.6f`, strip trailing zeros and a
/// trailing `.`, parse back to `f64`. Rust's `f64::to_string` yields the
/// shortest decimal string that parses back to the same `f64`, so if the
/// intermediate string is decimal-canonical for the target `f64` (which
/// `%.6f + strip` is by construction for values expressible in ≤6 decimal
/// places), the writer's later `f64::to_string` returns the same bytes.
fn qpdf_real(v: f64) -> Object {
    let s = format!("{v:.6}");
    let trimmed = s.trim_end_matches('0').trim_end_matches('.');
    // Preserve signed-zero: qpdf's QUtil::double_to_string(-0.0, 6, true)
    // yields "-0" (via `printf %.6f` → "-0.000000" → trim → "-0"). Rust's
    // f64::to_string on -0.0 also yields "-0", so a round-trip through parse
    // preserves the sign bit and the writer emits the same "-0" byte.
    let rounded: f64 = trimmed.parse().unwrap_or(0.0);
    Object::Real(rounded)
}

/// Multiply two matrices left-to-right (`this * other`), mirroring
/// `QPDFMatrix::concat` byte-for-byte (see overlay.rs::qpdf_concat).
fn concat_matrices(this: [f64; 6], other: [f64; 6]) -> [f64; 6] {
    let [a, b, c, d, e, f] = this;
    let [oa, ob, oc, od, oe, of] = other;
    [
        a * oa + c * ob,
        b * oa + d * ob,
        a * oc + c * od,
        b * oc + d * od,
        a * oe + c * of + e,
        b * oe + d * of + f,
    ]
}

const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];

/// Read the annot's `/Rect`, transform its four corners by `cm`, and write
/// back the normalized bounding rectangle. Mirrors qpdf's
/// `QPDFMatrix::transformRectangle` used at transformAnnotations line 1011.
fn transform_annot_rect<R: Read + Seek>(
    dest: &mut Pdf<R>,
    annot_ref: ObjectRef,
    cm: [f64; 6],
) -> Result<()> {
    let Some(mut dict) = dest.resolve(annot_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let rect_val = dict.get("Rect").cloned();
    let rect = match rect_val {
        Some(Object::Array(arr)) => arr,
        _ => return Ok(()), // cov:ignore: defensive early return
    };
    if rect.len() != 4 {
        return Ok(()); // cov:ignore: defensive early return
    }
    let mut nums = [0.0f64; 4];
    for (i, item) in rect.iter().enumerate() {
        nums[i] = match item {
            Object::Integer(n) => *n as f64,
            Object::Real(x) | Object::RealLiteral { value: x, .. } => *x,
            _ => return Ok(()), // cov:ignore: defensive early return
        };
    }
    let new_rect = transform_rect_by_cm(nums, cm);
    dict.insert(
        "Rect",
        Object::Array(new_rect.iter().map(|&x| qpdf_real(x)).collect()),
    );
    dest.set_object(annot_ref, Object::Dictionary(dict));
    Ok(())
}

/// Transform the four corners of `rect` by `cm` and return the axis-aligned
/// bounding rectangle of the transformed corners (`[min_x, min_y, max_x,
/// max_y]`), mirroring qpdf's `QPDFMatrix::transformRectangle`.
fn transform_rect_by_cm(rect: [f64; 4], cm: [f64; 6]) -> [f64; 4] {
    let [llx, lly, urx, ury] = rect;
    let corners = [(llx, lly), (llx, ury), (urx, lly), (urx, ury)];
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;
    for (x, y) in corners {
        let (tx, ty) = apply_matrix_to_point(cm, x, y);
        if tx < min_x {
            min_x = tx;
        }
        if tx > max_x {
            max_x = tx;
        }
        if ty < min_y {
            min_y = ty;
        }
        if ty > max_y {
            max_y = ty;
        }
    }
    [min_x, min_y, max_x, max_y]
}

/// Apply a 6-element matrix to a point: `[a b c d e f] * (x, y)` =
/// `(a*x + c*y + e, b*x + d*y + f)`.
fn apply_matrix_to_point(m: [f64; 6], x: f64, y: f64) -> (f64, f64) {
    let [a, b, c, d, e, f] = m;
    (a * x + c * y + e, b * x + d * y + f)
}

/// Read the destination `/AcroForm`'s `/DA` and `/Q` defaults and compare
/// with `template.source_default_da / _q`. Returns `Some(InheritedOverrides)`
/// only when at least one differs — matching qpdf's `override_da || override_q`
/// gate (transformAnnotations line 736-767). Missing values default to `""`
/// / `0` per qpdf.
fn compute_inherited_overrides<R: Read + Seek>(
    dest: &mut Pdf<R>,
    template: &AnnotationCopyTemplate,
) -> Result<Option<InheritedOverrides>> {
    let (dest_da, dest_q) = read_dest_acroform_defaults(dest)?;
    let from_da = template
        .source_default_da
        .as_deref()
        .unwrap_or(b"")
        .to_vec();
    let from_q = template.source_default_q.unwrap_or(0);
    let override_da = from_da != dest_da;
    let override_q = from_q != dest_q;
    if !override_da && !override_q {
        return Ok(None);
    }
    Ok(Some(InheritedOverrides {
        override_da,
        from_default_da: from_da,
        override_q,
        from_default_q: from_q,
    }))
}

/// Read `/AcroForm/DA` (as bytes; empty when absent) and `/AcroForm/Q`
/// (integer; 0 when absent) from the destination doc's catalog.
fn read_dest_acroform_defaults<R: Read + Seek>(dest: &mut Pdf<R>) -> Result<(Vec<u8>, i64)> {
    let Some(root_ref) = dest.root_ref() else {
        return Ok((Vec::new(), 0)); // cov:ignore: defensive early return
    };
    let acroform_val = {
        let obj = dest.resolve_borrowed(root_ref)?;
        let Some(dict) = obj.as_dict() else {
            return Ok((Vec::new(), 0)); // cov:ignore: defensive early return
        };
        dict.get("AcroForm").cloned()
    };
    let acroform_dict = match acroform_val {
        None | Some(Object::Null) => return Ok((Vec::new(), 0)),
        Some(Object::Dictionary(d)) => d, // cov:ignore: match arm — defensive on unexpected shape
        Some(Object::Reference(r)) => match dest.resolve(r)? {
            Object::Dictionary(d) => d,
            _ => return Ok((Vec::new(), 0)), // cov:ignore: defensive early return
        },
        _ => return Ok((Vec::new(), 0)), // cov:ignore: defensive early return
    };
    let da = match acroform_dict.get("DA") {
        Some(Object::String(s)) => s.clone(), // cov:ignore: match arm — defensive on unexpected shape
        _ => Vec::new(),
    };
    let q = match acroform_dict.get("Q") {
        Some(Object::Integer(n)) => *n, // cov:ignore: match arm — defensive on unexpected shape
        _ => 0,
    };
    Ok((da, q))
}

/// Apply `overrides` to a single field's dup during the BFS. Mirrors qpdf
/// `adjustInheritedFields` (`libqpdf/QPDFAcroFormDocumentHelper.cc:442-484`).
///
/// For each of /DA and /Q: if `override_*` is set AND the field does not
/// carry an explicit value on itself OR any ancestor visited earlier in this
/// placement (both flpdf's per_placement_dup and qpdf's `orig_to_copy` visit
/// parents before kids, so ancestors are already dup'd), pin the field to
/// the source's default so the (different) dest default is not silently
/// inherited.
fn adjust_inherited_field<R: Read + Seek>(
    dest: &mut Pdf<R>,
    field_ref: ObjectRef,
    field_dict: &mut crate::Dictionary,
    overrides: &InheritedOverrides,
    per_placement_dup: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
    // /FT gate: qpdf's `adjustInheritedFields` also proceeds unconditionally
    // (the comment at line 449-455 explains it may write to non-field
    // annots, and that's harmless), so we do too.
    if overrides.override_da
        && field_dict.get("DA").is_none()
        && !ancestor_has_key(dest, field_ref, b"DA", per_placement_dup)?
    {
        field_dict.insert("DA", Object::String(overrides.from_default_da.clone()));
    }
    if overrides.override_q
        && field_dict.get("Q").is_none()
        && !ancestor_has_key(dest, field_ref, b"Q", per_placement_dup)?
    {
        field_dict.insert("Q", Object::Integer(overrides.from_default_q));
    }
    Ok(())
}

/// True when any ancestor of `field_ref` (via `/Parent`) already carries an
/// explicit `key`. Follows the *dup* graph via `per_placement_dup` because
/// the BFS rewrites `/Parent` to point at the placement's dup before the
/// field is written back. Bounded by `MAX_PARENT_WALK_DEPTH`.
fn ancestor_has_key<R: Read + Seek>(
    dest: &mut Pdf<R>,
    field_ref: ObjectRef,
    key: &[u8],
    per_placement_dup: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<bool> {
    let mut current = field_ref;
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    for _ in 0..MAX_PARENT_WALK_DEPTH {
        if !visited.insert(current) {
            return Ok(false); // cov:ignore: defensive early return
        }
        let parent = {
            let obj = dest.resolve_borrowed(current)?;
            let Some(dict) = obj.as_dict() else {
                return Ok(false); // cov:ignore: defensive early return
            };
            dict.get_ref("Parent")
        };
        let Some(parent_ref) = parent else {
            return Ok(false);
        };
        // The BFS may have already rewritten /Parent to the dup; if not, map
        // via per_placement_dup so we walk within this placement's clones.
        let ancestor_ref = per_placement_dup
            .get(&parent_ref)
            .copied()
            .unwrap_or(parent_ref);
        let has = {
            let obj = dest.resolve_borrowed(ancestor_ref)?;
            match obj.as_dict() {
                Some(dict) => dict.get(key).is_some(),
                None => false, // cov:ignore: defensive `None` match arm
            }
        };
        if has {
            return Ok(true);
        } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
        current = ancestor_ref; // cov:ignore: multi-hop /Parent walk — the shipped adjustInheritedFields fixture has 1-hop parents at most
    }
    Ok(false) // cov:ignore: success arm reached only on defensive path
}

/// Remove the annot's `/P` entry when it is currently `Null`.
///
/// The source's `/P` was excluded from the copy closure
/// ([`survey_source_annotations`], `skip_parent_key = true`), so the
/// dup'd annot dict carries `/P null` after `copy_objects`'s rewrite pass
/// (unmapped refs become `Object::Null`). qpdf's oracle drops `/P` from
/// the copied annot entirely (verified against the
/// `overlay-source-p-and-inline.pdf` golden) — the page back-pointer is
/// re-established at read time by whatever consumer needs it. Removing
/// the key here rather than re-pointing it at `dest_page_ref` matches
/// that behavior; annots that never had `/P` (the primary target) are
/// unaffected since the key isn't present to remove.
fn set_annot_page_ref_if_null<R: Read + Seek>(
    dest: &mut Pdf<R>,
    annot_ref: ObjectRef,
) -> Result<()> {
    let Some(mut dict) = dest.resolve(annot_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    match dict.get("P") {
        Some(Object::Null) => {}
        _ => return Ok(()),
    }
    dict.remove("P");
    dest.set_object(annot_ref, Object::Dictionary(dict));
    Ok(())
}

/// Append `new_annot_refs` to the destination page's `/Annots` array,
/// creating the array if the page had none (qpdf copyAnnotations line
/// 1032-1038).
fn append_page_annots<R: Read + Seek>(
    dest: &mut Pdf<R>,
    dest_page_ref: ObjectRef,
    new_annot_refs: &[ObjectRef],
) -> Result<()> {
    if new_annot_refs.is_empty() {
        return Ok(()); // cov:ignore: defensive early return
    }
    let Some(mut page_dict) = dest.resolve(dest_page_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    // cov:ignore-start: pre-existing /Annots on the dest page — none of the
    // shipped fixtures pre-populate /Annots on a dest page (fxo-red pages
    // start bare), so the "already has annots" arms are only reachable via
    // hand-crafted PDFs.
    let mut annots = match page_dict.get("Annots").cloned() {
        None | Some(Object::Null) => Vec::new(),
        Some(Object::Array(arr)) => arr,
        Some(Object::Reference(r)) => match dest.resolve(r)? {
            Object::Array(arr) => arr,
            _ => Vec::new(),
        },
        _ => Vec::new(),
    };
    // cov:ignore-end
    for &r in new_annot_refs {
        annots.push(Object::Reference(r));
    }
    page_dict.insert("Annots", Object::Array(annots));
    dest.set_object(dest_page_ref, Object::Dictionary(page_dict));
    Ok(())
}

/// Lazy-initialize the destination `/AcroForm/DR`. If dest has no `/AcroForm`,
/// create one; the `/DR` (fresh or pre-existing) has `source_dr`'s (already
/// dest-space) contents merged into it via [`merge_resources_shallow`], which
/// records any conflict rename it performs into `dr_map`. Returns the ref of
/// the dest `/DR` (whether newly-created or previously present).
///
/// This matches qpdf transformAnnotations line 780-800 (init_dr_map): dest
/// `/AcroForm/DR` is a new object, and `source_dr` is preserved as a SEPARATE
/// object reachable via appearance-stream `/Resources` references — so the
/// dest ends up with two byte-identical `/DR`-shaped objects (dest_dr for
/// `/AcroForm/DR`, source_dr for AP stream `/Resources`). See qpdf golden
/// `overlay-copy-annotations.pdf` obj 4 (dest_dr) and obj 344 (source_dr copy).
///
/// For a dest that already has an `/AcroForm` and `/DR`, the pre-existing
/// `/DR` object is reused (not replaced) and `source_dr`'s entries are merged
/// into it with conflict renaming. Downstream consumption of `dr_map` to
/// rewrite copied fields' `/DA` and AP-stream content (qpdf's
/// `adjustDefaultAppearances` / `adjustAppearanceStream`) is not implemented
/// yet — left for a later change.
fn ensure_dest_acroform_dr<R: Read + Seek>(
    dest: &mut Pdf<R>,
    source_dr: ObjectRef,
    dr_map: &mut DrMap,
) -> Result<ObjectRef> {
    // cov:ignore-start: defensive early returns on catalog-shape guards.
    let Some(root_ref) = dest.root_ref() else {
        return Err(Error::Unsupported(
            "destination has no /Root; cannot install /AcroForm for copied form fields".into(),
        ));
    };
    let Some(mut catalog) = dest.resolve(root_ref)?.into_dict() else {
        return Err(Error::Unsupported(
            "destination /Root does not resolve to a dictionary".into(),
        ));
    };
    // cov:ignore-end
    let acroform_val = catalog.get("AcroForm").cloned();
    let acroform_ref = match acroform_val {
        Some(Object::Reference(r)) => r,
        // cov:ignore-start: direct-/AcroForm promotion — no shipped fixture
        // has a direct /AcroForm dict at the source (qpdf normalizes to
        // indirect on write), so the promotion body only runs on hand-
        // written PDFs. The behaviour is intentionally lossless (contents
        // preserved) — see the comment inside the arm.
        Some(Object::Dictionary(existing)) => {
            let af_ref = allocate_next_ref(dest)?;
            dest.set_object(af_ref, Object::Dictionary(existing));
            catalog.insert("AcroForm", Object::Reference(af_ref));
            dest.set_object(root_ref, Object::Dictionary(catalog));
            af_ref
        }
        // cov:ignore-end
        _ => {
            // No /AcroForm (or a non-dict value): install a fresh empty one.
            let mut af = crate::Dictionary::new();
            af.insert("Fields", Object::Array(Vec::new()));
            let af_ref = allocate_next_ref(dest)?;
            dest.set_object(af_ref, Object::Dictionary(af));
            catalog.insert("AcroForm", Object::Reference(af_ref));
            dest.set_object(root_ref, Object::Dictionary(catalog));
            af_ref
        }
    };
    let mut acroform_dict = match dest.resolve(acroform_ref)?.into_dict() {
        Some(d) => d,
        // cov:ignore-start: defensive early return on non-dict /AcroForm
        None => {
            return Err(Error::Unsupported(
                "destination /AcroForm does not resolve to a dictionary".into(),
            ));
            // cov:ignore-end
        }
    };
    // Existing /DR may be indirect (a ref) or a direct dict; preserve either
    // shape and merge `source_dr`'s entries into it either way.
    match acroform_dict.get("DR").cloned() {
        Some(Object::Reference(existing)) => {
            merge_resources_shallow(dest, existing, source_dr, dr_map)?;
            return Ok(existing);
        }
        // cov:ignore-start: direct-/DR promotion in the existing-AcroForm
        // path — analogous to the direct-/AcroForm case above. qpdf
        // normalizes /DR to indirect on write, so no shipped fixture
        // reaches this arm.
        Some(Object::Dictionary(existing)) => {
            let dr_ref = allocate_next_ref(dest)?;
            dest.set_object(dr_ref, Object::Dictionary(existing));
            acroform_dict.insert("DR", Object::Reference(dr_ref));
            dest.set_object(acroform_ref, Object::Dictionary(acroform_dict));
            merge_resources_shallow(dest, dr_ref, source_dr, dr_map)?;
            return Ok(dr_ref);
        }
        // cov:ignore-end
        _ => {}
    }
    // No existing /DR: allocate a fresh one, merge source_dr's contents into
    // it, and wire dest /AcroForm to point at it.
    let dr_ref = allocate_next_ref(dest)?;
    dest.set_object(dr_ref, Object::Dictionary(crate::Dictionary::new()));
    merge_resources_shallow(dest, dr_ref, source_dr, dr_map)?;
    acroform_dict.insert("DR", Object::Reference(dr_ref));
    dest.set_object(acroform_ref, Object::Dictionary(acroform_dict));
    Ok(dr_ref)
}

/// Merge `source_dr`'s resource entries into the dict at `dest_dr`, which may
/// already carry entries of its own (e.g. a pre-existing dest `/AcroForm/DR`).
/// Mirrors qpdf's `QPDFObjectHandle::mergeResources`.
///
/// For each top-level key (resource type: `/Font`, `/XObject`, `/ColorSpace`,
/// ...), source's per-name entries are merged into a dest-owned copy of that
/// category's sub-dict, so `dest_dr` and `source_dr` never share mutable
/// sub-dict state:
/// - a source name absent from dest's sub-dict is inserted verbatim;
/// - a source name present in dest's sub-dict pointing at the SAME object
///   (by [`ObjectRef`] identity, not deep equality — matches qpdf's
///   `QPDFObjGen`-based check) is a no-op;
/// - a source name present in dest's sub-dict pointing at a DIFFERENT object
///   is a genuine conflict: the source's entry is inserted under the
///   smallest unused `{name}_N` (`N` starting at 1, scanned against the dest
///   sub-dict as it grows during this call — qpdf's `getUniqueResourceName`),
///   and `(name, {name}_N)` is recorded into `dr_map[type]`.
///
/// Individual resource entries (e.g. `/F1 8 0 R`) are shallow-cloned — they
/// are typically refs, so the clone is cheap and the dest and source paths
/// continue to share the underlying font/xobject objects (as qpdf does).
///
/// Dest-scoped rename reuse: qpdf's `mergeResources` maintains a
/// `QPDFObjGen -> name` map on the dest `/DR` so the same colliding source
/// object gets the same renamed dest name on every subsequent call. Callers
/// therefore share a single `dr_map` across every merge into the same
/// destination (see `apply_aggregated_sources` in `overlay.rs`); when a
/// collision recurs and `dr_map` already records the rename and the mapped
/// dest name still holds the same source ref, the rename is reused rather
/// than minting a fresh `_N`. Byte parity across repeated placements onto a
/// pre-conflicting dest `/DR` depends on this reuse — every field's `/DA` and
/// every AP stream must reference the same renamed name across pages.
fn merge_resources_shallow<R: Read + Seek>(
    dest: &mut Pdf<R>,
    dest_dr: ObjectRef,
    source_dr: ObjectRef,
    dr_map: &mut DrMap,
) -> Result<()> {
    let Some(src_dict) = dest.resolve(source_dr)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let Some(mut dest_dict) = dest.resolve(dest_dr)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    // Reset the placement-scoped name map to the identity mappings this
    // merge is about to establish. `by_source_ref` is dest-scoped and
    // persists (that is how repeated collisions from the same source object
    // reuse a prior rename); `by_name` describes only THIS placement's
    // fields' /DA rewrite plan, so a stale entry from a prior merge of a
    // different source must NOT leak into
    // `adjust_default_appearance`'s lookup during the field-tree walk that
    // follows this merge.
    dr_map.by_name.clear();
    // PDF permits `/Font <ref>` (indirect resource-type sub-dict) as well as
    // the direct-dict shape; qpdf's `QPDFObjectHandle::mergeResources`
    // operates on resolved QPDFObjectHandle values, so both shapes must
    // merge — losing an indirect source sub-dict would drop the referenced
    // fonts entirely. `src_dict` is owned (from `into_dict`), so the loop's
    // borrow of it does not collide with `dest.resolve(...)` on the mutable
    // `dest` — both borrows are of separate variables.
    for (type_key, src_type_val) in src_dict.iter() {
        let src_type_dict = match src_type_val {
            Object::Reference(r) => dest.resolve(*r)?.into_dict(),
            _ => src_type_val.as_dict().cloned(),
        };

        let Some(src_type_dict) = src_type_dict else {
            // cov:ignore-start: verbatim-copy path — non-dict resource-type
            // value from an unusual source /DR shape (either a non-dict/-ref
            // direct value, or an indirect ref that does not resolve to a
            // dict). No shipped fixture supplies this shape.
            if dest_dict.get(type_key).is_none() {
                dest_dict.insert(type_key, src_type_val.clone());
            }
            continue;
            // cov:ignore-end
        };

        // Resolve dest's existing sub-dict for this type (if any) so a
        // pre-existing dest `/DR` category is preserved rather than
        // replaced. When the dest sub-dict is INDIRECT, allocate a NEW
        // indirect object holding a shallow copy of the referenced dict
        // and re-point `dest_dict[type_key]` at it — mirroring qpdf's
        // `this_val = replaceKeyAndGetNew(rtype, this_val.shallowCopy())`
        // in `QPDFObjectHandle::mergeResources`. Mutating the ORIGINAL
        // referenced object in place would leak the merge (and any
        // subsequent `_N` renames) into every other holder of that ref.
        let (mut new_type_dict, new_indirect_target) = match dest_dict.get(type_key).cloned() {
            Some(Object::Dictionary(existing)) => (existing, None),
            Some(Object::Reference(r)) => match dest.resolve(r)?.into_dict() {
                Some(d) => (d, Some(allocate_next_ref(dest)?)),
                // cov:ignore-start: dest resource-type ref does not resolve
                // to a dict — degrade to a fresh dict and replace inline.
                // No shipped fixture supplies this malformed shape.
                None => (crate::Dictionary::new(), None),
                // cov:ignore-end
            },
            _ => (crate::Dictionary::new(), None),
        };

        // Seed `by_source_ref` from dest's PRE-EXISTING category entries so
        // a source ref that turns out to already sit under some dest name
        // (from a prior life of the dest `/DR`, not a prior merge) can be
        // reused instead of duplicated. Same idea as recording verbatim
        // inserts below: without this, source `/F2 <ref>` colliding with
        // dest's `/F2 <other-ref>` would mint `/F2_1` even when the source
        // ref already sits in dest under `/F1`.
        for (existing_name, existing_val) in new_type_dict.iter() {
            if let Object::Reference(existing_ref) = existing_val {
                dr_map
                    .by_source_ref
                    .entry((type_key.to_vec(), *existing_ref))
                    .or_insert_with(|| existing_name.to_vec());
            } // cov:ignore: closing brace of the `if let Object::Reference` — llvm-cov instrumentation artifact; the body is exercised by `merge_resources_shallow_reuses_preexisting_dest_ref_at_different_name`.
        }

        for (name, val) in src_type_dict.iter() {
            match new_type_dict.get(name) {
                None => {
                    new_type_dict.insert(name, val.clone());
                    // Record the freshly-installed name against its source
                    // ref so a LATER entry in this same merge that collides
                    // under a DIFFERENT name but points at the SAME source
                    // object can reuse this one instead of minting a
                    // duplicate. Example: source `/DR/Font { /F1 X /F2 X }`
                    // into dest with only `/F2 Y` — qpdf inserts `/F1 X`
                    // verbatim, then on `/F2 X` sees `X` is already in dest
                    // under `/F1` and rewrites the `/DA` `/F2` operand to
                    // `/F1` rather than adding a `/F2_1` alias.
                    if let Some(source_ref) = val.as_ref_id() {
                        dr_map
                            .by_source_ref
                            .entry((type_key.to_vec(), source_ref))
                            .or_insert_with(|| name.to_vec());
                    } // cov:ignore: closing brace of the `if let Some(source_ref)` — llvm-cov instrumentation artifact; the body is exercised by `merge_resources_shallow_reuses_verbatim_insert_from_same_source_ref`.
                }
                Some(existing_val) => {
                    // Same-name collision. qpdf's short-circuit is object
                    // identity (QPDFObjGen), not deep equality — a direct
                    // (non-reference) value can never match here even if
                    // structurally equal, matching mergeResources.
                    let same_object = matches!(
                        (existing_val, val),
                        (Object::Reference(d), Object::Reference(s)) if d == s
                    );
                    if same_object {
                        continue;
                    }
                    // If THIS source object was already renamed on a prior
                    // merge call against the same dest `/DR`, reuse that
                    // rename instead of minting a fresh `_N`. Mirrors
                    // qpdf's dest-scoped `QPDFObjGen -> name` reuse map:
                    // byte parity across repeated placements onto the same
                    // dest depends on the colliding source object producing
                    // the same renamed name every time.
                    //
                    // Reuse is keyed by SOURCE `ObjectRef`, not by source
                    // NAME — two different source objects that both collide
                    // under `/F1` (e.g. two OverlaySpecs whose sources both
                    // use `/F1`) must produce distinct dest names
                    // (`/F1_1`, `/F1_2`), and a name-keyed reuse would let
                    // the second overwrite the first and mis-reuse on a
                    // later placement.
                    let reuse_key = val.as_ref_id().map(|r| (type_key.to_vec(), r));
                    let reuse = reuse_key
                        .as_ref()
                        .and_then(|k| dr_map.by_source_ref.get(k))
                        .cloned();
                    if let Some(existing_new_name) = reuse {
                        // Refresh `by_name` for this call's placement so
                        // `adjust_default_appearance` sees the reused
                        // rename under this source's name. Skip the
                        // dest-dict insert (already carries the same ref
                        // under `existing_new_name`).
                        dr_map
                            .by_name
                            .entry(type_key.to_vec())
                            .or_default()
                            .insert(name.to_vec(), existing_new_name);
                        continue;
                    }
                    let new_name = unique_dr_name(name, &new_type_dict)?;
                    new_type_dict.insert(&new_name, val.clone());
                    dr_map
                        .by_name
                        .entry(type_key.to_vec())
                        .or_default()
                        .insert(name.to_vec(), new_name.clone());
                    if let Some(key) = reuse_key {
                        dr_map.by_source_ref.insert(key, new_name);
                    }
                }
            }
        }

        if let Some(new_ref) = new_indirect_target {
            // qpdf-parity: dest sub-dict was indirect, so install the merged
            // dict into a freshly-allocated indirect object and re-point
            // dest_dict at it. The ORIGINAL indirect object is untouched —
            // other holders of the same ref are not affected.
            dest.set_object(new_ref, Object::Dictionary(new_type_dict));
            dest_dict.insert(type_key, Object::Reference(new_ref));
        } else {
            dest_dict.insert(type_key, Object::Dictionary(new_type_dict));
        }
    }
    dest.set_object(dest_dr, Object::Dictionary(dest_dict));
    Ok(())
}

/// Smallest `{base}_N` (`N` starting at 1) absent from `dict`, scanning
/// `dict` as it stands at call time — so repeated calls within the same
/// [`merge_resources_shallow`] pass see names inserted by earlier collisions
/// in that pass and do not reissue them. Mirrors qpdf's
/// `getUniqueResourceName`.
///
/// Also reused by
/// [`crate::overlay_appearance_stream::adjust_appearance_stream`] to mint a
/// stream-local unique name for the rare case where an appearance stream's
/// own (private) `/Resources` already has a *different* entry under a
/// `DrMap` rename's target name (`libqpdf/QPDFAcroFormDocumentHelper.cc:791-807`'s
/// `merge_with` re-merge).
///
/// # Errors
///
/// [`Error::Unsupported`] if `u32` wraps before an unused suffix is found
/// (would require billions of colliding names under one base).
pub(crate) fn unique_dr_name(base: &[u8], dict: &crate::Dictionary) -> Result<Vec<u8>> {
    let mut n: u32 = 1;
    loop {
        let candidate = [base, b"_", n.to_string().as_bytes()].concat();
        if dict.get(&candidate).is_none() {
            return Ok(candidate);
        }
        n = n
            .checked_add(1)
            .ok_or_else(|| Error::Unsupported("DR resource-name suffix space exhausted".into()))?;
    }
}

/// After every placement on a destination page has been applied, add the
/// collected new top-level fields to the dest `/AcroForm/Fields` with fully
/// qualified name collision renaming (qpdf's `+N` suffix scheme).
///
pub(crate) fn add_and_rename_form_fields<R: Read + Seek>(
    dest: &mut Pdf<R>,
    new_top_fields: Vec<ObjectRef>,
) -> Result<()> {
    if new_top_fields.is_empty() {
        return Ok(());
    }
    let Some(root_ref) = dest.root_ref() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let mut catalog = match dest.resolve(root_ref)?.into_dict() {
        Some(d) => d,
        None => return Ok(()), // cov:ignore: defensive early return
    };

    // Get or create /AcroForm. When apply_placement's `ensure_dest_acroform_dr`
    // ran (source had /DR), it already promoted the AcroForm to indirect and
    // this branch just uses that ref. When it did NOT run (source has no /DR),
    // we may still see a direct AcroForm here — promote it in place preserving
    // its existing contents (/Fields, /DA, /Q, /NeedAppearances, ...). Only
    // a truly missing/non-dict AcroForm gets a fresh empty one.
    let acroform_ref = match catalog.get("AcroForm").cloned() {
        Some(Object::Reference(r)) => r,
        // cov:ignore-start: direct-/AcroForm promotion inside
        // add_and_rename_form_fields — symmetric with
        // ensure_dest_acroform_dr's direct-/AcroForm branch; qpdf normalizes
        // /AcroForm to indirect on write so no shipped fixture reaches it.
        Some(Object::Dictionary(existing)) => {
            let r = allocate_next_ref(dest)?;
            dest.set_object(r, Object::Dictionary(existing));
            catalog.insert("AcroForm", Object::Reference(r));
            dest.set_object(root_ref, Object::Dictionary(catalog));
            r
        }
        // cov:ignore-end
        // cov:ignore-start: fresh-AcroForm creation only fires when
        // apply_placement's ensure_dest_acroform_dr did NOT run (source
        // had no /DR) yet new_top_fields is non-empty. All shipped
        // fixtures that produce fields (primary + defaults + p_and_inline
        // + direct-dr + existing-af + indirect-fields) also carry a
        // source /DR, so ensure runs and this branch stays cold.
        _ => {
            let mut dict = crate::Dictionary::new();
            dict.insert("Fields", Object::Array(Vec::new()));
            let r = allocate_next_ref(dest)?;
            dest.set_object(r, Object::Dictionary(dict));
            catalog.insert("AcroForm", Object::Reference(r));
            dest.set_object(root_ref, Object::Dictionary(catalog));
            r
        } // cov:ignore-end
    };

    // Build the set of existing FULLY-QUALIFIED field names, walking the
    // existing /AcroForm/Fields tree. On a fresh dest with no fields, this
    // starts empty and the first placement adds without renaming.
    let mut existing_fqns: BTreeSet<Vec<u8>> = BTreeSet::new();
    let existing_top_field_refs = read_existing_top_field_refs(dest, acroform_ref)?;
    for &top in &existing_top_field_refs {
        collect_fully_qualified_names(dest, top, Vec::new(), 0, &mut existing_fqns)?;
    }

    // BFS the new top fields, renaming /T on FQN collision (`+N` suffix).
    // Every field re-runs the collision check against the live `existing_fqns`
    // set (which is updated per-field below), so two independently-copied
    // fields that happen to share the same source FQN each pick a distinct
    // suffix instead of colliding in the dest AcroForm. A cache keyed by
    // old_fqn would produce the same suffix for both and re-introduce the
    // collision.
    let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut queue: std::collections::VecDeque<ObjectRef> = new_top_fields.iter().copied().collect();
    while let Some(field_ref) = queue.pop_front() {
        if !seen.insert(field_ref) {
            continue; // cov:ignore: field revisited via /Kids sharing — defensive
        }
        // Compute the OLD fully-qualified name (before any rename). Top-level
        // fields have no /Parent so FQN == /T. Sub-fields with /T get parent
        // FQN + "." + own /T. Because we rename by mutating /T in place, the
        // parent's /T at the time of the child's FQN computation is ALREADY
        // renamed if the parent was processed first — but the BFS visits
        // parents before kids, so the child sees the RENAMED parent /T. This
        // matches qpdf's behavior: renaming is done depth-first-ish via BFS
        // and the fully-qualified name computed inside the loop after the
        // parent's /T rewrite reflects the new name.
        let has_t = {
            let obj = dest.resolve_borrowed(field_ref)?;
            let Some(dict) = obj.as_dict() else { continue };
            dict.get("T").is_some()
        };
        if has_t {
            let old_fqn = fully_qualified_name_of(dest, field_ref)?;
            let append = {
                let mut candidate_fqn = old_fqn.clone();
                let mut suffix = 0u32;
                let mut append = Vec::new();
                while existing_fqns.contains(&candidate_fqn) {
                    // cov:ignore-start: u32 overflow on 4 billion suffix bumps — unreachable
                    suffix = suffix.checked_add(1).ok_or_else(|| {
                        Error::Unsupported("field name suffix space exhausted".into())
                    })?;
                    // cov:ignore-end
                    append = format!("+{suffix}").into_bytes();
                    candidate_fqn = old_fqn.clone();
                    candidate_fqn.extend_from_slice(&append);
                }
                append
            };
            if !append.is_empty() {
                let Some(mut dict) = dest.resolve(field_ref)?.into_dict() else {
                    continue; // cov:ignore: field ref resolved to non-dict — malformed
                };
                let old_t = match dict.get("T").cloned() {
                    Some(Object::String(s)) => s,
                    Some(_) => Vec::new(), // cov:ignore: match arm — defensive on unexpected shape
                    None => Vec::new(),    // cov:ignore: defensive `None` match arm
                };
                let mut new_t = old_t;
                new_t.extend_from_slice(&append);
                dict.insert("T", Object::String(new_t));
                dest.set_object(field_ref, Object::Dictionary(dict));
            }
            // Add the final (possibly renamed) FQN to the existing set so
            // subsequent placements' fields with the same source name pick a
            // NEW suffix.
            let mut final_fqn = old_fqn;
            final_fqn.extend_from_slice(&append);
            existing_fqns.insert(final_fqn);
        }

        // Enqueue kids (they may carry /T and need FQN collision handling).
        let kids_refs = {
            let obj = dest.resolve_borrowed(field_ref)?;
            let Some(dict) = obj.as_dict() else { continue };
            match dict.get("Kids") {
                Some(Object::Array(arr)) => arr
                    .iter()
                    .filter_map(|item| match item {
                        Object::Reference(r) => Some(*r),
                        _ => None, // cov:ignore: fallback match arm — defensive/malformed input
                    })
                    .collect::<Vec<_>>(),
                _ => Vec::new(),
            }
        };
        for k in kids_refs {
            queue.push_back(k);
        }
    }

    // Finally append the new top-level fields to /AcroForm/Fields (they may
    // now have renamed /T). /Fields may be a direct array or an indirect ref
    // to one; preserve the existing entries in either shape.
    let Some(mut acroform_dict) = dest.resolve(acroform_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    match acroform_dict.get("Fields").cloned() {
        Some(Object::Reference(fields_ref)) => {
            // Indirect /Fields: update the array in place so any other
            // references to it (there shouldn't be any, but be conservative)
            // stay valid.
            let mut fields = match dest.resolve(fields_ref)? {
                Object::Array(arr) => arr,
                _ => Vec::new(), // cov:ignore: fallback match arm — defensive/malformed input
            };
            for r in new_top_fields {
                fields.push(Object::Reference(r));
            }
            dest.set_object(fields_ref, Object::Array(fields));
        }
        other => {
            let mut fields = match other {
                Some(Object::Array(arr)) => arr,
                _ => Vec::new(), // cov:ignore: fallback match arm — defensive/malformed input
            };
            for r in new_top_fields {
                fields.push(Object::Reference(r));
            }
            acroform_dict.insert("Fields", Object::Array(fields));
            dest.set_object(acroform_ref, Object::Dictionary(acroform_dict));
        }
    }
    Ok(())
}

/// Read the existing top-level field refs from `dest`'s AcroForm/Fields.
/// Returns an empty vec when /Fields is missing or malformed.
fn read_existing_top_field_refs<R: Read + Seek>(
    dest: &mut Pdf<R>,
    acroform_ref: ObjectRef,
) -> Result<Vec<ObjectRef>> {
    let Some(dict) = dest.resolve(acroform_ref)?.into_dict() else {
        return Ok(Vec::new()); // cov:ignore: defensive early return
    };
    let fields = match dict.get("Fields").cloned() {
        Some(Object::Array(arr)) => arr,
        Some(Object::Reference(r)) => match dest.resolve(r)? {
            Object::Array(arr) => arr,
            _ => return Ok(Vec::new()), // cov:ignore: defensive early return
        },
        _ => return Ok(Vec::new()), // cov:ignore: defensive early return
    };
    Ok(fields
        .into_iter()
        .filter_map(|item| match item {
            Object::Reference(r) => Some(r),
            _ => None, // cov:ignore: fallback match arm — defensive/malformed input
        })
        .collect())
}

/// BFS `field_ref`'s tree, collecting the fully-qualified name of every node
/// that carries a /T. Bounded by [`MAX_PARENT_WALK_DEPTH`] via `depth`.
fn collect_fully_qualified_names<R: Read + Seek>(
    dest: &mut Pdf<R>,
    field_ref: ObjectRef,
    parent_fqn: Vec<u8>,
    depth: usize,
    out: &mut BTreeSet<Vec<u8>>,
) -> Result<()> {
    // cov:ignore-start: defensive early return on field-tree depth overflow
    if depth > MAX_PARENT_WALK_DEPTH {
        return Err(Error::Unsupported(format!(
            "AcroForm field tree exceeds maximum depth of {MAX_PARENT_WALK_DEPTH}"
        )));
    }
    // cov:ignore-end
    // Reading /T and /Kids in two steps: /T uses a borrowed read, then /Kids
    // may need to resolve an indirect array (which requires a mutable borrow
    // and therefore drops the borrowed read first). Both direct-array and
    // indirect-array forms of /Kids are valid per ISO 32000 and appear in
    // real-world AcroForm docs.
    let (own_fqn, kids_val) = {
        let obj = dest.resolve_borrowed(field_ref)?;
        let Some(dict) = obj.as_dict() else {
            return Ok(()); // cov:ignore: defensive early return
        };
        let own_fqn = match dict.get("T") {
            Some(Object::String(t)) => {
                let mut fqn = parent_fqn.clone();
                if !fqn.is_empty() {
                    fqn.push(b'.'); // cov:ignore: nested /T under a parent that also has /T — none of the shipped fixtures nest
                }
                fqn.extend_from_slice(t);
                Some(fqn)
            }
            _ => None,
        };
        (own_fqn, dict.get("Kids").cloned())
    };
    let kids_refs: Vec<ObjectRef> = match kids_val {
        Some(Object::Array(arr)) => arr
            .iter()
            .filter_map(|item| match item {
                Object::Reference(r) => Some(*r),
                _ => None, // cov:ignore: fallback match arm — defensive/malformed input
            })
            .collect(),
        // cov:ignore-start: indirect-/Kids resolution — a dest field whose
        // /Kids is stored as an indirect ref is a shape my Fixture 5
        // (fxo-red-indirect-fields) exercises for /Fields but not for
        // /Kids specifically; no shipped fixture nests an indirect-/Kids
        // sub-field under a top-level widget.
        Some(Object::Reference(r)) => match dest.resolve(r)? {
            Object::Array(arr) => arr
                .into_iter()
                .filter_map(|item| match item {
                    Object::Reference(r) => Some(r),
                    _ => None,
                })
                .collect(),
            _ => Vec::new(),
        },
        // cov:ignore-end
        _ => Vec::new(),
    };
    let recursion_fqn = own_fqn.clone().unwrap_or(parent_fqn);
    if let Some(fqn) = own_fqn {
        out.insert(fqn);
    }
    for kid in kids_refs {
        collect_fully_qualified_names(dest, kid, recursion_fqn.clone(), depth + 1, out)?;
    }
    Ok(())
}

/// Compute the fully-qualified name of a field by walking its /Parent chain
/// upward (qpdf `getFullyQualifiedName`). Bounded by
/// [`MAX_PARENT_WALK_DEPTH`].
fn fully_qualified_name_of<R: Read + Seek>(
    dest: &mut Pdf<R>,
    field_ref: ObjectRef,
) -> Result<Vec<u8>> {
    let mut names_reverse: Vec<Vec<u8>> = Vec::new();
    let mut current = field_ref;
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    // cov:ignore-start: defensive /Parent walk bailouts (cycle break,
    // non-dict parent, missing /T non-string arm) are hostile-input
    // guards; `_ => None` on /T fires only when a field lacks /T (no
    // shipped fixture nests such a field); and the "current = p"
    // continuation is exercised by every widget with a parent but
    // llvm-cov's guard-line instrumentation reports 0 hits on match
    // arms of the form `Some(p) => …`.
    for _ in 0..MAX_PARENT_WALK_DEPTH {
        if !visited.insert(current) {
            break;
        }
        let (t_opt, parent) = {
            let obj = dest.resolve_borrowed(current)?;
            let Some(dict) = obj.as_dict() else {
                break;
            };
            let t_opt = match dict.get("T") {
                Some(Object::String(s)) => Some(s.clone()),
                _ => None,
            };
            let parent = dict.get_ref("Parent");
            (t_opt, parent)
        };
        if let Some(t) = t_opt {
            names_reverse.push(t);
        }
        match parent {
            Some(p) => current = p,
            None => break,
        }
    }
    // cov:ignore-end
    // Reverse to root-to-leaf order and join with '.'.
    names_reverse.reverse();
    let mut out = Vec::new();
    for (i, n) in names_reverse.iter().enumerate() {
        if i > 0 {
            out.push(b'.'); // cov:ignore: nested-field FQN join — no shipped fixture nests fields under a parent that also has /T
        }
        out.extend_from_slice(n);
    }
    Ok(out)
}

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

    /// Minimal single-object (`/Type /Catalog`, no `/AcroForm`) PDF, just
    /// enough for [`Pdf::open`] to accept. Tests layer additional objects
    /// onto it via [`Pdf::set_object`] at object numbers beyond the xref
    /// table — the same pattern `allocate_next_ref` relies on elsewhere in
    /// this crate (a `set_object` at a fresh number is accepted and shows up
    /// in `object_refs()`/is resolvable immediately).
    fn minimal_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref_start = pdf.len() as u64;
        pdf.extend_from_slice(
            format!("xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \n").as_bytes(),
        );
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    fn open_minimal() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open(Cursor::new(minimal_pdf_bytes())).expect("minimal pdf should parse")
    }

    /// Set object `n` (generation 0) to a dictionary built from `entries` and
    /// return its ref.
    fn set_dict<R: Read + Seek>(pdf: &mut Pdf<R>, n: u32, entries: &[(&str, Object)]) -> ObjectRef {
        let mut d = crate::Dictionary::new();
        for (k, v) in entries {
            d.insert(*k, v.clone());
        }
        let r = ObjectRef::new(n, 0);
        pdf.set_object(r, Object::Dictionary(d));
        r
    }

    /// Build a one-category `/Font << name ref, ... >>` resource dict object.
    fn set_font_dr<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        n: u32,
        entries: &[(&str, ObjectRef)],
    ) -> ObjectRef {
        let mut font = crate::Dictionary::new();
        for (name, r) in entries {
            font.insert(*name, Object::Reference(*r));
        }
        set_dict(pdf, n, &[("Font", Object::Dictionary(font))])
    }

    fn font_dict<R: Read + Seek>(pdf: &mut Pdf<R>, dr_ref: ObjectRef) -> crate::Dictionary {
        let dr = pdf.resolve(dr_ref).unwrap().into_dict().unwrap();
        dr.get("Font").and_then(Object::as_dict).unwrap().clone()
    }

    // ---- merge_resources_shallow ------------------------------------------

    #[test]
    fn merge_resources_shallow_dest_empty_is_verbatim_insert() {
        let mut pdf = open_minimal();
        let font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let dest_dr = set_dict(&mut pdf, 2, &[]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", font_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert!(dr_map.is_empty());
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(font_ref));
    }

    #[test]
    fn merge_resources_shallow_renames_on_collision_with_different_ref() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", helv_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", courier_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec())
        );
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(helv_ref));
        assert_eq!(font.get_ref("F1_1"), Some(courier_ref));
    }

    #[test]
    fn merge_resources_shallow_same_ref_collision_is_noop() {
        let mut pdf = open_minimal();
        let font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", font_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", font_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert!(dr_map.is_empty());
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(font_ref));
        assert!(font.get("F1_1").is_none());
    }

    #[test]
    fn merge_resources_shallow_scans_past_taken_suffix_to_next_n() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let other_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"TimesRoman".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            12,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        // Pre-seed dest with BOTH F1 (which will collide with source) and
        // F1_1 (an unrelated pre-existing entry that already occupies the
        // first rename candidate), forcing the suffix scan to skip to F1_2.
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", helv_ref), ("F1_1", other_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", courier_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_2".to_vec())
        );
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(helv_ref));
        assert_eq!(font.get_ref("F1_1"), Some(other_ref));
        assert_eq!(font.get_ref("F1_2"), Some(courier_ref));
    }

    /// Source `/DR/Font` is stored as an indirect reference (not a direct
    /// sub-dict). qpdf's `mergeResources` resolves the reference and merges
    /// the underlying dict; a naive implementation that only matched
    /// `Object::Dictionary` would drop the fonts entirely.
    #[test]
    fn merge_resources_shallow_resolves_indirect_source_resource_type_dict() {
        let mut pdf = open_minimal();
        let font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        // Indirect /Font sub-dict on the source side: /Font 4 0 R where 4 0 R
        // resolves to << /F1 10 0 R >>.
        let font_subdict_ref = ObjectRef::new(4, 0);
        let mut font_sub = crate::Dictionary::new();
        font_sub.insert("F1", Object::Reference(font_ref));
        pdf.set_object(font_subdict_ref, Object::Dictionary(font_sub));
        let source_dr = set_dict(
            &mut pdf,
            3,
            &[("Font", Object::Reference(font_subdict_ref))],
        );
        let dest_dr = set_dict(&mut pdf, 2, &[]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert!(dr_map.is_empty());
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(font_ref));
    }

    /// Dest `/DR/Font` is stored as an indirect reference potentially
    /// shared with other holders. qpdf's `mergeResources` shallow-copies
    /// the referenced dict into a FRESH indirect object and re-points
    /// dest's `/Font` at the new ref
    /// (`this_val = replaceKeyAndGetNew(rtype, this_val.shallowCopy())` in
    /// `QPDFObjectHandle::mergeResources`); the ORIGINAL indirect object
    /// stays untouched so unrelated holders keep their original content.
    /// A naive implementation that mutated the original object in place
    /// would leak the merge (and any subsequent `_N` renames) into every
    /// other holder of that ref.
    #[test]
    fn merge_resources_shallow_copies_indirect_dest_sub_dict_into_fresh_ref() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        // Indirect /Font sub-dict on the dest side: /Font 4 0 R where 4 0 R
        // resolves to << /F0 10 0 R >> (F0 = Helvetica).
        let dest_font_subdict_ref = ObjectRef::new(4, 0);
        let mut dest_font_sub = crate::Dictionary::new();
        dest_font_sub.insert("F0", Object::Reference(helv_ref));
        pdf.set_object(dest_font_subdict_ref, Object::Dictionary(dest_font_sub));
        let dest_dr = set_dict(
            &mut pdf,
            2,
            &[("Font", Object::Reference(dest_font_subdict_ref))],
        );
        // Direct /Font sub-dict on the source side, adding a fresh F1.
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", courier_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        assert!(dr_map.is_empty(), "no name collision, no rename");
        // dest's /Font now points at a NEW indirect object (not the original).
        let dest_dict = pdf.resolve(dest_dr).unwrap().into_dict().unwrap();
        let new_font_ref = dest_dict.get_ref("Font").expect("Font must be indirect");
        assert_ne!(
            new_font_ref, dest_font_subdict_ref,
            "qpdf shallow-copies indirect sub-dicts into a fresh ref",
        );
        // The ORIGINAL indirect object is untouched — still only carries F0.
        let original = pdf
            .resolve(dest_font_subdict_ref)
            .unwrap()
            .into_dict()
            .unwrap();
        assert_eq!(original.get_ref("F0"), Some(helv_ref));
        assert!(
            original.get("F1").is_none(),
            "original indirect object must not be mutated (other holders would see F1 leak)",
        );
        // The NEW indirect object carries the shallow-copied F0 plus F1.
        let merged = pdf.resolve(new_font_ref).unwrap().into_dict().unwrap();
        assert_eq!(merged.get_ref("F0"), Some(helv_ref));
        assert_eq!(merged.get_ref("F1"), Some(courier_ref));
    }

    /// A stale `by_name` entry from a prior merge must NOT leak into the
    /// next placement. Concretely: source A collides and records
    /// `by_name[Font][F1] = F1_1`; source B's `/F1` is a same-object no-op
    /// (its Font equals dest's `F1`), so this merge records nothing new.
    /// `by_name` after B's merge must be empty (not still {F1: F1_1}), so
    /// `adjust_default_appearance` running on B's fields does not rewrite
    /// B's `/F1` to `/F1_1` — which would be catastrophic, since dest's
    /// `/F1_1` is actually A's font.
    #[test]
    fn merge_resources_shallow_clears_stale_by_name_between_source_merges() {
        let mut pdf = open_minimal();
        let times_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Times-Roman".to_vec()))],
        );
        let helv_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", times_ref)]);
        let source_a = set_font_dr(&mut pdf, 3, &[("F1", helv_ref)]);
        // Source B's /F1 points at times_ref, the SAME object dest already
        // holds under /F1 → same_object short-circuit fires, no rename.
        let source_b = set_font_dr(&mut pdf, 4, &[("F1", times_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_a, &mut dr_map).unwrap();
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec()),
        );

        merge_resources_shallow(&mut pdf, dest_dr, source_b, &mut dr_map).unwrap();
        assert!(
            dr_map.is_empty(),
            "by_name must clear at merge start so B's fields don't inherit A's F1→F1_1 mapping"
        );
        // by_source_ref (dest-scoped) must still remember A's rename.
        assert_eq!(
            dr_map.by_source_ref.get(&(b"Font".to_vec(), helv_ref)),
            Some(&b"F1_1".to_vec()),
            "by_source_ref must persist across merges (dest-scoped reuse map)",
        );
    }

    /// Reuse must be keyed by SOURCE `ObjectRef`, not by source name. If
    /// two different sources both collide with dest's `/F1` under the same
    /// old name (e.g. two `OverlaySpec` merges against the same dest), each
    /// must get its own dest name — and a later re-placement of source A
    /// must reuse A's original rename, not follow whatever `by_name`
    /// currently holds (which the intervening B merge overwrote).
    #[test]
    fn merge_resources_shallow_reuse_is_keyed_by_source_ref_not_by_name() {
        let mut pdf = open_minimal();
        let times_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Times-Roman".to_vec()))],
        );
        let helv_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            12,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", times_ref)]);
        // Two distinct source /DR dicts both using /F1 for different fonts.
        let source_a = set_font_dr(&mut pdf, 3, &[("F1", helv_ref)]);
        let source_b = set_font_dr(&mut pdf, 4, &[("F1", courier_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_a, &mut dr_map).unwrap();
        merge_resources_shallow(&mut pdf, dest_dr, source_b, &mut dr_map).unwrap();
        // After A then B: dest has {F1: Times, F1_1: Helv, F1_2: Courier}.
        // by_name["Font"]["F1"] is F1_2 (B's rename, overwrote A's F1_1).
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_2".to_vec()),
        );
        let font_after_ab = font_dict(&mut pdf, dest_dr);
        assert_eq!(font_after_ab.get_ref("F1"), Some(times_ref));
        assert_eq!(font_after_ab.get_ref("F1_1"), Some(helv_ref));
        assert_eq!(font_after_ab.get_ref("F1_2"), Some(courier_ref));

        // Re-merge A: the source_ref-keyed reuse map must recognize helv_ref
        // and reuse its original F1_1, NOT mint an F1_3.
        merge_resources_shallow(&mut pdf, dest_dr, source_a, &mut dr_map).unwrap();
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec()),
            "re-merging source A must refresh by_name back to F1_1 (the ref-keyed reuse)",
        );
        let font_after_aba = font_dict(&mut pdf, dest_dr);
        assert!(
            font_after_aba.get("F1_3").is_none(),
            "must NOT mint F1_3; must reuse F1_1 keyed by helv_ref",
        );
        assert_eq!(font_after_aba.get_ref("F1_1"), Some(helv_ref));
        assert_eq!(font_after_aba.get_ref("F1_2"), Some(courier_ref));
    }

    /// Two `merge_resources_shallow` calls against the SAME dest `/DR` with
    /// the SAME conflicting source: the first call renames `F1` → `F1_1`
    /// and records the mapping in `dr_map`; the second call must reuse
    /// `F1_1` (dr_map already carries the mapping and dest's `F1_1` still
    /// holds the source ref) rather than minting `F1_2`. This is qpdf's
    /// dest-scoped rename-reuse invariant; every field's `/DA` and every
    /// AP stream needs the renamed name to stay stable across placements
    /// or byte parity breaks.
    #[test]
    fn merge_resources_shallow_reuses_prior_rename_across_repeated_calls() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", helv_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", courier_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();
        // First call: F1 collision renamed to F1_1.
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec())
        );

        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();
        // Second call: reuse F1_1 (do NOT mint F1_2).
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec())
        );
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(helv_ref));
        assert_eq!(font.get_ref("F1_1"), Some(courier_ref));
        assert!(
            font.get("F1_2").is_none(),
            "second call must reuse F1_1 rather than minting F1_2"
        );
    }

    /// Within one merge call, when the source category has two entries
    /// (`/F1 X`, `/F2 X`) sharing the same underlying object and dest
    /// lacks `/F1` but has `/F2 Y`: qpdf inserts `/F1 X` verbatim, then
    /// on the `/F2` collision sees that `X` is already sitting at `/F1`
    /// and rewrites the `/F2` operand to `/F1` rather than duplicating
    /// `X` under `/F2_1`. Requires the verbatim-insert path to record
    /// `by_source_ref` so the collision branch can reuse it.
    #[test]
    fn merge_resources_shallow_reuses_verbatim_insert_from_same_source_ref() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        // Dest has only /F2 (Courier), source has /F1 and /F2 both pointing
        // at the same Helvetica ref.
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F2", courier_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", helv_ref), ("F2", helv_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        // by_name records the /F2 → /F1 REUSE (not /F2 → /F2_1).
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F2".as_slice())),
            Some(&b"F1".to_vec()),
            "second collision must reuse the verbatim-inserted /F1 name",
        );
        // dest carries only /F1 (Helv from source) + the pre-existing /F2
        // (Courier). NO /F2_1 duplicate.
        let font = font_dict(&mut pdf, dest_dr);
        assert_eq!(font.get_ref("F1"), Some(helv_ref));
        assert_eq!(font.get_ref("F2"), Some(courier_ref));
        assert!(
            font.get("F2_1").is_none(),
            "must not mint /F2_1 when the source ref is already at /F1",
        );
    }

    /// Same reuse behavior applies when the source ref is already at a
    /// dest name from a PRIOR life of the dest `/DR` (not from an earlier
    /// verbatim insert in the same merge). Pre-populating `by_source_ref`
    /// from `new_type_dict` at the start of each category enables this.
    #[test]
    fn merge_resources_shallow_reuses_preexisting_dest_ref_at_different_name() {
        let mut pdf = open_minimal();
        let helv_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let courier_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        // Dest already has helv_ref sitting at /F1 (from a prior life —
        // could be a hand-crafted /AcroForm/DR). Source uses /F2 for the
        // same helv_ref, colliding with dest's /F2 (Courier).
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", helv_ref), ("F2", courier_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F2", helv_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();

        // by_name records /F2 → /F1 (reuse of the pre-existing dest name).
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F2".as_slice())),
            Some(&b"F1".to_vec()),
        );
        let font = font_dict(&mut pdf, dest_dr);
        assert!(
            font.get("F2_1").is_none(),
            "must reuse the pre-existing /F1 rather than mint /F2_1",
        );
    }

    // ---- ensure_dest_acroform_dr -------------------------------------------

    #[test]
    fn ensure_dest_acroform_dr_creates_fresh_dr_when_dest_has_no_acroform() {
        let mut pdf = open_minimal();
        let font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", font_ref)]);

        let mut dr_map = DrMap::new();
        let dr_ref = ensure_dest_acroform_dr(&mut pdf, source_dr, &mut dr_map).unwrap();

        assert!(dr_map.is_empty());
        let font = font_dict(&mut pdf, dr_ref);
        assert_eq!(font.get_ref("F1"), Some(font_ref));
    }

    /// Simulates two placements onto two different pages of the SAME
    /// destination document: the first call creates a fresh `/AcroForm/DR`
    /// (`dr_map1` stays empty — verbatim insert); the second call finds the
    /// `/AcroForm/DR` already installed as an indirect reference (the
    /// `Some(Object::Reference(existing))` branch) and must reuse it. This is
    /// the invariant this layer must not break: `source_dr` did not change
    /// between calls, so the second call's `F1` collides with dest's `F1`
    /// under the *same* object — a same-ref no-op, not a rename. Every
    /// multi-page overlay byte gate with a form-field source relies on this:
    /// after the first placement establishes the dest `/DR`, every
    /// subsequent placement's `ensure_dest_acroform_dr` call must leave it
    /// untouched rather than minting spurious `F1_1`, `F1_2`, ... entries.
    #[test]
    fn ensure_dest_acroform_dr_reuses_existing_dr_across_repeated_calls_without_rename() {
        let mut pdf = open_minimal();
        let font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", font_ref)]);

        let mut dr_map1 = DrMap::new();
        let dr_ref1 = ensure_dest_acroform_dr(&mut pdf, source_dr, &mut dr_map1).unwrap();
        assert!(dr_map1.is_empty());

        let mut dr_map2 = DrMap::new();
        let dr_ref2 = ensure_dest_acroform_dr(&mut pdf, source_dr, &mut dr_map2).unwrap();

        assert_eq!(dr_ref1, dr_ref2, "the same /DR object must be reused");
        assert!(dr_map2.is_empty(), "same source ref must not be re-renamed");
        let font = font_dict(&mut pdf, dr_ref2);
        assert_eq!(font.get_ref("F1"), Some(font_ref));
        assert!(font.get("F1_1").is_none());
    }

    // ---- apply_placement ----------------------------------------------------

    /// A prior placement on this destination page installed a real DR-level
    /// rename into `dr_map.by_name` (here stood in for directly via
    /// `merge_resources_shallow`, the exact call `apply_placement`'s
    /// per-annot, first-field-triggered merge makes for any placement with a
    /// top-level field). A SECOND placement on the SAME page that carries
    /// annotations but NO top-level field at all (so the trigger condition
    /// never fires) must not see that stale rename: before this fix, neither
    /// arm of the (then pre-loop, unconditional) merge check ran for an
    /// annotation-only placement, so `dr_map.by_name` was left exactly as
    /// the first placement's merge left it — a rename table describing a
    /// DIFFERENT source's fonts, silently available to whatever later reads
    /// `dr_map.by_name` for this placement's own AP streams (roborev PR #490
    /// iter-3 finding 2).
    #[test]
    fn apply_placement_clears_stale_by_name_for_annotation_only_placement() {
        let mut pdf = open_minimal();
        let times_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Times-Roman".to_vec()))],
        );
        let helv_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", times_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", helv_ref)]);

        let mut dr_map = DrMap::new();
        merge_resources_shallow(&mut pdf, dest_dr, source_dr, &mut dr_map).unwrap();
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec()),
            "sanity: the setup step actually populated a stale rename"
        );

        let page_ref = set_dict(&mut pdf, 20, &[]);
        let annot_ref = set_dict(&mut pdf, 21, &[]);
        let template = AnnotationCopyTemplate {
            annots: vec![(annot_ref, None)], // annotation-only: no top-level field
            source_dr: None,
            ..Default::default()
        };
        let mut dest_acroform_dr: Option<ObjectRef> = None;

        apply_placement(
            &mut pdf,
            page_ref,
            &template,
            IDENTITY,
            &mut dest_acroform_dr,
            &mut dr_map,
        )
        .unwrap();

        assert!(
            dr_map.category(b"Font").is_none(),
            "an annotation-only placement (no top-level field) must clear a stale \
             by_name rename left over from a prior placement, not silently carry it \
             forward into whatever reads dr_map for THIS placement's own AP streams"
        );
    }

    /// roborev PR #490 iter-4 finding 2: a non-field annot that precedes the
    /// placement's first field-bearing annot in `/Annots` order must see an
    /// EMPTY `dr_map` when its own AP stream is processed — qpdf's `dr_map`
    /// starts empty for the whole `transformAnnotations` call and is
    /// populated only inside `traverse_field`'s `init_dr_map()`, which fires
    /// exclusively for field-bearing annots
    /// (`libqpdf/QPDFAcroFormDocumentHelper.cc` v11.9.0, `transformAnnotations`,
    /// fetched and verified against the live source: `init_dr_map()` is
    /// called at line ~920, inside `traverse_field`, called only from
    /// `transform_annotation`'s field branch; `adjustAppearanceStream` is
    /// gated by `!dr_map.empty()` at line ~1007, evaluated fresh for EACH
    /// annot in loop order). A prior version of `apply_placement` computed
    /// `has_any_top_field` and ran the merge ONCE, unconditionally, before
    /// the per-annot loop — so every annot in the placement, including one
    /// ordered before the first field, saw the fully-populated map.
    ///
    /// This test places a non-field annot with an AP stream FIRST and a
    /// (self-field) widget SECOND. The destination already has an
    /// `/AcroForm/DR/Font/F1` that collides with the source `/DR/Font/F1`
    /// the widget brings in, so the merge is a REAL, observable rename
    /// (Font: F1 -> F1_1) — not a vacuous no-op. The non-field annot's own
    /// AP stream also happens to use the name `/F1` locally; if `dr_map`
    /// were (incorrectly) already populated when it is processed, its
    /// `/Resources/Font/F1` entry and its `/F1` content token would both get
    /// renamed to `/F1_1`, exactly like the field-triggered collision. This
    /// must NOT happen — the AP stream must come out byte-for-byte
    /// unchanged (aside from the unrelated cm-Matrix dup every AP stream
    /// gets in step 3, which is identity here).
    #[test]
    fn apply_placement_leading_non_field_annot_sees_empty_dr_map() {
        let mut pdf = open_minimal();
        let dest_font_ref = set_dict(
            &mut pdf,
            10,
            &[("BaseFont", Object::Name(b"Times-Roman".to_vec()))],
        );
        let source_font_ref = set_dict(
            &mut pdf,
            11,
            &[("BaseFont", Object::Name(b"Helvetica".to_vec()))],
        );
        let local_font_ref = set_dict(
            &mut pdf,
            12,
            &[("BaseFont", Object::Name(b"Courier".to_vec()))],
        );
        let dest_dr = set_font_dr(&mut pdf, 2, &[("F1", dest_font_ref)]);
        let source_dr = set_font_dr(&mut pdf, 3, &[("F1", source_font_ref)]);

        // Install a destination /AcroForm/DR up front (mirrors
        // `fxo-red-with-existing-acroform-dr.pdf`'s shape) so
        // `ensure_dest_acroform_dr` merges into it — rather than creating a
        // fresh, empty one — and the F1 collision is real.
        let mut acroform = crate::Dictionary::new();
        acroform.insert("Fields", Object::Array(Vec::new()));
        acroform.insert("DR", Object::Reference(dest_dr));
        let acroform_ref = ObjectRef::new(30, 0);
        pdf.set_object(acroform_ref, Object::Dictionary(acroform));
        let mut catalog = crate::Dictionary::new();
        catalog.insert("Type", Object::Name(b"Catalog".to_vec()));
        catalog.insert("AcroForm", Object::Reference(acroform_ref));
        pdf.set_object(ObjectRef::new(1, 0), Object::Dictionary(catalog));

        let page_ref = set_dict(&mut pdf, 20, &[]);

        // Non-field annot: an /AP /N stream with its own local /Resources
        // that ALSO happens to use the name F1 — the name the merge below
        // renames — plus a content token spelling it out, so a wrongly
        // non-empty dr_map at the time this annot is processed would be
        // directly observable.
        let mut ap_font = crate::Dictionary::new();
        ap_font.insert("F1", Object::Reference(local_font_ref));
        let mut ap_resources = crate::Dictionary::new();
        ap_resources.insert("Font", Object::Dictionary(ap_font));
        let ap_stream_ref = ObjectRef::new(22, 0);
        let mut ap_stream_dict = crate::Dictionary::new();
        ap_stream_dict.insert("Resources", Object::Dictionary(ap_resources));
        pdf.set_object(
            ap_stream_ref,
            Object::Stream(crate::Stream::new(ap_stream_dict, b"/F1 10 Tf".to_vec())),
        );
        let mut ap_dict = crate::Dictionary::new();
        ap_dict.insert("N", Object::Reference(ap_stream_ref));
        let non_field_annot_ref = set_dict(&mut pdf, 21, &[("AP", Object::Dictionary(ap_dict))]);

        // Field-bearing annot (self-field widget): appears SECOND in
        // /Annots order, so it is the one that lazily triggers the /DR
        // merge — AFTER the non-field annot above has already been
        // processed by the per-annot loop.
        let field_annot_ref = set_dict(&mut pdf, 23, &[]);

        let template = AnnotationCopyTemplate {
            annots: vec![
                (non_field_annot_ref, None),
                (field_annot_ref, Some(field_annot_ref)),
            ],
            source_dr: Some(source_dr),
            ..Default::default()
        };
        let mut dr_map = DrMap::new();
        let mut dest_acroform_dr: Option<ObjectRef> = None;

        apply_placement(
            &mut pdf,
            page_ref,
            &template,
            IDENTITY,
            &mut dest_acroform_dr,
            &mut dr_map,
        )
        .unwrap();

        // Sanity: the setup did produce a REAL, non-vacuous F1 collision —
        // otherwise this test would pass trivially regardless of the fix.
        assert_eq!(
            dr_map
                .category(b"Font")
                .and_then(|m| m.get(b"F1".as_slice())),
            Some(&b"F1_1".to_vec()),
            "sanity: the widget's field-tree walk must have triggered a real \
             F1 -> F1_1 collision rename"
        );

        let page = pdf.resolve(page_ref).unwrap().into_dict().unwrap();
        let annots_arr = page.get("Annots").and_then(Object::as_array).unwrap();
        assert_eq!(annots_arr.len(), 2);
        let new_non_field_annot_ref = annots_arr[0].as_ref_id().unwrap();

        let new_annot = pdf
            .resolve(new_non_field_annot_ref)
            .unwrap()
            .into_dict()
            .unwrap();
        let new_ap_stream_ref = new_annot
            .get("AP")
            .and_then(Object::as_dict)
            .and_then(|ap| ap.get_ref("N"))
            .expect("dup'd AP /N stream ref");
        let new_ap_stream = pdf
            .resolve(new_ap_stream_ref)
            .unwrap()
            .into_stream()
            .unwrap();
        assert_eq!(
            new_ap_stream.data, b"/F1 10 Tf",
            "the leading non-field annot's AP content must be untouched — \
             dr_map was still empty when it was processed"
        );
        let new_ap_font = new_ap_stream
            .dict
            .get("Resources")
            .and_then(Object::as_dict)
            .and_then(|r| r.get("Font"))
            .and_then(Object::as_dict)
            .expect("AP stream /Resources/Font");
        assert_eq!(
            new_ap_font.get_ref("F1"),
            Some(local_font_ref),
            "the leading non-field annot's own /Resources/Font/F1 must be \
             untouched — no rename applied while dr_map was still empty"
        );
        assert!(
            new_ap_font.get("F1_1").is_none(),
            "no F1_1 entry should have been minted on the non-field annot's \
             AP stream — adjustAppearanceStream must not have run at all"
        );
    }

    // ---- adjust_default_appearance ------------------------------------------

    /// Build a `/DR`-shaped dict `<< /Font << name1 100 0 R, ... >> >>`.
    /// `adjust_default_appearance` only checks name *presence* in the Font
    /// sub-dict, so the target refs are arbitrary placeholders.
    /// Build a per-category resources map with just a `/Font` entry (the
    /// shape now expected by `adjust_default_appearance`, since
    /// `duplicate_field_tree` pre-resolves every category recorded in
    /// `dr_map` before calling).
    fn font_resources_map(names: &[&str]) -> BTreeMap<Vec<u8>, crate::Dictionary> {
        let mut font = crate::Dictionary::new();
        for (i, name) in names.iter().enumerate() {
            font.insert(*name, Object::Reference(ObjectRef::new(100 + i as u32, 0)));
        }
        let mut resources = BTreeMap::new();
        resources.insert(b"Font".to_vec(), font);
        resources
    }

    /// Build a per-category resources map with a single named category
    /// (e.g. `ColorSpace`, `ExtGState`) carrying the listed keys. Used by
    /// tests that exercise `/DA` operators beyond `Tf`.
    fn category_resources_map(
        category: &[u8],
        names: &[&str],
    ) -> BTreeMap<Vec<u8>, crate::Dictionary> {
        let mut sub = crate::Dictionary::new();
        for (i, name) in names.iter().enumerate() {
            sub.insert(*name, Object::Reference(ObjectRef::new(100 + i as u32, 0)));
        }
        let mut resources = BTreeMap::new();
        resources.insert(category.to_vec(), sub);
        resources
    }

    /// Build a `DrMap` with a single category populated from `(old, new)`
    /// pairs. Callers pick the category (`Font`, `ColorSpace`, ...) so the
    /// same helper covers Tf, cs/CS, gs, and friends.
    fn category_dr_map(category: &[u8], entries: &[(&str, &str)]) -> DrMap {
        let mut inner = BTreeMap::new();
        for (old, new) in entries {
            inner.insert(old.as_bytes().to_vec(), new.as_bytes().to_vec());
        }
        let mut dr_map = DrMap::new();
        dr_map.by_name.insert(category.to_vec(), inner);
        dr_map
    }

    #[test]
    fn adjust_default_appearance_empty_dr_map_is_identity() {
        let dr_map = DrMap::new();
        let resources: BTreeMap<Vec<u8>, crate::Dictionary> = BTreeMap::new();
        let da: &[u8] = b"0 0.4 0 rg /F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    /// The canonical case exercised by the (still-ignored) Layer 1 byte
    /// gate: `form-fields-and-annotations.pdf`'s `/DA (0 0.4 0 rg /F1 18
    /// Tf)` merged onto a dest whose `/DR/Font/F1` already existed, renaming
    /// the source's colliding `/F1` to `/F1_1`.
    #[test]
    fn adjust_default_appearance_rewrites_matched_font_name() {
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1", "F1_1"]);
        let da: &[u8] = b"0 0.4 0 rg /F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"0 0.4 0 rg /F1_1 18 Tf".to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_name_not_in_dr_map_is_verbatim() {
        // /ZaDi never collided during the merge (only /F1 did), so it has no
        // dr_map entry and must be left untouched — matching the qpdf golden
        // (`overlay-onto-existing-acroform-dr.pdf`), where every `/ZaDi`
        // `/DA` stays verbatim alongside the renamed `/F1_1` ones.
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["ZaDi"]);
        let da: &[u8] = b"0.18039 0.20392 0.21176 rg /ZaDi 0 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_name_absent_from_resources_is_verbatim() {
        // dr_map has a rename for "F1", but the resources dict's /Font
        // sub-dict does not carry "F1" as a key at all (only an unrelated
        // name) — the safety guard must leave /DA untouched rather than
        // rewrite a name that isn't actually backed by this resources dict.
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["SomeOtherName"]);
        let da: &[u8] = b"0 0.4 0 rg /F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    /// A renamed name containing delimiter bytes must be serialized with
    /// PDF name escaping (`#XX` for delimiters and non-printables), not
    /// spliced in raw. Concretely: a dest key `F A_1` (decoded bytes with
    /// a space) must emit as `/F#20A_1`, not `/F A_1` — the raw form
    /// tokenizes as `/F` followed by an operand run and breaks the /DA.
    #[test]
    fn adjust_default_appearance_escapes_name_bytes_needing_hex_escape() {
        let mut font = BTreeMap::new();
        // Decoded (in-memory) key = "F A_1" — the parser would have decoded
        // "F#20A_1" back to these bytes; the writer must re-escape on emit.
        font.insert(b"F1".to_vec(), b"F A_1".to_vec());
        let mut dr_map = DrMap::new();
        dr_map.by_name.insert(b"Font".to_vec(), font);
        // The dest /Font sub-dict lookup uses the ORIGINAL colliding name
        // ("F1"); the escape only affects the SERIALIZED output.
        let resources = font_resources_map(&["F1"]);
        let da: &[u8] = b"/F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/F#20A_1 18 Tf".to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_name_inside_string_literal_is_verbatim() {
        // `(F1)` is a STRING operand, not a name token, even though its
        // content matches a dr_map key — must not be mistaken for the font
        // name preceding `Tf`.
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1"]);
        let da: &[u8] = b"(F1) 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_skips_comment_verbatim() {
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1", "F1_1"]);
        let da: &[u8] = b"% a comment\n/F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"% a comment\n/F1_1 18 Tf".to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_recovers_from_stray_delimiter() {
        // A stray `)` with no matching `(` does not start any recognised
        // operand (it isn't `/(<[+-.0-9`); the scanner must copy it verbatim
        // and keep scanning rather than aborting, so the `/F1` rename after
        // it still applies.
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1", "F1_1"]);
        let da: &[u8] = b") /F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b") /F1_1 18 Tf".to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_recovers_from_operand_parse_error() {
        // An unterminated string literal (opens `(` but never closes) IS a
        // recognised operand start and reaches the shared object lexer,
        // which returns `Err` on EOF. The scanner must copy only the single
        // `(` byte and resume rather than losing the rest of the string, so
        // the `/F1` rename after it still applies.
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1", "F1_1"]);
        let da: &[u8] = b"(bad /F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"(bad /F1_1 18 Tf".to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_no_font_category_in_dr_map_is_verbatim() {
        // dr_map is non-empty but has no "Font" entry (e.g. only /XObject
        // collisions were recorded) — the Tf-pattern lookup must miss
        // cleanly rather than panic.
        let mut dr_map = DrMap::new();
        dr_map.by_name.insert(b"XObject".to_vec(), BTreeMap::new());
        let resources = font_resources_map(&["F1"]);
        let da: &[u8] = b"/F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    #[test]
    fn adjust_default_appearance_no_font_category_in_resources_is_verbatim() {
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources: BTreeMap<Vec<u8>, crate::Dictionary> = BTreeMap::new();
        let da: &[u8] = b"/F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    /// `/DA (/CS1 cs)` uses a ColorSpace name, not a Font name. When
    /// `merge_resources_shallow` renames `/AcroForm/DR/ColorSpace/CS1`, the
    /// `cs` operator in `/DA` must follow into the renamed name — the
    /// operator table matches qpdf's `ResourceFinder.cc` mapping (`cs` /
    /// `CS` → `ColorSpace`).
    #[test]
    fn adjust_default_appearance_rewrites_colorspace_via_cs_operator() {
        let dr_map = category_dr_map(b"ColorSpace", &[("CS1", "CS1_1")]);
        let resources = category_resources_map(b"ColorSpace", &["CS1", "CS1_1"]);
        let da: &[u8] = b"/CS1 cs 0.5 0.4 0.3 sc /F1 12 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/CS1_1 cs 0.5 0.4 0.3 sc /F1 12 Tf".to_vec()
        );
    }

    /// Uppercase `CS` (stroke color space) shares the ColorSpace category
    /// with lowercase `cs`. Both must rewrite when the color space is
    /// renamed.
    #[test]
    fn adjust_default_appearance_rewrites_colorspace_via_uppercase_cs_operator() {
        let dr_map = category_dr_map(b"ColorSpace", &[("CS1", "CS1_1")]);
        let resources = category_resources_map(b"ColorSpace", &["CS1"]);
        let da: &[u8] = b"/CS1 CS";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/CS1_1 CS".to_vec()
        );
    }

    /// `/DA (/GS1 gs)` uses the ExtGState category. `merge_resources_shallow`
    /// may rename `/ExtGState/GS1`; the operator `gs` picks up its NAME arg
    /// from the tracked `last_name`, same shape as `Tf` — verify the
    /// tokenizer does not stop after finding a Font-only rewrite.
    #[test]
    fn adjust_default_appearance_rewrites_extgstate_via_gs_operator() {
        let dr_map = category_dr_map(b"ExtGState", &[("GS1", "GS1_1")]);
        let resources = category_resources_map(b"ExtGState", &["GS1"]);
        let da: &[u8] = b"/GS1 gs 0 0 0 rg";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/GS1_1 gs 0 0 0 rg".to_vec()
        );
    }

    /// `/DA (/Im1 Do)` uses an XObject reference. Even though `Do` in
    /// `/DA` is atypical (widget /DA usually just sets fonts and colours),
    /// the qpdf operator table maps it, so the tokenizer must too.
    #[test]
    fn adjust_default_appearance_rewrites_xobject_via_do_operator() {
        let dr_map = category_dr_map(b"XObject", &[("Im1", "Im1_1")]);
        let resources = category_resources_map(b"XObject", &["Im1"]);
        let da: &[u8] = b"/Im1 Do";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Im1_1 Do".to_vec()
        );
    }

    /// `/DA (/Sh1 sh)` uses a Shading name. Same shape as `Tf`/`gs` — the
    /// operator picks up the tracked `last_name` and rewrites via the
    /// Shading category.
    #[test]
    fn adjust_default_appearance_rewrites_shading_via_sh_operator() {
        let dr_map = category_dr_map(b"Shading", &[("Sh1", "Sh1_1")]);
        let resources = category_resources_map(b"Shading", &["Sh1"]);
        let da: &[u8] = b"/Sh1 sh";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Sh1_1 sh".to_vec()
        );
    }

    /// `BDC` consumes its SECOND name arg as a Properties entry — the tag
    /// (`/Span`) sets `last_name` first and is then overwritten by the
    /// properties name (`/MC1`), so the tokenizer's single-name tracker
    /// picks up `/MC1` at BDC time. Renaming `Properties/MC1 → MC1_1`
    /// must follow into the marked-content wrapper.
    #[test]
    fn adjust_default_appearance_rewrites_properties_via_bdc_operator() {
        let dr_map = category_dr_map(b"Properties", &[("MC1", "MC1_1")]);
        let resources = category_resources_map(b"Properties", &["MC1"]);
        let da: &[u8] = b"/Span /MC1 BDC /F1 12 Tf EMC";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Span /MC1_1 BDC /F1 12 Tf EMC".to_vec()
        );
    }

    /// `DP` (marked-content point with properties) shares the Properties
    /// category with `BDC` and uses the same tag-then-name shape.
    #[test]
    fn adjust_default_appearance_rewrites_properties_via_dp_operator() {
        let dr_map = category_dr_map(b"Properties", &[("MC1", "MC1_1")]);
        let resources = category_resources_map(b"Properties", &["MC1"]);
        let da: &[u8] = b"/Span /MC1 DP";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Span /MC1_1 DP".to_vec()
        );
    }

    /// Defensive-guard coverage: when a caller hand-constructs a `dr_map`
    /// whose Properties rename maps a name that is NOT present in the
    /// caller-supplied resources dict, the presence guard skips the
    /// rewrite rather than emitting a dangling name.
    ///
    /// NOTE — this configuration is unreachable from any real merge:
    /// `merge_resources_shallow` always keeps the ORIGINAL colliding name
    /// in dest's category sub-dict alongside its `_N` rename, so a
    /// `dr_map[Properties][Span]` entry produced by a merge always
    /// implies `per_category_resources[Properties]` carries `Span`.
    ///
    /// For a `/Span << /K 3 >> BDC` shape where the caller's dr_map DOES
    /// have a Span rename and the resources DO carry Span (the real
    /// merge shape), tag rewriting fires — matching qpdf's
    /// `ResourceFinder` which tracks a single `last_name` overwritten
    /// only by name tokens and records `/Span` as a `/Properties`
    /// resource use regardless of whether the operand after `/Span` was
    /// a dict literal or a name.
    #[test]
    fn adjust_default_appearance_bdc_with_absent_properties_key_is_verbatim() {
        let dr_map = category_dr_map(b"Properties", &[("Span", "Span_1")]);
        let resources = category_resources_map(b"Properties", &["OtherKey"]);
        let da: &[u8] = b"/Span << /K 3 >> BDC";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    /// The real merge shape for a `/Span <<...>> BDC` tag rewrite: qpdf's
    /// `ResourceFinder` treats the last seen NAME token as the operator's
    /// resource operand regardless of whether the following operand was a
    /// name or a dict literal (its `last_name` is only cleared by another
    /// name token, per `libqpdf/ResourceFinder.cc`). When a merge produced
    /// `dr_map[Properties][Span] = Span_1`, dest's `/DR/Properties`
    /// carries both `Span` (original) and `Span_1` (renamed) — the
    /// presence guard passes and the tag rewrite fires, matching qpdf.
    #[test]
    fn adjust_default_appearance_bdc_with_dict_properties_rewrites_tag_matching_qpdf() {
        let dr_map = category_dr_map(b"Properties", &[("Span", "Span_1")]);
        // real merge shape: dest carries both the ORIGINAL colliding name
        // and its renamed counterpart.
        let resources = category_resources_map(b"Properties", &["Span", "Span_1"]);
        let da: &[u8] = b"/Span << /K 3 >> BDC";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Span_1 << /K 3 >> BDC".to_vec()
        );
    }

    /// `/DA (/Pat1 scn)` uses a Pattern name; both `SCN` and `scn` map to
    /// Pattern. Verify the trailing-name pattern operator category is
    /// looked up.
    #[test]
    fn adjust_default_appearance_rewrites_pattern_via_scn_operator() {
        let dr_map = category_dr_map(b"Pattern", &[("Pat1", "Pat1_1")]);
        let resources = category_resources_map(b"Pattern", &["Pat1"]);
        let da: &[u8] = b"/Pat1 scn";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/Pat1_1 scn".to_vec()
        );
    }

    /// Operators that do not take a resource-name arg (`rg`, `Tj`, `TJ`,
    /// numeric literals like `18`) must NOT trigger rewrites, and any
    /// preceding name-typed token must not "carry forward" past them to
    /// the next resource operator.
    #[test]
    fn adjust_default_appearance_ignores_non_resource_operators() {
        let dr_map = category_dr_map(b"Font", &[("F1", "F1_1")]);
        let resources = font_resources_map(&["F1"]);
        // `/F1 rg` is nonsense (rg wants three numbers), but the scanner
        // must not treat rg as a resource operator: the trailing Tf is
        // what carries the rewrite. Here there is no trailing Tf → nothing
        // rewritten.
        let da: &[u8] = b"/F1 rg";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            b"/F1 rg".to_vec()
        );
    }

    /// A rename recorded in `dr_map` for a category the `/DA` never
    /// references (e.g. dr_map has an XObject rename but /DA only uses
    /// Font) must NOT rewrite anything in that `/DA`.
    #[test]
    fn adjust_default_appearance_unmatched_category_in_dr_map_is_verbatim() {
        let dr_map = category_dr_map(b"XObject", &[("Im1", "Im1_1")]);
        let resources = category_resources_map(b"XObject", &["Im1"]);
        let da: &[u8] = b"/F1 18 Tf";
        assert_eq!(
            adjust_default_appearance(da, &dr_map, &resources),
            da.to_vec()
        );
    }

    // ---- end-to-end (structural, not byte-identical) -----------------------

    /// Full `apply_overlay_specs` pipeline over the Layer-1 fixtures used by
    /// the (still-`#[ignore]`d) byte gate in `overlay.rs`, asserting
    /// structure rather than exact bytes so this runs without the
    /// `qpdf-zlib-compat` feature. Restricted to destination page 1 only
    /// (`to: "1"`) so it drives exactly one merge call — the multi-page
    /// repeated-placement reuse case is covered separately by
    /// `overlay_pipeline_repeated_placements_reuse_dr_rename_end_to_end`.
    #[test]
    fn overlay_pipeline_renames_colliding_dr_font_end_to_end() {
        use crate::overlay::{apply_overlay_specs, OverlayKind, OverlaySpec};
        use crate::page_range::PageRange;
        use std::path::Path;

        fn fixture(name: &str) -> Pdf<std::io::BufReader<std::fs::File>> {
            let path = Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/fixtures/compat")
                .join(name);
            let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
            Pdf::open(std::io::BufReader::new(file)).unwrap()
        }
        fn pr(input: &str) -> PageRange {
            PageRange::parse(input).unwrap_or_else(|e| panic!("parse {input:?}: {e}"))
        }

        let mut dest = fixture("fxo-red-with-existing-acroform-dr.pdf");
        let src = fixture("form-fields-and-annotations.pdf");
        let mut specs = vec![OverlaySpec {
            source: src,
            kind: OverlayKind::Overlay,
            from: pr(""),
            to: pr("1"),
            repeat: None,
        }];
        apply_overlay_specs(&mut dest, &mut specs).unwrap();

        let root_ref = dest.root_ref().unwrap();
        let catalog = dest.resolve(root_ref).unwrap().into_dict().unwrap();
        let acroform_ref = catalog.get_ref("AcroForm").unwrap();
        let acroform = dest.resolve(acroform_ref).unwrap().into_dict().unwrap();
        let dr_ref = acroform.get_ref("DR").unwrap();
        let font = font_dict(&mut dest, dr_ref);
        let f1_ref = font.get_ref("F1").expect("original /F1 preserved");
        let f1_1_ref = font.get_ref("F1_1").expect("collision renamed to /F1_1");
        assert_ne!(f1_ref, f1_1_ref);

        let f1_font = dest.resolve(f1_ref).unwrap().into_dict().unwrap();
        assert_eq!(
            f1_font.get("BaseFont"),
            Some(&Object::Name(b"Helvetica".to_vec()))
        );
        let f1_1_font = dest.resolve(f1_1_ref).unwrap().into_dict().unwrap();
        assert_eq!(
            f1_1_font.get("BaseFont"),
            Some(&Object::Name(b"Courier".to_vec()))
        );

        // Layer 3: at least one copied field's /DA must have been rewritten
        // from the collision-renamed /F1 to /F1_1 (adjust_default_appearance,
        // called from duplicate_field_tree). form-fields-and-annotations.pdf
        // supplies `/DA (0 0.4 0 rg /F1 18 Tf)` on its text-box widgets.
        let fields = acroform.get("Fields").and_then(Object::as_array).unwrap();
        let mut saw_rewritten_da = false;
        for field in fields {
            // Every /AcroForm/Fields entry in this fixture is an indirect
            // reference resolving to a dict — unwrap rather than a
            // defensive continue, since a malformed shape here is a test
            // setup bug, not an input to tolerate.
            let field_ref = field.as_ref_id().unwrap();
            let field_dict = dest.resolve(field_ref).unwrap().into_dict().unwrap();
            if let Some(Object::String(da)) = field_dict.get("DA") {
                if da.as_slice() == b"0 0.4 0 rg /F1_1 18 Tf" {
                    saw_rewritten_da = true;
                }
            }
        }
        assert!(
            saw_rewritten_da,
            "expected at least one copied field's /DA rewritten to /F1_1"
        );
    }

    /// Repeated placements onto multiple dest pages: after page 1 renames
    /// the colliding /F1 → /F1_1, every subsequent page must reuse /F1_1
    /// rather than mint /F1_2, /F1_3, ... . qpdf's byte gate expects a
    /// single renamed entry regardless of page count; the dr_map lifetime
    /// (per-dest, threaded through apply_aggregated_sources) and the
    /// rename-reuse branch in merge_resources_shallow are what enforce this.
    #[test]
    fn overlay_pipeline_repeated_placements_reuse_dr_rename_end_to_end() {
        use crate::overlay::{apply_overlay_specs, OverlayKind, OverlaySpec};
        use crate::page_range::PageRange;
        use std::path::Path;

        fn fixture(name: &str) -> Pdf<std::io::BufReader<std::fs::File>> {
            let path = Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/fixtures/compat")
                .join(name);
            let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("open {path:?}: {e}"));
            Pdf::open(std::io::BufReader::new(file)).unwrap()
        }
        fn pr(input: &str) -> PageRange {
            PageRange::parse(input).unwrap_or_else(|e| panic!("parse {input:?}: {e}"))
        }

        let mut dest = fixture("fxo-red-with-existing-acroform-dr.pdf");
        let src = fixture("form-fields-and-annotations.pdf");
        // Overlay the single source page onto three dest pages (--repeat=1
        // cycles it). qpdf's mergeResources fires once per page against the
        // shared dest /DR; without dest-scoped rename reuse this would mint
        // F1_2 and F1_3 on pages 2 and 3.
        let mut specs = vec![OverlaySpec {
            source: src,
            kind: OverlayKind::Overlay,
            from: pr(""),
            to: pr("1-3"),
            repeat: Some(pr("1")),
        }];
        apply_overlay_specs(&mut dest, &mut specs).unwrap();

        let root_ref = dest.root_ref().unwrap();
        let catalog = dest.resolve(root_ref).unwrap().into_dict().unwrap();
        let acroform_ref = catalog.get_ref("AcroForm").unwrap();
        let acroform = dest.resolve(acroform_ref).unwrap().into_dict().unwrap();
        let dr_ref = acroform.get_ref("DR").unwrap();
        let font = font_dict(&mut dest, dr_ref);

        assert!(font.get("F1").is_some(), "original /F1 preserved");
        assert!(font.get("F1_1").is_some(), "collision renamed to /F1_1");
        assert!(
            font.get("F1_2").is_none(),
            "second page must reuse /F1_1, not mint /F1_2"
        );
        assert!(
            font.get("F1_3").is_none(),
            "third page must reuse /F1_1, not mint /F1_3"
        );
    }
}