laminapdf-model 0.4.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
//! Editing the page tree (ISO 32000-2 §7.7.3): inserting, removing and moving pages through
//! the overlay, with every `/Count` (§7.7.3.2), `/Parent` and inherited attribute
//! (§7.7.3.4) kept right.

mod load;
mod write;

use std::collections::{BTreeMap, BTreeSet};

use laminapdf_cos::{Dict, ObjRef, Object};

use crate::document::Document;
use crate::id::PageId;
use load::{Kid, Slot, Tree, overlay};

/// Where pages go in the page list. Positions name pages, never indices, since indices shift
/// while an edit runs.
///
/// Added in 0.2.0.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PagePosition {
    /// Before the first page.
    Start,
    /// After the last page.
    End,
    /// Just before this page.
    Before(PageId),
    /// Just after this page.
    After(PageId),
}

/// Why a page-tree edit failed.
///
/// Added in 0.2.0.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PageTreeError {
    /// Reading or writing the document failed (as [`laminapdf_cos::Error`]). The page tree
    /// root must be an indirect `/Pages` dictionary.
    #[error(transparent)]
    Cos(#[from] laminapdf_cos::Error),
    /// No page with this ID is in the page tree.
    #[error("no page {0} in the page tree")]
    UnknownPage(PageId),
    /// The page to insert is already in the page tree.
    #[error("page {0} is already in the page tree")]
    AlreadyInTree(PageId),
    /// The object to insert is not a page dictionary.
    #[error("object {0} is not a page dictionary")]
    NotAPage(ObjRef),
}

/// An editor of the page tree, over the document's overlay ([`Document::edit_page_tree`]).
///
/// It reads the tree once and edits a copy in memory; [`PageTreeEditor::finish`] writes the
/// nodes and pages that changed. Dropping it without `finish` changes nothing.
///
/// * **Shape.** Small edits keep the tree's shape: a page goes into the node that holds its
///   neighbour, and nodes left empty are removed. The tree is rebuilt balanced
///   ([`PageTreeEditor::FAN_OUT`] kids per node) only when, after the edits, it is deeper than
///   [`PageTreeEditor::MAX_DEPTH`] or a node the edits touched holds more than
///   [`PageTreeEditor::MAX_KIDS`] kids, and only when every kid is an indirect page or node
///   (a direct kid's inheritance couldn't be kept).
/// * **Inherited attributes.** A page that moves, and every page when the tree is rebuilt,
///   keeps what it showed: an inherited `/Resources`, `/MediaBox`, `/CropBox` or `/Rotate`
///   that its new ancestors don't give is written on the page itself, and one they give but it
///   didn't have is overridden with the neutral value (`/Rotate 0`, empty `/Resources`, a
///   `/CropBox` equal to its media box). An inserted page shows what its own dictionary says
///   in the same way; a `/MediaBox` it lacks is inherited.
/// * **Counts and parents.** Every touched node's `/Count` and `/Kids`, and the `/Parent` of
///   every page and node that moved, are written.
/// * **Pages listed twice.** A page dictionary listed in two places can't have two parents:
///   `finish` copies it to a new object for every listing after the first, raising
///   [`Warning::InvalidEntry`](laminapdf_cos::Warning::InvalidEntry) (key `Kids`) on the
///   node that lists the copy. An ID names the first listing in page order.
///
/// ```
/// use laminapdf_model::{Document, OpenOptions, PagePosition};
/// # use laminapdf_cos::{Dict, Object};
/// # use laminapdf_save::test_support::Writer;
/// # let mut w = Writer::new(1, 7);
/// # let pages = w.reserve();
/// # let mut kids = Vec::new();
/// # for _ in 0..3 {
/// #     kids.push(Object::Ref(w.add([("Type", Object::name("Page")), ("Parent", pages.into())].into_iter().collect::<Dict>())));
/// # }
/// # let media_box = Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]);
/// # w.set(pages, [("Type", Object::name("Pages")), ("Kids", kids.into()), ("Count", 3.into()), ("MediaBox", media_box)].into_iter().collect::<Dict>());
/// # let root = w.add([("Type", Object::name("Catalog")), ("Pages", pages.into())].into_iter().collect::<Dict>());
/// # let bytes = w.finish(&[("Root", root)].into_iter().collect())?;
/// let mut doc = Document::open(bytes, OpenOptions::default())?;
/// let ids: Vec<_> = doc.pages()?.iter().map(|p| p.id().clone()).collect();
/// let mut editor = doc.edit_page_tree()?;
/// editor.move_pages(&ids[2..], &PagePosition::Start)?;
/// editor.finish()?;
/// let order: Vec<_> = doc.pages()?.iter().map(|p| p.id().to_string()).collect();
/// assert_eq!(order, ["p4.0", "p2.0", "p3.0"]);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Added in 0.2.0.
#[derive(Debug)]
#[must_use = "the changes are written by `finish`"]
pub struct PageTreeEditor<'d> {
    doc: &'d mut Document,
    tree: Tree,
}

