rpdfium-doc 7676.6.2

Document-level features for rpdfium
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
//! PDF file specification dictionary (ISO 32000-2 section 7.11).
//!
//! A file specification dictionary identifies a file, either external or
//! embedded, and can provide platform-specific filenames plus an embedded
//! file stream reference.

use std::collections::HashMap;

use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::{Object, ObjectId, ObjectStore};

use crate::error::{DocError, DocResult};
use crate::name_tree::NameTree;

/// A parsed PDF file specification dictionary.
#[derive(Debug, Clone)]
pub struct FileSpec {
    /// File system name (`/FS`).
    pub file_system: Option<String>,
    /// Platform-independent filename (`/F`).
    pub filename: Option<String>,
    /// Unicode filename (`/UF`).
    pub unicode_filename: Option<String>,
    /// DOS filename (`/DOS`).
    pub dos_filename: Option<String>,
    /// Unix filename (`/Unix`).
    pub unix_filename: Option<String>,
    /// Indirect reference to the embedded file stream (from `/EF` sub-dict `/F`).
    pub embedded_file: Option<ObjectId>,
    /// Description of the file (`/Desc`).
    pub description: Option<String>,
    /// Decoded bytes of the embedded file stream, if available.
    ///
    /// Populated during parsing from the `/EF /F` stream when the
    /// ObjectStore can decode it.  Corresponds to the buffer returned by
    /// `FPDFAttachment_GetUnderlyingFile`.
    pub data: Option<Vec<u8>>,
}

/// Parse a file specification dictionary.
///
/// Returns `None` if the object is not a valid file specification dictionary.
pub fn parse_file_spec<S: PdfSource>(obj: &Object, store: &ObjectStore<S>) -> Option<FileSpec> {
    let resolved = store.deep_resolve(obj).ok()?;
    let dict = resolved.as_dict()?;

    let file_system = dict
        .get(&Name::fs())
        .and_then(|o| store.deep_resolve(o).ok())
        .and_then(|o| o.as_name().map(|n| n.as_str().into_owned()));

    let filename = extract_string(dict, &Name::f(), store);

    let unicode_filename = extract_string(dict, &Name::uf(), store);

    let dos_filename = extract_string(dict, &Name::dos(), store);

    let unix_filename = extract_string(dict, &Name::unix_name(), store);

    let ef_resolved = dict
        .get(&Name::ef())
        .and_then(|o| store.deep_resolve(o).ok());

    let embedded_file = ef_resolved
        .as_ref()
        .and_then(|o| o.as_dict().cloned())
        .and_then(|ef_dict| ef_dict.get(&Name::f()).and_then(|o| o.as_reference()));

    // Attempt to decode the embedded file stream bytes.
    let data: Option<Vec<u8>> = embedded_file.and_then(|stream_id| {
        let stream_obj = store.resolve(stream_id).ok()?;
        store.decode_stream(stream_obj).ok()
    });

    let description = extract_string(dict, &Name::desc(), store);

    Some(FileSpec {
        file_system,
        filename,
        unicode_filename,
        dos_filename,
        unix_filename,
        embedded_file,
        description,
        data,
    })
}

impl FileSpec {
    /// Returns the best available filename for this attachment.
    ///
    /// Prefers the Unicode filename (`/UF`) over the platform-encoded filename
    /// (`/F`), with further fallbacks to Unix and DOS filenames.
    ///
    /// Corresponds to `FPDFAttachment_GetName`.
    pub fn name(&self) -> Option<&str> {
        self.unicode_filename
            .as_deref()
            .or(self.filename.as_deref())
            .or(self.unix_filename.as_deref())
            .or(self.dos_filename.as_deref())
    }

    /// ADR-019 T2 alias for [`name()`](Self::name).
    ///
    /// Corresponds to `FPDFAttachment_GetName`.
    #[inline]
    pub fn attachment_get_name(&self) -> Option<&str> {
        self.name()
    }

