flpdf 0.2.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
//! Overlay/underlay annotation copy, mirroring qpdf 11.9.0's
//! `QPDFPageObjectHelper::copyAnnotations` +
//! `QPDFAcroFormDocumentHelper::transformAnnotations` +
//! `QPDFAcroFormDocumentHelper::addAndRenameFormFields`
//! (`libqpdf/QPDFPageObjectHelper.cc:991-1039`,
//! `libqpdf/QPDFAcroFormDocumentHelper.cc:698-1014`,
//! `libqpdf/QPDFAcroFormDocumentHelper.cc:61-110`).
//!
//! Split into two phases so the cross-document copy runs exactly once per
//! source document (unioned with the Form XObject closure), matching qpdf's
//! per-document `copyForeignObject` foreign→local map:
//!
//! 1. [`survey_source_annotations`] — walk the source page's `/Annots` in
//!    source space and return the reachable-ref closure to add to the batch
//!    [`copy_objects`](crate::object_copy::copy_objects) call, alongside a
//!    survey describing the per-annot top-level field and (when present) the
//!    source `/AcroForm/DR` ref.
//! 2. [`template_from_survey`] — after the batch copy returns its map, remap
//!    the survey's source-space refs into dest-space refs.
//! 3. [`apply_placement`] — per placement, shallow-duplicate each annotation
//!    (and its field-tree top) so that repeated placements of the same source
//!    page do NOT share (transformation would otherwise cumulate), transform
//!    `/Rect` and each `/AP` stream's `/Matrix` by `cm`, reset field `/DR`
//!    references to the dest AcroForm `/DR`, and append the transformed annots
//!    to the destination page `/Annots`. Returns the list of new top-level
//!    field dest refs added by this placement.
//! 4. [`add_and_rename_form_fields`] — once per destination page after all
//!    placements: BFS the collected new top-level fields, rename `/T` on
//!    fully-qualified-name collision with existing dest fields, and append to
//!    `/AcroForm/Fields`.

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

use crate::acroform_document_helper::{collect_reachable_refs, collect_refs_in_object};
use crate::{Error, Object, ObjectRef, Pdf, Result};

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

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

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

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

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

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

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

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

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

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

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

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

/// Per-placement annotation application:
/// - shallow-dup each templated annot (new indirect object) and any
///   associated top-level field / kid path (so repeated placements of the
///   same source page do not share cumulative /Rect transforms);
/// - shallow-dup each `/AP` stream and concatenate `cm` into its `/Matrix`
///   (identity when the stream had no /Matrix);
/// - transform the annot's `/Rect` by `cm`;
/// - if the source top-level field had a `/DR`, replace it with the
///   destination AcroForm `/DR` (lazy-initialized on first placement);
/// - append the dup'd annots to the destination page `/Annots`.
///
/// Returns the newly-added top-level field dest refs (one per distinct top
/// field observed in this placement), to be collected across all placements
/// on the dest page and passed to [`add_and_rename_form_fields`] once at the
/// end.
///
pub(crate) fn apply_placement<R: Read + Seek>(
    dest: &mut Pdf<R>,
    dest_page_ref: ObjectRef,
    template: &AnnotationCopyTemplate,
    cm: [f64; 6],
    dest_acroform_dr: &mut Option<ObjectRef>,
) -> Result<Vec<ObjectRef>> {
    if template.annots.is_empty() {
        return Ok(Vec::new()); // cov:ignore: defensive early return
    }

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

    // If ANY annot in this placement carries a top-level field and the source
    // supplied a /DR, ensure the destination /AcroForm/DR exists. This is
    // lazy: fxo-red (the primary target) has no /AcroForm, so `dest_acroform_dr`
    // is None on the first placement and is filled here.
    let has_any_top_field = template.annots.iter().any(|(_, tf)| tf.is_some());
    if has_any_top_field && dest_acroform_dr.is_none() {
        if let Some(source_dr) = template.source_dr {
            *dest_acroform_dr = Some(ensure_dest_acroform_dr(dest, source_dr)?);
        } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
    }

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

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

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

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

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

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

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

        new_annot_refs.push(new_annot_ref);
    }

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

    Ok(new_top_fields)
}

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

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

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

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

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

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

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

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

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

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

    Ok(new_top)
}