impl Document {
    /// An editor of the page tree ([`PageTreeEditor`]), reading the tree as it is now.
    ///
    /// # Errors
    /// [`PageTreeError::Cos`] when the catalog's `/Pages` is not an indirect dictionary, when
    /// a node is reached twice ([`laminapdf_cos::Error::ReferenceCycle`]) or reading fails.
    ///
    /// Added in 0.2.0.
    pub fn edit_page_tree(&mut self) -> Result<PageTreeEditor<'_>, PageTreeError> {
        let tree = Tree::load(self)?;
        Ok(PageTreeEditor { doc: self, tree })
    }
}

impl PageTreeEditor<'_> {
    /// Past this depth the tree is rebuilt. Writers' trees are a few levels deep (a balanced
    /// tree of [`PageTreeEditor::FAN_OUT`] kids holds a million pages in four); a deeper one
    /// is a chain left by appends, which costs a reader a step per level for every page.
    ///
    /// Added in 0.2.0.
    pub const MAX_DEPTH: usize = 32;
    /// Past this many kids, a node the edits touched gets the tree rebuilt. Writers that put
    /// every page under the root give files of a thousand pages one flat node, which readers
    /// take well, so only nodes larger than that count as too wide.
    ///
    /// Added in 0.2.0.
    pub const MAX_KIDS: usize = 1024;
    /// The kids per node of a rebuilt tree: shallow, and small enough that rewriting one
    /// node's `/Kids` stays cheap.
    ///
    /// Added in 0.2.0.
    pub const FAN_OUT: usize = 32;

    /// The pages in order, as their IDs (a page listed twice appears twice).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn page_ids(&self) -> Vec<PageId> {
        self.tree
            .order()
            .into_iter()
            .filter_map(|s| self.tree.slots.get(s))
            .map(|s| PageId::object(s.r))
            .collect()
    }

    /// The document being edited, for reading.
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn document(&self) -> &Document {
        self.doc
    }

    /// Inserts the page object `page` (a page dictionary already in the document, not in the
    /// page tree) at `at`, and returns its ID. Its `/Parent` is written by `finish`. A page
    /// dictionary has `/Type /Page`; one without `/Type` is taken when it has no `/Kids` and
    /// has a `/MediaBox` or `/Contents`, as some writers leave the type out.
    ///
    /// # Errors
    /// [`PageTreeError::NotAPage`] when `page` is not a page dictionary,
    /// [`PageTreeError::AlreadyInTree`], [`PageTreeError::UnknownPage`] for an `at` that names
    /// no page, and reading errors.
    ///
    /// Added in 0.2.0.
    pub fn insert(&mut self, page: ObjRef, at: &PagePosition) -> Result<PageId, PageTreeError> {
        let index = self.index();
        if index.first.contains_key(&page) {
            return Err(PageTreeError::AlreadyInTree(PageId::object(page)));
        }
        let dict = self
            .doc
            .read(&Object::Ref(page))?
            .and_then(|o| o.as_dict().cloned())
            .filter(is_page_dict)
            .ok_or(PageTreeError::NotAPage(page))?;
        let place = self.place(&index, at, &BTreeSet::new())?;
        self.put(page, dict, place)
    }

    /// Inserts a new page made from `dict` (given `/Type /Page`) at `at`, as
    /// [`PageTreeEditor::insert`] does. The page's object number is reserved now, for its ID;
    /// the object is written by `finish`, so dropping the editor writes nothing.
    ///
    /// # Errors
    /// [`PageTreeError::UnknownPage`] for an `at` that names no page; the overlay's error when
    /// no object number is left.
    ///
    /// Added in 0.2.0.
    pub fn insert_new(&mut self, mut dict: Dict, at: &PagePosition) -> Result<PageId, PageTreeError> {
        let index = self.index();
        let place = self.place(&index, at, &BTreeSet::new())?;
        dict.insert("Type", Object::name("Page"));
        let page = self.doc.reserve_number()?;
        self.put(page, dict, place)
    }

    /// Puts page `page` (dictionary `dict`) at `place`.
    fn put(&mut self, page: ObjRef, dict: Dict, (node, index): (usize, usize)) -> Result<PageId, PageTreeError> {
        // A page taken out by this editor comes back showing what it showed before.
        let removed = self.tree.slots.iter().position(|s| s.r == page && s.parent.is_none());
        let slot = if let Some(slot) = removed {
            slot
        } else {
            let desired = overlay(self.doc, &load::Attrs::default(), &dict)?;
            self.tree.slots.push(Slot {
                r: page,
                dict,
                desired,
                parent: None,
                moved: true,
            });
            self.tree.slots.len() - 1
        };
        if let Some(s) = self.tree.slots.get_mut(slot) {
            s.parent = Some(node);
            s.moved = true;
        }
        self.attach(node, index, &[slot]);
        Ok(PageId::object(page))
    }

    /// Takes `page` out of the page tree and returns its object, which stays in the document
    /// (delete it, or keep it for undo). Nodes left empty are removed by `finish`.
    ///
    /// # Errors
    /// [`PageTreeError::UnknownPage`].
    ///
    /// Added in 0.2.0.
    pub fn remove(&mut self, page: &PageId) -> Result<ObjRef, PageTreeError> {
        let slot = self
            .index()
            .find(page)
            .ok_or_else(|| PageTreeError::UnknownPage(page.clone()))?;
        self.detach(slot);
        self.tree
            .slots
            .get(slot)
            .map(|s| s.r)
            .ok_or_else(|| PageTreeError::UnknownPage(page.clone()))
    }

    /// Moves `pages` to `to`, keeping their order among themselves (the order given) and their
    /// IDs. An anchor that is itself moved is replaced by the nearest page that stays: the next
    /// one for [`PagePosition::Before`], the previous one for [`PagePosition::After`].
    ///
    /// # Errors
    /// [`PageTreeError::UnknownPage`] for a page or anchor not in the tree.
    ///
    /// Added in 0.2.0.
    pub fn move_pages(&mut self, pages: &[PageId], to: &PagePosition) -> Result<(), PageTreeError> {
        let lookup = self.index();
        let mut slots = Vec::with_capacity(pages.len());
        let mut moving = BTreeSet::new();
        for id in pages {
            let slot = lookup.find(id).ok_or_else(|| PageTreeError::UnknownPage(id.clone()))?;
            if moving.insert(slot) {
                slots.push(slot);
            }
        }
        let (node, index) = self.place(&lookup, to, &moving)?;
        // The anchor stays, so its node and index hold once the moved pages are out of the way;
        // only pages before it in the same node shift the index.
        let shift = self.tree.nodes.get(node).map_or(0, |n| {
            n.kids
                .iter()
                .take(index)
                .filter(|k| matches!(k, Kid::Page(s) if moving.contains(s)))
                .count()
        });
        for &slot in &slots {
            self.detach(slot);
        }
        for &slot in &slots {
            if let Some(s) = self.tree.slots.get_mut(slot) {
                s.parent = Some(node);
                s.moved = true;
            }
        }
        self.attach(node, index.saturating_sub(shift), &slots);
        Ok(())
    }

    /// Writes the changes: the touched nodes, the pages that moved or were inserted, copies
    /// of pages listed twice, and the tree rebuilt when it passes a threshold.
    ///
    /// # Errors
    /// Errors of the overlay; in strict mode, the warning for a page listed twice.
    ///
    /// Added in 0.2.0.
    pub fn finish(self) -> Result<(), PageTreeError> {
        Ok(write::finish(self.doc, self.tree)?)
    }

    /// The page order and where each page sits in it, built once per edit.
    fn index(&self) -> Index {
        let order = self.tree.order();
        let mut first = BTreeMap::new();
        let mut position = BTreeMap::new();
        for (at, &slot) in order.iter().enumerate() {
            position.insert(slot, at);
            if let Some(s) = self.tree.slots.get(slot) {
                first.entry(s.r).or_insert(slot);
            }
        }
        Index { order, first, position }
    }

    /// The node and kid index where `at` puts pages, skipping anchors in `moving`.
    fn place(
        &self,
        index: &Index,
        at: &PagePosition,
        moving: &BTreeSet<usize>,
    ) -> Result<(usize, usize), PageTreeError> {
        let all = &index.order;
        let staying = |s: &&usize| !moving.contains(*s);
        let anchor = |id: &PageId| -> Result<usize, PageTreeError> {
            let slot = index.find(id).ok_or_else(|| PageTreeError::UnknownPage(id.clone()))?;
            Ok(index.position.get(&slot).copied().unwrap_or(0))
        };
        // An anchor being moved gives way to the nearest page that stays.
        let (slot, after) = match at {
            PagePosition::Start => (all.iter().find(staying).copied(), false),
            PagePosition::End => (all.iter().rev().find(staying).copied(), true),
            PagePosition::Before(id) => {
                let at = anchor(id)?;
                match all.iter().skip(at).find(staying) {
                    Some(&s) => (Some(s), false),
                    None => (all.iter().rev().find(staying).copied(), true),
                }
            }
            PagePosition::After(id) => {
                let at = anchor(id)?;
                match all.iter().take(at + 1).rev().find(staying) {
                    Some(&s) => (Some(s), true),
                    None => (all.iter().find(staying).copied(), false),
                }
            }
        };
        let Some(slot) = slot else {
            // No page stays: the root's kids, at the start or the end.
            let len = self.tree.nodes.first().map_or(0, |n| n.kids.len());
            return Ok((0, if matches!(at, PagePosition::Start) { 0 } else { len }));
        };
        let node = self.tree.slots.get(slot).and_then(|s| s.parent).unwrap_or(0);
        let index = self
            .tree
            .nodes
            .get(node)
            .and_then(|n| n.kids.iter().position(|k| *k == Kid::Page(slot)))
            .unwrap_or(0);
        Ok((node, index + usize::from(after)))
    }

    /// Takes slot `slot` out of its node's `/Kids`.
    fn detach(&mut self, slot: usize) {
        let Some(parent) = self.tree.slots.get_mut(slot).and_then(|s| s.parent.take()) else {
            return;
        };
        if let Some(node) = self.tree.nodes.get_mut(parent) {
            node.kids.retain(|k| *k != Kid::Page(slot));
            node.touched = true;
        }
    }

    /// Puts `slots` into `node`'s `/Kids` at `index`, in order.
    fn attach(&mut self, node: usize, index: usize, slots: &[usize]) {
        if let Some(n) = self.tree.nodes.get_mut(node) {
            let index = index.min(n.kids.len());
            n.kids.splice(index..index, slots.iter().map(|&s| Kid::Page(s)));
            n.touched = true;
        }
    }
}

/// The page order of the tree as it is, with lookups, so one edit walks the tree once.
struct Index {
    /// The slots in page order.
    order: Vec<usize>,
    /// Each page object's first listing.
    first: BTreeMap<ObjRef, usize>,
    /// Each slot's place in `order`.
    position: BTreeMap<usize, usize>,
}

impl Index {
    /// The slot of `id`: its first listing in page order.
    fn find(&self, id: &PageId) -> Option<usize> {
        self.first.get(&id.as_lamina_id().obj_ref()?).copied()
    }
}

/// Whether `dict` is a page dictionary to insert: `/Type /Page`, or (some writers leave the
/// type out) no `/Type`, no `/Kids`, and a `/MediaBox` or `/Contents`.
fn is_page_dict(dict: &Dict) -> bool {
    match dict.get_name("Type") {
        Some(t) => t == b"Page",
        None => !dict.contains_key("Kids") && (dict.contains_key("MediaBox") || dict.contains_key("Contents")),
    }
}