flpdf 0.10.0

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

use crate::nntree::NameTree;
use crate::{Error, ObjectHandle, ObjectRef, Pdf, Result};
use std::collections::BTreeMap;
use std::io::{Read, Seek};

/// High-level helper for a document's `/Names /EmbeddedFiles` name tree.
///
/// Construct with [`EmbeddedFileDocumentHelper::new`] or
/// [`Pdf::embedded_files`]. The helper does not cache name-tree state; each
/// method observes the document's current object graph.
pub struct EmbeddedFileDocumentHelper<'a, R: Read + Seek + 'static> {
    pdf: &'a mut Pdf<R>,
}

fn embedded_files_tree_with_options<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    auto_repair: bool,
    max_depth: Option<usize>,
) -> Result<Option<NameTree>> {
    // qpdf's EmbeddedFileDocumentHelper constructor calls QPDF::getRoot,
    // whose dictionary gate accepts both direct and indirect /Root values.
    let catalog = pdf.root_handle()?;

    // Keep qpdf's getKey -> terminal-resolution order here. The public
    // has_key facade must resolve the child to test nullness, which would
    // move name-tree repair diagnostics before the tree walker sees the
    // malformed child.
    let names_seed = catalog.try_get_key(b"/Names")?;
    names_seed.try_dereference()?;
    let names = names_seed;
    if !names.try_is_dictionary()? {
        return Ok(None);
    }
    let root_seed = names.try_get_key(b"/EmbeddedFiles")?;
    root_seed.try_dereference()?;
    let root = root_seed;
    if !root.try_is_dictionary()? {
        return Ok(None);
    }

    let mut tree = NameTree::new(root, auto_repair);
    if let Some(max_depth) = max_depth {
        tree.set_max_depth(max_depth);
    }
    Ok(Some(tree))
}

impl<'a, R: Read + Seek> EmbeddedFileDocumentHelper<'a, R> {
    /// Create an embedded-files helper borrowing `pdf` mutably.
    pub fn new(pdf: &'a mut Pdf<R>) -> Self {
        Self { pdf }
    }

    fn embedded_files_tree(&mut self) -> Result<Option<NameTree>> {
        embedded_files_tree_with_options(self.pdf, true, None)
    }

    fn ensure_embedded_files_tree(&mut self) -> Result<Option<NameTree>> {
        if let Some(tree) = self.embedded_files_tree()? {
            return Ok(Some(tree));
        }

        // This is qpdf's initEmbeddedFiles -> QPDF::getRoot boundary, so a
        // direct catalog is valid and missing/non-dictionary roots propagate
        // the document-level root error.
        let catalog = self.pdf.root_handle()?;

        let names = if catalog.try_has_key(b"/Names")? {
            let candidate = catalog.try_get_key(b"/Names")?;
            candidate.try_dereference()?;
            let names = candidate;
            if names.try_is_dictionary()? {
                names
            } else {
                let names = ObjectHandle::dictionary(Vec::new());
                catalog.replace_key(b"/Names", names.clone())?;
                names
            }
        } else {
            let names = ObjectHandle::dictionary(Vec::new());
            catalog.replace_key(b"/Names", names.clone())?;
            names
        };

        let root = self.new_empty_embedded_files_root(&names)?;

        Ok(Some(NameTree::new(root, true)))
    }

    fn new_empty_embedded_files_root(&mut self, names: &ObjectHandle) -> Result<ObjectHandle> {
        let root = self
            .pdf
            .make_indirect_from_object_handle(ObjectHandle::dictionary(vec![(
                b"/Names".to_vec(),
                ObjectHandle::array(Vec::new()),
            )]))?;
        names.replace_key(b"/EmbeddedFiles", root.clone())?;
        Ok(root)
    }

    /// Return whether this document has an `/EmbeddedFiles` name tree.
    pub fn has_embedded_files(&mut self) -> Result<bool> {
        Ok(self.embedded_files_tree()?.is_some())
    }

    /// Return every embedded-files entry in key order.
    ///
    /// The values are qpdf-shaped Filespec object handles. Indirect values use
    /// the canonical handle of this document; direct Filespec dictionaries are
    /// returned as direct handles.
    pub fn get_embedded_files(&mut self) -> Result<BTreeMap<Vec<u8>, ObjectHandle>> {
        let Some(mut tree) = self.embedded_files_tree()? else {
            return Ok(BTreeMap::new());
        };
        tree.as_map(self.pdf)
    }

    /// Return the Filespec handle stored under `key`, if present.
    pub fn get_embedded_file(&mut self, key: &[u8]) -> Result<Option<ObjectHandle>> {
        let Some(mut tree) = self.embedded_files_tree()? else {
            return Ok(None);
        };
        tree.find_object(self.pdf, key)
    }

    /// Add or replace the Filespec stored under `key`.
    ///
    /// An indirect handle must be the canonical handle of this document;
    /// direct handles are stored directly in the name tree.
    pub fn replace_embedded_file(&mut self, key: &[u8], filespec: ObjectHandle) -> Result<()> {
        if let Some(object_ref) = filespec.object_ref() {
            if !self.pdf.is_canonical_object_handle(&filespec) {
                return Err(Error::Unsupported(
                    "filespec handle belongs to another Pdf".to_string(),
                ));
            }
            debug_assert_eq!(filespec.object_ref(), Some(object_ref));
        } else if !filespec.belongs_to_pdf(self.pdf.unique_id()) {
            return Err(Error::Unsupported(
                "filespec handle belongs to another Pdf".to_string(),
            ));
        }

        let Some(mut tree) = self.ensure_embedded_files_tree()? else {
            return Ok(());
        };
        tree.insert(self.pdf, key, filespec).map(|_| ())
    }

    /// Remove the Filespec stored under `key`.
    ///
    /// Returns `false` if the embedded-files tree or the named entry is
    /// absent. An indirect Filespec is replaced with `null`, matching qpdf's
    /// `removeEmbeddedFile`; direct Filespec values have no object slot to
    /// replace. This method intentionally does not perform `/AF` cleanup or
    /// reachability-based garbage collection.
    pub fn remove_embedded_file(&mut self, key: &[u8]) -> Result<bool> {
        let Some(mut tree) = self.embedded_files_tree()? else {
            return Ok(false);
        };
        let Some(removed) = tree.remove(self.pdf, key)? else {
            return Ok(false);
        };
        if let Some(object_ref) = removed.object_ref() {
            // qpdf's removeEmbeddedFile keeps the xref slot as a null object
            // (`QPDFEmbeddedFileDocumentHelper.cc:115-119`). The writer then
            // decides whether the detached Filespec and its streams are
            // emitted: ordinary rewrites garbage-collect them, while
            // preserve-unreferenced retains them.
            self.pdf.replace_object(object_ref, ObjectHandle::null())?;
        }
        Ok(true)
    }
}

impl<R: Read + Seek> Pdf<R> {
    /// Return a high-level embedded-files helper for this document.
    pub fn embedded_files(&mut self) -> EmbeddedFileDocumentHelper<'_, R> {
        EmbeddedFileDocumentHelper::new(self)
    }
}

// ── remove_attachment ─────────────────────────────────────────────────────────