/// Duplicate each `/AP` appearance stream referenced from the annot at
/// `annot_ref`, concatenate `cm` into the stream's `/Matrix` (qpdf
/// transformAnnotations line 992-1010), and rewrite the annot's `/AP` entries
/// to point at the dup'd streams. Only walked at `/AP/{N,R,D}` and one nested
/// dictionary level, matching qpdf's `apdict` traversal.
fn transform_annot_ap_streams<R: Read + Seek>(
    dest: &mut Pdf<R>,
    annot_ref: ObjectRef,
    cm: [f64; 6],
) -> Result<()> {
    let Some(mut annot_dict) = dest.resolve(annot_ref)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let Some(ap_val) = annot_dict.get("AP").cloned() else {
        return Ok(());
    };
    let Some(mut apdict) = (match ap_val {
        Object::Dictionary(d) => Some(d),
        Object::Reference(r) => dest.resolve(r)?.into_dict(), // cov:ignore: function signature — llvm-cov instrumentation artifact
        _ => None, // cov:ignore: fallback match arm — defensive/malformed input
    }) else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let ap_keys: Vec<Vec<u8>> = apdict.iter().map(|(k, _)| k.to_vec()).collect();
    for key in ap_keys {
        let val = apdict.get(&key).cloned();
        let Some(val) = val else { continue };
        match val {
            Object::Reference(stream_ref) => {
                if let Some(new_ref) = dup_and_transform_ap_stream(dest, stream_ref, cm)? {
                    apdict.insert(&key, Object::Reference(new_ref));
                }
            }
            Object::Dictionary(sub) => {
                // Nested per-state dict (e.g. /N << /1 stream_ref /Off stream_ref >>).
                let mut sub = sub;
                let sub_keys: Vec<Vec<u8>> = sub.iter().map(|(k, _)| k.to_vec()).collect();
                for sub_key in sub_keys {
                    let Some(sub_val) = sub.get(&sub_key).cloned() else {
                        continue; // cov:ignore: key vanished mid-iteration — impossible with BTreeMap
                    };
                    if let Object::Reference(stream_ref) = sub_val {
                        if let Some(new_ref) = dup_and_transform_ap_stream(dest, stream_ref, cm)? {
                            sub.insert(&sub_key, Object::Reference(new_ref));
                        }
                    } // cov:ignore: control-flow marker — llvm-cov instrumentation artifact
                }
                apdict.insert(&key, Object::Dictionary(sub));
            }
            _ => {} // cov:ignore: fallback match arm — defensive/malformed input
        }
    }
    annot_dict.insert("AP", Object::Dictionary(apdict));
    dest.set_object(annot_ref, Object::Dictionary(annot_dict));
    Ok(())
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Merge `source_dr`'s resource entries into the (existing, initially-empty)
/// dict at `dest_dr`. Mirrors qpdf's `QPDFObjectHandle::mergeResources` for
/// the "dest starts empty" path (the only path exercised by the primary
/// target fxo-red, which has no /AcroForm).
///
/// For each top-level key (resource type: /Font, /XObject, /ColorSpace, ...),
/// the source's sub-dictionary is copied into a NEW direct dict in dest so
/// dest_dr and source_dr do not share mutable sub-dict state. Individual
/// resource entries (e.g. `/F1 8 0 R`) are shallow-cloned — they are typically
/// refs, so the clone is cheap and the dest and source paths continue to
/// share the underlying font/xobject objects (as qpdf does).
///
/// Conflict handling (dest already has a key with a different ref) is NOT
/// implemented — that's the `dr_map` path that would drive
/// `adjustAppearanceStream`. Dormant for the primary target; extend when a
/// fixture requires it.
fn merge_resources_shallow<R: Read + Seek>(
    dest: &mut Pdf<R>,
    dest_dr: ObjectRef,
    source_dr: ObjectRef,
) -> Result<()> {
    let Some(src_dict) = dest.resolve(source_dr)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    let Some(mut dest_dict) = dest.resolve(dest_dr)?.into_dict() else {
        return Ok(()); // cov:ignore: defensive early return
    };
    for (type_key, src_type_val) in src_dict.iter() {
        // Resource-type entry (e.g. /Font) is expected to be a direct
        // sub-dict, matching the primary target and every qpdf golden we
        // currently oracle. PDF also permits `/Font <ref>` (indirect
        // sub-dict), but replicating qpdf's mergeResources semantics for
        // that shape needs an oracle golden that no shipped fixture
        // supplies — deferred to flpdf-4r6l, which lands alongside
        // dr_map + adjustAppearanceStream once a real fixture exercises
        // the merge-conflict path. Until then, non-dict resource-type
        // values are copied verbatim (works correctly for the empty-dest
        // /DR case that fxo-red exercises).
        let Some(src_type_dict) = src_type_val.as_dict() else {
            dest_dict.insert(type_key, src_type_val.clone()); // cov:ignore: verbatim-copy for non-dict resource-type — deferred to flpdf-4r6l
            continue; // cov:ignore: verbatim-copy for non-dict resource-type — deferred to flpdf-4r6l
        };
        // Copy each resource entry into a fresh direct sub-dict so dest_dr's
        // sub-dict is independent of source_dr's sub-dict.
        let mut new_type_dict = crate::Dictionary::new();
        for (name, val) in src_type_dict.iter() {
            new_type_dict.insert(name, val.clone());
        }
        dest_dict.insert(type_key, Object::Dictionary(new_type_dict));
    }
    dest.set_object(dest_dr, Object::Dictionary(dest_dict));
    Ok(())
}

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

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

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

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

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

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

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

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

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