flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Remove unreferenced resources from page and Form content.
//!
//! qpdf correspondence: `QPDFPageObjectHelper::removeUnreferencedResources`.
//!
//! (`QPDFPageObjectHelper.cc:539-649`) split into page/Form traversal helpers.
//!
//! The canonical route parses one page or Form at a time, then shallow-copies
//! and prunes only its `/Font` and `/XObject` dictionaries. Document-level
//! callers own the page iteration; the `Auto` decision is the separate qpdf
//! job-level `shouldRemoveUnreferencedResources` heuristic in
//! `should_remove_unreferenced_resources`. Both the Form pre-pass
//! and the ResourceReplacer name scan use the canonical
//! `ObjectHandleParserCallbacks` content route.
//!
//! Form XObject lookup resolves each canonical handle before inspecting its
//! stream dictionary, so lazy indirect resource values remain live through
//! the complete pruning walk.

use crate::page_object_helper::PageObjectHelper;
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::resource_finder::{ResourceFinder, ResourceNamesByType};
use crate::{Error, ObjectHandle, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::{Read, Seek};

/// Resource names referenced by a content scope, keyed by category
/// (`Font`, `XObject`, …) → set of referenced names.
type UsedNames = BTreeMap<Vec<u8>, BTreeSet<Vec<u8>>>;

/// Snapshot qpdf's `QPDF::numWarnings` around a document-owned content parse
/// (`QPDFPageObjectHelper.cc:547-557`).
fn diagnostic_count<R: Read + Seek>(pdf: &Pdf<R>) -> usize {
    pdf.num_warnings()
}

const BAD_TOKEN_WARNING: &str =
    "Bad token found while scanning content stream; not attempting to remove unreferenced objects from this object";

/// Report the same warning that qpdf's `removeUnreferencedResourcesHelper`
/// emits for a parse exception or a parser warning. The distinction matters:
/// qpdf uses the exception text for the former and the fixed bad-token text
/// for the latter (`QPDFPageObjectHelper.cc:539-564`).
fn warn_resource_parse_failure(handle: &ObjectHandle, parse_error: Option<&str>) -> Result<()> {
    if let Some(parse_error) = parse_error {
        let warning = format!(
            "Unable to parse content stream: {parse_error}; not attempting to remove unreferenced objects from this object"
        );
        handle.warn_if_possible(&warning)
    } else {
        handle.warn_if_possible(BAD_TOKEN_WARNING)
    }
}

/// qpdf `QPDFPageObjectHelper::removeUnreferencedResources` for one page.
///
/// qpdf first copies an inherited or indirect `/Resources` dictionary onto the
/// page, then shallow-copies the `/Font` and `/XObject` dictionaries it will
/// mutate. Each page therefore gets its own mutable resource scope; the caller
/// is responsible for iterating the selected pages and applying the job mode.
pub(crate) fn remove_unreferenced_resources_on_page<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
) -> Result<()> {
    let (unresolved, any_failures) = remove_unreferenced_resources_in_form_xobjects(pdf, page_ref)?;
    if any_failures {
        return Ok(());
    }

    // The page action itself follows qpdf's canonical PageObjectHelper route:
    // parsing stays on ObjectHandle callbacks and effective resources are
    // copied through getAttribute(copy_if_shared=true). The Form pre-pass
    // above remains separate because qpdf runs it before the page action and
    // uses its unresolved-name accumulator to protect page resources.
    let diagnostics_before = diagnostic_count(pdf);
    let (finder, parse_error, pending_operands) = {
        let mut helper = PageObjectHelper::new(page_ref, pdf);
        let mut finder = ResourceFinder::default();
        let parse_error = helper
            .parse_contents(&mut finder)
            .err()
            .map(|error| error.to_string());
        let pending_operands = finder.has_pending_operands();
        (finder, parse_error, pending_operands)
    };

    let page_handle = pdf.get_object_handle(page_ref);
    if let Some(parse_error) = parse_error {
        warn_resource_parse_failure(&page_handle, Some(&parse_error))?;
        return Ok(());
    }
    if pending_operands || diagnostic_count(pdf) > diagnostics_before {
        warn_resource_parse_failure(&page_handle, None)?;
        return Ok(());
    }

    let resources = PageObjectHelper::new(page_ref, pdf).get_resources(true)?;

    if resources.try_is_null()? {
        return Ok(());
    }

    for category in [b"/Font".as_slice(), b"/XObject".as_slice()] {
        let value = resources.try_get_key(category)?;
        if value.try_is_null()? {
            continue;
        }
        value.try_dereference()?;
        if !value.try_is_dictionary()? {
            // qpdf only shallow-copies and mutates a category when
            // `dict.isDictionary()` (`QPDFPageObjectHelper.cc:576-585`); a
            // malformed category is left as its original (possibly indirect)
            // value, never replaced or removed.
            continue;
        }
        let dictionary = if value.is_indirect() {
            let copy = value.shallow_copy()?;
            resources.replace_key(category, copy.clone())?;
            copy
        } else {
            value
        };
        let names = finder.names();
        let remove = dictionary
            .try_get_keys()?
            .into_iter()
            .filter(|name| {
                let resource_name = name.strip_prefix(b"/").unwrap_or(name.as_slice());
                !names.contains(resource_name)
                    && !unresolved
                        .iter()
                        .any(|unresolved_name| unresolved_name.as_slice() == resource_name)
            })
            .collect::<Vec<_>>();
        for name in remove {
            dictionary.remove_key(&name);
        }
    }

    Ok(())
}