/// Remove an attachment by name-tree key.
///
/// # Behaviour
///
/// 1. Looks up `key` in the catalog's `/Names /EmbeddedFiles` name tree.
///    Returns `Ok(false)` — without error — if the key is absent.
/// 2. Calls [`EmbeddedFileDocumentHelper::remove_embedded_file`], which
///    removes the name-tree entry and **unconditionally** replaces an
///    indirect Filespec with null, matching qpdf's `removeEmbeddedFile`
///    contract — regardless of any other live reference to that same object
///    (an `/AF` entry, a `/Dests` / `/JavaScript` name tree, another
///    Filespec). Associated-files (`/AF`) arrays are not modified, so an
///    `/AF` entry that pointed at the removed Filespec now points at null.
/// 3. Leaves document-wide reachability to the later writer. Ordinary rewrites
///    omit the detached Filespec and its `/EF` streams because they are no
///    longer reachable, while `preserve_unreferenced` can retain the null slot
///    and other unreferenced objects as qpdf does.
///
/// The conservative-share semantics only protect content that was never
/// routed through the removed Filespec in the first place: an `/EmbeddedFile`
/// stream shared by a *different*, still-live Filespec object stays
/// reachable through that other Filespec and survives. A `/Dests` /
/// `/JavaScript` name tree entry that points at the *same* Filespec object
/// being removed does **not** preserve it — step 2 nulls that object
/// unconditionally, so the other name tree ends up pointing at null too.
///
/// The wrapper itself does not delete any pre-existing unreachable object.
/// The later writer determines the document-wide output set, including whether
/// `preserve_unreferenced` retains such objects.
///
/// # Limitation
///
/// When the name-tree value is a *direct* `/Filespec` dictionary (not an
/// indirect reference), qpdf has no object slot to replace; the name-tree
/// entry is removed; the later writer decides which indirect objects to emit.
///
/// # Errors
///
/// Propagates any error from the canonical embedded-files helper.
pub fn remove_attachment<R: Read + Seek>(pdf: &mut Pdf<R>, key: &[u8]) -> Result<bool> {
    let removed = pdf.embedded_files().remove_embedded_file(key)?;
    if !removed {
        return Ok(false);
    }

    Ok(true)
}

// ── helpers for remove_attachment ─────────────────────────────────────────────

/// Walk a `/Filespec` dict and return the first `/EmbeddedFile` stream `ObjectRef`
/// reachable via `/EF /UF`, `/EF /F`, `/EF /Unix`, `/EF /Mac`, `/EF /DOS` (in
/// that priority order).  Returns `None` if not found or on any soft error.
///
/// Test-only helper for single-stream fixtures.
#[cfg(test)]
fn embedded_file_stream_ref<R: Read + Seek + 'static>(
    pdf: &mut Pdf<R>,
    filespec_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
    let candidate = {
        let filespec = pdf.get_object_handle(filespec_ref);
        let mut filespec = crate::filespec_helper::FileSpec::new(filespec, pdf)?;
        filespec.get_embedded_file_stream("")?
    };
    Ok(candidate.object_ref())
}

// ── Writer constants ──────────────────────────────────────────────────────────

/// Legacy maximum depth for callers that explicitly select bounded traversal.
///
/// qpdf's embedded-files helper does not use a numeric depth cap; its normal
/// read, replace, and remove paths rely on the name-tree walker's cycle
/// detection instead.
pub const DEFAULT_MAX_EMBEDDED_FILES_DEPTH: usize = 100;

/// Enumerate all `(name_key, filespec_ref)` entries in the catalog's
/// `/Names /EmbeddedFiles` name tree.
///
/// Returns entries in depth-first, key-ascending order (the order they appear
/// in the tree, which the spec requires to be sorted).  An empty list is
/// returned — without error — when `/Names` or `/EmbeddedFiles` is absent
/// from a valid catalog. A missing or non-dictionary `/Root` returns qpdf's
/// document-level `unable to find /Root dictionary` error.
///
/// **Semantics:** name-tree values that are *direct* `/Filespec` dictionaries
/// (rather than indirect references) are intentionally **skipped** — this
/// reader only surfaces `(key, ObjectRef)` pairs. Mutation and copying use the
/// handle-valued [`EmbeddedFileDocumentHelper::get_embedded_files`] projection,
/// which preserves direct-dict values.
//
///
/// List every embedded file referenced by an indirect `/Filespec` entry,
/// returning each entry's name and the [`ObjectRef`] of its file-specification
/// dictionary. Name-tree entries whose value is a *direct* `/Filespec`
/// dictionary (rather than an indirect reference) are intentionally skipped.
///
/// # Errors
///
/// Propagates any error from canonical ObjectHandle resolution, and returns
/// [`crate::Error::Unsupported`] for an explicit bounded-traversal limit.
pub fn list_embedded_files<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Vec<(Vec<u8>, ObjectRef)>> {
    list_embedded_files_with_max_depth(pdf, DEFAULT_MAX_EMBEDDED_FILES_DEPTH)
}

/// Like [`list_embedded_files`] but with a caller-supplied depth limit.
///
/// The depth limit guards against maliciously or accidentally cyclic `/Kids`
/// references.  Exceeding the limit returns an error rather than panicking.
///
/// # Errors
///
/// Propagates any error from canonical ObjectHandle resolution, and returns
/// [`crate::Error::Unsupported`] if a `/Kids` chain depth reaches `max_depth`.
pub fn list_embedded_files_with_max_depth<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    max_depth: usize,
) -> Result<Vec<(Vec<u8>, ObjectRef)>> {
    let Some(mut tree) = embedded_files_tree_with_options(pdf, true, Some(max_depth))? else {
        return Ok(vec![]);
    };
    Ok(tree
        .as_map(pdf)?
        .into_iter()
        .filter_map(|(key, value)| {
            value
                .object_ref()
                .or_else(|| value.object_ref())
                .map(|object_ref| (key, object_ref))
        })
        .collect())
}

// ── Writer ────────────────────────────────────────────────────────────────────

/// Insert or replace a `(key, filespec_ref)` entry in the catalog's
/// `/Names /EmbeddedFiles` name tree.
///
/// If `key` already exists its value is replaced with `filespec_ref`.
/// If the `/Names /EmbeddedFiles` path does not yet exist it is created.
///
/// The existing tree is mutated in place; an existing root reference is
/// retained.
///
/// # Errors
///
/// Propagates any error from canonical ObjectHandle resolution.
pub fn insert_embedded_file<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    key: &[u8],
    filespec_ref: ObjectRef,
) -> Result<()> {
    let filespec = pdf.get_object_handle(filespec_ref);
    pdf.embedded_files().replace_embedded_file(key, filespec)
}

/// Remove the entry with `key` from the catalog's `/Names /EmbeddedFiles`
/// name tree.
///
/// Returns `true` if the key was found and removed, `false` if it was absent.
///
/// When the last entry is removed, `/EmbeddedFiles` remains as an empty name
/// tree, as it does in qpdf.
///
/// # Errors
///
/// Propagates any error from the canonical embedded-files helper.
pub fn delete_embedded_file<R: Read + Seek>(pdf: &mut Pdf<R>, key: &[u8]) -> Result<bool> {
    pdf.embedded_files().remove_embedded_file(key)
}

