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