/// qpdf's Form-XObject target route for
/// `QPDFPageObjectHelper::removeUnreferencedResources`.
///
/// The page route above retains the document helper's unresolved-name
/// accumulator because page resources may be referenced by a resource-less
/// descendant Form. A Form helper has no containing page scope, so its nested
/// Forms are pruned first through the same canonical ObjectHandle parser, then
/// the requested Form is pruned.
pub(crate) fn remove_unreferenced_resources_on_form<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    form: ObjectHandle,
) -> Result<()> {
    let mut nested_forms = Vec::new();
    {
        let mut helper = PageObjectHelper::from_object_handle(form.clone(), pdf);
        helper.for_each_form_xobject(true, |nested, _, _| {
            nested_forms.push(nested);
            Ok(())
        })?;
    }

    for nested in nested_forms {
        prune_canonical_resource_target(pdf, nested)?;
    }
    prune_canonical_resource_target(pdf, form)
}

/// Prune a single canonical page/Form target after its content has been
/// parsed by [`ResourceFinder`]. This is the ObjectHandle counterpart of
/// qpdf's `removeUnreferencedResourcesHelper` resource-dictionary mutation.
fn prune_canonical_resource_target<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    target: ObjectHandle,
) -> Result<()> {
    let diagnostics_before = diagnostic_count(pdf);
    let (finder, parse_error, pending_operands) = {
        let mut helper = PageObjectHelper::from_object_handle(target.clone(), pdf);
        let mut finder = ResourceFinder::default();
        let parse_error = helper
            .parse_contents(&mut finder)
            .err()
            .map(|error| error.to_string());
        let pending_operands = finder.has_pending_operands();
        (finder, parse_error, pending_operands)
    };

    if let Some(parse_error) = parse_error {
        warn_resource_parse_failure(&target, Some(&parse_error))?;
        return Ok(());
    }
    if pending_operands || diagnostic_count(pdf) > diagnostics_before {
        warn_resource_parse_failure(&target, None)?;
        return Ok(());
    }

    let resources = PageObjectHelper::from_object_handle(target, pdf).get_resources(true)?;

    if resources.try_is_null()? {
        return Ok(());
    }

    let categories = [b"/Font".as_slice(), b"/XObject".as_slice()];
    let mut dictionaries = Vec::new();
    let mut known_names = BTreeSet::new();
    for category in categories {
        let value = resources.try_get_key(category)?;
        if value.try_is_null()? {
            continue;
        }
        value.try_dereference()?;
        if !value.try_is_dictionary()? {
            // qpdf leaves a malformed /Font or /XObject category untouched;
            // see the matching comment in remove_unreferenced_resources_on_page.
            continue;
        }
        let dictionary = if value.is_indirect() {
            let copy = value.shallow_copy()?;
            resources.replace_key(category, copy.clone())?;
            copy
        } else {
            value
        };
        let live_keys = dictionary.try_get_keys()?;
        known_names.extend(
            live_keys
                .iter()
                .map(|key| key.strip_prefix(b"/").unwrap_or(key.as_slice()).to_vec()),
        );
        dictionaries.push((category, dictionary, live_keys));
    }

    // qpdf treats an unresolved Font/XObject name as a veto when this target
    // has a Resources dictionary. The known-name set is intentionally shared
    // across both categories, matching ResourceFinder::getNames() in qpdf.
    let local_unresolved = categories
        .iter()
        .filter_map(|category| finder.names_by_resource_type().get(&category[1..]))
        .flat_map(|entries| entries.keys())
        .filter(|name| !known_names.contains(*name))
        .cloned()
        .collect::<BTreeSet<_>>();
    if !local_unresolved.is_empty() && resources.try_is_dictionary()? {
        return Ok(());
    }

    for (_category, dictionary, live_keys) in dictionaries {
        let names = finder.names();
        let remove = dictionary
            .try_get_keys()?
            .into_iter()
            .filter(|key| live_keys.contains(key))
            .filter(|key| {
                let name = key.strip_prefix(b"/").unwrap_or(key.as_slice());
                !names.contains(name)
            })
            .collect::<Vec<_>>();
        for key in remove {
            dictionary.remove_key(&key);
        }
    }

    Ok(())
}