    /// Deprecated — use [`attachment_get_name()`](Self::attachment_get_name).
    ///
    /// Corresponds to `FPDFAttachment_GetName`.
    #[deprecated(note = "use `attachment_get_name()` — matches upstream `FPDFAttachment_GetName`")]
    #[inline]
    pub fn get_name(&self) -> Option<&str> {
        self.name()
    }

    /// Returns the decoded bytes of the embedded file stream, if available.
    ///
    /// This is the primary data accessor for the embedded file content.
    /// Returns `None` if no embedded file data is present or if decoding
    /// failed during parsing.
    ///
    /// Corresponds to `FPDFAttachment_GetFile`.
    pub fn file_data(&self) -> Option<&[u8]> {
        self.data.as_deref()
    }

    /// ADR-019 T2 alias for [`file_data()`](Self::file_data).
    ///
    /// Corresponds to `FPDFAttachment_GetFile`.
    #[inline]
    pub fn attachment_get_file(&self) -> Option<&[u8]> {
        self.file_data()
    }

    /// Deprecated — use [`attachment_get_file()`](Self::attachment_get_file).
    ///
    /// Corresponds to `FPDFAttachment_GetFile`.
    #[deprecated(note = "use `attachment_get_file()` — matches upstream `FPDFAttachment_GetFile`")]
    #[inline]
    pub fn get_file(&self) -> Option<&[u8]> {
        self.file_data()
    }

    /// Returns the MIME type (Subtype) of the embedded file, if present.
    ///
    /// Reads the `/Subtype` entry from the embedded file stream dictionary.
    /// Returns `None` if no subtype is recorded.
    ///
    /// Corresponds to `FPDFAttachment_GetSubtype`.
    ///
    /// Note: `FileSpec` is parsed from the file specification dictionary; the
    /// subtype lives in the embedded file stream (`/EF /F` stream dict `/Subtype`).
    /// This field is not currently extracted during parsing — `None` is always
    /// returned in this release.
    pub fn subtype(&self) -> Option<&str> {
        None
    }

    /// Deprecated — use [`subtype()`](Self::subtype) — no public `FPDFAttachment_GetSubtype` API.
    #[deprecated(note = "use `subtype()` — there is no public `FPDFAttachment_GetSubtype` API")]
    #[inline]
    pub fn get_subtype(&self) -> Option<&str> {
        self.subtype()
    }

    /// Returns the raw decoded bytes of the embedded file, if available.
    ///
    /// This is populated during document parsing when the embedded file stream
    /// can be decoded.  Returns `None` if no embedded file data is present or
    /// if decoding failed during parsing.
    ///
    /// Corresponds to `FPDFAttachment_GetUnderlyingFile`.
    pub fn underlying_bytes(&self) -> Option<&[u8]> {
        self.data.as_deref()
    }

    /// Deprecated — use [`underlying_bytes()`](Self::underlying_bytes) — no public FPDF_* API.
    #[deprecated(
        note = "use `underlying_bytes()` — there is no public `FPDFAttachment_GetUnderlyingFile` API"
    )]
    #[inline]
    pub fn get_underlying_bytes(&self) -> Option<&[u8]> {
        self.underlying_bytes()
    }

    /// Set the filename.
    ///
    /// Updates both the PDF-encoded `/F` filename and the Unicode `/UF` filename
    /// in memory. To persist the change to a PDF file, use `EditDocument` in
    /// rpdfium-edit.
    pub fn set_filename(&mut self, filename: &str) -> DocResult<()> {
        self.filename = Some(encode_filename(filename));
        self.unicode_filename = Some(filename.to_string());
        Ok(())
    }

    /// Returns the best available filename, preferring Unicode over platform-specific.
    ///
    /// Deprecated: use [`name()`](Self::name) instead (primary) or
    /// [`get_name()`](Self::get_name) (upstream alias).
    #[deprecated(since = "0.1.0", note = "use name() instead")]
    #[inline]
    pub fn best_filename(&self) -> Option<&str> {
        self.name()
    }
}

