flpdf 0.5.1

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

use super::page_merge::{
    merge_documents_with_resource_decisions_and_preserve_primary, source_top_level_field_names,
    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;
use crate::page_label_document_helper::LabelRange;
use crate::pages::tree_rebuild::RebuildResult;
use crate::{
    AcroFormDocumentHelper, Error, Matrix, ObjectHandle, ObjectRef, PageObjectHelper, PageRange,
    Pdf, Result, UsageError,
};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, 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 struct PageSpecInput {
    /// Index of the source document in
    /// [`QPDFJob::handle_page_specs`](super::QPDFJob::handle_page_specs).
    pub source_index: usize,
    /// qpdf page-range expression for this source occurrence.
    pub range: PageRange,
}

/// Result of qpdf's page-specification boundary.
///
/// qpdf keeps a one-source page job in its primary `QPDF` and therefore
/// preserves the primary object's live identities. Multi-source jobs use the
/// existing fresh primary-based merge target because the copied foreign graph
/// must outlive the source-page operation. The caller must keep the source
/// documents alive while using either result's returned document.
pub enum PageSpecJobOutput<'a, R: Read + Seek + 'static> {
    /// The primary document was updated in place by the single-source page
    /// job. `result` is the page-tree rebuild result used by later job stages.
    InPlace {
        /// The primary document carrying the selected page tree.
        pdf: &'a mut Pdf<R>,
        /// The qpdf-shaped page-tree rebuild mapping.
        result: RebuildResult,
        /// The effective page-resource pruning mode selected before rebuild.
        prune_mode: RemoveUnreferencedResources,
    },
    /// A fresh target produced by the multi-source foreign-copy route.
    Merged(Box<Pdf<std::io::Cursor<Vec<u8>>>>),
}

/// 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
            )));
        }
        plans.push(PagePlan::build(source, &spec.range).map_err(|error| {
            Error::Unsupported(format!(
                "--pages: source 0 specification {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()));
    }

    let allows_empty_selection = plans.len() > 1
        && collate_values
            .as_ref()
            .is_some_and(|values| values.iter().all(|&value| value == 0));
    if selected.is_empty() && !allows_empty_selection {
        return Err(Error::Unsupported(
            "--pages: page selection is empty".into(),
        ));
    }
    Ok(selected)
}

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`).
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");
        pdf.mark_object_handle_dirty(&destination_page)?;
        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().as_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 result = crate::pages::tree_rebuild::rebuild_page_tree(source, &selected_refs)?;
    copy_duplicate_page_annotations(source, &result)?;

    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_with_prefix_presence(&src_indices, 0)?;
        let folded = crate::merge_adjacent_ranges_with_prefix_presence(entries);
        labels.write_reconstructed_labels_with_prefix_presence(&folded)?;
    }
    job.record_document_warnings(source);
    Ok((result, prune_mode))
}

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

fn merge_preserving_primary<R: Read + Seek>(
    inputs: &mut [MergeInput<'_, R>],
    remove_resources: &[bool],
) -> Result<Pdf<Cursor<Vec<u8>>>> {
    merge_documents_with_resource_decisions_and_preserve_primary(inputs, remove_resources, true)
}

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

/// One qpdf-style reconstructed label, retaining raw `/P` presence in
/// addition to the typed compatibility projection.
type JobLabelEntry = (i64, LabelRange, bool);

fn collect_primary_fields(
    merged: &mut Pdf<Cursor<Vec<u8>>>,
    pages: &[ObjectRef],
) -> Result<Vec<ObjectHandle>> {
    let mut field_refs = BTreeSet::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 let Some(field_ref) = field.object_ref() {
                    candidate_fields.push(field_ref);
                } // cov:ignore: structural brace has no LLVM executable counter
            }
        }
    }
    for field_ref in candidate_fields {
        let (top_level, _) = FormFieldObjectHelper::new(field_ref, merged).get_top_level_field()?;
        field_refs.insert(top_level);
    }
    let primary_order = {
        let mut acroform = AcroFormDocumentHelper::new_for_field_tree(merged)?;
        acroform.top_level_fields()?
    };
    Ok(primary_order
        .into_iter()
        .filter(|field_ref| field_refs.contains(field_ref))
        .map(|field_ref| merged.get_object_handle(field_ref))
        .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.
fn replace_merged_fields(
    merged: &mut Pdf<Cursor<Vec<u8>>>,
    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 = merged.resolve_handle(&root.try_get_key(b"/AcroForm")?)?;
    let Some(_) = acroform.as_dictionary() else {
        return Ok(());
    };
    if fields.is_empty() {
        root.remove_key(b"/AcroForm");
        merged.mark_object_handle_dirty(&root)?;
    } else {
        acroform.replace_key(b"/Fields", ObjectHandle::array(fields))?;
        merged.mark_object_handle_dirty(&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.
fn clear_grouped_foreign_fields_for_replay(merged: &mut Pdf<Cursor<Vec<u8>>>) -> Result<()> {
    let Some(root_ref) = merged.root_ref() else {
        return Ok(());
    };
    let root = merged.get_object_handle(root_ref);
    let acroform = merged.resolve_handle(&root.try_get_key(b"/AcroForm")?)?;
    if acroform.try_as_dictionary()?.is_none() {
        return Ok(());
    }
    let fields = merged.resolve_handle(&acroform.try_get_key(b"/Fields")?)?;
    if fields.try_as_array()?.is_none() {
        return Ok(());
    }
    acroform.replace_key(b"/Fields", ObjectHandle::array(Vec::new()))?;
    merged.mark_object_handle_dirty(&acroform)
}

/// 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.
fn set_annotation_page_refs(
    merged: &mut Pdf<Cursor<Vec<u8>>>,
    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())?;
            merged.mark_object_handle_dirty(&annotation)?;
        }
    }
    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.
fn rebuild_acroform_in_final_page_order<R: Read + Seek + 'static>(
    merged: &mut Pdf<Cursor<Vec<u8>>>,
    sources: &mut [Pdf<R>],
    source_page_refs: &[Vec<ObjectRef>],
    grouped_pages: &[Vec<usize>],
    ordered_pages: &[OrderedPage],
    final_refs: &[ObjectRef],
) -> Result<()> {
    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 branch is based on document ownership. The primary's first
    // occurrence remains on the primary route; repeated primary pages use the
    // same-document copier; only a secondary source with an AcroForm enters
    // the foreign resource/field route.
    let source_has_acroform: Vec<bool> = sources
        .iter_mut()
        .map(|source| source.acroform()?.has_acro_form())
        .collect::<Result<_>>()?;

    // 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()];
    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);
        object_map.extend(mappings.iter().map(|(&source, &target)| (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 || (!source_has_acroform[source_index] && source_index != 0) {
            // The grouped page copy already owns these annotations. Keep them
            // for qpdf's primary-first and foreign-no-AcroForm branches, but
            // repair `/P` after the grouped→final page-order reconstruction.
            set_annotation_page_refs(merged, final_refs[output_index], first_output_page)?;
            continue;
        }

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

        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.
        }
    }

    Ok(())
}

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`.
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>>>> {
    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 plan = PagePlan::build(source, &spec.range).map_err(|error| {
            Error::Unsupported(format!(
                "--pages: source {} specification {spec_index}: {error}",
                spec.source_index
            ))
        })?;
        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);
            }
        }
    }

    let allows_empty_selection = plans.len() > 1
        && collate_values
            .as_ref()
            .is_some_and(|values| values.iter().all(|&value| value == 0));
    if ordered_pages.is_empty() && !allows_empty_selection {
        return Err(Error::Unsupported(
            "--pages: page selection is empty".into(),
        ));
    }

    let remove_resources = report_page_spec_diagnostics(job, sources, specs, resource_mode)?;

    // qpdf's label accumulator is populated in final output order, not in
    // source-group order. Capture it before borrowing all sources for the
    // merge. When any source has labels, sources without labels still
    // contribute qpdf's default decimal label for their selected pages.
    let mut any_page_labels = false;
    for source in sources.iter_mut() {
        any_page_labels |= source.page_labels().has_page_labels()?;
    }

    let mut label_entries = 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 entries = source
                .page_labels()
                .labels_for_selection(&[source_page_index as i64], output_index as i64)?;
            let prefix_present = source
                .page_labels()
                .label_prefix_is_present(source_page_index as i64)?;
            // labels_for_selection always emits one entry for one selected
            // page; keep the defensive branch for malformed number-tree
            // implementations without panicking.
            if let Some(entry) = entries.into_iter().next() {
                label_entries.push((entry.0, entry.1, prefix_present));
            }
        }
    }

    // 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(&mut merge_inputs, &remove_resources)?
    } else {
        merge_documents_with_resource_decisions_and_preserve_primary(
            &mut merge_inputs,
            &remove_resources,
            false,
        )? // 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 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)?;
    }

    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 any_page_labels {
        let folded = merge_job_label_ranges(label_entries);
        merged
            .page_labels()
            .write_reconstructed_labels_with_prefix_presence(&folded)?;
    }

    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`). The
    /// low-level page tree and foreign-object responsibilities remain in
    /// [`crate::job::merge_documents`] and its page helpers. This method
    /// owns:
    ///
    /// - per-spec range resolution and source-index validation;
    /// - qpdf's round-robin `--collate` order across specifications;
    /// - retaining the source documents while copied objects are materialized;
    /// - rebuilding the page tree in the final 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` is qpdf's
    /// `--preserve-unreferenced` writer policy (`QPDFWriter.cc:2907-2913`),
    /// applied to the primary input's own otherwise-unreachable objects.
    /// Both settings live on `QPDFJob`'s member variables in qpdf
    /// (`m->remove_unreferenced_page_resources`,
    /// `m->preserve_unreferenced_objects`); qpdf has exactly one
    /// `handlePageSpecs`, so this stays the single Rust entry point rather
    /// than growing a family of same-named overloads with one more
    /// parameter each.
    pub fn handle_page_specs<'a, R: Read + Seek + 'static>(
        &mut self,
        sources: &'a mut [Pdf<R>],
        specs: &[PageSpecInput],
        collate: Option<&[usize]>,
        resource_mode: RemoveUnreferencedResources,
        preserve_unreferenced: bool,
    ) -> Result<PageSpecJobOutput<'a, R>> {
        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
            let (result, prune_mode) =
                handle_single_source_page_specs(self, source, specs, collate, resource_mode)?;
            return Ok(PageSpecJobOutput::InPlace {
                pdf: source,
                result,
                prune_mode,
            });
        }

        handle_page_specs(
            self,
            sources,
            specs,
            collate,
            resource_mode,
            preserve_unreferenced,
        )
        .map(|merged| PageSpecJobOutput::Merged(Box::new(merged)))
    }
}

