flpdf 0.6.0

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

use super::attachment_list::format_attachment_list_with_sink;
use super::lifecycle::{JobDocument, JobExitCode, QPDFJob};
use crate::filespec_helper::FileSpec;
use crate::pipeline::{Pipeline, PipelineHandle, PipelineResult};
use crate::qpdf_time::default_pdf_date;
use crate::{Error, ObjectHandle, ObjectRef, Pdf, Result};
use std::io::{Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::rc::Rc;

fn path_bytes(path: &Path) -> Vec<u8> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;

        path.as_os_str().as_bytes().to_vec()
    }

    #[cfg(not(unix))]
    {
        path.to_string_lossy().into_owned().into_bytes()
    }
}

struct PipelineHandleSink(PipelineHandle);

impl Pipeline for PipelineHandleSink {
    fn identifier(&self) -> &str {
        "qpdf job attachment save"
    }

    fn write(&mut self, data: &[u8]) -> PipelineResult<()> {
        self.0.write(data)
    }

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

/// qpdf's per-file configuration for `QPDFJob::copyAttachments`.
///
/// `path` is retained for the `copying attachments from PATH` verbose
/// diagnostic and the `file: PATH, key: ...` duplicate-key message. The
/// password is consumed by [`QPDFJob::copy_attachments_with_opener`]; the
/// source-backed [`QPDFJob::copy_attachments`] and
/// [`QPDFJob::copy_attachments_many`] forms intentionally accept already-open
/// sources for direct library callers.
#[derive(Debug, Clone)]
pub struct AttachmentCopyOptions {
    /// Source PDF path, used only for diagnostics.
    pub path: PathBuf,
    /// Password bytes used when the job opens the donor source.
    pub password: Vec<u8>,
    /// Prefix prepended to each copied key.
    pub prefix: Vec<u8>,
    /// Emit qpdf's `copying attachments from ...` / `  key -> new_key` diagnostics.
    pub verbose: bool,
}

/// One already-opened donor for [`QPDFJob::copy_attachments_many`].
///
/// The caller owns the donor PDF and supplies its per-file copy options. A
/// separate source entry is required for every qpdf
/// `--copy-attachments-from` group.
pub struct AttachmentCopySource<'a, R: Read + Seek + 'static> {
    /// Authenticated donor PDF.
    pub source: &'a mut Pdf<R>,
    /// Donor path, prefix, and verbosity policy.
    pub options: AttachmentCopyOptions,
}

/// qpdf's per-file configuration for `QPDFJob::addAttachments`.
///
/// The path is retained by the provider-backed embedded-file stream; the
/// payload is not materialized by the job. `creation_date` and
/// `modification_date` carry raw PDF date strings so an explicit qpdf date is
/// preserved byte-for-byte. When omitted, the job supplies qpdf's process-stable
/// local-wall-clock date with its UTC offset (`QUtil::get_current_qpdf_time`
/// and `QPDFJob::AttConfig::endAddAttachment`, `libqpdf/QUtil.cc:867-934`,
/// `libqpdf/QPDFJob_config.cc:911-936`).
#[derive(Debug, Clone)]
pub struct AttachmentAddOptions {
    /// Path whose bytes are embedded.
    pub path: PathBuf,
    /// `/Names /EmbeddedFiles` name-tree key.
    pub key: Vec<u8>,
    /// Displayed `/F` and `/UF` filename.
    pub filename: Vec<u8>,
    /// Optional `/EmbeddedFile /Subtype` MIME name.
    pub mimetype: Option<Vec<u8>>,
    /// Optional `/Filespec /Desc` text.
    pub description: Option<Vec<u8>>,
    /// Optional raw `/Params /CreationDate` value.
    pub creation_date: Option<Vec<u8>>,
    /// Optional raw `/Params /ModDate` value.
    pub modification_date: Option<Vec<u8>>,
    /// Replace an existing entry with the same key.
    pub replace: bool,
    /// Emit qpdf's `attached ... with key ...` diagnostic.
    pub verbose: bool,
}

impl QPDFJob {
    /// Add one or more provider-backed attachments through the shared qpdf
    /// job lifecycle.
    ///
    /// This is the Rust translation of `QPDFJob::addAttachments`:
    /// `QPDFJob.cc:2037-2087`. Page mode is changed before duplicate
    /// detection, Filespec/EmbeddedFile objects are created through the
    /// typed helpers, and the canonical ObjectHandle name-tree route owns the
    /// insertion/replacement. A duplicate is reported only after all
    /// non-duplicate entries have been processed, matching qpdf's aggregate
    /// error boundary.
    pub fn add_attachments<R: Read + Seek + 'static>(
        &mut self,
        pdf: &mut Pdf<R>,
        options: &[AttachmentAddOptions],
    ) -> Result<()> {
        // qpdf's sole caller only invokes `addAttachments` when
        // `attachments_to_add` is non-empty (`QPDFJob.cc:2241-2243`); an
        // empty batch is a no-op there, so no page-mode change happens.
        if options.is_empty() {
            return Ok(());
        }
        pdf.set_logger(self.logger());
        self.set_attachment_page_mode(pdf)?;

        let mut duplicated_keys = Vec::new();
        let default_date = default_pdf_date().to_vec();
        for option in options {
            let exists = {
                let mut embedded_files = pdf.embedded_files();
                embedded_files.get_embedded_file(&option.key)?.is_some()
            };
            if exists && !option.replace {
                duplicated_keys.push(option.key.clone());
                continue;
            }

            let filespec =
                FileSpec::create_file_spec_from_path(pdf, &option.filename, &option.path)?;
            {
                let mut filespec_helper = FileSpec::new(filespec.clone(), pdf)?;
                if let Some(description) = option.description.as_deref() {
                    filespec_helper.set_description(description)?;
                }
                let mut embedded_file = filespec_helper
                    .embedded_file()?
                    .expect("FileSpec::create_file_spec_from_path must create an /EmbeddedFile");
                let creation_date = option
                    .creation_date
                    .clone()
                    .unwrap_or_else(|| default_date.clone());
                let modification_date = option
                    .modification_date
                    .clone()
                    .unwrap_or_else(|| default_date.clone());
                embedded_file.set_creation_date(creation_date)?;
                embedded_file.set_mod_date(modification_date)?;
                if let Some(mimetype) = option.mimetype.as_deref() {
                    embedded_file.set_subtype(mimetype)?;
                }
            }

            pdf.embedded_files()
                .replace_embedded_file(&option.key, filespec)?;

            if option.verbose {
                // qpdf writes `filename`/`key` as raw bytes
                // (`QPDFJob.cc:2066-2068`); build the diagnostic as bytes
                // too so a non-UTF-8 value isn't replaced with U+FFFD.
                let mut message = Vec::new();
                message.extend_from_slice(self.message_prefix().as_bytes());
                message.extend_from_slice(b": attached ");
                message.extend_from_slice(&path_bytes(&option.path));
                message.extend_from_slice(b" as ");
                message.extend_from_slice(&option.filename);
                message.extend_from_slice(b" with key ");
                message.extend_from_slice(&option.key);
                message.push(b'\n');
                self.logger().info(message)?;
            }
        }

        if duplicated_keys.is_empty() {
            return Ok(());
        }

        let keys = duplicated_keys
            .iter()
            .map(|key| String::from_utf8_lossy(key).into_owned())
            .collect::<Vec<_>>()
            .join(", ");
        Err(Error::System(format!(
            "{} already has attachments with the following keys: {}; use --replace to replace or --key to specify a different key",
            self.input_name(), keys
        )))
    }

