flpdf 0.9.0

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
//! Resolve page specifications and apply them to qpdf's live primary document.
//! Foreign page graphs are copied into that primary in final occurrence order,
//! while the source documents remain available for deferred stream reads.
//!
//! qpdf correspondence: `QPDFJob::handlePageSpecs` page-selection boundary.
//!
//!

use super::page_merge::source_top_level_field_names;
#[cfg(test)]
use super::page_merge::{merge_documents_for_page_specs_into, MergeInput};
use super::page_plan::PagePlan;
use super::resource_pruning::{
    shared_resource_finding_message, should_remove_unreferenced_resources_with_report,
    RemoveUnreferencedResources,
};
use crate::form_field_object_helper::FormFieldObjectHelper;
#[cfg(test)]
use crate::page_label_document_helper::copy_raw_page_label_entries;
#[cfg(test)]
use crate::page_label_document_helper::LabelRange;
use crate::page_label_document_helper::{
    merge_adjacent_raw_labels, merge_adjacent_raw_page_labels, record_primary_label_provenance,
    RawPageLabelEntry,
};
use crate::pages::tree_rebuild::RebuildResult;
#[cfg(test)]
use crate::pdf::WriterObjectOrderKey;
use crate::qpdf_obj_gen::QpdfObjGen;
#[cfg(test)]
use crate::ObjectStreamMode;
use crate::{
    AcroFormDocumentHelper, Error, Matrix, ObjectHandle, ObjectRef, PageDocumentHelper, PageInput,
    PageObjectHelper, PageRange, Pdf, Result, UsageError,
};
use std::collections::{BTreeMap, BTreeSet};
#[cfg(test)]
use std::io::Cursor;
use std::io::{Read, Seek};

/// One parsed `--pages` specification, referring to a source in the job's
/// source-document array.
///
/// `source_index == 0` is the primary input. The primary may have no
/// corresponding page specification; qpdf still uses it as the catalog and
/// document-level base for the output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PageSpecInput {
    /// Index of the source document in
    /// the job's ordered source list.
    pub(crate) source_index: usize,
    /// Page-range expression selecting pages from this source occurrence.
    pub(crate) range: PageRange,
}

/// Select pages from one already-opened source, retaining source identities.
///
/// This is the planning and page-tree half of qpdf's single-source
/// `QPDFJob::handlePageSpecs`: range resolution remains in `PagePlan`, while
/// the source document itself is rebuilt in place so the writer can emit the
/// original object identities (`QPDFJob.cc:2514-2600`).
fn select_single_source_pages<R: Read + Seek>(
    source: &mut Pdf<R>,
    specs: &[PageSpecInput],
    collate: Option<&[usize]>,
) -> Result<Vec<super::page_plan::SelectedPage>> {
    if specs.is_empty() {
        return Err(Error::Unsupported(
            "--pages: no page specifications were supplied".into(),
        ));
    }

    let mut plans = Vec::with_capacity(specs.len());
    for (spec_index, spec) in specs.iter().enumerate() {
        if spec.source_index != 0 {
            return Err(Error::Unsupported(format!(
                "--pages: single-source specification {spec_index} refers to source {}",
                spec.source_index
            )));
        }
        let source_name = source.input_source_description();
        plans.push(
            PagePlan::build(source, &spec.range)
                .map_err(|error| page_spec_error(&source_name, 0, spec_index, error))?,
        );
    }

    let mut selected = Vec::new();
    let collate_values = collate_values_for_specs(collate, plans.len())?;
    if plans.len() > 1 {
        if let Some(values) = collate_values.as_deref() {
            let mut cursors = vec![0usize; plans.len()];
            loop {
                let mut emitted = false;
                for (plan_index, plan) in plans.iter().enumerate() {
                    let start = cursors[plan_index];
                    let end = start
                        .saturating_add(values[plan_index])
                        .min(plan.pages().len());
                    selected.extend(plan.pages()[start..end].iter().cloned());
                    emitted |= end > start;
                    cursors[plan_index] = end;
                }
                if !emitted {
                    break;
                }
            }
        } else {
            selected.extend(plans.iter().flat_map(|plan| plan.pages().iter().cloned()));
        }
    } else {
        selected.extend(plans.iter().flat_map(|plan| plan.pages().iter().cloned()));
    }

    // qpdf's `handlePageSpecs` (`QPDFJob.cc:2360-2632`) has no empty-selection
    // guard, and `QUtil::parse_numrange` returns an empty vector for a range
    // whose exclusions cancel it out, such as `1,x1` (`QUtil.cc:1385-1400`).
    // qpdf writes a valid 0-page document in that case, so flpdf must not
    // reject it.
    Ok(selected)
}

fn qpdf_page_range_error(source_name: &[u8], error: &Error) -> Option<Error> {
    let message = error.raw_message()?;
    let is_numeric_range = message.starts_with(b"error at * in numeric range ")
        || message.starts_with(b"error in numeric range ");
    if !is_numeric_range {
        return None;
    }
    let mut what = b"parsing numeric range for ".to_vec();
    what.extend_from_slice(source_name);
    what.extend_from_slice(b": ");
    what.extend_from_slice(message);
    Some(Error::SystemBytes(what))
}

fn page_spec_error(
    source_name: &[u8],
    source_index: usize,
    spec_index: usize,
    error: Error,
) -> Error {
    qpdf_page_range_error(source_name, &error).unwrap_or_else(|| {
        Error::Unsupported(format!(
            "--pages: source {source_index} specification {spec_index}: {error}"
        ))
    })
}

fn collate_values_for_specs(
    collate: Option<&[usize]>,
    spec_count: usize,
) -> Result<Option<Vec<usize>>> {
    let Some(values) = collate else {
        return Ok(None);
    };
    if values.is_empty() {
        return Ok(None);
    }
    if values.len() != 1 && values.len() != spec_count {
        return Err(Error::Usage(UsageError::new(
            "--pages: if --collate has more than one value, it must have one value per page specification",
        )));
    }
    if values.len() == 1 && spec_count > 1 {
        return Ok(Some(vec![values[0]; spec_count]));
    }
    Ok(Some(values.to_vec()))
}

/// Apply qpdf's same-document duplicate-page annotation copy while adding a
/// repeated primary page. `QPDFJob.cc:2564-2585` calls
/// `QPDFAcroFormDocumentHelper::fixCopiedAnnotations`
/// (`QPDFAcroFormDocumentHelper.cc:1017-1047`) here, not `copyAnnotations`.
///
/// Both run the same `transformAnnotations`, but they differ on what they do
/// with the destination's existing `/Annots`: `fixCopiedAnnotations` replaces
/// the array outright (`:1040`), while `copyAnnotations` appends to it
/// (`QPDFPageObjectHelper.cc:1032-1037`). Clearing `/Annots` on the
/// destination page before calling [`PageObjectHelper::copy_annotations`]
/// lines the two up when the source's `/Annots` is a non-empty array or is
/// absent, which is what the qtest and compat corpora contain; removing that
/// step would reintroduce the difference.
///
/// The two part ways on two of the inputs `fixCopiedAnnotations` early-returns
/// on (`:1024-1026`): a present but non-array `/Annots` (`null`, say) and an
/// empty array. An absent `/Annots` takes that same return, but there the
/// clear is a no-op and both sides leave the key off, so it stays in the
/// agreeing set above. qpdf leaves whatever page copying installed
/// alone; clearing first drops it, after which `copy_annotations` either
/// returns on its own non-array check
/// (`QPDFPageObjectHelper.cc:999-1001`) or, for an empty array, installs a
/// fresh direct one that no longer shares the original's identity.
pub fn copy_duplicate_page_annotations<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    result: &RebuildResult,
) -> Result<()> {
    let mut first_occurrence: BTreeMap<ObjectRef, ObjectRef> = BTreeMap::new();
    for page_refs in result.ref_map.values() {
        let Some(&first_page) = page_refs.first() else {
            continue; // cov:ignore: RebuildResult stores only non-empty page-reference groups
        };
        for &duplicate_page in page_refs.iter().skip(1) {
            first_occurrence.insert(duplicate_page, first_page);
        }
    }
    for &new_page in &result.new_kids {
        let Some(&source_page_ref) = first_occurrence.get(&new_page) else {
            continue;
        };
        let source_page = pdf.get_object_handle(source_page_ref);
        let destination_page = pdf.get_object_handle(new_page);
        destination_page.remove_key(b"/Annots");
        PageObjectHelper::new(new_page, pdf).copy_annotations(source_page, Matrix::default())?;
    }
    Ok(())
}

/// Execute the qpdf-shaped in-place page-tree portion for one source.
fn prefixed_info_line(job: &super::QPDFJob, body: &[u8]) -> Vec<u8> {
    let mut message = job.message_prefix_bytes().to_vec();
    message.extend_from_slice(b": ");
    message.extend_from_slice(body);
    message
}

/// Run qpdf's per-source page-job resource preflight and emit the diagnostics
/// that surround the page-copy phase.
///
/// qpdf performs this work after all page specifications have been parsed but
/// before it removes the primary page tree (`libqpdf/QPDFJob.cc:2440-2472`).
/// The source map is ordered by the raw filename, while the later page-add
/// lines follow specification order. Return the decisions by source index so
/// the merge primitive does not scan the same document a second time.
fn report_page_spec_diagnostics<R: Read + Seek>(
    job: &super::QPDFJob,
    sources: &mut [Pdf<R>],
    specs: &[PageSpecInput],
    resource_mode: RemoveUnreferencedResources,
) -> Result<Vec<bool>> {
    let source_names: Vec<Vec<u8>> = sources.iter().map(Pdf::input_source_description).collect();
    let mut source_order: Vec<(usize, Vec<u8>)> = source_names
        .iter()
        .enumerate()
        .map(|(index, name)| (index, job.page_spec_source_sort_key(index, name)))
        .collect();
    source_order.sort_by(|(left_index, left_name), (right_index, right_name)| {
        left_name
            .cmp(right_name)
            .then_with(|| left_index.cmp(right_index))
    });

    let verbose = job.verbose();
    let logger = job.logger();
    let mut decisions = vec![false; sources.len()];
    let mut decisions_by_source_id = BTreeMap::new();
    for (source_index, _source_sort_key) in source_order {
        let source_name = &source_names[source_index];
        let source_id = sources[source_index].unique_id();
        if let Some(&decision) = decisions_by_source_id.get(&source_id) {
            decisions[source_index] = decision;
            continue;
        }

        let decision = match resource_mode {
            RemoveUnreferencedResources::No => false,
            RemoveUnreferencedResources::Yes => true,
            RemoveUnreferencedResources::Auto => {
                if verbose {
                    let mut message = prefixed_info_line(job, source_name.as_slice());
                    message.extend_from_slice(b": checking for shared resources\n");
                    logger.info(message)?;
                }
                let should_remove = should_remove_unreferenced_resources_with_report(
                    &mut sources[source_index],
                    |finding| {
                        if verbose {
                            logger.info(shared_resource_finding_message(finding))
                        } else {
                            Ok(())
                        }
                    },
                )?; // cov:ignore: llvm-cov attributes this executed generic preflight call to its closing delimiter
                if verbose && !should_remove {
                    logger.info(prefixed_info_line(job, b"no shared resources found\n"))?;
                }
                should_remove
            }
        };
        decisions_by_source_id.insert(source_id, decision);
        decisions[source_index] = decision;
    }

    if verbose {
        logger.info(prefixed_info_line(
            job,
            b"removing unreferenced pages from primary input\n",
        ))?; // cov:ignore: llvm-cov attributes this executed multiline logger call to its closing delimiter
        for spec in specs {
            let source_name = source_names.get(spec.source_index).ok_or_else(|| {
                Error::Unsupported(format!(
                    "--pages: specification refers to missing source {}",
                    spec.source_index
                ))
            })?;
            let mut message = prefixed_info_line(job, b"adding pages from ");
            message.extend_from_slice(source_name);
            message.push(b'\n');
            logger.info(message)?;
        }
    }

    Ok(decisions)
}

