exprim 0.4.0

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
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
//! Page-tree indexing: walk `/Root → /Pages → /Kids` iteratively, flatten
//! inheritance, and freeze the result into the snapshot's `PageTreeIndex`.
//!
//! Malformed trees are the norm, not the exception: cycles (visited set),
//! `/Count` lies (never trusted — we walk), broken kids (skipped with a
//! recovery note), missing boxes (US-Letter default, PDFium behavior).

use std::collections::HashSet;

use crate::object::{Dictionary, ObjectError, ObjectId, PdfObject, decode_text_string_lossy};
use crate::structure::RecoveryEvent;

use crate::document::resolve::{Resolver, kind_name};
use crate::document::{
    DocumentError, PageAnnotation, PageIndex, PageRef, PageTreeIndex, ParseContext,
};

/// US Letter, the PDFium default when a MediaBox is absent or invalid.
const LETTER: [f64; 4] = [0.0, 0.0, 612.0, 792.0];

/// Attributes inheritable through the page tree (ISO 32000-1 Table 29).
///
/// Exactly four: `/Resources`, `/MediaBox`, `/CropBox` and `/Rotate`.
/// `/BleedBox`, `/TrimBox` and `/ArtBox` are deliberately absent — the spec
/// does not list them as inheritable, so they are read from the page's own
/// dictionary by [`resolve_page_boxes`].
#[derive(Debug, Clone, Default)]
struct Inherited {
    resources: Option<PdfObject>,
    media_box: Option<[f64; 4]>,
    crop_box: Option<[f64; 4]>,
    rotate: Option<i64>,
}

impl Inherited {
    /// Child view: any attribute present on `dict` overrides the parent's.
    fn updated_from(
        &self,
        dict: &Dictionary,
        resolver: &Resolver<'_>,
        ctx: &mut ParseContext,
    ) -> Self {
        let names = resolver.names;
        Self {
            resources: dict
                .get(names.known.resources)
                .cloned()
                .or_else(|| self.resources.clone()),
            media_box: resolve_rect(dict.get(names.known.media_box), resolver, ctx)
                .or(self.media_box),
            crop_box: resolve_rect(dict.get(names.known.crop_box), resolver, ctx).or(self.crop_box),
            rotate: resolve_int(dict.get(names.known.rotate), resolver, ctx).or(self.rotate),
        }
    }
}

/// What the page-tree walk actually recovered, so the document layer can decide
/// whether a full xref rebuild is worth trying. `real_pages` excludes blank
/// placeholders; `lost_subtrees` counts nodes the walk provably dropped
/// (unreadable/null kids). A zero-`real_pages` walk with lost subtrees is the
/// escalation signal.
#[derive(Debug, Clone, Copy)]
pub(crate) struct WalkStats {
    pub real_pages: usize,
    pub lost_subtrees: usize,
}

