laminapdf-model 0.6.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
//! Rewriting the page labels after a change to the page list ([`PageLabels::remap`]) and
//! writing them back as the catalog's `/PageLabels` number tree ([`PageLabels::write`]).

use std::collections::BTreeMap;

use laminapdf_cos::{CosMut, Dict, Object, PdfString, Result};
use laminapdf_syntax::text::encode_text_string;

use super::{LabelRange, LabelStyle, PageLabels};
use crate::document::Document;
use crate::edit::set_catalog_entry;
use crate::id::PageId;
use crate::tree_writer::TreeWriter;

impl LabelStyle {
    const fn name(self) -> &'static str {
        match self {
            Self::Decimal => "D",
            Self::UpperRoman => "R",
            Self::LowerRoman => "r",
            Self::UpperLetters => "A",
            Self::LowerLetters => "a",
        }
    }
}

impl LabelRange {
    /// The label dictionary (§12.4.2, Table 161), leaving out `/St 1` and an empty prefix.
    fn to_dict(&self) -> Dict {
        let mut dict = Dict::new();
        if let Some(style) = self.style {
            dict.insert("S", Object::name(style.name()));
        }
        if !self.prefix.is_empty() {
            dict.insert(
                "P",
                Object::String(PdfString::literal(encode_text_string(&self.prefix))),
            );
        }
        if self.first != 1 {
            dict.insert("St", Object::Integer(i64::try_from(self.first).unwrap_or(i64::MAX)));
        }
        dict
    }
}

impl LabelRange {
    /// A range starting at page `start` with this numbering `style` (`None`: the prefix
    /// alone), `prefix` and `first` number. Nothing is checked here: [`PageLabels::write`]
    /// writes what it is given, so callers check that ranges start at page 0, increase and
    /// number from 1 (ISO 32000-2 §12.4.2).
    ///
    /// Added in 0.3.0.
    #[must_use]
    pub fn new(start: u64, style: Option<LabelStyle>, prefix: impl Into<String>, first: u64) -> Self {
        Self {
            start,
            style,
            prefix: prefix.into(),
            first,
        }
    }
}

impl PageLabels {
    /// Labels made of these `ranges`, sorted by first page.
    ///
    /// ```
    /// use laminapdf_model::{LabelRange, LabelStyle, PageLabels};
    ///
    /// let labels = PageLabels::from_ranges(vec![
    ///     LabelRange::new(2, Some(LabelStyle::Decimal), "", 1),
    ///     LabelRange::new(0, Some(LabelStyle::LowerRoman), "", 1),
    /// ]);
    /// assert_eq!((labels.label(1).as_deref(), labels.label(2).as_deref()), (Some("ii"), Some("1")));
    /// ```
    ///
    /// Added in 0.3.0.
    #[must_use]
    pub fn from_ranges(mut ranges: Vec<LabelRange>) -> Self {
        ranges.sort_by_key(|r| r.start);
        Self { ranges }
    }

    /// The labels after a change to the page list: `before` is the list these labels
    /// describe, `after` the new one (each a list of page IDs, in order). Every page in both
    /// keeps its label, but for one case below; a page only in `after` continues the range
    /// it lands in (the label after its previous page's). Ranges are then written again from
    /// the labels, so a range starts wherever the style, the prefix or the run of numbers
    /// breaks.
    ///
    /// New pages ahead of the first labelled page join the start of its range. They take the
    /// numbers below its first label while there are any (before a range that starts at 5,
    /// one new page is 4 and nothing else moves); since numbers start at 1, a range that
    /// already starts at 1 (or "i", or "A-1") starts again at 1 on the first new page, and
    /// that range's own pages are numbered up by as many as are short. Later ranges keep
    /// their labels: a contents page put before "i" is "i", the old "i" becomes "ii", and the
    /// body and appendix stay as they were, so the new pages never repeat a label of that
    /// range.
    ///
    /// A page that had no label (before the first range) keeps none while it stays ahead of
    /// every labelled page; one that lands after a labelled page gets the decimal number it
    /// was shown before, its old index plus one.
    ///
    /// ```
    /// use laminapdf_model::{PageId, PageLabels};
    /// # use laminapdf_cos::ObjRef;
    /// let ids: Vec<PageId> = (1..=4).map(|n| PageId::object(ObjRef::new(n, 0))).collect();
    /// let labels = PageLabels::default(); // no /PageLabels
    /// let moved = vec![ids[3].clone(), ids[0].clone(), ids[1].clone(), ids[2].clone()];
    /// assert!(labels.remap(&ids, &moved).is_empty());
    /// ```
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub fn remap(&self, before: &[PageId], after: &[PageId]) -> Self {
        if self.ranges.is_empty() {
            return Self::default();
        }
        let old: BTreeMap<&PageId, usize> = before.iter().enumerate().map(|(i, id)| (id, i)).collect();
        let was: Vec<Was> = after
            .iter()
            .map(|id| match old.get(id) {
                Some(&i) => self
                    .spec(i)
                    .map_or_else(|| Was::Unlabelled(i), |(spec, range)| Was::Label(spec, range)),
                None => Was::New,
            })
            .collect();
        let specs = fill(was);
        Self::from_specs(&specs)
    }