fn handle_single_source_page_specs<R: Read + Seek>(
    job: &mut super::QPDFJob,
    source: &mut Pdf<R>,
    specs: &[PageSpecInput],
    collate: Option<&[usize]>,
    resource_mode: RemoveUnreferencedResources,
) -> Result<(RebuildResult, RemoveUnreferencedResources)> {
    // QPDFPageData captures qpdf's getAllPages() result before the resource
    // heuristic and page-tree mutation (`QPDFJob.cc:259-268,2442-2460`).
    // Use the canonical repair/cache boundary here so duplicate leaves are
    // cloned before the page range is resolved.
    crate::PageDocumentHelper::new(source).get_all_pages()?;
    let selected = select_single_source_pages(source, specs, collate)?;
    let remove_resources =
        report_page_spec_diagnostics(job, std::slice::from_mut(source), specs, resource_mode)?;
    let prune_mode = if remove_resources[0] {
        resource_mode
    } else {
        RemoveUnreferencedResources::No
    };
    // QPDF::insertPage first flattens the source page tree, whose qpdf
    // implementation calls pushInheritedAttributesToPage before rebuilding
    // the selected page list (`QPDF_pages.cc:204-218`). Keep that operation at
    // the page-document boundary so JSON metadata observes the same
    // everPushedInheritedAttributesToPages state as qpdf.
    crate::PageDocumentHelper::new(source).push_inherited_attributes_to_pages()?;
    let selected_refs: Vec<_> = selected.iter().map(|page| page.page_ref).collect();
    let mut copy_duplicate_annotations =
        |pdf: &mut Pdf<R>, source_page_ref: ObjectRef, new_page: ObjectRef| -> Result<()> {
            let source_page = pdf.get_object_handle(source_page_ref);
            let destination_page = pdf.get_object_handle(new_page);
            destination_page.remove_key(b"/Annots");
            PageObjectHelper::new(new_page, pdf).copy_annotations(source_page, Matrix::default())
        };
    let result = crate::pages::tree_rebuild::rebuild_page_tree_with_duplicate_hook(
        source,
        &selected_refs,
        &mut copy_duplicate_annotations,
    )?; // cov:ignore: llvm-cov attributes this executed multiline call to its closing delimiter

    let mut labels = source.page_labels();
    if labels.has_page_labels()? {
        let src_indices: Vec<i64> = selected
            .iter()
            .map(|page| i64::from(page.index_1based) - 1)
            .collect();
        let entries = labels.labels_for_selection_raw(&src_indices, 0)?;
        let folded = merge_adjacent_raw_labels(entries)?;
        labels.write_reconstructed_labels_raw(&folded)?;
    }
    job.record_document_warnings(source);
    Ok((result, prune_mode))
}

/// Apply qpdf's multi-source `QPDFJob::handlePageSpecs` operation to the
/// primary document itself.
///
/// qpdf removes the primary pages, inserts selected primary pages back into
/// that same `QPDF`, and copies foreign page graphs into its live object
/// cache in page-spec order (`QPDFJob.cc:2462-2632`). Keeping the primary as
/// the output owner preserves its complete object cache and allocator state;
/// the JSON `getAllObjects` consumer then sees the same document qpdf sees.
#[allow(clippy::too_many_arguments)]
fn handle_multi_source_page_specs_in_place<R: Read + Seek + 'static>(
    job: &mut super::QPDFJob,
    sources: &mut [Pdf<R>],
    specs: &[PageSpecInput],
    collate: Option<&[usize]>,
    resource_mode: RemoveUnreferencedResources,
) -> Result<(RebuildResult, RemoveUnreferencedResources)> {
    if sources.is_empty() {
        return Err(Error::Unsupported(
            "--pages: a primary source document is required".into(),
        ));
    }
    if specs.is_empty() {
        return Err(Error::Unsupported(
            "--pages: no page specifications were supplied".into(),
        ));
    }

    let mut plans = Vec::with_capacity(specs.len());
    for (spec_index, spec) in specs.iter().enumerate() {
        let source = sources.get_mut(spec.source_index).ok_or_else(|| {
            Error::Unsupported(format!(
                "--pages: specification {spec_index} refers to missing source {}",
                spec.source_index
            ))
        })?;
        let source_name = source.input_source_description();
        PageDocumentHelper::new(source).get_all_pages()?;
        let plan = PagePlan::build(source, &spec.range)
            .map_err(|error| page_spec_error(&source_name, spec.source_index, spec_index, error))?;
        plans.push(plan);
    }
    let collate_values = collate_values_for_specs(collate, plans.len())?;
    let mut grouped_pages: Vec<Vec<usize>> = vec![Vec::new(); sources.len()];
    let mut ordered_pages: Vec<OrderedPage> = Vec::new();
    let mut append_page = |source_index: usize, page_index_1based: u32| {
        let page_index = page_index_1based as usize - 1;
        let group_index = grouped_pages[source_index].len();
        grouped_pages[source_index].push(page_index);
        ordered_pages.push((source_index, group_index));
    };
    if plans.len() > 1 {
        if let Some(values) = collate_values.as_deref() {
            let mut cursors = vec![0usize; plans.len()];
            loop {
                let mut emitted = false;
                for (spec_index, plan) in plans.iter().enumerate() {
                    let start = cursors[spec_index];
                    let end = start
                        .saturating_add(values[spec_index])
                        .min(plan.pages().len());
                    for page in &plan.pages()[start..end] {
                        append_page(specs[spec_index].source_index, page.index_1based);
                    }
                    if end > start {
                        emitted = true;
                    }
                    cursors[spec_index] = end;
                }
                if !emitted {
                    break;
                }
            }
        } else {
            for (spec_index, plan) in plans.iter().enumerate() {
                for page in plan.pages() {
                    append_page(specs[spec_index].source_index, page.index_1based);
                }
            }
        }
    } else {
        for (spec_index, plan) in plans.iter().enumerate() {
            for page in plan.pages() {
                append_page(specs[spec_index].source_index, page.index_1based);
            }
        }
    }

    let remove_resources = report_page_spec_diagnostics(job, sources, specs, resource_mode)?;
    let source_page_refs: Vec<Vec<ObjectRef>> = sources
        .iter_mut()
        .enumerate()
        .map(|(source_index, source)| {
            if source_index != 0 && grouped_pages[source_index].is_empty() {
                Ok(Vec::new())
            } else {
                crate::pages::page_refs(source)
            }
        })
        .collect::<Result<_>>()?;
    let original_primary_pages = source_page_refs[0].clone();

    let referenced_source_indices: BTreeSet<_> =
        specs.iter().map(|spec| spec.source_index).collect();
    let mut any_page_labels = false;
    for source_index in referenced_source_indices {
        any_page_labels |= sources[source_index].page_labels().has_page_labels()?;
    }

    // Keep qpdf's per-page label lookup in final output order. Each lookup
    // returns a new direct label dictionary, just as
    // QPDFPageLabelDocumentHelper::getLabelsForPageRange does.
    let mut label_entries = Vec::new();

    // `flattenPagesTree` runs on the first primary removal, or on the first
    // insertion when the primary starts without pages. `rebuild_page_tree`
    // performs qpdf's inherited-attribute push and rewrites the root `/Kids`
    // to the flat live page sequence without replacing the primary document.
    let mut current_pages = if !original_primary_pages.is_empty() || !ordered_pages.is_empty() {
        PageDocumentHelper::new(&mut sources[0]).push_inherited_attributes_to_pages()?;
        crate::pages::tree_rebuild::rebuild_page_tree(&mut sources[0], &original_primary_pages)?
            .new_kids
    } else {
        Vec::new()
    };
    for page in &original_primary_pages {
        PageDocumentHelper::new(&mut sources[0])
            .remove_flattened_page_for_job(*page, &mut current_pages)?;
    }

    let primary_field_names = source_top_level_field_names(&mut sources[0])?
        .into_iter()
        .filter_map(|(_, name)| name)
        .collect::<BTreeSet<_>>();
    let mut seen_source_pages: Vec<BTreeSet<ObjectRef>> = vec![BTreeSet::new(); sources.len()];
    let mut final_refs = Vec::with_capacity(ordered_pages.len());

    for (output_index, &(source_index, group_index)) in ordered_pages.iter().enumerate() {
        let source_page_index = grouped_pages[source_index][group_index];
        let source_page_ref = source_page_refs[source_index][source_page_index];
        let first_copy = seen_source_pages[source_index].insert(source_page_ref);

        // qpdf prunes resources once, immediately before a source page's
        // first copy. The primary tree is already flat here, and a foreign
        // page still belongs to its source document until insertPage copies
        // it into the primary.
        if first_copy && remove_resources[source_index] {
            if source_index == 0 {
                PageObjectHelper::new(source_page_ref, &mut sources[0])
                    .remove_unreferenced_resources()?;
            } else {
                PageObjectHelper::new(source_page_ref, &mut sources[source_index])
                    .remove_unreferenced_resources()?;
            }
        }

        if any_page_labels {
            let labels = sources[source_index]
                .page_labels()
                .labels_for_selection_raw(&[source_page_index as i64], output_index as i64)?;
            if let Some((index, label)) = labels.into_iter().next() {
                label_entries.push(RawPageLabelEntry {
                    index,
                    source_id: sources[source_index].unique_id(),
                    source_is_primary: source_index == 0,
                    label,
                });
            }
        }

        let page_ref = if source_index == 0 {
            PageDocumentHelper::new(&mut sources[0]).append_flattened_page_for_job(
                PageInput::<R>::Existing(source_page_ref),
                &mut current_pages,
            )? // cov:ignore: LLVM maps this executed append continuation to the call's opening expressions; helper error cases are tested directly.
        } else {
            let (primary, secondary) = sources.split_at_mut(1);
            PageDocumentHelper::new(&mut primary[0]).append_flattened_page_for_job(
                PageInput::foreign(&mut secondary[source_index - 1], source_page_ref),
                &mut current_pages,
            )? // cov:ignore: LLVM maps this executed append continuation to the call's opening expressions; helper error cases are tested directly.
        };
        final_refs.push(page_ref);

        // QPDFJob calls fixCopiedAnnotations after every foreign page
        // occurrence and every repeated primary page. The first primary
        // occurrence keeps its original annotation graph.
        if source_index == 0 && !first_copy {
            let source_page = sources[0].get_object_handle(source_page_ref);
            PageObjectHelper::new(page_ref, &mut sources[0])
                .fix_copied_annotations_with_field_tree_only(source_page, &primary_field_names)?;
        } else if source_index != 0 {
            let (primary, secondary) = sources.split_at_mut(1);
            let source_page = secondary[source_index - 1].get_object_handle(source_page_ref);
            PageObjectHelper::new(page_ref, &mut primary[0])
                .fix_copied_annotations_from_with_field_tree_only(
                    source_page,
                    &mut secondary[source_index - 1],
                    &primary_field_names,
                )?; // cov:ignore: LLVM maps this executed generic call terminator to a defensive continuation; malformed-copy errors are covered by AcroForm helper tests.
        }
    }

    if any_page_labels {
        let folded = merge_adjacent_raw_page_labels(label_entries)?;
        let copied = folded
            .iter()
            .map(|entry| Ok((entry.index, entry.label.shallow_copy()?)))
            .collect::<Result<Vec<_>>>()?;
        record_primary_label_provenance(&mut sources[0], &folded);
        sources[0]
            .page_labels()
            .write_reconstructed_labels_raw(&copied)?;
    }

    let selected_primary_pages: BTreeSet<_> = ordered_pages
        .iter()
        .filter(|&&(source_index, _)| source_index == 0)
        .map(|&(_, group_index)| source_page_refs[0][grouped_pages[0][group_index]])
        .collect();
    for page in &original_primary_pages {
        if !selected_primary_pages.contains(page) {
            sources[0].replace_object(*page, ObjectHandle::null())?;
        }
    }

    prune_page_spec_acroform_fields(&mut sources[0], &final_refs)?;

    let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
    for (output_index, &(source_index, group_index)) in ordered_pages.iter().enumerate() {
        if source_index == 0 {
            let source_page_ref = source_page_refs[0][grouped_pages[0][group_index]];
            ref_map
                .entry(source_page_ref)
                .or_default()
                .push(final_refs[output_index]);
        }
    }
    let retained_primary: BTreeSet<_> = ref_map.keys().copied().collect();
    let removed_page_objgens = original_primary_pages
        .iter()
        .filter(|page| !retained_primary.contains(page))
        .filter_map(|page| QpdfObjGen::try_from_object_ref(*page).ok())
        .collect();
    let result = RebuildResult {
        new_kids: final_refs,
        ref_map,
        removed_page_objgens,
    };
    let prune_mode = if remove_resources[0] {
        resource_mode
    } else {
        RemoveUnreferencedResources::No
    };
    job.record_document_warnings(&sources[0]);
    for source in sources.iter().skip(1) {
        job.record_document_warnings(source);
    }
    Ok((result, prune_mode))
}