#[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, 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 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")
    }

    #[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("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("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_uses_the_non_preserving_merge_decision_route() {
        let primary = three_page_pdf();
        let secondary = inherited_resources_pdf();
        let range = PageRange::parse("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 output = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
                false,
            )
            .expect("multi-source page job");
        assert!(matches!(output, PageSpecJobOutput::Merged(_)));
    }

    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
    }

    /// 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);
        pdf.resolve(&object).expect("resolve object handle");
        object
    }

    fn resolved_key(
        pdf: &mut Pdf<Cursor<Vec<u8>>>,
        owner: &ObjectHandle,
        key: &[u8],
    ) -> ObjectHandle {
        let value = owner.get_key(key);
        pdf.resolve(&value).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 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");
    }

    #[test]
    fn replace_merged_fields_removes_acroform_when_no_fields_survive() {
        let mut merged = acroform_pdf();
        replace_merged_fields(&mut merged, Vec::new(), true)
            .expect("an empty survivor list removes /AcroForm");
        let root_ref = merged.root_ref().expect("root");
        assert!(
            resolved_object(&mut merged, root_ref)
                .get_key(b"/AcroForm")
                .is_null(),
            "qpdf removes /AcroForm entirely once 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();
        merged.mark_object_handle_dirty(&page).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("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.get_key(b"/Resources").as_dictionary().is_some(),
                "qpdf --pages default copies inherited /Resources directly onto the page"
            );
        }
    }

    #[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("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("2").unwrap())];
        let mut job = QPDFJob::new();

        let output = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
                false,
            )
            .expect("single-source page job");
        assert!(matches!(&output, PageSpecJobOutput::InPlace { .. }));
        if let PageSpecJobOutput::InPlace {
            pdf,
            result,
            prune_mode: _,
        } = output
        {
            assert_eq!(result.new_kids.len(), 1);
            assert_eq!(selected_page_count(pdf), 1);
            assert!(pdf
                .repair_diagnostics()
                .entries()
                .iter()
                .all(|entry| !entry.message.contains("foreign object")));
        } // cov:ignore: structural close of the asserted InPlace result branch
    }

    #[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("1").unwrap()),
            PageSpecInput::new(0, PageRange::parse("1").unwrap()),
        ];
        let mut job = QPDFJob::new();

        let output = job
            .handle_page_specs(
                &mut sources,
                &specs,
                None,
                RemoveUnreferencedResources::Auto,
                false,
            )
            .expect("repeated single-source page job");
        assert!(matches!(&output, PageSpecJobOutput::InPlace { .. }));
        if let PageSpecJobOutput::InPlace { pdf, result, .. } = output {
            assert_eq!(result.new_kids.len(), 2);
            assert_eq!(selected_page_count(pdf), 2);
        } // cov:ignore: structural close of the asserted InPlace result branch
    }

    #[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("1").unwrap())],
            Some(&[1, 2]),
        )
        .is_err());
        assert!(select_single_source_pages(
            &mut source,
            &[PageSpecInput::new(1, PageRange::parse("1").unwrap())],
            None,
        )
        .is_err());
        assert!(select_single_source_pages(
            &mut source,
            &[PageSpecInput::new(0, PageRange::parse("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("1-3").unwrap()),
            PageSpecInput::new(0, PageRange::parse("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("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("1").unwrap()),
            PageSpecInput::new(1, PageRange::parse("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(&mut merged, &root, b"/AcroForm");
        assert_eq!(
            resolved_key(&mut merged, &acroform, b"/NeedAppearances").as_boolean(),
            Some(true)
        );
        assert!(
            acroform.get_key(b"/Fields").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("1").unwrap()),
            PageSpecInput::new(1, PageRange::parse("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)
                .get_key(b"/AcroForm")
                .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)
                .get_key(b"/AcroForm")
                .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("1-2").unwrap();
        assert_eq!(PageSpecInput::new(3, range.clone()).source_index, 3);
        assert_eq!(
            PageSpecInput::new(3, range).range,
            PageRange::parse("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("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("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("99").unwrap())];
        assert!(handle_page_specs(
            &mut QPDFJob::new(),
            &mut sources,
            &out_of_range,
            None,
            RemoveUnreferencedResources::Auto,
            false,
        )
        .is_err());

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

    #[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("1").unwrap()),
            PageSpecInput::new(0, PageRange::parse("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("1-2").unwrap()),
            PageSpecInput::new(1, PageRange::parse("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("1-3").unwrap()),
            PageSpecInput::new(1, PageRange::parse("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("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(&mut output, &catalog, b"/PageLabels");
        let nums = resolved_key(&mut output, &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");
        output
            .resolve(&first_label)
            .expect("resolve first reconstructed label");
        assert_eq!(first_label.get_key(b"/P").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);
    }
}