Skip to main content

pdfrum_edit/
pages.rs

1//! Page-tree edits that are not imports: a blank page, deleting pages, and
2//! the per-page attributes a save carries — rotation and the boxes.
3//!
4//! Every function works on the page tree as the base document has it, so
5//! page indices are the base document's numbering throughout; a caller who
6//! deletes and then adds does both against that numbering, and the writer
7//! resolves the edits together.
8
9use pdfrum_common::PageIndex;
10use pdfrum_object::{Array, Dict, Name, ObjRef, Object, Resolve, names};
11
12use crate::doc::EditDoc;
13use crate::error::Error;
14use crate::import::{PageRange, init_dest, insert_into_tree};
15
16/// One of the five page boxes (ISO 32000-1 §14.11.2).
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum PageBox {
19    /// `/MediaBox`.
20    Media,
21    /// `/CropBox`.
22    Crop,
23    /// `/BleedBox`.
24    Bleed,
25    /// `/TrimBox`.
26    Trim,
27    /// `/ArtBox`.
28    Art,
29}
30
31impl PageBox {
32    fn key(self) -> &'static Name {
33        match self {
34            Self::Media => names::MEDIA_BOX,
35            Self::Crop => names::CROP_BOX,
36            Self::Bleed => names::BLEED_BOX,
37            Self::Trim => names::TRIM_BOX,
38            Self::Art => names::ART_BOX,
39        }
40    }
41}
42
43/// Add an empty page of `width` by `height` points at index `at` (past the
44/// end appends), and return its reference.
45///
46/// The page carries only `/Type`, `/Parent` and `/MediaBox`; it has no
47/// contents and no resources until a caller draws on it.
48///
49/// # Errors
50///
51/// [`Error::NoDestinationCatalog`] when the document has no catalog to hang
52/// a page tree on.
53pub fn add_blank_page(
54    dest: &mut EditDoc<'_>,
55    width: f32,
56    height: f32,
57    at: impl Into<PageIndex>,
58) -> Result<ObjRef, Error> {
59    let at = u32::from(at.into());
60    let pages_node = init_dest(dest)?;
61    let page = Dict::from_pairs([
62        (names::TYPE.clone(), Object::Name(names::PAGE.clone())),
63        (
64            names::PARENT.clone(),
65            Object::Ref(ObjRef::new(pages_node, 0)),
66        ),
67        (
68            names::MEDIA_BOX.clone(),
69            rect_object([0.0, 0.0, width, height]),
70        ),
71    ]);
72    let created = dest.add(Object::Dict(page));
73    insert_into_tree(dest, pages_node, &[created], at);
74    Ok(created)
75}
76
77/// Delete the pages `range` names, by the base document's numbering.
78///
79/// Each page is unlinked from its parent's `/Kids` and every `/Count` up the
80/// chain is decremented; the page object itself is left for the writer's
81/// garbage collection. A duplicate index deletes once.
82///
83/// # Errors
84///
85/// [`Error::PageIndexOutOfRange`] when the range names a page the document
86/// does not have; the document is untouched on that.
87pub fn delete_pages(dest: &mut EditDoc<'_>, range: &PageRange) -> Result<(), Error> {
88    let mut refs = Vec::with_capacity(range.indices().len());
89    for &index in range.indices() {
90        let page = dest
91            .base()
92            .page(index)
93            .map_err(|_| Error::PageIndexOutOfRange(index))?;
94        let Some(reference) = page.reference else {
95            // A page written inline in its parent's `/Kids` has no reference
96            // to unlink by; the oracle cannot delete one either.
97            return Err(Error::PageIndexOutOfRange(index));
98        };
99        if !refs.contains(&reference) {
100            refs.push(reference);
101        }
102    }
103    for reference in refs {
104        unlink(dest, reference);
105    }
106    Ok(())
107}
108
109/// Unlink one page from its parent and decrement the counts above it.
110fn unlink(dest: &mut EditDoc<'_>, page: ObjRef) {
111    let Some(page_dict) = dict_of(dest, page) else {
112        return;
113    };
114    let Some(Object::Ref(parent_ref)) = page_dict.raw(names::PARENT).cloned() else {
115        return;
116    };
117    let Some(mut parent) = dict_of(dest, parent_ref) else {
118        return;
119    };
120    let kids: Array = parent
121        .raw(names::KIDS)
122        .and_then(Object::as_array)
123        .map(|kids| {
124            kids.iter()
125                .filter(|kid| !matches!(kid, Object::Ref(r) if *r == page))
126                .cloned()
127                .collect()
128        })
129        .unwrap_or_default();
130    parent.insert(names::KIDS.clone(), Object::Array(kids));
131    dest.replace(parent_ref, Object::Dict(parent));
132    decrement_counts(dest, parent_ref);
133}
134
135/// Take one off `/Count` on `node` and every ancestor.
136fn decrement_counts(dest: &mut EditDoc<'_>, mut node_ref: ObjRef) {
137    // A cycle in `/Parent` would loop forever; the tree's depth bounds it.
138    for _ in 0..64 {
139        let Some(mut node) = dict_of(dest, node_ref) else {
140            return;
141        };
142        let count = node
143            .raw(names::COUNT)
144            .and_then(Object::as_int)
145            .unwrap_or(0)
146            .saturating_sub(1)
147            .max(0);
148        node.insert(names::COUNT.clone(), Object::Int(count));
149        let parent = node.raw(names::PARENT).cloned();
150        dest.replace(node_ref, Object::Dict(node));
151        match parent {
152            Some(Object::Ref(parent_ref)) => node_ref = parent_ref,
153            _ => return,
154        }
155    }
156}
157
158/// Set a page's `/Rotate`. `degrees` is normalized to a multiple of 90; a
159/// value that is not one is rounded to the nearest.
160///
161/// # Errors
162///
163/// [`Error::PageIndexOutOfRange`] when there is no such page or the page is
164/// written inline.
165pub fn set_page_rotation(
166    dest: &mut EditDoc<'_>,
167    index: impl Into<PageIndex>,
168    degrees: i32,
169) -> Result<(), Error> {
170    let index = index.into();
171    // Nearest multiple of 90, then modulo a full turn: 45 rounds up, -90
172    // is 270.
173    let quarter_turns =
174        (degrees.div_euclid(90) + i32::from(degrees.rem_euclid(90) >= 45)).rem_euclid(4);
175    let quarter_turns = i64::from(quarter_turns);
176    edit_page(dest, index, |page| {
177        page.insert(names::ROTATE.clone(), Object::Int(quarter_turns * 90));
178    })
179}
180
181/// Set one of a page's boxes.
182///
183/// # Errors
184///
185/// As [`set_page_rotation`].
186pub fn set_page_box(
187    dest: &mut EditDoc<'_>,
188    index: impl Into<PageIndex>,
189    which: PageBox,
190    rect: [f32; 4],
191) -> Result<(), Error> {
192    let index = index.into();
193    edit_page(dest, index, |page| {
194        page.insert(which.key().clone(), rect_object(rect));
195    })
196}
197
198/// Fetch a page's dictionary as the edits leave it, change it, write it back.
199fn edit_page(
200    dest: &mut EditDoc<'_>,
201    index: PageIndex,
202    change: impl FnOnce(&mut Dict),
203) -> Result<(), Error> {
204    let page = dest
205        .base()
206        .page(index)
207        .map_err(|_| Error::PageIndexOutOfRange(index))?;
208    let Some(reference) = page.reference else {
209        return Err(Error::PageIndexOutOfRange(index));
210    };
211    let mut dict = dict_of(dest, reference).unwrap_or(page.dict);
212    change(&mut dict);
213    dest.replace(reference, Object::Dict(dict));
214    Ok(())
215}
216
217/// A dictionary as the edits currently leave it.
218fn dict_of(dest: &EditDoc<'_>, reference: ObjRef) -> Option<Dict> {
219    dest.fetch(reference)
220        .ok()
221        .and_then(|object| object.as_dict().cloned())
222}
223
224fn rect_object(rect: [f32; 4]) -> Object {
225    Object::Array(rect.into_iter().map(Object::Real).collect())
226}