// ── Tests for remove_attachment ───────────────────────────────────────────────

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use super::*;
    use crate::filespec_helper::FileSpecBuilder;
    use crate::job::add_attachment_from_path;

    // ── Minimal PDF fixture (same as filespec_helper tests) ───────────────────

    fn minimal_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    fn open_minimal() -> Pdf<std::io::Cursor<Vec<u8>>> {
        Pdf::open(std::io::Cursor::new(minimal_pdf_bytes())).expect("open minimal PDF")
    }

    fn next_object_number(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> u32 {
        pdf.next_obj_gen()
            .expect("object-number space must have room in the test fixture")
            .number
            .checked_sub(1)
            .expect("minimal test fixture has object 1 as its first object")
    }

    fn handle_array(items: Vec<ObjectHandle>) -> ObjectHandle {
        ObjectHandle::array(items)
    }

    fn handle_dictionary(entries: Vec<(&[u8], ObjectHandle)>) -> ObjectHandle {
        ObjectHandle::dictionary(
            entries
                .into_iter()
                .map(|(key, value)| (key.to_vec(), value))
                .collect(),
        )
    }

    fn set_test_object(
        pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>,
        object_ref: ObjectRef,
        value: ObjectHandle,
    ) -> ObjectHandle {
        pdf.replace_object(object_ref, value)
            .expect("set canonical test object");
        pdf.get_object_handle(object_ref)
    }

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

    fn catalog_handle(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> ObjectHandle {
        let catalog_ref = pdf.root_ref().expect("root");
        resolved_handle(pdf, catalog_ref)
    }

    fn rewritten(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> Pdf<std::io::Cursor<Vec<u8>>> {
        let bytes = crate::writer::write_qpdf_to_memory(pdf, |_| {}).expect("rewrite PDF");
        Pdf::open(std::io::Cursor::new(bytes)).expect("reopen rewritten PDF")
    }

    fn count_streams(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> usize {
        let objects = pdf.get_all_objects().expect("enumerate rewritten objects");
        objects
            .into_iter()
            .filter(|object| {
                object.try_is_scalar().expect("resolve rewritten object");
                object.as_stream_dict().is_some()
            })
            .count()
    }

    fn count_embedded_file_streams(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> usize {
        let objects = pdf.get_all_objects().expect("enumerate rewritten objects");
        objects
            .into_iter()
            .filter(|object| {
                object.try_is_scalar().expect("resolve rewritten object");
                let Some(dict) = object.as_stream_dict() else {
                    return false;
                };
                let kind = dict.try_get_key(b"/Type").unwrap();
                kind.try_is_scalar().expect("resolve embedded stream type");
                kind.as_name().as_deref() == Some(b"EmbeddedFile")
            })
            .count()
    }

    fn replace_catalog_key(
        pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>,
        key: &[u8],
        value: ObjectHandle,
    ) {
        let catalog = catalog_handle(pdf);
        catalog
            .replace_key(key, value)
            .expect("replace catalog key");
    }

    fn indirect_names_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Names 4 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"4 0 obj\n<< /EmbeddedFiles << /Names [ (entry) 5 0 R ] >> >>\nendobj\n",
        );
        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /Type /Filespec /F (entry.txt) >>\nendobj\n");
        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 6\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3, off4, off5,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    // ── Test: add 2, remove 1, check list has 1 ──────────────────────────────

    #[test]
    fn remove_one_of_two_leaves_other_intact() {
        let mut pdf = open_minimal();
        let dir = tempfile::tempdir().expect("tempdir");

        let file_a = dir.path().join("a.txt");
        let file_b = dir.path().join("b.txt");
        std::fs::write(&file_a, b"content A").unwrap();
        std::fs::write(&file_b, b"content B").unwrap();

        add_attachment_from_path(&mut pdf, b"a.txt", &file_a).expect("add a");
        let fs_b = add_attachment_from_path(&mut pdf, b"b.txt", &file_b).expect("add b");

        let removed = remove_attachment(&mut pdf, b"a.txt").expect("remove a");
        assert!(
            removed,
            "remove_attachment must return true for existing key"
        );

        let entries = list_embedded_files(&mut pdf).expect("list");
        assert_eq!(entries.len(), 1, "exactly one attachment must remain");
        assert_eq!(entries[0].0, b"b.txt", "b.txt must survive");
        assert_eq!(entries[0].1, fs_b, "surviving filespec ref must match");

        // Deleted key must not appear
        let keys: Vec<&[u8]> = entries.iter().map(|(k, _)| k.as_slice()).collect();
        assert!(!keys.contains(&b"a.txt".as_ref()), "a.txt must be gone");
    }

    #[test]
    fn helper_reads_preserve_an_unchanged_indirect_names_dictionary() {
        let mut pdf = Pdf::open(std::io::Cursor::new(indirect_names_pdf_bytes())).expect("open");

        assert_eq!(
            pdf.embedded_files()
                .get_embedded_files()
                .expect("list")
                .len(),
            1
        );

        assert!(pdf
            .embedded_files()
            .get_embedded_file(b"entry")
            .expect("lookup")
            .is_some());
    }

    #[test]
    fn helper_absent_removal_preserves_an_unchanged_indirect_names_dictionary() {
        let mut pdf = Pdf::open(std::io::Cursor::new(indirect_names_pdf_bytes())).expect("open");

        assert!(!pdf
            .embedded_files()
            .remove_embedded_file(b"missing")
            .expect("absent removal"));
    }

    #[test]
    fn legacy_insert_updates_retained_embedded_files_root() {
        let mut pdf = Pdf::open(std::io::Cursor::new(indirect_names_pdf_bytes())).expect("open");
        let catalog_ref = pdf.root_ref().expect("root");
        let catalog = pdf.get_object_handle(catalog_ref);
        catalog.try_is_scalar().expect("resolve catalog");
        let retained_root = catalog
            .try_get_key(b"/Names")
            .unwrap()
            .try_get_key(b"/EmbeddedFiles")
            .unwrap();
        retained_root
            .try_is_scalar()
            .expect("resolve embedded-files root");

        let filespec_ref = ObjectRef::new(90, 0);
        set_test_object(&mut pdf, filespec_ref, handle_dictionary(Vec::new()));
        insert_embedded_file(&mut pdf, b"new.txt", filespec_ref).expect("insert");

        let pairs = retained_root
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("retained names array");
        assert_eq!(pairs.len(), 4, "the retained root must observe insertion");
        assert_eq!(pairs[2].as_string(), Some(b"new.txt".to_vec()));
    }

    #[test]
    fn remove_attachment_preserves_retained_af_array_handle_and_nulls_filespec() {
        let mut pdf = open_minimal();
        let filespec_ref = FileSpecBuilder::new("retained-af.txt", b"payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"retained-af.txt", filespec_ref).expect("insert");

        let af_ref = ObjectRef::new(next_object_number(&mut pdf) + 1, 0);
        let filespec_handle = pdf.get_object_handle(filespec_ref);
        set_test_object(&mut pdf, af_ref, handle_array(vec![filespec_handle]));
        let af_handle = pdf.get_object_handle(af_ref);
        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/AF", af_handle.clone())
            .expect("replace catalog /AF");
        let page_ref = crate::pages::page_refs(&mut pdf)
            .expect("page refs")
            .into_iter()
            .next()
            .expect("page");
        let page = resolved_handle(&mut pdf, page_ref);
        page.replace_key(b"/AF", af_handle)
            .expect("replace page /AF");

        let retained_af = pdf.get_object_handle(af_ref);
        retained_af.try_is_scalar().expect("resolve AF array");

        assert!(
            remove_attachment(&mut pdf, b"retained-af.txt").expect("remove"),
            "attachment must be found"
        );

        assert_eq!(
            retained_af.as_array().expect("retained AF array").len(),
            1,
            "qpdf keeps the retained AF array element"
        );
        assert!(
            resolved_handle(&mut pdf, filespec_ref).is_null(),
            "qpdf replaces the removed Filespec with null"
        );
    }

    #[test]
    fn helper_mutates_a_retained_direct_embedded_files_root() {
        let mut pdf = open_minimal();
        let root = handle_dictionary(vec![(b"/Names", handle_array(Vec::new()))]);
        let names = handle_dictionary(vec![(b"/EmbeddedFiles", root)]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        let catalog_handle = catalog_handle(&mut pdf);
        let retained_root = catalog_handle
            .try_get_key(b"/Names")
            .unwrap()
            .try_get_key(b"/EmbeddedFiles")
            .unwrap();
        let retained_pairs = retained_root.try_get_key(b"/Names").unwrap();

        let filespec_ref = ObjectRef::new(90, 0);
        set_test_object(&mut pdf, filespec_ref, handle_dictionary(Vec::new()));
        let filespec = pdf.get_object_handle(filespec_ref);
        pdf.embedded_files()
            .replace_embedded_file(b"entry", filespec)
            .expect("replace");

        assert!(
            retained_root
                .try_get_key(b"/Names")
                .unwrap()
                .as_array()
                .is_some_and(|pairs| pairs.len() == 2),
            "a retained direct root must observe helper replacement"
        );
        assert_eq!(
            retained_pairs
                .as_array()
                .expect("retained names array")
                .len(),
            2,
            "a retained direct leaf array must observe helper replacement"
        );

        assert!(pdf
            .embedded_files()
            .remove_embedded_file(b"entry")
            .expect("remove"));
        assert_eq!(
            retained_root
                .try_get_key(b"/Names")
                .unwrap()
                .as_array()
                .expect("names array")
                .len(),
            0,
            "a retained direct root must observe helper removal"
        );
        assert_eq!(
            retained_pairs
                .as_array()
                .expect("retained names array")
                .len(),
            0,
            "a retained direct leaf array must observe helper removal"
        );
        assert!(pdf.embedded_files().has_embedded_files().expect("has tree"));
        assert!(!pdf
            .embedded_files()
            .remove_embedded_file(b"missing")
            .expect("missing removal"));
    }

    #[test]
    fn helper_mutates_an_indirect_root_without_detaching_direct_filespec_handle() {
        let mut pdf = open_minimal();
        let root_ref = ObjectRef::new(90, 0);
        let added_ref = ObjectRef::new(91, 0);

        let existing_filespec =
            handle_dictionary(vec![(b"/F", ObjectHandle::string(b"old.txt".to_vec()))]);
        let root = handle_dictionary(vec![(
            b"/Names",
            handle_array(vec![ObjectHandle::string(b"a".to_vec()), existing_filespec]),
        )]);
        let root_handle = set_test_object(&mut pdf, root_ref, root);
        set_test_object(&mut pdf, added_ref, handle_dictionary(Vec::new()));
        let names = handle_dictionary(vec![(b"/EmbeddedFiles", root_handle)]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        let catalog_handle = catalog_handle(&mut pdf);
        let retained_root = catalog_handle
            .try_get_key(b"/Names")
            .unwrap()
            .try_get_key(b"/EmbeddedFiles")
            .unwrap();
        retained_root
            .try_is_scalar()
            .expect("resolve embedded-files root");
        let retained_filespec = retained_root
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("names array")[1]
            .clone();

        let added = pdf.get_object_handle(added_ref);
        pdf.embedded_files()
            .replace_embedded_file(b"b", added)
            .expect("replace");

        pdf.embedded_files()
            .replace_embedded_file(b"c", retained_filespec.clone())
            .expect("insert direct filespec");
        let inserted_direct = pdf
            .embedded_files()
            .get_embedded_file(b"c")
            .expect("lookup direct filespec")
            .expect("direct filespec");
        assert!(
            inserted_direct.is_same_object_as(&retained_filespec),
            "qpdf stores the direct Filespec handle itself in the name tree"
        );

        assert!(pdf
            .embedded_files()
            .remove_embedded_file(b"b")
            .expect("remove indirect filespec"));

        retained_filespec
            .replace_key(b"/F", ObjectHandle::string(b"new.txt".to_vec()))
            .unwrap();
        let current_filespec = retained_root
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("updated names array")[1]
            .clone();
        assert_eq!(
            current_filespec.try_get_key(b"/F").unwrap().as_string(),
            Some(b"new.txt".to_vec())
        );
    }

    #[test]
    fn helper_mutates_a_retained_direct_kids_root() {
        let mut pdf = open_minimal();
        let leaf = handle_dictionary(vec![
            (
                b"/Names",
                handle_array(vec![
                    ObjectHandle::string(b"a".to_vec()),
                    ObjectHandle::integer(1),
                ]),
            ),
            (
                b"/Limits",
                handle_array(vec![
                    ObjectHandle::string(b"a".to_vec()),
                    ObjectHandle::string(b"a".to_vec()),
                ]),
            ),
        ]);
        let root = handle_dictionary(vec![(b"/Kids", handle_array(vec![leaf]))]);
        let names = handle_dictionary(vec![(b"/EmbeddedFiles", root)]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        let catalog_handle = catalog_handle(&mut pdf);
        let retained_root = catalog_handle
            .try_get_key(b"/Names")
            .unwrap()
            .try_get_key(b"/EmbeddedFiles")
            .unwrap();

        let filespec_ref = ObjectRef::new(90, 0);
        set_test_object(&mut pdf, filespec_ref, handle_dictionary(Vec::new()));
        let filespec = pdf.get_object_handle(filespec_ref);
        pdf.embedded_files()
            .replace_embedded_file(b"b", filespec)
            .expect("replace");

        assert!(
            retained_root
                .try_get_key(b"/Kids")
                .unwrap()
                .as_array()
                .and_then(|kids| kids.first().cloned())
                .is_some_and(|kid| kid.is_indirect()),
            "a retained direct /Kids root must observe direct-kid repair"
        );
    }

    #[test]
    fn helper_preserves_an_untouched_direct_filespec_handle_during_root_update() {
        let mut pdf = open_minimal();
        let filespec = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"Filespec".to_vec())),
            (b"/F", ObjectHandle::string(b"old.txt".to_vec())),
        ]);
        let root = handle_dictionary(vec![(
            b"/Names",
            handle_array(vec![ObjectHandle::string(b"a".to_vec()), filespec]),
        )]);
        let names = handle_dictionary(vec![(b"/EmbeddedFiles", root)]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        let catalog_handle = catalog_handle(&mut pdf);
        let retained_root = catalog_handle
            .try_get_key(b"/Names")
            .unwrap()
            .try_get_key(b"/EmbeddedFiles")
            .unwrap();
        let retained_filespec = retained_root
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("names array")[1]
            .clone();

        let added_ref = ObjectRef::new(90, 0);
        set_test_object(&mut pdf, added_ref, handle_dictionary(Vec::new()));
        let added = pdf.get_object_handle(added_ref);
        pdf.embedded_files()
            .replace_embedded_file(b"b", added)
            .expect("replace");

        retained_filespec
            .replace_key(b"/F", ObjectHandle::string(b"new.txt".to_vec()))
            .unwrap();
        let current_filespec = retained_root
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("updated names array")[1]
            .clone();
        assert_eq!(
            current_filespec.try_get_key(b"/F").unwrap().as_string(),
            Some(b"new.txt".to_vec())
        );
    }

    // ── Test: transitively-unreachable subgraph is swept by the writer ─────
    //
    // An object reachable *only* through the filespec dictionary (e.g. an
    // indirect `/CI` collection-item stream) is not deleted by this mutation;
    // the qpdf rewrite model drops the now-unreachable subgraph at the writer
    // boundary.
    #[test]
    fn remove_attachment_sweeps_transitively_unreachable_subgraph() {
        let mut pdf = open_minimal();

        // A side-car stream that will be reachable ONLY via the filespec dict.
        let next = next_object_number(&mut pdf);
        let sidecar_ref = ObjectRef::new(next + 1, 0);
        let sidecar = ObjectHandle::stream(
            ObjectHandle::dictionary(Vec::new()),
            std::rc::Rc::new(b"sidecar".to_vec()),
        );
        set_test_object(&mut pdf, sidecar_ref, sidecar);

        // Build a filespec, then point an indirect key at the side-car so the
        // side-car is reachable exclusively through the filespec.
        let fs_ref = FileSpecBuilder::new("trans.txt", b"payload")
            .build(&mut pdf)
            .expect("build filespec");
        let filespec = resolved_handle(&mut pdf, fs_ref);
        filespec
            .replace_key(b"/CI", pdf.get_object_handle(sidecar_ref))
            .expect("add side-car reference");
        insert_embedded_file(&mut pdf, b"trans.txt", fs_ref).expect("insert");

        remove_attachment(&mut pdf, b"trans.txt").expect("remove");

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_ref),
            "filespec remains in memory until the writer runs"
        );
        assert!(
            live.contains(&sidecar_ref),
            "side-car remains in memory until the writer runs"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(
            count_streams(&mut written),
            0,
            "writer must drop the stream reachable only through the removed filespec"
        );
    }

    #[test]
    fn embedded_file_stream_ref_accepts_indirect_ef_dict() {
        let mut pdf = open_minimal();
        let fs_ref = FileSpecBuilder::new("indirect-ef.txt", b"payload")
            .build(&mut pdf)
            .expect("build filespec");
        let filespec = resolved_handle(&mut pdf, fs_ref);
        let ef_dict = filespec
            .try_get_key(b"/EF")
            .unwrap()
            .as_dictionary()
            .expect("/EF dict");
        let ef_ref = ObjectRef::new(fs_ref.number + 100, 0);
        let ef_handle = ObjectHandle::dictionary(ef_dict.into_iter().collect());
        set_test_object(&mut pdf, ef_ref, ef_handle);
        filespec
            .replace_key(b"/EF", pdf.get_object_handle(ef_ref))
            .expect("replace /EF with indirect dictionary");

        let stream_ref = embedded_file_stream_ref(&mut pdf, fs_ref)
            .expect("resolve stream")
            .expect("stream ref");

        assert!(pdf.canonical_object_refs().contains(&stream_ref));
    }

    // ── Test: removed filespec and stream are dropped by the writer ──────────

    #[test]
    fn remove_attachment_gc_deletes_filespec_and_stream() {
        let mut pdf = open_minimal();
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("gc.txt");
        std::fs::write(&file, b"gc test").unwrap();

        let fs_ref = add_attachment_from_path(&mut pdf, b"gc.txt", &file).expect("add");

        // Resolve the stream ref before removal.
        let stream_ref = embedded_file_stream_ref(&mut pdf, fs_ref)
            .expect("resolve_stream_ref")
            .expect("stream ref must exist");

        remove_attachment(&mut pdf, b"gc.txt").expect("remove");

        // Both objects remain available for the writer's policy decision.
        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_ref),
            "filespec remains in memory before writer output"
        );
        assert!(
            live.contains(&stream_ref),
            "stream remains in memory before writer output"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 0);
        assert!(list_embedded_files(&mut written)
            .expect("list rewritten attachments")
            .is_empty());
    }

    // ── Test: indirect /AF array retains the null Filespec reference ─────────
    //
    // qpdf keeps an indirect /AF array and its reference to the nulled
    // Filespec, while the embedded stream is dropped by the writer.
    #[test]
    fn remove_attachment_with_indirect_af_array_gcs_filespec_and_stream() {
        let mut pdf = open_minimal();

        let fs_ref = FileSpecBuilder::new("idx.txt", b"indirect-af payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"idx.txt", fs_ref).expect("insert");

        let stream_ref = embedded_file_stream_ref(&mut pdf, fs_ref)
            .expect("resolve stream ref")
            .expect("stream ref must exist");

        // Allocate a standalone array object [fs_ref] and point catalog /AF at
        // it *indirectly* (the only reference to this array object).
        let next = next_object_number(&mut pdf);
        let af_array_ref = ObjectRef::new(next + 1, 0);
        let filespec_handle = pdf.get_object_handle(fs_ref);
        set_test_object(&mut pdf, af_array_ref, handle_array(vec![filespec_handle]));

        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/AF", pdf.get_object_handle(af_array_ref))
            .expect("replace catalog /AF");

        let removed = remove_attachment(&mut pdf, b"idx.txt").expect("remove");
        assert!(removed);

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_ref),
            "null Filespec must remain reachable through the indirect /AF array"
        );
        assert!(
            live.contains(&stream_ref),
            "embedded stream remains in memory before writer output"
        );
        assert!(
            live.contains(&af_array_ref),
            "qpdf keeps the indirect /AF array referenced by the catalog"
        );

        // Catalog /AF and its null Filespec reference remain.
        let catalog2 = catalog_handle(&mut pdf);
        assert_eq!(
            catalog2.try_get_key(b"/AF").unwrap().object_ref(),
            Some(af_array_ref),
            "catalog /AF must remain in place"
        );
        assert!(
            resolved_handle(&mut pdf, fs_ref).is_null(),
            "Filespec must be nulled, not removed"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 0);
    }

    // ── Test: indirect /AF shared by catalog + page retains null Filespec ────
    //
    // The same indirect /AF array object is referenced by both catalog and
    // page. qpdf keeps both parent references and the null Filespec element.
    #[test]
    fn remove_attachment_shared_indirect_af_across_catalog_and_page_not_dangled() {
        let mut pdf = open_minimal();

        let fs_ref = FileSpecBuilder::new("sh.txt", b"shared-af payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"sh.txt", fs_ref).expect("insert");

        // One indirect /AF array object [fs_ref], referenced by BOTH the
        // catalog and the page.
        let next = next_object_number(&mut pdf);
        let af_array_ref = ObjectRef::new(next + 1, 0);
        let filespec_handle = pdf.get_object_handle(fs_ref);
        set_test_object(&mut pdf, af_array_ref, handle_array(vec![filespec_handle]));

        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/AF", pdf.get_object_handle(af_array_ref))
            .expect("replace catalog /AF");

        let page_refs = crate::pages::page_refs(&mut pdf).expect("page_refs");
        assert_eq!(page_refs.len(), 1, "fixture has one page");
        let page_ref = page_refs[0];
        let page = resolved_handle(&mut pdf, page_ref);
        page.replace_key(b"/AF", pdf.get_object_handle(af_array_ref))
            .expect("replace page /AF");

        // Removal walks catalog then every page, calling the helper once per
        // parent against the SAME shared array object.
        let removed = remove_attachment(&mut pdf, b"sh.txt").expect("remove");
        assert!(removed);

        // The shared array object must still resolve for every parent and keep
        // the removed Filespec reference.
        let af_after = resolved_handle(&mut pdf, af_array_ref)
            .as_array()
            .expect("shared indirect /AF array must still resolve (not deleted)");
        assert_eq!(
            af_after.len(),
            1,
            "shared /AF array must retain the nulled Filespec reference"
        );
        assert_eq!(af_after[0].object_ref(), Some(fs_ref));

        // The null Filespec remains reachable through the shared array.
        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_ref),
            "null Filespec must remain reachable through the shared /AF array"
        );

        // Page /AF must still point at the surviving shared array.
        let page_after = resolved_handle(&mut pdf, page_ref);
        assert_eq!(
            page_after.try_get_key(b"/AF").unwrap().object_ref(),
            Some(af_array_ref),
            "page /AF must still point at the surviving shared array"
        );
        assert!(
            resolved_handle(&mut pdf, fs_ref).is_null(),
            "Filespec must be nulled, not removed"
        );
    }

    // ── Test: another live name tree retains the null Filespec reference ────
    //
    // qpdf replaces the Filespec object with null even when a live /Dests
    // name tree still retains its object reference.
    #[test]
    fn remove_attachment_preserves_filespec_referenced_by_other_name_tree() {
        let mut pdf = open_minimal();

        // Register a filespec under /Names /EmbeddedFiles.
        let fs_ref = FileSpecBuilder::new("shared.txt", b"shared payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"shared.txt", fs_ref).expect("insert");

        let stream_ref = embedded_file_stream_ref(&mut pdf, fs_ref)
            .expect("resolve stream ref")
            .expect("stream ref must exist");

        // A separate, type-less name-tree leaf (models a /Dests name tree) that
        // legitimately references the SAME filespec.
        let next = next_object_number(&mut pdf);
        let dests_leaf_ref = ObjectRef::new(next + 1, 0);
        let dests_leaf = handle_dictionary(vec![(
            b"/Names",
            handle_array(vec![
                ObjectHandle::string(b"shared-dest".to_vec()),
                pdf.get_object_handle(fs_ref),
            ]),
        )]);
        set_test_object(&mut pdf, dests_leaf_ref, dests_leaf);

        // Hang it off the catalog's /Dests so it is reachable from the catalog
        // (a legitimate live name tree, not a dead ghost).
        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/Dests", pdf.get_object_handle(dests_leaf_ref))
            .expect("replace catalog /Dests");

        // Remove the embedded-files attachment. qpdf nulls the Filespec
        // object even when another name tree still references its object ref.
        let removed = remove_attachment(&mut pdf, b"shared.txt").expect("remove");
        assert!(removed, "existing key must report removed");

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_ref),
            "the null Filespec ref remains reachable through /Dests"
        );
        assert!(
            resolved_handle(&mut pdf, fs_ref).is_null(),
            "qpdf replaces the shared Filespec with null"
        );

        // The /Dests reference itself must remain intact.
        let leaf = resolved_handle(&mut pdf, dests_leaf_ref);
        let names = leaf
            .try_get_key(b"/Names")
            .unwrap()
            .as_array()
            .expect("dests leaf names");
        assert!(
            names.iter().any(|value| value.object_ref() == Some(fs_ref)),
            "/Dests leaf must still reference the filespec"
        );

        // The Filespec is null, so its embedded stream is no longer reachable
        // through that object and the writer drops it.
        assert!(
            live.contains(&stream_ref),
            "embedded stream remains in memory before writer output"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 0);
    }

    // ── Test: live object referencing the stream (with stream back-ref) ──────
    //
    // qpdf replaces the removed Filespec with null. The externally referenced
    // stream survives, but its dictionary's back-reference resolves to null
    // and is not a writer reachability edge (`QPDFWriter.cc:1131-1135`), so the
    // Filespec itself is omitted by the ordinary writer.
    #[test]
    fn remove_attachment_keeps_external_stream_but_collects_nulled_filespec() {
        let mut pdf = open_minimal();

        let fs_ref = FileSpecBuilder::new("paired.txt", b"paired payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"paired.txt", fs_ref).expect("insert");

        let stream_ref = embedded_file_stream_ref(&mut pdf, fs_ref)
            .expect("resolve stream ref")
            .expect("stream ref must exist");

        // Make the stream dictionary back-reference the filespec (pathological
        // but legal) and have a live, catalog-reachable object reference the
        // stream so conservative GC must preserve it.
        let stream = resolved_handle(&mut pdf, stream_ref);
        let stream_dict = stream.as_stream_dict().expect("stream dictionary");
        stream_dict
            .replace_key(b"/RelatedFS", pdf.get_object_handle(fs_ref))
            .expect("add stream back-reference");

        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/ExtraStreamRef", pdf.get_object_handle(stream_ref))
            .expect("replace catalog stream reference");

        let removed = remove_attachment(&mut pdf, b"paired.txt").expect("remove");
        assert!(removed);

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&stream_ref),
            "externally-referenced stream remains in memory"
        );
        assert!(live.contains(&fs_ref), "nulled filespec remains in memory");

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 1);
        assert!(list_embedded_files(&mut written)
            .expect("list rewritten attachments")
            .is_empty());
    }

    // ── Test: shared embedded stream is preserved by the writer ───────────────
    //
    // Two filespecs share one /EmbeddedFile stream.  Removing one attachment
    // must let the writer drop its otherwise-unreferenced filespec but keep the
    // shared stream and the other filespec intact. Guards against an over-conservative
    // "pair-or-nothing" handling would incorrectly discard the shared stream.
    #[test]
    fn remove_attachment_with_shared_stream_keeps_stream_and_other_filespec() {
        let mut pdf = open_minimal();

        let fs_a = FileSpecBuilder::new("a.txt", b"shared body")
            .build(&mut pdf)
            .expect("build a");
        insert_embedded_file(&mut pdf, b"a.txt", fs_a).expect("insert a");
        let shared_stream = embedded_file_stream_ref(&mut pdf, fs_a)
            .expect("resolve stream a")
            .expect("stream a exists");

        // Build a second filespec whose /EF points at the SAME stream object.
        let next = next_object_number(&mut pdf);
        let fs_b = ObjectRef::new(next + 1, 0);
        let ef = handle_dictionary(vec![
            (b"/F", pdf.get_object_handle(shared_stream)),
            (b"/UF", pdf.get_object_handle(shared_stream)),
        ]);
        let fs_b_handle = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"Filespec".to_vec())),
            (b"/F", ObjectHandle::string(b"b.txt".to_vec())),
            (b"/UF", ObjectHandle::string(b"b.txt".to_vec())),
            (b"/EF", ef),
        ]);
        set_test_object(&mut pdf, fs_b, fs_b_handle);
        insert_embedded_file(&mut pdf, b"b.txt", fs_b).expect("insert b");

        // Remove attachment "a": its filespec is otherwise unreferenced and
        // must be omitted by ordinary writer output; the stream is still used
        // by fs_b and must survive, and fs_b itself must remain intact.
        let removed = remove_attachment(&mut pdf, b"a.txt").expect("remove a");
        assert!(removed);

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&fs_a),
            "removed attachment's nulled filespec remains in memory"
        );
        assert!(
            live.contains(&shared_stream),
            "stream shared with another filespec must be preserved"
        );
        assert!(
            live.contains(&fs_b),
            "the other filespec sharing the stream must remain intact"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 1);
        let entries = list_embedded_files(&mut written).expect("list rewritten attachments");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].0, b"b.txt");
    }

    // ── Test: filespec with distinct /EF streams is GC'd by the writer ───────
    //
    // Every stream under an /EF key must be collected when the filespec is
    // deleted; resolving only the first stream would leave sibling streams
    // orphaned.
    #[test]
    fn remove_attachment_gcs_all_distinct_ef_streams() {
        let mut pdf = open_minimal();

        let fs_ref = FileSpecBuilder::new("multi.txt", b"primary stream")
            .build(&mut pdf)
            .expect("build filespec");

        // The builder points /EF /F and /EF /UF at one stream; capture it.
        let filespec = resolved_handle(&mut pdf, fs_ref);
        let ef = filespec.try_get_key(b"/EF").unwrap();
        assert!(ef.as_dictionary().is_some(), "expected inline /EF dict");
        let stream_f = ef
            .try_get_key(b"/F")
            .unwrap()
            .object_ref()
            .expect("expected /EF /F indirect stream");

        // Add a *distinct* second stream object under /EF /UF.
        let next = next_object_number(&mut pdf);
        let stream_uf = ObjectRef::new(next + 1, 0);
        let stream = ObjectHandle::stream(
            handle_dictionary(vec![(
                b"/Type",
                ObjectHandle::name(b"EmbeddedFile".to_vec()),
            )]),
            std::rc::Rc::new(b"sibling stream".to_vec()),
        );
        set_test_object(&mut pdf, stream_uf, stream);
        ef.replace_key(b"/UF", pdf.get_object_handle(stream_uf))
            .expect("replace /EF /UF");

        insert_embedded_file(&mut pdf, b"multi.txt", fs_ref).expect("insert");

        let removed = remove_attachment(&mut pdf, b"multi.txt").expect("remove");
        assert!(removed);

        let live = pdf.canonical_live_object_refs();
        assert!(live.contains(&fs_ref), "filespec remains in memory");
        assert!(live.contains(&stream_f), "primary stream remains in memory");
        assert!(
            live.contains(&stream_uf),
            "sibling stream remains in memory"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 0);
        assert!(list_embedded_files(&mut written)
            .expect("list rewritten attachments")
            .is_empty());
    }

    // ── Test: empty/target-absent indirect /AF array is left untouched ───────
    //
    // An *empty* (or target-absent) indirect /AF array must remain intact when
    // the target reference was never present, especially when the array is
    // shared by multiple dictionaries.
    #[test]
    fn remove_attachment_leaves_empty_indirect_af_array_intact() {
        let mut pdf = open_minimal();

        let next = next_object_number(&mut pdf);

        // An empty indirect /AF array object, shared by the catalog *and* a
        // second dictionary so wrongly deleting it would dangle a live ref.
        let af_array_ref = ObjectRef::new(next + 1, 0);
        set_test_object(&mut pdf, af_array_ref, handle_array(Vec::new()));

        let sharer_ref = ObjectRef::new(next + 2, 0);
        let sharer = handle_dictionary(vec![(b"/AF", pdf.get_object_handle(af_array_ref))]);
        set_test_object(&mut pdf, sharer_ref, sharer);

        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/AF", pdf.get_object_handle(af_array_ref))
            .expect("replace catalog /AF");
        catalog
            .replace_key(b"/Sharer", pdf.get_object_handle(sharer_ref))
            .expect("replace catalog /Sharer");

        // Add and remove an unrelated attachment.  Its filespec is NOT in the
        // empty indirect /AF array, so the array and parent key must survive.
        let fs_ref = FileSpecBuilder::new("x.txt", b"x")
            .build(&mut pdf)
            .expect("build");
        insert_embedded_file(&mut pdf, b"x.txt", fs_ref).expect("insert");

        let removed = remove_attachment(&mut pdf, b"x.txt").expect("remove");
        assert!(removed);

        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&af_array_ref),
            "empty indirect /AF array (target absent) must NOT be deleted"
        );
        let catalog2 = catalog_handle(&mut pdf);
        assert!(
            catalog2.try_get_key(b"/AF").unwrap().object_ref() == Some(af_array_ref),
            "catalog /AF must still point at the untouched indirect array"
        );
    }

    // ── Test: missing key returns false, document unchanged ──────────────────

    #[test]
    fn remove_nonexistent_key_returns_false() {
        let mut pdf = open_minimal();
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("keep.txt");
        std::fs::write(&file, b"keep me").unwrap();
        add_attachment_from_path(&mut pdf, b"keep.txt", &file).expect("add");

        let result = remove_attachment(&mut pdf, b"no-such-key.txt").expect("no error");
        assert!(!result, "must return false for absent key");

        // Document must still contain the original attachment.
        let entries = list_embedded_files(&mut pdf).expect("list");
        assert_eq!(entries.len(), 1, "document must be unchanged");
        assert_eq!(entries[0].0, b"keep.txt");
    }

    // ── Test: /AF on catalog and page is cleared after remove ─────────────────

    #[test]
    fn remove_attachment_preserves_af_and_nulls_filespec_on_catalog_and_page() {
        let mut pdf = open_minimal();

        // Build a filespec manually so we control the ref.
        let fs_ref = FileSpecBuilder::new("af-test.txt", b"payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"af-test.txt", fs_ref).expect("insert");

        // Add /AF to catalog pointing at fs_ref.
        let catalog = catalog_handle(&mut pdf);
        catalog
            .replace_key(b"/AF", handle_array(vec![pdf.get_object_handle(fs_ref)]))
            .expect("replace catalog /AF");

        // Add /AF to the single page as well.
        let page_refs = crate::pages::page_refs(&mut pdf).expect("page_refs");
        assert_eq!(page_refs.len(), 1, "fixture has one page");
        let page_ref = page_refs[0];
        let page = resolved_handle(&mut pdf, page_ref);
        page.replace_key(b"/AF", handle_array(vec![pdf.get_object_handle(fs_ref)]))
            .expect("replace page /AF");

        // Remove the attachment.
        let removed = remove_attachment(&mut pdf, b"af-test.txt").expect("remove");
        assert!(removed);

        // qpdf leaves the associated-files reference in place; the Filespec
        // object itself is replaced with null by removeEmbeddedFile.
        let catalog2 = catalog_handle(&mut pdf);
        let catalog_af = catalog2
            .try_get_key(b"/AF")
            .unwrap()
            .as_array()
            .expect("catalog /AF");
        assert_eq!(
            catalog_af.len(),
            1,
            "qpdf keeps catalog /AF pointing at the nulled Filespec"
        );
        assert_eq!(catalog_af[0].object_ref(), Some(fs_ref));

        assert!(
            resolved_handle(&mut pdf, fs_ref).is_null(),
            "qpdf replaces the removed Filespec with null"
        );

        // The page's /AF reference is retained too.
        let page_dict2 = resolved_handle(&mut pdf, page_ref);
        let page_af = page_dict2
            .try_get_key(b"/AF")
            .unwrap()
            .as_array()
            .expect("page /AF");
        assert_eq!(
            page_af.len(),
            1,
            "qpdf keeps page /AF pointing at the nulled Filespec"
        );
        assert_eq!(page_af[0].object_ref(), Some(fs_ref));
    }

    // ── Test: shared stream is preserved by the writer ──────────────────────

    #[test]
    fn conservative_gc_preserves_shared_stream() {
        // Build two /Filespec dicts that share the same /EmbeddedFile stream.
        // When one filespec is removed, the shared stream must survive the
        // writer because the other filespec still references it.
        let mut pdf = open_minimal();

        // Allocate the shared EmbeddedFile stream object.
        let next = next_object_number(&mut pdf);
        let stream_ref = ObjectRef::new(next + 1, 0);
        let fs_ref1 = ObjectRef::new(next + 2, 0);
        let fs_ref2 = ObjectRef::new(next + 3, 0);

        // Shared EmbeddedFile stream.
        let ef_dict = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"EmbeddedFile".to_vec())),
            (b"/Length", ObjectHandle::integer(7)),
        ]);
        set_test_object(
            &mut pdf,
            stream_ref,
            ObjectHandle::stream(ef_dict, std::rc::Rc::new(b"payload".to_vec())),
        );

        // /EF sub-dict pointing both filespecs at the same stream.
        let ef_sub = handle_dictionary(vec![
            (b"/F", pdf.get_object_handle(stream_ref)),
            (b"/UF", pdf.get_object_handle(stream_ref)),
        ]);

        // Filespec 1.
        let fs1 = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"Filespec".to_vec())),
            (b"/F", ObjectHandle::string(b"shared1.txt".to_vec())),
            (b"/EF", ef_sub.clone()),
        ]);
        set_test_object(&mut pdf, fs_ref1, fs1);

        // Filespec 2.
        let fs2 = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"Filespec".to_vec())),
            (b"/F", ObjectHandle::string(b"shared2.txt".to_vec())),
            (b"/EF", ef_sub),
        ]);
        set_test_object(&mut pdf, fs_ref2, fs2);

        // Insert both into the name tree.
        insert_embedded_file(&mut pdf, b"shared1.txt", fs_ref1).expect("insert 1");
        insert_embedded_file(&mut pdf, b"shared2.txt", fs_ref2).expect("insert 2");

        // Remove only the first attachment.
        let removed = remove_attachment(&mut pdf, b"shared1.txt").expect("remove");
        assert!(removed);

        // The shared stream must still be alive (fs_ref2 still references it).
        let live = pdf.canonical_live_object_refs();
        assert!(
            live.contains(&stream_ref),
            "shared stream must NOT be GC'd while fs_ref2 still references it"
        );

        // fs_ref1 is nulled in memory and is omitted by ordinary writer output.
        assert!(
            live.contains(&fs_ref1),
            "removed filespec ref remains in memory before writer output"
        );

        // fs_ref2 must still be alive.
        assert!(
            live.contains(&fs_ref2),
            "surviving filespec ref must remain alive"
        );

        let mut written = rewritten(&mut pdf);
        assert_eq!(count_embedded_file_streams(&mut written), 1);
        let entries = list_embedded_files(&mut written).expect("list rewritten attachments");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].0, b"shared2.txt");
    }

    // ── Test: /Names present but /EmbeddedFiles absent → empty ────────────────
    //
    // Covers the `None => Ok(vec![])` branch in both readers when the catalog
    // has a /Names dictionary that simply does not carry an /EmbeddedFiles key.
    #[test]
    fn readers_return_empty_when_names_has_no_embedded_files() {
        let mut pdf = open_minimal();

        // Attach a /Names dict carrying only an unrelated key (no /EmbeddedFiles).
        let names = handle_dictionary(vec![(b"/Dests", handle_dictionary(Vec::new()))]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        assert!(
            list_embedded_files(&mut pdf).expect("list").is_empty(),
            "list_embedded_files must be empty when /EmbeddedFiles is absent"
        );
        assert!(
            pdf.embedded_files()
                .get_embedded_files()
                .expect("handle-valued entries")
                .is_empty(),
            "handle-valued entries must be empty when /EmbeddedFiles is absent"
        );
    }

    #[test]
    fn handle_entries_preserve_direct_filespec_handles() {
        let mut pdf = open_minimal();
        let filespec = handle_dictionary(vec![
            (b"/Type", ObjectHandle::name(b"Filespec".to_vec())),
            (b"/F", ObjectHandle::string(b"direct.txt".to_vec())),
        ]);
        let root = handle_dictionary(vec![(
            b"/Names",
            handle_array(vec![ObjectHandle::string(b"direct".to_vec()), filespec]),
        )]);
        let names = handle_dictionary(vec![(b"/EmbeddedFiles", root)]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        let entries = pdf
            .embedded_files()
            .get_embedded_files()
            .expect("collect direct filespec handle");
        let filespec = entries
            .get(b"direct".as_slice())
            .expect("direct Filespec entry");
        assert!(filespec.as_dictionary().is_some());
        assert_eq!(
            filespec.try_get_key(b"/F").unwrap().as_string(),
            Some(b"direct.txt".to_vec())
        );
    }

    // ── Test: empty removal preserves an indirect /Names dict ────────────────
    //
    // When the last /EmbeddedFiles entry is removed and the /Names dict still
    // carries a surviving sibling (here /Dests), the empty-rebuild path rewrites
    // the indirect names dict in place. The qpdf-shaped catalog reaches the
    // terminal directly through its indirect /Names child.
    #[test]
    fn empty_remove_preserves_indirect_names_with_surviving_sibling() {
        let mut pdf = open_minimal();

        // Register an attachment so /Names /EmbeddedFiles holds a real entry.
        let fs_ref = FileSpecBuilder::new("only.txt", b"only payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"only.txt", fs_ref).expect("insert");

        // Materialize qpdf's direct names dictionary as an indirect terminal
        // and add a surviving sibling key.
        let catalog = catalog_handle(&mut pdf);
        let terminal = catalog
            .try_get_key(b"/Names")
            .unwrap()
            .shallow_copy()
            .expect("copy direct names");
        // /Dests as a small inline dict: survives writer output because it is
        // owned by the (still-reachable) terminal names dict.
        terminal
            .replace_key(
                b"/Dests",
                handle_dictionary(vec![(b"/X", pdf.get_object_handle(fs_ref))]),
            )
            .expect("add /Dests sibling");
        let terminal_ref = ObjectRef::new(next_object_number(&mut pdf) + 1, 0);
        set_test_object(&mut pdf, terminal_ref, terminal);

        catalog
            .replace_key(b"/Names", pdf.get_object_handle(terminal_ref))
            .expect("install indirect Names");

        // Remove the last (only) embedded file → empty rebuild with a surviving
        // /Dests sibling.
        let removed = remove_attachment(&mut pdf, b"only.txt").expect("remove only");
        assert!(removed, "remove_attachment must return true");

        // qpdf modifies the indirect names dictionary in place.
        let catalog_after = catalog_handle(&mut pdf);
        let names_after = catalog_after
            .try_get_key(b"/Names")
            .unwrap()
            .object_ref()
            .expect("catalog /Names must still be indirect");
        assert_eq!(names_after, terminal_ref);

        // The terminal retains its sibling and an empty EmbeddedFiles tree.
        let names_dict = resolved_handle(&mut pdf, terminal_ref);
        assert!(
            names_dict.try_has_key(b"/Dests").unwrap(),
            "terminal /Names dict must retain the surviving /Dests sibling"
        );
        assert!(names_dict.try_has_key(b"/EmbeddedFiles").unwrap());
    }

    // ── Test: non-empty rebuild with a *direct* (inline) /Names dict ──────────
    //
    // Catalog /Names may be stored inline as a dictionary rather than indirectly.
    // The qpdf path preserves its direct representation while writing the
    // /EmbeddedFiles tree and retaining siblings.
    #[test]
    fn non_empty_rebuild_with_direct_names_dict() {
        let mut pdf = open_minimal();

        // Seed catalog /Names as a *direct* dict carrying only an unrelated key.
        let names = handle_dictionary(vec![(b"/Dests", handle_dictionary(Vec::new()))]);
        replace_catalog_key(&mut pdf, b"/Names", names);

        // Adding an attachment drives the non-empty rebuild over the direct dict.
        let fs_ref = FileSpecBuilder::new("direct.txt", b"direct payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"direct.txt", fs_ref).expect("insert");

        let entries = list_embedded_files(&mut pdf).expect("list");
        assert_eq!(entries.len(), 1, "attachment must be registered");
        assert_eq!(entries[0].0, b"direct.txt");

        // /Names stays direct and retains /Dests.
        let catalog_after = catalog_handle(&mut pdf);
        let names_after = catalog_after
            .try_get_key(b"/Names")
            .unwrap()
            .as_dictionary()
            .expect("/Names direct after insert");
        assert!(
            names_after.contains_key(b"/Dests".as_slice()),
            "the inline /Dests sibling must survive the rebuild"
        );
        assert!(
            names_after.contains_key(b"/EmbeddedFiles".as_slice()),
            "/EmbeddedFiles must be written into the /Names dict"
        );
    }

    // ── Test: empty rebuild with a *direct* (inline) /Names dict + sibling ────
    //
    // When /Names is an inline dict that directly holds both /EmbeddedFiles and a
    // surviving sibling (/Dests), removing the last attachment must drop
    // /EmbeddedFiles and rewrite the catalog with the trimmed inline dict.
    #[test]
    fn empty_rebuild_with_direct_names_dict_and_sibling() {
        let mut pdf = open_minimal();

        // First build a real /EmbeddedFiles tree via the helper.
        let fs_ref = FileSpecBuilder::new("only2.txt", b"only2 payload")
            .build(&mut pdf)
            .expect("build filespec");
        insert_embedded_file(&mut pdf, b"only2.txt", fs_ref).expect("insert");

        // Inline that names dict directly into the catalog (and add /Dests), so
        // the catalog reaches /EmbeddedFiles through a *direct* /Names dict.
        let catalog = catalog_handle(&mut pdf);
        let names = catalog
            .try_get_key(b"/Names")
            .unwrap()
            .shallow_copy()
            .expect("copy direct Names");
        names
            .replace_key(b"/Dests", handle_dictionary(Vec::new()))
            .expect("add /Dests sibling");
        catalog
            .replace_key(b"/Names", names)
            .expect("install direct Names");

        // Remove the only attachment → empty rebuild over the direct /Names dict.
        let removed = remove_attachment(&mut pdf, b"only2.txt").expect("remove only2");
        assert!(removed, "remove_attachment must return true");

        // /Names stays inline on the catalog; /Dests and the empty
        // /EmbeddedFiles tree are preserved.
        let catalog_after = catalog_handle(&mut pdf);
        let names_after = catalog_after
            .try_get_key(b"/Names")
            .unwrap()
            .as_dictionary()
            .expect("/Names must remain a direct dict");
        assert!(
            names_after.contains_key(b"/Dests".as_slice()),
            "the /Dests sibling must survive the empty rebuild"
        );
        assert!(names_after.contains_key(b"/EmbeddedFiles".as_slice()));
    }
}