Skip to main content

pdfboss_write/
update.rs

1//! Incremental updates to an existing file (ISO 32000-1 §7.5.6): the base
2//! bytes stay in place and an update section appends new and replaced
3//! objects plus a cross-reference section chained to the base's by `/Prev`,
4//! in the base's own cross-reference style.
5
6use std::io::Write;
7
8use flate2::write::ZlibEncoder;
9use flate2::Compression;
10use pdfboss_core::crypt::Sha256;
11use pdfboss_core::object::decode_text_string;
12use pdfboss_core::xref::{parse_section_at, startxref};
13use pdfboss_core::{Dict, Document, FastMap, Name, ObjRef, Object, Page, Stream, XrefKind};
14
15use crate::error::{Error, Result};
16use crate::importer::{rect_array, Importer};
17use crate::pdf::{text_string, Date, Metadata};
18use crate::ser::{serialize_dict, serialize_object};
19use crate::writer::{WriteOptions, Writer, XrefStyle};
20
21/// The first name tried for the resource every page draws the overlay
22/// form under. [`free_form_name`] falls back to `PdfbossWatermark2`,
23/// `PdfbossWatermark3`, ... when this one is already taken.
24const FORM_NAME: &str = "PdfbossWatermark";
25
26/// The first name in the series `PdfbossWatermark`, `PdfbossWatermark2`,
27/// ... whose `/XObject` entry is free in every marked page of `pages`.
28/// Overlaying a file that already carries a mark under an earlier name in
29/// the series draws its own form under the next free one instead of
30/// replacing the earlier entry and leaving its `Do` operators pointing at
31/// the new form. `pages` is fetched once by the caller and reused for the
32/// mark loop that follows: [`Document::page`] materializes a page's
33/// effective resources on every call, so probing by re-fetching would
34/// double that cost across the whole document.
35fn free_form_name(base: &Document, pages: &[Page]) -> Result<String> {
36    let mut candidate = FORM_NAME.to_string();
37    let mut next = 2;
38    while xobject_name_taken(base, pages, &candidate)? {
39        candidate = format!("{FORM_NAME}{next}");
40        next += 1;
41    }
42    Ok(candidate)
43}
44
45/// Whether any page in `pages` that is marked (has an [`ObjRef`] of its
46/// own) already carries an `/XObject` resource named `candidate`,
47/// resolving each page's effective resources the same way
48/// [`marked_page_dict`] and [`watermark_placed`] do before adding their
49/// own entry. A page inlined into `/Kids`, having no object of its own,
50/// is never marked, so it is skipped: only a marked page's `/XObject`
51/// dictionary can ever collide with the name this picks.
52fn xobject_name_taken(base: &Document, pages: &[Page], candidate: &str) -> Result<bool> {
53    for page in pages {
54        if page.object_ref().is_none() {
55            continue;
56        }
57        let Some(existing) = page.resources.get("XObject") else {
58            continue;
59        };
60        let existing = base.resolve(existing).map_err(core_error)?;
61        let Some(dict) = existing.as_dict() else {
62            continue;
63        };
64        if dict.get(candidate).is_some() {
65            return Ok(true);
66        }
67    }
68    Ok(false)
69}
70
71/// Every page of `base`, in order, fetched once: shared by the name probe
72/// and the mark loop that follows it, so [`Document::page`] materializes
73/// each page's effective resources only once per watermark construction
74/// rather than once for the probe and again for marking.
75fn fetch_pages(base: &Document) -> Result<Vec<Page>> {
76    crate::assemble::fetch_page_run(base, 0..base.page_count())
77}
78
79/// The content wrappers for one marked page: what precedes the page's own
80/// content and what follows it. Drawing over paints the form after the
81/// content; drawing under paints it first, so the content covers it.
82fn wrapper_streams(form_name: &str, under: bool) -> (Vec<u8>, Vec<u8>) {
83    if under {
84        return (
85            format!("q /{form_name} Do Q\nq\n").into_bytes(),
86            b"Q\n".to_vec(),
87        );
88    }
89    (
90        b"q\n".to_vec(),
91        format!("Q\nq /{form_name} Do Q\n").into_bytes(),
92    )
93}
94
95/// Shared by [`watermark_with`] and [`watermark_under_with`]: writes a fresh
96/// file through the [`Writer`] under `options` instead of appending an
97/// update, wrapping each page's content per [`wrapper_streams`].
98fn watermark_rewrite_placed(
99    base: &Document,
100    overlay: &Document,
101    options: WriteOptions,
102    under: bool,
103) -> Result<Vec<u8>> {
104    let pages = fetch_pages(base)?;
105    let form_name = free_form_name(base, &pages)?;
106    let mut writer = Writer::new(options);
107    let (prefix_bytes, suffix_bytes) = wrapper_streams(&form_name, under);
108    let prefix = writer.put_stream_raw(Dict::new(), prefix_bytes);
109    let suffix = writer.put_stream_raw(Dict::new(), suffix_bytes);
110    let form = overlay_form(&mut writer, overlay)?;
111
112    let trailer = &base.xref().trailer;
113    let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
114    let mut importer = Importer::new(&mut writer, base)?;
115    let new_root = importer.reference(root);
116    let new_info = trailer.get_ref("Info").map(|info| importer.reference(info));
117    for page in &pages {
118        let Some(page_ref) = page.object_ref() else {
119            continue;
120        };
121        let dict = marked_page_dict(&mut importer, base, page, form, prefix, suffix, &form_name)?;
122        importer.substitute(page_ref, dict);
123    }
124    importer.finish()?;
125    if let Some(new_info) = new_info {
126        writer.set_info(new_info);
127    }
128    writer.finish(new_root)
129}
130
131/// Like [`watermark`], but writes a fresh file through the [`Writer`] under
132/// `options` instead of appending an update: every object the base's
133/// catalog reaches is copied over, uncompressed streams are compressed when
134/// `options.compress` is set, and unreachable objects and earlier sections
135/// are left behind, so the result is usually smaller than the base. Both
136/// `base` and `overlay` are refused when locked, through
137/// [`crate::importer::Importer::new`]; a password-opened encrypted `base`
138/// or `overlay` copies its plaintext content across like any unencrypted
139/// source.
140///
141/// Placement is absolute and unscaled, and an unbalanced graphics state in
142/// a page's own content can clip or restyle the overlay, for the same
143/// reasons documented on [`watermark`].
144pub fn watermark_with(
145    base: &Document,
146    overlay: &Document,
147    options: WriteOptions,
148) -> Result<Vec<u8>> {
149    watermark_rewrite_placed(base, overlay, options, false)
150}
151
152/// Like [`watermark_with`], but draws the overlay beneath each page's
153/// content: the form paints first and the page's own content paints over
154/// it, so opaque content covers the overlay instead of the other way
155/// round.
156///
157/// Placement is absolute and unscaled, for the same reason documented on
158/// [`watermark`]. Painting the form first means no page state can reach
159/// it, so the unbalanced-graphics-state risk documented on [`watermark`]
160/// does not apply to this placement.
161pub fn watermark_under_with(
162    base: &Document,
163    overlay: &Document,
164    options: WriteOptions,
165) -> Result<Vec<u8>> {
166    watermark_rewrite_placed(base, overlay, options, true)
167}
168
169/// The marked dictionary for `page`, already fetched from `base` by the
170/// caller: its own dictionary translated into the target with `/Type
171/// /Page` guaranteed, its effective resources gaining the overlay form
172/// under `form_name`, and its content wrapped in `prefix` and `suffix`.
173fn marked_page_dict(
174    importer: &mut Importer,
175    base: &Document,
176    page: &Page,
177    form: ObjRef,
178    prefix: ObjRef,
179    suffix: ObjRef,
180    form_name: &str,
181) -> Result<Object> {
182    let mut dict = importer.copy_dict(page.dict())?;
183    let mut resources = importer.copy_dict(&page.resources)?;
184    let mut xobjects = match page.resources.get("XObject") {
185        Some(existing) => {
186            let existing = base.resolve(existing).map_err(core_error)?;
187            match existing.as_dict() {
188                Some(d) => importer.copy_dict(d)?,
189                None => Dict::new(),
190            }
191        }
192        None => Dict::new(),
193    };
194    xobjects.insert(name(form_name), Object::Ref(form));
195    resources.insert(name("XObject"), Object::Dict(xobjects));
196    dict.insert(name("Resources"), Object::Dict(resources));
197    dict.insert(name("Type"), Object::Name(name("Page")));
198    let mut contents = vec![Object::Ref(prefix)];
199    match page.dict().get("Contents") {
200        Some(Object::Array(items)) => {
201            for item in items {
202                contents.push(importer.copy(item)?);
203            }
204        }
205        Some(Object::Ref(r)) => match base.get(*r).map_err(core_error)? {
206            Object::Array(items) => {
207                for item in &items {
208                    contents.push(importer.copy(item)?);
209                }
210            }
211            _ => contents.push(Object::Ref(importer.reference(*r))),
212        },
213        _ => {}
214    }
215    contents.push(Object::Ref(suffix));
216    dict.insert(name("Contents"), Object::Array(contents));
217    Ok(Object::Dict(dict))
218}
219
220/// The overlay's first page as a form XObject, filled directly into
221/// `writer`: its media box as the bounding box, its decoded content
222/// deflated, its resources imported from `overlay`.
223fn overlay_form(writer: &mut Writer, overlay: &Document) -> Result<ObjRef> {
224    let page = overlay.page(0).map_err(core_error)?;
225    let content = page.content(overlay).map_err(core_error)?;
226    let resources = {
227        let mut importer = Importer::new(writer, overlay)?;
228        let resources = importer.copy_dict(&page.resources)?;
229        importer.finish()?;
230        resources
231    };
232    let mut dict = Dict::new();
233    dict.insert(name("Type"), Object::Name(name("XObject")));
234    dict.insert(name("Subtype"), Object::Name(name("Form")));
235    dict.insert(name("FormType"), Object::Int(1));
236    dict.insert(name("BBox"), rect_array(page.media_box));
237    dict.insert(name("Resources"), Object::Dict(resources));
238    dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
239    let form = writer.reserve();
240    writer.fill(
241        form,
242        Object::Stream(Stream {
243            dict,
244            data: deflate(&content)?,
245        }),
246    )?;
247    Ok(form)
248}
249
250/// Shared by [`watermark`] and [`watermark_under`]: draws the first page of
251/// `overlay` over (or, when `under` is set, beneath) every page of `base`,
252/// returning `base`'s bytes followed by an incremental update: the overlay
253/// page as one form XObject (its resources copied into the base's object
254/// space), and each page's dictionary rewritten with that form in its
255/// resources, under the first free name [`free_form_name`] finds, and its
256/// content wrapped per [`wrapper_streams`]. Pages inlined directly into
257/// `/Kids`, having no object of their own, are left as they are. An
258/// encrypted `base` is refused: its new strings and streams would need
259/// encrypting too. An encrypted `overlay` is refused as well: its
260/// decrypted content would otherwise copy across into the plain update
261/// section.
262fn watermark_placed(base: &Document, overlay: &Document, under: bool) -> Result<Vec<u8>> {
263    let pages = fetch_pages(base)?;
264    let form_name = free_form_name(base, &pages)?;
265    let mut update = Update::new(base)?;
266    let form = update.overlay.import_form(overlay)?;
267    let (prefix_bytes, suffix_bytes) = wrapper_streams(&form_name, under);
268    let prefix = update
269        .overlay
270        .put(Object::Stream(plain_stream(prefix_bytes)));
271    let suffix = update
272        .overlay
273        .put(Object::Stream(plain_stream(suffix_bytes)));
274    for page in &pages {
275        let Some(page_ref) = page.object_ref() else {
276            continue;
277        };
278        let mut dict = page.dict().clone();
279        let mut resources = page.resources.clone();
280        let mut xobjects = match resources.get("XObject") {
281            Some(existing) => base
282                .resolve(existing)
283                .map_err(core_error)?
284                .as_dict()
285                .cloned()
286                .unwrap_or_default(),
287            None => Dict::new(),
288        };
289        xobjects.insert(name(&form_name), Object::Ref(form));
290        resources.insert(name("XObject"), Object::Dict(xobjects));
291        dict.insert(name("Resources"), Object::Dict(resources));
292        let mut contents = vec![Object::Ref(prefix)];
293        match dict.get("Contents").cloned() {
294            Some(Object::Array(items)) => contents.extend(items),
295            Some(Object::Ref(r)) => match base.get(r).map_err(core_error)? {
296                Object::Array(items) => contents.extend(items),
297                _ => contents.push(Object::Ref(r)),
298            },
299            _ => {}
300        }
301        contents.push(Object::Ref(suffix));
302        dict.insert(name("Contents"), Object::Array(contents));
303        update.set(page_ref, Object::Dict(dict));
304    }
305    update.bytes()
306}
307
308/// Draws the first page of `overlay` over every page of `base`, returning
309/// `base`'s bytes followed by an incremental update: the overlay page as
310/// one form XObject (its resources copied into the base's object space),
311/// and each page's dictionary rewritten with that form in its resources
312/// and its content wrapped in `q … Q` before the form is drawn. Pages
313/// inlined directly into `/Kids`, having no object of their own, are left
314/// as they are. An encrypted `base` is refused: its new strings and
315/// streams would need encrypting too. An encrypted `overlay` is refused
316/// as well: its decrypted content would otherwise copy across into the
317/// plain update section.
318///
319/// Placement is absolute and unscaled: the overlay page draws at its own
320/// coordinates on every page of `base`, with no scaling to that page's
321/// size, and the overlay page's `/Rotate` and `/CropBox` are not applied.
322/// Because the form paints last, a page whose own content leaves
323/// unbalanced graphics state (an unclosed clip or transform) can clip or
324/// restyle the overlay, since the wrapper's one closing `Q` cannot undo
325/// it.
326pub fn watermark(base: &Document, overlay: &Document) -> Result<Vec<u8>> {
327    watermark_placed(base, overlay, false)
328}
329
330/// Like [`watermark`], but draws the overlay beneath each page's content:
331/// the form paints first and the page's own content paints over it, so
332/// opaque content covers the overlay instead of the other way round.
333///
334/// The same absolute, unscaled placement documented on [`watermark`]
335/// applies here too. Painting the form first, before any of the page's
336/// own operators run, means no page state can reach it, so the
337/// unbalanced-graphics-state risk documented on [`watermark`] does not
338/// apply to this placement.
339pub fn watermark_under(base: &Document, overlay: &Document) -> Result<Vec<u8>> {
340    watermark_placed(base, overlay, true)
341}
342
343/// Stages `by` degrees of rotation, clockwise, on each of `pages` (0-based
344/// indices) into `update`: a clone of the page's own leaf dictionary, its
345/// `/Rotate` set to its current effective rotation plus `by`, normalized
346/// with `rem_euclid(360)`. The staged dictionary is untranslated: it
347/// keeps its own `/Parent`, so it stays exactly where it was in the page
348/// tree. A page with no object of its own (inlined directly into
349/// `/Kids`) cannot be staged this way: refused, naming its 1-based page
350/// number. `by` must be a multiple of 90; anything else is refused before
351/// any page is touched.
352pub fn rotate_pages(update: &mut Update, pages: &[usize], by: i32) -> Result<()> {
353    if by % 90 != 0 {
354        return Err(Error::Other(
355            "rotation must be a multiple of 90 degrees".to_string(),
356        ));
357    }
358    for &index in pages {
359        let page = update.doc.page(index).map_err(core_error)?;
360        let Some(page_ref) = page.object_ref() else {
361            return Err(Error::Other(format!(
362                "page {} is inlined into /Kids and cannot be edited in place",
363                index + 1
364            )));
365        };
366        let mut dict = page.dict().clone();
367        let rotate = (page.rotate + by).rem_euclid(360);
368        dict.insert(name("Rotate"), Object::Int(i64::from(rotate)));
369        update.set(page_ref, Object::Dict(dict));
370    }
371    Ok(())
372}
373
374/// The facts about a base document an update needs, read once from its
375/// trailer and its own newest cross-reference section: refuses an
376/// encrypted base or one missing `/Root` or a `startxref` to chain from.
377#[derive(Debug, Clone)]
378pub struct OverlayBase {
379    /// Byte offset of the base's own newest cross-reference section, named
380    /// as the appended section's `/Prev`.
381    pub prev: u64,
382    /// Style of that newest section, read from the section itself rather
383    /// than the merged trailer (a hybrid base's merged trailer carries
384    /// `/Type /XRef` inherited from its `/XRefStm`, even though its newest
385    /// section, per `startxref`, is the classic table).
386    pub kind: XrefStyle,
387    /// The next free object number: the base's declared `/Size`, raised to
388    /// one past its highest addressed object number.
389    pub size: u32,
390    /// Offset of the cross-reference stream the base's newest section names
391    /// as its `/XRefStm`, when the base is a hybrid-reference file; the
392    /// appended trailer repeats it.
393    pub xrefstm: Option<u64>,
394    /// The base's catalog.
395    pub root: ObjRef,
396    /// The base's document information dictionary, when present.
397    pub info: Option<ObjRef>,
398    /// The base trailer's `/ID` array, cloned.
399    pub id: Option<Object>,
400}
401
402impl OverlayBase {
403    /// Reads `doc`'s trailer and newest cross-reference section: the
404    /// section's offset and kind come from `doc.xref().newest_section()`,
405    /// already recorded while core loaded the file, falling back to
406    /// re-deriving them from `startxref` and `parse_section_at` when the
407    /// document has none (a recovery-scan base refuses with
408    /// [`Error::MissingStartxref`] on this fallback path). Refuses any
409    /// encrypted `doc` outright, wider than
410    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
411    /// appending onto an already-encrypted base is a feature this crate
412    /// does not yet implement, so every encrypted base is refused here for
413    /// now, password-opened or not.
414    pub fn from_document(doc: &Document) -> Result<OverlayBase> {
415        if doc.is_encrypted() {
416            return Err(Error::EncryptedBase);
417        }
418        let trailer = &doc.xref().trailer;
419        let root = trailer.get_ref("Root").ok_or(Error::MissingRoot)?;
420        let (prev, kind) = match doc.xref().newest_section() {
421            Some(section) => (section.offset, xref_style(section.kind)),
422            None => {
423                let offset = startxref(doc.bytes()).ok_or(Error::MissingStartxref)?;
424                let kind = xref_style(
425                    parse_section_at(doc.bytes(), offset)
426                        .map_err(core_error)?
427                        .kind,
428                );
429                (offset as u64, kind)
430            }
431        };
432        let xrefstm = usize::try_from(prev)
433            .ok()
434            .and_then(|offset| parse_section_at(doc.bytes(), offset).ok())
435            .and_then(|section| section.xrefstm)
436            .and_then(|offset| u64::try_from(offset).ok());
437        let highest = doc.xref().iter().map(|(num, _)| num).max().unwrap_or(0);
438        let declared = trailer.get_int("Size").unwrap_or(0).max(0) as u32;
439        Ok(OverlayBase {
440            prev,
441            kind,
442            size: declared.max(highest + 1),
443            xrefstm,
444            root,
445            info: trailer.get_ref("Info"),
446            id: trailer.get("ID").cloned(),
447        })
448    }
449}
450
451/// The [`XrefStyle`] an appended section should copy for a base whose
452/// newest section is `kind`.
453fn xref_style(kind: XrefKind) -> XrefStyle {
454    match kind {
455        XrefKind::Table => XrefStyle::Table,
456        XrefKind::Stream => XrefStyle::Stream,
457    }
458}
459
460/// One recorded change against an object number: a new or replacement body
461/// from [`Overlay::set`], or a free marker from [`Overlay::remove`].
462#[derive(Debug, Clone)]
463enum Change {
464    Set(Object),
465    Free,
466}
467
468/// An update section under construction over an [`OverlayBase`]: which
469/// objects it holds, new ones numbered from the base's first free number.
470#[derive(Debug, Clone)]
471pub struct Overlay {
472    base: OverlayBase,
473    next: u32,
474    objects: Vec<(ObjRef, Change)>,
475    imported: FastMap<ObjRef, ObjRef>,
476    info: Option<ObjRef>,
477}
478
479impl Overlay {
480    /// An empty update section over `base`, numbering new objects from its
481    /// first free number.
482    pub fn new(base: OverlayBase) -> Overlay {
483        let next = base.size;
484        Overlay {
485            base,
486            next,
487            objects: Vec::new(),
488            imported: FastMap::default(),
489            info: None,
490        }
491    }
492
493    /// Sets an object under its own number, whether new or a replacement
494    /// of one already in the base. Raises the next free number past `r`
495    /// when `r` was not already reserved, so a later `reserve`/`put` never
496    /// collides with a caller-chosen number. A no-op for object number 0:
497    /// it is already the free list's own permanent head, represented by
498    /// this section's synthetic entry-0 row whenever any other object is
499    /// freed, and a `set` row for it would collide with that row. Symmetric
500    /// with [`Overlay::remove`]'s guard.
501    pub fn set(&mut self, r: ObjRef, obj: Object) {
502        if r.num == 0 {
503            return;
504        }
505        self.next = self.next.max(r.num.saturating_add(1));
506        self.objects.push((r, Change::Set(obj)));
507    }
508
509    /// Marks `r` free: the appended section's cross-reference data chains
510    /// it into entry 0's free list, in whichever style the base uses. Its
511    /// generation for reuse is `r.gen` advanced by one (saturating at
512    /// 65535, the field's own limit), per the classic table's convention
513    /// for a deleted entry's row. A no-op for object number 0: it is
514    /// already the free list's own permanent head, represented by this
515    /// section's synthetic entry-0 row whenever any other object is freed.
516    pub fn remove(&mut self, r: ObjRef) {
517        if r.num == 0 {
518            return;
519        }
520        self.next = self.next.max(r.num.saturating_add(1));
521        let gen = r.gen.saturating_add(1);
522        self.objects
523            .push((ObjRef { num: r.num, gen }, Change::Free));
524    }
525
526    /// Allocates the next free object number without storing anything
527    /// under it yet.
528    pub fn reserve(&mut self) -> ObjRef {
529        let r = ObjRef {
530            num: self.next,
531            gen: 0,
532        };
533        self.next += 1;
534        r
535    }
536
537    /// Adds a new object under the next free number.
538    pub fn put(&mut self, obj: Object) -> ObjRef {
539        let r = self.reserve();
540        self.set(r, obj);
541        r
542    }
543
544    /// Registers the document information dictionary for the appended
545    /// section's trailer, overriding the base's own.
546    pub fn set_info(&mut self, r: ObjRef) {
547        self.info = Some(r);
548    }
549
550    /// Whether nothing has been set or removed yet.
551    pub fn is_empty(&self) -> bool {
552        self.objects.is_empty()
553    }
554
555    /// The appended section alone: every set object at `start` plus its
556    /// position within this section, then a cross-reference section in the
557    /// base's style naming the base's section as `/Prev`. Refused when no
558    /// object has been set. A number recorded more than once (repeated
559    /// `set`, or `set` and `remove` on the same reference) keeps only its
560    /// last-recorded change, so the appended cross-reference data never
561    /// carries two rows for one number.
562    pub fn section(&self, start: u64) -> Result<Vec<u8>> {
563        if self.is_empty() {
564            return Err(Error::EmptyUpdate);
565        }
566        let mut last: FastMap<u32, usize> = FastMap::default();
567        for (index, (r, _)) in self.objects.iter().enumerate() {
568            last.insert(r.num, index);
569        }
570        let mut winners: Vec<usize> = last.into_values().collect();
571        winners.sort_by_key(|&index| self.objects[index].0.num);
572        let mut out = Vec::new();
573        let mut rows: Vec<Row> = Vec::with_capacity(winners.len() + 1);
574        let mut freed: Vec<ObjRef> = Vec::new();
575        for index in winners {
576            let (r, change) = &self.objects[index];
577            match change {
578                Change::Set(obj) => {
579                    rows.push(Row::InFile(*r, start as usize + out.len()));
580                    write_indirect(&mut out, *r, obj)?;
581                }
582                Change::Free => freed.push(*r),
583            }
584        }
585        if !freed.is_empty() {
586            freed.sort_by_key(|r| r.num);
587            let head = freed.first().map_or(0, |r| r.num);
588            rows.push(Row::Free {
589                num: 0,
590                gen: 65535,
591                next: head,
592            });
593            for (index, r) in freed.iter().enumerate() {
594                let next = freed.get(index + 1).map_or(0, |n| n.num);
595                rows.push(Row::Free {
596                    num: r.num,
597                    gen: r.gen,
598                    next,
599                });
600            }
601        }
602        rows.sort_by_key(Row::num);
603
604        let mut trailer = Dict::new();
605        trailer.insert(name("Root"), Object::Ref(self.base.root));
606        if let Some(info) = self.info.or(self.base.info) {
607            trailer.insert(name("Info"), Object::Ref(info));
608        }
609        if let Some(id) = rotated_id(&self.base, &out, &freed) {
610            trailer.insert(name("ID"), id);
611        }
612        trailer.insert(name("Prev"), Object::Int(self.base.prev as i64));
613        if let (XrefStyle::Table, Some(xrefstm)) = (self.base.kind, self.base.xrefstm) {
614            trailer.insert(name("XRefStm"), Object::Int(xrefstm as i64));
615        }
616        match self.base.kind {
617            XrefStyle::Stream => finish_stream(&mut out, start, rows, trailer, self.next)?,
618            XrefStyle::Table => finish_table(&mut out, start, &rows, trailer, self.next)?,
619        }
620        Ok(out)
621    }
622
623    /// The overlay's first page as a form XObject in the base's object
624    /// space: its media box as the form's bounding box, its decoded content
625    /// as the form's stream, and its resource graph deep-copied and
626    /// renumbered. Refuses any encrypted `overlay` outright, wider than
627    /// [`crate::importer::Importer::new`]'s own locked-only refusal:
628    /// appending onto an encrypted base is a feature this crate does not
629    /// yet implement, so every encrypted overlay is refused here for now,
630    /// password-opened or not.
631    pub(crate) fn import_form(&mut self, overlay: &Document) -> Result<ObjRef> {
632        if overlay.is_encrypted() {
633            return Err(Error::EncryptedBase);
634        }
635        let page = overlay.page(0).map_err(core_error)?;
636        let content = page.content(overlay).map_err(core_error)?;
637        let resources = self.import_object(overlay, &Object::Dict(page.resources.clone()))?;
638        let mut dict = Dict::new();
639        dict.insert(name("Type"), Object::Name(name("XObject")));
640        dict.insert(name("Subtype"), Object::Name(name("Form")));
641        dict.insert(name("FormType"), Object::Int(1));
642        dict.insert(name("BBox"), rect_array(page.media_box));
643        dict.insert(name("Resources"), resources);
644        dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
645        Ok(self.put(Object::Stream(Stream {
646            dict,
647            data: deflate(&content)?,
648        })))
649    }
650
651    /// A deep copy of `obj` from `source` into the update: every reference
652    /// it reaches becomes a new object here, each source object copied once
653    /// however many times it is referenced. Streams keep their encoded
654    /// bytes and filters; their `/Length` is rewritten on emission.
655    pub(crate) fn import_object(&mut self, source: &Document, obj: &Object) -> Result<Object> {
656        Ok(match obj {
657            Object::Ref(r) => {
658                if let Some(copied) = self.imported.get(r) {
659                    return Ok(Object::Ref(*copied));
660                }
661                let copied = self.reserve();
662                self.imported.insert(*r, copied);
663                let body = source.get(*r).map_err(core_error)?;
664                let body = self.import_object(source, &body)?;
665                self.objects.push((copied, Change::Set(body)));
666                Object::Ref(copied)
667            }
668            Object::Dict(d) => Object::Dict(self.import_dict(source, d)?),
669            Object::Array(items) => Object::Array(
670                items
671                    .iter()
672                    .map(|item| self.import_object(source, item))
673                    .collect::<Result<Vec<Object>>>()?,
674            ),
675            Object::Stream(s) => {
676                let mut dict = s.dict.clone();
677                dict.remove("Length");
678                Object::Stream(Stream {
679                    dict: self.import_dict(source, &dict)?,
680                    data: s.data.clone(),
681                })
682            }
683            other => other.clone(),
684        })
685    }
686
687    pub(crate) fn import_dict(&mut self, source: &Document, dict: &Dict) -> Result<Dict> {
688        let mut out = Dict::new();
689        for (key, value) in dict.iter() {
690            out.insert(key.clone(), self.import_object(source, value)?);
691        }
692        Ok(out)
693    }
694}
695
696/// Merges `meta` into `existing_info`'s dictionary (or a fresh one, staged
697/// under a newly reserved number, when `existing_info` is `None`): a
698/// `Some` field overwrites its key (`Some(String::new())` writes an empty
699/// string), a `None` field leaves whatever key was already there. The
700/// merged dictionary is staged into `overlay` via `set` and `set_info`.
701///
702/// When `xmp_ref` is `Some`, the merged dictionary is read back into a
703/// [`Metadata`] (text fields via `decode_text_string`, dates via
704/// [`Date::parse_pdf`], an unparseable date simply dropping out) and
705/// staged under `xmp_ref` as a fresh, unfiltered `/Type /Metadata /Subtype
706/// /XML` stream of the crate's XMP packet over that merged value: any XMP
707/// property outside those eight fields is not carried into the new
708/// packet, though the original packet's bytes stay in the base.
709///
710/// Shared by [`Update::set_metadata`] and its asynchronous counterpart.
711pub fn set_metadata_with(
712    overlay: &mut Overlay,
713    existing_info: Option<(ObjRef, Dict)>,
714    xmp_ref: Option<ObjRef>,
715    meta: Metadata,
716) -> Result<()> {
717    let (target, existing_dict) = match existing_info {
718        Some((r, dict)) => (r, Some(dict)),
719        None => (overlay.reserve(), None),
720    };
721    let (dict, merged) = merge_metadata(existing_dict, &meta);
722    overlay.set(target, Object::Dict(dict));
723    overlay.set_info(target);
724    let Some(xmp_ref) = xmp_ref else {
725        return Ok(());
726    };
727    overlay.set(xmp_ref, xmp_metadata_stream(&merged));
728    Ok(())
729}
730
731/// `existing` (`None` starts from an empty dictionary) with every `Some`
732/// field of `meta` applied: a `Some` field overwrites its key
733/// (`Some(String::new())` writes an empty string), a `None` field leaves
734/// whatever key was already there. Also returns that merged dictionary read
735/// back into a [`Metadata`] (text fields via `decode_text_string`, dates via
736/// [`Date::parse_pdf`], an unparseable date simply dropping out), for
737/// [`xmp_metadata_stream`]: any XMP property outside those eight fields is
738/// not carried into a rebuilt packet.
739///
740/// Shared by [`set_metadata_with`] and [`crate::assemble::rewrite_with_metadata`].
741pub(crate) fn merge_metadata(existing: Option<Dict>, meta: &Metadata) -> (Dict, Metadata) {
742    let mut dict = existing.unwrap_or_default();
743    apply_metadata_fields(&mut dict, meta);
744    let merged = metadata_from_info(&dict);
745    (dict, merged)
746}
747
748/// A fresh, unfiltered `/Type /Metadata /Subtype /XML` stream over `meta`'s
749/// XMP packet, ready to stage into an [`Overlay`] or substitute into an
750/// import.
751pub(crate) fn xmp_metadata_stream(meta: &Metadata) -> Object {
752    let mut xmp_dict = Dict::new();
753    xmp_dict.insert(name("Type"), Object::Name(name("Metadata")));
754    xmp_dict.insert(name("Subtype"), Object::Name(name("XML")));
755    Object::Stream(Stream {
756        dict: xmp_dict,
757        data: crate::xmp::packet(meta),
758    })
759}
760
761/// `dict` with every value resolved against `doc`: an indirect value such
762/// as `/Title 12 0 R` becomes the string object it points to, so a field
763/// [`merge_metadata`] keeps (a `None` field in the merge) still reads back
764/// as text rather than silently vanishing from a rebuilt XMP packet. A
765/// value whose reference chain fails to resolve (an unreadable target, or
766/// a cycle) is kept as given.
767pub(crate) fn resolve_dict(doc: &Document, dict: &Dict) -> Dict {
768    let mut out = Dict::new();
769    for (key, value) in dict.iter() {
770        let resolved = doc.resolve(value).unwrap_or_else(|_| value.clone());
771        out.insert(key.clone(), resolved);
772    }
773    out
774}
775
776/// `doc`'s catalog's `/Metadata` entry, when it is an indirect reference.
777/// `None` for a catalog with no `/Metadata`, or one that reads as a direct
778/// stream rather than a reference.
779pub(crate) fn catalog_metadata_ref(doc: &Document, root: ObjRef) -> Option<ObjRef> {
780    let catalog = doc.get(root).ok()?;
781    match catalog.as_dict()?.get("Metadata")? {
782        Object::Ref(r) => Some(*r),
783        _ => None,
784    }
785}
786
787/// Writes every `Some` field of `meta` into `dict` under its `/Info` key;
788/// a `None` field is left untouched.
789fn apply_metadata_fields(dict: &mut Dict, meta: &Metadata) {
790    let texts = [
791        ("Title", &meta.title),
792        ("Author", &meta.author),
793        ("Subject", &meta.subject),
794        ("Keywords", &meta.keywords),
795        ("Creator", &meta.creator),
796        ("Producer", &meta.producer),
797    ];
798    for (key, value) in texts {
799        if let Some(value) = value {
800            dict.insert(name(key), text_string(value));
801        }
802    }
803    let dates = [
804        ("CreationDate", meta.creation_date),
805        ("ModDate", meta.modification_date),
806    ];
807    for (key, value) in dates {
808        if let Some(date) = value {
809            dict.insert(name(key), Object::String(date.to_pdf_string().into_bytes()));
810        }
811    }
812}
813
814/// Reads an `/Info` dictionary back into a [`Metadata`]: text fields via
815/// `decode_text_string`, dates via [`Date::parse_pdf`]. A missing or
816/// unparseable field is simply `None`.
817fn metadata_from_info(dict: &Dict) -> Metadata {
818    Metadata {
819        title: info_text(dict, "Title"),
820        author: info_text(dict, "Author"),
821        subject: info_text(dict, "Subject"),
822        keywords: info_text(dict, "Keywords"),
823        creator: info_text(dict, "Creator"),
824        producer: info_text(dict, "Producer"),
825        creation_date: info_date(dict, "CreationDate"),
826        modification_date: info_date(dict, "ModDate"),
827    }
828}
829
830/// `dict[key]` decoded as a text string, when present and a string.
831fn info_text(dict: &Dict, key: &str) -> Option<String> {
832    Some(decode_text_string(dict.get(key)?.as_str_bytes()?))
833}
834
835/// `dict[key]` decoded and parsed as a PDF date, when present, a string,
836/// and a valid date.
837fn info_date(dict: &Dict, key: &str) -> Option<Date> {
838    Date::parse_pdf(&decode_text_string(dict.get(key)?.as_str_bytes()?))
839}
840
841/// The base's length as an update's write position, plus whether a pad
842/// newline must be inserted first: an object header may not follow
843/// directly after `%%EOF` unless the base already ends on a line
844/// terminator (`\n` or `\r`).
845pub fn start_offset(base: &[u8]) -> (u64, bool) {
846    let pad = !matches!(base.last(), Some(b'\n') | Some(b'\r'));
847    (base.len() as u64 + u64::from(pad), pad)
848}
849
850/// A base document plus the update section being built over it.
851pub struct Update<'a> {
852    doc: &'a Document,
853    overlay: Overlay,
854}
855
856impl<'a> Update<'a> {
857    /// Opens `doc` for an update: refuses an encrypted base or one missing
858    /// `/Root` or a `startxref` to chain the appended section's `/Prev` to.
859    pub fn new(doc: &'a Document) -> Result<Update<'a>> {
860        let base = OverlayBase::from_document(doc)?;
861        Ok(Update {
862            doc,
863            overlay: Overlay::new(base),
864        })
865    }
866
867    /// Sets an object under its own number, whether new or a replacement
868    /// of one already in the base.
869    pub fn set(&mut self, r: ObjRef, obj: Object) {
870        self.overlay.set(r, obj);
871    }
872
873    /// Marks `r` free in the appended section's cross-reference data.
874    pub fn remove(&mut self, r: ObjRef) {
875        self.overlay.remove(r);
876    }
877
878    /// Allocates the next free object number without storing anything
879    /// under it yet.
880    pub fn reserve(&mut self) -> ObjRef {
881        self.overlay.reserve()
882    }
883
884    /// The update section under construction.
885    pub fn overlay(&self) -> &Overlay {
886        &self.overlay
887    }
888
889    /// Merges `meta` into the base document's `/Info` dictionary: the ref
890    /// comes from the overlay's own info ref when a prior call set one,
891    /// else the base's; the dictionary itself always comes from the base
892    /// document (never from a prior call's staged fields, so two calls on
893    /// one `Update` do not compound; on a base without `/Info`, a call
894    /// starts from a fresh dictionary). When the catalog already names an
895    /// XMP packet, it is rewritten from the merged fields. See
896    /// [`set_metadata_with`] for the merge and rewrite rules.
897    pub fn set_metadata(&mut self, meta: Metadata) -> Result<()> {
898        let info_ref = self.overlay.info.or(self.overlay.base.info);
899        let existing_info = info_ref.and_then(|r| {
900            let dict = self.doc.get(r).ok()?.as_dict()?.clone();
901            Some((r, resolve_dict(self.doc, &dict)))
902        });
903        let xmp_ref = catalog_metadata_ref(self.doc, self.overlay.base.root);
904        set_metadata_with(&mut self.overlay, existing_info, xmp_ref, meta)
905    }
906
907    /// The base bytes, whether a pad newline goes before the appended
908    /// section, and the section itself, computed together so a refused
909    /// update (or any other failure) is known before anything is written
910    /// anywhere.
911    fn parts(&self) -> Result<(&[u8], bool, Vec<u8>)> {
912        let base = self.doc.bytes();
913        let (start, pad) = start_offset(base);
914        let section = self.overlay.section(start)?;
915        Ok((base, pad, section))
916    }
917
918    /// Writes the base bytes, a pad newline when the base needs one, and
919    /// the appended section into `out`. The section is built before any
920    /// byte reaches `out`, so a refused update (or any other failure)
921    /// writes nothing at all.
922    pub fn append_into(&self, mut out: impl std::io::Write) -> Result<()> {
923        let (base, pad, section) = self.parts()?;
924        out.write_all(base)?;
925        if pad {
926            out.write_all(b"\n")?;
927        }
928        out.write_all(&section)?;
929        Ok(())
930    }
931
932    /// [`Update::append_into`] to a new file at `path`: the file is
933    /// created only once the update is known to build, so a refused
934    /// update leaves no file behind at all.
935    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
936        let (base, pad, section) = self.parts()?;
937        let mut file = std::fs::File::create(path)?;
938        file.write_all(base)?;
939        if pad {
940            file.write_all(b"\n")?;
941        }
942        file.write_all(&section)?;
943        Ok(())
944    }
945
946    /// The base bytes followed by the update section, as one buffer.
947    pub fn bytes(&self) -> Result<Vec<u8>> {
948        let mut out = Vec::new();
949        self.append_into(&mut out)?;
950        Ok(out)
951    }
952}
953
954/// One row of the appended section's cross-reference data: an object
955/// stored at a byte offset, or a freed number chained to the next free
956/// number in the section's own free list (entry 0 when it is the head).
957#[derive(Debug, Clone, Copy)]
958enum Row {
959    InFile(ObjRef, usize),
960    Free { num: u32, gen: u16, next: u32 },
961}
962
963impl Row {
964    fn num(&self) -> u32 {
965        match self {
966            Row::InFile(r, _) => r.num,
967            Row::Free { num, .. } => *num,
968        }
969    }
970}
971
972/// Splits `rows`, already sorted ascending by object number, into maximal
973/// runs of consecutive numbers, as `(run start index, run length)` pairs.
974/// Shared by the classic table's subsections and the xref stream's
975/// `/Index` pairs, so both group the same way.
976fn contiguous_runs(rows: &[Row]) -> Vec<(usize, usize)> {
977    let mut runs = Vec::new();
978    let mut begin = 0;
979    while begin < rows.len() {
980        let mut end = begin + 1;
981        while end < rows.len() && rows[end].num() == rows[end - 1].num() + 1 {
982            end += 1;
983        }
984        runs.push((begin, end - begin));
985        begin = end;
986    }
987    runs
988}
989
990/// The appended trailer's `/ID`: the base's first half kept verbatim, the
991/// second half replaced by the first 16 bytes of a SHA-256 over the first
992/// half's bytes, the base's `/Prev` offset as little-endian bytes, `body`
993/// (the section's serialized objects, built before its xref part), and
994/// finally each of `freed`'s `(num, gen)` pairs in order (`num` then `gen`,
995/// both little-endian), so a frees-only update, whose `body` is empty,
996/// still rotates by what it freed rather than staying fixed. `None` when
997/// the base carries no `/ID` array with a string first element, in which
998/// case the appended trailer omits the key entirely.
999fn rotated_id(base: &OverlayBase, body: &[u8], freed: &[ObjRef]) -> Option<Object> {
1000    let Some(Object::Array(halves)) = &base.id else {
1001        return None;
1002    };
1003    let Some(Object::String(first)) = halves.first() else {
1004        return None;
1005    };
1006    let mut hasher = Sha256::new();
1007    hasher.update(first);
1008    hasher.update(&base.prev.to_le_bytes());
1009    hasher.update(body);
1010    for r in freed {
1011        hasher.update(&r.num.to_le_bytes());
1012        hasher.update(&r.gen.to_le_bytes());
1013    }
1014    let digest = hasher.finalize();
1015    Some(Object::Array(vec![
1016        Object::String(first.clone()),
1017        Object::String(digest[..16].to_vec()),
1018    ]))
1019}
1020
1021/// A cross-reference stream as the section's last object: one row per
1022/// object of the update (or per freed number) plus one for the stream
1023/// itself, and `/Index` pairs one per contiguous run of object numbers.
1024fn finish_stream(
1025    out: &mut Vec<u8>,
1026    start: u64,
1027    mut rows: Vec<Row>,
1028    mut dict: Dict,
1029    mut next: u32,
1030) -> Result<()> {
1031    let xref_ref = ObjRef { num: next, gen: 0 };
1032    next += 1;
1033    let xref_offset = start as usize + out.len();
1034    rows.push(Row::InFile(xref_ref, xref_offset));
1035    rows.sort_by_key(Row::num);
1036    let runs = contiguous_runs(&rows);
1037    let mut index = Vec::with_capacity(runs.len() * 2);
1038    for (begin, len) in runs {
1039        index.push(Object::Int(i64::from(rows[begin].num())));
1040        index.push(Object::Int(len as i64));
1041    }
1042    let mut data = Vec::with_capacity(rows.len() * 7);
1043    for row in &rows {
1044        match row {
1045            Row::InFile(r, offset) => {
1046                data.push(1);
1047                data.extend_from_slice(&field_offset(*offset)?.to_be_bytes());
1048                data.extend_from_slice(&r.gen.to_be_bytes());
1049            }
1050            Row::Free {
1051                gen,
1052                next: free_next,
1053                ..
1054            } => {
1055                data.push(0);
1056                data.extend_from_slice(&free_next.to_be_bytes());
1057                data.extend_from_slice(&gen.to_be_bytes());
1058            }
1059        }
1060    }
1061    dict.insert(name("Type"), Object::Name(name("XRef")));
1062    dict.insert(name("Size"), Object::Int(i64::from(next)));
1063    dict.insert(
1064        name("W"),
1065        Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]),
1066    );
1067    dict.insert(name("Index"), Object::Array(index));
1068    write_indirect(out, xref_ref, &Object::Stream(Stream { dict, data }))?;
1069    out.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
1070    Ok(())
1071}
1072
1073/// A classic `xref` table with one subsection per run of consecutive
1074/// object numbers, then the `trailer` dictionary. A freed row uses `f` in
1075/// place of `n`, its first field naming the next free number in the
1076/// section's own chain rather than a byte offset.
1077fn finish_table(
1078    out: &mut Vec<u8>,
1079    start: u64,
1080    rows: &[Row],
1081    mut dict: Dict,
1082    size: u32,
1083) -> Result<()> {
1084    let xref_offset = start as usize + out.len();
1085    out.extend_from_slice(b"xref\n");
1086    for (begin, len) in contiguous_runs(rows) {
1087        out.extend_from_slice(format!("{} {}\n", rows[begin].num(), len).as_bytes());
1088        for row in &rows[begin..begin + len] {
1089            match row {
1090                Row::InFile(r, offset) => out.extend_from_slice(
1091                    format!("{:010} {:05} n \n", table_offset(*offset)?, r.gen).as_bytes(),
1092                ),
1093                Row::Free { gen, next, .. } => {
1094                    out.extend_from_slice(format!("{next:010} {gen:05} f \n").as_bytes())
1095                }
1096            }
1097        }
1098    }
1099    dict.insert(name("Size"), Object::Int(i64::from(size)));
1100    out.extend_from_slice(b"trailer\n");
1101    serialize_dict(&dict, out)?;
1102    out.extend_from_slice(format!("\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes());
1103    Ok(())
1104}
1105
1106/// Emits `num gen obj` through `endobj`; a stream carries a direct
1107/// `/Length` of its stored byte count.
1108fn write_indirect(out: &mut Vec<u8>, r: ObjRef, obj: &Object) -> Result<()> {
1109    out.extend_from_slice(format!("{} {} obj\n", r.num, r.gen).as_bytes());
1110    match obj {
1111        Object::Stream(s) => {
1112            let mut dict = s.dict.clone();
1113            dict.insert(name("Length"), Object::Int(s.data.len() as i64));
1114            serialize_dict(&dict, out)?;
1115            out.extend_from_slice(b"\nstream\n");
1116            out.extend_from_slice(&s.data);
1117            out.extend_from_slice(b"\nendstream\nendobj\n");
1118        }
1119        direct => {
1120            serialize_object(direct, out)?;
1121            out.extend_from_slice(b"\nendobj\n");
1122        }
1123    }
1124    Ok(())
1125}
1126
1127/// An uncompressed stream with no filter of its own.
1128fn plain_stream(data: Vec<u8>) -> Stream {
1129    Stream {
1130        dict: Dict::new(),
1131        data,
1132    }
1133}
1134
1135pub(crate) fn deflate(data: &[u8]) -> Result<Vec<u8>> {
1136    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1137    encoder.write_all(data)?;
1138    Ok(encoder.finish()?)
1139}
1140
1141/// A byte position as the 4-byte offset field of a cross-reference stream.
1142fn field_offset(position: usize) -> Result<u32> {
1143    u32::try_from(position)
1144        .map_err(|_| Error::Other("file offset exceeds the 4-byte xref field".to_string()))
1145}
1146
1147/// A byte position as the 10-digit offset field of a classic xref table.
1148fn table_offset(position: usize) -> Result<usize> {
1149    if position as u64 <= 9_999_999_999 {
1150        return Ok(position);
1151    }
1152    Err(Error::Other(
1153        "file offset exceeds the 10-digit xref table field".to_string(),
1154    ))
1155}
1156
1157fn name(text: &str) -> Name {
1158    Name(text.to_string())
1159}
1160
1161pub(crate) fn core_error(error: pdfboss_core::Error) -> Error {
1162    Error::Other(error.to_string())
1163}