fn prune_page_spec_acroform_fields<R: Read + Seek>(
    primary: &mut Pdf<R>,
    selected_pages: &[ObjectRef],
) -> Result<()> {
    let catalog = primary.root_handle()?;
    if !catalog.try_has_key(b"/AcroForm")? {
        return Ok(());
    }
    let acroform = catalog.try_get_key(b"/AcroForm")?;
    acroform.try_dereference()?;
    if !acroform.try_is_dictionary()? {
        return Ok(());
    }
    let fields = acroform.try_get_key(b"/Fields")?;
    if !fields.try_is_array()? {
        return Ok(());
    }

    // QPDFJob allocates the replacement array before filtering its entries
    // (`QPDFJob.cc:2609-2629`), leaving it in the object cache even when the
    // final empty array causes `/AcroForm` itself to be removed.
    let replacement = ObjectHandle::array(Vec::new());
    let replacement = if fields.is_indirect() {
        primary.make_indirect_object_handle(replacement)?
    } else {
        replacement
    };
    let fields = collect_primary_fields(primary, selected_pages)?;
    replacement.try_set_array_items(fields)?;
    if replacement.try_array_len()?.unwrap_or_default() == 0 {
        catalog.remove_key(b"/AcroForm");
    } else {
        acroform.replace_key(b"/Fields", replacement)?;
    }
    Ok(())
}

impl PageSpecInput {
    /// Construct one source-indexed page specification.
    #[must_use]
    pub(crate) const fn new(source_index: usize, range: PageRange) -> Self {
        Self {
            source_index,
            range,
        }
    }
}

#[cfg(test)]
fn merge_preserving_primary_into<R: Read + Seek, T: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
    target: Pdf<T>,
    object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
    merge_documents_for_page_specs_into(inputs, remove_resources, true, target, object_stream_mode)
}

/// A selected page represented by its source and its occurrence within the
/// source's grouped merge input.
type OrderedPage = (usize, usize);

/// The page/replay allocations that qpdf assigns in one page-spec occurrence.
/// The grouped page merge supplies the first list; the AcroForm replay fills
/// the second list after the occurrence's copy helper returns.
#[derive(Debug)]
#[cfg(test)]
struct PageSpecWriterProvenance {
    order: BTreeMap<ObjectRef, WriterObjectOrderKey>,
    next_original: ObjectRef,
    page_allocations: Vec<Vec<ObjectRef>>,
}

/// Collect fresh merge-object provenance in qpdf page-spec occurrence order.
///
/// The page merge keeps one foreign copier per source so shared source objects
/// retain their identity, but qpdf allocates a repeated page clone at the
/// occurrence where `handlePageSpecs` encounters it. The fresh Rust target has
/// already copied the grouped graphs, so the writer-order map is finalized
/// after replay without introducing a second copy route. Each foreign page
/// graph group retains its existing discovery order, while those groups and
/// shallow page clones are interleaved according to `ordered_pages`.
#[cfg(test)]
fn restore_occurrence_writer_provenance<T: Read + Seek + 'static, R: Read + Seek + 'static>(
    merged: &mut Pdf<T>,
    sources: &mut [Pdf<R>],
    source_page_refs: &[Vec<ObjectRef>],
    grouped_pages: &[Vec<usize>],
    ordered_pages: &[OrderedPage],
    grouped_refs: &[ObjectRef],
    offsets: &[usize],
) -> Result<Option<PageSpecWriterProvenance>> {
    // cov:ignore-start: the page-spec merge target always records writer order.
    let Some(existing_order) = merged.writer_object_order.clone() else {
        return Ok(None);
    };
    // cov:ignore-end
    let mut page_allocations = Vec::with_capacity(ordered_pages.len());
    let mut seen_pages: Vec<BTreeSet<ObjectRef>> = vec![BTreeSet::new(); sources.len()];
    for &(source_index, group_index) in ordered_pages {
        let source_page_index = grouped_pages[source_index][group_index];
        let source_page_ref = source_page_refs[source_index][source_page_index];
        // A repeated occurrence of a page already selected from the same source
        // is the clone qpdf allocates at this point, so it takes fresh
        // provenance. The per-source seen set keeps this pass linear.
        let duplicate = !seen_pages[source_index].insert(source_page_ref);
        let mut allocations = Vec::new();
        if source_index != 0 && !duplicate {
            let source_id = sources[source_index].unique_id();
            if let Some((_, target_refs)) = merged
                .foreign_page_copy_orders
                .get(&source_id)
                .and_then(|groups| {
                    groups
                        .iter()
                        .find(|(source_ref, _)| *source_ref == source_page_ref)
                })
            {
                allocations.extend(target_refs.iter().copied());
            } // cov:ignore: merge records a copy group for every selected foreign page
        }
        if duplicate {
            allocations.push(grouped_refs[offsets[source_index] + group_index]);
        }
        page_allocations.push(allocations);
    }
    let Some(next_original) = page_allocations
        .iter()
        .flatten()
        .map(|object_ref| merged.writer_original_object_ref(*object_ref))
        .min()
    else {
        return Ok(None);
    };
    Ok(Some(PageSpecWriterProvenance {
        order: existing_order,
        next_original,
        page_allocations,
    }))
}

/// Add the allocation identities made by AcroForm replay to the same
/// occurrence-ordered writer provenance as page graph copies and duplicate
/// page shallow copies.
#[cfg(test)]
fn finalize_page_spec_writer_provenance<T: Read + Seek + 'static>(
    merged: &mut Pdf<T>,
    mut provenance: PageSpecWriterProvenance,
    replay_allocations: &[Vec<ObjectRef>],
) -> Result<()> {
    debug_assert_eq!(provenance.page_allocations.len(), replay_allocations.len());
    for (page_allocations, replay_allocations) in
        provenance.page_allocations.iter().zip(replay_allocations)
    {
        for &target_ref in page_allocations.iter().chain(replay_allocations) {
            provenance.order.insert(
                target_ref,
                WriterObjectOrderKey::foreign_with_allocation_identity(
                    target_ref,
                    provenance.next_original,
                ),
            );
            // cov:ignore-start: exhausting the u32 PDF object space is unreachable for a page merge.
            provenance.next_original = ObjectRef::new(
                provenance
                    .next_original
                    .number
                    .checked_add(1)
                    .ok_or_else(|| {
                        Error::Unsupported("page-selection provenance overflows u32".to_owned())
                    })?,
                provenance.next_original.generation,
            );
            // cov:ignore-end
        }
    }
    merged.set_writer_object_order(provenance.order);
    Ok(())
}

/// One qpdf-style reconstructed label in the test-only typed compatibility
/// projection. Production page selection uses raw label handles instead.
#[cfg(test)]
type JobLabelEntry = (i64, LabelRange, bool);

fn collect_primary_fields<T: Read + Seek>(
    merged: &mut Pdf<T>,
    pages: &[ObjectRef],
) -> Result<Vec<ObjectHandle>> {
    let mut field_identities = BTreeSet::<QpdfObjGen>::new();
    let mut candidate_fields = Vec::new();
    {
        let mut acroform = AcroFormDocumentHelper::new_for_field_tree(merged)?;
        for &page_ref in pages {
            let widgets = acroform.get_widget_annotations_for_page(page_ref)?;
            for widget in widgets {
                let field = acroform.get_field_for_annotation_handle(widget)?;
                if field.qpdf_obj_gen().is_some_and(QpdfObjGen::is_indirect) {
                    candidate_fields.push(field);
                } // cov:ignore: structural brace has no LLVM executable counter
            }
        }
    }
    for field in candidate_fields {
        let (top_level, _) =
            FormFieldObjectHelper::from_object_handle(field, merged).get_top_level_field()?;
        if let Some(object_gen) = top_level.qpdf_obj_gen().filter(|gen| gen.is_indirect()) {
            field_identities.insert(object_gen);
        }
    }
    let primary_order = {
        let mut acroform = AcroFormDocumentHelper::new_for_field_tree(merged)?;
        acroform.top_level_field_handles()?
    };
    Ok(primary_order
        .into_iter()
        .filter(|field| {
            field
                .qpdf_obj_gen()
                .is_some_and(|gen| gen.is_indirect() && field_identities.contains(&gen))
        })
        .collect())
}

/// Rebuild the merged primary's `/AcroForm /Fields` with the primary's
/// first-occurrence fields, mirroring the *gate and removal* half of qpdf's
/// end-of-selection field prune (`QPDFJob.cc:2609-2629`). qpdf only touches
/// `/AcroForm` when the *original* `/Fields` resolved to an array
/// (`had_fields_array`, the same gate in the job-owned page-merge module's
/// `PrimaryAcroForm::had_fields_array` captures); an `/AcroForm` with no
/// `/Fields` array (e.g. only `/NeedAppearances`) is left untouched. When the
/// gate passes, qpdf keeps a non-empty rebuilt array or removes `/AcroForm`
/// entirely if nothing survived -- it never leaves a stray empty `/Fields`.
///
/// This does *not* port qpdf's `referenced_fields` accumulation or its
/// end-of-loop call timing: qpdf's prune runs once, after every page's copy
/// is complete, against a `pdf` that still holds every original field
/// (including ones on pages that end up unselected). flpdf's caller runs
/// this *before* the per-occurrence copy loop and scopes `fields` to the
/// primary's first-occurrence pages only. As a result, a name still held by
/// an unselected primary field is never copied into `merged` at all, so it
/// cannot participate in the loop's collision-avoidance check -- a repeated
/// or foreign field that would collide with that name in qpdf can receive
/// the wrong `+N` suffix here.
#[cfg(test)]
fn replace_merged_fields<T: Read + Seek>(
    merged: &mut Pdf<T>,
    fields: Vec<ObjectHandle>,
    had_fields_array: bool,
) -> Result<()> {
    if !had_fields_array {
        return Ok(());
    }
    let Some(root_ref) = merged.root_ref() else {
        return Ok(());
    };
    let root = merged.get_object_handle(root_ref);
    let acroform = root.try_get_key(b"/AcroForm")?;
    acroform.try_dereference()?;
    if !acroform.try_is_dictionary()? {
        return Ok(());
    }
    // qpdf does not perform the final `/AcroForm` removal until after every
    // foreign `fixCopiedAnnotations` event (`QPDFJob.cc:2517-2585,2609-2629`).
    // Keep the primary AcroForm itself, including its direct representation
    // and `/DR`, alive while those events append their copied fields. The
    // caller removes this temporary empty array only after replay completes.
    let fields_holder = acroform.try_get_key(b"/Fields")?;
    let replacement = ObjectHandle::array(fields);
    let replacement = if fields_holder.is_indirect() {
        // qpdf allocates a fresh indirect array when the original `/Fields`
        // holder was indirect (`QPDFJob.cc:2615-2618`).
        merged.make_indirect_object_handle(replacement)?
    } else {
        replacement
    };
    acroform.replace_key(b"/Fields", replacement)?;
    Ok(())
}

/// Apply qpdf's final empty-field AcroForm removal after occurrence replay.
///
/// This is deliberately separate from [`replace_merged_fields`]: removing the
/// primary AcroForm before a foreign page is replayed loses the primary `/DR`
/// merge base and changes a direct catalog child into a newly created indirect
/// AcroForm (`QPDFJob.cc:2609-2629`).
#[cfg(test)]
fn remove_empty_acroform_after_replay<T: Read + Seek>(
    merged: &mut Pdf<T>,
    had_fields_array: bool,
) -> Result<()> {
    if !had_fields_array {
        return Ok(());
    }
    let Some(root_ref) = merged.root_ref() else {
        return Ok(());
    };
    let root = merged.get_object_handle(root_ref);
    let acroform = root.try_get_key(b"/AcroForm")?;
    acroform.try_dereference()?;
    if !acroform.try_is_dictionary()? {
        return Ok(());
    }
    let fields = acroform.try_get_key(b"/Fields")?;
    fields.try_dereference()?;
    if fields.try_array_len()?.is_some_and(|length| length == 0) {
        root.remove_key(b"/AcroForm");
    }
    Ok(())
}