    /// Writes these labels as the catalog's `/PageLabels` number tree, or removes the entry
    /// when there are none.
    ///
    /// # Errors
    /// Errors of the overlay; [`laminapdf_cos::Error::MissingRoot`] without a catalog.
    ///
    /// Added in 0.2.0.
    pub fn write(&self, cos: &mut CosMut<'_>) -> Result<()> {
        if self.ranges.is_empty() {
            return set_catalog_entry(cos, "PageLabels", None);
        }
        let entries: BTreeMap<i64, Object> = self
            .ranges
            .iter()
            .map(|r| (i64::try_from(r.start).unwrap_or(i64::MAX), Object::Dict(r.to_dict())))
            .collect();
        let root = TreeWriter::new().write_numbers(cos, &entries)?;
        set_catalog_entry(cos, "PageLabels", Some(Object::Ref(root)))
    }

    /// Whether the catalog's `/PageLabels` already holds exactly what [`PageLabels::write`]
    /// would write: no entry for no labels, else one node whose `/Nums` lists these ranges'
    /// dictionaries. Read without warnings, so a strict document never fails here; a tree
    /// stored any other way (several nodes, other values, damage) is `false`, so writing
    /// replaces it.
    ///
    /// Added in 0.3.0.
    #[must_use]
    pub fn is_written(&self, doc: &Document) -> bool {
        let Ok(catalog) = doc.catalog() else {
            return false;
        };
        let Some(root) = catalog.get("PageLabels") else {
            return self.ranges.is_empty();
        };
        let nums = match doc.read(root) {
            Ok(Some(node)) => match node.as_dict() {
                Some(node) if node.len() == 1 => node.get("Nums").cloned(),
                _ => None,
            },
            _ => None,
        };
        let Some(Ok(Some(nums))) = nums.map(|n| doc.read(&n)) else {
            return false;
        };
        let Some(nums) = nums.as_array() else {
            return false;
        };
        nums.len() == self.ranges.len() * 2
            && self.ranges.iter().zip(nums.chunks(2)).all(|(range, pair)| match pair {
                [Object::Integer(start), value] => {
                    u64::try_from(*start).is_ok_and(|s| s == range.start)
                        && matches!(doc.read(value), Ok(Some(v)) if *v == Object::Dict(range.to_dict()))
                }
                _ => false,
            })
    }

    /// What page `index` shows: its label's parts and the index of its range, `None` before
    /// the first range.
    fn spec(&self, index: usize) -> Option<(Spec, usize)> {
        let index = u64::try_from(index).ok()?;
        let at = self.ranges.partition_point(|r| r.start <= index);
        let Some(range) = at.checked_sub(1).and_then(|i| self.ranges.get(i)) else {
            // Unlabelled: a viewer shows the page number.
            return None;
        };
        let spec = Spec {
            style: range.style,
            prefix: range.prefix.clone(),
            value: range.first.saturating_add(index - range.start),
        };
        Some((spec, at - 1))
    }

    /// The fewest ranges that give each page its label; unlabelled pages lead the list.
    fn from_specs(specs: &[Option<Spec>]) -> Self {
        let mut ranges: Vec<LabelRange> = Vec::new();
        let mut previous: Option<Spec> = None;
        for (index, spec) in specs.iter().enumerate() {
            let start = u64::try_from(index).unwrap_or(u64::MAX);
            let Some(spec) = spec.clone() else {
                previous = None;
                continue;
            };
            if previous.as_ref().is_none_or(|p| !p.continued_by(&spec)) {
                ranges.push(LabelRange {
                    start,
                    style: spec.style,
                    prefix: spec.prefix.clone(),
                    first: spec.value,
                });
            }
            previous = Some(spec);
        }
        Self { ranges }
    }
}

