laminapdf-model 0.7.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Pages (ISO 32000-2 §7.7.3): [`Pages`] and the [`Page`] view, with boundary boxes
//! (§14.11.2), rotation and the page's resources, contents and annotations.

use std::cell::OnceCell;
use std::collections::BTreeMap;

use laminapdf_cos::{Dict, DirectPath, ObjRef, Object, PathSegment, Result, Warning};
pub use laminapdf_syntax::Rotation;

use crate::document::Document;
use crate::geometry::{LETTER, PageFrame, UserSpaceRect};
use crate::id::PageId;
use crate::labels::PageLabels;
use crate::outline::Outline;

/// The document's pages in page-tree order (the result of one walk; see
/// [`laminapdf_cos::Document::pages`]).
///
/// Added in 0.2.0.
#[derive(Debug)]
pub struct Pages<'d> {
    doc: &'d Document,
    walked: Vec<laminapdf_cos::Page>,
    ids: Vec<PageId>,
    /// Page index by ID (IDs are unique: one object, or one path, per page).
    by_id: BTreeMap<PageId, usize>,
    /// What each page reads once: its media and crop boxes (every other box is clipped to
    /// them), rotation, user unit and frame (ADR 0027 §3), so their warnings are raised once.
    cache: Vec<PageCache>,
    labels: OnceCell<PageLabels>,
}

/// A page's boxes, rotation, user unit and frame, each computed at most once.
#[derive(Debug, Default)]
struct PageCache {
    boxes: OnceCell<Boxes>,
    rotate: OnceCell<Rotation>,
    user_unit: OnceCell<f64>,
    frame: OnceCell<PageFrame>,
}

/// `cell`'s value, computing it with `compute` the first time (a failure is not cached).
fn memo<T: Copy>(cell: Option<&OnceCell<T>>, compute: impl FnOnce() -> Result<T>) -> Result<T> {
    if let Some(value) = cell.and_then(OnceCell::get) {
        return Ok(*value);
    }
    let value = compute()?;
    Ok(cell.map_or(value, |c| *c.get_or_init(|| value)))
}

/// A page's effective media and crop boxes.
#[derive(Debug, Clone, Copy)]
struct Boxes {
    media: Option<UserSpaceRect>,
    crop: Option<UserSpaceRect>,
}

impl<'d> Pages<'d> {
    pub(crate) fn new(doc: &'d Document) -> Result<Self> {
        let walked = doc.cos().pages()?;
        let ids: Vec<PageId> = walked
            .iter()
            .map(|p| match (&p.obj_ref, &p.direct_path) {
                (Some(r), _) => PageId::object(*r),
                (None, Some(path)) => PageId::path(path),
                // Unreachable: the walk sets one of the two for every page. Should that
                // change, the page is still named by where the tree starts.
                (None, None) => PageId::path(&DirectPath::new(
                    None,
                    vec![PathSegment::Key("Root"), PathSegment::Key("Pages")],
                )),
            })
            .collect();
        let by_id = ids.iter().enumerate().map(|(i, id)| (id.clone(), i)).collect();
        let cache = walked.iter().map(|_| PageCache::default()).collect();
        Ok(Self {
            doc,
            walked,
            ids,
            by_id,
            cache,
            labels: OnceCell::new(),
        })
    }