/// Mirror qpdf's `forEachFormXObject(true, ...)` pre-pass for a page-resource
/// scope. Each indirect Form XObject gets its own `/Font` and `/XObject`
/// dictionaries shallow-copied and pruned before the containing page is
/// processed. The traversal follows declared `/XObject` resources rather than
/// only `Do` operators, exactly as qpdf's helper traversal does.
fn remove_unreferenced_resources_in_form_xobjects<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
) -> Result<(BTreeSet<Vec<u8>>, bool)> {
    let page_resources = {
        let mut helper = PageObjectHelper::new(page_ref, pdf);
        // qpdf's forEachFormXObject uses getAttribute("/Resources", false)
        // while discovering nested Forms; the later per-Form pruning helper
        // is the first boundary that copies an indirect Resources dictionary.
        helper.get_resources(false)?
    };
    if page_resources.try_is_null()? {
        return Ok((BTreeSet::new(), false));
    }
    let mut pending = VecDeque::from(form_xobjects_in_resources(&page_resources)?);
    let mut visited: BTreeSet<QpdfObjGen> = BTreeSet::new();
    let mut unresolved = BTreeSet::new();
    let mut any_failures = false;

    while let Some(holder_handle) = pending.pop_front() {
        // cov:ignore-start: form_xobjects_in_resources enqueues only indirect
        // handles, so this is a defensive invariant guard.
        let Some(object_gen) = holder_handle
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect())
        else {
            continue;
        };
        // cov:ignore-end
        if !visited.insert(object_gen) {
            continue;
        }
        // Resolve the canonical form handle before inspecting its stream type.
        holder_handle.try_dereference()?;
        let form_handle = holder_handle;
        if !form_handle.is_form_xobject()? {
            continue; // cov:ignore: form_xobjects_in_resources already terminal-chase-filters to Form XObjects
        }
        let stream_dict = form_stream_dict(&form_handle)?;
        // Resolve the live resource dictionary before reading its children.
        let resources = stream_dict.try_get_key(b"/Resources")?;
        let resources = resources.try_is_dictionary()?.then_some(resources);
        // qpdf's removeUnreferencedResourcesHelper (QPDFPageObjectHelper.cc:539-556)
        // is the single function called for every Form and for the page
        // itself: parse through ResourceFinder and reject the scope if
        // parsing failed or emitted a new warning, matching the page-level
        // block in remove_unreferenced_resources_on_page above.
        let diagnostics_before = diagnostic_count(pdf);
        let (finder, parse_error, pending_operands) = {
            let mut helper = PageObjectHelper::from_object_handle(form_handle.clone(), pdf);
            let mut finder = ResourceFinder::default();
            let parse_error = helper
                .parse_contents(&mut finder)
                .err()
                .map(|error| error.to_string());
            let pending_operands = finder.has_pending_operands();
            (finder, parse_error, pending_operands)
        };
        if let Some(parse_error) = parse_error {
            warn_resource_parse_failure(&form_handle, Some(&parse_error))?;
            any_failures = true;
            if let Some(resources) = resources.as_ref() {
                pending.extend(form_xobjects_in_resources(resources)?);
            } // cov:ignore: llvm-cov maps the covered child-Form continuation to this closing brace
            continue;
        }
        if pending_operands || diagnostic_count(pdf) > diagnostics_before {
            warn_resource_parse_failure(&form_handle, None)?;
            any_failures = true;
            if let Some(resources) = resources.as_ref() {
                pending.extend(form_xobjects_in_resources(resources)?);
            } // cov:ignore: llvm-cov maps the covered child-Form continuation to this closing brace
            continue;
        }
        // qpdf's removeUnreferencedResourcesHelper parses each Form
        // independently: a resource-less descendant's names only enter the
        // containing page's unresolved-name protection set (via
        // unresolved_resource_names below), never this Form's own /Font or
        // /XObject dictionaries, so only directly-parsed names are recorded.
        let mut used = BTreeMap::new();
        record_direct_names(&mut used, finder.names_by_resource_type(), true);
        let local_unresolved = unresolved_resource_names(resources.as_ref(), &used)?;
        unresolved.extend(local_unresolved.iter().cloned());
        // qpdf's forEachFormXObject retains the original child object handle
        // while its action prunes the parent. Capture those children before
        // pruning can remove their names from this Form's /XObject dictionary.
        let child_forms = match resources.as_ref() {
            Some(resources) => form_xobjects_in_resources(resources)?,
            None => Vec::new(),
        };

        if !local_unresolved.is_empty() && resources.is_some() {
            any_failures = true;
        } else if let Some(resources) = &resources {
            // Only shallow-copy the shared indirect Resources dictionary once
            // pruning is actually going to happen: qpdf's contract (mirrored
            // by prune_canonical_resource_target's own parse-then-copy order)
            // leaves a Form whose content failed to parse untouched.
            let resources = if resources.is_indirect() {
                let copy = resources.shallow_copy()?;
                stream_dict.replace_key(b"/Resources", copy.clone())?;
                copy
            } else {
                resources.clone()
            };
            prune_font_and_xobject_dictionaries(&resources, &used)?;
        }

        pending.extend(child_forms);
    }
    Ok((unresolved, any_failures))
}