    /// Add one attachment through [`Self::add_attachments`].
    pub fn add_attachment<R: Read + Seek + 'static>(
        &mut self,
        pdf: &mut Pdf<R>,
        options: AttachmentAddOptions,
    ) -> Result<()> {
        self.add_attachments(pdf, std::slice::from_ref(&options))
    }

    /// Copy every embedded file from an already-opened `source` into `target`
    /// through the shared qpdf copy body.
    ///
    /// This is the Rust translation of `QPDFJob::copyAttachments`:
    /// `QPDFJob.cc:2089-2135`. Page mode is changed before duplicate
    /// detection; each source filespec's object graph is copied through the
    /// canonical [`Pdf::copy_foreign_object`] cross-document primitive and
    /// inserted into the target's `/EmbeddedFiles` name tree; a duplicate
    /// key is reported only after every entry has been processed, matching
    /// qpdf's aggregate error boundary. Warnings observed on `source` (e.g.
    /// from a repaired open) are folded into this job's own warning state,
    /// matching qpdf's `other->anyWarnings()` check (`QPDFJob.cc:2116-2118`).
    ///
    pub fn copy_attachments<R1, R2>(
        &mut self,
        target: &mut Pdf<R1>,
        source: &mut Pdf<R2>,
        options: &AttachmentCopyOptions,
    ) -> Result<()>
    where
        R1: Read + Seek + 'static,
        R2: Read + Seek + 'static,
    {
        let mut sources = [AttachmentCopySource {
            source,
            options: options.clone(),
        }];
        self.copy_attachments_many(target, &mut sources)
    }

    /// Copy every embedded file from every configured donor, opening each
    /// donor inside the qpdf-shaped copy loop.
    ///
    /// The opener is only the document-I/O boundary. This method owns the
    /// qpdf order of the verbose donor message, opener call, copy operation,
    /// warning collection, and aggregate duplicate-key error
    /// (`QPDFJob.cc:2089-2135`). The error type is generic so CLI callers can
    /// preserve their path-scoped error wrapper while library callers use
    /// [`crate::Error`] directly.
    pub fn copy_attachments_with_opener<R1, F, E>(
        &mut self,
        target: &mut Pdf<R1>,
        options: &[AttachmentCopyOptions],
        mut open_source: F,
    ) -> std::result::Result<(), E>
    where
        R1: Read + Seek + 'static,
        F: FnMut(&mut QPDFJob, &AttachmentCopyOptions) -> std::result::Result<JobDocument, E>,
        E: From<Error>,
    {
        if options.is_empty() {
            return Ok(());
        }
        target.set_logger(self.logger());
        self.set_attachment_page_mode(target).map_err(E::from)?;

        let mut duplicates = Vec::new();
        for option in options {
            self.report_copy_attachment_source(option)
                .map_err(E::from)?;
            let mut source = open_source(self, option)?;
            // This opener-owned donor is dropped at the end of the iteration,
            // before `target` is written. qpdf's copyAttachments also drops
            // each per-donor `QPDF` (`QPDFJob.cc:2100`), but a copied foreign
            // stream that stays deferred would dangle once its provider-backed
            // donor is gone (`pipeStreamData called for non-stream`). Reserve
            // the copied stream data now via qpdf's immediate-copy contract
            // (`QPDF::setImmediateCopyFrom`) so the donor can be released.
            source.set_immediate_copy_from(true);
            self.copy_attachment_source(target, &mut source, option, &mut duplicates)
                .map_err(E::from)?;
            self.record_document_warnings(&source);
        }

        self.finish_copy_attachment_duplicates(duplicates)
            .map_err(E::from)
    }

    /// Copy every embedded file from already-opened donors in `sources` into
    /// `target`.
    ///
    /// This is the source-backed form of qpdf's `QPDFJob::copyAttachments`
    /// loop (`QPDFJob.cc:2089-2135`). The canonical path-based form is
    /// [`Self::copy_attachments_with_opener`], which places each donor open at
    /// the qpdf per-donor boundary. This method changes `/PageMode` once,
    /// processes every already-opened donor in order, and delays the aggregate
    /// duplicate-key error until all source entries have been visited. This
    /// preserves qpdf's behavior when a duplicate in an earlier donor must not
    /// prevent a later donor's non-conflicting entries from being copied.
    pub fn copy_attachments_many<R1, R2>(
        &mut self,
        target: &mut Pdf<R1>,
        sources: &mut [AttachmentCopySource<'_, R2>],
    ) -> Result<()>
    where
        R1: Read + Seek + 'static,
        R2: Read + Seek + 'static,
    {
        // qpdf's sole caller only invokes `copyAttachments` when
        // `attachments_to_copy` is non-empty (`QPDFJob.cc:2245-2247`); an
        // empty batch is a no-op there, so no page-mode change happens.
        if sources.is_empty() {
            return Ok(());
        }
        target.set_logger(self.logger());
        self.set_attachment_page_mode(target)?;

        let mut duplicates: Vec<String> = Vec::new();
        for donor in sources {
            self.report_copy_attachment_source(&donor.options)?;
            self.copy_attachment_source(target, donor.source, &donor.options, &mut duplicates)?;
            self.record_document_warnings(donor.source);
        }

        self.finish_copy_attachment_duplicates(duplicates)
    }

    fn report_copy_attachment_source(&self, options: &AttachmentCopyOptions) -> Result<()> {
        if !options.verbose {
            return Ok(());
        }
        let mut message = Vec::new();
        message.extend_from_slice(self.message_prefix().as_bytes());
        message.extend_from_slice(b": copying attachments from ");
        message.extend_from_slice(options.path.display().to_string().as_bytes());
        message.push(b'\n');
        self.logger().info(message)
    }

    fn copy_attachment_source<R1, R2>(
        &self,
        target: &mut Pdf<R1>,
        source: &mut Pdf<R2>,
        options: &AttachmentCopyOptions,
        duplicates: &mut Vec<String>,
    ) -> Result<()>
    where
        R1: Read + Seek + 'static,
        R2: Read + Seek + 'static,
    {
        source.set_logger(self.logger());
        let other_attachments = source.embedded_files().get_embedded_files()?;
        for (key, filespec) in other_attachments {
            let mut new_key = options.prefix.clone();
            new_key.extend_from_slice(&key);

            let exists = target
                .embedded_files()
                .get_embedded_file(&new_key)?
                .is_some();
            if exists {
                duplicates.push(format!(
                    "file: {}, key: {}",
                    options.path.display(),
                    String::from_utf8_lossy(&new_key)
                ));
                continue;
            }

            let copied = target.copy_foreign_object(&filespec)?;
            target
                .embedded_files()
                .replace_embedded_file(&new_key, copied)?;

            if options.verbose {
                let mut message = Vec::new();
                message.extend_from_slice(b"  ");
                message.extend_from_slice(&key);
                message.extend_from_slice(b" -> ");
                message.extend_from_slice(&new_key);
                message.push(b'\n');
                self.logger().info(message)?;
            }
        }
        Ok(())
    }

    fn finish_copy_attachment_duplicates(&self, duplicates: Vec<String>) -> Result<()> {
        if duplicates.is_empty() {
            return Ok(());
        }

        Err(Error::System(format!(
            "{} already has attachments with keys that conflict with attachments from other files: {}. Use --prefix with --copy-attachments-from or manually copy individual attachments.",
            self.input_name(),
            duplicates.join("; ")
        )))
    }

    fn set_attachment_page_mode<R: Read + Seek>(&self, pdf: &mut Pdf<R>) -> Result<()> {
        // qpdf's `maybe_set_pagemode` (`QPDFJob.cc:2036-2042`) calls
        // `QPDF::getRoot`, which throws when the trailer has no valid
        // `/Root` dictionary (`QPDF.cc:2355-2359`).
        let root = pdf.root_handle()?;
        if root.try_get_key(b"/PageMode")?.try_is_null()? {
            root.replace_key(b"/PageMode", ObjectHandle::name(b"UseAttachments".to_vec()))?;
        }
        Ok(())
    }

    /// List embedded files through the shared qpdf info pipeline.
    ///
    /// `QPDFJob::doListAttachments` owns the output and warning lifecycle,
    /// while `QPDFEmbeddedFileDocumentHelper` and the FileSpec/EF helpers own
    /// name-tree traversal and metadata projection. The existing
    /// The internal `format_attachment_list_with_sink` implementation remains
    /// the one attachment traversal route.
    pub fn list_attachments<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        verbose: bool,
    ) -> Result<JobExitCode> {
        let logger = self.logger();
        let input_name = self.input_name_bytes().to_owned();
        self.inspect(pdf, |pdf| {
            emit_list_attachments(pdf, &logger, &input_name, verbose)
        })
    }

    /// Emit the attachment list without completing the enclosing job.
    pub(crate) fn list_attachments_report<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        verbose: bool,
    ) -> Result<()> {
        let logger = self.logger();
        let input_name = self.input_name_bytes().to_owned();
        emit_list_attachments(pdf, &logger, &input_name, verbose)
    }

    /// Show one embedded file through the shared qpdf save pipeline.
    ///
    /// The attachment is resolved before `save_to_standard_output`, matching
    /// qpdf's `doShowAttachment` order: a missing key is a fatal inspection
    /// error and does not claim the standard-output save route
    /// (`libqpdf/QPDFJob.cc:916-927`).
    pub fn show_attachment<R: Read + Seek>(
        &mut self,
        pdf: &mut Pdf<R>,
        key: &[u8],
    ) -> Result<JobExitCode> {
        let logger = self.logger();
        self.inspect(pdf, |pdf| emit_show_attachment(pdf, &logger, key))
    }

    /// Emit one embedded file without completing the enclosing job.
    pub(crate) fn show_attachment_report<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        key: &[u8],
    ) -> Result<()> {
        let logger = self.logger();
        emit_show_attachment(pdf, &logger, key)
    }
}