/// Encode a platform path to PDF file specification format.
///
/// Converts platform-specific path separators to `/` and handles
/// Windows drive letters (e.g., `C:\dir\file.pdf` → `/C/dir/file.pdf`).
pub fn encode_filename(path: &str) -> String {
    let normalized = path.replace('\\', "/");
    // Handle Windows drive letter (e.g., "C:/..." → "/C/...")
    if normalized.len() >= 2 && normalized.as_bytes()[1] == b':' {
        let drive = &normalized[0..1];
        let rest = &normalized[2..];
        format!("/{drive}{rest}")
    } else {
        normalized
    }
}

/// Decode a PDF file specification path to platform format.
///
/// Reverses the encoding: converts `/` path separators to the platform
/// separator and restores drive letters on Windows-style paths.
pub fn decode_filename(path: &str) -> String {
    // Detect encoded drive letter: "/C/..." → "C:/..."
    if path.len() >= 3
        && path.starts_with('/')
        && path.as_bytes()[1].is_ascii_alphabetic()
        && path.as_bytes()[2] == b'/'
    {
        let drive = &path[1..2];
        let rest = &path[2..];
        return format!("{drive}:{rest}");
    }
    path.to_string()
}

/// Collect all embedded file attachments from the document catalog.
///
/// Walks the `/Root/Names/EmbeddedFiles` name tree and returns all
/// [`FileSpec`] entries. Returns an empty `Vec` if the document has no
/// attachments or the names tree is absent.
///
/// Corresponds to `FPDFDoc_GetAttachmentCount` / `FPDFDoc_GetAttachment` in
/// PDFium's `fpdf_attachment.h`.
pub fn collect_attachments<S: PdfSource>(
    catalog: &Object,
    store: &ObjectStore<S>,
) -> DocResult<Vec<FileSpec>> {
    // /Root/Names/EmbeddedFiles
    let catalog_dict = match catalog.as_dict() {
        Some(d) => d,
        None => return Ok(Vec::new()),
    };

    let names_obj = match catalog_dict
        .get(&Name::names())
        .and_then(|o| store.deep_resolve(o).ok())
    {
        Some(o) => o,
        None => return Ok(Vec::new()),
    };

    let names_dict = match names_obj.as_dict() {
        Some(d) => d,
        None => return Ok(Vec::new()),
    };

    let ef_obj = match names_dict
        .get(&Name::embedded_files())
        .and_then(|o| store.deep_resolve(o).ok())
    {
        Some(o) => o,
        None => return Ok(Vec::new()),
    };

    // Parse the EmbeddedFiles name tree.  Values are file specification dicts.
    let tree = NameTree::parse(ef_obj, store, |val_obj| {
        parse_file_spec(val_obj, store).ok_or(DocError::UnexpectedType)
    })?;

    Ok(tree.entries().iter().map(|(_, v)| v.clone()).collect())
}

