Skip to main content

pdfboss_core/
document.rs

1//! The document model: loading, object resolution with caching, the
2//! lazily-flattened page tree with attribute inheritance, and document
3//! metadata.
4
5use crate::hash::{FastMap, FastSet};
6use std::cell::{OnceCell, RefCell};
7use std::path::Path;
8use std::rc::Rc;
9use std::sync::Arc;
10
11use crate::crypt::{direct_crypt_filters, Decryptor};
12use crate::date::Date;
13use crate::elements::Span;
14use crate::error::{Error, Result};
15use crate::filters;
16use crate::geom::Rect;
17use crate::object::{Dict, ObjRef, Object, Stream};
18use crate::objstm;
19use crate::parser::{Parser, Resolve};
20use crate::source::{block_on, AsyncObjectSource, Immediate};
21use crate::tree::Entries;
22use crate::xref::{load_xref, Xref, XrefEntry};
23
24/// Page-tree traversal depth cap.
25const MAX_TREE_DEPTH: usize = 256;
26
27/// A loaded PDF document.
28pub struct Document {
29    data: Arc<Vec<u8>>,
30    version: (u8, u8),
31    xref: Arc<Xref>,
32    /// Interior cache of fetched indirect objects.
33    cache: RefCell<FastMap<(u32, u16), Rc<Object>>>,
34    /// Object numbers currently being parsed, guarding re-entrant fetches
35    /// (e.g. a stream whose `/Length` refers back to the stream itself).
36    loading: RefCell<FastSet<u32>>,
37    /// Decoded object streams, keyed by their stream object number, so a
38    /// stream is decompressed and its header parsed at most once even when
39    /// many compressed objects are read from it.
40    objstms: RefCell<FastMap<u32, Rc<objstm::ObjStm>>>,
41    /// Present when the file uses the Standard security handler (RC4 or AES)
42    /// and opens under the empty user password; decrypts strings and stream
43    /// data as objects are loaded from the file.
44    decryptor: Option<Decryptor>,
45    /// The flattened page tree, built lazily on the first page access so that
46    /// merely opening a document (or reading its page count) never parses
47    /// every page dictionary. See [`Document::pages`]. Shared so a
48    /// [`Document::fork`] does not re-walk the tree.
49    pages: OnceCell<Arc<Vec<PageRec>>>,
50}
51
52/// A document's immutable core, detached from its single-threaded caches:
53/// the file bytes, the merged cross-reference table, the decryption key
54/// material, and the flattened page tree. `Send + Sync` (asserted in this
55/// module's tests), which the [`Document`] deliberately is not — this is
56/// the value that crosses a thread boundary, one fresh document
57/// materializing from it on each side. See [`Document::seed`],
58/// [`Document::from_seed`] and [`map_pages`].
59pub struct DocumentSeed {
60    data: Arc<Vec<u8>>,
61    version: (u8, u8),
62    xref: Arc<Xref>,
63    decryptor: Option<Decryptor>,
64    pages: Arc<Vec<PageRec>>,
65}
66
67impl Clone for DocumentSeed {
68    fn clone(&self) -> DocumentSeed {
69        DocumentSeed {
70            data: Arc::clone(&self.data),
71            version: self.version,
72            xref: Arc::clone(&self.xref),
73            decryptor: self.decryptor.clone(),
74            pages: Arc::clone(&self.pages),
75        }
76    }
77}
78
79impl DocumentSeed {
80    /// Number of pages in the flattened page tree the seed carries: what
81    /// every document built from it reports, without materializing one.
82    pub fn page_count(&self) -> usize {
83        self.pages.len()
84    }
85}
86
87/// The flattened, inheritance-applied record for one page.
88///
89/// Covers ISO 32000-1 §7.7.3.4.
90struct PageRec {
91    obj_ref: Option<ObjRef>,
92    media_box: Rect,
93    crop_box: Rect,
94    bleed_box: Rect,
95    trim_box: Rect,
96    art_box: Rect,
97    rotate: i32,
98    resources: Dict,
99    dict: Dict,
100}
101
102/// Attributes inherited down the page tree (ISO 32000 §7.7.3.4).
103#[derive(Clone, Default)]
104struct Inherited {
105    resources: Option<Dict>,
106    media_box: Option<Rect>,
107    crop_box: Option<Rect>,
108    rotate: Option<i32>,
109}
110
111/// Parses the `%PDF-x.y` header, scanning the first 1 KiB; absent or
112/// malformed headers default to version 1.4.
113///
114/// Covers ISO 32000-1 §7.5.2 and Annex I.
115fn parse_version(data: &[u8]) -> (u8, u8) {
116    try_parse_version(data).unwrap_or((1, 4))
117}
118
119/// Covers ISO 32000-1 §7.5.2.
120fn try_parse_version(data: &[u8]) -> Option<(u8, u8)> {
121    let window = &data[..data.len().min(1024)];
122    let pos = memchr::memmem::find(window, b"%PDF-")?;
123    let rest = &window[pos + 5..];
124    let (major, used) = read_version_component(rest)?;
125    if rest.get(used) != Some(&b'.') {
126        return None;
127    }
128    let (minor, _) = read_version_component(&rest[used + 1..])?;
129    Some((major, minor))
130}
131
132/// Reads a run of 1–3 ASCII digits as a `u8`, returning the value and the
133/// number of bytes consumed.
134fn read_version_component(bytes: &[u8]) -> Option<(u8, usize)> {
135    let end = bytes
136        .iter()
137        .position(|b| !b.is_ascii_digit())
138        .unwrap_or(bytes.len());
139    if end == 0 || end > 3 {
140        return None;
141    }
142    let value = std::str::from_utf8(&bytes[..end]).ok()?.parse().ok()?;
143    Some((value, end))
144}
145
146/// Normalizes a `/Rotate` value to one of {0, 90, 180, 270}; values that
147/// are not multiples of 90 fall back to 0 (lenient).
148fn normalize_rotation(deg: i32) -> i32 {
149    let r = deg.rem_euclid(360);
150    if r % 90 == 0 {
151        r
152    } else {
153        0
154    }
155}
156
157impl Document {
158    /// Loads a document from bytes: locates the `%PDF-x.y` header (scanning
159    /// the first 1 KiB, defaulting to 1.4), loads the xref, and sets up
160    /// decryption for files using the Standard security handler (RC4 or AES)
161    /// under the empty user password (password-protected files yield
162    /// [`Error::Encrypted`]).
163    ///
164    /// The page tree is **not** walked here: it is flattened lazily on the
165    /// first page access, so opening a document (or reading `page_count`) does
166    /// not parse every page dictionary.
167    pub fn load(data: Vec<u8>) -> Result<Document> {
168        Document::load_with_password(data, "")
169    }
170
171    /// [`Document::load`] with the password that opens the file, accepted as
172    /// either the user or the owner password. The empty string is the
173    /// transparent empty-user-password case [`Document::load`] always
174    /// handles; a password the file does not accept yields
175    /// [`Error::Encrypted`]. Non-ASCII passwords are tried UTF-8 encoded
176    /// and, for the legacy RC4/AES-128 revisions, Latin-1 encoded as well,
177    /// covering both encodings real files use.
178    pub fn load_with_password(data: Vec<u8>, password: &str) -> Result<Document> {
179        let version = parse_version(&data);
180        let xref = load_xref(&data)?;
181        let mut doc = Document {
182            data: Arc::new(data),
183            version,
184            xref: Arc::new(xref),
185            cache: RefCell::new(FastMap::default()),
186            loading: RefCell::new(FastSet::default()),
187            objstms: RefCell::new(FastMap::default()),
188            decryptor: None,
189            pages: OnceCell::new(),
190        };
191        if doc
192            .xref
193            .trailer
194            .get("Encrypt")
195            .is_some_and(|o| !o.is_null())
196        {
197            doc.setup_decryption(password)?;
198        }
199        Ok(doc)
200    }
201
202    /// Reads the file at `path` and loads it via
203    /// [`Document::load_with_password`].
204    pub fn open_with_password(path: impl AsRef<Path>, password: &str) -> Result<Document> {
205        Document::load_with_password(std::fs::read(path)?, password)
206    }
207
208    /// Configures decryption for an encrypted file. Supports the Standard
209    /// security handler with RC4 (`/V` 1–2), AESV2 (`/V` 4) and AESV3 (`/V` 5)
210    /// with `password` as the user or owner password (the empty string is
211    /// the transparent empty-user-password case); a password the file does
212    /// not accept is reported as [`Error::Encrypted`]. Must run before any
213    /// content object is fetched, and reads `/Encrypt` and `/ID` while
214    /// decryption is still off (those values are stored unencrypted).
215    fn setup_decryption(&mut self, password: &str) -> Result<()> {
216        let enc_obj = self
217            .xref
218            .trailer
219            .get("Encrypt")
220            .cloned()
221            .unwrap_or(Object::Null);
222        let enc = self.resolve(&enc_obj)?;
223        let enc_dict = enc.as_dict().ok_or(Error::Encrypted)?;
224        // Only the strings of an encryption dictionary must be direct, so
225        // the crypt filters may sit in objects of their own.
226        let enc_dict = direct_crypt_filters(enc_dict, |r| self.get(r).ok());
227        let id0: Vec<u8> = self
228            .xref
229            .trailer
230            .get("ID")
231            .and_then(Object::as_array)
232            .and_then(<[Object]>::first)
233            .and_then(Object::as_str_bytes)
234            .unwrap_or(&[])
235            .to_vec();
236        match Decryptor::from_standard_with_password_str(&enc_dict, &id0, password) {
237            Some(dec) => {
238                self.decryptor = Some(dec);
239                // Objects fetched while resolving /Encrypt were cached without
240                // decryption; drop them so they are re-read through the
241                // decrypting path if referenced again.
242                self.cache.borrow_mut().clear();
243                Ok(())
244            }
245            None => Err(Error::Encrypted),
246        }
247    }
248
249    /// Reads the file at `path` and loads it via [`Document::load`].
250    pub fn open(path: impl AsRef<Path>) -> Result<Document> {
251        Document::load(std::fs::read(path)?)
252    }
253
254    /// The PDF version from the header, e.g. `(1, 7)`.
255    pub fn version(&self) -> (u8, u8) {
256        self.version
257    }
258
259    /// Raw bytes of the loaded file.
260    pub fn bytes(&self) -> &[u8] {
261        &self.data
262    }
263
264    /// The merged cross-reference table and trailer.
265    pub fn xref(&self) -> &Xref {
266        &self.xref
267    }
268
269    /// True when the trailer carries a non-null `/Encrypt` entry: the file
270    /// declares encryption, whether or not this handle decrypted it.
271    pub fn is_encrypted(&self) -> bool {
272        self.xref()
273            .trailer
274            .get("Encrypt")
275            .is_some_and(|o| !o.is_null())
276    }
277
278    /// True when the file is encrypted and not opened with a working
279    /// password: [`Document::is_encrypted`] but no [`Decryptor`] was
280    /// configured, so object strings and stream data would decode as
281    /// ciphertext rather than the document's actual content.
282    pub fn is_locked(&self) -> bool {
283        self.is_encrypted() && self.decryptor.is_none()
284    }
285
286    /// Fetches an indirect object by reference (xref lookup, object-stream
287    /// indirection, cached). A generation mismatch between the request and
288    /// the file is tolerated (lenient).
289    pub fn get(&self, r: ObjRef) -> Result<Object> {
290        if let Some(cached) = self.cache.borrow().get(&(r.num, r.gen)) {
291            return Ok((**cached).clone());
292        }
293        if !self.loading.borrow_mut().insert(r.num) {
294            return Err(Error::CircularReference(r.num));
295        }
296        let result = self.load_object(r);
297        self.loading.borrow_mut().remove(&r.num);
298        let object = result?;
299        self.cache
300            .borrow_mut()
301            .insert((r.num, r.gen), Rc::new(object.clone()));
302        Ok(object)
303    }
304
305    /// Uncached fetch: parses the object at its file offset or extracts it
306    /// from its containing object stream.
307    ///
308    /// Covers ISO 32000-1 §7.5.3.
309    fn load_object(&self, r: ObjRef) -> Result<Object> {
310        match self.xref.get(r.num) {
311            None | Some(XrefEntry::Free) => Err(Error::ObjectNotFound(r.num, r.gen)),
312            Some(XrefEntry::InFile { offset, .. }) => {
313                let offset = usize::try_from(offset)
314                    .ok()
315                    .filter(|&o| o < self.data.len())
316                    .ok_or(Error::ObjectNotFound(r.num, r.gen))?;
317                self.object_at_spanned(offset).map(|parsed| parsed.1)
318            }
319            Some(XrefEntry::InStream { stream_num, index }) => {
320                self.load_from_object_stream(stream_num, index)
321            }
322        }
323    }
324
325    /// Parses the indirect object at `offset`, applying decryption, and
326    /// reports the byte range consumed (`N G obj … endobj`).
327    pub(crate) fn object_at_spanned(&self, offset: usize) -> Result<(ObjRef, Object, Span)> {
328        let mut parser = Parser::at(&self.data, offset);
329        let (r, mut object) = parser.parse_indirect(self)?;
330        // Objects stored directly in the file carry encrypted strings and
331        // stream data; decrypt with this object's key. (Objects living in
332        // object streams are decrypted with their container.)
333        if let Some(dec) = &self.decryptor {
334            dec.decrypt_object_with(&mut object, r.num, r.gen, &|target| self.get(target).ok());
335        }
336        Ok((r, object, Span::new(offset as u64, parser.pos() as u64)))
337    }
338
339    /// The decoded, header-parsed object stream `stream_num`, built at most
340    /// once and cached.
341    pub(crate) fn objstm_handle(&self, stream_num: u32) -> Result<Rc<objstm::ObjStm>> {
342        if let Some(stm) = self.objstms.borrow().get(&stream_num) {
343            return Ok(Rc::clone(stm));
344        }
345        let container = self.get(ObjRef {
346            num: stream_num,
347            gen: 0,
348        })?;
349        let stream = container.as_stream().ok_or_else(|| Error::TypeMismatch {
350            expected: "stream",
351            found: type_name(&container),
352        })?;
353        let n = self
354            .resolve(stream.dict.get("N").unwrap_or(&Object::Null))?
355            .as_int()
356            .and_then(|v| usize::try_from(v).ok())
357            .ok_or(Error::MissingKey("N"))?;
358        let first = self
359            .resolve(stream.dict.get("First").unwrap_or(&Object::Null))?
360            .as_int()
361            .and_then(|v| usize::try_from(v).ok())
362            .ok_or(Error::MissingKey("First"))?;
363        let decoded = self.stream_data(stream)?;
364        let stm = Rc::new(objstm::ObjStm::parse(decoded, n, first)?);
365        self.objstms
366            .borrow_mut()
367            .insert(stream_num, Rc::clone(&stm));
368        Ok(stm)
369    }
370
371    /// Extracts a compressed object from the object stream `stream_num`.
372    fn load_from_object_stream(&self, stream_num: u32, index: u32) -> Result<Object> {
373        self.objstm_handle(stream_num)?.object(index)
374    }
375
376    /// Chases reference chains with a depth guard of
377    /// [`MAX_RESOLVE_DEPTH`](crate::source::MAX_RESOLVE_DEPTH) (beyond that:
378    /// [`Error::CircularReference`], naming the last reference followed); a
379    /// reference to a missing or unreadable object resolves to `Null`
380    /// (lenient).
381    ///
382    /// The loop is [`crate::source::resolve_sync_with`], shared with the
383    /// provided [`crate::source::ObjectSource::resolve`], so the two cannot
384    /// drift apart. It reaches `Document::get` through this type's
385    /// `ObjectSource` implementation, which forwards to it unchanged.
386    pub fn resolve(&self, o: &Object) -> Result<Object> {
387        crate::source::resolve_sync_with(self, o)
388    }
389
390    /// Decodes a stream's data through its filter chain, resolving indirect
391    /// filter parameters against this document.
392    pub fn stream_data(&self, s: &Stream) -> Result<Vec<u8>> {
393        filters::decode_stream(s, self)
394    }
395
396    /// The flattened page tree, built once on first access.
397    fn pages(&self) -> &[PageRec] {
398        self.pages.get_or_init(|| Arc::new(self.flatten_pages()))
399    }
400
401    /// The document's shareable core: everything immutable, nothing cached.
402    /// Forces the page tree first, so no document built from the seed
403    /// re-walks it.
404    pub fn seed(&self) -> DocumentSeed {
405        DocumentSeed {
406            data: Arc::clone(&self.data),
407            version: self.version,
408            xref: Arc::clone(&self.xref),
409            decryptor: self.decryptor.clone(),
410            pages: Arc::clone(self.pages.get_or_init(|| Arc::new(self.flatten_pages()))),
411        }
412    }
413
414    /// A handle to the same document for another thread: share a
415    /// [`DocumentSeed`] across the thread boundary — the seed is `Send` and
416    /// `Sync`; the document, whose caches are single-threaded by design, is
417    /// neither — and materialize one of these per thread.
418    ///
419    /// The immutable core is shared — the file bytes, the merged
420    /// cross-reference table, the decryption key material, and the flattened
421    /// page tree — while the interior caches start fresh, private to this
422    /// document. That is the whole design: per-page work is independent and
423    /// lock-free precisely because nothing mutable is shared, so N documents
424    /// on N threads contend on nothing.
425    ///
426    /// [`map_pages`] is the ready-made consumer.
427    pub fn from_seed(seed: DocumentSeed) -> Document {
428        Document {
429            data: seed.data,
430            version: seed.version,
431            xref: seed.xref,
432            cache: RefCell::new(FastMap::default()),
433            loading: RefCell::new(FastSet::default()),
434            objstms: RefCell::new(FastMap::default()),
435            decryptor: seed.decryptor,
436            pages: OnceCell::from(seed.pages),
437        }
438    }
439
440    /// [`Document::seed`] and [`Document::from_seed`] in one step, for a
441    /// fork used on the calling thread.
442    pub fn fork(&self) -> Document {
443        Document::from_seed(self.seed())
444    }
445
446    /// Number of pages: the length of the walked page tree, the same count
447    /// [`Document::page`] indexes into. The tree is flattened on first use.
448    /// The declared `/Count` is not consulted, since producers write it
449    /// wrong in both directions.
450    ///
451    /// Covers ISO 32000-1 §7.7.3 and §7.7.3.2.
452    pub fn page_count(&self) -> usize {
453        self.pages().len()
454    }
455
456    /// The page at 0-based `index`.
457    pub fn page(&self, index: usize) -> Result<Page> {
458        let pages = self.pages();
459        let rec = pages
460            .get(index)
461            .ok_or(Error::PageNotFound(index, pages.len()))?;
462        Ok(Page {
463            index,
464            media_box: rec.media_box,
465            crop_box: rec.crop_box,
466            bleed_box: rec.bleed_box,
467            trim_box: rec.trim_box,
468            art_box: rec.art_box,
469            rotate: rec.rotate,
470            resources: rec.resources.clone(),
471            dict: rec.dict.clone(),
472            obj_ref: rec.obj_ref,
473        })
474    }
475
476    /// Document metadata from the trailer `/Info` dictionary (lenient:
477    /// absent or malformed entries are simply `None`).
478    ///
479    /// Covers ISO 32000-1 §14.3.3, §7.9.4 and §8.11.4.3.
480    pub fn metadata(&self) -> Metadata {
481        let meta = Metadata::default();
482        let Some(info) = self.xref.trailer.get("Info") else {
483            return meta;
484        };
485        let Ok(info) = self.resolve(info) else {
486            return meta;
487        };
488        let Some(dict) = info.as_dict() else {
489            return meta;
490        };
491        block_on(metadata_with(&Immediate(self), dict))
492    }
493
494    /// The document's optional-content visibility as a viewer shows it on
495    /// screen: the default configuration (ISO 32000-1 §8.11.4.3) with the
496    /// View usage application (§8.11.4.4) applied, or `None` when the
497    /// catalog declares no `/OCProperties` — no optional content, everything
498    /// visible. Computed per call from a handful of object reads.
499    ///
500    /// Covers ISO 32000-1 §8.11.4.2.
501    pub fn oc_state(&self) -> Option<crate::oc::OcState> {
502        block_on(crate::oc::OcState::load_with(
503            &Immediate(self),
504            &self.xref.trailer,
505        ))
506    }
507
508    /// The document's optional-content visibility under one usage
509    /// application event (ISO 32000-1 §8.11.4.4), or under the default
510    /// configuration alone for `None`; `None` in the result when the catalog
511    /// declares no `/OCProperties`. See [`crate::OcState::load_for_with`].
512    ///
513    /// Covers ISO 32000-1 §8.11.4.5.
514    pub fn oc_state_for(&self, event: Option<crate::oc::OcEvent>) -> Option<crate::oc::OcState> {
515        block_on(crate::oc::OcState::load_for_with(
516            &Immediate(self),
517            &self.xref.trailer,
518            event,
519        ))
520    }
521
522    /// The document's optional content groups (ISO 32000-1 §8.11.2.1) in
523    /// `/OCGs` order, each with its state under `event`; empty without
524    /// `/OCProperties`.
525    ///
526    /// Covers ISO 32000-1 §8.11.4.2.
527    pub fn optional_content_groups(
528        &self,
529        event: Option<crate::oc::OcEvent>,
530    ) -> Vec<crate::oc::OcGroup> {
531        block_on(crate::oc::optional_content_groups_with(
532            &Immediate(self),
533            &self.xref.trailer,
534            event,
535        ))
536    }
537
538    /// The document's structure tree (ISO 32000-1 §14.7), or `None` when the
539    /// catalog names no `/StructTreeRoot`. Loaded per call: the root, its
540    /// role and class maps and every entry of its parent tree, so a caller
541    /// walking the pages loads it once and forks it per worker (its
542    /// `Clone`, see [`map_pages_forking`]); the tree ranks a page's marked
543    /// content on request and keeps what each walk read for the next.
544    pub fn structure_tree(&self) -> Option<crate::structure::StructureTree> {
545        block_on(crate::structure::StructureTree::load_with(
546            &Immediate(self),
547            &self.xref.trailer,
548        ))
549    }
550
551    /// A page's content items in structure-tree order (ISO 32000-1
552    /// §14.7.4): the marked-content sequences of its content stream and
553    /// the annotations the tree holds through object references, ranked
554    /// together, so each annotation sits where §14.8.2.3.2 puts it in the
555    /// page's content order. Empty for a page the tree does not reach, or
556    /// a document without a tree.
557    pub fn content_items(&self, page: &Page) -> Vec<crate::structure::PlacedItem> {
558        let Some(tree) = self.structure_tree() else {
559            return Vec::new();
560        };
561        block_on(tree.content_items_with(&Immediate(self), page))
562    }
563
564    /// The object that `key` names in the catalog's `tree` (ISO 32000-1
565    /// §7.7.4), resolved: a destination for `NameTree::Dests`, a file
566    /// specification for `NameTree::EmbeddedFiles`. `None` when the
567    /// document has no such tree or the tree has no such name.
568    pub fn named(&self, tree: crate::names::NameTree, key: &[u8]) -> Option<Object> {
569        block_on(crate::names::named_with(
570            &Immediate(self),
571            &self.xref.trailer,
572            tree,
573            key,
574        ))
575    }
576
577    /// Every name in the catalog's `tree` with the object it names,
578    /// unresolved, in tree order; empty when the document has no such tree.
579    pub fn names(&self, tree: crate::names::NameTree) -> Vec<(Vec<u8>, Object)> {
580        block_on(crate::names::names_with(
581            &Immediate(self),
582            &self.xref.trailer,
583            tree,
584        ))
585    }
586
587    /// The destination `name` designates (ISO 32000-1 §12.3.2.3), from the
588    /// `/Names` `/Dests` tree or the catalog's `/Dests` dictionary.
589    pub fn named_destination(&self, name: &[u8]) -> Option<crate::destination::Destination> {
590        block_on(crate::destination::named_destination_with(
591            &Immediate(self),
592            &self.xref.trailer,
593            name,
594        ))
595    }
596
597    /// Every named destination of the document, sorted by name.
598    pub fn named_destinations(&self) -> Vec<(Vec<u8>, crate::destination::Destination)> {
599        block_on(crate::destination::named_destinations_with(
600            &Immediate(self),
601            &self.xref.trailer,
602        ))
603    }
604
605    /// The destination a `/Dest` or `/D` value denotes: an explicit array,
606    /// a name or string looked up among the named destinations, or a
607    /// dictionary whose `/D` holds one of those (ISO 32000-1 §12.3.2).
608    pub fn destination(&self, value: &Object) -> Option<crate::destination::Destination> {
609        block_on(crate::destination::destination_value_with(
610            &Immediate(self),
611            &self.xref.trailer,
612            value,
613        ))
614    }
615
616    /// The document outline (ISO 32000-1 §12.3.3): the top-level items with
617    /// their descendants, in display order; empty when there is none.
618    pub fn outline(&self) -> Vec<crate::outline::OutlineItem> {
619        block_on(crate::outline::outline_with(
620            &Immediate(self),
621            &self.xref.trailer,
622        ))
623    }
624
625    /// The document's page labelling ranges (ISO 32000-1 §12.4.2), sorted
626    /// by first page; `None` when the catalog has no `/PageLabels`.
627    pub fn page_labels(&self) -> Option<Vec<crate::page_label::PageLabel>> {
628        block_on(crate::page_label::page_labels_with(
629            &Immediate(self),
630            &self.xref.trailer,
631        ))
632    }
633
634    /// The language the catalog declares for the document's text
635    /// (`/Lang`, ISO 32000-1 §14.9.2), or `None` when it declares none.
636    pub fn language(&self) -> Option<String> {
637        block_on(crate::language::language_with(
638            &Immediate(self),
639            &self.xref.trailer,
640        ))
641    }
642
643    /// The document's language as a parsed identifier (ISO 32000-1
644    /// §14.9.2.2), `None` when the catalog declares none or the tag is not
645    /// well formed.
646    pub fn language_tag(&self) -> Option<crate::language::LanguageTag> {
647        crate::language::LanguageTag::parse(&self.language()?)
648    }
649
650    /// The developer extensions the catalog declares (ISO 32000-1 §7.12),
651    /// sorted by prefix; empty when the catalog declares none.
652    pub fn extensions(&self) -> Vec<crate::extension::DeveloperExtension> {
653        block_on(crate::extension::extensions_with(
654            &Immediate(self),
655            &self.xref.trailer,
656        ))
657    }
658
659    /// The catalog's viewer preferences (ISO 32000-1 §12.2), `None` when
660    /// the catalog declares none.
661    pub fn viewer_preferences(&self) -> Option<crate::viewer_preferences::ViewerPreferences> {
662        block_on(crate::viewer_preferences::viewer_preferences_with(
663            &Immediate(self),
664            &self.xref.trailer,
665        ))
666    }
667
668    /// The linearization parameter dictionary (ISO 32000-1 Annex F.3) as
669    /// written, `None` when the file's first object is not one. It may be
670    /// stale after an appended update; [`Document::is_linearized`] tells.
671    pub fn linearization(&self) -> Option<crate::linearization::Linearization> {
672        crate::linearization::linearization_dictionary(&self.data)
673    }
674
675    /// Whether the file is linearized and its parameter dictionary still
676    /// applies, which Table F.1 ties to `/L` naming the file's actual
677    /// length.
678    ///
679    /// Covers ISO 32000-1 Annex F.3.
680    pub fn is_linearized(&self) -> bool {
681        self.linearization()
682            .is_some_and(|record| record.is_current(self.data.len() as u64))
683    }
684
685    /// The catalog's output intents (ISO 32000-1 §14.11.5) in array order,
686    /// empty without `/OutputIntents`.
687    pub fn output_intents(&self) -> Vec<crate::output_intent::OutputIntent> {
688        block_on(crate::output_intent::output_intents_with(
689            &Immediate(self),
690            &self.xref.trailer,
691        ))
692    }
693
694    /// The catalog's page-piece dictionary (ISO 32000-1 §14.5): one record
695    /// per product, empty without `/PieceInfo`.
696    pub fn piece_info(&self) -> Vec<crate::piece_info::PagePiece> {
697        block_on(crate::piece_info::document_piece_info_with(
698            &Immediate(self),
699            &self.xref.trailer,
700        ))
701    }
702
703    /// A page's page-piece dictionary (ISO 32000-1 §14.5): one record per
704    /// product, empty without `/PieceInfo` on the page.
705    pub fn page_piece_info(&self, page: &Page) -> Vec<crate::piece_info::PagePiece> {
706        block_on(crate::piece_info::piece_info_with(
707            &Immediate(self),
708            page.dict(),
709        ))
710    }
711
712    /// A page's thumbnail image (ISO 32000-1 §12.3.4), `None` when the
713    /// page has no `/Thumb` stream.
714    pub fn thumbnail(&self, page: &Page) -> Option<crate::thumbnail::Thumbnail> {
715        block_on(crate::thumbnail::thumbnail_with(&Immediate(self), page))
716    }
717
718    /// The catalog's article threads (ISO 32000-1 §12.4.3) in array order,
719    /// empty without `/Threads`.
720    pub fn articles(&self) -> Vec<crate::article::ArticleThread> {
721        block_on(crate::article::articles_with(
722            &Immediate(self),
723            &self.xref.trailer,
724        ))
725    }
726
727    /// The beads on a page in drawing order (ISO 32000-1 §12.4.3), empty
728    /// without `/B`.
729    pub fn page_beads(&self, page: &Page) -> Vec<ObjRef> {
730        block_on(crate::article::page_beads_with(&Immediate(self), page))
731    }
732
733    /// A page's presentation entries (ISO 32000-1 §12.4.4), `None` when
734    /// the page has neither `/Dur` nor a `/Trans` dictionary.
735    pub fn presentation(&self, page: &Page) -> Option<crate::presentation::Presentation> {
736        block_on(crate::presentation::presentation_with(
737            &Immediate(self),
738            page,
739        ))
740    }
741
742    /// The viewports of a page's `/VP` array (ISO 32000-1 §12.9), empty
743    /// without one.
744    pub fn viewports(&self, page: &Page) -> Vec<crate::measure::Viewport> {
745        block_on(crate::measure::viewports_with(&Immediate(self), page))
746    }
747
748    /// A page's separation dictionary (ISO 32000-1 §14.11.4), `None` when
749    /// the page has no `/SeparationInfo` naming a colorant.
750    pub fn separation_info(&self, page: &Page) -> Option<crate::separation_info::SeparationInfo> {
751        block_on(crate::separation_info::separation_info_with(
752            &Immediate(self),
753            page,
754        ))
755    }
756
757    /// The annotations of a page's `/Annots` array (ISO 32000-1 §12.5.2),
758    /// in order, with their actions read as data.
759    pub fn annotations(&self, page: &Page) -> Vec<crate::annotation::Annotation> {
760        block_on(crate::annotation::annotations_with(
761            &Immediate(self),
762            &self.xref.trailer,
763            page,
764        ))
765    }
766
767    /// The actions a page's `/AA` dictionary fires when it opens and closes
768    /// (ISO 32000-1 §12.6.3), empty without one.
769    pub fn page_additional_actions(&self, page: &Page) -> Vec<crate::annotation::TriggeredAction> {
770        block_on(crate::annotation::page_additional_actions_with(
771            &Immediate(self),
772            &self.xref.trailer,
773            page,
774        ))
775    }
776
777    /// The actions the catalog's `/AA` dictionary fires around closing,
778    /// saving and printing (ISO 32000-1 §12.6.3), empty without one.
779    pub fn additional_actions(&self) -> Vec<crate::annotation::TriggeredAction> {
780        block_on(crate::annotation::document_additional_actions_with(
781            &Immediate(self),
782            &self.xref.trailer,
783        ))
784    }
785
786    /// The action an `/A` or `/AA` value holds, with its `/Next` chain
787    /// (ISO 32000-1 §12.6.2); `None` when the value is no action
788    /// dictionary.
789    pub fn action(&self, value: &Object) -> Option<crate::annotation::Action> {
790        block_on(crate::annotation::action_with(
791            &Immediate(self),
792            &self.xref.trailer,
793            value,
794        ))
795    }
796
797    /// The permission handlers of the catalog's `/Perms` dictionary (ISO
798    /// 32000-1 §12.8.4), `None` without one.
799    pub fn permission_handlers(&self) -> Option<crate::permission::PermissionHandlers> {
800        block_on(crate::permission::permission_handlers_with(
801            &Immediate(self),
802            &self.xref.trailer,
803        ))
804    }
805
806    /// The requirements the catalog's `/Requirements` array lists (ISO
807    /// 32000-1 §12.10.1), empty without one.
808    pub fn requirements(&self) -> Vec<crate::requirement::Requirement> {
809        block_on(crate::requirement::requirements_with(
810            &Immediate(self),
811            &self.xref.trailer,
812        ))
813    }
814
815    /// The catalog's legal attestation dictionary (ISO 32000-1 §12.8.5),
816    /// `None` without one.
817    pub fn legal_attestation(&self) -> Option<crate::legal::LegalAttestation> {
818        block_on(crate::legal::legal_attestation_with(
819            &Immediate(self),
820            &self.xref.trailer,
821        ))
822    }
823
824    /// The document's interactive form dictionary (ISO 32000-1 §12.7.2),
825    /// `None` when the catalog has no `/AcroForm`.
826    pub fn interactive_form(&self) -> Option<crate::form::InteractiveForm> {
827        block_on(crate::form::interactive_form_with(
828            &Immediate(self),
829            &self.xref.trailer,
830        ))
831    }
832
833    /// Every field of the document's interactive form (ISO 32000-1
834    /// §12.7.3), depth first from the root fields; empty without a form.
835    pub fn form_fields(&self) -> Vec<crate::form::FormField> {
836        block_on(crate::form::form_fields_with(
837            &Immediate(self),
838            &self.xref.trailer,
839        ))
840    }
841
842    /// The label the page at `index` shows, or `None` when the document
843    /// has no page labels or no such page.
844    pub fn page_label(&self, index: usize) -> Option<String> {
845        if index >= self.page_count() {
846            return None;
847        }
848        let ranges = self.page_labels()?;
849        Some(crate::page_label::page_label(&ranges, index))
850    }
851
852    /// The document-level embedded files (ISO 32000-1 §7.11.4): every entry
853    /// of the catalog's `/EmbeddedFiles` name tree, in tree order.
854    pub fn embedded_files(&self) -> Vec<crate::embedded_file::EmbeddedFile> {
855        block_on(crate::embedded_file::embedded_files_with(
856            &Immediate(self),
857            &self.xref.trailer,
858        ))
859    }
860
861    /// The decoded bytes of one embedded file.
862    ///
863    /// # Errors
864    ///
865    /// `MissingKey("EF")` when the file specification embeds no stream,
866    /// and the stream's own decoding errors.
867    pub fn embedded_file_data(&self, file: &crate::embedded_file::EmbeddedFile) -> Result<Vec<u8>> {
868        block_on(crate::embedded_file::embedded_file_data_with(
869            &Immediate(self),
870            file,
871        ))
872    }
873
874    /// The decoded bytes of the stream a file specification embeds, such
875    /// as a file attachment annotation's (ISO 32000-1 §7.11.4).
876    ///
877    /// # Errors
878    ///
879    /// `MissingKey("EF")` when the specification embeds no stream, and the
880    /// stream's own decoding errors.
881    pub fn file_spec_data(&self, spec: &crate::embedded_file::FileSpec) -> Result<Vec<u8>> {
882        block_on(crate::embedded_file::file_spec_data_with(
883            &Immediate(self),
884            spec,
885        ))
886    }
887
888    /// Flattens the page tree by iterative depth-first traversal of `/Kids`
889    /// with a visited-reference cycle guard and a depth cap, applying
890    /// attribute inheritance. Any structural problem simply truncates or
891    /// skips (lenient) — this never fails.
892    ///
893    /// Covers ISO 32000-1 §14.11.2, §7.7.2, §7.7.3, §7.7.3.2, §7.7.3.3, §7.7.3.4 and §8.3.2.2.
894    fn flatten_pages(&self) -> Vec<PageRec> {
895        let mut pages = Vec::new();
896        let Some(root) = self.xref.trailer.get("Root") else {
897            return pages;
898        };
899        let Ok(catalog) = self.resolve(root) else {
900            return pages;
901        };
902        let Some(tree_root) = catalog.as_dict().and_then(|d| d.get("Pages")) else {
903            return pages;
904        };
905        let mut visited: FastSet<ObjRef> = FastSet::default();
906        let mut stack: Vec<(Object, Inherited, usize)> =
907            vec![(tree_root.clone(), Inherited::default(), 0)];
908        while let Some((node, mut inherited, depth)) = stack.pop() {
909            if depth > MAX_TREE_DEPTH {
910                continue;
911            }
912            let node_ref = if let Object::Ref(r) = node {
913                Some(r)
914            } else {
915                None
916            };
917            if let Some(r) = node_ref {
918                if !visited.insert(r) {
919                    continue; // cycle: this node was already traversed
920                }
921            }
922            let Ok(resolved) = self.resolve(&node) else {
923                continue;
924            };
925            let Some(dict) = resolved.as_dict() else {
926                continue;
927            };
928            if let Some(res) = self.dict_value(dict, "Resources") {
929                inherited.resources = Some(res);
930            }
931            if let Some(mb) = self.rect_value(dict, "MediaBox") {
932                inherited.media_box = Some(mb);
933            }
934            if let Some(cb) = self.rect_value(dict, "CropBox") {
935                inherited.crop_box = Some(cb);
936            }
937            if let Some(rot) = self.int_value(dict, "Rotate") {
938                inherited.rotate = Some(rot);
939            }
940            let is_page = dict.get_name("Type").is_some_and(|n| n.0 == "Page");
941            let kids = if is_page {
942                None
943            } else {
944                self.array_value(dict, "Kids")
945            };
946            match kids {
947                Some(kids) => {
948                    // Reverse push so pop order matches document order.
949                    for kid in kids.iter().rev() {
950                        stack.push((kid.clone(), inherited.clone(), depth + 1));
951                    }
952                }
953                None => {
954                    // BleedBox, TrimBox and ArtBox are not inheritable
955                    // (ISO 32000 §7.7.3.3, Table 30): read them from the
956                    // leaf dictionary only.
957                    let bleed = self.rect_value(dict, "BleedBox");
958                    let trim = self.rect_value(dict, "TrimBox");
959                    let art = self.rect_value(dict, "ArtBox");
960                    pages.push(make_page_rec(
961                        node_ref,
962                        dict.clone(),
963                        &inherited,
964                        bleed,
965                        trim,
966                        art,
967                    ));
968                }
969            }
970        }
971        pages
972    }
973
974    /// Resolves `dict[key]` to a dictionary, if present and well-formed.
975    fn dict_value(&self, dict: &Dict, key: &str) -> Option<Dict> {
976        self.resolve(dict.get(key)?).ok()?.as_dict().cloned()
977    }
978
979    /// Resolves `dict[key]` to an array, if present and well-formed.
980    fn array_value(&self, dict: &Dict, key: &str) -> Option<Vec<Object>> {
981        match self.resolve(dict.get(key)?).ok()? {
982            Object::Array(items) => Some(items),
983            _ => None,
984        }
985    }
986
987    /// Resolves `dict[key]` to an integer (reals truncate, lenient).
988    fn int_value(&self, dict: &Dict, key: &str) -> Option<i32> {
989        let v = self.resolve(dict.get(key)?).ok()?.as_f64()?;
990        if v.is_finite() {
991            Some(v as i32)
992        } else {
993            None
994        }
995    }
996
997    /// Resolves `dict[key]` to a normalized rectangle: a four-number array
998    /// whose elements may themselves be references.
999    ///
1000    /// Covers ISO 32000-1 §7.9.5.
1001    fn rect_value(&self, dict: &Dict, key: &str) -> Option<Rect> {
1002        let items = self.array_value(dict, key)?;
1003        if items.len() != 4 {
1004            return None;
1005        }
1006        let mut coords = [0.0f32; 4];
1007        for (slot, item) in coords.iter_mut().zip(&items) {
1008            let n = self.resolve(item).ok()?.as_f64()?;
1009            if !n.is_finite() {
1010                return None;
1011            }
1012            *slot = n as f32;
1013        }
1014        Some(Rect::new(coords[0], coords[1], coords[2], coords[3]).normalize())
1015    }
1016}
1017
1018/// Applies `work` to every page of `doc` in parallel and returns the
1019/// results in page order.
1020///
1021/// Per-page work over a `Document` — text extraction, rasterization — is
1022/// independent and CPU-bound, so this fans it out over
1023/// `std::thread::available_parallelism()` threads, each holding its own
1024/// [`Document::fork`]: the immutable core is shared, the caches are private,
1025/// and the workers contend on nothing.
1026///
1027/// Workers pull page indexes from a shared counter rather than a static
1028/// stride. This is not a style choice: pages vary wildly in cost, and on a
1029/// machine with heterogeneous cores a static partition ends with the fast
1030/// cores idle while a slow one finishes its stripe — measured as the
1031/// difference between 3.9x and 5.9x on twelve cores. A counter keeps every
1032/// worker busy until the pages run out.
1033///
1034/// A single-page document, or a single-core machine, runs inline on the
1035/// calling thread with no fork and no thread.
1036pub fn map_pages<T, F>(doc: &Document, work: F) -> Vec<Result<T>>
1037where
1038    T: Send + Sync,
1039    F: Fn(&Document, &Page) -> Result<T> + Send + Sync,
1040{
1041    map_pages_forking(doc, || (), |(), doc, page| work(doc, page))
1042}
1043
1044/// [`map_pages`] with state forked once per worker: `fork` runs on each
1045/// worker before its first page (on the calling thread when the work runs
1046/// inline) and `work` gets that worker's copy with every page it handles.
1047/// For state a page walk fills as it goes, such as a
1048/// [`crate::StructureTree`], whose fork is the same tree over an empty
1049/// cache, this keeps what one page read for the pages the same worker
1050/// takes next, without the workers sharing a lock.
1051pub fn map_pages_forking<W, T, K, F>(doc: &Document, fork: K, work: F) -> Vec<Result<T>>
1052where
1053    T: Send + Sync,
1054    K: Fn() -> W + Sync,
1055    F: Fn(&W, &Document, &Page) -> Result<T> + Send + Sync,
1056{
1057    let count = doc.pages().len();
1058    let workers = std::thread::available_parallelism()
1059        .map(std::num::NonZeroUsize::get)
1060        .unwrap_or(1)
1061        .min(count);
1062    if workers <= 1 {
1063        let state = fork();
1064        return (0..count)
1065            .map(|i| doc.page(i).and_then(|page| work(&state, doc, &page)))
1066            .collect();
1067    }
1068
1069    let seed = doc.seed();
1070    let next = std::sync::atomic::AtomicUsize::new(0);
1071    let slots: Vec<std::sync::OnceLock<Result<T>>> =
1072        (0..count).map(|_| std::sync::OnceLock::new()).collect();
1073    std::thread::scope(|scope| {
1074        for _ in 0..workers {
1075            // The seed crosses the thread boundary; the document — whose
1076            // caches are single-threaded by design — materializes inside,
1077            // and so does the worker's fork of the state.
1078            let seed = seed.clone();
1079            let next = &next;
1080            let slots = &slots;
1081            let fork = &fork;
1082            let work = &work;
1083            scope.spawn(move || {
1084                let worker = Document::from_seed(seed);
1085                let state = fork();
1086                loop {
1087                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1088                    if i >= count {
1089                        break;
1090                    }
1091                    let outcome = worker.page(i).and_then(|page| work(&state, &worker, &page));
1092                    let _ = slots[i].set(outcome);
1093                }
1094            });
1095        }
1096    });
1097    slots
1098        .into_iter()
1099        .map(|slot| {
1100            slot.into_inner()
1101                .unwrap_or_else(|| Err(Error::Other("page index was never dispatched".to_owned())))
1102        })
1103        .collect()
1104}
1105
1106/// Builds the final page record from a leaf dictionary and its inherited
1107/// attributes. The defaults live in [`Page::from_tree_attrs`] — the one
1108/// implementation of page defaulting, shared with the asynchronous API —
1109/// and this only reshapes its output into the index-less cache record.
1110///
1111/// Covers ISO 32000-1 §7.7.3.3.
1112fn make_page_rec(
1113    obj_ref: Option<ObjRef>,
1114    dict: Dict,
1115    inherited: &Inherited,
1116    bleed_box: Option<Rect>,
1117    trim_box: Option<Rect>,
1118    art_box: Option<Rect>,
1119) -> PageRec {
1120    let page = Page::from_tree_attrs(
1121        0,
1122        inherited.resources.clone(),
1123        inherited.media_box,
1124        inherited.crop_box,
1125        bleed_box,
1126        trim_box,
1127        art_box,
1128        inherited.rotate,
1129        dict,
1130        obj_ref,
1131    );
1132    PageRec {
1133        obj_ref: page.obj_ref,
1134        media_box: page.media_box,
1135        crop_box: page.crop_box,
1136        bleed_box: page.bleed_box,
1137        trim_box: page.trim_box,
1138        art_box: page.art_box,
1139        rotate: page.rotate,
1140        resources: page.resources,
1141        dict: page.dict,
1142    }
1143}
1144
1145/// Human-readable object type name for error messages.
1146pub(crate) fn type_name(o: &Object) -> &'static str {
1147    match o {
1148        Object::Null => "null",
1149        Object::Bool(_) => "boolean",
1150        Object::Int(_) => "integer",
1151        Object::Real(_) => "real",
1152        Object::String(_) => "string",
1153        Object::Name(_) => "name",
1154        Object::Array(_) => "array",
1155        Object::Dict(_) => "dictionary",
1156        Object::Stream(_) => "stream",
1157        Object::Ref(_) => "reference",
1158    }
1159}
1160
1161impl Resolve for Document {
1162    fn resolve_ref(&self, r: ObjRef) -> Option<Object> {
1163        self.get(r).ok()
1164    }
1165}
1166
1167/// Forwards to the inherent methods, so reading a document through the trait
1168/// is bit-identical to reading it directly. `resolve` is forwarded too, even
1169/// though the provided implementation is now the same shared chase
1170/// ([`crate::source::resolve_sync_with`]) that the inherent method delegates
1171/// to: routing it through the inherent method keeps the two entry points a
1172/// single call, so they cannot drift should `Document::resolve` ever grow
1173/// document-specific behaviour.
1174impl crate::source::ObjectSource for Document {
1175    fn get(&self, r: ObjRef) -> Result<Object> {
1176        Document::get(self, r)
1177    }
1178
1179    fn stream_data(&self, s: &Stream) -> Result<Vec<u8>> {
1180        Document::stream_data(self, s)
1181    }
1182
1183    fn resolve(&self, o: &Object) -> Result<Object> {
1184        Document::resolve(self, o)
1185    }
1186}
1187
1188/// Document information from the trailer `/Info` dictionary. Only present,
1189/// well-formed entries are populated. The two dates hold the text as
1190/// written; [`Metadata::creation_date_parsed`] and
1191/// [`Metadata::mod_date_parsed`] read them as [`Date`]s.
1192#[derive(Debug, Clone, Default, PartialEq, Eq)]
1193pub struct Metadata {
1194    pub title: Option<String>,
1195    pub author: Option<String>,
1196    pub subject: Option<String>,
1197    pub keywords: Option<String>,
1198    pub creator: Option<String>,
1199    pub producer: Option<String>,
1200    pub creation_date: Option<String>,
1201    pub mod_date: Option<String>,
1202}
1203
1204/// The document information entries `dict` holds (ISO 32000-1 §14.3.3,
1205/// Table 317), each decoded as a text string. The same reader serves the
1206/// trailer's `/Info` dictionary and an article thread's `/I` (§12.4.3).
1207///
1208/// Covers ISO 32000-1 §7.9.2.2 and §14.3.3.
1209pub async fn metadata_with<S: AsyncObjectSource>(src: &S, dict: &Dict) -> Metadata {
1210    let entries = Entries { src, dict };
1211    Metadata {
1212        title: entries.text("Title").await,
1213        author: entries.text("Author").await,
1214        subject: entries.text("Subject").await,
1215        keywords: entries.text("Keywords").await,
1216        creator: entries.text("Creator").await,
1217        producer: entries.text("Producer").await,
1218        creation_date: entries.text("CreationDate").await,
1219        mod_date: entries.text("ModDate").await,
1220    }
1221}
1222
1223impl Metadata {
1224    /// `/CreationDate` as a date (ISO 32000-1 §7.9.4), `None` when absent
1225    /// or not a date string; the text as written stays in `creation_date`.
1226    ///
1227    /// Covers ISO 32000-1 §7.9.4.
1228    pub fn creation_date_parsed(&self) -> Option<Date> {
1229        Date::parse_pdf(self.creation_date.as_deref()?)
1230    }
1231
1232    /// `/ModDate` as a date, like [`Metadata::creation_date_parsed`].
1233    ///
1234    /// Covers ISO 32000-1 §7.9.4.
1235    pub fn mod_date_parsed(&self) -> Option<Date> {
1236        Date::parse_pdf(self.mod_date.as_deref()?)
1237    }
1238}
1239
1240/// A single page with inherited attributes already applied.
1241///
1242/// Defaults: `media_box` falls back to US Letter (612x792) when absent or
1243/// invalid, `crop_box` falls back to (and is intersected with) `media_box`,
1244/// `bleed_box`, `trim_box` and `art_box` fall back to `crop_box` (and are
1245/// clipped to `media_box`) per ISO 32000 §14.11.2, and `rotate` is
1246/// normalized to one of {0, 90, 180, 270}. Every construction path
1247/// normalizes `rotate` — [`Document::page`] and [`Page::from_parts`] alike —
1248/// so the invariant holds however a `Page` was built. `rotate` is a public
1249/// field, so a caller may still overwrite it afterwards; [`Page::size`]
1250/// reads it modulo a full turn and so stays correct if they do.
1251///
1252/// All five boxes are in unrotated PDF user space: [`Page::size`] swaps
1253/// width and height under a quarter-turn `/Rotate`, the boxes never do.
1254#[derive(Clone)]
1255pub struct Page {
1256    /// 0-based page index.
1257    pub index: usize,
1258    pub media_box: Rect,
1259    pub crop_box: Rect,
1260    pub bleed_box: Rect,
1261    pub trim_box: Rect,
1262    pub art_box: Rect,
1263    pub rotate: i32,
1264    /// The page's (inherited) `/Resources` dictionary.
1265    pub resources: Dict,
1266    dict: Dict,
1267    obj_ref: Option<ObjRef>,
1268}
1269
1270impl Page {
1271    /// Builds a page from already-resolved attributes.
1272    ///
1273    /// [`Document::page`] resolves page-tree inheritance itself; this is for
1274    /// a caller that has done that resolution some other way — notably the
1275    /// asynchronous API, which flattens the page tree while reading it — and
1276    /// needs the same [`Page`] type back.
1277    ///
1278    /// `rotate` is normalized here to one of `{0, 90, 180, 270}` exactly as
1279    /// [`Document::page`] normalizes it, so a caller may pass a raw `/Rotate`
1280    /// straight through: a negative or over-a-full-turn multiple of 90 is
1281    /// reduced, and a value that is not a multiple of 90 falls back to 0
1282    /// (lenient). The caller does not have to pre-normalize, and the [`Page`]
1283    /// invariant holds whichever constructor built it.
1284    ///
1285    /// `bleed_box`, `trim_box` and `art_box` are set to `crop_box` — their
1286    /// ISO 32000 §14.11.2 default. A caller that resolved real values
1287    /// overwrites the public fields afterwards.
1288    ///
1289    /// Covers ISO 32000-1 §14.11.2.
1290    pub fn from_parts(
1291        index: usize,
1292        media_box: Rect,
1293        crop_box: Rect,
1294        rotate: i32,
1295        resources: Dict,
1296        dict: Dict,
1297        obj_ref: Option<ObjRef>,
1298    ) -> Page {
1299        Page {
1300            index,
1301            media_box,
1302            crop_box,
1303            bleed_box: crop_box,
1304            trim_box: crop_box,
1305            art_box: crop_box,
1306            rotate: normalize_rotation(rotate),
1307            resources,
1308            dict,
1309            obj_ref,
1310        }
1311    }
1312
1313    /// The default media box for a page that declares none: US Letter
1314    /// (612 by 792 points). Public because the default is part of the
1315    /// observable contract — a caller comparing two APIs' pages needs to
1316    /// know which rectangle "the file said nothing" maps to.
1317    pub const US_LETTER: Rect = Rect::new(0.0, 0.0, 612.0, 792.0);
1318
1319    /// Builds a page from raw, possibly missing page-tree attributes,
1320    /// applying the same defaults [`Document::page`] applies (ISO 32000
1321    /// §7.7.3.3, §14.11.2): a missing or degenerate `/MediaBox` reads as
1322    /// [`Page::US_LETTER`], `/CropBox` clips to the media box and falls back
1323    /// to it, `/BleedBox`, `/TrimBox` and `/ArtBox` clip to the media box
1324    /// and fall back to the crop box, a missing `/Rotate` reads as 0 and is
1325    /// normalized, and missing `/Resources` read as empty.
1326    ///
1327    /// This is the one implementation of page defaulting. The synchronous
1328    /// tree walk routes through it, and a caller that resolved inheritance
1329    /// some other way — notably the asynchronous API, which flattens the
1330    /// page tree while reading it — gets the identical `Page` back, so the
1331    /// two APIs cannot disagree about what an attribute-less page looks
1332    /// like.
1333    #[allow(clippy::too_many_arguments)]
1334    pub fn from_tree_attrs(
1335        index: usize,
1336        resources: Option<Dict>,
1337        media_box: Option<Rect>,
1338        crop_box: Option<Rect>,
1339        bleed_box: Option<Rect>,
1340        trim_box: Option<Rect>,
1341        art_box: Option<Rect>,
1342        rotate: Option<i32>,
1343        dict: Dict,
1344        obj_ref: Option<ObjRef>,
1345    ) -> Page {
1346        let media_box = media_box
1347            .filter(|r| r.width() > 0.0 && r.height() > 0.0)
1348            .unwrap_or(Page::US_LETTER);
1349        let crop_box = crop_box
1350            .and_then(|c| c.intersect(media_box))
1351            .filter(|r| r.width() > 0.0 && r.height() > 0.0)
1352            .unwrap_or(media_box);
1353        let clip = |declared: Option<Rect>| {
1354            declared
1355                .and_then(|b| b.intersect(media_box))
1356                .filter(|r| r.width() > 0.0 && r.height() > 0.0)
1357                .unwrap_or(crop_box)
1358        };
1359        Page {
1360            index,
1361            media_box,
1362            crop_box,
1363            bleed_box: clip(bleed_box),
1364            trim_box: clip(trim_box),
1365            art_box: clip(art_box),
1366            rotate: normalize_rotation(rotate.unwrap_or(0)),
1367            resources: resources.unwrap_or_default(),
1368            dict,
1369            obj_ref,
1370        }
1371    }
1372
1373    /// The page's indirect object reference, when the page came from an
1374    /// indirect kid in the page tree (pages inlined directly into a `/Kids`
1375    /// array have none).
1376    pub fn object_ref(&self) -> Option<ObjRef> {
1377        self.obj_ref
1378    }
1379
1380    /// The page's decoded content: the `/Contents` stream, or all streams
1381    /// of a `/Contents` array decoded and joined with `b"\n"`. A missing
1382    /// `/Contents` yields empty content (lenient).
1383    ///
1384    /// This drives [`page_content_with`] to completion on the calling thread.
1385    /// There is one implementation of the algorithm, so this and the
1386    /// asynchronous API cannot drift apart in what they consider a page's
1387    /// content to be.
1388    pub fn content(&self, doc: &Document) -> Result<Vec<u8>> {
1389        block_on(page_content_with(Immediate(doc), self))
1390    }
1391
1392    /// Crop-box width and height, swapped when `/Rotate` is a quarter turn.
1393    ///
1394    /// Both constructors normalize `rotate`, but the field is public and so
1395    /// can be overwritten with a raw `/Rotate`; the rotation is therefore read
1396    /// modulo a full turn rather than compared against 90 and 270 exactly, so
1397    /// that -90 and 450 swap the dimensions just as 270 and 90 do. For an
1398    /// already-normalized value this is the same test as before: 0, 90, 180
1399    /// and 270 are unchanged by `rem_euclid(360)`.
1400    pub fn size(&self) -> (f32, f32) {
1401        let (w, h) = (self.crop_box.width(), self.crop_box.height());
1402        let turn = self.rotate.rem_euclid(360);
1403        if turn == 90 || turn == 270 {
1404            (h, w)
1405        } else {
1406            (w, h)
1407        }
1408    }
1409
1410    /// The raw page dictionary.
1411    pub fn dict(&self) -> &Dict {
1412        &self.dict
1413    }
1414}
1415
1416/// A page's decoded content, awaiting each fetch: the `/Contents` stream, or
1417/// all streams of a `/Contents` array decoded and joined with `b"\n"`. A
1418/// missing `/Contents` yields empty content (lenient).
1419///
1420/// This is the only implementation of that algorithm. [`Page::content`] is a
1421/// [`block_on`] wrapper over it, which is what stops the synchronous and
1422/// asynchronous APIs from disagreeing about what a page's content is.
1423///
1424/// # Choosing this signature
1425///
1426/// `src` is taken **by value** rather than by reference. A future holding
1427/// `&'a S` is `Send` but never `'static`, and the asynchronous consumers —
1428/// spawning onto a runtime, or crossing into the Python bindings — need both.
1429/// By value costs nothing in practice: an asynchronous document is an `Arc`
1430/// handle, and [`Immediate`] over a borrowed document is `Copy`.
1431///
1432/// There is deliberately **no `Send` or `Sync` bound** on `S`. Auto traits are
1433/// inferred per instantiation, so this one function yields a `Send` future over
1434/// a genuinely asynchronous source and a non-`Send` future over
1435/// `Immediate<&Document>` — which is what is wanted, because [`block_on`]
1436/// drives the latter on the calling thread and never sends it anywhere. A
1437/// `S: Sync` bound would exclude `Immediate<&Document>` outright; that is also
1438/// why this calls `src.resolve` directly rather than
1439/// [`crate::source::resolve_with`], which does require `Sync`.
1440///
1441/// The returned future is `'static` only when the caller owns the [`Page`]
1442/// inside its own `async` block — the `&Page` borrow is what otherwise
1443/// prevents it.
1444///
1445/// # Errors
1446///
1447/// Propagates whatever `src` reports for a fetch or a stream decode.
1448pub async fn page_content_with<S: AsyncObjectSource>(src: S, page: &Page) -> Result<Vec<u8>> {
1449    let Some(contents) = page.dict.get("Contents") else {
1450        return Ok(Vec::new());
1451    };
1452    match src.resolve(contents).await? {
1453        Object::Stream(ref s) => content_stream_data_with(&src, s).await,
1454        Object::Array(items) => {
1455            let mut out = Vec::new();
1456            let mut first = true;
1457            for item in &items {
1458                let part = src.resolve(item).await?;
1459                let Some(stream) = part.as_stream() else {
1460                    continue; // non-stream entries are skipped (lenient)
1461                };
1462                if !first {
1463                    out.push(b'\n');
1464                }
1465                out.extend_from_slice(&content_stream_data_with(&src, stream).await?);
1466                first = false;
1467            }
1468            Ok(out)
1469        }
1470        _ => Ok(Vec::new()),
1471    }
1472}
1473
1474/// Fetches one stream's bytes GUARANTEED DECODED — refusing the streams
1475/// whose bytes `decode_stream` leaves encoded for the image layer. This is
1476/// the fetch for **every consumer that is not an image decoder**: content
1477/// streams, font programs, `/ToUnicode` CMaps, `/CIDToGIDMap` tables —
1478/// anything that parses what it fetches.
1479///
1480/// This is [`AsyncObjectSource::stream_data`] with two refusals in front.
1481/// A stream whose trailing `/Filter` entry is an image codec (`DCTDecode`,
1482/// `JPXDecode`) fails with [`Error::UnsupportedFilter`] instead of handing
1483/// back the passthrough (ISO 32000-1 7.4.9): a raw JPEG or JPEG 2000
1484/// codestream is indistinguishable from decoded data to anything that is
1485/// not an image decoder, and a parser fed one chews binary garbage into
1486/// operators, tables, or mappings with a clean result. And a `/Filter`
1487/// that cannot be READ at all — a reference cycle, or a chain deeper than
1488/// [`crate::source::MAX_RESOLVE_DEPTH`] — is refused with the resolve
1489/// error, because a value that cannot be read might name an image codec,
1490/// and `decode_stream` would leniently return the bytes as stored. Either
1491/// refusal is the same reportable error as any other filter this library
1492/// cannot run.
1493///
1494/// One leniency is kept, deliberately: a `/Filter` that READS as `null`
1495/// (a dangling reference included — ISO 32000-1 7.3.10 makes one
1496/// equivalent to `null`) or as an unusable value says "no filter", which
1497/// is exactly what `decode_stream` does with it; the stored bytes are the
1498/// decoded bytes by that reading, and no codec name can hide in a value
1499/// that is fully visible.
1500///
1501/// Raw [`AsyncObjectSource::stream_data`] remains correct in exactly one
1502/// place: the image layer, which reads the trailing filter itself and
1503/// decodes the passthrough. A new call site that is not decoding images
1504/// belongs here instead. Same calling convention as [`page_content_with`]
1505/// (`src` by value; see that function's docs).
1506pub async fn decoded_stream_data_with<S: AsyncObjectSource>(src: S, s: &Stream) -> Result<Vec<u8>> {
1507    if let Some(name) = filters::trailing_filter_checked_with(&src, &s.dict).await? {
1508        if filters::is_image_codec(&name.0) {
1509            return Err(Error::UnsupportedFilter(name.0));
1510        }
1511    }
1512    src.stream_data(s).await
1513}
1514
1515/// Fetches and decodes one CONTENT stream — page `/Contents`, a form
1516/// XObject, a Type3 CharProc, a pattern cell: anything whose bytes feed a
1517/// content parser rather than an image decoder.
1518///
1519/// The content-flavored name for [`decoded_stream_data_with`], which is
1520/// the same refusal for every non-image consumer; see it for why a
1521/// passthrough image codec must never reach a parser. For a content
1522/// stream the refusal is what turns the mislabelled stream into the same
1523/// reported skip as any other filter this library cannot run.
1524pub async fn content_stream_data_with<S: AsyncObjectSource>(src: S, s: &Stream) -> Result<Vec<u8>> {
1525    decoded_stream_data_with(src, s).await
1526}
1527
1528#[cfg(test)]
1529mod tests {
1530    use super::*;
1531    use crate::object::Name;
1532    use crate::parser::{NoResolve, Parser};
1533    use crate::xref::XrefEntry;
1534    use pdfboss_testkit::{multi_page_doc, objstm_doc, objstm_payload, simple_doc, PdfBuilder};
1535
1536    /// The synchronous accessor delegates to the asynchronous one, so the two
1537    /// cannot report different content for the same page. This asserts the
1538    /// equality directly rather than trusting the delegation to stay in place.
1539    #[test]
1540    fn async_page_content_matches_the_sync_accessor() {
1541        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).expect("load");
1542        let mut saw_content = false;
1543        for index in 0..3 {
1544            let page = doc.page(index).expect("page");
1545            let direct = page.content(&doc).expect("sync content");
1546            let awaited =
1547                block_on(page_content_with(Immediate(&doc), &page)).expect("async content");
1548            assert_eq!(direct, awaited, "page {index}");
1549            saw_content |= !direct.is_empty();
1550        }
1551        // Without this the loop above would pass on three empty vectors.
1552        assert!(
1553            saw_content,
1554            "fixture must give at least one page real content"
1555        );
1556    }
1557
1558    /// A page `/Contents` stream whose trailing filter is an image codec is
1559    /// refused, never parsed: `decode_stream` would pass its bytes through
1560    /// STILL ENCODED (ISO 32000-1 7.4.9 reserves that for the image layer),
1561    /// and the stream below is deliberately valid operator syntax to prove
1562    /// the refusal happens on the label, not on the bytes. The error is the
1563    /// same `UnsupportedFilter` any genuinely undecodable filter raises, so
1564    /// every caller reports it identically.
1565    #[test]
1566    fn image_codec_page_contents_are_refused_not_returned() {
1567        for codec in ["JPXDecode", "DCTDecode"] {
1568            let mut b = PdfBuilder::new();
1569            b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1570            b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
1571            b.object(
1572                3,
1573                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>",
1574            );
1575            b.stream(
1576                4,
1577                &format!("/Filter /{codec}"),
1578                b"1 0 0 rg 0 0 100 100 re f",
1579            );
1580            let doc = Document::load(b.build(1)).expect("load");
1581            let page = doc.page(0).expect("page");
1582            match page.content(&doc) {
1583                Err(Error::UnsupportedFilter(n)) => assert_eq!(n, codec),
1584                other => panic!("{codec} content must be refused, got {other:?}"),
1585            }
1586        }
1587    }
1588
1589    /// A `/Contents` whose `/Filter` is a reference CYCLE is refused as
1590    /// unreadable, never fetched: `decode_stream` cannot resolve the value
1591    /// either and would leniently return the bytes AS STORED — and a value
1592    /// nobody can read might name an image codec, so the stored bytes may
1593    /// be a passthrough codestream. The bytes below are deliberately valid
1594    /// operator syntax to prove the refusal is about the unreadable label.
1595    #[test]
1596    fn an_unreadable_filter_refuses_the_content_not_returns_it_raw() {
1597        let mut b = PdfBuilder::new();
1598        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1599        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
1600        b.object(
1601            3,
1602            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>",
1603        );
1604        b.stream(4, "/Filter 6 0 R", b"1 0 0 rg 0 0 100 100 re f");
1605        b.object(6, "7 0 R");
1606        b.object(7, "6 0 R");
1607        let doc = Document::load(b.build(1)).expect("load");
1608        let page = doc.page(0).expect("page");
1609        assert!(
1610            page.content(&doc).is_err(),
1611            "an unreadable /Filter must refuse, not pass stored bytes"
1612        );
1613    }
1614
1615    /// The composition every page-reading algorithm actually uses: the caller
1616    /// owns its source so that its own future can be `'static`, and reaches this
1617    /// helper — which owns its source for the same reason — by handing out a
1618    /// reference. That works because `&S` is itself an `AsyncObjectSource`.
1619    #[test]
1620    fn a_shared_helper_is_reachable_from_a_caller_that_owns_its_source() {
1621        let doc = Document::load(simple_doc("Hello")).expect("load");
1622        let page = doc.page(0).expect("page");
1623
1624        let owner = Immediate(&doc);
1625        let through_reference = block_on(page_content_with(&owner, &page)).expect("async content");
1626
1627        assert_eq!(through_reference, page.content(&doc).expect("sync content"));
1628        assert!(!through_reference.is_empty());
1629    }
1630
1631    /// The seed is what crosses a thread boundary, so this is the compile
1632    /// gate for the whole fan-out design. The `Document` itself must stay
1633    /// out of this list: its caches are single-threaded by design.
1634    #[test]
1635    fn the_seed_is_shareable_across_threads() {
1636        fn assert_send_sync<T: Send + Sync>() {}
1637        assert_send_sync::<DocumentSeed>();
1638    }
1639
1640    /// A fork shares the file and the page tree but none of the caches, and
1641    /// reads identically to its parent — including through decryption, whose
1642    /// key material is part of the shared immutable core.
1643    #[test]
1644    fn a_fork_reads_exactly_what_its_parent_reads() {
1645        let doc = Document::load(pdfboss_testkit::encrypted_rc4_doc("forked secret")).unwrap();
1646        let fork = doc.fork();
1647        assert_eq!(fork.page_count(), doc.page_count());
1648        let (a, b) = (doc.page(0).unwrap(), fork.page(0).unwrap());
1649        assert_eq!(a.media_box, b.media_box);
1650        assert_eq!(
1651            a.content(&doc).expect("parent content"),
1652            b.content(&fork).expect("fork content"),
1653            "decrypted content agrees"
1654        );
1655    }
1656
1657    /// The seed's page count is the flattened tree's length: the number
1658    /// every document built from it reports, available without building one.
1659    #[test]
1660    fn the_seed_reports_the_flattened_page_count() {
1661        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).unwrap();
1662        let seed = doc.seed();
1663        assert_eq!(seed.page_count(), 3);
1664        assert_eq!(Document::from_seed(seed).page_count(), 3);
1665    }
1666
1667    /// The results come back in page order whatever order the workers finish
1668    /// in, and a per-page error occupies its own slot without disturbing the
1669    /// others.
1670    #[test]
1671    fn map_pages_preserves_page_order() {
1672        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).unwrap();
1673        let contents = map_pages(&doc, |doc, page| page.content(doc));
1674        assert_eq!(contents.len(), 3);
1675        let texts: Vec<String> = contents
1676            .into_iter()
1677            .map(|c| String::from_utf8_lossy(&c.unwrap()).into_owned())
1678            .collect();
1679        assert!(texts[0].contains("(one)"), "{}", texts[0]);
1680        assert!(texts[1].contains("(two)"), "{}", texts[1]);
1681        assert!(texts[2].contains("(three)"), "{}", texts[2]);
1682    }
1683
1684    /// The state is forked once per worker, never per page, and every page
1685    /// sees a fork: over a three-page document the forks number at most
1686    /// three and at least one, and each page's work reads the fork it got.
1687    #[test]
1688    fn map_pages_forking_forks_the_state_once_per_worker() {
1689        let doc = Document::load(multi_page_doc(&["one", "two", "three"])).unwrap();
1690        let forks = std::sync::atomic::AtomicUsize::new(0);
1691        let tags = map_pages_forking(
1692            &doc,
1693            || forks.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1694            |fork, doc, page| Ok((*fork, page.content(doc)?.len())),
1695        );
1696        let forked = forks.load(std::sync::atomic::Ordering::Relaxed);
1697        assert!((1..=3).contains(&forked), "{forked} forks for three pages");
1698        for outcome in tags {
1699            let (fork, len) = outcome.unwrap();
1700            assert!((1..=forked).contains(&fork));
1701            assert!(len > 0);
1702        }
1703    }
1704
1705    /// Replaces the first occurrence of `from` with `to`. Splicing happens
1706    /// after the xref section, so byte offsets stay valid.
1707    fn replace_once(data: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
1708        let pos = memchr::memmem::find(data, from).expect("pattern present in fixture");
1709        let mut out = Vec::with_capacity(data.len() - from.len() + to.len());
1710        out.extend_from_slice(&data[..pos]);
1711        out.extend_from_slice(to);
1712        out.extend_from_slice(&data[pos + from.len()..]);
1713        out
1714    }
1715
1716    fn contains(haystack: &[u8], needle: &[u8]) -> bool {
1717        memchr::memmem::find(haystack, needle).is_some()
1718    }
1719
1720    const FONT: &str = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";
1721
1722    // Covers ISO 32000-1 §7.5.3 and §7.7.2.
1723    #[test]
1724    fn loads_simple_doc() {
1725        let doc = Document::load(simple_doc("Greetings, cosmos!")).unwrap();
1726        assert_eq!(doc.version(), (1, 7));
1727        assert_eq!(doc.page_count(), 1);
1728        let page = doc.page(0).unwrap();
1729        assert_eq!(page.index, 0);
1730        assert_eq!(page.media_box, Rect::new(0.0, 0.0, 612.0, 792.0));
1731        assert_eq!(page.crop_box, page.media_box);
1732        assert_eq!(page.rotate, 0);
1733        assert_eq!(page.size(), (612.0, 792.0));
1734        assert!(page.resources.get("Font").is_some());
1735        let content = page.content(&doc).unwrap();
1736        assert!(contains(&content, b"Greetings, cosmos!"));
1737    }
1738
1739    // Covers ISO 32000-1 §7.7.3 and §7.7.3.2.
1740    #[test]
1741    fn multi_page_ordering() {
1742        let doc = Document::load(multi_page_doc(&["alpha", "beta", "gamma"])).unwrap();
1743        assert_eq!(doc.page_count(), 3);
1744        for (i, text) in ["alpha", "beta", "gamma"].iter().enumerate() {
1745            let content = doc.page(i).unwrap().content(&doc).unwrap();
1746            assert!(
1747                contains(&content, text.as_bytes()),
1748                "page {i} should show {text}"
1749            );
1750        }
1751    }
1752
1753    #[test]
1754    fn page_index_out_of_bounds() {
1755        let doc = Document::load(simple_doc("x")).unwrap();
1756        assert!(matches!(doc.page(5), Err(Error::PageNotFound(5, 1))));
1757    }
1758
1759    #[test]
1760    fn open_reads_from_disk() {
1761        let dir = std::env::temp_dir();
1762        let path = dir.join(format!("pdfboss-doc-test-{}.pdf", std::process::id()));
1763        std::fs::write(&path, simple_doc("from disk")).unwrap();
1764        let doc = Document::open(&path).unwrap();
1765        std::fs::remove_file(&path).ok();
1766        assert_eq!(doc.page_count(), 1);
1767        let content = doc.page(0).unwrap().content(&doc).unwrap();
1768        assert!(contains(&content, b"from disk"));
1769        assert!(matches!(
1770            Document::open(dir.join("pdfboss-doc-test-missing.pdf")),
1771            Err(Error::Io(_))
1772        ));
1773    }
1774
1775    // Covers ISO 32000-1 §7.5.5.
1776    #[test]
1777    fn encrypt_in_trailer_is_rejected() {
1778        let data = replace_once(
1779            &simple_doc("secret"),
1780            b"trailer\n<< /Size",
1781            b"trailer\n<< /Encrypt 9 0 R /Size",
1782        );
1783        assert!(matches!(Document::load(data), Err(Error::Encrypted)));
1784    }
1785
1786    // Covers ISO 32000-1 §14.3.3, §7.5.5 and §7.9.2.2.
1787    #[test]
1788    fn metadata_utf16be_round_trip() {
1789        let mut b = PdfBuilder::new();
1790        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1791        b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
1792        // /Title is UTF-16BE with BOM: "H\u{151}" (H + o with double acute).
1793        b.object(6, "<< /Title <FEFF00480151> /Author (plain author) >>");
1794        let data = replace_once(&b.build(1), b"<< /Size", b"<< /Info 6 0 R /Size");
1795        let doc = Document::load(data).unwrap();
1796        let meta = doc.metadata();
1797        assert_eq!(meta.title.as_deref(), Some("H\u{151}"));
1798        assert_eq!(meta.author.as_deref(), Some("plain author"));
1799        assert_eq!(meta.subject, None);
1800        assert_eq!(meta.keywords, None);
1801        assert_eq!(meta.creation_date, None);
1802    }
1803
1804    // Covers ISO 32000-1 §7.9.4 and §14.3.3: the dates read as dates, and a
1805    // string that is not one keeps only its text.
1806    #[test]
1807    fn metadata_dates_parse_per_the_date_clause() {
1808        let mut b = PdfBuilder::new();
1809        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1810        b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
1811        // The clause's own example, and a month 20 no calendar has.
1812        b.object(
1813            6,
1814            "<< /CreationDate (D:199812231952-08'00) /ModDate (D:191020717014604) >>",
1815        );
1816        let data = replace_once(&b.build(1), b"<< /Size", b"<< /Info 6 0 R /Size");
1817        let doc = Document::load(data).unwrap();
1818        let meta = doc.metadata();
1819        assert_eq!(meta.creation_date.as_deref(), Some("D:199812231952-08'00"));
1820        assert_eq!(
1821            meta.creation_date_parsed(),
1822            Some(Date {
1823                year: 1998,
1824                month: 12,
1825                day: 23,
1826                hour: 19,
1827                minute: 52,
1828                second: 0,
1829                utc_offset_minutes: -480,
1830            })
1831        );
1832        assert_eq!(meta.mod_date.as_deref(), Some("D:191020717014604"));
1833        assert_eq!(meta.mod_date_parsed(), None, "month 20 is not a date");
1834    }
1835
1836    #[test]
1837    fn metadata_without_info_is_all_none() {
1838        let doc = Document::load(simple_doc("x")).unwrap();
1839        assert_eq!(doc.metadata(), Metadata::default());
1840    }
1841
1842    // Covers ISO 32000-1 §7.3.10 and §7.3.9.
1843    #[test]
1844    fn missing_object_resolves_to_null() {
1845        let doc = Document::load(simple_doc("x")).unwrap();
1846        let missing = Object::Ref(ObjRef { num: 99, gen: 0 });
1847        assert_eq!(doc.resolve(&missing).unwrap(), Object::Null);
1848        assert!(matches!(
1849            doc.get(ObjRef { num: 99, gen: 0 }),
1850            Err(Error::ObjectNotFound(99, 0))
1851        ));
1852    }
1853
1854    #[test]
1855    fn self_reference_is_circular() {
1856        let mut b = PdfBuilder::new();
1857        b.object(1, "<< /Type /Catalog >>");
1858        b.object(6, "6 0 R");
1859        let doc = Document::load(b.build(1)).unwrap();
1860        let loops = Object::Ref(ObjRef { num: 6, gen: 0 });
1861        assert!(matches!(
1862            doc.resolve(&loops),
1863            Err(Error::CircularReference(6))
1864        ));
1865    }
1866
1867    // Covers ISO 32000-1 §7.3.10.
1868    #[test]
1869    fn generation_mismatch_is_tolerated() {
1870        let doc = Document::load(simple_doc("x")).unwrap();
1871        let catalog = doc.get(ObjRef { num: 1, gen: 7 }).unwrap();
1872        let dict = catalog.as_dict().unwrap();
1873        assert_eq!(dict.get_name("Type").map(|n| n.0.as_str()), Some("Catalog"));
1874    }
1875
1876    // Covers ISO 32000-1 §7.5.7.
1877    #[test]
1878    fn objects_in_object_streams_are_fetched() {
1879        let mut b = PdfBuilder::new();
1880        let (dict, payload) =
1881            objstm_payload(&[(1, "<< /Type /Catalog /Pages 2 0 R >>"), (5, FONT)]);
1882        b.stream(6, &dict, &payload);
1883        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
1884        b.object(
1885            3,
1886            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
1887             /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
1888        );
1889        b.stream(4, "", b"BT /F1 12 Tf (compressed hello) Tj ET");
1890        let doc = Document::load(b.build_xref_stream(1)).unwrap();
1891        assert_eq!(doc.page_count(), 1);
1892        let page = doc.page(0).unwrap();
1893        assert!(contains(&page.content(&doc).unwrap(), b"compressed hello"));
1894        let font = doc.get(ObjRef { num: 5, gen: 0 }).unwrap();
1895        assert_eq!(
1896            font.as_dict()
1897                .and_then(|d| d.get_name("BaseFont"))
1898                .map(|n| n.0.as_str()),
1899            Some("Helvetica")
1900        );
1901    }
1902
1903    // Covers ISO 32000-1 §7.7.3.3 and §7.8.2.
1904    #[test]
1905    fn contents_array_is_joined_with_newlines() {
1906        let mut b = PdfBuilder::new();
1907        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1908        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
1909        b.object(
1910            3,
1911            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
1912             /Contents [4 0 R null 5 0 R] >>",
1913        );
1914        b.stream(4, "", b"q");
1915        b.stream(5, "", b"Q");
1916        let doc = Document::load(b.build(1)).unwrap();
1917        let content = doc.page(0).unwrap().content(&doc).unwrap();
1918        assert_eq!(content, b"q\nQ", "streams joined by \\n, null skipped");
1919    }
1920
1921    // Covers ISO 32000-1 §7.7.3 and §7.7.3.4.
1922    #[test]
1923    fn inheritance_from_pages_node_and_rotate_swap() {
1924        let mut b = PdfBuilder::new();
1925        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1926        b.object(
1927            2,
1928            "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 \
1929             /Resources << /Font << /F1 5 0 R >> >> /MediaBox [0 0 400 600] >>",
1930        );
1931        b.object(3, "<< /Type /Page /Parent 2 0 R >>");
1932        b.object(4, "<< /Type /Page /Parent 2 0 R /Rotate 270 >>");
1933        b.object(5, FONT);
1934        let doc = Document::load(b.build(1)).unwrap();
1935        assert_eq!(doc.page_count(), 2);
1936
1937        let first = doc.page(0).unwrap();
1938        assert_eq!(first.media_box, Rect::new(0.0, 0.0, 400.0, 600.0));
1939        assert_eq!(first.crop_box, first.media_box);
1940        assert!(first.resources.get("Font").is_some(), "inherited resources");
1941        assert_eq!(first.rotate, 0);
1942        assert!(
1943            first.content(&doc).unwrap().is_empty(),
1944            "no /Contents means empty content"
1945        );
1946        assert_eq!(first.size(), (400.0, 600.0));
1947
1948        let second = doc.page(1).unwrap();
1949        assert_eq!(second.rotate, 270);
1950        assert_eq!(second.size(), (600.0, 400.0), "rotate 270 swaps w/h");
1951    }
1952
1953    // Covers ISO 32000-1 §7.7.3.4 and §7.9.5.
1954    #[test]
1955    fn crop_box_intersected_and_rotate_normalized() {
1956        let mut b = PdfBuilder::new();
1957        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1958        b.object(2, "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>");
1959        b.object(
1960            3,
1961            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
1962             /CropBox [100 100 400 400] /Rotate 450 >>",
1963        );
1964        b.object(4, "<< /Type /Page /Parent 2 0 R /Rotate -90 >>");
1965        b.object(
1966            5,
1967            "<< /Type /Page /Parent 2 0 R /Rotate 45 /MediaBox [0 0 0 0] >>",
1968        );
1969        let doc = Document::load(b.build(1)).unwrap();
1970
1971        let clipped = doc.page(0).unwrap();
1972        assert_eq!(clipped.crop_box, Rect::new(100.0, 100.0, 200.0, 200.0));
1973        assert_eq!(clipped.rotate, 90, "450 normalizes to 90");
1974        assert_eq!(clipped.size(), (100.0, 100.0));
1975
1976        assert_eq!(doc.page(1).unwrap().rotate, 270, "-90 normalizes to 270");
1977        let odd = doc.page(2).unwrap();
1978        assert_eq!(odd.rotate, 0, "non-multiple of 90 falls back to 0");
1979        assert_eq!(
1980            odd.media_box,
1981            Page::US_LETTER,
1982            "degenerate media box defaults"
1983        );
1984    }
1985
1986    // Covers ISO 32000-1 §14.11.2, §7.7.3.3 and §7.9.5.
1987    #[test]
1988    fn page_boxes_declared_and_defaulted() {
1989        let mut b = PdfBuilder::new();
1990        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
1991        b.object(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>");
1992        b.object(
1993            3,
1994            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] \
1995             /CropBox [50 50 550 750] /BleedBox [40 40 560 760] \
1996             /TrimBox [5 0 R 6 0 R 7 0 R 8 0 R] >>",
1997        );
1998        b.object(4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] >>");
1999        b.object(5, "60");
2000        b.object(6, "70");
2001        b.object(7, "540");
2002        b.object(8, "730");
2003        let doc = Document::load(b.build(1)).unwrap();
2004
2005        let page = doc.page(0).unwrap();
2006        assert_eq!(page.bleed_box, Rect::new(40.0, 40.0, 560.0, 760.0));
2007        assert_eq!(
2008            page.trim_box,
2009            Rect::new(60.0, 70.0, 540.0, 730.0),
2010            "indirect array elements resolve"
2011        );
2012        assert_eq!(
2013            page.art_box, page.crop_box,
2014            "undeclared box is the crop box"
2015        );
2016
2017        let bare = doc.page(1).unwrap();
2018        assert_eq!(bare.bleed_box, bare.crop_box);
2019        assert_eq!(bare.trim_box, bare.crop_box);
2020        assert_eq!(bare.art_box, bare.crop_box);
2021    }
2022
2023    // Covers ISO 32000-1 §14.11.2 and §7.7.3.3.
2024    #[test]
2025    fn page_boxes_clip_to_media_and_fall_back() {
2026        let mut b = PdfBuilder::new();
2027        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2028        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
2029        b.object(
2030            3,
2031            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
2032             /CropBox [10 10 190 190] /TrimBox [100 100 400 400] \
2033             /BleedBox [0 0 0 0] /ArtBox [300 300 400 400] >>",
2034        );
2035        let doc = Document::load(b.build(1)).unwrap();
2036
2037        let page = doc.page(0).unwrap();
2038        assert_eq!(
2039            page.trim_box,
2040            Rect::new(100.0, 100.0, 200.0, 200.0),
2041            "a trim box past the media box clips to it"
2042        );
2043        assert_eq!(
2044            page.bleed_box, page.crop_box,
2045            "a degenerate bleed box falls back to the crop box"
2046        );
2047        assert_eq!(
2048            page.art_box, page.crop_box,
2049            "an art box disjoint from the media box falls back to the crop box"
2050        );
2051    }
2052
2053    /// `/BleedBox`, `/TrimBox` and `/ArtBox` are not in ISO 32000 Table 30's
2054    /// inheritable set: a value on a `/Pages` node must not leak into its
2055    /// leaves, which read their spec default (the crop box) instead.
2056    // Covers ISO 32000-1 §14.11.2 and §7.7.3.3.
2057    #[test]
2058    fn page_boxes_are_not_inherited() {
2059        let mut b = PdfBuilder::new();
2060        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2061        b.object(
2062            2,
2063            "<< /Type /Pages /Kids [3 0 R] /Count 1 \
2064             /TrimBox [10 10 90 90] /BleedBox [5 5 95 95] /ArtBox [20 20 80 80] >>",
2065        );
2066        b.object(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2067        let doc = Document::load(b.build(1)).unwrap();
2068
2069        let page = doc.page(0).unwrap();
2070        assert_eq!(page.trim_box, page.crop_box);
2071        assert_eq!(page.bleed_box, page.crop_box);
2072        assert_eq!(page.art_box, page.crop_box);
2073    }
2074
2075    // Covers ISO 32000-1 §7.7.3.2.
2076    #[test]
2077    fn kids_cycle_truncates_without_hanging() {
2078        let mut b = PdfBuilder::new();
2079        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2080        // 2 → 3 → {4, back to 2}: the back-edge must be ignored.
2081        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
2082        b.object(3, "<< /Type /Pages /Kids [4 0 R 2 0 R] /Count 1 >>");
2083        b.object(
2084            4,
2085            "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 100 100] /Contents 5 0 R >>",
2086        );
2087        b.stream(5, "", b"0 0 50 50 re f");
2088        let doc = Document::load(b.build(1)).unwrap();
2089        assert_eq!(doc.page_count(), 1, "cycle back-edge yields no extra pages");
2090        assert!(contains(
2091            &doc.page(0).unwrap().content(&doc).unwrap(),
2092            b"re f"
2093        ));
2094    }
2095
2096    // Covers ISO 32000-1 §7.7.3.2 and Annex C.2.
2097    #[test]
2098    fn tree_depth_is_capped() {
2099        let mut b = PdfBuilder::new();
2100        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2101        // A unary chain of 300 intermediate nodes, page leaf at the bottom.
2102        let last = 302u32;
2103        for num in 2..last {
2104            b.object(
2105                num,
2106                &format!("<< /Type /Pages /Kids [{} 0 R] /Count 1 >>", num + 1),
2107            );
2108        }
2109        b.object(last, "<< /Type /Page >>");
2110        let doc = Document::load(b.build(1)).unwrap();
2111        assert_eq!(doc.page_count(), 0, "the leaf lies beyond the depth cap");
2112        assert!(
2113            matches!(doc.page(0), Err(Error::PageNotFound(0, 0))),
2114            "leaf beyond the depth cap cannot be materialized"
2115        );
2116    }
2117
2118    // Covers ISO 32000-1 §7.7.3.2.
2119    #[test]
2120    fn page_count_ignores_a_count_above_the_kids() {
2121        let mut b = PdfBuilder::new();
2122        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2123        b.object(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 5 >>");
2124        b.object(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2125        b.object(4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2126        let doc = Document::load(b.build(1)).unwrap();
2127        assert_eq!(doc.page_count(), 2);
2128        assert!(doc.page(1).is_ok());
2129        assert!(matches!(doc.page(2), Err(Error::PageNotFound(2, 2))));
2130    }
2131
2132    // Covers ISO 32000-1 §7.7.3.2.
2133    #[test]
2134    fn page_count_ignores_a_count_below_the_kids() {
2135        let mut b = PdfBuilder::new();
2136        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2137        b.object(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 1 >>");
2138        b.object(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2139        b.object(4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2140        let doc = Document::load(b.build(1)).unwrap();
2141        assert_eq!(doc.page_count(), 2);
2142        assert_eq!(doc.seed().page_count(), 2);
2143    }
2144
2145    // Covers ISO 32000-1 §7.7.3.2.
2146    #[test]
2147    fn page_count_falls_back_to_walk_when_count_absent() {
2148        let mut b = PdfBuilder::new();
2149        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2150        b.object(2, "<< /Type /Pages /Kids [3 0 R] >>"); // no /Count
2151        b.object(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2152        let doc = Document::load(b.build(1)).unwrap();
2153        assert_eq!(
2154            doc.page_count(),
2155            1,
2156            "missing /Count is recovered by walking"
2157        );
2158    }
2159
2160    // Covers ISO 32000-1 §7.7.3.2.
2161    #[test]
2162    fn page_count_ignores_corrupt_oversized_count() {
2163        // A `/Count` larger than the whole file is impossible: fall back to a
2164        // real walk rather than trust it.
2165        let mut b = PdfBuilder::new();
2166        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2167        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 999999999 >>");
2168        b.object(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>");
2169        let doc = Document::load(b.build(1)).unwrap();
2170        assert_eq!(doc.page_count(), 1, "implausible /Count is rejected");
2171    }
2172
2173    // Covers ISO 32000-1 §7.5.2 and Annex I.
2174    #[test]
2175    fn version_scan_and_default() {
2176        let mut b = PdfBuilder::new().version(2, 0);
2177        b.object(1, "<< /Type /Catalog >>");
2178        assert_eq!(Document::load(b.build(1)).unwrap().version(), (2, 0));
2179        // Corrupting the header magic (same length) falls back to 1.4.
2180        let data = replace_once(&simple_doc("v"), b"%PDF-", b"%QQQ-");
2181        assert_eq!(Document::load(data).unwrap().version(), (1, 4));
2182    }
2183
2184    // Covers ISO 32000-1 Annex C.2.
2185    #[test]
2186    fn deeply_nested_root_object_does_not_overflow_the_stack() {
2187        // A ~100 KB file whose Root is a 50k-deep array used to drive the
2188        // object parser's recursion into a fatal stack overflow during
2189        // `Document::load`. Run on a small stack so a regression aborts
2190        // loudly rather than depending on the main thread's stack size.
2191        let mut data = b"%PDF-1.7\n1 0 obj\n".to_vec();
2192        data.extend(std::iter::repeat_n(b'[', 50_000));
2193        data.extend(std::iter::repeat_n(b']', 50_000));
2194        data.extend_from_slice(b"\nendobj\ntrailer\n<</Root 1 0 R>>\n%%EOF\n");
2195        let outcome = std::thread::Builder::new()
2196            .stack_size(1024 * 1024)
2197            .spawn(move || Document::load(data).map(|doc| doc.page_count()))
2198            .expect("spawn test thread")
2199            .join()
2200            .expect("Document::load must not overflow the stack");
2201        // The over-nested Root is rejected or ignored (lenient), but the
2202        // process survives and no page is fabricated from it.
2203        assert!(matches!(outcome, Ok(0) | Err(_)));
2204    }
2205
2206    #[test]
2207    fn bytes_and_xref_accessors() {
2208        let data = simple_doc("accessors");
2209        let doc = Document::load(data.clone()).unwrap();
2210        assert_eq!(doc.bytes(), &data[..]);
2211        assert!(!doc.xref().is_empty());
2212        assert!(doc.xref().trailer.get("Root").is_some());
2213    }
2214
2215    #[test]
2216    fn object_at_spanned_reparses_identically() {
2217        let data = simple_doc("spanned");
2218        let doc = Document::load(data).unwrap();
2219        for (num, entry) in doc.xref().iter() {
2220            let XrefEntry::InFile { offset, gen } = entry else {
2221                continue;
2222            };
2223            let (r, object, span) = doc.object_at_spanned(offset as usize).unwrap();
2224            assert_eq!(r.num, num);
2225            assert_eq!(r.gen, gen);
2226            assert_eq!(span.start, offset);
2227            assert!(span.end as usize <= doc.bytes().len());
2228            // The bytes at the span parse back to the same object.
2229            let slice = &doc.bytes()[span.start as usize..span.end as usize];
2230            let (r2, object2) = Parser::new(slice).parse_indirect(&NoResolve).unwrap();
2231            assert_eq!(r2, r);
2232            assert_eq!(object2, object);
2233        }
2234    }
2235
2236    #[test]
2237    fn page_object_ref_points_at_a_page_dict() {
2238        let doc = Document::load(multi_page_doc(&["one", "two"])).unwrap();
2239        for index in 0..doc.page_count() {
2240            let page = doc.page(index).unwrap();
2241            let r = page.object_ref().expect("builder pages are indirect");
2242            let resolved = doc.get(r).unwrap();
2243            assert_eq!(
2244                resolved
2245                    .as_dict()
2246                    .unwrap()
2247                    .get_name("Type")
2248                    .map(|n| n.0.as_str()),
2249                Some("Page")
2250            );
2251        }
2252    }
2253
2254    // --- Minimal Standard-handler (RC4 V2/R3) fixture builder, duplicating
2255    // the key-derivation mechanism `crypt::tests` uses under the empty user
2256    // password (those helpers are private to that module's tests). Needed
2257    // only to pin the decrypt-identity regression test below: RC4's
2258    // per-object key depends on the object's num/gen, so it is the cipher
2259    // that can actually distinguish "decrypt with the parsed header's
2260    // identity" from "decrypt with the caller's requested identity".
2261
2262    const RC4_FIXTURE_KEY_LEN: usize = 16; // 128-bit key
2263    const RC4_FIXTURE_P: i32 = -44;
2264    const RC4_FIXTURE_ID0: &[u8] = b"0123456789abcdef";
2265    const RC4_FIXTURE_PAD: [u8; 32] = [
2266        0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01,
2267        0x08, 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53,
2268        0x69, 0x7A,
2269    ];
2270
2271    #[rustfmt::skip]
2272    const RC4_FIXTURE_MD5_S: [u32; 64] = [
2273        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
2274        5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
2275        4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
2276        6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
2277    ];
2278    #[rustfmt::skip]
2279    const RC4_FIXTURE_MD5_K: [u32; 64] = [
2280        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
2281        0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
2282        0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
2283        0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
2284        0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
2285        0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
2286        0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
2287        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
2288    ];
2289
2290    fn rc4_fixture_md5(input: &[u8]) -> [u8; 16] {
2291        let (mut a0, mut b0, mut c0, mut d0) = (
2292            0x6745_2301u32,
2293            0xefcd_ab89u32,
2294            0x98ba_dcfeu32,
2295            0x1032_5476u32,
2296        );
2297        let mut msg = input.to_vec();
2298        let bitlen = (input.len() as u64).wrapping_mul(8);
2299        msg.push(0x80);
2300        while msg.len() % 64 != 56 {
2301            msg.push(0);
2302        }
2303        msg.extend_from_slice(&bitlen.to_le_bytes());
2304        for chunk in msg.as_chunks::<64>().0 {
2305            let mut m = [0u32; 16];
2306            for (word, bytes) in m.iter_mut().zip(chunk.as_chunks::<4>().0) {
2307                *word = u32::from_le_bytes(*bytes);
2308            }
2309            let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
2310            for i in 0..64 {
2311                let (f, g) = match i {
2312                    0..=15 => ((b & c) | (!b & d), i),
2313                    16..=31 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2314                    32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
2315                    _ => (c ^ (b | !d), (7 * i) % 16),
2316                };
2317                let f = f
2318                    .wrapping_add(a)
2319                    .wrapping_add(RC4_FIXTURE_MD5_K[i])
2320                    .wrapping_add(m[g]);
2321                a = d;
2322                d = c;
2323                c = b;
2324                b = b.wrapping_add(f.rotate_left(RC4_FIXTURE_MD5_S[i]));
2325            }
2326            a0 = a0.wrapping_add(a);
2327            b0 = b0.wrapping_add(b);
2328            c0 = c0.wrapping_add(c);
2329            d0 = d0.wrapping_add(d);
2330        }
2331        let mut out = [0u8; 16];
2332        out[0..4].copy_from_slice(&a0.to_le_bytes());
2333        out[4..8].copy_from_slice(&b0.to_le_bytes());
2334        out[8..12].copy_from_slice(&c0.to_le_bytes());
2335        out[12..16].copy_from_slice(&d0.to_le_bytes());
2336        out
2337    }
2338
2339    fn rc4_fixture_rc4(key: &[u8], data: &[u8]) -> Vec<u8> {
2340        let mut s: [u8; 256] = core::array::from_fn(|i| i as u8);
2341        let mut j = 0u8;
2342        for i in 0..256 {
2343            j = j.wrapping_add(s[i]).wrapping_add(key[i % key.len()]);
2344            s.swap(i, j as usize);
2345        }
2346        let mut out = Vec::with_capacity(data.len());
2347        let (mut i, mut j) = (0u8, 0u8);
2348        for &byte in data {
2349            i = i.wrapping_add(1);
2350            j = j.wrapping_add(s[i as usize]);
2351            s.swap(i as usize, j as usize);
2352            let k = s[s[i as usize].wrapping_add(s[j as usize]) as usize];
2353            out.push(byte ^ k);
2354        }
2355        out
2356    }
2357
2358    /// `/O` for empty owner and user passwords (Algorithm 3, R3).
2359    fn rc4_fixture_owner_entry() -> Vec<u8> {
2360        let mut d = rc4_fixture_md5(&RC4_FIXTURE_PAD);
2361        for _ in 0..50 {
2362            d = rc4_fixture_md5(&d[..RC4_FIXTURE_KEY_LEN]);
2363        }
2364        let rc4key = d[..RC4_FIXTURE_KEY_LEN].to_vec();
2365        let mut o = rc4_fixture_rc4(&rc4key, &RC4_FIXTURE_PAD);
2366        for i in 1u8..=19 {
2367            let k: Vec<u8> = rc4key.iter().map(|b| b ^ i).collect();
2368            o = rc4_fixture_rc4(&k, &o);
2369        }
2370        o
2371    }
2372
2373    /// File key from `/O` for the empty user password (Algorithm 2, R3).
2374    fn rc4_fixture_file_key(o: &[u8]) -> Vec<u8> {
2375        let mut input = Vec::new();
2376        input.extend_from_slice(&RC4_FIXTURE_PAD);
2377        input.extend_from_slice(o);
2378        input.extend_from_slice(&(RC4_FIXTURE_P as u32).to_le_bytes());
2379        input.extend_from_slice(RC4_FIXTURE_ID0);
2380        let mut d = rc4_fixture_md5(&input);
2381        for _ in 0..50 {
2382            d = rc4_fixture_md5(&d[..RC4_FIXTURE_KEY_LEN]);
2383        }
2384        d[..RC4_FIXTURE_KEY_LEN].to_vec()
2385    }
2386
2387    /// `/U` for the empty user password (Algorithm 5, R3).
2388    fn rc4_fixture_user_entry(key: &[u8]) -> Vec<u8> {
2389        let mut input = Vec::new();
2390        input.extend_from_slice(&RC4_FIXTURE_PAD);
2391        input.extend_from_slice(RC4_FIXTURE_ID0);
2392        let mut x = rc4_fixture_md5(&input).to_vec();
2393        x = rc4_fixture_rc4(key, &x);
2394        for i in 1u8..=19 {
2395            let k: Vec<u8> = key.iter().map(|b| b ^ i).collect();
2396            x = rc4_fixture_rc4(&k, &x);
2397        }
2398        x.resize(32, 0); // trailing padding is arbitrary
2399        x
2400    }
2401
2402    fn rc4_fixture_obj_key(key: &[u8], num: u32, gen: u16) -> Vec<u8> {
2403        let mut input = key.to_vec();
2404        input.extend_from_slice(&num.to_le_bytes()[..3]);
2405        input.extend_from_slice(&gen.to_le_bytes()[..2]);
2406        rc4_fixture_md5(&input)[..(key.len() + 5).min(16)].to_vec()
2407    }
2408
2409    fn rc4_fixture_hexstr(b: &[u8]) -> String {
2410        let mut s = String::from("<");
2411        for x in b {
2412            s.push_str(&format!("{x:02x}"));
2413        }
2414        s.push('>');
2415        s
2416    }
2417
2418    /// Builds a V2/R3 (128-bit RC4) file, encrypted under the empty
2419    /// password, with a single indirect object (`3 0 obj`, i.e. gen 0)
2420    /// holding an encrypted string.
2421    fn rc4_encrypted_fixture() -> Vec<u8> {
2422        let o = rc4_fixture_owner_entry();
2423        let key = rc4_fixture_file_key(&o);
2424        let u = rc4_fixture_user_entry(&key);
2425        let msg = rc4_fixture_rc4(&rc4_fixture_obj_key(&key, 3, 0), b"Top secret message");
2426
2427        let mut b = PdfBuilder::new().version(1, 4);
2428        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2429        b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
2430        b.object(3, &format!("<< /Msg {} >>", rc4_fixture_hexstr(&msg)));
2431        b.object(
2432            9,
2433            &format!(
2434                "<< /Filter /Standard /V 2 /R 3 /Length 128 /P {} /O {} /U {} >>",
2435                RC4_FIXTURE_P,
2436                rc4_fixture_hexstr(&o),
2437                rc4_fixture_hexstr(&u)
2438            ),
2439        );
2440        let trailer = format!(
2441            "/Encrypt 9 0 R /ID [{}{}]",
2442            rc4_fixture_hexstr(RC4_FIXTURE_ID0),
2443            rc4_fixture_hexstr(RC4_FIXTURE_ID0)
2444        );
2445        b.trailer_extra(&trailer).build(1)
2446    }
2447
2448    // Covers ISO 32000-1 §7.6.2.
2449    #[test]
2450    fn encrypted_generation_mismatch_still_decrypts() {
2451        // `object_at_spanned` derives the per-object RC4/AESV2 decrypt key
2452        // from the PARSED "N G obj" header at the object's file offset
2453        // (`r.num`, `r.gen` from `parser.parse_indirect`), never from the
2454        // caller's requested `ObjRef` — mirroring how plain (unencrypted)
2455        // lookups already tolerate a generation mismatch
2456        // (`generation_mismatch_is_tolerated`). Request object 3 (really
2457        // "3 0 obj" in the file) under a deliberately wrong generation: if
2458        // decryption instead used the requested (wrong) gen to derive the
2459        // RC4 object key, the result would be garbage, not the plaintext.
2460        let doc = Document::load(rc4_encrypted_fixture()).expect("empty password opens the file");
2461        let obj3 = doc.get(ObjRef { num: 3, gen: 7 }).unwrap();
2462        let msg = obj3
2463            .as_dict()
2464            .unwrap()
2465            .get("Msg")
2466            .unwrap()
2467            .as_str_bytes()
2468            .unwrap();
2469        assert_eq!(
2470            msg, b"Top secret message",
2471            "decrypted using the file's real gen (0), not the mismatched request (7)"
2472        );
2473    }
2474
2475    // Covers ISO 32000-1 §7.5.7.
2476    #[test]
2477    fn objstm_doc_fixture_loads_and_resolves_members() {
2478        let data = objstm_doc(&[(7, "<< /Marker (inside) >>")]);
2479        let doc = Document::load(data).unwrap();
2480        assert_eq!(doc.page_count(), 1);
2481        let member = doc.get(ObjRef { num: 7, gen: 0 }).unwrap();
2482        let text = member.as_dict().unwrap().get("Marker").unwrap();
2483        assert_eq!(text.as_str_bytes(), Some(&b"inside"[..]));
2484        // The member really is xref'd into the object stream.
2485        assert!(matches!(
2486            doc.xref().get(7),
2487            Some(XrefEntry::InStream { stream_num: 4, .. })
2488        ));
2489    }
2490
2491    /// A page built from parts must expose the same accessors as one that
2492    /// came out of the page tree — this is the constructor aio uses.
2493    #[test]
2494    fn page_from_parts_exposes_its_accessors() {
2495        let mut dict = Dict::default();
2496        dict.insert(Name("Type".into()), Object::Name(Name("Page".into())));
2497        let media = Rect::new(0.0, 0.0, 200.0, 400.0);
2498        let obj_ref = ObjRef { num: 7, gen: 0 };
2499
2500        let page = Page::from_parts(
2501            3,
2502            media,
2503            media,
2504            90,
2505            Dict::default(),
2506            dict.clone(),
2507            Some(obj_ref),
2508        );
2509
2510        assert_eq!(page.index, 3);
2511        assert_eq!(page.object_ref(), Some(obj_ref));
2512        assert_eq!(page.dict(), &dict);
2513        // /Rotate 90 swaps the reported page size.
2514        assert_eq!(page.size(), (400.0, 200.0));
2515        // The boxes from_parts does not take read as their spec default.
2516        assert_eq!(page.bleed_box, page.crop_box);
2517        assert_eq!(page.trim_box, page.crop_box);
2518        assert_eq!(page.art_box, page.crop_box);
2519    }
2520
2521    /// `from_parts` normalizes `/Rotate` just as the page tree does, so an
2522    /// unnormalized quarter-turn stores — and reports the size of — its
2523    /// canonical equivalent.
2524    #[test]
2525    fn page_from_parts_normalizes_rotation() {
2526        let media = Rect::new(0.0, 0.0, 200.0, 400.0);
2527        let build = |rotate: i32| {
2528            Page::from_parts(
2529                0,
2530                media,
2531                media,
2532                rotate,
2533                Dict::default(),
2534                Dict::default(),
2535                None,
2536            )
2537        };
2538
2539        for (given, canonical) in [(-90, 270), (450, 90), (540, 180), (720, 0), (-360, 0)] {
2540            let page = build(given);
2541            assert_eq!(
2542                page.rotate, canonical,
2543                "from_parts must normalize /Rotate {given} to {canonical}"
2544            );
2545            assert_eq!(
2546                page.size(),
2547                build(canonical).size(),
2548                "/Rotate {given} must report the same size as {canonical}"
2549            );
2550        }
2551    }
2552
2553    /// `rotate` is a public field, so `size()` cannot rely on the constructor
2554    /// having normalized it: any multiple of 90 must be read modulo a full
2555    /// turn. The already-canonical values are listed too, pinning that this
2556    /// is unchanged for them.
2557    #[test]
2558    fn page_size_handles_unnormalized_rotation() {
2559        let media = Rect::new(0.0, 0.0, 200.0, 400.0);
2560        let mut page = Page::from_parts(0, media, media, 0, Dict::default(), Dict::default(), None);
2561
2562        for rotate in [90, 270, -90, -270, 450, 630] {
2563            page.rotate = rotate;
2564            assert_eq!(
2565                page.size(),
2566                (400.0, 200.0),
2567                "/Rotate {rotate} is a quarter turn and must swap the size"
2568            );
2569        }
2570        for rotate in [0, 180, -180, 360, 540, 720] {
2571            page.rotate = rotate;
2572            assert_eq!(
2573                page.size(),
2574                (200.0, 400.0),
2575                "/Rotate {rotate} is a half turn and must leave the size alone"
2576            );
2577        }
2578    }
2579}