/// Return `/Font` and `/XObject` names used by `used` but absent from the
/// current Form resource scope. qpdf deliberately compares the categories as
/// one name set before deciding whether a Form may be pruned.
fn unresolved_resource_names(
    resources: Option<&ObjectHandle>,
    used: &UsedNames,
) -> Result<BTreeSet<Vec<u8>>> {
    let mut known_names: BTreeSet<Vec<u8>> = BTreeSet::new();
    if let Some(resources) = resources {
        for category in [b"Font".as_slice(), b"XObject".as_slice()] {
            let mut key = Vec::with_capacity(category.len() + 1);
            key.push(b'/');
            key.extend_from_slice(category);
            let value = resources.try_get_key(&key)?;
            value.try_dereference()?;
            let Some(dictionary) = value.try_as_dictionary()? else {
                continue;
            };
            known_names.extend(
                dictionary
                    .keys()
                    .map(|name| name.strip_prefix(b"/").unwrap_or(name.as_slice()).to_vec()),
            );
        }
    }

    let mut unresolved = BTreeSet::new();
    for category in [b"Font".as_slice(), b"XObject".as_slice()] {
        for name in used
            .get(category)
            .into_iter()
            .flat_map(|names| names.iter())
        {
            if !known_names.contains(&name.to_vec()) {
                unresolved.insert(name.clone());
            }
        }
    }
    Ok(unresolved)
}