fn emit_list_attachments<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    logger: &crate::QPDFLogger,
    input_name: &[u8],
    verbose: bool,
) -> Result<()> {
    let listing = format_attachment_list_with_sink(pdf, verbose, |data| logger.info(data))?;
    if listing.is_none() {
        let mut message = input_name.to_vec();
        message.extend_from_slice(b" has no embedded files\n");
        logger.info(message)?;
    }
    Ok(())
}

fn emit_show_attachment<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    logger: &crate::QPDFLogger,
    key: &[u8],
) -> Result<()> {
    let filespec = {
        let mut embedded_files = pdf.embedded_files();
        embedded_files.get_embedded_file(key)?
    }
    .ok_or_else(|| raw_attachment_error(key, b" not found"))?;
    let mut filespec = FileSpec::new(filespec, pdf)?;
    let embedded_file = filespec
        .embedded_file()?
        .ok_or_else(|| raw_attachment_error(key, b" has no resolvable /EmbeddedFile stream"))?;
    logger.save_to_standard_output(true)?;
    let save = logger.get_save()?;
    let mut sink = PipelineHandleSink(save);
    let _ = embedded_file.pipe_stream_data(&mut sink)?;
    Ok(())
}

fn raw_attachment_error(key: &[u8], suffix: &[u8]) -> Error {
    let mut message = b"attachment ".to_vec();
    message.extend_from_slice(key);
    message.extend_from_slice(suffix);
    Error::SystemBytes(message)
}

/// This is a convenience wrapper around [`FileSpec::create_file_spec_from_path`] +
/// [`crate::embedded_files::insert_embedded_file`] that:
///
/// 1. Streams the file at `path` through the deferred provider factory.
/// 2. Derives the name-tree key and `/F`/`/UF` filename from the path's
///    **basename** (the last component of the path).
/// 3. Builds a `/Filespec` + `/EmbeddedFile` pair without installing a local
///    filter. `/Params /Size` and `/Params /CheckSum` reflect the **raw** bytes,
///    as required by ISO 32000-1 §7.11.4.
/// 4. Inserts the pair into the catalog's `/Names /EmbeddedFiles` name tree
///    under the UTF-8 `key` (which may differ from the basename if the caller
///    wants an explicit tree key).
///
/// Returns the [`ObjectRef`] of the newly created `/Filespec` dictionary.
///
/// # Parameters
///
/// - `pdf` — the target document (must be mutable).
/// - `key` — the name-tree key used to look up the attachment later (e.g. the
///   basename encoded as bytes, or any other agreed-upon string).
/// - `path` — path to the file on disk; its basename is used for `/F`/`/UF`.
///
/// # Errors
///
/// - [`Error::Io`] if the file cannot be opened or read.
/// - [`Error::Unsupported`] if the path has no basename or the basename is not
///   valid UTF-8.
/// - Any error from [`FileSpec::create_file_spec_from_path`] or
///   [`crate::embedded_files::insert_embedded_file`].
///
/// # Example
///
/// ```no_run
/// use std::io::Cursor;
/// use flpdf::Pdf;
///
/// # fn main() -> flpdf::Result<()> {
/// let mut pdf: Pdf<Cursor<Vec<u8>>> = todo!();
/// let fs_ref = flpdf::add_attachment_from_path(
///     &mut pdf,
///     b"README.txt",
///     "/tmp/README.txt",
/// )?;
/// println!("inserted filespec at {fs_ref}");
/// # Ok(())
/// # }
/// ```
#[allow(deprecated)]
#[deprecated(
    note = "no qpdf counterpart; this library-level path attachment convenience wrapper is flpdf-specific (QPDFJob.cc:2046-2087) -- do not add new callers"
)]
pub fn add_attachment_from_path<R, P>(pdf: &mut Pdf<R>, key: &[u8], path: P) -> Result<ObjectRef>
where
    R: Read + Seek,
    P: AsRef<Path>,
{
    let path = path.as_ref();

    // Derive the basename for /F and /UF.
    let basename = path
        .file_name()
        .ok_or_else(|| {
            Error::Unsupported(format!(
                "add_attachment_from_path: path has no basename: {}",
                path.display()
            ))
        })?
        .to_str()
        .ok_or_else(|| {
            Error::Unsupported(format!(
                "add_attachment_from_path: basename is not valid UTF-8: {}",
                path.display()
            ))
        })?;

    // Build the /Filespec + /EmbeddedFile through qpdf's path-provider route.
    // `create_file_spec` initially uses the same Unicode name for `/F` and
    // `/UF`; replace `/F` with the independent ASCII fallback while retaining
    // the original Unicode `/UF` value, matching FileSpecBuilder's behavior.
    let filespec_handle = FileSpec::create_file_spec_from_path(pdf, basename.as_bytes(), path)?;
    let filespec_ref = filespec_handle
        .object_ref()
        .expect("create_file_spec_from_path must create an indirect Filespec");
    let fallback = ascii_filename_fallback(basename);
    {
        let mut filespec = FileSpec::new(pdf.get_object_handle(filespec_ref), pdf)?;
        filespec.set_filename(basename.as_bytes(), Some(fallback.as_slice()))?;
    }
    crate::embedded_files::insert_embedded_file(pdf, key, filespec_ref)?;

    Ok(filespec_ref)
}