/// The parts of one page's label.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Spec {
    style: Option<LabelStyle>,
    prefix: String,
    /// The number (unused without a style).
    value: u64,
}

impl Spec {
    /// Whether `next`, on the following page, can stay in this page's range.
    fn continued_by(&self, next: &Self) -> bool {
        self.style == next.style
            && self.prefix == next.prefix
            && (self.style.is_none() || self.value.checked_add(1) == Some(next.value))
    }

    fn next(&self) -> Self {
        Self {
            value: self.value.saturating_add(1),
            ..self.clone()
        }
    }
}

/// What a page of the new list was in the old one.
enum Was {
    /// A labelled page, and the index of its old range.
    Label(Spec, usize),
    /// An unlabelled page (before the first range), at this old index.
    Unlabelled(usize),
    /// A page the old list didn't have.
    New,
}

/// Each page's label in the new list. A new page continues the labelled page before it; an
/// old unlabelled page after a labelled one gets the decimal number a viewer showed for it.
/// Pages ahead of every labelled page stay unlabelled, except new pages right before the
/// first labelled one, which join the start of its range ([`lead_into_first_range`]).
fn fill(mut was: Vec<Was>) -> Vec<Option<Spec>> {
    let lead = lead_into_first_range(&mut was);
    let mut out: Vec<Option<Spec>> = Vec::with_capacity(was.len());
    let mut previous: Option<Spec> = None;
    for page in &was {
        let spec = match (page, &previous) {
            (Was::Label(spec, _), _) => Some(spec.clone()),
            (Was::Unlabelled(index), Some(_)) => Some(Spec {
                style: Some(LabelStyle::Decimal),
                prefix: String::new(),
                value: u64::try_from(*index).unwrap_or(u64::MAX).saturating_add(1),
            }),
            (Was::New, Some(p)) => Some(p.next()),
            (Was::Unlabelled(_) | Was::New, None) => None,
        };
        if spec.is_some() {
            previous.clone_from(&spec);
        }
        out.push(spec);
    }
    if let Some(Lead { at, count, spec }) = lead {
        let mut value = spec.value;
        for slot in out.iter_mut().skip(at).take(count) {
            *slot = Some(Spec { value, ..spec.clone() });
            if spec.style.is_some() {
                value = value.saturating_add(1);
            }
        }
    }
    out
}

/// The new pages that open the new list's labels: `count` of them from index `at`, the
/// first labelled `spec`.
struct Lead {
    at: usize,
    count: usize,
    spec: Spec,
}

/// Where the new pages right before the first labelled page join the start of its range.
/// They take the numbers below its label while there are any. Numbers start at 1 (§12.4.2,
/// `/St`), so when there are too few the range starts at 1 on the first new page, and every
/// old page of that range is numbered up by the shortfall here, before the new pages after
/// them are numbered. Later ranges keep their labels. A prefix-only range (no style) has no
/// numbers: the new pages repeat its prefix. `None` when no new page comes first.
fn lead_into_first_range(was: &mut [Was]) -> Option<Lead> {
    let first = was.iter().position(|page| matches!(page, Was::Label(..)))?;
    let count = was
        .iter()
        .take(first)
        .rev()
        .take_while(|page| matches!(page, Was::New))
        .count();
    let at = first.checked_sub(count).filter(|_| count > 0)?;
    let Some(Was::Label(lead, range)) = was.get(first) else {
        return None;
    };
    let (mut lead, range) = (lead.clone(), *range);
    if lead.style.is_some() {
        let count_u64 = u64::try_from(count).unwrap_or(u64::MAX);
        let start = lead.value.saturating_sub(count_u64).max(1);
        let shift = start.saturating_add(count_u64).saturating_sub(lead.value);
        if shift > 0 {
            for page in was.iter_mut() {
                if let Was::Label(spec, r) = page
                    && *r == range
                {
                    spec.value = spec.value.saturating_add(shift);
                }
            }
        }
        lead.value = start;
    }
    Some(Lead { at, count, spec: lead })
}