/// Return indirect Form XObjects listed in a resource dictionary, retaining
/// each handle's raw qpdf identity for the caller's traversal seen set.
fn form_xobjects_in_resources(resources: &ObjectHandle) -> Result<Vec<ObjectHandle>> {
    let xobjects = resources.try_get_key(b"/XObject")?;
    xobjects.try_dereference()?;
    let Some(xobjects) = xobjects.try_as_dictionary()? else {
        return Ok(Vec::new());
    };
    let mut forms = Vec::new();
    for value in xobjects.values() {
        if value
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect())
            .is_none()
        {
            continue;
        }
        // Resolve the live XObject value before applying the form predicate.
        value.try_dereference()?;
        if !value.is_form_xobject()? {
            continue;
        }
        forms.push(value.clone());
    }
    Ok(forms)
}

/// Shallow-copy qpdf's mutable resource categories then remove names not used
/// by the directly parsed content stream. Empty category dictionaries remain
/// present, matching qpdf's `removeKey` loop on the category contents.
fn prune_font_and_xobject_dictionaries(resources: &ObjectHandle, used: &UsedNames) -> Result<()> {
    for category in [b"Font".as_slice(), b"XObject".as_slice()] {
        let mut key = Vec::with_capacity(category.len() + 1);
        key.push(b'/');
        key.extend_from_slice(category);
        let value = resources.try_get_key(&key)?;
        value.try_dereference()?;
        if !value.try_is_dictionary()? {
            // qpdf leaves a malformed /Font or /XObject category untouched;
            // see the matching comment in remove_unreferenced_resources_on_page.
            continue;
        }
        let dictionary = if value.is_indirect() {
            let copy = value.shallow_copy()?;
            resources.replace_key(&key, copy.clone())?;
            copy
        } else {
            value
        };
        let names = used.get(category).cloned().unwrap_or_default();
        let remove = dictionary
            .try_get_keys()?
            .into_iter()
            .filter(|name| !names.contains(name.strip_prefix(b"/").unwrap_or(name.as_slice())))
            .collect::<Vec<_>>();
        for name in remove {
            dictionary.remove_key(&name);
        }
    }
    Ok(())
}

/// Resource dictionary categories reported by qpdf's `ResourceFinder`.
///
/// The canonical pruning mutation uses only `/Font` and `/XObject`, but the
/// content walk records all categories so Form scope and unresolved-name
/// handling remain faithful to qpdf's parser callbacks.
const RESOURCE_CATEGORIES: &[&str] = &[
    "Font",
    "XObject",
    "ColorSpace",
    "Pattern",
    "Shading",
    "ExtGState",
    "Properties",
];

// ── Device-colorspace names that are never looked up in /ColorSpace ───────────

/// Names that appear as operands to the page-content `cs`/`CS` operators but
/// are **built-in** device colour spaces, not entries in the page's
/// `/ColorSpace` dictionary.
///
/// ISO 32000-1 §8.6.8: only `/DeviceGray`, `/DeviceRGB`, `/DeviceCMYK`, and
/// `/Pattern` may be selected by name directly in page content.  All other
/// colour spaces (`/CalGray`, `/CalRGB`, `/Lab`, `/ICCBased`, `/Indexed`, …)
/// are array-based and **must** be named via an entry in `/Resources/ColorSpace`.
fn is_builtin_color_space_cs_op(name: &[u8]) -> bool {
    matches!(
        name,
        b"DeviceGray" | b"DeviceRGB" | b"DeviceCMYK" | b"Pattern"
    )
}

fn record_direct_names(used: &mut UsedNames, names: &ResourceNamesByType, record_direct: bool) {
    if !record_direct {
        return;
    }
    for &category in RESOURCE_CATEGORIES {
        let category = category.as_bytes();
        for name in names
            .get(category)
            .into_iter()
            .flat_map(|by_name| by_name.keys())
        {
            if category == b"ColorSpace" && is_builtin_color_space_cs_op(name) {
                continue;
            }
            used.entry(category.to_vec())
                .or_default()
                .insert(name.clone());
        }
    }
}