/// Return an ASCII-safe `/F` fallback while preserving readable ASCII filename parts.
#[deprecated(
    note = "no qpdf counterpart; qpdf accepts an explicit compatibility filename instead of deriving this fallback (QPDFFileSpecObjectHelper.cc:118-130) -- do not add new callers"
)]
pub fn ascii_filename_fallback(filename: &str) -> Vec<u8> {
    let fallback: String = filename
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') {
                ch
            } else {
                '_'
            }
        })
        .collect();

    if fallback.is_empty() || fallback.bytes().all(|b| b == b'.' || b == b'_') {
        b"attachment".to_vec()
    } else {
        fallback.into_bytes()
    }
}

// ── Attachment extraction API ─────────────────────────────────────────────────

/// Extract the decoded payload of an attachment identified by `key`.
///
/// Looks up `key` in the catalog's `/Names /EmbeddedFiles` name tree, resolves
/// the associated `/Filespec` dictionary, and decodes the `/EmbeddedFile` stream
/// (applying the filter chain, e.g. FlateDecode) to return the original file
/// contents.
///
/// # Note on direct-dict filespecs
///
/// Name-tree entries whose value is a direct `/Filespec` dictionary (rather than
/// an indirect reference) are not surfaced by the underlying
/// [`crate::embedded_files::list_embedded_files`] enumeration; they are
/// skipped with the same limitation documented there. Only attachments with
/// indirect-reference values are extractable by this function.
///
/// # Errors
///
/// - [`Error::Unsupported`] when `key` is not present in the name tree.  The
///   error message includes the missing key name and a sorted list of available
///   keys so the caller can emit an actionable diagnostic.
/// - [`Error::Unsupported`] when the filespec at `key` has no resolvable
///   `/EmbeddedFile` stream (e.g. the `/EF` sub-dictionary is absent or
///   malformed).
/// - Any error from canonical ObjectHandle resolution or the filter decoder.
///
/// # Example
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::Pdf;
///
/// # fn main() -> flpdf::Result<()> {
/// let mut pdf = Pdf::open(BufReader::new(File::open("with-attachment.pdf")?))?;
/// let bytes = flpdf::extract_attachment(&mut pdf, b"report.pdf")?;
/// println!("extracted {} bytes", bytes.len());
/// # Ok(())
/// # }
/// ```
#[deprecated(
    note = "no qpdf counterpart; QPDFJob::doShowAttachment streams to its save pipeline instead of returning a library Vec (QPDFJob.cc:914-926) -- do not add new callers"
)]
pub fn extract_attachment<R: Read + Seek>(pdf: &mut Pdf<R>, key: &[u8]) -> Result<Vec<u8>> {
    // Look up all entries in the name tree.
    let entries = crate::embedded_files::list_embedded_files(pdf)?;

    // Find the target key.
    let filespec_ref = match entries.iter().find(|(k, _)| k.as_slice() == key) {
        Some((_, r)) => *r,
        None => {
            // Collect available keys for an actionable error message.
            // Sorted so the diagnostic is deterministic / reproducible,
            // independent of name-tree iteration order (CodeRabbit nitpick).
            let mut available: Vec<String> = entries
                .iter()
                .map(|(k, _)| String::from_utf8_lossy(k).into_owned())
                .collect();
            available.sort_unstable();
            let hint = if available.is_empty() {
                " (no attachments present)".to_string()
            } else {
                format!(" (available keys: {})", available.join(", "))
            };
            return Err(Error::Unsupported(format!(
                "extract_attachment: key {:?} not found{}",
                String::from_utf8_lossy(key),
                hint,
            )));
        }
    };

    // Resolve the filespec and decode its embedded file stream.
    let mut fs = FileSpec::new(pdf.get_object_handle(filespec_ref), pdf)?;
    let ef = fs.embedded_file()?.ok_or_else(|| {
        Error::Unsupported(format!(
            "extract_attachment: key {:?} has no resolvable /EmbeddedFile stream \
             (the /EF sub-dictionary may be absent or malformed)",
            String::from_utf8_lossy(key),
        ))
    })?;
    // `payload` hands back a fresh `Rc`, so unwrap it instead of copying the
    // whole decoded attachment; the clone is only the fallback for a payload
    // that someone else still holds.
    Ok(Rc::try_unwrap(ef.payload()?).unwrap_or_else(|shared| (*shared).clone()))
}

/// Write the decoded payload of attachment `key` to `out`.
///
/// Decodes the embedded file stream via [`extract_attachment`] and writes all
/// bytes to `out` in a single [`Write::write_all`] call.
///
/// # Errors
///
/// Propagates all errors from [`extract_attachment`] and from `out.write_all`.
///
/// # Example
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::Pdf;
///
/// # fn main() -> flpdf::Result<()> {
/// let mut pdf = Pdf::open(BufReader::new(File::open("with-attachment.pdf")?))?;
/// let mut buf = Vec::new();
/// flpdf::write_attachment(&mut pdf, b"report.pdf", &mut buf)?;
/// println!("wrote {} bytes", buf.len());
/// # Ok(())
/// # }
/// ```
#[allow(deprecated)]
#[deprecated(
    note = "no qpdf counterpart; QPDFJob::doShowAttachment owns its output pipeline instead of accepting a generic Write sink (QPDFJob.cc:914-926) -- do not add new callers"
)]
pub fn write_attachment<R: Read + Seek, W: Write>(
    pdf: &mut Pdf<R>,
    key: &[u8],
    out: &mut W,
) -> Result<()> {
    let bytes = extract_attachment(pdf, key)?;
    out.write_all(&bytes)?;
    Ok(())
}