/// Remove the grouped foreign fields before the final per-occurrence replay
/// when the primary AcroForm had no `/Fields` array of its own. The grouped
/// page merge is an intermediate copy optimization; qpdf's empty-primary path
/// adds each foreign field only at `fixCopiedAnnotations`, so retaining that
/// intermediate field would make the replay rename the field against itself
/// (`QPDFJob.cc:2514-2584`). Existing `/DR`, `/DA`, and other AcroForm keys are
/// intentionally left in place for the replay's lazy initialization boundary.
#[cfg(test)]
fn clear_grouped_foreign_fields_for_replay<T: Read + Seek>(merged: &mut Pdf<T>) -> Result<()> {
    let Some(root_ref) = merged.root_ref() else {
        return Ok(());
    };
    let root = merged.get_object_handle(root_ref);
    let acroform = root.try_get_key(b"/AcroForm")?;
    acroform.try_dereference()?;
    if !acroform.try_is_dictionary()? {
        return Ok(());
    }
    let fields = acroform.try_get_key(b"/Fields")?;
    fields.try_dereference()?;
    if !fields.try_is_array()? {
        return Ok(());
    }
    acroform.replace_key(b"/Fields", ObjectHandle::array(Vec::new()))?;
    Ok(())
}

/// Repair grouped-copy annotation `/P` values after the final page order is
/// restored. qpdf installs this back-pointer at each final page-copy event,
/// while the structural merge initially copies pages in source-group order.
#[cfg(test)]
fn set_annotation_page_refs<T: Read + Seek>(
    merged: &mut Pdf<T>,
    page_ref: ObjectRef,
    first_output_page: ObjectRef,
) -> Result<()> {
    let annotations = PageObjectHelper::new(page_ref, merged).get_annotation_handles(None)?;
    let page = merged.get_object_handle(first_output_page);
    for annotation in annotations {
        if annotation.try_has_key(b"/P")? {
            annotation.replace_key(b"/P", page.clone())?;
        }
    }
    Ok(())
}

/// Rebuild the copied page annotations and form fields in qpdf's final page
/// order.
///
/// `QPDFJob.cc:2517-2584` invokes `fixCopiedAnnotations` for every foreign page
/// and for every repeated page from the primary. The page-group merge below
/// deliberately keeps one object-copy map per source for page/resource sharing,
/// but that is not the AcroForm boundary: `fixCopiedAnnotations` makes a fresh
/// annotation/field-tree copy for each page occurrence and then lets
/// `addAndRenameFormFields` resolve names against the fields already added.
///
/// The initial page merge has already copied page-owned annotations and built a
/// grouped `/AcroForm /Fields` array. Retain the primary's first-occurrence
/// fields and no-AcroForm foreign annotations, while replaying only the
/// occurrence-sensitive copies in `ordered_pages` order. The existing
/// `PageObjectHelper` facades own the same-document and foreign field-tree
/// transforms and collision-rename routes.
#[cfg(test)]
fn rebuild_acroform_in_final_page_order<R: Read + Seek + 'static, T: Read + Seek>(
    merged: &mut Pdf<T>,
    sources: &mut [Pdf<R>],
    source_page_refs: &[Vec<ObjectRef>],
    grouped_pages: &[Vec<usize>],
    ordered_pages: &[OrderedPage],
    final_refs: &[ObjectRef],
) -> Result<Vec<Vec<ObjectRef>>> {
    debug_assert_eq!(ordered_pages.len(), final_refs.len());

    // qpdf analyzes the primary AcroForm before its final unselected-page
    // prune (`QPDFJob.cc:2516-2521,2600-2629`). Keep every original primary
    // top-level name visible to each later copy event, even when that field's
    // page is not selected and its object is absent from the rebuilt `/Fields`.
    let primary_field_names: BTreeSet<Vec<u8>> = match sources.first_mut() {
        Some(primary) => source_top_level_field_names(primary)?
            .into_iter()
            .filter_map(|(_, name)| name)
            .collect(),
        None => BTreeSet::new(),
    };

    // qpdf's foreign ObjCopier has already mapped each source page to the first
    // output page inserted for that source page. When a copied widget's `/P`
    // is encountered during a later field-tree copy, it therefore retains the
    // first occurrence's destination page, including repeated primary pages.
    let mut first_output_for_source_page: Vec<BTreeMap<ObjectRef, ObjectRef>> =
        vec![BTreeMap::new(); sources.len()];
    let mut replay_allocations = Vec::with_capacity(ordered_pages.len());
    for (output_index, &(source_index, group_index)) in ordered_pages.iter().enumerate() {
        let source_page_index = grouped_pages[source_index][group_index];
        let source_page_ref = source_page_refs[source_index][source_page_index];
        first_output_for_source_page[source_index]
            .entry(source_page_ref)
            .or_insert(final_refs[output_index]);
    }

    // The grouped merge already copied the primary's first-occurrence field
    // trees. Keep those handles, discard secondary grouped fields, and let
    // the per-occurrence routes append only the copies qpdf would append.
    let primary_first_pages: Vec<ObjectRef> = ordered_pages
        .iter()
        .enumerate()
        .filter_map(|(output_index, &(source_index, group_index))| {
            if source_index != 0 {
                return None;
            }
            let source_page_index = grouped_pages[source_index][group_index];
            let source_page_ref = source_page_refs[source_index][source_page_index];
            (first_output_for_source_page[source_index].get(&source_page_ref)
                == Some(&final_refs[output_index]))
            .then_some(final_refs[output_index])
        })
        .collect();
    // qpdf's field prune (`QPDFJob.cc:2609-2610`, `hasAcroForm() &&
    // fields.isArray()`) only fires when the primary's *original* `/Fields`
    // was an array; an `/AcroForm` with no `/Fields` (e.g. only
    // `/NeedAppearances`) is left untouched. The primary page tree has already
    // been flattened by the merge, but its AcroForm dictionary remains live;
    // this reads the original field-array gate from that same source document.
    let had_fields_array = match sources.first_mut() {
        Some(primary) => primary.acroform()?.has_fields_array()?,
        None => false,
    };
    let primary_fields = collect_primary_fields(merged, &primary_first_pages)?;
    replace_merged_fields(merged, primary_fields, had_fields_array)?;
    if !had_fields_array {
        clear_grouped_foreign_fields_for_replay(merged)?;
    }

    for (source_index, mappings) in first_output_for_source_page.iter().enumerate() {
        if mappings.is_empty() {
            continue;
        }
        let source_id = sources[source_index].unique_id();
        let mut object_map = merged.take_foreign_object_map(source_id);
        for (&source, &target) in mappings {
            object_map.insert(QpdfObjGen::try_from_object_ref(source)?, target);
        }
        merged.set_foreign_object_map(source_id, object_map);
    }

    for (output_index, &(source_index, group_index)) in ordered_pages.iter().enumerate() {
        let source_page_index = grouped_pages[source_index][group_index];
        let source_page_ref = source_page_refs[source_index][source_page_index];
        let first_output_page = first_output_for_source_page[source_index]
            .get(&source_page_ref)
            .copied()
            .ok_or(Error::Missing("first output page for source page"))?;
        let is_primary_first = source_index == 0 && first_output_page == final_refs[output_index];

        if is_primary_first {
            // The grouped page copy already owns the primary's first
            // occurrence annotations. Repair `/P` after the grouped→final
            // page-order reconstruction; qpdf does not run
            // fixCopiedAnnotations on this occurrence.
            set_annotation_page_refs(merged, final_refs[output_index], first_output_page)?;
            replay_allocations.push(Vec::new());
            continue;
        }

        let destination_page = merged.get_object_handle(final_refs[output_index]);
        destination_page.remove_key(b"/Annots");
        let allocation_checkpoint = merged.allocation_checkpoint();

        if source_index == 0 {
            // A repeated primary page is a same-document transform: it must
            // not create or merge a foreign destination `/DR`.
            let source_page = merged.get_object_handle(first_output_page);
            PageObjectHelper::new(final_refs[output_index], merged)
                .copy_annotations_with_field_tree_only(
                    source_page,
                    Matrix::default(),
                    &primary_field_names,
                )?; // cov:ignore: valid page selections exercise this route; malformed copy errors are covered by helper tests.
        } else {
            let source_page = sources[source_index].get_object_handle(source_page_ref);
            let source = &mut sources[source_index];
            let mut destination = PageObjectHelper::new(final_refs[output_index], merged);
            destination.copy_annotations_from_with_field_tree_only(
                source_page,
                Matrix::default(),
                source,
                &primary_field_names,
            )?; // cov:ignore: valid page selections exercise this route; malformed copy errors are covered by helper tests.
        }
        replay_allocations.push(merged.allocated_object_refs_after(allocation_checkpoint));
    }

    remove_empty_acroform_after_replay(merged, had_fields_array)?;
    Ok(replay_allocations)
}

#[cfg(test)]
fn merge_job_label_ranges(ranges: Vec<JobLabelEntry>) -> Vec<JobLabelEntry> {
    let mut out: Vec<JobLabelEntry> = Vec::with_capacity(ranges.len());
    for (idx, range, prefix_present) in ranges {
        if let Some((previous_idx, previous, previous_prefix_present)) = out.last() {
            let expected_start = idx
                .checked_sub(*previous_idx)
                .and_then(|gap| previous.start.checked_add(gap));
            if let Some(expected_start) = expected_start {
                if previous.style == range.style
                    && previous.prefix == range.prefix
                    && *previous_prefix_present == prefix_present
                    && range.start == expected_start
                {
                    continue;
                }
            }
        }
        out.push((idx, range, prefix_present));
    }
    out
}

/// Crate-internal implementation of [`super::QPDFJob::handle_page_specs`];
/// see that method for the parameter contract. Kept as a free function,
/// rather than inlined into the method, so tests can drive it directly
/// without spinning up a whole `QPDFJob`.
#[cfg(test)]
fn handle_page_specs<R: Read + Seek + 'static>(
    job: &mut super::QPDFJob,
    sources: &mut [Pdf<R>],
    specs: &[PageSpecInput],
    collate: Option<&[usize]>,
    resource_mode: RemoveUnreferencedResources,
    preserve_unreferenced: bool,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    handle_page_specs_into(
        job,
        sources,
        specs,
        collate,
        resource_mode,
        preserve_unreferenced,
        Pdf::empty()?,
        ObjectStreamMode::Preserve,
    )
}