fn form_stream_dict(handle: &ObjectHandle) -> Result<ObjectHandle> {
    handle.as_stream_dict().ok_or_else(|| {
        Error::Internal("Form XObject handle did not resolve to a stream".to_owned())
    })
}

#[cfg(test)]
mod final_handle_tests {
    use super::{
        form_xobjects_in_resources, remove_unreferenced_resources_in_form_xobjects,
        remove_unreferenced_resources_on_form,
    };
    use crate::{ObjectHandle, ObjectRef, Pdf};
    use std::io::Cursor;
    use std::rc::Rc;

    fn fixture() -> Pdf<Cursor<Vec<u8>>> {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat/direct-root-one-page.pdf");
        Pdf::open_mem_owned(std::fs::read(path).expect("fixture exists")).expect("fixture opens")
    }

    fn form_with_resources(pdf: &Pdf<Cursor<Vec<u8>>>, contents: &[u8]) -> ObjectHandle {
        let form = pdf
            .new_stream_with_data(Rc::new(contents.to_vec()))
            .expect("form stream");
        let form_dict = form.as_stream_dict().expect("form dictionary");
        form_dict
            .replace_key(b"/Type", ObjectHandle::name(b"XObject".to_vec()))
            .expect("form type");
        form_dict
            .replace_key(b"/Subtype", ObjectHandle::name(b"Form".to_vec()))
            .expect("form subtype");
        form_dict
            .replace_key(
                b"/Resources",
                ObjectHandle::dictionary(vec![(
                    b"/Font".to_vec(),
                    ObjectHandle::dictionary(vec![
                        (b"/F1".to_vec(), ObjectHandle::dictionary(Vec::new())),
                        (b"/Unused".to_vec(), ObjectHandle::dictionary(Vec::new())),
                    ]),
                )]),
            )
            .expect("form resources");
        form
    }

    #[test]
    fn form_resource_prepass_resolves_form_and_resource_handles() {
        let mut pdf = fixture();
        let page_ref = crate::pages::page_refs(&mut pdf).expect("page refs")[0];
        let page_handle = pdf.get_object_handle(page_ref);
        page_handle.try_is_scalar().expect("page resolves");
        let replacement = page_handle.shallow_copy().expect("page is copyable");

        let form = pdf
            .new_stream_with_data(Rc::new(b"q Q".to_vec()))
            .expect("form stream");
        let form_dict = form.as_stream_dict().expect("form dictionary");
        form_dict
            .replace_key(b"/Type", ObjectHandle::name(b"XObject".to_vec()))
            .expect("form type");
        form_dict
            .replace_key(b"/Subtype", ObjectHandle::name(b"Form".to_vec()))
            .expect("form subtype");
        form_dict
            .replace_key(
                b"/Resources",
                ObjectHandle::dictionary(vec![(
                    b"/Font".to_vec(),
                    ObjectHandle::dictionary(vec![(b"/Unused".to_vec(), ObjectHandle::integer(1))]),
                )]),
            )
            .expect("form resources");
        let resources = ObjectHandle::dictionary(vec![(
            b"/XObject".to_vec(),
            ObjectHandle::dictionary(vec![(b"/Fm0".to_vec(), form)]),
        )]);
        replacement
            .replace_key(b"/Resources", resources)
            .expect("page resources");
        pdf.replace_object(page_ref, replacement)
            .expect("replace page");

        let (unresolved, failures) =
            remove_unreferenced_resources_in_form_xobjects(&mut pdf, page_ref)
                .expect("form resource prepass");
        assert!(unresolved.is_empty());
        assert!(!failures);
    }

    #[test]
    fn form_resource_prepass_does_not_drop_a_raw_generation_form() {
        let mut pdf = fixture();
        let raw_ref = ObjectRef::new(50, 65_535);
        let form = ObjectHandle::stream(
            ObjectHandle::dictionary(vec![
                (b"/Type".to_vec(), ObjectHandle::name(b"XObject".to_vec())),
                (b"/Subtype".to_vec(), ObjectHandle::name(b"Form".to_vec())),
            ]),
            Rc::new(Vec::new()),
        );
        pdf.replace_object(raw_ref, form).expect("install raw form");
        let resources = ObjectHandle::dictionary(vec![(
            b"/XObject".to_vec(),
            ObjectHandle::dictionary(vec![(b"/Fm0".to_vec(), pdf.get_object_handle(raw_ref))]),
        )]);

        let forms = form_xobjects_in_resources(&resources).expect("find raw form");

        assert_eq!(forms.len(), 1);
    }