/// Write the decoded payload of attachment `key` to a file at `path`.
///
/// Creates (or truncates) the file at `path` and writes the decoded stream
/// bytes.  This is the library-side counterpart of the CLI `-o` option
/// (wiring of the `-o` flag is handled by the CLI layer, not here).
///
/// # Errors
///
/// - Any error from [`extract_attachment`].
/// - [`Error::Io`] if the file cannot be created or written.
///
/// # Example
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::Pdf;
///
/// # fn main() -> flpdf::Result<()> {
/// let mut pdf = Pdf::open(BufReader::new(File::open("with-attachment.pdf")?))?;
/// flpdf::extract_attachment_to_path(&mut pdf, b"report.pdf", "/tmp/out.pdf")?;
/// # Ok(())
/// # }
/// ```
#[allow(deprecated)]
#[deprecated(
    note = "no qpdf counterpart; QPDFJob::doShowAttachment writes through its save pipeline instead of exposing a path helper (QPDFJob.cc:914-926) -- do not add new callers"
)]
pub fn extract_attachment_to_path<R, P>(pdf: &mut Pdf<R>, key: &[u8], path: P) -> Result<()>
where
    R: Read + Seek,
    P: AsRef<Path>,
{
    let bytes = extract_attachment(pdf, key)?;
    std::fs::write(path, &bytes)?;
    Ok(())
}
#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use super::super::{JobExitCode, QPDFJob};
    use super::extract_attachment;
    use super::AttachmentAddOptions;
    use super::PipelineHandleSink;
    use crate::pipeline::test_support::NthWriteFailure;
    use crate::pipeline::{Pipeline, PipelineError, PipelineHandle, PipelineResult};
    use crate::{Pdf, PdfOpenOptions, QPDFLogger};
    use std::io::Cursor;
    use std::sync::{Arc, Mutex};

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

    type CaptureBytes = Arc<Mutex<Vec<u8>>>;

    impl Pipeline for Capture {
        fn identifier(&self) -> &str {
            "attachment test capture"
        }

        fn write(&mut self, data: &[u8]) -> PipelineResult<()> {
            self.bytes
                .lock()
                .map_err(|_| PipelineError::runtime("capture mutex poisoned"))?
                .extend_from_slice(data);
            Ok(())
        }

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

    #[test]
    fn capture_pipeline_exposes_its_identifier() {
        let capture = Capture {
            bytes: Arc::new(Mutex::new(Vec::new())),
        };
        assert_eq!(Pipeline::identifier(&capture), "attachment test capture");
        let sink = PipelineHandleSink(PipelineHandle::new(Capture {
            bytes: Arc::new(Mutex::new(Vec::new())),
        }));
        assert_eq!(Pipeline::identifier(&sink), "qpdf job attachment save");
    }

    fn job_with_captures() -> (QPDFJob, CaptureBytes, CaptureBytes) {
        let info = Arc::new(Mutex::new(Vec::new()));
        let save = Arc::new(Mutex::new(Vec::new()));
        let logger = QPDFLogger::create();
        logger.set_output_streams(
            Some(PipelineHandle::new(Capture {
                bytes: Arc::clone(&info),
            })),
            None,
        );
        logger
            .set_save(
                Some(PipelineHandle::new(Capture {
                    bytes: Arc::clone(&save),
                })),
                false,
            )
            .expect("capture save sink");
        let mut job = QPDFJob::new();
        job.set_logger(logger);
        (job, info, save)
    }

    fn page_mode(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> Option<Vec<u8>> {
        let root_ref = pdf.root_ref().expect("catalog root");
        let root = pdf.get_object_handle(root_ref);
        root.try_is_scalar().expect("resolve catalog");
        root.try_get_key(b"/PageMode").unwrap().as_name()
    }

    #[test]
    fn list_attachments_owns_no_embedded_files_message_and_completion() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ))
        .to_vec();
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(Cursor::new(bytes), "minimal.pdf", PdfOpenOptions::default())
            .expect("open fixture");

        let status = job
            .list_attachments(&mut pdf, false)
            .expect("list attachments");

        assert_eq!(status, JobExitCode::Success);
        assert_eq!(
            *info.lock().expect("info capture"),
            b"minimal.pdf has no embedded files\n"
        );
    }

    #[test]
    fn show_attachment_does_not_use_save_sink_when_key_is_missing() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let (mut job, _, save) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.as_slice()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let error = job
            .show_attachment(&mut pdf, b"missing")
            .expect_err("missing attachment must fail");

        assert!(error.to_string().contains("not found"));
        assert!(save.lock().expect("save capture").is_empty());
    }

    #[test]
    fn show_attachment_error_preserves_raw_key_bytes() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let (mut job, _, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.as_slice()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let key = b"quote-\"-\\-\r-\t-\x01-\xff";
        let error = job
            .show_attachment(&mut pdf, key)
            .expect_err("missing attachment must fail");

        assert_eq!(
            error.raw_message(),
            Some(b"attachment quote-\"-\\-\r-\t-\x01-\xff not found".as_slice())
        );
    }

    #[test]
    fn list_attachments_writes_qpdf_header_to_job_info_pipeline() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ));
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "attachment-two-page.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        assert_eq!(
            job.list_attachments(&mut pdf, false)
                .expect("list attachments"),
            JobExitCode::Success
        );
        assert_eq!(
            *info.lock().expect("info capture"),
            b"attachment.txt -> 8,0\n"
        );
    }

    #[test]
    fn show_attachment_writes_decoded_bytes_to_job_save_pipeline() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ));
        let (mut job, _, save) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "attachment-two-page.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        assert_eq!(
            job.show_attachment(&mut pdf, b"attachment.txt")
                .expect("show attachment"),
            JobExitCode::Success
        );
        assert_eq!(
            *save.lock().expect("save capture"),
            b"This is a small text attachment for PDF fixture testing.\nGenerated by flpdf test corpus setup.\n"
        );
    }

    #[test]
    fn show_attachment_decode_failure_is_a_warning_for_an_existing_key() {
        let mut bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ))
        .to_vec();
        // Object 8's EF stream begins at this fixture offset. A broken zlib
        // header is a decode warning in qpdf's pipeStreamData route.
        bytes[1187] = 0;
        let (mut job, _, save) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes),
                "corrupt-attachment.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        assert_eq!(
            job.show_attachment(&mut pdf, b"attachment.txt")
                .expect("decode failure should complete with a warning"),
            JobExitCode::Warning
        );
        assert!(save.lock().expect("save capture").is_empty());
    }

    #[test]
    fn show_attachment_rejects_a_filespec_without_an_embedded_stream() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ));
        let (mut job, _, save) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "missing-embedded-stream.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");
        let filespec_ref = crate::ObjectRef::new(5, 0);
        let filespec = pdf.get_object_handle(filespec_ref);
        filespec.try_is_scalar().expect("resolve filespec");
        filespec.remove_key(b"/EF");

        let error = job
            .show_attachment(&mut pdf, b"attachment.txt")
            .expect_err("missing embedded stream must fail");
        assert!(error
            .to_string()
            .contains("no resolvable /EmbeddedFile stream"));
        assert!(save.lock().expect("save capture").is_empty());
    }

    #[test]
    fn add_attachment_owns_page_mode_metadata_name_tree_and_verbose_diagnostic() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"attachment payload").expect("write payload");
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        job.add_attachment(
            &mut pdf,
            AttachmentAddOptions {
                path: attachment.clone(),
                key: b"payload-key".to_vec(),
                filename: b"renamed.txt".to_vec(),
                mimetype: Some(b"text/plain".to_vec()),
                description: Some(b"test description".to_vec()),
                creation_date: Some(b"D:20240101120000Z".to_vec()),
                modification_date: Some(b"D:20240102130000Z".to_vec()),
                replace: false,
                verbose: true,
            },
        )
        .expect("add attachment");

        assert_eq!(page_mode(&mut pdf), Some(b"UseAttachments".to_vec()));

        assert_eq!(
            job.list_attachments(&mut pdf, true)
                .expect("list attachments"),
            JobExitCode::Success
        );

        let info = info.lock().expect("info capture");
        let info = String::from_utf8_lossy(&info);
        assert!(info.contains("qpdf: attached "));
        assert!(info.contains(" as renamed.txt with key payload-key\n"));
        assert!(info.contains("payload-key -> "));
        assert!(info.contains("  description: test description\n"));
        assert!(info.contains("  preferred name: renamed.txt\n"));
        assert!(info.contains("      mime type: text/plain\n"));
        assert!(info.contains("      creation date: D:20240101120000Z\n"));
        assert!(info.contains("      modification date: D:20240102130000Z\n"));
    }

    #[cfg(unix)]
    #[test]
    fn add_attachment_verbose_diagnostic_preserves_non_utf8_filename_and_key() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"attachment payload").expect("write payload");
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        // Invalid UTF-8: a lone continuation byte, which `from_utf8_lossy`
        // would replace with U+FFFD (b"\xEF\xBF\xBD").
        let non_utf8_filename = vec![b'f', 0x80, b'.', b't', b'x', b't'];
        let non_utf8_key = vec![b'k', 0x80];
        job.add_attachment(
            &mut pdf,
            AttachmentAddOptions {
                path: attachment,
                key: non_utf8_key.clone(),
                filename: non_utf8_filename.clone(),
                mimetype: None,
                description: None,
                creation_date: Some(b"D:20240101120000Z".to_vec()),
                modification_date: Some(b"D:20240101120000Z".to_vec()),
                replace: false,
                verbose: true,
            },
        )
        .expect("add attachment");

        let info = info.lock().expect("info capture");
        let mut expected = b" as ".to_vec();
        expected.extend_from_slice(&non_utf8_filename);
        expected.extend_from_slice(b" with key ");
        expected.extend_from_slice(&non_utf8_key);
        expected.push(b'\n');
        assert!(
            info.windows(expected.len())
                .any(|window| window == expected),
            "expected raw non-UTF-8 bytes in verbose diagnostic, got {info:?}"
        );
    }

    fn add_options(path: std::path::PathBuf, key: &[u8]) -> AttachmentAddOptions {
        AttachmentAddOptions {
            path,
            key: key.to_vec(),
            filename: b"payload.txt".to_vec(),
            mimetype: None,
            description: None,
            creation_date: Some(b"D:20240101120000Z".to_vec()),
            modification_date: Some(b"D:20240101120000Z".to_vec()),
            replace: false,
            verbose: false,
        }
    }

    #[test]
    fn add_attachment_defaults_dates_and_preserves_existing_page_mode() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"payload").expect("write payload");
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let root_ref = pdf.root_ref().expect("catalog root");
        let root = pdf.get_object_handle(root_ref);
        root.try_is_scalar().expect("resolve catalog");
        root.replace_key(b"/PageMode", crate::ObjectHandle::name(b"UseNone".to_vec()))
            .expect("set existing page mode");

        let mut options = add_options(attachment, b"payload-key");
        options.creation_date = None;
        options.modification_date = None;
        job.add_attachment(&mut pdf, options)
            .expect("add attachment");

        assert_eq!(page_mode(&mut pdf), Some(b"UseNone".to_vec()));

        assert_eq!(
            job.list_attachments(&mut pdf, true)
                .expect("list attachments"),
            JobExitCode::Success
        );
        let info = info.lock().expect("info capture");
        let info = String::from_utf8_lossy(&info);
        assert!(info.contains("      creation date: D:"), "{info:?}");
        assert!(info.contains("      modification date: D:"), "{info:?}");
    }

    #[test]
    fn add_attachment_aggregates_duplicate_error_and_replaces_when_requested() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let first = dir.path().join("first.txt");
        let second = dir.path().join("second.txt");
        std::fs::write(&first, b"first").expect("write first payload");
        std::fs::write(&second, b"second").expect("write second payload");
        let (mut job, _, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "input.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        job.add_attachment(&mut pdf, add_options(first, b"duplicate"))
            .expect("add first attachment");
        job.add_attachment(
            &mut pdf,
            add_options(dir.path().join("first.txt"), b"other"),
        )
        .expect("add second attachment");
        let error = job
            .add_attachments(
                &mut pdf,
                &[
                    add_options(second.clone(), b"duplicate"),
                    add_options(second.clone(), b"other"),
                ],
            )
            .expect_err("duplicate must fail without replace");
        assert_eq!(
            error.to_string(),
            "input.pdf already has attachments with the following keys: duplicate, other; use --replace to replace or --key to specify a different key"
        );

        let mut replacement = add_options(second, b"duplicate");
        replacement.replace = true;
        job.add_attachment(&mut pdf, replacement)
            .expect("replace attachment");
        assert_eq!(
            extract_attachment(&mut pdf, b"duplicate").expect("extract replacement"),
            b"second"
        );
    }

    #[test]
    fn add_attachment_accepts_raw_mimetype_at_the_library_boundary() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"payload").expect("write payload");
        let (mut job, info, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");
        let mut options = add_options(attachment, b"payload-key");
        options.mimetype = Some(b"textplain".to_vec());

        job.add_attachment(&mut pdf, options)
            .expect("library boundary must not validate mimetype syntax");
        assert_eq!(
            job.list_attachments(&mut pdf, true)
                .expect("list attachments"),
            JobExitCode::Success
        );
        let info = info.lock().expect("info capture");
        let info = String::from_utf8_lossy(&info);
        assert!(info.contains("      mime type: textplain\n"), "{info:?}");
    }

    #[test]
    fn add_attachment_propagates_verbose_info_pipeline_failure() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"payload").expect("write payload");

        let logger = QPDFLogger::create();
        logger.set_info(Some(PipelineHandle::new(NthWriteFailure::new(1))));
        let mut job = QPDFJob::new();
        job.set_logger(logger);
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let mut options = add_options(attachment, b"payload-key");
        options.verbose = true;
        let error = job
            .add_attachment(&mut pdf, options)
            .expect_err("verbose info sink failure must propagate");
        assert_eq!(error.to_string(), "sink write failure 1");
    }

    fn rootless_fixture_bytes() -> Vec<u8> {
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let object_offset = bytes.len();
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref_offset = bytes.len();
        bytes.extend_from_slice(
            format!(
                "xref\n0 2\n0000000000 65535 f \n{object_offset:010} 00000 n \ntrailer\n<< /Size 2 >>\nstartxref\n{xref_offset}\n%%EOF\n"
            )
            .as_bytes(),
        );
        bytes
    }

    #[test]
    fn set_attachment_page_mode_rejects_a_pdf_without_catalog_root() {
        let mut pdf = Pdf::open(Cursor::new(rootless_fixture_bytes())).expect("open fixture");
        assert!(
            pdf.root_ref().is_none(),
            "fixture must have no catalog root"
        );
        let job = QPDFJob::new();
        let error = job
            .set_attachment_page_mode(&mut pdf)
            .expect_err("missing root must be rejected, matching qpdf's getRoot() throw");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    #[test]
    fn add_attachment_rejects_a_pdf_without_catalog_root() {
        let dir = tempfile::tempdir().expect("temporary directory");
        let attachment = dir.path().join("payload.txt");
        std::fs::write(&attachment, b"payload").expect("write payload");
        let (mut job, _, _) = job_with_captures();
        let mut pdf = Pdf::open(Cursor::new(rootless_fixture_bytes())).expect("open fixture");

        let error = job
            .add_attachment(&mut pdf, add_options(attachment, b"payload-key"))
            .expect_err("missing root must be rejected before creating any objects");
        assert_eq!(error.to_string(), "unable to find /Root dictionary");
    }

    #[test]
    fn add_attachments_with_empty_batch_leaves_page_mode_untouched() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let (mut job, _, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");
        assert_eq!(
            page_mode(&mut pdf),
            None,
            "fixture must start without /PageMode"
        );

        job.add_attachments(&mut pdf, &[])
            .expect("empty batch must be a no-op");

        assert_eq!(
            page_mode(&mut pdf),
            None,
            "empty batch must not introduce /PageMode /UseAttachments"
        );
    }

    #[test]
    fn add_attachment_reports_missing_file_without_os_error_suffix() {
        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let missing = dir.path().join("does-not-exist.bin");
        let (mut job, _, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let error = job
            .add_attachment(&mut pdf, add_options(missing.clone(), b"payload-key"))
            .expect_err("missing source file must fail");
        assert_eq!(
            error.to_string(),
            format!("open {}: No such file or directory", missing.display())
        );
    }

    #[cfg(unix)]
    #[test]
    fn add_attachment_reports_permission_denied_without_os_error_suffix() {
        use std::os::unix::fs::PermissionsExt;

        let bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ));
        let dir = tempfile::tempdir().expect("temporary directory");
        let unreadable = dir.path().join("unreadable.bin");
        std::fs::write(&unreadable, b"payload").expect("write payload");
        std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000))
            .expect("restrict permissions");
        if std::fs::File::open(&unreadable).is_ok() {
            // Root (or CAP_DAC_OVERRIDE) bypasses Unix permission bits
            // entirely, so this scenario cannot be exercised as such. CI
            // runs unprivileged, so this branch is never taken there.
            return; // cov:ignore: only reachable when the test runs as root
        }
        let (mut job, _, _) = job_with_captures();
        let mut pdf = job
            .open(
                Cursor::new(bytes.to_vec()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open fixture");

        let error = job
            .add_attachment(&mut pdf, add_options(unreadable.clone(), b"payload-key"))
            .expect_err("unreadable source file must fail");
        assert_eq!(
            error.to_string(),
            format!("open {}: Permission denied", unreadable.display())
        );
    }

    // ── copy_attachments ─────────────────────────────────────────────────────

    use super::{AttachmentCopyOptions, AttachmentCopySource};

    fn minimal_fixture_bytes() -> Vec<u8> {
        include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/minimal.pdf"
        ))
        .to_vec()
    }

    /// Build a fresh minimal-fixture `Pdf` (own throwaway `QPDFJob`, not the
    /// caller's) with `entries` embedded through [`QPDFJob::add_attachments`].
    fn pdf_with_attachments(
        dir: &std::path::Path,
        prefix: &str,
        entries: &[(&[u8], &[u8])],
    ) -> Pdf<Cursor<Vec<u8>>> {
        let mut job = QPDFJob::new();
        let mut pdf = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "fixture.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open minimal fixture");
        let options: Vec<AttachmentAddOptions> = entries
            .iter()
            .enumerate()
            .map(|(i, (key, content))| {
                let path = dir.join(format!("{prefix}-{i}.bin"));
                std::fs::write(&path, content).expect("write payload");
                AttachmentAddOptions {
                    path,
                    key: key.to_vec(),
                    filename: key.to_vec(),
                    mimetype: None,
                    description: None,
                    creation_date: None,
                    modification_date: None,
                    replace: false,
                    verbose: false,
                }
            })
            .collect();
        job.add_attachments(&mut pdf, &options)
            .expect("build attachment fixture");
        pdf
    }

    fn copy_options(
        path: std::path::PathBuf,
        prefix: &[u8],
        verbose: bool,
    ) -> AttachmentCopyOptions {
        AttachmentCopyOptions {
            path,
            password: Vec::new(),
            prefix: prefix.to_vec(),
            verbose,
        }
    }

    #[test]
    fn copy_attachments_copies_object_graph_with_prefix_and_verbose_diagnostics() {
        let source_bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ));
        let mut source =
            Pdf::open(Cursor::new(source_bytes.to_vec())).expect("open source fixture");

        let (mut job, info, _) = job_with_captures();
        let mut target = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open target fixture");

        job.copy_attachments(
            &mut target,
            &mut source,
            &copy_options(std::path::PathBuf::from("donor.pdf"), b"src-", true),
        )
        .expect("copy attachments");

        assert_eq!(
            page_mode(&mut target),
            Some(b"UseAttachments".to_vec()),
            "copyAttachments always sets /PageMode, even for a single entry"
        );

        let copied =
            extract_attachment(&mut target, b"src-attachment.txt").expect("extract copied file");
        assert_eq!(
            copied,
            b"This is a small text attachment for PDF fixture testing.\nGenerated by flpdf test corpus setup.\n"
        );

        let info = String::from_utf8_lossy(&info.lock().expect("info capture")).into_owned();
        assert!(
            info.contains("qpdf: copying attachments from donor.pdf\n"),
            "info was: {info:?}"
        );
        assert!(
            info.contains("  attachment.txt -> src-attachment.txt\n"),
            "info was: {info:?}"
        );
    }

    #[test]
    fn copy_attachments_with_opener_survives_a_dropped_owned_donor() {
        // The opener owns each donor and drops it at the end of its iteration,
        // before the target is written -- matching qpdf's copyAttachments,
        // which drops each per-donor `QPDF` (`QPDFJob.cc:2100`). The copied
        // attachment must stay readable after the owned in-memory donor is
        // released; `copy_attachments_with_opener` reserves stream data via
        // qpdf's immediate-copy contract so a provider-backed donor cannot
        // leave a dangling deferred stream behind either.
        let donor_bytes = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        ))
        .to_vec();
        let expected = {
            let mut donor = Pdf::open(Cursor::new(donor_bytes.clone())).expect("open donor");
            extract_attachment(&mut donor, b"attachment.txt").expect("donor attachment")
        };

        let mut target =
            Pdf::open(Cursor::new(minimal_fixture_bytes())).expect("open target fixture");
        let mut job = QPDFJob::new();
        job.set_input_name("target.pdf");
        let options = [copy_options(
            std::path::PathBuf::from("donor.pdf"),
            b"a_",
            false,
        )];

        job.copy_attachments_with_opener::<_, _, crate::Error>(
            &mut target,
            &options,
            |_job, _option| {
                let reader: Box<dyn crate::ReadSeek> = Box::new(Cursor::new(donor_bytes.clone()));
                Pdf::open(reader)
            },
        )
        .expect("copy from an owned in-memory donor succeeds");

        let copied = extract_attachment(&mut target, b"a_attachment.txt")
            .expect("copied attachment survives the dropped donor");
        assert_eq!(copied, expected);
    }

    #[test]
    fn copy_attachments_many_with_no_sources_leaves_the_target_untouched() {
        let mut target =
            Pdf::open(Cursor::new(minimal_fixture_bytes())).expect("open target fixture");
        let mut job = QPDFJob::new();
        let mut sources: [AttachmentCopySource<'_, Cursor<Vec<u8>>>; 0] = [];

        job.copy_attachments_many(&mut target, &mut sources)
            .expect("an empty donor batch is a no-op");

        let root = target.root_handle().expect("target root");
        assert!(
            root.try_get_key(b"/PageMode")
                .expect("PageMode lookup")
                .is_null(),
            "qpdf never reaches copyAttachments for an empty configuration"
        );
    }

    #[test]
    fn copy_attachments_many_processes_all_sources_before_aggregating_duplicates() {
        let dir = tempfile::tempdir().expect("temporary directory");
        let mut first = pdf_with_attachments(
            dir.path(),
            "first",
            &[(b"first".as_slice(), b"first payload".as_slice())],
        );
        let mut second = pdf_with_attachments(
            dir.path(),
            "second",
            &[
                (b"first".as_slice(), b"duplicate payload".as_slice()),
                (b"second".as_slice(), b"second payload".as_slice()),
            ],
        );
        let mut target =
            Pdf::open(Cursor::new(minimal_fixture_bytes())).expect("open target fixture");
        let mut job = QPDFJob::new();
        job.set_input_name("target.pdf");
        let first_options = copy_options(std::path::PathBuf::from("first.pdf"), b"", false);
        let second_options = copy_options(std::path::PathBuf::from("second.pdf"), b"", false);
        let mut sources = [
            AttachmentCopySource {
                source: &mut first,
                options: first_options,
            },
            AttachmentCopySource {
                source: &mut second,
                options: second_options,
            },
        ];

        let error = job
            .copy_attachments_many(&mut target, &mut sources)
            .expect_err("duplicate keys from later sources must be reported");
        assert_eq!(
            error.to_string(),
            "target.pdf already has attachments with keys that conflict with attachments from other files: file: second.pdf, key: first. Use --prefix with --copy-attachments-from or manually copy individual attachments."
        );
        assert_eq!(
            extract_attachment(&mut target, b"first").expect("first attachment"),
            b"first payload"
        );
        assert_eq!(
            extract_attachment(&mut target, b"second").expect("second attachment"),
            b"second payload"
        );
    }

    #[test]
    fn copy_attachments_aggregates_duplicate_keys_and_still_copies_the_rest() {
        let dir = tempfile::tempdir().expect("temporary directory");
        let mut source = pdf_with_attachments(
            dir.path(),
            "src",
            &[
                (b"a".as_slice(), b"content a".as_slice()),
                (b"b".as_slice(), b"content b".as_slice()),
                (b"c".as_slice(), b"content c".as_slice()),
            ],
        );
        let mut target = pdf_with_attachments(
            dir.path(),
            "tgt",
            &[
                (b"a".as_slice(), b"existing a".as_slice()),
                (b"b".as_slice(), b"existing b".as_slice()),
            ],
        );

        let mut job = QPDFJob::new();
        job.set_input_name("target.pdf");
        let error = job
            .copy_attachments(
                &mut target,
                &mut source,
                &copy_options(std::path::PathBuf::from("donor.pdf"), b"", false),
            )
            .expect_err("colliding keys must be reported");

        assert_eq!(
            error.to_string(),
            "target.pdf already has attachments with keys that conflict with attachments from other files: file: donor.pdf, key: a; file: donor.pdf, key: b. Use --prefix with --copy-attachments-from or manually copy individual attachments."
        );

        // qpdf processes every entry before throwing: the non-colliding key
        // is still copied even though the batch as a whole reports an error.
        let copied = extract_attachment(&mut target, b"c").expect("non-colliding key copied");
        assert_eq!(copied, b"content c");
        assert!(target
            .embedded_files()
            .get_embedded_file(b"a")
            .expect("lookup")
            .is_some());
    }

    #[test]
    fn copy_attachments_returns_ok_for_an_empty_source_and_still_sets_page_mode() {
        let (mut job, _, _) = job_with_captures();
        let mut source = Pdf::open(Cursor::new(minimal_fixture_bytes())).expect("open donor");
        let mut target = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open target fixture");

        job.copy_attachments(
            &mut target,
            &mut source,
            &copy_options(std::path::PathBuf::from("donor.pdf"), b"", false),
        )
        .expect("empty source copies nothing but still succeeds");

        assert_eq!(page_mode(&mut target), Some(b"UseAttachments".to_vec()));
        assert!(!job.has_warnings());
    }

    #[test]
    fn copy_attachments_installs_the_job_logger_on_source_as_well_as_target() {
        let (mut job, _, _) = job_with_captures();
        let mut source = Pdf::open(Cursor::new(minimal_fixture_bytes())).expect("open donor");
        let mut target = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open target fixture");

        // Source starts with its own default logger, distinct from the job's.
        assert_ne!(source.logger(), job.logger());

        job.copy_attachments(
            &mut target,
            &mut source,
            &copy_options(std::path::PathBuf::from("donor.pdf"), b"", false),
        )
        .expect("empty source copy succeeds");

        assert_eq!(
            source.logger(),
            job.logger(),
            "a lazy warning raised while traversing source must reach the job's own sink, \
             not source's original (possibly silent) logger"
        );
    }

    #[test]
    fn copy_attachments_records_source_warnings_even_with_no_attachments() {
        // A `startxref` offset past EOF forces `repair: true` recovery,
        // which records a warning repair diagnostic on the
        // opened document (qpdf: "file is damaged" / "Attempting to
        // reconstruct cross-reference table").
        let mut bytes = minimal_fixture_bytes();
        // The fixture's own trailer/startxref tail is replaced with one
        // pointing far beyond the file's length.
        let cut = bytes
            .windows(4)
            .rposition(|w| w == b"xref")
            .expect("fixture must contain an xref keyword");
        bytes.truncate(cut);
        bytes.extend_from_slice(
            b"xref\n0 1\n0000000000 65535 f \ntrailer\n<< /Size 1 /Root 1 0 R >>\nstartxref\n999999\n%%EOF\n",
        );
        let source_options = PdfOpenOptions {
            repair: true,
            ..PdfOpenOptions::default()
        };
        let mut source = Pdf::open_with_options(Cursor::new(bytes), source_options)
            .expect("open damaged donor with recovery");
        assert!(
            !source.repair_diagnostics().entries().is_empty(),
            "fixture must actually trigger a repair diagnostic"
        );

        let (mut job, _, _) = job_with_captures();
        let mut target = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open target fixture");

        job.copy_attachments(
            &mut target,
            &mut source,
            &copy_options(std::path::PathBuf::from("donor.pdf"), b"", false),
        )
        .expect("damaged-but-recovered source with no attachments still succeeds");

        assert!(
            job.has_warnings(),
            "source's repair diagnostics must fold into the job's own warning state"
        );
    }

    #[test]
    fn copy_attachments_encrypted_source_password_open_has_no_attachments() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../..",
            "/tests/fixtures/encrypted/v4-aes-128-r4.pdf"
        );
        let file = std::fs::File::open(path)
            .expect("encrypted fixture missing: tests/fixtures/encrypted/v4-aes-128-r4.pdf");
        let source_options = PdfOpenOptions {
            password: b"user-v4-aes".to_vec(),
            ..PdfOpenOptions::default()
        };
        let mut source = Pdf::open_with_options(std::io::BufReader::new(file), source_options)
            .expect("open encrypted source");

        let (mut job, _, _) = job_with_captures();
        let mut target = job
            .open(
                Cursor::new(minimal_fixture_bytes()),
                "minimal.pdf",
                PdfOpenOptions::default(),
            )
            .expect("open target fixture");

        job.copy_attachments(
            &mut target,
            &mut source,
            &copy_options(std::path::PathBuf::from(path), b"", false),
        )
        .expect("encrypted fixture has no attachments; copy must succeed with zero entries");
    }
}