/// Exercise the old grouped fresh-target merge in lower-level unit tests.
///
/// Production `QPDFJob::handlePageSpecs` mutates the primary and imports
/// foreign page graphs one occurrence at a time. This helper tests the generic
/// grouped merge primitive without routing the Job through that representation.
#[allow(clippy::too_many_arguments)]
#[cfg(test)]
fn handle_page_specs_into<R: Read + Seek + 'static, T: Read + Seek + 'static>(
    job: &mut super::QPDFJob,
    sources: &mut [Pdf<R>],
    specs: &[PageSpecInput],
    collate: Option<&[usize]>,
    resource_mode: RemoveUnreferencedResources,
    preserve_unreferenced: bool,
    target: Pdf<T>,
    object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
    if sources.is_empty() {
        return Err(Error::Unsupported(
            "--pages: a primary source document is required".into(),
        ));
    }
    if specs.is_empty() {
        return Err(Error::Unsupported(
            "--pages: no page specifications were supplied".into(),
        ));
    }
    // Build one PagePlan per *specification*, rather than one per source.
    // Repeated occurrences of the same file are distinct qpdf specs and must
    // remain distinct for collate ordering even though their object-copy
    // state is grouped by source below.
    let mut plans = Vec::with_capacity(specs.len());
    for (spec_index, spec) in specs.iter().enumerate() {
        let source = sources.get_mut(spec.source_index).ok_or_else(|| {
            Error::Unsupported(format!(
                "--pages: specification {spec_index} refers to missing source {}",
                spec.source_index
            ))
        })?;
        let source_name = source.input_source_description();
        // qpdf's QPDFPageData constructor repairs and enumerates the source
        // before resolving its page range (`QPDFJob.cc:259-269`). The
        // multi-source path must establish that same canonical page list
        // before PagePlan observes the live page-tree graph.
        crate::PageDocumentHelper::new(source).get_all_pages()?;
        let plan = PagePlan::build(source, &spec.range)
            .map_err(|error| page_spec_error(&source_name, spec.source_index, spec_index, error))?;
        plans.push(plan);
    }
    let collate_values = collate_values_for_specs(collate, plans.len())?;

    // `grouped_pages[source]` is the order in which that source is handed to
    // merge_documents. `ordered_pages` records the corresponding final order
    // as (source, occurrence-in-group), allowing us to restore an arbitrary
    // cross-source collate order after each source has been copied once.
    let mut grouped_pages: Vec<Vec<usize>> = vec![Vec::new(); sources.len()];
    let mut ordered_pages: Vec<OrderedPage> = Vec::new();

    let mut append_page = |source_index: usize, page_index_1based: u32| {
        let page_index = page_index_1based as usize - 1;
        let group_index = grouped_pages[source_index].len();
        grouped_pages[source_index].push(page_index);
        ordered_pages.push((source_index, group_index));
    };

    if plans.len() > 1 {
        if let Some(values) = collate_values.as_deref() {
            let mut cursors = vec![0usize; plans.len()];
            loop {
                let mut emitted = false;
                for (spec_index, plan) in plans.iter().enumerate() {
                    let start = cursors[spec_index];
                    let end = start
                        .saturating_add(values[spec_index])
                        .min(plan.pages().len());
                    for page in &plan.pages()[start..end] {
                        append_page(specs[spec_index].source_index, page.index_1based);
                    }
                    if end > start {
                        emitted = true;
                    }
                    cursors[spec_index] = end;
                }
                if !emitted {
                    break;
                }
            }
        } else {
            for (spec_index, plan) in plans.iter().enumerate() {
                for page in plan.pages() {
                    append_page(specs[spec_index].source_index, page.index_1based);
                }
            }
        }
    } else {
        for (spec_index, plan) in plans.iter().enumerate() {
            for page in plan.pages() {
                append_page(specs[spec_index].source_index, page.index_1based);
            }
        }
    }

    // See the sibling guard removal above: qpdf has no empty-selection check.
    let remove_resources = report_page_spec_diagnostics(job, sources, specs, resource_mode)?;

    // qpdf constructs QPDFPageLabelDocumentHelper only for each parsed page
    // specification, not for every opened source. Keep unused secondary
    // sources on that fast path, especially when they are an empty document
    // without a Catalog. The label accumulator is populated in final output
    // order, not in source-group order. When any referenced source has labels,
    // referenced sources without labels still contribute qpdf's default
    // decimal label for their selected pages.
    let mut any_page_labels = false;
    let referenced_source_indices: BTreeSet<_> =
        specs.iter().map(|spec| spec.source_index).collect();
    for source_index in referenced_source_indices {
        any_page_labels |= sources[source_index].page_labels().has_page_labels()?;
    }

    let mut label_entries: Vec<RawPageLabelEntry> = Vec::new();
    if any_page_labels {
        label_entries.reserve(ordered_pages.len());
        for (output_index, &(source_index, group_index)) in ordered_pages.iter().enumerate() {
            let source_page_index = grouped_pages[source_index][group_index];
            let source = &mut sources[source_index];
            let source_id = source.unique_id();
            let entries = source
                .page_labels()
                .labels_for_selection_raw(&[source_page_index as i64], output_index as i64)?;
            // labels_for_selection_raw always emits one entry for one selected
            // page; keep the defensive branch for malformed number-tree
            // implementations without panicking.
            if let Some((index, label)) = entries.into_iter().next() {
                label_entries.push(RawPageLabelEntry {
                    index,
                    source_id,
                    source_is_primary: source_index == 0,
                    label,
                });
            }
        }
    }

    // Capture source page identities before the primary page tree is flattened
    // by the job-owned merge. The qpdf source keeps these handles alive after
    // `removePage` has emptied the primary tree, and the AcroForm occurrence
    // replay below needs the same source-space mapping.
    let source_page_refs: Vec<Vec<ObjectRef>> = sources
        .iter_mut()
        .enumerate()
        .map(|(source_index, source)| {
            if source_index != 0 && grouped_pages[source_index].is_empty() {
                // An unused secondary is intentionally not read by the merge
                // route; preserve that qpdf-shaped fast path here as well.
                Ok(Vec::new())
            } else {
                crate::pages::page_refs(source)
            }
        })
        .collect::<Result<_>>()?;

    // qpdf aggregates all occurrences of one source document into one live
    // source QPDF. That gives merge_documents one copy map per source while
    // `ordered_pages` above preserves the original spec order and repeated
    // page occurrences.
    let mut merge_inputs: Vec<MergeInput<'_, R>> = sources
        .iter_mut()
        .zip(grouped_pages.iter())
        .map(|(source, pages)| MergeInput {
            source,
            pages: pages.clone(),
        })
        .collect();
    let mut merged = if preserve_unreferenced {
        merge_preserving_primary_into(
            &mut merge_inputs,
            &remove_resources,
            target,
            object_stream_mode,
        )? // cov:ignore: preserve page-spec merge is exercised by preserve-unreferenced integration tests; LLVM maps this multiline call continuation separately.
    } else {
        merge_documents_for_page_specs_into(
            &mut merge_inputs,
            &remove_resources,
            false,
            target,
            object_stream_mode,
        )? // cov:ignore: ordinary page-spec merge is exercised by page-operation differentials; LLVM maps this multiline call continuation separately.
           // cov:ignore: llvm-cov attributes this executed multiline merge call to its closing delimiter
    };
    drop(merge_inputs);

    // merge_documents emits source-group order. Rebuild the target tree with
    // the exact page-spec order. The copied page refs are already distinct for
    // duplicate occurrences, so this rebuild does not create a second copy.
    let grouped_refs = crate::pages::page_refs(&mut merged)?;
    // cov:ignore-start: merge_documents guarantees one copied page per selected page; this is a defensive postcondition guard.
    if grouped_refs.len() != ordered_pages.len() {
        return Err(Error::Unsupported(format!(
            "--pages: merge produced {} pages for {} selected pages",
            grouped_refs.len(),
            ordered_pages.len()
        )));
    }
    // cov:ignore-end
    let offsets: Vec<usize> = grouped_pages
        .iter()
        .scan(0usize, |offset, pages| {
            let current = *offset;
            *offset += pages.len();
            Some(current)
        })
        .collect();
    let occurrence_provenance = restore_occurrence_writer_provenance(
        &mut merged,
        sources,
        &source_page_refs,
        &grouped_pages,
        &ordered_pages,
        &grouped_refs,
        &offsets,
    )?; // cov:ignore: page-spec merge always supplies a valid writer-order target
    let final_refs: Vec<_> = ordered_pages
        .iter()
        .map(|&(source_index, group_index)| grouped_refs[offsets[source_index] + group_index])
        .collect();
    if final_refs != grouped_refs {
        crate::pages::tree_rebuild::rebuild_page_tree(&mut merged, &final_refs)?;
    }

    let replay_allocations = rebuild_acroform_in_final_page_order(
        &mut merged,
        sources,
        &source_page_refs,
        &grouped_pages,
        &ordered_pages,
        &final_refs,
    )?; // cov:ignore: public page selection supplies validated refs; the fallible continuation is covered by the direct helper error test
    if let Some(occurrence_provenance) = occurrence_provenance {
        finalize_page_spec_writer_provenance(
            &mut merged,
            occurrence_provenance,
            &replay_allocations,
        )?; // cov:ignore: page-spec merge always supplies a valid writer-order target
    }

    if any_page_labels {
        let folded = merge_adjacent_raw_page_labels(label_entries)?;
        let copied = copy_raw_page_label_entries(&mut merged, &folded)?;
        record_primary_label_provenance(&mut merged, &folded);
        merged
            .page_labels()
            .write_reconstructed_labels_raw(&copied)?;
    }

    // qpdf's multi-source merge is qpdf's own primary `QPDF::insertPage`
    // called once per selected page (`QPDFJob.cc:2470,2597`), and each call
    // flattens the *target*'s own page tree first
    // (`QPDF_pages.cc:204-218,161-164`), which materializes
    // `everPushedInheritedAttributesToPages` on the target as a side effect.
    // flpdf's bulk `merge_documents` route builds the same final page tree in
    // one pass instead of one `insertPage` per page, so that per-insertion
    // side effect never fires here. Reproduce it once, after the target's
    // page tree has its final shape, so JSON metadata (and any other
    // consumer of the flag/object-cache state) observes the same
    // target-document state qpdf's per-page loop would have left behind.
    //
    // A selection that resolves to no pages makes zero `insertPage` calls, so
    // qpdf never reaches that side effect at all; reproducing it anyway would
    // report `pushedinheritedpageresources` as true for an empty result.
    if !crate::PageDocumentHelper::new(&mut merged)
        .get_all_pages()?
        .is_empty()
    {
        crate::PageDocumentHelper::new(&mut merged).push_inherited_attributes_to_pages()?;
    }
    for source in sources.iter() {
        job.record_document_warnings(source);
    }
    job.record_document_warnings(&merged);
    Ok(merged)
}