    #[test]
    fn canonical_form_pruning_uses_the_clean_parse_boundary() {
        let mut pdf = fixture();
        let form = form_with_resources(&pdf, b"/F1 12 Tf");

        remove_unreferenced_resources_on_form(&mut pdf, form.clone())
            .expect("clean Form content should be pruned");

        let resources = form
            .as_stream_dict()
            .expect("form dictionary")
            .try_get_key(b"/Resources")
            .expect("resources");
        let fonts = resources.try_get_key(b"/Font").expect("fonts");
        assert!(!fonts.try_get_key(b"/F1").expect("used font").is_null());
        assert!(fonts
            .try_get_key(b"/Unused")
            .expect("unused font")
            .is_null());
    }

    #[test]
    fn canonical_form_pruning_skips_a_scope_with_parser_warnings() {
        let mut pdf = fixture();
        let form = form_with_resources(&pdf, b"<0g>");

        remove_unreferenced_resources_on_form(&mut pdf, form.clone())
            .expect("recoverable Form warnings should skip pruning");

        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .any(|diagnostic| diagnostic
                .message_string()
                .contains("invalid character (g) in hexstring")));
        let resources = form
            .as_stream_dict()
            .expect("form dictionary")
            .try_get_key(b"/Resources")
            .expect("resources");
        let fonts = resources.try_get_key(b"/Font").expect("fonts");
        assert!(!fonts
            .try_get_key(b"/Unused")
            .expect("unused font")
            .is_null());
    }

    #[test]
    fn canonical_form_pruning_reports_a_parse_exception() {
        let mut pdf = fixture();
        let form = form_with_resources(&pdf, b"not-flate");
        form.as_stream_dict()
            .expect("form dictionary")
            .replace_key(b"/Filter", ObjectHandle::name(b"FlateDecode".to_vec()))
            .expect("filter");

        remove_unreferenced_resources_on_form(&mut pdf, form)
            .expect("recoverable Form parse failures should be warnings");

        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .any(|diagnostic| diagnostic
                .message_string()
                .contains("Unable to parse content stream: stream inflate")));
    }

    #[test]
    fn page_resource_pruning_reports_a_parse_exception() {
        let mut pdf = fixture();
        let page_ref = crate::pages::page_refs(&mut pdf).expect("page refs")[0];
        let page_handle = pdf.get_object_handle(page_ref);
        page_handle.try_is_scalar().expect("page resolves");
        let replacement = page_handle.shallow_copy().expect("page is copyable");
        let contents = pdf
            .new_stream_with_data(Rc::new(b"not-flate".to_vec()))
            .expect("content stream");
        contents
            .as_stream_dict()
            .expect("content stream dictionary")
            .replace_key(b"/Filter", ObjectHandle::name(b"FlateDecode".to_vec()))
            .expect("filter");
        replacement
            .replace_key(b"/Contents", contents)
            .expect("page contents");
        pdf.replace_object(page_ref, replacement)
            .expect("replace page");

        super::remove_unreferenced_resources_on_page(&mut pdf, page_ref)
            .expect("recoverable page parse failures should be warnings");

        assert!(pdf
            .repair_diagnostics()
            .entries()
            .iter()
            .any(|diagnostic| diagnostic
                .message_string()
                .contains("Unable to parse content stream: stream inflate")));
    }

    /// Build a page whose single declared Form XObject is malformed (either
    /// undecodable or unparseable, per `outer_stream`/`outer_filter`) but
    /// still declares a nested child Form. `remove_unreferenced_resources_in_form_xobjects`
    /// must record the failure and keep walking into that child rather than
    /// aborting — the child's own content references a resource name absent
    /// from its own `/Resources`, so seeing that name surface in the
    /// returned unresolved set is an externally observable proof the walk
    /// descended past the malformed parent.
    fn page_with_malformed_form_and_child(
        outer_stream: &[u8],
        outer_filter: Option<&[u8]>,
    ) -> (Pdf<std::io::Cursor<Vec<u8>>>, crate::ObjectRef) {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat/direct-root-one-page.pdf");
        let mut pdf = Pdf::open_mem_owned(std::fs::read(path).expect("fixture exists"))
            .expect("fixture opens");
        let page_ref = crate::pages::page_refs(&mut pdf).expect("page refs")[0];
        let page_handle = pdf.get_object_handle(page_ref);
        page_handle.try_is_scalar().expect("page resolves");
        let replacement = page_handle.shallow_copy().expect("page is copyable");

        let child_form = pdf
            .new_stream_with_data(Rc::new(b"/Ghost Do".to_vec()))
            .expect("child form stream");
        let child_dict = child_form.as_stream_dict().expect("child form dictionary");
        child_dict
            .replace_key(b"/Type", ObjectHandle::name(b"XObject".to_vec()))
            .expect("child form type");
        child_dict
            .replace_key(b"/Subtype", ObjectHandle::name(b"Form".to_vec()))
            .expect("child form subtype");
        child_dict
            .replace_key(b"/Resources", ObjectHandle::dictionary(vec![]))
            .expect("child form resources");

        let outer_form = pdf
            .new_stream_with_data(Rc::new(outer_stream.to_vec()))
            .expect("outer form stream");
        let outer_dict = outer_form.as_stream_dict().expect("outer form dictionary");
        outer_dict
            .replace_key(b"/Type", ObjectHandle::name(b"XObject".to_vec()))
            .expect("outer form type");
        outer_dict
            .replace_key(b"/Subtype", ObjectHandle::name(b"Form".to_vec()))
            .expect("outer form subtype");
        if let Some(filter) = outer_filter {
            outer_dict
                .replace_key(b"/Filter", ObjectHandle::name(filter.to_vec()))
                .expect("outer form filter");
        }
        outer_dict
            .replace_key(
                b"/Resources",
                ObjectHandle::dictionary(vec![(
                    b"/XObject".to_vec(),
                    ObjectHandle::dictionary(vec![(b"/FmChild".to_vec(), child_form)]),
                )]),
            )
            .expect("outer form resources");

        let resources = ObjectHandle::dictionary(vec![(
            b"/XObject".to_vec(),
            ObjectHandle::dictionary(vec![(b"/Fm0".to_vec(), outer_form)]),
        )]);
        replacement
            .replace_key(b"/Resources", resources)
            .expect("page resources");
        pdf.replace_object(page_ref, replacement)
            .expect("replace page");
        (pdf, page_ref)
    }

    #[test]
    fn form_walk_continues_into_declared_children_after_a_decode_failure() {
        let (mut pdf, page_ref) =
            page_with_malformed_form_and_child(b"not-flate", Some(b"FlateDecode"));

        let (unresolved, failures) =
            remove_unreferenced_resources_in_form_xobjects(&mut pdf, page_ref)
                .expect("form resource prepass tolerates an undecodable Form");
        assert!(failures, "the undecodable outer Form must set any_failures");
        assert!(
            unresolved.contains(b"Ghost".as_slice()),
            "the child Form's own unresolved /Ghost use must surface, proving \
             the walk descended past the undecodable parent: {unresolved:?}"
        );
    }

    #[test]
    fn form_walk_continues_into_declared_children_after_a_parse_failure() {
        let (mut pdf, page_ref) = page_with_malformed_form_and_child(b"<0g>", None);

        let (unresolved, failures) =
            remove_unreferenced_resources_in_form_xobjects(&mut pdf, page_ref)
                .expect("form resource prepass tolerates an unparseable Form");
        assert!(failures, "the unparseable outer Form must set any_failures");
        assert!(
            unresolved.contains(b"Ghost".as_slice()),
            "the child Form's own unresolved /Ghost use must surface, proving \
             the walk descended past the unparseable parent: {unresolved:?}"
        );
    }
}