/// Build the page index from the catalog.
pub(crate) fn build_page_tree(
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Result<(PageTreeIndex, WalkStats), DocumentError> {
    let names = resolver.names;
    let limits = resolver.limits;

    let catalog = resolver.resolve(resolver.structure.trailer.root, ctx)?;
    let Some(catalog_dict) = catalog.as_dict() else {
        return Err(ObjectError::TypeMismatch {
            expected: "catalog dictionary",
            found: kind_name(&catalog),
        }
        .into());
    };
    let pages_root = catalog_dict
        .get(names.known.pages)
        .ok_or_else(|| ObjectError::MissingKey {
            key: "Pages".into(),
        })?
        .clone();

    // The root's declared /Count, for the truncated-tree placeholder pass
    // below. Never *trusted* for the walk itself.
    let declared_count = resolver
        .resolve_value(&pages_root, ctx)
        .ok()
        .and_then(|root| {
            root.as_dict()
                .and_then(|d| d.get(names.intern(b"Count")))
                .and_then(|v| resolve_int(Some(v), resolver, ctx))
        });

    let mut pages: Vec<PageRef> = Vec::new();
    let mut real_pages = 0usize;
    let mut lost_subtrees = 0usize;
    let mut visited: HashSet<ObjectId> = HashSet::new();
    // Stack of (node value, inherited attrs, expected leaf span). The span is
    // used only when the node proves unreadable, and only when its parent
    // `/Count` made that span exact. Kids are pushed reversed so the walk emits
    // document order.
    let root_span = declared_count
        .and_then(|count| usize::try_from(count).ok())
        .filter(|&count| limits.max_pages == 0 || count <= limits.max_pages as usize);
    let mut stack: Vec<(PdfObject, Inherited, Option<usize>)> =
        vec![(pages_root, Inherited::default(), root_span)];

    while let Some((node, inherited, expected_span)) = stack.pop() {
        // Resolve the node to a dictionary, remembering its id when it is
        // (as the spec requires) an indirect reference.
        let (resolved, node_id) = match node {
            PdfObject::Reference(id) => {
                if !visited.insert(id) {
                    ctx.recovery.push(RecoveryEvent::Other(format!(
                        "page tree cycle at {id}; subtree skipped"
                    )));
                    continue;
                }
                match resolver.resolve(id, ctx) {
                    Ok(value) => (value, Some(id)),
                    Err(e) => {
                        ctx.recovery.push(RecoveryEvent::Other(format!(
                            "page tree node {id} unreadable ({e}); skipped"
                        )));
                        lost_subtrees += 1;
                        append_inferred_placeholders(
                            &mut pages,
                            expected_span,
                            &inherited,
                            limits.max_pages,
                            ctx,
                            &format!("unreadable page-tree node {id}"),
                        )?;
                        continue;
                    }
                }
            }
            direct => (std::sync::Arc::new(direct), None),
        };
        let Some(dict) = resolved.as_dict() else {
            ctx.recovery.push(RecoveryEvent::Other(format!(
                "page tree node is a {}, not a dictionary; skipped",
                kind_name(&resolved)
            )));
            // A dangling kid resolves to Null in the tolerant resolver —
            // the truncated-tail shape; counts as a lost subtree.
            lost_subtrees += 1;
            append_inferred_placeholders(
                &mut pages,
                expected_span,
                &inherited,
                limits.max_pages,
                ctx,
                "non-dictionary page-tree node",
            )?;
            continue;
        };

        let inherited = inherited.updated_from(dict, resolver, ctx);

        // Interior node iff it has /Kids (tolerates missing /Type — PDFium
        // treats nodes without kids as leaves).
        if let Some(kids_value) = dict.get(names.known.kids) {
            let kids = match resolver.resolve_value(kids_value, ctx) {
                Ok(v) => v,
                Err(e) => {
                    ctx.recovery.push(RecoveryEvent::Other(format!(
                        "unreadable /Kids ({e}); subtree skipped"
                    )));
                    lost_subtrees += 1;
                    append_inferred_placeholders(
                        &mut pages,
                        expected_span,
                        &inherited,
                        limits.max_pages,
                        ctx,
                        "unreadable /Kids",
                    )?;
                    continue;
                }
            };
            let PdfObject::Array(kids) = &*kids else {
                ctx.recovery.push(RecoveryEvent::Other(
                    "/Kids is not an array; subtree skipped".into(),
                ));
                lost_subtrees += 1;
                append_inferred_placeholders(
                    &mut pages,
                    expected_span,
                    &inherited,
                    limits.max_pages,
                    ctx,
                    "non-array /Kids",
                )?;
                continue;
            };
            let spans = infer_child_spans(dict, kids, resolver, ctx);
            for (kid, span) in kids.iter().zip(spans).rev() {
                stack.push((kid.clone(), inherited.clone(), span));
            }
            continue;
        }

        // Leaf. A direct (inline-dict) page has no object id, but everything
        // rendering needs — MediaBox/CropBox/rotate/resources/contents/annots —
        // is read from the resolved dict right here, so `object: None` is fine;
        // PDFium renders such pages, so dropping them was a recovery gap.
        if limits.max_pages > 0 && pages.len() as u32 >= limits.max_pages {
            return Err(DocumentError::LimitExceeded("max_pages"));
        }

        let media_box = inherited.media_box.unwrap_or(LETTER);
        let crop_box = clamp_to(inherited.crop_box.unwrap_or(media_box), media_box);
        let boxes = resolve_page_boxes(dict, media_box, crop_box, resolver, ctx);
        pages.push(PageRef {
            index: PageIndex(pages.len() as u32),
            object: node_id,
            media_box,
            crop_box,
            bleed_box: boxes.bleed,
            trim_box: boxes.trim,
            art_box: boxes.art,
            rotate: normalize_rotation(inherited.rotate.unwrap_or(0)),
            resources: inherited.resources.clone(),
            contents: dict.get(names.known.contents).cloned(),
            annotations: parse_annots(dict.get(names.intern(b"Annots")), resolver, ctx),
        });
        real_pages += 1;
    }

    // PDFium-parity placeholder synthesis: PDFium reports the root's
    // declared /Count and yields null (blank) pages for subtrees it cannot
    // load — typically a physically truncated file whose tail kids point
    // past EOF (the Hoyos "739 vs 845" case). When subtrees were provably
    // lost AND the declaration exceeds what the walk recovered, append
    // blank placeholder pages so page counts (and diff-tool page keys)
    // line up with the oracle. Never triggered by a merely lying /Count:
    // it requires an actual unresolvable subtree.
    if lost_subtrees > 0
        && let Some(declared) = declared_count
        && declared > pages.len() as i64
        && (limits.max_pages == 0 || declared <= limits.max_pages as i64)
    {
        let missing = declared as usize - pages.len();
        ctx.recovery.push(RecoveryEvent::Other(format!(
            "page tree declares {declared} pages but only {real_pages} were recoverable \
             ({lost_subtrees} lost subtrees); appending {missing} ambiguous blank \
             placeholder pages at the tail (PDFium count parity)"
        )));
        append_blank_pages(&mut pages, missing, &Inherited::default(), limits.max_pages)?;
    }

    Ok((
        PageTreeIndex::from_pages(pages.into_boxed_slice()),
        WalkStats {
            real_pages,
            lost_subtrees,
        },
    ))
}

/// Estimate each child's leaf span without trusting `/Count` for the normal
/// walk. Counts are used only to position a blank hole if a child later proves
/// unreadable. One unknown gets the exact parent residual; multiple unknowns
/// are exact only when the residual is one leaf apiece.
fn infer_child_spans(
    parent: &Dictionary,
    kids: &[PdfObject],
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Vec<Option<usize>> {
    let mut spans = kids
        .iter()
        .map(|kid| declared_child_span(kid, resolver, ctx))
        .collect::<Vec<_>>();
    let unknown = spans
        .iter()
        .enumerate()
        .filter_map(|(index, span)| span.is_none().then_some(index))
        .collect::<Vec<_>>();
    if unknown.is_empty() {
        return spans;
    }

    let Some(declared) = resolve_int(parent.get(resolver.names.intern(b"Count")), resolver, ctx)
        .and_then(|value| usize::try_from(value).ok())
        .filter(|&value| {
            resolver.limits.max_pages == 0 || value <= resolver.limits.max_pages as usize
        })
    else {
        return spans;
    };
    let Some(known) = spans
        .iter()
        .flatten()
        .try_fold(0usize, |sum, &span| sum.checked_add(span))
    else {
        return spans;
    };
    let Some(residual) = declared.checked_sub(known) else {
        return spans;
    };

    if unknown.len() == 1 {
        spans[unknown[0]] = Some(residual);
    } else if residual == unknown.len() {
        for index in unknown {
            spans[index] = Some(1);
        }
    }
    spans
}

fn declared_child_span(
    child: &PdfObject,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<usize> {
    let resolved = resolver.resolve_value(child, ctx).ok()?;
    let dict = resolved.as_dict()?;
    if dict.contains_key(resolver.names.known.kids) {
        resolve_int(dict.get(resolver.names.intern(b"Count")), resolver, ctx)
            .and_then(|value| usize::try_from(value).ok())
            .filter(|&value| {
                resolver.limits.max_pages == 0 || value <= resolver.limits.max_pages as usize
            })
    } else {
        Some(1)
    }
}

fn append_inferred_placeholders(
    pages: &mut Vec<PageRef>,
    count: Option<usize>,
    inherited: &Inherited,
    max_pages: u32,
    ctx: &mut ParseContext,
    reason: &str,
) -> Result<(), DocumentError> {
    let Some(count) = count.filter(|&count| count > 0) else {
        return Ok(());
    };
    ctx.recovery.push(RecoveryEvent::Other(format!(
        "{reason}; inserted {count} blank placeholder page(s) at the lost tree position"
    )));
    append_blank_pages(pages, count, inherited, max_pages)
}

fn append_blank_pages(
    pages: &mut Vec<PageRef>,
    count: usize,
    inherited: &Inherited,
    max_pages: u32,
) -> Result<(), DocumentError> {
    let final_len = pages
        .len()
        .checked_add(count)
        .ok_or(DocumentError::LimitExceeded("max_pages"))?;
    if max_pages > 0 && final_len > max_pages as usize {
        return Err(DocumentError::LimitExceeded("max_pages"));
    }
    let media_box = inherited.media_box.unwrap_or(LETTER);
    let crop_box = clamp_to(inherited.crop_box.unwrap_or(media_box), media_box);
    // A placeholder has no page dictionary, so the non-inheritable boxes take
    // their default: the CropBox.
    let boxes = PageBoxes::all(crop_box);
    for _ in 0..count {
        pages.push(PageRef {
            index: PageIndex(pages.len() as u32),
            object: None,
            media_box,
            crop_box,
            bleed_box: boxes.bleed,
            trim_box: boxes.trim,
            art_box: boxes.art,
            rotate: normalize_rotation(inherited.rotate.unwrap_or(0)),
            resources: inherited.resources.clone(),
            contents: None,
            annotations: std::sync::Arc::from(Vec::new()),
        });
    }
    Ok(())
}

/// Last-resort recovery for a rebuilt document whose page-tree walk still
/// found no real pages: inspect every live xref object for orphan `/Type /Page`
/// dictionaries and synthesize a deterministic index in object-number order.
///
/// This is deliberately narrower than the normal walk. It runs only after the
/// caller has tried both the loaded and fully rebuilt structures, so explicit
/// `/Type /Page` is required and ordinary documents never pay for the scan.
/// Parent links are followed only to recover inheritable page attributes; a
/// malformed/cyclic chain is tolerated and bounded by `max_reference_chain`.
pub(crate) fn recover_orphan_pages(
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> PageTreeIndex {
    let names = resolver.names;
    let page_name = names.intern(b"Page");
    let parent_name = names.intern(b"Parent");
    let mut pages = Vec::new();

    for entry in resolver.structure.xref.live_entries() {
        if resolver.limits.max_pages > 0 && pages.len() as u32 >= resolver.limits.max_pages {
            ctx.recovery.push(RecoveryEvent::Other(format!(
                "orphan /Type/Page recovery truncated at max_pages={}",
                resolver.limits.max_pages
            )));
            break;
        }

        let resolved = match resolver.resolve(entry.id, ctx) {
            Ok(value) => value,
            Err(_) => continue,
        };
        let Some(dict) = resolved.as_dict() else {
            continue;
        };
        if dict.get(names.known.type_).and_then(PdfObject::as_name) != Some(page_name)
            || dict.contains_key(names.known.kids)
        {
            continue;
        }

        // Collect parents leaf→root, then apply them root→leaf so nearer
        // dictionaries override inherited values exactly like the normal walk.
        let mut ancestors = Vec::new();
        let mut seen = HashSet::new();
        let mut parent = dict.get(parent_name).cloned();
        for _ in 0..resolver.limits.max_reference_chain {
            let Some(value) = parent.take() else {
                break;
            };
            if let PdfObject::Reference(id) = value
                && !seen.insert(id)
            {
                ctx.recovery.push(RecoveryEvent::Other(format!(
                    "orphan page {0} has a cyclic /Parent chain at {id}",
                    entry.id
                )));
                break;
            }
            let Ok(node) = resolver.resolve_value(&value, ctx) else {
                break;
            };
            let Some(parent_dict) = node.as_dict() else {
                break;
            };
            parent = parent_dict.get(parent_name).cloned();
            ancestors.push(node);
        }

        let mut inherited = Inherited::default();
        for ancestor in ancestors.iter().rev() {
            if let Some(parent_dict) = ancestor.as_dict() {
                inherited = inherited.updated_from(parent_dict, resolver, ctx);
            }
        }
        inherited = inherited.updated_from(dict, resolver, ctx);
        let media_box = inherited.media_box.unwrap_or(LETTER);
        let crop_box = clamp_to(inherited.crop_box.unwrap_or(media_box), media_box);
        let boxes = resolve_page_boxes(dict, media_box, crop_box, resolver, ctx);
        pages.push(PageRef {
            index: PageIndex(pages.len() as u32),
            object: Some(entry.id),
            media_box,
            crop_box,
            bleed_box: boxes.bleed,
            trim_box: boxes.trim,
            art_box: boxes.art,
            rotate: normalize_rotation(inherited.rotate.unwrap_or(0)),
            resources: inherited.resources,
            contents: dict.get(names.known.contents).cloned(),
            annotations: parse_annots(dict.get(names.intern(b"Annots")), resolver, ctx),
        });
    }

    if !pages.is_empty() {
        ctx.recovery.push(RecoveryEvent::Other(format!(
            "page tree remained empty after xref rebuild; recovered {} orphan /Type/Page objects in object-number order",
            pages.len()
        )));
    }
    PageTreeIndex::from_pages(pages.into_boxed_slice())
}

/// Parse a page's `/Annots` array into [`PageAnnotation`]s.
///
/// Recovery-driven: a broken entry is skipped with a note, never fatal.
/// `/Popup` annotations are structurally skipped, matching PDFium's
/// `CPDF_AnnotList` (cpdf_annotlist.cpp — popups are folded into their
/// parents at list-build time and never drawn standalone).
fn parse_annots(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> std::sync::Arc<[PageAnnotation]> {
    let names = resolver.names;
    let mut out: Vec<PageAnnotation> = Vec::new();
    let Some(value) = value else {
        return out.into();
    };
    let resolved = match resolver.resolve_value(value, ctx) {
        Ok(v) => v,
        Err(e) => {
            ctx.recovery.push(RecoveryEvent::Other(format!(
                "unreadable /Annots ({e}); skipped"
            )));
            return out.into();
        }
    };
    let PdfObject::Array(items) = &*resolved else {
        if !matches!(&*resolved, PdfObject::Null) {
            ctx.recovery.push(RecoveryEvent::Other(
                "/Annots is not an array; skipped".into(),
            ));
        }
        return out.into();
    };
    for item in items.iter() {
        let entry = match resolver.resolve_value(item, ctx) {
            Ok(v) => v,
            Err(e) => {
                ctx.recovery.push(RecoveryEvent::Other(format!(
                    "annotation entry unreadable ({e}); skipped"
                )));
                continue;
            }
        };
        let Some(dict) = entry.as_dict() else {
            // Nulls (freed annots) are silently common; only note real junk.
            if !matches!(&*entry, PdfObject::Null) {
                ctx.recovery.push(RecoveryEvent::Other(
                    "annotation entry is not a dictionary; skipped".into(),
                ));
            }
            continue;
        };
        let subtype = dict.get(names.known.subtype).and_then(PdfObject::as_name);
        if let Some(s) = subtype
            && names.resolve(s).as_ref() == b"Popup"
        {
            continue;
        }
        out.push(PageAnnotation {
            subtype,
            source: item.as_reference(),
            rect: annot_rect(dict.get(names.intern(b"Rect")), resolver, ctx),
            flags: resolve_int(dict.get(names.intern(b"F")), resolver, ctx)
                .map_or(0, |f| f.clamp(0, u32::MAX as i64) as u32),
            appearance: dict.get(names.intern(b"AP")).cloned(),
            appearance_state: dict.get(names.intern(b"AS")).and_then(PdfObject::as_name),
            destination: dict.get(names.intern(b"Dest")).cloned(),
            action: dict.get(names.intern(b"A")).cloned(),
            quad_points: annot_quad_points(dict.get(names.intern(b"QuadPoints")), resolver, ctx),
            color: annot_color(dict.get(names.intern(b"C")), resolver, ctx),
            opacity: resolve_number(dict.get(names.intern(b"CA")), resolver, ctx)
                .unwrap_or(1.0)
                .clamp(0.0, 1.0) as f32,
            contents: annot_text(dict.get(names.intern(b"Contents")), resolver, ctx),
            name: annot_text(dict.get(names.intern(b"NM")), resolver, ctx),
            modified: annot_text(dict.get(names.intern(b"M")), resolver, ctx),
            creation_date: annot_text(dict.get(names.intern(b"CreationDate")), resolver, ctx),
            author: annot_text(dict.get(names.intern(b"T")), resolver, ctx),
            subject: annot_text(dict.get(names.intern(b"Subj")), resolver, ctx),
            intent: annot_name(dict.get(names.intern(b"IT")), resolver, ctx),
        });
    }
    out.into()
}

fn resolve_number(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<f64> {
    resolver
        .resolve_value(value?, ctx)
        .ok()?
        .as_number()
        .filter(|number| number.is_finite())
}

fn annot_numbers(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<Vec<f64>> {
    let resolved = resolver.resolve_value(value?, ctx).ok()?;
    let PdfObject::Array(items) = &*resolved else {
        return None;
    };
    items
        .iter()
        .map(|item| {
            resolver
                .resolve_value(item, ctx)
                .ok()?
                .as_number()
                .filter(|number| number.is_finite())
        })
        .collect()
}

fn annot_quad_points(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> std::sync::Arc<[[f64; 8]]> {
    let Some(numbers) = annot_numbers(value, resolver, ctx) else {
        return std::sync::Arc::from([]);
    };
    numbers
        .chunks_exact(8)
        .map(|chunk| {
            let mut quad = [0.0; 8];
            quad.copy_from_slice(chunk);
            quad
        })
        .collect::<Vec<[f64; 8]>>()
        .into()
}

fn annot_color(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<crate::document::AnnotationColor> {
    let numbers = annot_numbers(value, resolver, ctx)?;
    let c = |index: usize| numbers[index].clamp(0.0, 1.0) as f32;
    match numbers.len() {
        1 => Some(crate::document::AnnotationColor::Gray(c(0))),
        3 => Some(crate::document::AnnotationColor::Rgb([c(0), c(1), c(2)])),
        4 => Some(crate::document::AnnotationColor::Cmyk([
            c(0),
            c(1),
            c(2),
            c(3),
        ])),
        _ => None,
    }
}

/// An annotation's text-string field (`/Contents`, `/NM`, `/M`,
/// `/CreationDate`, `/T`, `/Subj`): resolved when indirect, decoded lossy.
/// Anything that is not a string — including a missing key — stays `None`.
fn annot_text(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<String> {
    let resolved = resolver.resolve_value(value?, ctx).ok()?;
    match &*resolved {
        PdfObject::String(text) => Some(decode_text_string_lossy(text.as_bytes())),
        _ => None,
    }
}

/// An annotation's name field (`/IT` intent): resolved when indirect, read
/// as the name's bytes. Anything that is not a name stays `None`.
fn annot_name(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<String> {
    let resolved = resolver.resolve_value(value?, ctx).ok()?;
    match &*resolved {
        PdfObject::Name(id) => {
            Some(String::from_utf8_lossy(&resolver.names.resolve(*id)).into_owned())
        }
        _ => None,
    }
}

/// An annotation's `/Rect`: corner-normalized but *not* required to have
/// positive area (a degenerate rect is kept and skipped at render time,
/// so `[0,0,0,0]` doubles as the missing/invalid marker).
fn annot_rect(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> [f64; 4] {
    let Some(value) = value else { return [0.0; 4] };
    let Ok(resolved) = resolver.resolve_value(value, ctx) else {
        return [0.0; 4];
    };
    let PdfObject::Array(items) = &*resolved else {
        return [0.0; 4];
    };
    if items.len() < 4 {
        return [0.0; 4];
    }
    let mut n = [0f64; 4];
    for (i, item) in items.iter().take(4).enumerate() {
        let Some(v) = resolver
            .resolve_value(item, ctx)
            .ok()
            .and_then(|o| o.as_number())
            .filter(|v| v.is_finite())
        else {
            return [0.0; 4];
        };
        n[i] = v;
    }
    [
        n[0].min(n[2]),
        n[1].min(n[3]),
        n[0].max(n[2]),
        n[1].max(n[3]),
    ]
}

/// Resolve a (possibly indirect) rectangle: 4 numbers, themselves possibly
/// indirect. Invalid or empty rectangles yield `None` (caller defaults).
fn resolve_rect(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<[f64; 4]> {
    let value = resolver.resolve_value(value?, ctx).ok()?;
    let PdfObject::Array(items) = &*value else {
        return None;
    };
    if items.len() < 4 {
        return None;
    }
    let mut n = [0f64; 4];
    for (i, item) in items.iter().take(4).enumerate() {
        n[i] = resolver.resolve_value(item, ctx).ok()?.as_number()?;
        if !n[i].is_finite() {
            return None;
        }
    }
    // Normalize corner order.
    let rect = [
        n[0].min(n[2]),
        n[1].min(n[3]),
        n[0].max(n[2]),
        n[1].max(n[3]),
    ];
    // Zero-area boxes are treated as absent (PDFium falls back to Letter).
    if rect[2] - rect[0] <= 0.0 || rect[3] - rect[1] <= 0.0 {
        return None;
    }
    Some(rect)
}

fn resolve_int(
    value: Option<&PdfObject>,
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> Option<i64> {
    let value = resolver.resolve_value(value?, ctx).ok()?;
    match &*value {
        PdfObject::Integer(i) => Some(*i),
        // Real-valued /Rotate occurs in the wild; truncate like PDFium's
        // GetInteger.
        PdfObject::Real(r) if r.is_finite() => Some(*r as i64),
        _ => None,
    }
}

/// Normalize `/Rotate` into {0, 90, 180, 270}: reduce modulo 360 (negative
/// values wrap), and treat non-multiples of 90 as 0 (invalid per spec).
fn normalize_rotation(rotate: i64) -> u16 {
    let r = rotate.rem_euclid(360);
    if r % 90 == 0 { r as u16 } else { 0 }
}

/// Intersect `rect` with `bounds`, or `None` when the intersection has no
/// area (a box entirely outside its bounds is meaningless).
fn intersect(rect: [f64; 4], bounds: [f64; 4]) -> Option<[f64; 4]> {
    let out = [
        rect[0].max(bounds[0]),
        rect[1].max(bounds[1]),
        rect[2].min(bounds[2]),
        rect[3].min(bounds[3]),
    ];
    (out[2] - out[0] > 0.0 && out[3] - out[1] > 0.0).then_some(out)
}

/// Intersect `rect` with `bounds`; an empty intersection collapses to
/// `bounds` (a CropBox entirely outside the MediaBox is ignored).
fn clamp_to(rect: [f64; 4], bounds: [f64; 4]) -> [f64; 4] {
    intersect(rect, bounds).unwrap_or(bounds)
}

/// The non-inheritable page boxes: `/BleedBox`, `/TrimBox`, `/ArtBox`
/// (ISO 32000-1 §14.11.2, Table 30).
///
/// Each is read from the page's **own** dictionary only — unlike
/// MediaBox/CropBox/Resources/Rotate these do not inherit through `/Parent`.
/// Each is clamped to `media_box` exactly as CropBox is, and falls back to
/// `crop_box` when absent, malformed, degenerate, or disjoint from the
/// MediaBox. Since `crop_box` itself defaults to `media_box`, the spec's
/// chain "Art/Trim/Bleed → Crop → Media" holds.
fn resolve_page_boxes(
    dict: &Dictionary,
    media_box: [f64; 4],
    crop_box: [f64; 4],
    resolver: &Resolver<'_>,
    ctx: &mut ParseContext,
) -> PageBoxes {
    let names = resolver.names;
    let mut one = |key: &[u8]| {
        resolve_rect(dict.get(names.intern(key)), resolver, ctx)
            .and_then(|rect| intersect(rect, media_box))
            .unwrap_or(crop_box)
    };
    PageBoxes {
        bleed: one(b"BleedBox"),
        trim: one(b"TrimBox"),
        art: one(b"ArtBox"),
    }
}

/// The three non-inheritable boxes, resolved together.
#[derive(Debug, Clone, Copy)]
struct PageBoxes {
    bleed: [f64; 4],
    trim: [f64; 4],
    art: [f64; 4],
}

impl PageBoxes {
    /// The defaulting case: no page dictionary to read from (a synthesized
    /// blank placeholder), so every box collapses to the CropBox.
    const fn all(rect: [f64; 4]) -> Self {
        Self {
            bleed: rect,
            trim: rect,
            art: rect,
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;

    #[test]
    fn rotation_normalizes() {
        assert_eq!(normalize_rotation(0), 0);
        assert_eq!(normalize_rotation(90), 90);
        assert_eq!(normalize_rotation(360), 0);
        assert_eq!(normalize_rotation(450), 90);
        assert_eq!(normalize_rotation(-90), 270);
        assert_eq!(normalize_rotation(-450), 270);
        assert_eq!(normalize_rotation(45), 0);
        assert_eq!(normalize_rotation(123), 0);
    }

    #[test]
    fn crop_clamps_and_collapses() {
        let media = [0.0, 0.0, 612.0, 792.0];
        assert_eq!(
            clamp_to([100.0, 100.0, 500.0, 700.0], media),
            [100.0, 100.0, 500.0, 700.0]
        );
        assert_eq!(clamp_to([-50.0, -50.0, 700.0, 900.0], media), media);
        // Disjoint crop box → media box.
        assert_eq!(clamp_to([1000.0, 1000.0, 2000.0, 2000.0], media), media);
    }

    #[test]
    fn intersect_rejects_empty_and_disjoint() {
        let media = [0.0, 0.0, 612.0, 792.0];
        assert_eq!(
            intersect([100.0, 100.0, 500.0, 700.0], media),
            Some([100.0, 100.0, 500.0, 700.0])
        );
        // Oversized boxes are trimmed to the bounds.
        assert_eq!(intersect([-50.0, -50.0, 700.0, 900.0], media), Some(media));
        // Disjoint and edge-touching intersections have no area.
        assert_eq!(intersect([1000.0, 1000.0, 2000.0, 2000.0], media), None);
        assert_eq!(intersect([612.0, 0.0, 800.0, 792.0], media), None);
    }

    #[test]
    fn page_boxes_default_and_clamp() {
        // TrimBox is inset; BleedBox overhangs the MediaBox and is clamped to
        // it; ArtBox is absent and must fall back to CropBox.
        let page = single_page(
            "<< /Type /Pages /Count 1 /Kids [3 0 R] /MediaBox [0 0 612 792] >>",
            "<< /Type /Page /Parent 2 0 R /CropBox [10 10 600 780] \
             /TrimBox [50 50 500 700] /BleedBox [-20 -20 700 900] >>",
        );
        assert_eq!(page.media_box, [0.0, 0.0, 612.0, 792.0]);
        assert_eq!(page.crop_box, [10.0, 10.0, 600.0, 780.0]);
        assert_eq!(page.trim_box, [50.0, 50.0, 500.0, 700.0]);
        assert_eq!(page.bleed_box, [0.0, 0.0, 612.0, 792.0]);
        assert_eq!(page.art_box, page.crop_box);
    }

    #[test]
    fn page_boxes_do_not_inherit_but_crop_does() {
        // A TrimBox on the *parent* must be ignored: only Resources,
        // MediaBox, CropBox and Rotate inherit. CropBox does.
        let page = single_page(
            "<< /Type /Pages /Count 1 /Kids [3 0 R] /MediaBox [0 0 612 792] \
             /CropBox [5 5 605 785] /TrimBox [100 100 200 200] >>",
            "<< /Type /Page /Parent 2 0 R >>",
        );
        assert_eq!(page.crop_box, [5.0, 5.0, 605.0, 785.0]);
        assert_eq!(page.trim_box, page.crop_box);
        assert_eq!(page.bleed_box, page.crop_box);
        assert_eq!(page.art_box, page.crop_box);
    }

    #[test]
    fn degenerate_and_disjoint_page_boxes_fall_back_to_crop() {
        // Zero-width TrimBox, disjoint BleedBox, short ArtBox array.
        let page = single_page(
            "<< /Type /Pages /Count 1 /Kids [3 0 R] /MediaBox [0 0 612 792] >>",
            "<< /Type /Page /Parent 2 0 R /CropBox [10 10 600 780] \
             /TrimBox [100 100 100 400] /BleedBox [900 900 1000 1000] \
             /ArtBox [1 2 3] >>",
        );
        assert_eq!(page.crop_box, [10.0, 10.0, 600.0, 780.0]);
        assert_eq!(page.trim_box, page.crop_box);
        assert_eq!(page.bleed_box, page.crop_box);
        assert_eq!(page.art_box, page.crop_box);
    }

    #[test]
    fn missing_media_box_defaults_to_letter_and_boxes_follow() {
        let page = single_page(
            "<< /Type /Pages /Count 1 /Kids [3 0 R] >>",
            "<< /Type /Page /Parent 2 0 R >>",
        );
        assert_eq!(page.media_box, LETTER);
        assert_eq!(page.crop_box, LETTER);
        assert_eq!(page.bleed_box, LETTER);
        assert_eq!(page.trim_box, LETTER);
        assert_eq!(page.art_box, LETTER);
    }

    /// Build a one-page document from a page-tree root and a page dictionary,
    /// open it, and return the single resolved [`crate::document::PageRef`].
    fn single_page(pages_dict: &str, page_dict: &str) -> crate::document::PageRef {
        use crate::test_support::builder::PdfBuilder;

        let mut builder = PdfBuilder::new();
        builder.add_object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        builder.add_object(2, pages_dict);
        builder.add_object(3, page_dict);
        builder.finish_classic_xref("/Root 1 0 R");
        let source: std::sync::Arc<dyn crate::source::PdfSource> =
            std::sync::Arc::new(crate::source::OwnedBytesSource::new(builder.into_bytes()));
        let snapshot = crate::document::DocumentSnapshot::open(
            source,
            crate::document::DocumentLimits::default(),
        )
        .expect("document opens");
        assert_eq!(snapshot.page_count(), 1);
        snapshot.page(PageIndex(0)).expect("page 0").clone()
    }
}