impl super::QPDFJob {
    /// Complete qpdf's page-subset cleanup after the page tree and navigation
    /// references have been updated.
    ///
    /// The page-document helper owns per-page `/Font` and `/XObject` pruning;
    /// the writer reachability module owns xref-level orphan cleanup. This
    /// method is the job boundary that preserves qpdf's ordering without
    /// exposing the old mixed resource/reachability module as a public API.
    /// `Auto` must be the effective mode returned by the caller's pre-rebuild
    /// qpdf shared-resource heuristic.
    pub fn prune_after_subset<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        mode: RemoveUnreferencedResources,
    ) -> Result<()> {
        super::page_subset::prune_after_subset(pdf, mode)
    }

    /// Apply the qpdf `QPDFJob::handlePageSpecs` final AcroForm field filter
    /// for the single-document page-selection route.
    ///
    /// qpdf performs this operation inline after all selected-page copies and
    /// after unselected primary pages have been nulled
    /// (`QPDFJob.cc:2597-2632`). The multi-source path above owns its
    /// occurrence-aware copy and field filtering in the same job module; the
    /// single-source CLI path supplies its rebuilt-page result here so the
    /// operation is still owned by `job/`, not by CLI orchestration.
    ///
    /// The lower-level field-tree walk remains the one canonical
    /// `acroform_field_prune` implementation. This method only establishes
    /// the QPDFJob operation boundary and adds no alternate repair or
    /// compatibility route.
    pub fn prune_acroform_after_subset<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        result: &RebuildResult,
    ) -> Result<()> {
        super::acroform_field_prune::prune_acroform_after_subset(pdf, result)
    }

    /// Complete qpdf's page-selection mutation for an in-place result.
    ///
    /// qpdf performs page navigation cleanup, page-reference cleanup, subset
    /// pruning, and AcroForm field filtering as one ordered continuation of
    /// `handlePageSpecs` (`libqpdf/QPDFJob.cc:2360-2632`). Keep the same
    /// completion boundary for both the QPDFJob lifecycle and the CLI's
    /// already-opened primary document. Rotation remains a later operation,
    /// matching qpdf's `createQPDF` order (`QPDFJob.cc:466-470`).
    ///
    /// The structural-reference helpers are qpdf-backed page-subset
    /// consumers: they drop dangling `/Pg` and `/P` references before the
    /// subset sweep can collect the removed pages. CLI output and writer
    /// stages are deliberately outside this helper.
    pub fn complete_in_place_page_selection<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        result: &RebuildResult,
        prune_mode: RemoveUnreferencedResources,
    ) -> Result<()> {
        super::outline_dest_remap::remap_outline_and_dests(pdf, result)?;
        let objr_obj_targets = crate::drop_struct_elem_dangling_pg(pdf, result)?;
        crate::drop_thread_bead_dangling_p(pdf, result)?;
        crate::drop_objr_obj_annot_dangling_p(pdf, result, &objr_obj_targets)?;
        super::page_subset::prune_after_subset(pdf, prune_mode)?;
        super::acroform_field_prune::prune_acroform_after_subset(pdf, result)
    }

    /// Resolve and execute qpdf's page-specification operation
    /// (`QPDFJob::handlePageSpecs`, `libqpdf/QPDFJob.cc:2360-2632`) against the
    /// primary document itself. It owns:
    ///
    /// - per-spec range resolution and source-index validation;
    /// - qpdf's round-robin `--collate` order across specifications;
    /// - retaining source documents for deferred foreign stream reads;
    /// - removing and inserting pages on the primary's live page tree;
    /// - allocating foreign page graphs through its object cache in spec order; and
    /// - reconstructing `/PageLabels` in that same final order.
    ///
    /// `sources` supplies source documents in qpdf order, with the primary
    /// at index zero, and must remain mutable because page-tree repair and
    /// inherited-attribute materialization are part of the qpdf copy
    /// operation. `collate` is `None` for the ordinary concatenation order
    /// and `Some(values)` for qpdf's `--collate=n[,m,...]`; a single value is
    /// applied to every specification, and zero is a valid group size. A
    /// vector with more than one value must have one value per specification.
    /// `resource_mode` is qpdf's
    /// `--remove-unreferenced-resources={auto,yes,no}` job-level policy
    /// (qpdf's default is `auto`). `--preserve-unreferenced` remains a writer
    /// option and does not change this create-stage object cache.
    pub(crate) fn handle_page_specs<R: Read + Seek + 'static>(
        &mut self,
        sources: &mut [Pdf<R>],
        specs: &[PageSpecInput],
        collate: Option<&[usize]>,
        resource_mode: RemoveUnreferencedResources,
    ) -> Result<(RebuildResult, RemoveUnreferencedResources)> {
        let keep_files_open = self.keep_files_open_for_page_specs(specs);
        // qpdf never replaces the primary input's `InputSource` here, but it
        // selects the secondary-source implementation before page-spec reads
        // begin (`QPDFJob.cc:2392-2427`). Generic readers are unaffected; the
        // file factory installs a controller that closes/reopens at the same
        // boundary.
        for (source_index, source) in sources.iter().enumerate().skip(1) {
            if specs.iter().any(|spec| spec.source_index == source_index) {
                source.set_input_source_stay_open(keep_files_open);
            }
        }
        if sources.len() == 1 && specs.iter().all(|spec| spec.source_index == 0) {
            // cov:ignore-start: len()==1 guarantees first_mut() succeeds.
            let source = sources.first_mut().ok_or_else(|| {
                Error::Unsupported("--pages: a primary source is required".to_owned())
            })?;
            // cov:ignore-end
            return handle_single_source_page_specs(self, source, specs, collate, resource_mode);
        }

        handle_multi_source_page_specs_in_place(self, sources, specs, collate, resource_mode)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::job::QPDFJob;
    use crate::page_label_document_helper::LabelStyle;
    use crate::pipeline::{Pipeline, PipelineHandle, PipelineResult};
    use crate::{ObjectHandle, ObjectStreamMode, PdfWriter, QPDFLogger};
    use std::io::Cursor;
    use std::sync::{Arc, Mutex};

    struct RecordingInfoSink {
        bytes: Arc<Mutex<Vec<u8>>>,
    }

    impl Pipeline for RecordingInfoSink {
        fn identifier(&self) -> &str {
            "page-spec info capture"
        }

        fn write(&mut self, data: &[u8]) -> PipelineResult<()> {
            self.bytes.lock().unwrap().extend_from_slice(data);
            Ok(())
        }

        fn finish(&mut self) -> PipelineResult<()> {
            Ok(())
        }
    }

    fn verbose_job() -> (QPDFJob, Arc<Mutex<Vec<u8>>>) {
        let bytes = Arc::new(Mutex::new(Vec::new()));
        let logger = QPDFLogger::create();
        logger.set_info(Some(PipelineHandle::new(RecordingInfoSink {
            bytes: Arc::clone(&bytes),
        })));
        logger.set_warn(Some(logger.discard()));
        logger.set_error(Some(logger.discard()));
        let mut job = QPDFJob::new();
        job.set_logger(logger);
        job.set_message_prefix("qpdf");
        job.set_verbose(true);
        (job, bytes)
    }

    #[test]
    fn recording_info_sink_implements_the_pipeline_contract() {
        let bytes = Arc::new(Mutex::new(Vec::new()));
        let mut sink = RecordingInfoSink {
            bytes: Arc::clone(&bytes),
        };

        assert_eq!(sink.identifier(), "page-spec info capture");
        sink.write(b"probe\n").unwrap();
        sink.finish().unwrap();
        assert_eq!(&*bytes.lock().unwrap(), b"probe\n");
    }

    fn three_page_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/three-page.pdf").to_vec(),
        )
        .expect("open three-page fixture")
    }

    fn direct_root_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/direct-root-one-page.pdf").to_vec(),
        )
        .expect("open direct-root fixture")
    }

    fn direct_root_with_acroform_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let mut pdf = direct_root_pdf();
        pdf.root_handle()
            .expect("direct Catalog")
            .replace_key(
                b"/AcroForm",
                ObjectHandle::dictionary(vec![(
                    b"/NeedAppearances".to_vec(),
                    ObjectHandle::boolean(true),
                )]),
            )
            .expect("install direct AcroForm");
        pdf
    }

    fn acroform_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/acroform-sig-widget.pdf").to_vec(),
        )
        .expect("open AcroForm fixture")
    }

    fn inherited_resources_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/inherited-resources-one-page.pdf")
                .to_vec(),
        )
        .expect("open inherited-resources fixture")
    }

    fn link_annot_no_acroform_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/compat/link-annot-no-acroform.pdf").to_vec(),
        )
        .expect("open link-annot-no-acroform fixture")
    }

    #[test]
    fn page_spec_report_reuses_one_decision_per_source_identity() {
        let (job, output) = verbose_job();
        let inherited = inherited_resources_pdf();
        let mut duplicate_identity = three_page_pdf();
        duplicate_identity.unique_id = inherited.unique_id;
        let range = PageRange::parse_numrange("1").expect("one-page range");
        let specs = [
            PageSpecInput::new(0, range.clone()),
            PageSpecInput::new(1, range),
        ];
        let mut sources = [inherited, duplicate_identity];

        let decisions = report_page_spec_diagnostics(
            &job,
            &mut sources,
            &specs,
            RemoveUnreferencedResources::Auto,
        )
        .expect("resource report");
        assert_eq!(decisions, [true, true]);
        let output = output.lock().unwrap().clone();
        assert!(
            output
                .windows(b"found resources in non-leaf page node".len())
                .any(|window| window == b"found resources in non-leaf page node"),
            "verbose report must include the first finding: {output:?}"
        );
        assert_eq!(
            output
                .windows(b"checking for shared resources".len())
                .filter(|window| window == b"checking for shared resources")
                .count(),
            1,
            "a repeated source identity is preflighted once: {output:?}"
        );
    }

    #[test]
    fn page_spec_report_rejects_a_missing_source_after_reporting_preflight() {
        let (job, _output) = verbose_job();
        let mut source = three_page_pdf();
        let specs = [PageSpecInput::new(
            1,
            PageRange::parse_numrange("1").expect("one-page range"),
        )];

        assert!(matches!(
            report_page_spec_diagnostics(
                &job,
                std::slice::from_mut(&mut source),
                &specs,
                RemoveUnreferencedResources::Auto,
            ),
            Err(Error::Unsupported(message))
                if message == "--pages: specification refers to missing source 1"
        ));
    }

    #[test]
    fn empty_primary_keeps_qpdf_map_key_separate_from_display_name() {
        let mut job = QPDFJob::new();
        let empty = job.create_empty_document().expect("empty primary");
        let description = empty.input_source_description();

        assert_eq!(description, b"empty PDF");
        assert!(job.page_spec_source_sort_key(0, &description).is_empty());
        assert_eq!(job.page_spec_source_sort_key(1, b"empty PDF"), b"empty PDF");
    }

    #[test]
    fn page_spec_job_keeps_the_primary_document_as_multi_source_owner() {
        let primary = three_page_pdf();
        let secondary = inherited_resources_pdf();
        let primary_root = primary.root_ref();
        let range = PageRange::parse_numrange("1").expect("one-page range");
        let specs = [
            PageSpecInput::new(0, range.clone()),
            PageSpecInput::new(1, range),
        ];
        let mut sources = [primary, secondary];
        let mut job = QPDFJob::new();

        let (_result, _prune_mode) = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
            )
            .expect("multi-source page job");
        assert_eq!(sources[0].root_ref(), primary_root);
        assert_eq!(crate::pages::page_refs(&mut sources[0]).unwrap().len(), 2);
    }

    #[test]
    fn page_spec_job_accepts_a_direct_root_primary_with_a_secondary_source() {
        let primary = direct_root_pdf();
        let secondary = three_page_pdf();
        let range = PageRange::parse_numrange("1").expect("one-page range");
        let specs = [
            PageSpecInput::new(0, range.clone()),
            PageSpecInput::new(1, range),
        ];
        let mut sources = [primary, secondary];
        let mut job = QPDFJob::new();

        let mut merged = handle_page_specs_into(
            &mut job,
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
            Pdf::empty().expect("empty merge target"),
            ObjectStreamMode::Preserve,
        )
        .expect("direct-root primary must not panic during page merge");
        assert_eq!(crate::pages::page_refs(&mut merged).unwrap().len(), 2);
    }

    #[test]
    fn page_spec_job_copies_catalog_values_from_a_direct_root_primary() {
        let primary = direct_root_with_acroform_pdf();
        let secondary = three_page_pdf();
        let range = PageRange::parse_numrange("1").expect("one-page range");
        let specs = [
            PageSpecInput::new(0, range.clone()),
            PageSpecInput::new(1, range),
        ];
        let mut sources = [primary, secondary];
        let mut job = QPDFJob::new();

        let mut merged = handle_page_specs_into(
            &mut job,
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
            Pdf::empty().expect("empty merge target"),
            ObjectStreamMode::Preserve,
        )
        .expect("direct-root Catalog values must be copied");
        let catalog = merged.root_handle().expect("merged Catalog");
        let acroform = catalog.try_get_key(b"/AcroForm").expect("copied /AcroForm");
        assert!(acroform.try_is_dictionary().unwrap());
        assert_eq!(
            acroform
                .try_get_key(b"/NeedAppearances")
                .unwrap()
                .as_boolean(),
            Some(true)
        );
    }

    fn labelled_pdf() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open_mem_owned(
            include_bytes!("../../../../tests/fixtures/json-diff/direct-outlines.pdf").to_vec(),
        )
        .expect("open labelled fixture")
    }

    /// Build a minimal PDF from a flat list of contiguously-numbered object
    /// bodies (1-indexed from 1).
    fn assemble_pdf(objects: &[&[u8]]) -> Vec<u8> {
        use std::io::Write;
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let mut offsets = Vec::with_capacity(objects.len());
        for object in objects {
            offsets.push(bytes.len());
            bytes.extend_from_slice(object);
        }
        let start_xref = bytes.len();
        let _ = writeln!(&mut bytes, "xref\n0 {}", objects.len() + 1);
        bytes.extend_from_slice(b"0000000000 65535 f \n");
        for &offset in &offsets {
            let _ = writeln!(&mut bytes, "{offset:010} 00000 n ");
        }
        let _ = writeln!(
            &mut bytes,
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF",
            objects.len() + 1,
            start_xref
        );
        bytes
    }

    fn raw_generation_orphan_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let catalog_offset = bytes.len();
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let pages_offset = bytes.len();
        bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
        let page_offset = bytes.len();
        bytes.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let orphan_offset = bytes.len();
        bytes.extend_from_slice(b"5 65536 obj\n45\nendobj\n");
        let xref_offset = bytes.len();
        bytes.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n");
        bytes.extend_from_slice(format!("{catalog_offset:010} 00000 n \n").as_bytes());
        bytes.extend_from_slice(format!("{pages_offset:010} 00000 n \n").as_bytes());
        bytes.extend_from_slice(format!("{page_offset:010} 00000 n \n").as_bytes());
        bytes.extend_from_slice(b"0000000000 00000 f \n");
        bytes.extend_from_slice(format!("{orphan_offset:010} 65536 n \n").as_bytes());
        bytes.extend_from_slice(
            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
                .as_bytes(),
        );
        Pdf::open_mem_owned(bytes).expect("open raw-generation orphan fixture")
    }

    /// Single-page PDF whose `/AcroForm` has `/NeedAppearances` but no
    /// `/Fields` key at all (qpdf's `had_fields_array` gate is false).
    fn acroform_no_fields_array_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = assemble_pdf(&[
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
              /AcroForm << /NeedAppearances true >> >>\nendobj\n",
            b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n",
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        ]);
        Pdf::open_mem_owned(bytes).expect("open AcroForm-no-fields-array fixture")
    }

    /// Two-page PDF: page 1 has no widgets; page 2 (left unselected by the
    /// tests below) carries the document's only field, "Orphan".
    fn acroform_all_fields_on_page_two_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = assemble_pdf(&[
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
              /AcroForm << /Fields [5 0 R] /NeedAppearances true >> >>\nendobj\n",
            b"2 0 obj\n<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>\nendobj\n",
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
            b"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
              /Annots [5 0 R] >>\nendobj\n",
            b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (Orphan) \
              /Rect [0 0 10 10] /P 4 0 R >>\nendobj\n",
        ]);
        Pdf::open_mem_owned(bytes).expect("open AcroForm-orphan-field fixture")
    }

    fn selected_page_count(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> usize {
        crate::pages::page_refs(pdf)
            .expect("read merged page tree")
            .len()
    }

    fn selected_indices(
        source: &mut Pdf<Cursor<Vec<u8>>>,
        specs: &[PageSpecInput],
        collate: Option<&[usize]>,
    ) -> Vec<u32> {
        select_single_source_pages(source, specs, collate)
            .expect("valid page specifications")
            .into_iter()
            .map(|page| page.index_1based)
            .collect()
    }

    fn resolved_object(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef) -> ObjectHandle {
        let object = pdf.get_object_handle(object_ref);
        object.try_is_scalar().expect("resolve object handle");
        object
    }

    fn resolved_key(owner: &ObjectHandle, key: &[u8]) -> ObjectHandle {
        let value = owner.try_get_key(key).unwrap();
        value.try_is_scalar().expect("resolve child handle");
        value
    }

    fn pdf_without_root() -> Pdf<Cursor<Vec<u8>>> {
        let mut pdf = Pdf::empty().expect("empty PDF");
        pdf.trailer().remove_key(b"/Root");
        assert!(pdf.root_ref().is_none());
        pdf
    }

    #[test]
    fn page_spec_error_keeps_non_range_errors_in_the_existing_context() {
        let error = page_spec_error(b"input.pdf", 2, 3, Error::Missing("/Root"));
        assert!(matches!(
            error,
            Error::Unsupported(message)
                if message == "--pages: source 2 specification 3: missing required PDF entry: /Root"
        ));

        let unrelated = Error::SystemBytes(b"not a numeric range error".to_vec());
        assert!(qpdf_page_range_error(b"input.pdf", &unrelated).is_none());
    }

    #[test]
    fn rebuild_acroform_ignores_a_missing_merged_root() {
        let mut merged = pdf_without_root();
        let mut sources: Vec<Pdf<Cursor<Vec<u8>>>> = Vec::new();
        rebuild_acroform_in_final_page_order(&mut merged, &mut sources, &[], &[], &[], &[])
            .expect("a missing merged root has no AcroForm to rebuild");
    }

    #[test]
    fn replace_merged_fields_ignores_a_missing_merged_root_when_gated_open() {
        let mut merged = pdf_without_root();
        replace_merged_fields(&mut merged, Vec::new(), true)
            .expect("a missing merged root has no AcroForm to rebuild, even past the gate");
        remove_empty_acroform_after_replay(&mut merged, true)
            .expect("a missing merged root has no AcroForm to remove");
    }

    #[test]
    fn replace_merged_fields_defers_empty_acroform_removal_until_replay_finishes() {
        let mut merged = acroform_pdf();
        replace_merged_fields(&mut merged, Vec::new(), true)
            .expect("an empty survivor list leaves the replay base in place");
        let root_ref = merged.root_ref().expect("root");
        assert!(
            !resolved_object(&mut merged, root_ref)
                .try_get_key(b"/AcroForm")
                .unwrap()
                .is_null(),
            "qpdf keeps /AcroForm alive through foreign annotation replay"
        );
        remove_empty_acroform_after_replay(&mut merged, true)
            .expect("final replay cleanup removes an empty /AcroForm");
        assert!(
            resolved_object(&mut merged, root_ref)
                .try_get_key(b"/AcroForm")
                .unwrap()
                .is_null(),
            "qpdf removes /AcroForm after the filtered field count reaches zero"
        );
    }

    #[test]
    fn rebuild_acroform_propagates_annotation_copy_errors() {
        let mut merged = three_page_pdf();
        let invalid_final_ref = ObjectRef::new(999, 0);
        let mut sources = vec![three_page_pdf()];
        let source_page_refs = sources
            .iter_mut()
            .map(crate::pages::page_refs)
            .collect::<Result<Vec<_>>>()
            .unwrap();
        rebuild_acroform_in_final_page_order(
            &mut merged,
            &mut sources,
            &source_page_refs,
            &[vec![0]],
            &[(0, 0)],
            &[invalid_final_ref],
        )
        .expect_err("an invalid destination page must escape the foreign copy route");
    }

    #[test]
    fn rebuild_acroform_uses_foreign_copy_route_for_secondary_acroform() {
        let mut merged = three_page_pdf();
        let mut sources = vec![three_page_pdf(), acroform_pdf()];
        let source_page_refs = sources
            .iter_mut()
            .map(crate::pages::page_refs)
            .collect::<Result<Vec<_>>>()
            .unwrap();

        rebuild_acroform_in_final_page_order(
            &mut merged,
            &mut sources,
            &source_page_refs,
            &[vec![], vec![0]],
            &[(1, 0)],
            &[ObjectRef::new(3, 0)],
        )
        .expect("a secondary AcroForm page must use the foreign copy route");
    }

    #[test]
    fn collect_primary_fields_ignores_direct_field_handles() {
        let mut merged = three_page_pdf();
        let page_ref = crate::pages::page_refs(&mut merged).unwrap()[0];
        let page = merged.get_object_handle(page_ref);
        let widget = ObjectHandle::dictionary(vec![
            (b"Type".to_vec(), ObjectHandle::name(b"Annot".to_vec())),
            (b"Subtype".to_vec(), ObjectHandle::name(b"Widget".to_vec())),
        ]);
        page.replace_key(b"/Annots", ObjectHandle::array(vec![widget]))
            .unwrap();

        assert!(
            collect_primary_fields(&mut merged, &[page_ref])
                .unwrap()
                .is_empty(),
            "direct field handles have no stable top-level object identity"
        );
    }

    #[test]
    fn handle_page_specs_default_materializes_inherited_resources_like_qpdf() {
        let mut sources = vec![inherited_resources_pdf()];
        let specs = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1,1").unwrap(),
        )];

        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("merge inherited-resources page");
        let page_refs = crate::pages::page_refs(&mut merged).expect("read merged page tree");
        assert_eq!(page_refs.len(), 2);
        for page_ref in page_refs {
            let page = resolved_object(&mut merged, page_ref);
            assert!(
                page.try_get_key(b"/Resources")
                    .unwrap()
                    .as_dictionary()
                    .is_some(),
                "qpdf --pages default copies inherited /Resources directly onto the page"
            );
        }
    }

    /// qpdf allocates each duplicate page's clone and its annotation clone
    /// back to back, before moving on to the next occurrence
    /// (`QPDFJob.cc:2537-2585`: `shallowCopyPage` immediately followed by
    /// `fixCopiedAnnotations` within the same loop iteration). Pin that
    /// interleaved allocation order rather than only checking that the final
    /// annotation content is correct. Uses the real in-place single-source
    /// dispatch (`QPDFJob::handle_page_specs`), not the test-only
    /// `handle_page_specs` free function above, which always merges into a
    /// fresh empty target and so never reaches
    /// `handle_single_source_page_specs`.
    #[test]
    fn handle_page_specs_interleaves_duplicate_page_and_annotation_clone_allocation() {
        let mut sources = vec![link_annot_no_acroform_pdf()];
        let specs = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1,1,1").unwrap(),
        )];
        let mut job = QPDFJob::new();

        let (_result, _prune_mode) = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
            )
            .expect("triple-duplicate single-source page job");
        let pdf = &mut sources[0];

        let page_refs = crate::pages::page_refs(pdf).expect("read merged page tree");
        assert_eq!(page_refs.len(), 3);

        let mut annot_refs = Vec::with_capacity(3);
        for &page_ref in &page_refs {
            let page = resolved_object(pdf, page_ref);
            let annots = resolved_key(&page, b"/Annots");
            let annot_array = annots.as_array().expect("/Annots is an array");
            assert_eq!(annot_array.len(), 1);
            let annot_ref = annot_array[0]
                .object_ref()
                .expect("annotation is an indirect reference");
            annot_refs.push(annot_ref);
        }

        assert_eq!(
            annot_refs.iter().collect::<BTreeSet<_>>().len(),
            3,
            "each duplicated page must get its own annotation clone: {annot_refs:?}"
        );

        for (page_ref, annot_ref) in page_refs.iter().skip(1).zip(annot_refs.iter().skip(1)) {
            assert_eq!(
                annot_ref.number,
                page_ref.number + 1,
                "annotation clone must be allocated immediately after its page clone, \
                 matching qpdf's interleaved order: pages={page_refs:?} annots={annot_refs:?}"
            );
        }
    }

    #[test]
    fn handle_page_specs_preserve_unreferenced_keeps_raw_generation_objects() {
        let mut sources = vec![raw_generation_orphan_pdf(), three_page_pdf()];
        let raw_orphans = sources[0]
            .canonical_live_object_handles()
            .expect("enumerate raw-generation live objects");
        assert!(
            raw_orphans
                .iter()
                .any(|handle| { handle.qpdf_obj_gen() == Some(QpdfObjGen::new(5, 65_536)) }),
            "canonical live handles must retain raw-generation source objects"
        );
        let mut allocated_raw = three_page_pdf();
        allocated_raw
            .replace_object(ObjectRef::new(9, 65_535), ObjectHandle::integer(45))
            .expect("install document-allocated raw identity");
        assert!(
            allocated_raw
                .canonical_live_object_handles()
                .expect("enumerate allocated raw object")
                .iter()
                .any(|handle| { handle.qpdf_obj_gen() == Some(QpdfObjGen::new(9, 65_535)) }),
            "canonical live handles must retain allocated raw identities"
        );
        let specs = [
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
            PageSpecInput::new(1, PageRange::parse_numrange("1").unwrap()),
        ];
        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            true,
        )
        .expect("preserve-unreferenced page merge");

        let mut writer = PdfWriter::new(&mut merged);
        writer.set_static_id(true);
        writer.set_object_stream_mode(ObjectStreamMode::Disable);
        writer.set_preserve_unreferenced_objects(true);
        writer.set_output_memory().expect("configure memory output");
        writer.write().expect("preserve-unreferenced merge write");
        let output = writer.get_buffer().expect("writer output");
        assert_eq!(
            output
                .windows(b"\n45\n".len())
                .filter(|window| *window == b"\n45\n")
                .count(),
            1,
            "raw-generation primary orphan must be copied into the preserve target"
        );
    }

    #[test]
    fn handle_page_specs_skips_an_unused_secondary_source() {
        let mut sources = vec![three_page_pdf(), pdf_without_root()];
        let specs = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1").unwrap(),
        )];

        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("an unused secondary source must not be read");

        assert_eq!(selected_page_count(&mut merged), 1);
    }

    #[test]
    fn qpdf_job_keeps_a_single_source_page_job_in_place() {
        let mut sources = vec![three_page_pdf()];
        let specs = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("2").unwrap(),
        )];
        let mut job = QPDFJob::new();

        let (result, _prune_mode) = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
            )
            .expect("single-source page job");
        let pdf = &mut sources[0];
        assert_eq!(result.new_kids.len(), 1);
        assert_eq!(selected_page_count(pdf), 1);
        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .all(|entry| !entry.message_string().contains("foreign object")));
    }

    #[test]
    fn qpdf_job_in_place_page_job_copies_repeated_page_annotations() {
        let mut sources = vec![acroform_pdf()];
        let specs = [
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
        ];
        let mut job = QPDFJob::new();

        let (result, _prune_mode) = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
            )
            .expect("repeated single-source page job");
        let pdf = &mut sources[0];
        assert_eq!(result.new_kids.len(), 2);
        assert_eq!(selected_page_count(pdf), 2);
    }

    #[test]
    fn single_source_page_planner_reports_its_input_errors() {
        let mut source = three_page_pdf();
        assert!(select_single_source_pages(&mut source, &[], None).is_err());
        assert!(select_single_source_pages(
            &mut source,
            &[PageSpecInput::new(
                0,
                PageRange::parse_numrange("1").unwrap()
            )],
            Some(&[1, 2]),
        )
        .is_err());
        assert!(select_single_source_pages(
            &mut source,
            &[PageSpecInput::new(
                1,
                PageRange::parse_numrange("1").unwrap()
            )],
            None,
        )
        .is_err());
        assert!(select_single_source_pages(
            &mut source,
            &[PageSpecInput::new(
                0,
                PageRange::parse_numrange("999").unwrap()
            )],
            None,
        )
        .is_err());
    }

    #[test]
    fn collate_value_cardinality_matches_qpdf() {
        assert_eq!(collate_values_for_specs(None, 2).unwrap(), None);
        assert_eq!(collate_values_for_specs(Some(&[]), 2).unwrap(), None);
        assert_eq!(
            collate_values_for_specs(Some(&[2]), 2).unwrap(),
            Some(vec![2, 2])
        );
        assert_eq!(
            collate_values_for_specs(Some(&[2, 3]), 2).unwrap(),
            Some(vec![2, 3])
        );
        assert!(collate_values_for_specs(Some(&[1, 2, 3]), 2).is_err());
    }

    #[test]
    fn single_source_page_planner_applies_qpdf_collate_values_per_spec() {
        let specs = [
            PageSpecInput::new(0, PageRange::parse_numrange("1-3").unwrap()),
            PageSpecInput::new(0, PageRange::parse_numrange("1-3").unwrap()),
        ];

        let mut source = three_page_pdf();
        assert_eq!(
            selected_indices(&mut source, &specs, Some(&[2, 1])),
            vec![1, 2, 1, 3, 2, 3]
        );

        let mut source = three_page_pdf();
        assert_eq!(
            selected_indices(&mut source, &specs, Some(&[2])),
            vec![1, 2, 1, 2, 3, 3]
        );

        let mut source = three_page_pdf();
        assert!(selected_indices(&mut source, &specs, Some(&[0])).is_empty());

        let mut source = three_page_pdf();
        assert_eq!(
            selected_indices(&mut source, &specs, Some(&[0, 1])),
            vec![1, 2, 3]
        );

        let mut source = three_page_pdf();
        let single_spec = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1").unwrap(),
        )];
        assert_eq!(
            selected_indices(&mut source, &single_spec, Some(&[0])),
            vec![1]
        );

        let mut source = three_page_pdf();
        assert!(select_single_source_pages(&mut source, &specs, Some(&[1, 2, 3])).is_err());
    }

    #[test]
    fn handle_page_specs_preserves_an_acroform_with_no_fields_array_across_sources() {
        let mut sources = vec![acroform_no_fields_array_pdf(), three_page_pdf()];
        let specs = [
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
            PageSpecInput::new(1, PageRange::parse_numrange("1").unwrap()),
        ];

        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("merge across a fields-less-AcroForm primary and a secondary source");
        let root_ref = merged.root_ref().expect("merged root");
        let root = resolved_object(&mut merged, root_ref);
        let acroform = resolved_key(&root, b"/AcroForm");
        assert_eq!(
            resolved_key(&acroform, b"/NeedAppearances").as_boolean(),
            Some(true)
        );
        assert!(
            acroform.try_get_key(b"/Fields").unwrap().is_null(),
            "no /Fields array existed originally; the merge must not manufacture one"
        );
    }

    #[test]
    fn handle_page_specs_removes_acroform_when_the_only_field_page_is_unselected() {
        let mut sources = vec![acroform_all_fields_on_page_two_pdf(), three_page_pdf()];
        let specs = [
            // Only page 1 (no widgets); page 2's "Orphan" field is dropped.
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
            PageSpecInput::new(1, PageRange::parse_numrange("1").unwrap()),
        ];

        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("merge with the only AcroForm field on an unselected page");
        let root_ref = merged.root_ref().expect("merged root");
        assert!(
            resolved_object(&mut merged, root_ref)
                .try_get_key(b"/AcroForm")
                .unwrap()
                .is_null(),
            "qpdf removes /AcroForm entirely once its filtered field count reaches zero"
        );
    }

    #[test]
    fn qpdf_job_owns_single_document_acroform_prune_boundary() {
        let mut pdf = acroform_all_fields_on_page_two_pdf();
        let original_pages = crate::pages::page_refs(&mut pdf).expect("original page refs");
        let result = crate::pages::tree_rebuild::rebuild_page_tree(&mut pdf, &[original_pages[0]])
            .expect("rebuild the selected page");

        QPDFJob::prune_acroform_after_subset(&mut pdf, &result)
            .expect("job-owned AcroForm pruning");

        let root_ref = pdf.root_ref().expect("root");
        assert!(
            resolved_object(&mut pdf, root_ref)
                .try_get_key(b"/AcroForm")
                .unwrap()
                .is_null(),
            "the job boundary must remove an empty AcroForm after page selection"
        );
    }

    #[test]
    fn page_spec_input_constructor_keeps_source_and_range() {
        let range = PageRange::parse_numrange("1-2").unwrap();
        assert_eq!(PageSpecInput::new(3, range.clone()).source_index, 3);
        assert_eq!(
            PageSpecInput::new(3, range).range,
            PageRange::parse_numrange("1-2").unwrap()
        );
    }

    #[test]
    fn handle_page_specs_rejects_invalid_job_inputs_and_selections() {
        let mut no_sources: Vec<Pdf<Cursor<Vec<u8>>>> = Vec::new();
        let spec = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1").unwrap(),
        )];
        assert!(handle_page_specs(
            &mut QPDFJob::new(),
            &mut no_sources,
            &spec,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .is_err());

        let mut sources = vec![three_page_pdf()];
        assert!(handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &[],
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .is_err());

        let mut sources = vec![three_page_pdf()];
        let missing = [PageSpecInput::new(
            1,
            PageRange::parse_numrange("1").unwrap(),
        )];
        assert!(handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &missing,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .is_err());

        let mut sources = vec![three_page_pdf()];
        let out_of_range = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("99").unwrap(),
        )];
        assert!(handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &out_of_range,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .is_err());
    }

    #[test]
    fn multi_source_handler_rejects_missing_sources_empty_specs_and_bad_source_indices() {
        let mut no_sources: Vec<Pdf<Cursor<Vec<u8>>>> = Vec::new();
        assert!(handle_multi_source_page_specs_in_place(
            &mut QPDFJob::new(),
            &mut no_sources,
            &[],
            None,
            RemoveUnreferencedResources::Auto,
        )
        .is_err());

        let mut sources = vec![three_page_pdf()];
        assert!(handle_multi_source_page_specs_in_place(
            &mut QPDFJob::new(),
            &mut sources,
            &[],
            None,
            RemoveUnreferencedResources::Auto,
        )
        .is_err());

        let invalid_source = [PageSpecInput::new(
            1,
            PageRange::parse_numrange("1").expect("page range"),
        )];
        assert!(handle_multi_source_page_specs_in_place(
            &mut QPDFJob::new(),
            &mut sources,
            &invalid_source,
            None,
            RemoveUnreferencedResources::Auto,
        )
        .is_err());
    }

    #[test]
    fn multi_source_acroform_pruning_skips_a_non_dictionary_value() {
        let mut pdf = three_page_pdf();
        pdf.root_handle()
            .expect("catalog")
            .replace_key(b"/AcroForm", ObjectHandle::integer(1))
            .expect("install malformed AcroForm");

        prune_page_spec_acroform_fields(&mut pdf, &[])
            .expect("qpdf skips field pruning without an AcroForm dictionary");
    }

    /// qpdf's `handlePageSpecs` (`QPDFJob.cc:2360-2632`) has no empty-selection
    /// guard and `QUtil::parse_numrange` returns an empty vector when the
    /// exclusions cancel a group out (`QUtil.cc:1385-1400`). Probed with qpdf
    /// 11.9.0: `--pages . 1,x1 --` and `--pages . :odd --` both exit 0 and
    /// write a valid 0-page document, and flpdf's output is byte-identical.
    #[test]
    fn handle_page_specs_accepts_an_empty_selection_like_qpdf() {
        let mut sources = vec![three_page_pdf()];
        let empty = [PageSpecInput::new(0, PageRange::empty())];
        let mut merged = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &empty,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("an empty page selection writes a 0-page document");
        let page_refs = crate::pages::page_refs(&mut merged).expect("read the page tree");
        assert!(page_refs.is_empty(), "got {page_refs:?}");
    }

    #[test]
    fn handle_page_specs_restores_cross_source_order_and_collates() {
        let mut sources = vec![three_page_pdf(), three_page_pdf()];
        let reversed = [
            PageSpecInput::new(1, PageRange::parse_numrange("1").unwrap()),
            PageSpecInput::new(0, PageRange::parse_numrange("1").unwrap()),
        ];
        let mut reversed_output = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &reversed,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .unwrap();
        assert_eq!(selected_page_count(&mut reversed_output), 2);

        let mut sources = vec![three_page_pdf(), three_page_pdf()];
        let collated = [
            PageSpecInput::new(0, PageRange::parse_numrange("1-2").unwrap()),
            PageSpecInput::new(1, PageRange::parse_numrange("1-2").unwrap()),
        ];
        let mut collated_output = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &collated,
            Some(&[1]),
            RemoveUnreferencedResources::Auto,
            false,
        )
        .unwrap();
        assert_eq!(selected_page_count(&mut collated_output), 4);
    }

    #[test]
    fn handle_page_specs_accepts_per_spec_and_zero_collate_values() {
        let specs = [
            PageSpecInput::new(0, PageRange::parse_numrange("1-3").unwrap()),
            PageSpecInput::new(1, PageRange::parse_numrange("1-3").unwrap()),
        ];

        let mut sources = vec![three_page_pdf(), three_page_pdf()];
        let mut per_spec = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            Some(&[2, 3]),
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("per-spec collate values are valid");
        assert_eq!(selected_page_count(&mut per_spec), 6);

        let mut sources = vec![three_page_pdf(), three_page_pdf()];
        let mut second_only = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            Some(&[0, 1]),
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("zero collate value is valid");
        assert_eq!(selected_page_count(&mut second_only), 3);

        let mut sources = vec![three_page_pdf(), three_page_pdf()];
        let mut empty = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            Some(&[0]),
            RemoveUnreferencedResources::Auto,
            false,
        )
        .expect("all-zero collate value is valid");
        assert_eq!(selected_page_count(&mut empty), 0);
    }

    #[test]
    fn handle_page_specs_reconstructs_qpdf_page_labels_with_empty_prefix() {
        let mut sources = vec![labelled_pdf()];
        let specs = [PageSpecInput::new(
            0,
            PageRange::parse_numrange("1-2").unwrap(),
        )];
        let mut output = handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &specs,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .unwrap();

        let catalog_ref = output.root_ref().unwrap();
        let catalog = resolved_object(&mut output, catalog_ref);
        let page_labels = resolved_key(&catalog, b"/PageLabels");
        let nums = resolved_key(&page_labels, b"/Nums")
            .as_array()
            .expect("merged PageLabels /Nums must be an array");
        let first_label = nums.get(1).cloned().expect("first reconstructed label");
        first_label
            .try_is_scalar()
            .expect("resolve first reconstructed label");
        assert_eq!(
            first_label.try_get_key(b"/P").unwrap().as_string(),
            Some(Vec::new())
        );
    }

    #[test]
    fn merge_job_label_ranges_preserves_prefix_presence_and_checked_arithmetic() {
        let decimal = |start| LabelRange {
            style: LabelStyle::Decimal,
            prefix: String::new(),
            start,
        };
        let merged = merge_job_label_ranges(vec![(0, decimal(1), true), (1, decimal(2), true)]);
        assert_eq!(merged.len(), 1);

        let prefix_presence_mismatch =
            merge_job_label_ranges(vec![(0, decimal(1), true), (1, decimal(2), false)]);
        assert_eq!(prefix_presence_mismatch.len(), 2);

        let underflow =
            merge_job_label_ranges(vec![(1, decimal(1), false), (0, decimal(1), false)]);
        assert_eq!(underflow.len(), 2);
        let overflow =
            merge_job_label_ranges(vec![(0, decimal(i64::MAX), false), (1, decimal(0), false)]);
        assert_eq!(overflow.len(), 2);
    }
}