    /// The number of pages.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn len(&self) -> usize {
        self.walked.len()
    }

    /// True when the document has no pages.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.walked.is_empty()
    }

    /// The page at `index` (0-based), if any.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<Page<'_>> {
        let cos = self.walked.get(index)?;
        let id = self.ids.get(index)?;
        Some(Page {
            pages: self,
            cos,
            id,
            index,
        })
    }

    /// The page with ID `id`, if it is in this document.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn by_id(&self, id: &PageId) -> Option<Page<'_>> {
        self.index_of(id).and_then(|i| self.get(i))
    }

    /// The index of the page with ID `id`.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn index_of(&self, id: &PageId) -> Option<usize> {
        self.by_id.get(id).copied()
    }

    /// The index of the page whose object is `r`.
    pub(crate) fn index_of_object(&self, r: ObjRef) -> Option<usize> {
        self.index_of(&PageId::object(r))
    }

    /// The pages in order.
    ///
    /// Added in 0.2.0.
    pub fn iter(&self) -> impl Iterator<Item = Page<'_>> + '_ {
        (0..self.len()).filter_map(|i| self.get(i))
    }

    /// The document outline, resolving destinations against these pages instead of walking
    /// the page tree again.
    ///
    /// # Errors
    /// As [`Document::outline`].
    ///
    /// Added in 0.2.0.
    pub fn outline(&self) -> Result<Outline<'_>> {
        Outline::with_pages(self.doc, self)
    }

    /// The visible link annotations of `page` (one of these pages), in `/Annots` order (§12.5.6.5).
    /// Hidden ones (`/F` with Hidden or `NoView`, §12.5.3) and those without a usable `/Rect` are
    /// left out. Destinations resolve through the named destinations, read once per call; the
    /// outline's items aren't walked.
    ///
    /// # Errors
    /// Reading errors (the annotations, named destinations, the page tree); in strict mode a
    /// warning they raise.
    ///
    /// Added in 0.2.0.
    pub fn links(&self, page: &Page<'_>) -> Result<Vec<crate::Link>> {
        Outline::without_items(self.doc, self).links(page)
    }

    /// The document these pages belong to.
    pub(crate) const fn document(&self) -> &'d Document {
        self.doc
    }

    /// The page labels, read once per [`Pages`].
    fn labels(&self) -> Result<&PageLabels> {
        if let Some(labels) = self.labels.get() {
            return Ok(labels);
        }
        let labels = PageLabels::new(self.doc)?;
        Ok(self.labels.get_or_init(|| labels))
    }
}

/// One page: a thin view over its dictionary and inherited attributes.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, Copy)]
pub struct Page<'p> {
    pages: &'p Pages<'p>,
    cos: &'p laminapdf_cos::Page,
    id: &'p PageId,
    index: usize,
}

