Skip to main content

pdfcer_model/
page_tree.rs

1//! # Page tree walk + attribute inheritance (ISO 32000-1 §7.7.3, §7.9.5)
2//!
3//! Flattens the document's page tree into ordered, fully-resolved
4//! [`Page`]s. Spec sources: `iso32000__s__7.7.3.md` (tree structure,
5//! Tables 29/30, the inheritance rules) and `iso32000__s__7.9.5.md`
6//! (rectangle corner normalization) in the PDF-spec RAG. Clause
7//! numbers are ISO 32000-1:2008.
8//!
9//! ## The four inheritable attributes (§7.7.3.4 — exactly four)
10//!
11//! `Resources`, `MediaBox`, `CropBox`, `Rotate` — verified in the RAG
12//! by exhaustive search of Table 30's inheritable markers. Nothing
13//! else inherits; in particular `BleedBox`/`TrimBox`/`ArtBox` do NOT
14//! walk ancestors (they default to the resolved `CropBox`).
15//!
16//! Resolution, per attribute (§7.7.3.4):
17//! - `Resources`: own → nearest ancestor; **required** to resolve.
18//!   **Present-but-empty `<< >>` means "no resources" and STOPS
19//!   inheritance — different from absent (absent = inherit).** This
20//!   normative distinction is a common implementation bug (RAG note).
21//! - `MediaBox`: own → nearest ancestor; required to resolve.
22//! - `CropBox`: own → nearest ancestor → default = resolved `MediaBox`.
23//! - `Rotate`: own → nearest ancestor → default = 0. Shall be a
24//!   multiple of 90; negative multiples are legal and normalize via
25//!   positive modulo (`-90` → `270`).
26//!
27//! Inheritance is resolved **top-down during the walk** (O(n), needs
28//! no `Parent` chasing), not bottom-up via `/Parent`.
29//!
30//! ## Structure tolerance and guards
31//!
32//! "Conforming products shall be prepared to handle any form of tree
33//! structure" (§7.7.3.1) — so no shape assumptions. Node kind is
34//! dispatched on `/Type` where present, falling back to structural
35//! detection (`Kids` present ⇒ intermediate node) where absent —
36//! Table 29/30 mark `/Type` Required, so absence is malformed but
37//! recoverable, and §7.3.7 says type is "almost always inferable from
38//! context". `Count` is a cross-check only, never trusted — a damaged
39//! `Count` must not truncate the walk (RAG guard note). `Kids` cycles
40//! and hostile depth are guarded ([`MAX_TREE_DEPTH`], [`MAX_PAGES`],
41//! plus a visited-set — ARCHITECTURE.md §10 policy values, not spec).
42
43use std::collections::HashSet;
44
45use crate::document::Document;
46use crate::graph::ObjectGraph;
47use crate::object::{Dict, ObjId, Object};
48use crate::view::DocumentView;
49
50/// Maximum page-tree nesting depth (pdfcer policy, ARCHITECTURE.md
51/// §10): legitimate trees are shallow (balanced fan-out ~25–50); a
52/// deeper chain is damage or hostility.
53pub const MAX_TREE_DEPTH: usize = 64;
54
55/// Maximum number of pages walked (pdfcer policy, ARCHITECTURE.md
56/// §10.1): bounds allocation against a hostile tree. Far beyond any
57/// legitimate document.
58pub const MAX_PAGES: usize = 1_000_000;
59
60/// A rectangle normalized per §7.9.5: the array `[x1 y1 x2 y2]` gives
61/// two diagonally opposite corners **in either order**, so consumers
62/// must normalize — this type stores (min, min) → (max, max) always.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct Rect {
65    /// Lower-left x (the smaller x).
66    pub llx: f64,
67    /// Lower-left y (the smaller y).
68    pub lly: f64,
69    /// Upper-right x (the larger x).
70    pub urx: f64,
71    /// Upper-right y (the larger y).
72    pub ury: f64,
73}
74
75impl Rect {
76    /// Normalize two arbitrary diagonal corners into a `Rect`
77    /// (§7.9.5's corners-in-any-order rule).
78    #[must_use]
79    pub fn from_corners(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
80        Self {
81            llx: x1.min(x2),
82            lly: y1.min(y2),
83            urx: x1.max(x2),
84            ury: y1.max(y2),
85        }
86    }
87
88    /// Width (always non-negative by construction).
89    #[must_use]
90    pub fn width(&self) -> f64 {
91        self.urx - self.llx
92    }
93
94    /// Height (always non-negative by construction).
95    #[must_use]
96    pub fn height(&self) -> f64 {
97        self.ury - self.lly
98    }
99
100    /// Whether `other` lies wholly inside this rectangle, edges included.
101    ///
102    /// **Inclusive on every edge**, which is the answer the page-boundary
103    /// questions want: §14.11.2's boxes routinely coincide exactly (Table
104    /// 30 makes `CropBox` *default* to `MediaBox`, and the defaulted case
105    /// must not report itself as "outside"), and a page whose crop box
106    /// equals its media box is the overwhelmingly common shape.
107    ///
108    /// Both rectangles are assumed §7.9.5-normalized — true by
109    /// construction for anything from [`Rect::from_corners`] or from the
110    /// page-tree walk, which is every `Rect` pdfcer produces.
111    #[must_use]
112    pub fn contains(&self, other: &Self) -> bool {
113        other.llx >= self.llx
114            && other.lly >= self.lly
115            && other.urx <= self.urx
116            && other.ury <= self.ury
117    }
118
119    /// The overlap of two rectangles, or `None` when it has no area
120    /// (disjoint, or touching only along an edge or at a corner).
121    ///
122    /// A zero-area overlap is `None` rather than a degenerate `Rect`
123    /// because every caller is resolving a page box, and a page box with
124    /// no area frames nothing (ISO 32000-2 §14.11.2.1 leaves that case
125    /// undefined — ambiguity PB-A1).
126    #[must_use]
127    pub fn intersection(&self, other: &Self) -> Option<Self> {
128        let r = Self {
129            llx: self.llx.max(other.llx),
130            lly: self.lly.max(other.lly),
131            urx: self.urx.min(other.urx),
132            ury: self.ury.min(other.ury),
133        };
134        (r.urx > r.llx && r.ury > r.lly).then_some(r)
135    }
136}
137
138/// How a resolved page box ([`Page::crop_box`], [`Page::bleed_box`],
139/// [`Page::trim_box`], [`Page::art_box`]) relates to what the file wrote.
140///
141/// ISO 32000-2 §14.11.2.1: "If the bounds of the crop, trim, bleed or art
142/// box extends outside of the bounds of the media box, a processor shall
143/// treat the box as its intersection with the media box." Every resolved
144/// box is therefore already clipped to [`Page::media_box`]; this says
145/// whether that changed anything. Report anything but `Defaulted` /
146/// `AsWritten` off-canvas (project rule 4) — the file is not rewritten.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
148#[non_exhaustive]
149pub enum BoxResolution {
150    /// The file wrote no such box (nor, for `CropBox`, did an ancestor);
151    /// the Table 30 default is in use.
152    #[default]
153    Defaulted,
154    /// The written box lies inside the media box and is used unchanged.
155    AsWritten,
156    /// The written box extended beyond the media box and was reduced to
157    /// the intersection.
158    Clipped,
159    /// The written box could not be used and the Table 30 default is in
160    /// use instead: its intersection with the media box has no area
161    /// (the spec leaves this undefined, PB-A1), or — for the three
162    /// non-inheritable boxes only — it is not a four-number array.
163    ///
164    /// Falling back to the default rather than framing an empty page is
165    /// pdfcer's choice for PB-A1; a caller that wants the other answer
166    /// (render nothing) can act on this variant.
167    Unusable,
168}
169
170/// One page, fully resolved: every inheritable attribute has its final
171/// value, defaults applied.
172#[derive(Debug, Clone)]
173pub struct Page {
174    /// The page object's identity (pages are always reached through
175    /// indirect `Kids` references, so this is always known).
176    pub id: ObjId,
177    /// Resolved `Resources` (§7.8.3) — own, inherited, the page's
178    /// explicit empty dictionary, or (when the attribute is on neither the
179    /// page nor any ancestor) the empty dictionary pdfcer supplied, which
180    /// [`Self::resources_defaulted`] discloses.
181    pub resources: Dict,
182    /// `true` when `/Resources` was on **neither the page nor any
183    /// ancestor**, and this page's [`Self::resources`] is therefore the
184    /// empty dictionary pdfcer supplied rather than one the file wrote.
185    ///
186    /// # Why this is a disclosure rather than a refusal
187    ///
188    /// §7.7.3.3 Table 30 lists `/Resources` as *required; inheritable*, and
189    /// §7.7.3.4 says a value "shall be supplied in an ancestor node" when a
190    /// page has none of its own. A file that satisfies neither is
191    /// non-conforming — but non-conforming is not the same as unreadable,
192    /// and until `Pass 290.0` this attribute alone cost the operator every
193    /// page of the document, including the well-formed ones, because the
194    /// walk returns one `Result` for the whole page tree.
195    ///
196    /// Two files make the case concretely:
197    ///
198    ///   * **Acrobat writes pages like this.** A user-created stamp
199    ///     collection under `%APPDATA%\Adobe\Acrobat\DC\Stamps\` holds a
200    ///     blank spacer page with no `/Contents` and no `/Resources`
201    ///     between two complete stamp pages. The file is what Acrobat uses
202    ///     to sign a document; every reader opens it; pdfcer refused all
203    ///     three pages.
204    ///   * **`fixtures/synthetic/minimal.pdf` — pdfcer's own smallest legal
205    ///     fixture — has no `/Resources`**, so the project shipped a page
206    ///     tree walk that could not read its own minimal file.
207    ///
208    /// # What is and is not claimed when this is `true`
209    ///
210    /// Nothing is invented, and the value is the standard's own: Table 30's
211    /// `/Resources` row says "If the page requires no resources, the value
212    /// of this entry shall be an empty dictionary". A name looked up in the
213    /// dictionary pdfcer supplies fails exactly as it fails in an explicit
214    /// `<< >>` that any file could have written legally — and those failures
215    /// are already counted, one by one, by the renderer
216    /// (`fonts_unsupported`, `cs_unresolved`, unpainted forms) and by the
217    /// extractor. **This flag is the single cause behind them.**
218    ///
219    /// ⚠ It is NOT a claim that the page was harmless. In particular, do not
220    /// reason that a page with no `/Contents` can name nothing: §7.8.3's
221    /// third bullet lets form XObjects and Type 3 fonts omit their own
222    /// `/Resources` and inherit the page's, and ISO 32000-2's erratum
223    /// extends that to **annotation appearance streams**. A page whose only
224    /// marks are annotation `/AP` forms — the shape that motivated this
225    /// Pass — is therefore a page that can genuinely need the dictionary it
226    /// does not have.
227    ///
228    /// # And the file is definitely non-conforming
229    ///
230    /// ISO considered conditioning the requirement on `/Contents` and
231    /// decided against it (`pdf-issues` #81, ISO approved), adding a NOTE to
232    /// ISO 32000-2's `/Contents` row: a `/Resources` dictionary must still
233    /// be present, directly or by inheritance. pdfcer says so rather than
234    /// pretending otherwise — it just does not make the operator pay for it
235    /// with the document. §2.2 scopes a reader's rendering duty to
236    /// *conforming* files and §1 excludes conformance validation from the
237    /// standard's scope, so refusal was never owed; it was chosen.
238    ///
239    /// # For a shell
240    ///
241    /// Report it off-canvas (project rule 4): the page renders normally,
242    /// and the fact that pdfcer supplied the dictionary belongs in a status
243    /// line or a report, never as a mark on the page.
244    pub resources_defaulted: bool,
245    /// Resolved `MediaBox`, normalized (§7.9.5).
246    pub media_box: Rect,
247    /// The effective `CropBox`: the resolved entry intersected with
248    /// [`Self::media_box`] (§14.11.2.1), or `media_box` when absent or
249    /// unusable. Content is clipped to this at display time (Table 30),
250    /// so this is the rectangle a renderer frames the page by. What the
251    /// file itself wrote is left in the file; see
252    /// [`Self::crop_box_resolution`].
253    pub crop_box: Rect,
254    /// How [`Self::crop_box`] was obtained from the file.
255    pub crop_box_resolution: BoxResolution,
256    /// The effective `BleedBox` (PDF 1.3, not inheritable): the page's own
257    /// entry intersected with [`Self::media_box`], else [`Self::crop_box`].
258    pub bleed_box: Rect,
259    /// How [`Self::bleed_box`] was obtained.
260    pub bleed_box_resolution: BoxResolution,
261    /// The effective `TrimBox` — the finished page after trimming; same
262    /// resolution rule as [`Self::bleed_box`].
263    pub trim_box: Rect,
264    /// How [`Self::trim_box`] was obtained.
265    pub trim_box_resolution: BoxResolution,
266    /// The effective `ArtBox` — the creator's meaningful content; same
267    /// resolution rule as [`Self::bleed_box`].
268    pub art_box: Rect,
269    /// How [`Self::art_box`] was obtained.
270    pub art_box_resolution: BoxResolution,
271    /// Resolved `Rotate`, normalized to {0, 90, 180, 270} — clockwise
272    /// display rotation (Table 30).
273    pub rotate: u16,
274    /// The `Contents` streams, in order (Table 30: a single stream or
275    /// an array whose streams concatenate; streams are always indirect
276    /// per §7.3.8.1, so these are always resolvable ids). Empty =
277    /// an empty page (absent `Contents` is NOT an error).
278    pub contents: Vec<ObjId>,
279    /// How many `Contents` entries named an object that is **not in the
280    /// file**, and therefore contribute nothing to this page.
281    ///
282    /// §7.3.10: "An indirect reference to an undefined object is not an
283    /// error; it shall be treated as a reference to the null object."
284    /// Table 30 then makes the consequence explicit for this key —
285    /// `Contents` is optional, and "if this entry is absent, the page
286    /// shall be empty". A dangling element is therefore a page that is
287    /// *incomplete*, not a document that is *invalid*, and refusing the
288    /// whole document over one would violate the §10 fail-clean posture
289    /// (a damaged part must not cost the operator the whole file).
290    ///
291    /// Non-zero means content the page asked for could not be drawn or
292    /// extracted. It is counted rather than silently swallowed because
293    /// "fuzzy, never sneaky" applies to omissions as much as to
294    /// suggestions: a silently-empty page is indistinguishable from a
295    /// genuinely blank one, and the operator would have no way to tell
296    /// that text they expected is missing.
297    ///
298    /// Note what this does **not** cover: an entry of the wrong *type* —
299    /// a number, a dictionary, an array element that is not a reference —
300    /// is a genuine structural error and still yields
301    /// [`PageTreeError::BadContents`]. Only "the reference resolves to
302    /// null" degrades.
303    pub contents_unresolved: usize,
304    /// How many **nested arrays** were flattened out of this page's
305    /// `/Contents` on the way in — the count of a specific, recognisable
306    /// damage that **pdfcer itself wrote** (`Pass 111.0`).
307    ///
308    /// # What the damage is, and why the repair is exact rather than a guess
309    ///
310    /// Until 2026-08-20, appending a content stream to a page whose
311    /// `/Contents` was an *indirect reference to an array* wrapped that
312    /// reference instead of splicing into it, producing
313    /// `/Contents [38 0 R, new]` where `38 0 R` dereferences to
314    /// `[7 0 R, 37 0 R]`. Nothing in Table 30 permits an array inside the
315    /// `/Contents` array, so this walker rejected the page with
316    /// [`PageTreeError::BadContents`] — and the file was one pdfcer had just
317    /// written and reported `Ok` for.
318    ///
319    /// **The repair is deterministic, which is the whole reason it is
320    /// allowed.** Flattening `[[a, b], c]` to `[a, b, c]` recovers exactly the
321    /// streams the page had, in exactly the order Table 30 concatenates them.
322    /// Nothing is inferred, chosen, or approximated — the nesting is pure
323    /// noise, and the correct reading is the only reading. Contrast
324    /// [`Self::contents_unresolved`], where content genuinely IS missing.
325    ///
326    /// # It is READ-side only — nothing is rewritten
327    ///
328    /// This makes a damaged document open, render and extract. It does **not**
329    /// repair the file: `ARCHITECTURE.md` §5 forbids normalising structure as
330    /// a side effect of reading, and an incremental save with no edits still
331    /// emits nothing. The page is repaired in the file only when something
332    /// else legitimately rewrites that page dictionary — at which point the
333    /// overlay append ([`plan_overlay_append`]) writes the flat form.
334    ///
335    /// Non-zero therefore means: *this document was damaged by a pdfcer build
336    /// older than `Pass 111.0`, and other readers may still refuse it.* That
337    /// is worth surfacing to an operator, which is why it is a counted
338    /// disclosure and not a silent kindness.
339    pub contents_flattened: usize,
340}
341
342/// Page-tree structural errors.
343#[derive(Debug, Clone, PartialEq, thiserror::Error)]
344#[non_exhaustive]
345pub enum PageTreeError {
346    /// The catalog has no usable `/Pages` entry.
347    #[error("catalog /Pages missing or not a dictionary")]
348    NoPageTreeRoot,
349    /// A `Kids` element resolved to something that is not a
350    /// dictionary (including a dangling reference's null).
351    #[error("page tree kid is not a dictionary (object {0})")]
352    BadKid(ObjId),
353    /// A node was visited twice — the tree has a cycle.
354    #[error("page tree cycle at object {0}")]
355    Cycle(ObjId),
356    /// Nesting exceeded [`MAX_TREE_DEPTH`] (pdfcer guard).
357    #[error("page tree exceeds MAX_TREE_DEPTH ({MAX_TREE_DEPTH})")]
358    TooDeep,
359    /// More than [`MAX_PAGES`] leaves (pdfcer guard).
360    #[error("page tree exceeds MAX_PAGES ({MAX_PAGES})")]
361    TooManyPages,
362    /// A required inheritable attribute resolved nowhere on the path to
363    /// the root (§7.7.3.4: "a value shall be supplied in an ancestor
364    /// node").
365    ///
366    /// **`MediaBox` only, since `Pass 290.0`.** `Resources` used to
367    /// produce this too, and it was the wrong severity for the wrong
368    /// attribute: an absent resource dictionary means "no named resource is
369    /// available", which is a statement the empty dictionary makes exactly,
370    /// whereas an absent `MediaBox` means the page has **no geometry** and
371    /// any value pdfcer chose (Letter? A4? the previous page's?) would be
372    /// invented. Continuing requires inventing nothing; that is the line
373    /// decision 145 draws, and `MediaBox` is on the other side of it. See
374    /// [`Page::resources_defaulted`].
375    #[error("required page attribute {0} missing on page and all ancestors")]
376    MissingRequired(&'static str),
377    /// `/Resources` was present but resolved to something that is **not a
378    /// dictionary** — a number, a name, an array, a string or a stream.
379    ///
380    /// Deliberately narrower than "the attribute is unusable": an absent
381    /// `/Resources`, and one whose reference dangles (§7.3.10 makes that
382    /// the null object; §7.3.9 makes null "equivalent to omitting the
383    /// entry"), are **not** this error. Those degrade to the empty
384    /// dictionary and are disclosed through [`Page::resources_defaulted`].
385    /// This variant is reserved for a value with no spec-sanctioned
386    /// reading, which is a real structural defect and must not be laundered
387    /// into a page that merely renders emptier — the same split
388    /// [`Self::BadContents`] makes, for the same reason.
389    #[error("page /Resources is not a dictionary")]
390    BadResources,
391    /// A rectangle entry wasn't an array of four numbers.
392    #[error("malformed rectangle in page attribute {0}")]
393    BadRectangle(&'static str),
394    /// `Rotate` was not an integer multiple of 90 (Table 30 "shall").
395    #[error("page /Rotate value {0} is not a multiple of 90")]
396    BadRotate(i64),
397    /// `Contents` held a value of the wrong **type** — something that is
398    /// neither a stream reference, an array of them, nor null.
399    ///
400    /// Deliberately narrower than it looks: an element that resolves to
401    /// **null** (a dangling reference to an object the file does not
402    /// contain) is NOT this error. §7.3.10 defines such a reference to be
403    /// the null object and Table 30 makes an absent `Contents` an empty
404    /// page, so that case degrades — the element contributes nothing and
405    /// the omission is counted in [`Page::contents_unresolved`]. This
406    /// variant is reserved for values with no spec-sanctioned reading (a
407    /// number, a name, a dictionary, a non-reference array element), which
408    /// are real structural defects and must not be laundered into a silent
409    /// blank page.
410    #[error("page /Contents is neither a stream nor an array of streams")]
411    BadContents,
412}
413
414/// Inheritable-attribute state carried down the walk (raw objects —
415/// resolution to `Rect`/`Dict` happens once, at the leaf, so an
416/// intermediate node's malformed value only errors if a page actually
417/// inherits it).
418#[derive(Clone, Default)]
419struct Inherited<'a> {
420    resources: Option<&'a Object>,
421    media_box: Option<&'a Object>,
422    crop_box: Option<&'a Object>,
423    rotate: Option<&'a Object>,
424}
425
426/// Walk the **loaded file's** page tree and return its pages in
427/// document order, attributes fully resolved.
428///
429/// A thin wrapper over [`pages_in`]. Kept as a named function because
430/// "the pages of this document" is what the renderer and every read-only
431/// consumer actually want, and spelling it `pages_in(doc)` at forty call
432/// sites would obscure that the interesting case is the *other* one.
433///
434/// ⚠️ **This is the base revision, not the edited state.** Anything that
435/// must see unsaved structural edits calls
436/// `EditSession::pages`, which walks
437/// the overlay through the same code.
438///
439/// # Errors
440///
441/// [`PageTreeError`] — structural damage, guard violations, or
442/// unresolvable required attributes. A well-formed empty tree
443/// (`/Count 0`, empty `Kids`) returns an empty vec, not an error.
444pub fn pages(doc: &Document) -> Result<Vec<Page>, PageTreeError> {
445    pages_in(doc)
446}
447
448/// Walk any [`ObjectGraph`]'s page tree and return its pages in document
449/// order, attributes fully resolved.
450///
451/// The generic form exists for exactly one reason, recorded in
452/// [`crate::graph`]'s module docs: from Pass 3.2 an edit can change the
453/// page tree's **shape**, so the walk must be able to run over the
454/// session overlay rather than over the base file. There is deliberately
455/// only one walk — a session-specialised copy is how a build eventually
456/// renders a page the operator deleted.
457///
458/// # Errors
459///
460/// [`PageTreeError`] — as [`pages`].
461pub fn pages_in<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<Page>, PageTreeError> {
462    let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
463    let root_obj = catalog
464        .get(b"Pages")
465        .map(|o| graph.resolve(o))
466        .ok_or(PageTreeError::NoPageTreeRoot)?;
467    let root = root_obj.as_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
468
469    // The root's id (for cycle tracking) if it was reached by
470    // reference — it always is in well-formed files (`/Pages` "shall
471    // be an indirect reference", Table 15/28).
472    let root_id = catalog.get(b"Pages").and_then(Object::as_reference);
473
474    let mut out = Vec::new();
475    let mut visited: HashSet<ObjId> = root_id.into_iter().collect();
476    walk(graph, root, Inherited::default(), 0, &mut visited, &mut out)?;
477    Ok(out)
478}
479
480/// One page's **structural** position in the tree: which node holds it,
481/// where in that node's `Kids`, and what its ancestors are.
482///
483/// [`Page`] answers *"what does this page look like?"*; this answers
484/// *"where does this page live?"*, which is the only question a
485/// structural operation asks. Splitting them keeps the renderer's type
486/// free of bookkeeping it has no use for, and keeps this type free of
487/// the expensive attribute resolution a delete does not need.
488///
489/// `inherited` carries the **raw, unresolved** values an ancestor
490/// supplies for the four inheritable attributes (§7.7.3.4), and it is
491/// the reason this type is worth building at all. When a page moves to a
492/// different parent — a reorder across nodes, an extract into a fresh
493/// document — the attributes it used to inherit may no longer reach it.
494/// Writing the *raw* value back onto the page (usually a single
495/// reference) preserves rendering exactly, whereas writing a *resolved*
496/// value would inline an entire resource dictionary and change bytes far
497/// beyond the edit.
498#[derive(Debug, Clone)]
499pub struct PageSlot {
500    /// The page object's identity.
501    pub id: ObjId,
502    /// The `Pages` node whose `Kids` array holds this page, if the walk
503    /// reached that node by reference (it always does in a well-formed
504    /// file — Table 29 requires `Kids` elements to be indirect).
505    pub parent: Option<ObjId>,
506    /// This page's index within `parent`'s `Kids` array.
507    pub index_in_parent: usize,
508    /// Every ancestor `Pages` node, **root first**, excluding the page
509    /// itself. A delete must decrement `/Count` on all of them.
510    pub ancestors: Vec<ObjId>,
511    /// What the ancestors supply for the four inheritable attributes,
512    /// unresolved. `None` for an attribute no ancestor sets.
513    pub inherited: InheritedRaw,
514}
515
516/// The raw inheritable-attribute values an ancestor chain supplies
517/// (§7.7.3.4 — exactly four attributes; see the module docs).
518///
519/// Deliberately **not** merged with the page's own entries: the whole
520/// point is to know what would be *lost* if the page left this chain.
521#[derive(Debug, Clone, Default, PartialEq)]
522pub struct InheritedRaw {
523    /// Nearest ancestor `/Resources`.
524    pub resources: Option<Object>,
525    /// Nearest ancestor `/MediaBox`.
526    pub media_box: Option<Object>,
527    /// Nearest ancestor `/CropBox`.
528    pub crop_box: Option<Object>,
529    /// Nearest ancestor `/Rotate`.
530    pub rotate: Option<Object>,
531}
532
533impl InheritedRaw {
534    /// The `(key, value)` pairs a page would need written onto it to
535    /// keep these attributes after leaving this ancestor chain.
536    ///
537    /// Only entries the page does not already carry itself are
538    /// returned, because a page's own entry always wins (§7.7.3.4) and
539    /// restating it would modify an object pdfcer was not asked to
540    /// modify (§5).
541    #[must_use]
542    pub fn materialize_for(&self, page: &Dict) -> Vec<(&'static [u8], Object)> {
543        let mut out = Vec::new();
544        for (key, value) in [
545            (&b"Resources"[..], &self.resources),
546            (&b"MediaBox"[..], &self.media_box),
547            (&b"CropBox"[..], &self.crop_box),
548            (&b"Rotate"[..], &self.rotate),
549        ] {
550            // `contains_key` collapses a null-valued entry to absent
551            // (§7.3.7), which is the right test: a page carrying
552            // `/Rotate null` inherits, exactly as one with no entry does.
553            if let Some(v) = value
554                && !page.contains_key(key)
555            {
556                out.push((key, v.clone()));
557            }
558        }
559        out
560    }
561}
562
563/// Walk the page tree recording each page's **structural position**
564/// rather than its resolved appearance.
565///
566/// Same traversal, same guards, same tolerance as [`pages_in`] — and
567/// deliberately a separate function rather than an extra field on
568/// [`Page`], because resolving `Resources`/`MediaBox` can *fail* for a
569/// damaged file (`MissingRequired`) and a structural operation should
570/// not be blocked by an attribute it never reads. A page with no
571/// `MediaBox` anywhere is still a page that can be deleted.
572///
573/// # Errors
574///
575/// [`PageTreeError`] — structural damage or a guard violation. Notably
576/// **not** [`PageTreeError::MissingRequired`], which this walk cannot
577/// produce.
578pub fn page_slots<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<PageSlot>, PageTreeError> {
579    let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
580    let root_id = catalog
581        .get(b"Pages")
582        .and_then(Object::as_reference)
583        .ok_or(PageTreeError::NoPageTreeRoot)?;
584    let root = graph
585        .resolved(root_id)
586        .as_dict()
587        .ok_or(PageTreeError::NoPageTreeRoot)?;
588
589    let mut out = Vec::new();
590    let mut visited: HashSet<ObjId> = [root_id].into_iter().collect();
591    walk_slots(
592        graph,
593        root_id,
594        root,
595        &InheritedRaw::default(),
596        &[],
597        0,
598        &mut visited,
599        &mut out,
600    )?;
601    Ok(out)
602}
603
604/// Recursive half of [`page_slots`].
605#[allow(clippy::too_many_arguments)] // every argument is walk state; a
606// struct here would only rename the same eight values.
607fn walk_slots<G: ObjectGraph + ?Sized>(
608    graph: &G,
609    node_id: ObjId,
610    node: &Dict,
611    inherited: &InheritedRaw,
612    ancestors: &[ObjId],
613    depth: usize,
614    visited: &mut HashSet<ObjId>,
615    out: &mut Vec<PageSlot>,
616) -> Result<(), PageTreeError> {
617    if depth > MAX_TREE_DEPTH {
618        return Err(PageTreeError::TooDeep);
619    }
620    let here = InheritedRaw {
621        resources: node
622            .get(b"Resources")
623            .cloned()
624            .or_else(|| inherited.resources.clone()),
625        media_box: node
626            .get(b"MediaBox")
627            .cloned()
628            .or_else(|| inherited.media_box.clone()),
629        crop_box: node
630            .get(b"CropBox")
631            .cloned()
632            .or_else(|| inherited.crop_box.clone()),
633        rotate: node
634            .get(b"Rotate")
635            .cloned()
636            .or_else(|| inherited.rotate.clone()),
637    };
638    let mut chain = ancestors.to_vec();
639    chain.push(node_id);
640
641    let Some(kids) = node
642        .get(b"Kids")
643        .map(|o| graph.resolve(o))
644        .and_then(Object::as_array)
645    else {
646        return Err(PageTreeError::NoPageTreeRoot);
647    };
648
649    for (index, kid) in kids.iter().enumerate() {
650        let Some(kid_id) = kid.as_reference() else {
651            return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
652        };
653        if !visited.insert(kid_id) {
654            return Err(PageTreeError::Cycle(kid_id));
655        }
656        let Some(kid_dict) = graph.resolved(kid_id).as_dict() else {
657            return Err(PageTreeError::BadKid(kid_id));
658        };
659        if is_pages_node(graph, kid_dict) {
660            walk_slots(
661                graph,
662                kid_id,
663                kid_dict,
664                &here,
665                &chain,
666                depth + 1,
667                visited,
668                out,
669            )?;
670        } else {
671            if out.len() >= MAX_PAGES {
672                return Err(PageTreeError::TooManyPages);
673            }
674            out.push(PageSlot {
675                id: kid_id,
676                parent: Some(node_id),
677                index_in_parent: index,
678                ancestors: chain.clone(),
679                inherited: here.clone(),
680            });
681        }
682    }
683    Ok(())
684}
685
686/// Node-kind dispatch: `/Type` where present, structural fallback
687/// (`Kids` present ⇒ intermediate node) where absent.
688///
689/// Shared by both walks so the two cannot disagree about what a node
690/// with no `/Type` is — a disagreement that would show up as a page
691/// count that changes depending on which walk asked.
692fn is_pages_node<G: ObjectGraph + ?Sized>(graph: &G, node: &Dict) -> bool {
693    match node
694        .get(b"Type")
695        .map(|o| graph.resolve(o))
696        .and_then(Object::as_name)
697        .map(crate::object::Name::as_bytes)
698    {
699        Some(b"Pages") => true,
700        Some(b"Page") => false,
701        _ => node.contains_key(b"Kids"),
702    }
703}
704
705/// Recursive top-down walk (see module docs for why top-down).
706fn walk<'a, G: ObjectGraph + ?Sized>(
707    doc: &'a G,
708    node: &'a Dict,
709    inherited: Inherited<'a>,
710    depth: usize,
711    visited: &mut HashSet<ObjId>,
712    out: &mut Vec<Page>,
713) -> Result<(), PageTreeError> {
714    if depth > MAX_TREE_DEPTH {
715        return Err(PageTreeError::TooDeep);
716    }
717
718    // Layer this node's own inheritable entries over what came down.
719    // Values stay raw here; leaves resolve them (module docs).
720    let inherited = Inherited {
721        resources: node.get(b"Resources").or(inherited.resources),
722        media_box: node.get(b"MediaBox").or(inherited.media_box),
723        crop_box: node.get(b"CropBox").or(inherited.crop_box),
724        rotate: node.get(b"Rotate").or(inherited.rotate),
725    };
726
727    // Node-kind dispatch: /Type where present, structural fallback
728    // (Kids ⇒ intermediate) where absent (module docs).
729    let type_name = node
730        .get(b"Type")
731        .map(|o| doc.resolve(o))
732        .and_then(Object::as_name)
733        .map(crate::object::Name::as_bytes);
734    let is_pages_node = match type_name {
735        Some(b"Pages") => true,
736        Some(b"Page") => false,
737        _ => node.contains_key(b"Kids"),
738    };
739
740    if !is_pages_node {
741        return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
742        // unreachable in practice: leaves are emitted by the caller
743        // below; kept as a defensive arm for a root that is itself a
744        // Page (malformed — a root must be a Pages node).
745    }
746
747    let kids = node
748        .get(b"Kids")
749        .map(|o| doc.resolve(o))
750        .and_then(Object::as_array)
751        .ok_or(PageTreeError::NoPageTreeRoot)?;
752
753    for kid in kids {
754        // Kids "shall only be page objects or other page tree nodes",
755        // referenced indirectly (Table 29).
756        let Some(kid_id) = kid.as_reference() else {
757            return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
758        };
759        if !visited.insert(kid_id) {
760            return Err(PageTreeError::Cycle(kid_id));
761        }
762        let Some(kid_dict) = doc.resolve(kid).as_dict() else {
763            return Err(PageTreeError::BadKid(kid_id));
764        };
765
766        let kid_type = kid_dict
767            .get(b"Type")
768            .map(|o| doc.resolve(o))
769            .and_then(Object::as_name)
770            .map(crate::object::Name::as_bytes);
771        let kid_is_pages = match kid_type {
772            Some(b"Pages") => true,
773            Some(b"Page") => false,
774            _ => kid_dict.contains_key(b"Kids"),
775        };
776
777        if kid_is_pages {
778            walk(doc, kid_dict, inherited.clone(), depth + 1, visited, out)?;
779        } else {
780            if out.len() >= MAX_PAGES {
781                return Err(PageTreeError::TooManyPages);
782            }
783            out.push(resolve_page(doc, kid_id, kid_dict, &inherited)?);
784        }
785    }
786    Ok(())
787}
788
789/// Resolve one leaf into a [`Page`], applying the §7.7.3.4 resolution
790/// order and defaults documented in the module docs.
791fn resolve_page<G: ObjectGraph + ?Sized>(
792    doc: &G,
793    id: ObjId,
794    page: &Dict,
795    inherited: &Inherited<'_>,
796) -> Result<Page, PageTreeError> {
797    // Resources: own → ancestor; §7.7.3.3 Table 30 calls it "required;
798    // inheritable". NOTE the empty-vs-absent distinction is preserved
799    // automatically here: a page with `/Resources << >>` has an OWN entry
800    // (empty dict), which wins over any ancestor value.
801    //
802    // ABSENT EVERYWHERE IS THE EMPTY RESOURCE DICTIONARY, NOT A REFUSAL.
803    //
804    // This used to be `.ok_or(MissingRequired("Resources"))?` — and the `?`
805    // is on a walk that returns `Result<Vec<Page>, _>` for the WHOLE
806    // document, so one page missing the attribute cost every other page in
807    // the file. Two facts settle which reading is right:
808    //
809    //   * **Acrobat writes such pages.** A user-authored stamp collection in
810    //     Acrobat's own preferences folder carries a blank spacer page with
811    //     no `/Contents` and no `/Resources`, alongside two complete pages;
812    //     pdfcer refused all three. The reference implementation opens it,
813    //     and it is the file an operator signs drawings with.
814    //   * **pdfcer's own `fixtures/synthetic/minimal.pdf` has no
815    //     `/Resources` either**, so this walk could not render the smallest
816    //     legal file the project ships. `plan_paste_at` had already grown a
817    //     hand-written bypass around this exact refusal for annotation-only
818    //     pastes — a guard a caller has to route around is the defect, not
819    //     the caller.
820    //
821    // THE FILE IS CERTAINLY NON-CONFORMING, AND THAT STRENGTHENS THE CASE
822    // RATHER THAN WEAKENING IT. ISO considered conditioning `/Resources` on
823    // `/Contents` and decided AGAINST it: `pdf-issues` #81 ("Are Page node
824    // Resources required even if Contents is not present?", ISO approved,
825    // Feb 2022 submission) resolved by appending a NOTE to ISO 32000-2's
826    // `/Contents` row — "If the Contents key is not present, a Resources
827    // dictionary must still be present, either directly or through
828    // inheritance, in the pages tree." So this is not a grey area pdfcer
829    // gets to read generously.
830    //
831    // It is a conformance judgement, not a behaviour: §2.1 binds the FILE,
832    // §2.3 the WRITER, and §2.2 scopes the reader's rendering duty to
833    // "conforming files" — while §1 Scope excludes "methods for validating
834    // the conformance of PDF files or readers" outright. Nothing in ISO
835    // 32000 says what a reader does with a file that violates a `shall`.
836    // Refusing is therefore a choice pdfcer made, never one it was owed, and
837    // the erratum's own motivation was "some issues with some PDF parsers
838    // not liking no Contents keys" — the reader is the known failure mode.
839    //
840    // Nothing is invented by defaulting, and the standard supplies the value:
841    // Table 30's own `/Resources` row says "If the page requires no
842    // resources, the value of this entry shall be an empty dictionary". A
843    // name looked up in the dictionary pdfcer supplies therefore fails
844    // exactly as it fails in an explicit `<< >>` a file could have written
845    // legally — the renderer and the extractor count those failures already.
846    // Refusing the document instead is the "fail-clean never meant refuse"
847    // mistake decision 145 corrected one attribute along, and it escalates a
848    // ONE-PAGE, ONE-ATTRIBUTE defect to the whole file, which §7.7.3.4 never
849    // asks for.
850    //
851    // ⚠ Do NOT rebuild this argument on "a page with no `/Contents` can
852    // never name a resource" — that reading is false and the spec librarian
853    // caught it here. §7.8.3's third bullet: files written to earlier PDF
854    // versions "may have omitted the Resources entry in all form XObjects
855    // and Type 3 fonts used on a page", and those resources "shall be
856    // inherited from the resource dictionary of the page on which they are
857    // used" — which ISO 32000-2's erratum extends explicitly to annotation
858    // appearance streams. A page whose only marks are annotation `/AP`
859    // forms is exactly the shape that motivated this Pass, so the
860    // contentless case is not self-evidently harmless; it is merely one
861    // more failed lookup, disclosed like the rest.
862    //
863    // The disclosure is [`Page::resources_defaulted`] — R20 /
864    // fuzzy-never-sneaky: the operator learns the page was incomplete, and
865    // does not lose the file to learn it.
866    //
867    // The absent/null vs wrong-type split is the same one `/Contents` makes
868    // below, for the same reason. A reference to an object the file does not
869    // contain IS the null object (§7.3.10), and a null value is "equivalent
870    // to omitting the entry" (§7.3.9), so both degrade. A number, a name, an
871    // array or a stream has no spec-sanctioned reading and still fails the
872    // page — laundering those into an empty dictionary would hide a real
873    // structural defect behind a page that merely renders emptier.
874    let (resources, resources_defaulted) = match page
875        .get(b"Resources")
876        .or(inherited.resources)
877        .map(|o| doc.resolve(o))
878    {
879        Some(Object::Dict(d)) => (d.clone(), false),
880        None | Some(Object::Null) => (Dict::new(), true),
881        Some(_) => return Err(PageTreeError::BadResources),
882    };
883
884    let media_box = page
885        .get(b"MediaBox")
886        .or(inherited.media_box)
887        .ok_or(PageTreeError::MissingRequired("MediaBox"))
888        .and_then(|o| parse_rect(doc, o, "MediaBox"))?;
889
890    // CropBox: own → ancestor → default = resolved MediaBox, then clipped to
891    // the media box (§14.11.2.1). A malformed CropBox still fails the page,
892    // as it always has; only the three production boxes below degrade.
893    let (crop_box, crop_box_resolution) = match page.get(b"CropBox").or(inherited.crop_box) {
894        Some(o) => clip_to_media(parse_rect(doc, o, "CropBox")?, media_box, media_box),
895        None => (media_box, BoxResolution::Defaulted),
896    };
897    // Bleed/Trim/Art: own only (not inheritable, Table 30) → default =
898    // effective CropBox.
899    let production_box = |key: &[u8]| match page.get(key) {
900        None => (crop_box, BoxResolution::Defaulted),
901        Some(o) => match parse_rect(doc, o, "BleedBox") {
902            Ok(r) => clip_to_media(r, media_box, crop_box),
903            Err(_) => (crop_box, BoxResolution::Unusable),
904        },
905    };
906    let (bleed_box, bleed_box_resolution) = production_box(b"BleedBox");
907    let (trim_box, trim_box_resolution) = production_box(b"TrimBox");
908    let (art_box, art_box_resolution) = production_box(b"ArtBox");
909
910    // Rotate: own → ancestor → 0; multiple of 90; positive modulo.
911    let rotate = match page
912        .get(b"Rotate")
913        .or(inherited.rotate)
914        .map(|o| doc.resolve(o))
915    {
916        None => 0,
917        Some(Object::Integer(v)) if v % 90 == 0 => u16::try_from(v.rem_euclid(360)).unwrap_or(0),
918        Some(Object::Integer(v)) => return Err(PageTreeError::BadRotate(*v)),
919        Some(_) => return Err(PageTreeError::BadRotate(i64::MIN)),
920    };
921
922    // Contents: absent = empty page; single stream ref; or array of
923    // stream refs (streams are always indirect, §7.3.8.1).
924    //
925    // The two failure modes are deliberately NOT treated alike:
926    //
927    //   * A reference that resolves to **null** — because the object is
928    //     absent from the file, or because the file explicitly wrote
929    //     `null` — is not an error at all. §7.3.10 makes a reference to an
930    //     undefined object *be* the null object, and §7.3.9 makes a null
931    //     value equivalent to omitting the entry; Table 30 then says an
932    //     absent `Contents` means an empty page. So it degrades: that
933    //     element contributes nothing, the rest of the page still loads,
934    //     and the omission is COUNTED into `contents_unresolved` for
935    //     disclosure.
936    //   * A value of the wrong **type** — a number, a name, a dictionary,
937    //     a direct non-reference array element — is a genuine structural
938    //     error with no spec-sanctioned reading, and still fails the page
939    //     with `BadContents`. Degrading these too would convert a real
940    //     defect into a silent blank page, which is precisely the outcome
941    //     "fuzzy, never sneaky" forbids.
942    let (contents, contents_unresolved, contents_flattened) = match page.get(b"Contents") {
943        None => (Vec::new(), 0, 0),
944        // A direct `null` value: §7.3.9 "equivalent to omitting the entry",
945        // so this is a well-formed empty page, not a degradation — nothing
946        // is missing, so nothing is counted.
947        Some(Object::Null) => (Vec::new(), 0, 0),
948        Some(entry @ Object::Reference(r)) => match doc.resolve(entry) {
949            Object::Stream(_) => (vec![*r], 0, 0),
950            // A reference to an ARRAY of streams is also legal
951            // (substitutability, §7.3.10) — recurse into the array.
952            Object::Array(items) => contents_from_array(doc, items, 0)?,
953            // §7.3.10 + Table 30: the whole `Contents` value is the null
954            // object, which reads as absent — an empty page, disclosed.
955            Object::Null => (Vec::new(), 1, 0),
956            _ => return Err(PageTreeError::BadContents),
957        },
958        Some(Object::Array(items)) => contents_from_array(doc, items, 0)?,
959        Some(_) => return Err(PageTreeError::BadContents),
960    };
961
962    Ok(Page {
963        id,
964        resources,
965        resources_defaulted,
966        media_box,
967        crop_box,
968        crop_box_resolution,
969        bleed_box,
970        bleed_box_resolution,
971        trim_box,
972        trim_box_resolution,
973        art_box,
974        art_box_resolution,
975        rotate,
976        contents,
977        contents_unresolved,
978        contents_flattened,
979    })
980}
981
982impl Page {
983    /// A page that states no production boxes, as [`pages`] resolves one:
984    /// `crop_box` is the effective box, bleed, trim and art equal it (Table
985    /// 30 defaults), every resolution is [`BoxResolution::Defaulted`], and
986    /// resources and contents are empty (`resources_defaulted` `false`).
987    ///
988    /// `crop_box` is taken as given, not intersected with `media_box`.
989    /// `rotate` is normalized as the page tree normalizes it: a multiple of
990    /// 90 reduced into {0, 90, 180, 270}, anything else 0.
991    ///
992    /// Set any other field afterwards, or with struct-update syntax: new
993    /// fields added to `Page` are then filled here and do not break callers.
994    ///
995    /// # Examples
996    ///
997    /// ```
998    /// use pdfcer_model::object::ObjId;
999    /// use pdfcer_model::page_tree::{BoxResolution, Page, Rect};
1000    ///
1001    /// let media = Rect::from_corners(0.0, 0.0, 612.0, 792.0);
1002    /// let page = Page {
1003    ///     contents: vec![ObjId::new(4, 0)],
1004    ///     ..Page::with_boxes(ObjId::new(3, 0), media, media, 450)
1005    /// };
1006    /// assert_eq!(page.rotate, 90);
1007    /// assert_eq!(page.trim_box, media);
1008    /// assert_eq!(page.art_box_resolution, BoxResolution::Defaulted);
1009    /// ```
1010    #[must_use]
1011    pub fn with_boxes(id: ObjId, media_box: Rect, crop_box: Rect, rotate: u16) -> Self {
1012        let rotate = if rotate.is_multiple_of(90) {
1013            rotate % 360
1014        } else {
1015            0
1016        };
1017        Self {
1018            id,
1019            resources: Dict::new(),
1020            resources_defaulted: false,
1021            media_box,
1022            crop_box,
1023            crop_box_resolution: BoxResolution::Defaulted,
1024            bleed_box: crop_box,
1025            bleed_box_resolution: BoxResolution::Defaulted,
1026            trim_box: crop_box,
1027            trim_box_resolution: BoxResolution::Defaulted,
1028            art_box: crop_box,
1029            art_box_resolution: BoxResolution::Defaulted,
1030            rotate,
1031            contents: Vec::new(),
1032            contents_unresolved: 0,
1033            contents_flattened: 0,
1034        }
1035    }
1036}
1037
1038/// Resolve a written page box against the media box (§14.11.2.1), falling
1039/// back to `default` when the intersection has no area (PB-A1).
1040fn clip_to_media(written: Rect, media_box: Rect, default: Rect) -> (Rect, BoxResolution) {
1041    match media_box.intersection(&written) {
1042        Some(r) if r == written => (r, BoxResolution::AsWritten),
1043        Some(r) => (r, BoxResolution::Clipped),
1044        None => (default, BoxResolution::Unusable),
1045    }
1046}
1047
1048/// The deepest nesting [`contents_from_array`] will flatten before refusing.
1049///
1050/// Realistically the damage is ONE level deep — a wrapped reference — and two
1051/// only if a damaged page was damaged again. The bound is generous rather than
1052/// tight because its job is to stop unbounded recursion on hostile input, not
1053/// to second-guess an unusual file (`ARCHITECTURE.md` §10).
1054const MAX_CONTENTS_NESTING: usize = 8;
1055
1056/// Collect the stream ids of a `Contents` array, degrading unresolvable
1057/// elements, FLATTENING nested arrays, and rejecting wrong-typed ones.
1058///
1059/// Returns the ids that resolved to real streams, in order, plus the count
1060/// of elements that resolved to null (§7.3.10) and so contribute nothing.
1061/// The surviving elements still concatenate in order — Table 30's "the
1062/// division between streams may occur only at the boundaries between
1063/// lexical tokens" means a dropped element leaves a *shorter* content
1064/// stream, never a syntactically broken one.
1065///
1066/// # Errors
1067///
1068/// [`PageTreeError::BadContents`] if an element is not an indirect
1069/// reference at all, or resolves to something other than a stream or null
1070/// — a type error, which stays an error (see the caller's commentary).
1071fn contents_from_array<G: ObjectGraph + ?Sized>(
1072    doc: &G,
1073    items: &[Object],
1074    depth: usize,
1075) -> Result<(Vec<ObjId>, usize, usize), PageTreeError> {
1076    if depth > MAX_CONTENTS_NESTING {
1077        return Err(PageTreeError::BadContents);
1078    }
1079    let mut ids = Vec::with_capacity(items.len());
1080    let mut unresolved = 0usize;
1081    let mut flattened = 0usize;
1082    for item in items {
1083        match (item.as_reference(), doc.resolve(item)) {
1084            (Some(id), Object::Stream(_)) => ids.push(id),
1085            // A reference whose target is missing from the file: §7.3.10
1086            // says this IS the null object, not an error. Count and skip.
1087            (Some(_), Object::Null) => unresolved += 1,
1088            // A DIRECT null element (`[ 4 0 R null 6 0 R ]`): §7.3.9 makes
1089            // it equivalent to an omitted value. Nothing is missing from
1090            // the file, so it is skipped WITHOUT counting — the count is
1091            // reserved for content that should have been there and wasn't.
1092            (None, Object::Null) => {}
1093            // A NESTED ARRAY. Not legal, and specifically the damage a
1094            // pdfcer build older than `Pass 111.0` wrote into any page whose
1095            // `/Contents` was an indirect reference to an array (see
1096            // `Page::contents_flattened`). Flattened rather than refused,
1097            // because the repair is EXACT — the nesting carries no
1098            // information and the streams inside it are already in the order
1099            // Table 30 concatenates them — and because refusing costs the
1100            // operator a document pdfcer itself damaged.
1101            //
1102            // Depth-guarded (`MAX_CONTENTS_NESTING`) rather than trusted:
1103            // this is a recursive walk over attacker-controllable structure,
1104            // which `ARCHITECTURE.md` §10 requires a bound on. A cycle
1105            // (`38 0 obj [ 38 0 R ] endobj`) terminates by depth, not by
1106            // luck.
1107            (_, Object::Array(inner)) => {
1108                let (mut nested, unres, flat) = contents_from_array(doc, inner, depth + 1)?;
1109                ids.append(&mut nested);
1110                unresolved += unres;
1111                flattened += flat + 1;
1112            }
1113            // Anything else — a number, a dict, a reference to a non-stream
1114            // — is a type error.
1115            _ => return Err(PageTreeError::BadContents),
1116        }
1117    }
1118    Ok((ids, unresolved, flattened))
1119}
1120
1121/// The first stream of pdfcer's overlay wrapper: a save (`q`) placed before a
1122/// page's original content. The comment ties the stream to pdfcer, so a
1123/// foreign stream that merely holds `q` is never taken for one.
1124#[doc(hidden)] // workspace-internal
1125pub const WRAP_SAVE: &[u8] = b"%pdfcer overlay wrap: save\nq\n";
1126
1127/// The restore (`Q`) that closes [`WRAP_SAVE`] after the original content.
1128#[doc(hidden)] // workspace-internal
1129pub const WRAP_RESTORE: &[u8] = b"%pdfcer overlay wrap: restore\nQ\n";
1130
1131/// Decoded content no larger than this is classified in full when a page is
1132/// not yet wrapped; a larger original is wrapped without being read.
1133const NEUTRAL_SCAN_LIMIT: usize = 64 * 1024;
1134
1135/// A raw stream longer than this cannot be a wrapper stream, so it is never
1136/// decoded to ask.
1137const WRAPPER_RAW_LIMIT: usize = 256;
1138
1139/// The object numbers of one [`WRAP_SAVE`] / [`WRAP_RESTORE`] stream pair. One
1140/// pair is shared by every page a single command wraps.
1141#[doc(hidden)] // workspace-internal
1142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1143pub struct WrapStreams {
1144    /// The [`WRAP_SAVE`] stream.
1145    pub save: ObjId,
1146    /// The [`WRAP_RESTORE`] stream.
1147    pub restore: ObjId,
1148}
1149
1150/// How appending a self-contained overlay stream to one page's `/Contents`
1151/// will go: made by [`plan_overlay_append`], completed by
1152/// [`OverlayAppend::finish`].
1153///
1154/// A `/Contents` array is one content stream (ISO 32000-2 §7.8.2) and §8.4.2
1155/// requires only that `q`/`Q` balance across it, so a page may leave a `cm`,
1156/// clip, `gs`, colour or text-state operator in effect at its end, and a
1157/// stream appended after it would inherit that state. The plan therefore puts
1158/// the page's content between a [`WRAP_SAVE`]/[`WRAP_RESTORE`] pair unless it
1159/// can show nothing leaks: the page is already wrapped by pdfcer and only
1160/// state-neutral streams follow the restore, or the whole content is small
1161/// and state-neutral. Original streams are never rewritten; only the element
1162/// list changes. An original with unbalanced `q`/`Q` (non-conforming) is not
1163/// repaired. Design: `docs/decisions/039-overlay-wrap.md`.
1164///
1165/// Every append route in `pdfcer-core` goes through this type; there is no
1166/// public way to append without it.
1167#[doc(hidden)] // workspace-internal
1168#[derive(Debug, Clone, PartialEq)]
1169pub struct OverlayAppend {
1170    items: Vec<Object>,
1171    wrap: bool,
1172}
1173
1174impl OverlayAppend {
1175    /// Whether [`Self::finish`] needs a [`WrapStreams`] pair.
1176    #[must_use]
1177    pub const fn needs_wrap(&self) -> bool {
1178        self.wrap
1179    }
1180
1181    /// The new `/Contents` value with `new_id` appended: `[S, …, R, new]` when
1182    /// wrapping, else `[…, new]`. `None` when a wrap is needed and `wrap` is
1183    /// `None`.
1184    #[must_use]
1185    pub fn finish(&self, new_id: ObjId, wrap: Option<WrapStreams>) -> Option<Object> {
1186        let mut out = Vec::with_capacity(self.items.len() + 3);
1187        if self.wrap {
1188            let pair = wrap?;
1189            out.push(Object::Reference(pair.save));
1190            out.extend(self.items.iter().cloned());
1191            out.push(Object::Reference(pair.restore));
1192        } else {
1193            out.extend(self.items.iter().cloned());
1194        }
1195        out.push(Object::Reference(new_id));
1196        Some(Object::Array(out))
1197    }
1198}
1199
1200/// Plan appending an overlay to a page whose `/Contents` is `before`.
1201///
1202/// `before` may be absent, a stream reference, an array, or a reference to an
1203/// array (resolved, depth-guarded per §7.3.10). The array's elements are
1204/// spliced into a new direct array, so a shared array object is never
1205/// extended onto another page. A value that is none of these is kept as the
1206/// first element rather than dropped.
1207#[doc(hidden)] // workspace-internal
1208#[must_use]
1209pub fn plan_overlay_append(view: &DocumentView<'_>, before: Option<&Object>) -> OverlayAppend {
1210    let items = contents_items(view, before);
1211    let wrap = !items.is_empty() && !leaves_no_state(view, &items);
1212    OverlayAppend { items, wrap }
1213}
1214
1215/// Remove every stream of `before` for which `drop` returns `true` (given its
1216/// decoded bytes), then peel pdfcer wrapper pairs left with nothing after
1217/// them. Returns the new `/Contents` value, `None` when nothing is left.
1218/// Unchanged content returns `before` as-is, so a shared array reference stays
1219/// a reference. Removed stream objects are orphaned, not deleted: they may be
1220/// shared with another page.
1221#[doc(hidden)] // workspace-internal
1222#[must_use]
1223pub fn remove_overlays(
1224    view: &DocumentView<'_>,
1225    before: Option<&Object>,
1226    drop: impl Fn(&Object, &[u8]) -> bool,
1227) -> Option<Object> {
1228    let before = before?;
1229    let items = contents_items(view, Some(before));
1230    let mut kept: Vec<Object> = items
1231        .iter()
1232        .filter(|item| !decoded_item(view, item).is_some_and(|b| drop(item, &b)))
1233        .cloned()
1234        .collect();
1235    if kept.len() == items.len() {
1236        return Some(before.clone());
1237    }
1238    while kept.len() >= 2
1239        && is_exactly(view, kept.first(), WRAP_SAVE)
1240        && is_exactly(view, kept.last(), WRAP_RESTORE)
1241    {
1242        kept.pop();
1243        kept.remove(0);
1244    }
1245    (!kept.is_empty()).then_some(Object::Array(kept))
1246}
1247
1248/// `true` when `content` leaves no graphics or text state behind: at `q`-depth
1249/// 0 it holds only `q`, marked-content operators, compatibility sections and
1250/// comments, its depth never goes negative and ends at 0, and it parses.
1251/// Conservative: anything uncertain is `false`, which costs a wrap, never a
1252/// leak.
1253#[doc(hidden)] // workspace-internal
1254#[must_use]
1255pub fn is_state_neutral(content: &[u8]) -> bool {
1256    let Ok(cs) = crate::content::ContentStream::parse(content.to_vec()) else {
1257        return false;
1258    };
1259    let buf = cs.buf.as_slice();
1260    let mut depth = 0_usize;
1261    for op in cs.operations() {
1262        match op.operator_name(buf) {
1263            Some(b"q") => depth += 1,
1264            Some(b"Q") => match depth.checked_sub(1) {
1265                Some(d) => depth = d,
1266                None => return false,
1267            },
1268            Some(b"BMC" | b"BDC" | b"EMC" | b"MP" | b"DP" | b"BX" | b"EX") => {}
1269            _ if depth > 0 => {}
1270            _ => return false,
1271        }
1272    }
1273    depth == 0
1274}
1275
1276/// The elements of a `/Contents` value, as the append splices them.
1277fn contents_items(view: &DocumentView<'_>, before: Option<&Object>) -> Vec<Object> {
1278    let Some(before) = before else {
1279        return Vec::new();
1280    };
1281    match view.resolve(before) {
1282        Object::Array(items) => items.clone(),
1283        // A stream shall be indirect (§7.3.8), so `before` is kept verbatim.
1284        _ => vec![before.clone()],
1285    }
1286}
1287
1288/// The decoded bytes of one `/Contents` element, or `None`.
1289fn decoded_item(view: &DocumentView<'_>, item: &Object) -> Option<Vec<u8>> {
1290    let Object::Stream(stream) = view.resolve(item) else {
1291        return None;
1292    };
1293    crate::filters::decode_stream(&stream.dict, view.slice(stream.data_span)?).ok()
1294}
1295
1296/// Whether `item` is a stream decoding to exactly `bytes`.
1297fn is_exactly(view: &DocumentView<'_>, item: Option<&Object>, bytes: &[u8]) -> bool {
1298    let Some(item) = item else {
1299        return false;
1300    };
1301    let Object::Stream(stream) = view.resolve(item) else {
1302        return false;
1303    };
1304    stream.data_span.len <= WRAPPER_RAW_LIMIT && decoded_item(view, item).as_deref() == Some(bytes)
1305}
1306
1307/// Whether appending after `items` needs no wrap (see [`OverlayAppend`]).
1308fn leaves_no_state(view: &DocumentView<'_>, items: &[Object]) -> bool {
1309    let neutral = |part: &[Object]| {
1310        let mut all = Vec::new();
1311        for item in part {
1312            let Some(bytes) = decoded_item(view, item) else {
1313                return false;
1314            };
1315            // Stream boundaries are token boundaries (§7.8.2).
1316            all.extend_from_slice(&bytes);
1317            all.push(b'\n');
1318        }
1319        is_state_neutral(&all)
1320    };
1321    if is_exactly(view, items.first(), WRAP_SAVE)
1322        && let Some(r) = items
1323            .iter()
1324            .rposition(|item| is_exactly(view, Some(item), WRAP_RESTORE))
1325        && r > 0
1326    {
1327        return neutral(items.get(r + 1..).unwrap_or_default());
1328    }
1329    let raw: usize = items
1330        .iter()
1331        .map(|item| match view.resolve(item) {
1332            Object::Stream(s) => s.data_span.len,
1333            _ => usize::MAX,
1334        })
1335        .fold(0, usize::saturating_add);
1336    raw <= NEUTRAL_SCAN_LIMIT && neutral(items)
1337}
1338
1339/// Parse (and resolve) a rectangle attribute: an array of four
1340/// numbers, each possibly an indirect reference (§7.3.10
1341/// substitutability), normalized per §7.9.5.
1342#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
1343pub fn parse_rect<G: ObjectGraph + ?Sized>(
1344    doc: &G,
1345    obj: &Object,
1346    attr: &'static str,
1347) -> Result<Rect, PageTreeError> {
1348    let arr = doc
1349        .resolve(obj)
1350        .as_array()
1351        .ok_or(PageTreeError::BadRectangle(attr))?;
1352    let nums: Vec<f64> = arr
1353        .iter()
1354        .filter_map(|o| doc.resolve(o).as_number())
1355        .collect();
1356    match nums.as_slice() {
1357        &[x1, y1, x2, y2] => Ok(Rect::from_corners(x1, y1, x2, y2)),
1358        _ => Err(PageTreeError::BadRectangle(attr)),
1359    }
1360}
1361
1362#[cfg(test)]
1363#[allow(
1364    clippy::unwrap_used,
1365    clippy::expect_used,
1366    clippy::panic,
1367    clippy::indexing_slicing
1368)]
1369mod tests {
1370    use super::*;
1371
1372    /// Same builder as document::tests — duplicated deliberately so
1373    /// each module's tests stay self-contained and readable.
1374    fn build_pdf(objects: &[(u32, &str)]) -> Document {
1375        let mut buf = b"%PDF-1.4\n".to_vec();
1376        let mut offsets: Vec<(u32, usize)> = Vec::new();
1377        for (num, body) in objects {
1378            offsets.push((*num, buf.len()));
1379            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
1380        }
1381        let xref_at = buf.len();
1382        let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
1383        buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
1384        buf.extend_from_slice(b"0000000000 65535 f\r\n");
1385        for num in 1..=max_num {
1386            match offsets.iter().find(|(n, _)| *n == num) {
1387                Some((_, off)) => {
1388                    buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
1389                }
1390                None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
1391            }
1392        }
1393        buf.extend_from_slice(
1394            format!(
1395                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n",
1396                max_num + 1
1397            )
1398            .as_bytes(),
1399        );
1400        Document::from_bytes(buf).unwrap()
1401    }
1402
1403    #[test]
1404    fn inheritance_spec_figure_6_style() {
1405        // Root sets MediaBox + Rotate 90; page 3 overrides Rotate to
1406        // 270; page 4 has its own MediaBox. Mirrors the §7.7.3.4
1407        // Figure 6 pattern.
1408        let doc = build_pdf(&[
1409            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1410            (
1411                2,
1412                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
1413                 /MediaBox [0 0 612 792] /Rotate 90 /Resources << >> >>",
1414            ),
1415            (3, "<< /Type /Page /Parent 2 0 R >>"),
1416            (4, "<< /Type /Page /Parent 2 0 R /Rotate 270 >>"),
1417            (5, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >>"),
1418        ]);
1419        let pages = pages(&doc).unwrap();
1420        assert_eq!(pages.len(), 3);
1421        // Page 1: everything inherited.
1422        assert_eq!(pages[0].media_box.width(), 612.0);
1423        assert_eq!(pages[0].rotate, 90);
1424        // CropBox defaulted to the resolved MediaBox.
1425        assert_eq!(pages[0].crop_box, pages[0].media_box);
1426        // Page 2: Rotate overridden.
1427        assert_eq!(pages[1].rotate, 270);
1428        // Page 3: MediaBox overridden, Rotate still inherited.
1429        assert_eq!(pages[2].media_box.width(), 200.0);
1430        assert_eq!(pages[2].rotate, 90);
1431    }
1432
1433    /// One page with MediaBox [0 0 100 100] and the given extra entries.
1434    fn one_page(extra: &str) -> Page {
1435        let page = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] {extra} >>");
1436        let doc = build_pdf(&[
1437            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1438            (
1439                2,
1440                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
1441            ),
1442            (3, &page),
1443        ]);
1444        pages(&doc).unwrap().remove(0)
1445    }
1446
1447    #[test]
1448    fn page_boxes_are_intersected_with_the_media_box() {
1449        let r = Rect::from_corners;
1450        // §14.11.2.1: a crop box overhanging the sheet frames the sheet.
1451        let p = one_page("/CropBox [-50 20 300 80]");
1452        assert_eq!(p.crop_box, r(0.0, 20.0, 100.0, 80.0));
1453        assert_eq!(p.crop_box_resolution, BoxResolution::Clipped);
1454        // A contained one is untouched, and says so.
1455        let p = one_page("/CropBox [10 10 90 90]");
1456        assert_eq!(p.crop_box, r(10.0, 10.0, 90.0, 90.0));
1457        assert_eq!(p.crop_box_resolution, BoxResolution::AsWritten);
1458        // PB-A1: no overlap falls back to the media box, disclosed.
1459        let p = one_page("/CropBox [200 200 300 300]");
1460        assert_eq!(p.crop_box, p.media_box);
1461        assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
1462        // Touching only along an edge has no area either.
1463        let p = one_page("/CropBox [100 0 200 100]");
1464        assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
1465        let p = one_page("");
1466        assert_eq!(p.crop_box_resolution, BoxResolution::Defaulted);
1467    }
1468
1469    #[test]
1470    fn production_boxes_clip_to_the_media_box_and_default_to_the_crop_box() {
1471        let r = Rect::from_corners;
1472        let p = one_page(
1473            "/CropBox [10 10 90 90] /TrimBox [-5 -5 50 50] \
1474             /BleedBox [500 500 600 600] /ArtBox [1 2 3]",
1475        );
1476        // Clipped to the MEDIA box, not the crop box: the crop box "has no
1477        // defined relationship with any of the other boundaries".
1478        assert_eq!(p.trim_box, r(0.0, 0.0, 50.0, 50.0));
1479        assert_eq!(p.trim_box_resolution, BoxResolution::Clipped);
1480        // No overlap, and malformed, both fall back to the effective crop box.
1481        assert_eq!(p.bleed_box, p.crop_box);
1482        assert_eq!(p.bleed_box_resolution, BoxResolution::Unusable);
1483        assert_eq!(p.art_box, p.crop_box);
1484        assert_eq!(p.art_box_resolution, BoxResolution::Unusable);
1485        // Absent defaults to the effective (clipped) crop box.
1486        let p = one_page("/CropBox [50 50 500 500]");
1487        assert_eq!(p.trim_box, r(50.0, 50.0, 100.0, 100.0));
1488        assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
1489    }
1490
1491    #[test]
1492    fn production_boxes_are_not_inherited() {
1493        let doc = build_pdf(&[
1494            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1495            (
1496                2,
1497                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> \
1498                 /MediaBox [0 0 100 100] /TrimBox [10 10 20 20] >>",
1499            ),
1500            (3, "<< /Type /Page /Parent 2 0 R >>"),
1501        ]);
1502        let p = pages(&doc).unwrap().remove(0);
1503        assert_eq!(p.trim_box, p.media_box);
1504        assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
1505    }
1506
1507    #[test]
1508    fn deep_tree_and_intermediate_inheritance() {
1509        let doc = build_pdf(&[
1510            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1511            (
1512                2,
1513                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1514                 /MediaBox [0 0 100 100] /Resources << >> >>",
1515            ),
1516            (
1517                3,
1518                "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R] /Count 1 /Rotate 180 >>",
1519            ),
1520            (4, "<< /Type /Page /Parent 3 0 R >>"),
1521        ]);
1522        let pages = pages(&doc).unwrap();
1523        assert_eq!(pages.len(), 1);
1524        assert_eq!(pages[0].rotate, 180);
1525        assert_eq!(pages[0].media_box.width(), 100.0);
1526    }
1527
1528    #[test]
1529    fn empty_own_resources_beats_inherited() {
1530        // §7.7.3.3: an explicit empty /Resources means "no resources"
1531        // — it must NOT fall through to the ancestor's non-empty one.
1532        let doc = build_pdf(&[
1533            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1534            (
1535                2,
1536                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1537                 /MediaBox [0 0 10 10] /Resources << /Font << >> >> >>",
1538            ),
1539            (3, "<< /Type /Page /Parent 2 0 R /Resources << >> >>"),
1540        ]);
1541        let pages = pages(&doc).unwrap();
1542        assert!(pages[0].resources.is_empty());
1543        // An explicit `<< >>` is the file's own statement, not pdfcer's.
1544        // The two must stay distinguishable or the disclosure would accuse
1545        // a well-formed file of being incomplete.
1546        assert!(!pages[0].resources_defaulted);
1547    }
1548
1549    /// The Acrobat shape, and the regression this Pass exists for: a
1550    /// three-page file whose FIRST page is a blank spacer with no
1551    /// `/Contents` and no `/Resources`, and whose other two are complete.
1552    ///
1553    /// Before `Pass 290.0` `pages()` returned `Err(MissingRequired)` for the
1554    /// whole document, so one degenerate page cost the operator two perfect
1555    /// ones — in a real file (`%APPDATA%\Adobe\Acrobat\DC\Stamps\…`, his
1556    /// signature stamps) that every other reader opens.
1557    ///
1558    /// The assertions are deliberately three: that the walk SUCCEEDS,
1559    /// that the two good pages keep the resources the file gave them, and
1560    /// that the flag is `true` on exactly the page that lacked the
1561    /// attribute. Testing only the first would pass on a build that
1562    /// defaulted every page's resources to empty.
1563    #[test]
1564    fn a_resourceless_page_does_not_cost_its_siblings() {
1565        let doc = build_pdf(&[
1566            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1567            (
1568                2,
1569                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
1570                 /MediaBox [0 0 612 792] >>",
1571            ),
1572            // The spacer: no /Contents, so no resource can ever be named.
1573            (3, "<< /Type /Page /Parent 2 0 R >>"),
1574            (
1575                4,
1576                "<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 9 0 R >> >> >>",
1577            ),
1578            (
1579                5,
1580                "<< /Type /Page /Parent 2 0 R /Resources << /XObject << /Im0 9 0 R >> >> >>",
1581            ),
1582        ]);
1583        let pages = pages(&doc).unwrap();
1584        assert_eq!(pages.len(), 3);
1585        assert!(pages[0].resources_defaulted);
1586        assert!(pages[0].resources.is_empty());
1587        assert!(!pages[1].resources_defaulted);
1588        assert!(pages[1].resources.contains_key(b"Font"));
1589        assert!(!pages[2].resources_defaulted);
1590        assert!(pages[2].resources.contains_key(b"XObject"));
1591    }
1592
1593    /// Defaulting must not shadow inheritance. A page with no `/Resources`
1594    /// of its own whose ANCESTOR has one still inherits it, and reports
1595    /// nothing — this is the ordinary well-formed shape, and a build that
1596    /// defaulted before consulting the ancestor would silently strip every
1597    /// font from every page of a file that inherits its resources (the
1598    /// §7.7.3.4 pattern, which is common).
1599    #[test]
1600    fn an_inherited_resource_dictionary_is_not_a_default() {
1601        let doc = build_pdf(&[
1602            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1603            (
1604                2,
1605                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] \
1606                 /Resources << /Font << /F1 9 0 R >> >> >>",
1607            ),
1608            (3, "<< /Type /Page /Parent 2 0 R >>"),
1609        ]);
1610        let pages = pages(&doc).unwrap();
1611        assert!(!pages[0].resources_defaulted);
1612        assert!(pages[0].resources.contains_key(b"Font"));
1613    }
1614
1615    /// A `/Resources` whose reference names an object the file does not
1616    /// contain degrades exactly like an absent one: §7.3.10 makes such a
1617    /// reference the null object and §7.3.9 makes a null value equivalent
1618    /// to omitting the entry, so there is no third reading to invent.
1619    #[test]
1620    fn a_dangling_resources_reference_degrades_like_an_absent_one() {
1621        let doc = build_pdf(&[
1622            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1623            (
1624                2,
1625                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
1626            ),
1627            (3, "<< /Type /Page /Parent 2 0 R /Resources 99 0 R >>"),
1628        ]);
1629        let pages = pages(&doc).unwrap();
1630        assert!(pages[0].resources_defaulted);
1631        assert!(pages[0].resources.is_empty());
1632    }
1633
1634    /// …but a `/Resources` that is present and is NOT a dictionary still
1635    /// fails the page. There is no spec-sanctioned reading of `/Resources 42`,
1636    /// and laundering it into an empty dictionary would hide a real
1637    /// structural defect behind a page that merely renders emptier — the
1638    /// same split `/Contents` makes between a dangling reference and a value
1639    /// of the wrong type.
1640    #[test]
1641    fn a_resources_entry_of_the_wrong_type_still_fails_the_page() {
1642        let doc = build_pdf(&[
1643            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1644            (
1645                2,
1646                "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
1647            ),
1648            (3, "<< /Type /Page /Parent 2 0 R /Resources 42 >>"),
1649        ]);
1650        assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadResources);
1651    }
1652
1653    /// `MediaBox` did NOT move with `Resources`, and the difference is the
1654    /// whole boundary decision 145 draws: an empty resource dictionary says
1655    /// what the file says, while any media box pdfcer picked would be a size
1656    /// nobody wrote. A future session tempted to "finish the job" by
1657    /// defaulting this one to Letter should read this test as the answer.
1658    #[test]
1659    fn a_missing_media_box_is_still_fatal_to_the_page() {
1660        let doc = build_pdf(&[
1661            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1662            (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
1663            (3, "<< /Type /Page /Parent 2 0 R >>"),
1664        ]);
1665        assert_eq!(
1666            pages(&doc).unwrap_err(),
1667            PageTreeError::MissingRequired("MediaBox")
1668        );
1669    }
1670
1671    #[test]
1672    fn rectangle_corners_normalize_in_any_order() {
1673        // §7.9.5: corners may come in either order.
1674        let doc = build_pdf(&[
1675            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1676            (
1677                2,
1678                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
1679            ),
1680            (3, "<< /Type /Page /Parent 2 0 R /MediaBox [612 792 0 0] >>"),
1681        ]);
1682        let pages = pages(&doc).unwrap();
1683        assert_eq!(pages[0].media_box.llx, 0.0);
1684        assert_eq!(pages[0].media_box.urx, 612.0);
1685        assert_eq!(pages[0].media_box.height(), 792.0);
1686    }
1687
1688    #[test]
1689    fn negative_rotate_normalizes_positive() {
1690        let doc = build_pdf(&[
1691            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1692            (
1693                2,
1694                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1695                 /MediaBox [0 0 10 10] /Resources << >> >>",
1696            ),
1697            (3, "<< /Type /Page /Parent 2 0 R /Rotate -90 >>"),
1698        ]);
1699        assert_eq!(pages(&doc).unwrap()[0].rotate, 270);
1700    }
1701
1702    #[test]
1703    fn non_multiple_of_90_rotate_is_error() {
1704        let doc = build_pdf(&[
1705            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1706            (
1707                2,
1708                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1709                 /MediaBox [0 0 10 10] /Resources << >> >>",
1710            ),
1711            (3, "<< /Type /Page /Parent 2 0 R /Rotate 45 >>"),
1712        ]);
1713        assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadRotate(45));
1714    }
1715
1716    #[test]
1717    fn missing_mediabox_everywhere_is_error() {
1718        let doc = build_pdf(&[
1719            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1720            (
1721                2,
1722                "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
1723            ),
1724            (3, "<< /Type /Page /Parent 2 0 R >>"),
1725        ]);
1726        assert_eq!(
1727            pages(&doc).unwrap_err(),
1728            PageTreeError::MissingRequired("MediaBox")
1729        );
1730    }
1731
1732    #[test]
1733    fn kids_cycle_is_detected() {
1734        // Node 2's Kids points back at node 2.
1735        let doc = build_pdf(&[
1736            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1737            (
1738                2,
1739                "<< /Type /Pages /Kids [2 0 R] /Count 1 \
1740                 /MediaBox [0 0 10 10] /Resources << >> >>",
1741            ),
1742        ]);
1743        assert_eq!(
1744            pages(&doc).unwrap_err(),
1745            PageTreeError::Cycle(ObjId::new(2, 0))
1746        );
1747    }
1748
1749    #[test]
1750    fn count_is_not_trusted() {
1751        // Declared /Count 99 with one real page: the walk wins.
1752        let doc = build_pdf(&[
1753            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1754            (
1755                2,
1756                "<< /Type /Pages /Kids [3 0 R] /Count 99 \
1757                 /MediaBox [0 0 10 10] /Resources << >> >>",
1758            ),
1759            (3, "<< /Type /Page /Parent 2 0 R >>"),
1760        ]);
1761        assert_eq!(pages(&doc).unwrap().len(), 1);
1762    }
1763
1764    #[test]
1765    fn contents_single_and_array_and_absent() {
1766        let doc = build_pdf(&[
1767            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1768            (
1769                2,
1770                "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
1771                 /MediaBox [0 0 10 10] /Resources << >> >>",
1772            ),
1773            (3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
1774            (4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R] >>"),
1775            (5, "<< /Type /Page /Parent 2 0 R >>"),
1776            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
1777            (7, "<< /Length 2 >>\nstream\nQ \nendstream"),
1778        ]);
1779        let pages = pages(&doc).unwrap();
1780        assert_eq!(pages[0].contents, vec![ObjId::new(6, 0)]);
1781        assert_eq!(pages[1].contents, vec![ObjId::new(6, 0), ObjId::new(7, 0)]);
1782        assert!(pages[2].contents.is_empty(), "absent Contents = empty page");
1783        // Nothing degraded here: every named stream was present.
1784        assert!(pages.iter().all(|p| p.contents_unresolved == 0));
1785    }
1786
1787    /// A **dangling element** in a `/Contents` array degrades: the element
1788    /// contributes nothing, the surviving streams still load in order, and
1789    /// the omission is disclosed via `contents_unresolved`.
1790    ///
1791    /// §7.3.10: "An indirect reference to an undefined object ... shall be
1792    /// treated as a reference to the null object." Object 7 is never
1793    /// defined, so `[6 0 R 7 0 R 8 0 R]` is `[stream, null, stream]` and
1794    /// the page's content is the concatenation of the two real streams.
1795    /// Before this fix the whole DOCUMENT was unopenable for this shape.
1796    #[test]
1797    fn contents_array_with_dangling_element_degrades_and_is_disclosed() {
1798        let doc = build_pdf(&[
1799            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1800            (
1801                2,
1802                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1803                 /MediaBox [0 0 10 10] /Resources << >> >>",
1804            ),
1805            // Object 7 is deliberately never defined.
1806            (
1807                3,
1808                "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R 8 0 R] >>",
1809            ),
1810            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
1811            (8, "<< /Length 2 >>\nstream\nQ \nendstream"),
1812        ]);
1813        let pages = pages(&doc).expect("a dangling element must not fail the document");
1814        assert_eq!(pages.len(), 1);
1815        assert_eq!(
1816            pages[0].contents,
1817            vec![ObjId::new(6, 0), ObjId::new(8, 0)],
1818            "the streams that DO exist still load, in order"
1819        );
1820        assert_eq!(
1821            pages[0].contents_unresolved, 1,
1822            "the omission is counted, not swallowed"
1823        );
1824    }
1825
1826    /// An **entirely unresolvable** `/Contents` (a single reference to an
1827    /// object the file does not contain) yields an empty page, disclosed —
1828    /// not a failed load.
1829    ///
1830    /// This is the dominant real-world shape: of 341 corpus files that
1831    /// failed with `BadContents`, ~300 were this single-reference form.
1832    /// §7.3.10 makes the value the null object; Table 30 then says
1833    /// "`Contents` ... if this entry is absent, the page shall be empty".
1834    #[test]
1835    fn contents_entirely_unresolvable_is_an_empty_page_disclosed() {
1836        let doc = build_pdf(&[
1837            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1838            (
1839                2,
1840                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1841                 /MediaBox [0 0 10 10] /Resources << >> >>",
1842            ),
1843            // Object 9 is never defined anywhere in the file.
1844            (3, "<< /Type /Page /Parent 2 0 R /Contents 9 0 R >>"),
1845        ]);
1846        let pages = pages(&doc).expect("an unresolvable /Contents must not fail the document");
1847        assert_eq!(pages.len(), 1);
1848        assert!(pages[0].contents.is_empty(), "empty page, per Table 30");
1849        assert_eq!(
1850            pages[0].contents_unresolved, 1,
1851            "an empty page from a MISSING stream is disclosed, unlike a genuinely blank one"
1852        );
1853    }
1854
1855    /// A **wrong-typed** `/Contents` is still a hard error. This is the
1856    /// blast-radius guard: degrading a dangling reference must not also
1857    /// launder a value that has no spec-sanctioned reading into a silent
1858    /// blank page.
1859    #[test]
1860    fn contents_of_the_wrong_type_is_still_an_error() {
1861        // A direct integer — no reading under any clause.
1862        let numeric = build_pdf(&[
1863            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1864            (
1865                2,
1866                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1867                 /MediaBox [0 0 10 10] /Resources << >> >>",
1868            ),
1869            (3, "<< /Type /Page /Parent 2 0 R /Contents 42 >>"),
1870        ]);
1871        assert_eq!(pages(&numeric).unwrap_err(), PageTreeError::BadContents);
1872
1873        // A reference to a plain DICTIONARY (an object that exists, but is
1874        // not a stream): present, wrong type — distinct from absent.
1875        let dict_target = build_pdf(&[
1876            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1877            (
1878                2,
1879                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1880                 /MediaBox [0 0 10 10] /Resources << >> >>",
1881            ),
1882            (3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
1883            (6, "<< /NotAStream true >>"),
1884        ]);
1885        assert_eq!(pages(&dict_target).unwrap_err(), PageTreeError::BadContents);
1886
1887        // A wrong-typed ELEMENT inside an otherwise fine array: one bad
1888        // element still condemns the page (it is not an omission).
1889        let bad_element = build_pdf(&[
1890            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1891            (
1892                2,
1893                "<< /Type /Pages /Kids [3 0 R] /Count 1 \
1894                 /MediaBox [0 0 10 10] /Resources << >> >>",
1895            ),
1896            (3, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 42] >>"),
1897            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
1898        ]);
1899        assert_eq!(pages(&bad_element).unwrap_err(), PageTreeError::BadContents);
1900    }
1901
1902    /// An EXPLICIT `null` is equivalent to omitting the entry (§7.3.9), so
1903    /// it is a well-formed empty page and is NOT counted as a degradation
1904    /// — nothing is missing from the file. Distinguishing this from a
1905    /// dangling reference is what keeps `contents_unresolved` meaningful.
1906    #[test]
1907    fn explicit_null_contents_is_absent_not_a_degradation() {
1908        let doc = build_pdf(&[
1909            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1910            (
1911                2,
1912                "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 \
1913                 /MediaBox [0 0 10 10] /Resources << >> >>",
1914            ),
1915            (3, "<< /Type /Page /Parent 2 0 R /Contents null >>"),
1916            (4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R null] >>"),
1917            (6, "<< /Length 2 >>\nstream\nq \nendstream"),
1918        ]);
1919        let pages = pages(&doc).unwrap();
1920        assert!(pages[0].contents.is_empty());
1921        assert_eq!(
1922            pages[0].contents_unresolved, 0,
1923            "an explicit null is an omitted entry, not missing content"
1924        );
1925        assert_eq!(pages[1].contents, vec![ObjId::new(6, 0)]);
1926        assert_eq!(pages[1].contents_unresolved, 0);
1927    }
1928
1929    #[test]
1930    fn missing_type_falls_back_to_structural_detection() {
1931        // Node 2 lacks /Type but has /Kids ⇒ treated as Pages node;
1932        // node 3 lacks /Type and has no /Kids ⇒ treated as Page.
1933        let doc = build_pdf(&[
1934            (1, "<< /Type /Catalog /Pages 2 0 R >>"),
1935            (
1936                2,
1937                "<< /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] /Resources << >> >>",
1938            ),
1939            (3, "<< /Parent 2 0 R >>"),
1940        ]);
1941        assert_eq!(pages(&doc).unwrap().len(), 1);
1942    }
1943}