/// Extract a string value from a dictionary key.
fn extract_string<S: PdfSource>(
    dict: &HashMap<Name, Object>,
    key: &Name,
    store: &ObjectStore<S>,
) -> Option<String> {
    dict.get(key)
        .and_then(|o| store.deep_resolve(o).ok())
        .and_then(|o| o.as_string().map(|s| s.to_string_lossy()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use rpdfium_core::PdfString;

    fn build_store() -> ObjectStore<Vec<u8>> {
        let pdf = build_minimal_pdf();
        ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
    }

    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let obj1_offset = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let obj2_offset = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 3\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj1_offset).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj2_offset).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{}\n%%EOF", xref_offset).as_bytes());
        pdf
    }

    fn str_obj(s: &str) -> Object {
        Object::String(PdfString::from_bytes(s.as_bytes().to_vec()))
    }

    #[test]
    fn test_parse_file_spec_full() {
        let store = build_store();

        let mut ef_dict = HashMap::new();
        ef_dict.insert(Name::f(), Object::Reference(ObjectId::new(10, 0)));

        let mut dict = HashMap::new();
        dict.insert(Name::fs(), Object::Name(Name::from("URL")));
        dict.insert(Name::f(), str_obj("report.pdf"));
        dict.insert(Name::uf(), str_obj("report.pdf"));
        dict.insert(Name::dos(), str_obj("REPORT.PDF"));
        dict.insert(Name::unix_name(), str_obj("/home/user/report.pdf"));
        dict.insert(Name::ef(), Object::Dictionary(ef_dict));
        dict.insert(Name::desc(), str_obj("Annual report"));

        let obj = Object::Dictionary(dict);
        let spec = parse_file_spec(&obj, &store).unwrap();

        assert_eq!(spec.file_system.as_deref(), Some("URL"));
        assert_eq!(spec.filename.as_deref(), Some("report.pdf"));
        assert_eq!(spec.unicode_filename.as_deref(), Some("report.pdf"));
        assert_eq!(spec.dos_filename.as_deref(), Some("REPORT.PDF"));
        assert_eq!(spec.unix_filename.as_deref(), Some("/home/user/report.pdf"));
        assert_eq!(spec.embedded_file, Some(ObjectId::new(10, 0)));
        assert_eq!(spec.description.as_deref(), Some("Annual report"));
    }

    #[test]
    fn test_parse_file_spec_minimal() {
        let store = build_store();

        let mut dict = HashMap::new();
        dict.insert(Name::f(), str_obj("data.txt"));

        let obj = Object::Dictionary(dict);
        let spec = parse_file_spec(&obj, &store).unwrap();

        assert!(spec.file_system.is_none());
        assert_eq!(spec.filename.as_deref(), Some("data.txt"));
        assert!(spec.unicode_filename.is_none());
        assert!(spec.embedded_file.is_none());
    }

    #[test]
    fn test_parse_file_spec_not_dict_returns_none() {
        let store = build_store();
        let obj = Object::Integer(42);
        assert!(parse_file_spec(&obj, &store).is_none());
    }

    #[test]
    fn test_set_filename_updates_in_memory() {
        let mut spec = FileSpec {
            file_system: None,
            filename: Some("test.pdf".into()),
            unicode_filename: None,
            dos_filename: None,
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: None,
        };
        spec.set_filename("new.pdf").unwrap();
        assert_eq!(spec.filename.as_deref(), Some("new.pdf"));
        assert_eq!(spec.unicode_filename.as_deref(), Some("new.pdf"));
    }

    #[test]
    fn test_best_filename_prefers_unicode() {
        let spec = FileSpec {
            file_system: None,
            filename: Some("fallback.pdf".into()),
            unicode_filename: Some("unicode.pdf".into()),
            dos_filename: None,
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: None,
        };
        assert_eq!(spec.name(), Some("unicode.pdf"));
    }

    #[test]
    fn test_best_filename_falls_back() {
        let spec = FileSpec {
            file_system: None,
            filename: None,
            unicode_filename: None,
            dos_filename: Some("DOS.PDF".into()),
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: None,
        };
        assert_eq!(spec.name(), Some("DOS.PDF"));
    }

    #[test]
    fn test_best_filename_none() {
        let spec = FileSpec {
            file_system: None,
            filename: None,
            unicode_filename: None,
            dos_filename: None,
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: None,
        };
        assert!(spec.name().is_none());
    }

    #[test]
    fn test_encode_filename_unix() {
        assert_eq!(encode_filename("/home/user/doc.pdf"), "/home/user/doc.pdf");
    }

    #[test]
    fn test_encode_filename_windows() {
        assert_eq!(encode_filename("C:\\Users\\doc.pdf"), "/C/Users/doc.pdf");
    }

    #[test]
    fn test_encode_filename_already_pdf() {
        assert_eq!(encode_filename("/path/to/file.pdf"), "/path/to/file.pdf");
    }

    #[test]
    fn test_decode_filename_drive_letter() {
        assert_eq!(decode_filename("/C/Users/doc.pdf"), "C:/Users/doc.pdf");
    }

    #[test]
    fn test_decode_filename_unix() {
        assert_eq!(decode_filename("/home/user/doc.pdf"), "/home/user/doc.pdf");
    }

    #[test]
    fn test_decode_filename_no_drive() {
        assert_eq!(decode_filename("relative/path.pdf"), "relative/path.pdf");
    }

    // -----------------------------------------------------------------------
    // underlying_bytes / get_underlying_bytes tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_underlying_bytes_returns_none_when_no_data() {
        let spec = FileSpec {
            file_system: None,
            filename: Some("report.pdf".into()),
            unicode_filename: None,
            dos_filename: None,
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: None,
        };
        assert!(spec.underlying_bytes().is_none());
    }

    /// Upstream: TEST(CPDFFileSpecTest, GetFileStream)
    ///
    /// Tests embedded file stream retrieval from the /EF dictionary.
    /// The upstream test builds an /EF dict with keys in precedence order
    /// (Unix, Mac, DOS, F, UF) and verifies the highest-precedence stream
    /// is returned. In rpdfium, `parse_file_spec` extracts the /EF /F
    /// stream reference; we verify the embedded_file field is populated
    /// when /EF contains a /F reference, and None when absent.
    #[test]
    fn test_cpdf_file_spec_get_file_stream() {
        let store = build_store();

        // Case 1: No /EF dict => no embedded file
        let mut dict1 = HashMap::new();
        dict1.insert(Name::f(), str_obj("test.pdf"));
        let spec1 = parse_file_spec(&Object::Dictionary(dict1), &store).unwrap();
        assert!(spec1.embedded_file.is_none());

        // Case 2: Empty /EF dict => no embedded file
        let mut dict2 = HashMap::new();
        dict2.insert(Name::f(), str_obj("test.pdf"));
        dict2.insert(Name::ef(), Object::Dictionary(HashMap::new()));
        let spec2 = parse_file_spec(&Object::Dictionary(dict2), &store).unwrap();
        assert!(spec2.embedded_file.is_none());

        // Case 3: /EF dict with /F reference
        let mut ef_dict = HashMap::new();
        ef_dict.insert(Name::f(), Object::Reference(ObjectId::new(10, 0)));
        let mut dict3 = HashMap::new();
        dict3.insert(Name::f(), str_obj("test.pdf"));
        dict3.insert(Name::ef(), Object::Dictionary(ef_dict));
        let spec3 = parse_file_spec(&Object::Dictionary(dict3), &store).unwrap();
        assert_eq!(spec3.embedded_file, Some(ObjectId::new(10, 0)));
    }

    /// Upstream: TEST(CPDFFileSpecTest, GetParamsDict)
    ///
    /// Tests /Params dictionary retrieval from an embedded file stream.
    /// Since rpdfium's FileSpec doesn't directly expose the /Params dict,
    /// this test verifies the related behavior: when data can be decoded
    /// from the stream, file_data() returns it; otherwise None.
    #[test]
    fn test_cpdf_file_spec_get_params_dict() {
        let store = build_store();

        // Non-dict object => parse_file_spec returns None
        let spec = parse_file_spec(&Object::Name(Name::from("test.pdf")), &store);
        assert!(spec.is_none());

        // Dict with /EF but stream not in store => data is None
        let mut ef_dict = HashMap::new();
        ef_dict.insert(Name::f(), Object::Reference(ObjectId::new(999, 0)));
        let mut dict = HashMap::new();
        dict.insert(Name::uf(), str_obj("test.pdf"));
        dict.insert(Name::ef(), Object::Dictionary(ef_dict));
        let spec = parse_file_spec(&Object::Dictionary(dict), &store).unwrap();
        // The reference points to a non-existent object, so data is None
        assert!(spec.file_data().is_none());
        assert_eq!(spec.embedded_file, Some(ObjectId::new(999, 0)));
    }

    #[test]
    fn test_underlying_bytes_returns_data_when_present() {
        let payload = b"Hello, embedded file!".to_vec();
        let spec = FileSpec {
            file_system: None,
            filename: Some("doc.txt".into()),
            unicode_filename: None,
            dos_filename: None,
            unix_filename: None,
            embedded_file: None,
            description: None,
            data: Some(payload.clone()),
        };
        assert_eq!(spec.underlying_bytes(), Some(payload.as_slice()));
    }
}