impl<'p> Page<'p> {
    /// The page's stable ID.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn id(&self) -> &'p PageId {
        self.id
    }

    /// The page's 0-based index in the document.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn index(&self) -> usize {
        self.index
    }

    /// The page object (`None` for a direct page dictionary).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn obj_ref(&self) -> Option<ObjRef> {
        self.cos.obj_ref
    }

    /// The page dictionary.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn dict(&self) -> &'p Dict {
        &self.cos.dict
    }

    /// The COS page (inherited attributes resolved).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn cos(&self) -> &'p laminapdf_cos::Page {
        self.cos
    }

    pub(crate) fn doc(&self) -> &'p Document {
        self.pages.doc
    }

    fn object(&self) -> Option<u32> {
        self.cos.obj_ref.map(|r| r.num)
    }

    fn page_number(&self) -> u64 {
        u64::try_from(self.index).unwrap_or(u64::MAX)
    }

    /// The box `key` from its stored value: `None` when absent, `None` plus
    /// [`Warning::InvalidBox`] (naming the page and the box) when it is not four numbers.
    fn read_box(&self, key: &'static str, value: Option<&Object>) -> Result<Option<UserSpaceRect>> {
        let Some(value) = value else {
            return Ok(None);
        };
        let rect = read_rect(self.doc(), value)?;
        if rect.is_none() {
            self.doc().warn(Warning::InvalidBox {
                object: self.object(),
                page: self.page_number(),
                key,
            })?;
        }
        Ok(rect)
    }

    /// The media and crop boxes, read once per page.
    fn boxes(&self) -> Result<Boxes> {
        memo(self.cache().map(|c| &c.boxes), || {
            let media = self.read_box("MediaBox", self.cos.inherited.media_box.as_deref())?;
            let crop = self.read_box("CropBox", self.cos.inherited.crop_box.as_deref())?;
            let crop = match (crop, media) {
                (Some(crop), Some(media)) => Some(crop.intersect(&media).unwrap_or(media)),
                (crop, media) => crop.or(media),
            };
            Ok(Boxes { media, crop })
        })
    }

    fn cache(&self) -> Option<&'p PageCache> {
        self.pages.cache.get(self.index)
    }

    /// `/MediaBox`, own or inherited (§14.11.2); `None` when absent or malformed (the latter
    /// with [`Warning::InvalidBox`]).
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::Strict`] in strict mode for a malformed box;
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`].
    ///
    /// Added in 0.2.0.
    pub fn media_box(&self) -> Result<Option<UserSpaceRect>> {
        Ok(self.boxes()?.media)
    }

    /// The crop box: `/CropBox` (own or inherited) intersected with the media box, or the
    /// media box when `/CropBox` is absent or malformed (§14.11.2).
    ///
    /// # Errors
    /// As [`Page::media_box`].
    ///
    /// Added in 0.2.0.
    pub fn crop_box(&self) -> Result<Option<UserSpaceRect>> {
        Ok(self.boxes()?.crop)
    }

    /// A box that defaults to the crop box (bleed, trim and art boxes are not inheritable).
    /// The box itself is read first, so in strict mode its own problem is the one reported.
    fn clipped_box(&self, key: &'static str) -> Result<Option<UserSpaceRect>> {
        let own = self.read_box(key, self.cos.dict.get(key))?;
        let crop = self.crop_box()?;
        Ok(match (own, crop) {
            (Some(own), Some(crop)) => Some(own.intersect(&crop).unwrap_or(crop)),
            (own, crop) => own.or(crop),
        })
    }

    /// `/BleedBox` intersected with the crop box; defaults to the crop box.
    ///
    /// # Errors
    /// As [`Page::media_box`].
    ///
    /// Added in 0.2.0.
    pub fn bleed_box(&self) -> Result<Option<UserSpaceRect>> {
        self.clipped_box("BleedBox")
    }

    /// `/TrimBox` intersected with the crop box; defaults to the crop box.
    ///
    /// # Errors
    /// As [`Page::media_box`].
    ///
    /// Added in 0.2.0.
    pub fn trim_box(&self) -> Result<Option<UserSpaceRect>> {
        self.clipped_box("TrimBox")
    }

    /// `/ArtBox` intersected with the crop box; defaults to the crop box.
    ///
    /// # Errors
    /// As [`Page::media_box`].
    ///
    /// Added in 0.2.0.
    pub fn art_box(&self) -> Result<Option<UserSpaceRect>> {
        self.clipped_box("ArtBox")
    }

    /// `/Rotate`, own or inherited, read once per page. A value that is not a multiple of 90
    /// (or not a number) reads as [`Rotation::None`] with [`Warning::InvalidRotate`].
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::Strict`] in strict mode for an invalid value;
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`].
    ///
    /// Added in 0.2.0.
    pub fn rotate(&self) -> Result<Rotation> {
        memo(self.cache().map(|c| &c.rotate), || self.read_rotate())
    }

    /// `/Rotate`, own or inherited, as [`Page::rotate`] reads it but without the warning: a
    /// value that is not a multiple of 90 (or not a number) reads as [`Rotation::None`]. For
    /// code that replaces the value, such as the `RotatePage` op.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`], and
    /// [`laminapdf_cos::Error::Strict`] in strict mode when the value cannot be resolved.
    ///
    /// Added in 0.2.0.
    pub fn rotate_quietly(&self) -> Result<Rotation> {
        Ok(self.stored_rotate()?.unwrap_or_default())
    }

    /// The stored `/Rotate` as a rotation ([`Rotation::None`] when absent), `None` when it is
    /// malformed.
    fn stored_rotate(&self) -> Result<Option<Rotation>> {
        let Some(value) = self.cos.inherited.rotate.as_deref() else {
            return Ok(Some(Rotation::None));
        };
        self.doc().read_rotate(value)
    }

    fn read_rotate(&self) -> Result<Rotation> {
        if let Some(rotation) = self.stored_rotate()? {
            return Ok(rotation);
        }
        self.doc().warn(Warning::InvalidRotate {
            object: self.object(),
            page: self.page_number(),
        })?;
        Ok(Rotation::None)
    }

    /// `/UserUnit` (§14.11.2.1): the size of a default user-space unit in 1/72 inch, read
    /// once per page; 1 when absent, and 1 with [`Warning::InvalidEntry`] when not a positive
    /// number.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::Strict`] in strict mode for an invalid value;
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`].
    ///
    /// Added in 0.2.0.
    pub fn user_unit(&self) -> Result<f64> {
        memo(self.cache().map(|c| &c.user_unit), || self.read_user_unit())
    }

    fn read_user_unit(&self) -> Result<f64> {
        let Some(value) = self.cos.dict.get("UserUnit") else {
            return Ok(1.0);
        };
        let unit = self
            .doc()
            .read(value)?
            .and_then(|v| v.as_f64())
            .filter(|u| u.is_finite() && *u > 0.0);
        if let Some(unit) = unit {
            Ok(unit)
        } else {
            self.doc().warn(Warning::InvalidEntry {
                object: self.object(),
                key: "UserUnit",
            })?;
            Ok(1.0)
        }
    }

    /// The page's frame ([ADR 0027] §3): the effective crop box, [`Page::rotate`] and
    /// [`Page::user_unit`], computed once per page. When neither the crop box nor the media
    /// box has an area, the frame is US Letter (`[0 0 612 792]`) and [`Warning::InvalidBox`]
    /// (key `MediaBox`) is raised, once.
    ///
    /// # Errors
    /// As [`Page::media_box`], [`Page::rotate`] and [`Page::user_unit`].
    ///
    /// [ADR 0027]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0027-coordinates-units-and-page-indexing.md
    ///
    /// Added in 0.2.0.
    pub fn frame(&self) -> Result<PageFrame> {
        memo(self.cache().map(|c| &c.frame), || self.read_frame())
    }

    fn read_frame(&self) -> Result<PageFrame> {
        let Boxes { media, crop } = self.boxes()?;
        let rotate = self.rotate()?;
        let unit = self.user_unit()?;
        let reference = crop
            .filter(UserSpaceRect::has_area)
            .or(media.filter(UserSpaceRect::has_area));
        let frame = if let Some(reference) = reference {
            PageFrame::new(reference, rotate, unit)
        } else {
            self.doc().warn(Warning::InvalidBox {
                object: self.object(),
                page: self.page_number(),
                key: "MediaBox",
            })?;
            PageFrame::new(LETTER, rotate, unit).with_letter_fallback()
        };
        Ok(frame)
    }

    /// `/Resources`, own or inherited, resolved.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn resources(&self) -> Option<&'p Dict> {
        self.cos.resources_dict()
    }

    /// The references in `/Contents` (one stream, or an array of streams, possibly itself
    /// indirect). Direct elements and anything unreadable are left out.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`].
    ///
    /// Added in 0.2.0.
    pub fn contents(&self) -> Result<Vec<ObjRef>> {
        self.refs("Contents", true)
    }

    /// The references in `/Annots` (an array, possibly indirect). Direct annotation
    /// dictionaries are left out (annotation views arrive with the editor rounds).
    ///
    /// # Errors
    /// As [`Page::contents`].
    ///
    /// Added in 0.2.0.
    pub fn annots(&self) -> Result<Vec<ObjRef>> {
        self.refs("Annots", false)
    }

    fn refs(&self, key: &str, single_ok: bool) -> Result<Vec<ObjRef>> {
        let Some(value) = self.cos.dict.get(key) else {
            return Ok(Vec::new());
        };
        let Some(resolved) = self.doc().read(value)? else {
            return Ok(Vec::new());
        };
        Ok(match (&*resolved, value) {
            (Object::Array(items), _) => items.iter().filter_map(Object::as_ref).collect(),
            (Object::Null, _) => Vec::new(),
            (_, Object::Ref(r)) if single_ok => vec![*r],
            _ => Vec::new(),
        })
    }

    /// The page label (§12.4.2), when the document has `/PageLabels`.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::Strict`] in strict mode for a malformed label entry; errors
    /// reading the catalog.
    ///
    /// Added in 0.2.0.
    pub fn label(&self) -> Result<Option<String>> {
        Ok(self.pages.labels()?.label(self.index))
    }
}

/// `/F` bits that hide an annotation: Hidden (2) and `NoView` (6), §12.5.3.
pub(crate) const HIDDEN_ANNOT_FLAGS: i64 = (1 << 1) | (1 << 5);

/// `obj` as a rectangle of four numbers, tolerantly; `None` when it is anything else.
pub(crate) fn read_rect(doc: &Document, obj: &Object) -> Result<Option<UserSpaceRect>> {
    let Some(arr) = doc.read(obj)? else {
        return Ok(None);
    };
    let Some(items @ [_, _, _, _]) = arr.as_array() else {
        return Ok(None);
    };
    let mut out = [0.0; 4];
    for (slot, item) in out.iter_mut().zip(items) {
        match number(doc, item)? {
            Some(value) => *slot = value,
            None => return Ok(None),
        }
    }
    let [x0, y0, x1, y1] = out;
    Ok(Some(UserSpaceRect::from_corners(x0, y0, x1, y1)))
}

/// A finite number, tolerantly.
pub(crate) fn number(doc: &Document, obj: &Object) -> Result<Option<f64>> {
    Ok(doc.read(obj)?.and_then(|n| n.as_f64()).filter(|n| n.is_finite()))
}