laminapdf-model 0.9.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
//! Whether optional content is off as the document opens (ISO 32000-2 §8.11): an optional
//! content group against the default configuration's `/BaseState`, `/ON` and `/OFF`
//! (§8.11.4.3), and a membership dictionary by its visibility expression (`/VE`) or, without
//! one, its `/OCGs` and `/P` policy (§8.11.2.2).
//!
//! What can't be read or decided is [`Visibility::Unknown`]: a group the configuration's intent
//! ignores, one `/OCGs` doesn't list, one a usage application (`/AS`) names (a viewer may turn
//! it on or off for viewing, printing or exporting), one both `/ON` and `/OFF` list, a policy or expression no standard defines, an expression
//! longer than [`MAX_EXPRESSION`] items or nested deeper than [`MAX_DEPTH`]. A caller that
//! removes hidden content keeps unknown content and says so; [`Document::optional_content_off`]
//! counts it as on.

use std::collections::BTreeSet;

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

use crate::document::Document;

/// The most groups and operators one visibility expression or membership may hold before it
/// counts as [`Visibility::Unknown`].
const MAX_EXPRESSION: usize = 1_024;

/// How deep a visibility expression may nest before it counts as [`Visibility::Unknown`].
const MAX_DEPTH: usize = 32;

/// Whether content an `/OC` entry marks shows as the document opens (ISO 32000-2 §8.11).
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Visibility {
    /// It shows.
    Visible,
    /// The default configuration hides it.
    Hidden,
    /// Its state can't be decided: something it names is missing, malformed, outside the
    /// configuration's intent or beyond the evaluation's bounds.
    Unknown,
}

impl Visibility {
    /// Kleene's `and`: hidden when either is, visible when both are.
    const fn and(self, other: Self) -> Self {
        match (self, other) {
            (Self::Hidden, _) | (_, Self::Hidden) => Self::Hidden,
            (Self::Visible, Self::Visible) => Self::Visible,
            _ => Self::Unknown,
        }
    }

    /// Kleene's `or`: visible when either is, hidden when both are.
    const fn or(self, other: Self) -> Self {
        match (self, other) {
            (Self::Visible, _) | (_, Self::Visible) => Self::Visible,
            (Self::Hidden, Self::Hidden) => Self::Hidden,
            _ => Self::Unknown,
        }
    }

    const fn not(self) -> Self {
        match self {
            Self::Visible => Self::Hidden,
            Self::Hidden => Self::Visible,
            Self::Unknown => Self::Unknown,
        }
    }
}

/// The document's default optional content configuration (`/OCProperties /D`, §8.11.4.3), read
/// once: which groups exist and which are on.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OptionalContent {
    /// The groups `/OCGs` lists, by object number.
    groups: BTreeSet<u32>,
    base_off: bool,
    on: BTreeSet<u32>,
    off: BTreeSet<u32>,
    /// The groups a usage application (`/AS`) names: a viewer may turn them on or off for
    /// viewing, printing or exporting, so the default state alone doesn't decide them.
    usage: BTreeSet<u32>,
    /// The configuration's `/Intent` names; `None` for `All`.
    intents: Option<BTreeSet<Vec<u8>>>,
}

impl OptionalContent {
    /// The groups `/OCProperties /OCGs` lists, by object number.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn groups(&self) -> &BTreeSet<u32> {
        &self.groups
    }

    /// The listed groups the default configuration turns off, whatever their intent.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn off_groups(&self) -> BTreeSet<u32> {
        self.groups
            .iter()
            .copied()
            .filter(|g| !self.on(*g) || (self.on.contains(g) && self.off.contains(g)))
            .collect()
    }

    fn on(&self, group: u32) -> bool {
        if self.base_off {
            self.on.contains(&group)
        } else {
            !self.off.contains(&group)
        }
    }

    /// Whether the content that the `/OC` value `oc` marks (a group or a membership dictionary,
    /// by reference or direct) shows as the document opens. Its work is bounded: a membership
    /// or expression of more than 1,024 items, or nested more than 32 deep, is
    /// [`Visibility::Unknown`].
    ///
    /// # Errors
    /// Only what must propagate (strict mode, pending data, a source error).
    ///
    /// Added in 0.7.0.
    pub fn visibility(&self, doc: &Document, oc: &Object) -> Result<Visibility> {
        let mut left = MAX_EXPRESSION;
        let Some(dict) = doc.read(oc)?.and_then(|o| o.as_dict().cloned()) else {
            return Ok(Visibility::Unknown);
        };
        match name(doc, &dict, "Type")?.as_deref() {
            Some(b"OCG") => self.group(doc, oc, &dict),
            Some(b"OCMD") => self.membership(doc, &dict, &mut left),
            _ => Ok(Visibility::Unknown),
        }
    }

    /// A group, by reference: only a listed group within the configuration's intent counts.
    fn group(&self, doc: &Document, oc: &Object, dict: &Dict) -> Result<Visibility> {
        let Some(num) = oc.as_ref().map(|r| r.num) else {
            return Ok(Visibility::Unknown);
        };
        // A group in both `/ON` and `/OFF` is read either way by different viewers.
        let contradicted = self.on.contains(&num) && self.off.contains(&num);
        if !self.groups.contains(&num) || contradicted || self.usage.contains(&num) || !self.in_intent(doc, dict)? {
            return Ok(Visibility::Unknown);
        }
        Ok(if self.on(num) {
            Visibility::Visible
        } else {
            Visibility::Hidden
        })
    }

    /// Whether the group's `/Intent` (default `View`) meets the configuration's.
    fn in_intent(&self, doc: &Document, dict: &Dict) -> Result<bool> {
        let Some(config) = &self.intents else {
            return Ok(true);
        };
        let own = match dict.get("Intent") {
            Some(value) => names(doc, value)?,
            None => Some(BTreeSet::from([b"View".to_vec()])),
        };
        Ok(own.is_some_and(|own| !own.is_disjoint(config)))
    }

    /// A membership dictionary: its `/VE` when it has one, else `/OCGs` under `/P`.
    fn membership(&self, doc: &Document, dict: &Dict, left: &mut usize) -> Result<Visibility> {
        if let Some(ve) = dict.get("VE") {
            return self.expression(doc, ve, 0, left);
        }
        let members: Vec<Object> = match dict.get("OCGs") {
            None => Vec::new(),
            Some(value) => match doc.read(value)?.as_deref() {
                Some(Object::Array(items)) => items.clone(),
                Some(Object::Dict(_)) => vec![value.clone()],
                Some(Object::Null) | None => Vec::new(),
                Some(_) => return Ok(Visibility::Unknown),
            },
        };
        let mut states = Vec::with_capacity(members.len().min(MAX_EXPRESSION));
        for member in members.iter().filter(|m| !matches!(m, Object::Null)) {
            if !charge(left) {
                return Ok(Visibility::Unknown);
            }
            let state = match doc.read(member)?.and_then(|o| o.as_dict().cloned()) {
                Some(group) if name(doc, &group, "Type")?.as_deref() == Some(b"OCG") => {
                    self.group(doc, member, &group)?
                }
                _ => Visibility::Unknown,
            };
            states.push(state);
        }
        // No groups: the dictionary has no effect on visibility (§8.11.2.2).
        if states.is_empty() {
            return Ok(Visibility::Visible);
        }
        let all =
            |f: fn(Visibility) -> Visibility| states.iter().map(|s| f(*s)).fold(Visibility::Visible, Visibility::and);
        let any =
            |f: fn(Visibility) -> Visibility| states.iter().map(|s| f(*s)).fold(Visibility::Hidden, Visibility::or);
        let same = |s: Visibility| s;
        Ok(match name(doc, dict, "P")?.as_deref() {
            None | Some(b"AnyOn") => any(same),
            Some(b"AllOn") => all(same),
            Some(b"AnyOff") => any(Visibility::not),
            Some(b"AllOff") => all(Visibility::not),
            Some(_) => Visibility::Unknown,
        })
    }

    /// A visibility expression (§8.11.2.2, Table 98): a group, or `[/And …]`, `[/Or …]` or
    /// `[/Not e]`.
    fn expression(&self, doc: &Document, value: &Object, depth: usize, left: &mut usize) -> Result<Visibility> {
        if depth > MAX_DEPTH || !charge(left) {
            return Ok(Visibility::Unknown);
        }
        let Some(resolved) = doc.read(value)? else {
            return Ok(Visibility::Unknown);
        };
        match &*resolved {
            Object::Dict(group) if name(doc, group, "Type")?.as_deref() == Some(b"OCG") => {
                self.group(doc, value, group)
            }
            Object::Array(items) => {
                let Some((operator, operands)) = items.split_first() else {
                    return Ok(Visibility::Unknown);
                };
                let operator = match doc.read(operator)?.as_deref() {
                    Some(Object::Name(n)) => n.as_bytes().to_vec(),
                    _ => return Ok(Visibility::Unknown),
                };
                match (operator.as_slice(), operands) {
                    (b"Not", [only]) => Ok(self.expression(doc, only, depth + 1, left)?.not()),
                    (b"And" | b"Or", [_, ..]) => {
                        let and = operator == b"And";
                        let mut out = if and { Visibility::Visible } else { Visibility::Hidden };
                        for operand in operands {
                            let state = self.expression(doc, operand, depth + 1, left)?;
                            out = if and { out.and(state) } else { out.or(state) };
                        }
                        Ok(out)
                    }
                    _ => Ok(Visibility::Unknown),
                }
            }
            _ => Ok(Visibility::Unknown),
        }
    }
}

/// Takes one step of the bound; `false` when none is left.
fn charge(left: &mut usize) -> bool {
    match left.checked_sub(1) {
        Some(rest) => {
            *left = rest;
            true
        }
        None => false,
    }
}

/// The name at `key`, read through a reference.
fn name(doc: &Document, dict: &Dict, key: &str) -> Result<Option<Vec<u8>>> {
    Ok(match dict.get(key) {
        Some(value) => match doc.read(value)?.as_deref() {
            Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
            _ => None,
        },
        None => None,
    })
}

/// A name or an array of names, read through references; `None` when it is neither.
fn names(doc: &Document, value: &Object) -> Result<Option<BTreeSet<Vec<u8>>>> {
    Ok(match doc.read(value)?.as_deref() {
        Some(Object::Name(n)) => Some(BTreeSet::from([n.as_bytes().to_vec()])),
        Some(Object::Array(items)) => {
            let mut out = BTreeSet::new();
            for item in items.iter().take(MAX_EXPRESSION) {
                match doc.read(item)?.as_deref() {
                    Some(Object::Name(n)) => {
                        out.insert(n.as_bytes().to_vec());
                    }
                    _ => return Ok(None),
                }
            }
            Some(out)
        }
        _ => None,
    })
}

impl Document {
    /// The default optional content configuration (`/OCProperties /D`), read once; `None` for a
    /// document without one, whose `/OC` entries a viewer ignores. A group is named by its
    /// object number.
    ///
    /// # Errors
    /// Only what must propagate (strict mode, pending data, a source error).
    ///
    /// Added in 0.7.0.
    pub fn optional_content(&self) -> Result<Option<OptionalContent>> {
        let catalog = self.catalog()?;
        let Some(properties) = self.dict_of(catalog.get("OCProperties"))? else {
            return Ok(None);
        };
        let Some(d) = self.dict_of(properties.get("D"))? else {
            return Ok(None);
        };
        let refs = |value: Option<&Object>| -> Result<BTreeSet<u32>> {
            Ok(match value {
                Some(value) => self
                    .read(value)?
                    .as_deref()
                    .and_then(Object::as_array)
                    .map(|items| items.iter().filter_map(|i| i.as_ref().map(|r| r.num)).collect())
                    .unwrap_or_default(),
                None => BTreeSet::new(),
            })
        };
        let intents = match d.get("Intent") {
            None => Some(BTreeSet::from([b"View".to_vec()])),
            Some(value) => match names(self, value)? {
                Some(set) if set.contains(b"All".as_slice()) => None,
                Some(set) => Some(set),
                // An intent no one can read: no group meets it, so every group is unknown.
                None => Some(BTreeSet::new()),
            },
        };
        let mut usage = BTreeSet::new();
        if let Some(applications) = d.get("AS") {
            let applications = self.read(applications)?;
            for application in applications
                .as_deref()
                .and_then(Object::as_array)
                .unwrap_or_default()
                .iter()
                .take(MAX_EXPRESSION)
            {
                if let Some(app) = self.dict_of(Some(application))? {
                    usage.extend(refs(app.get("OCGs"))?);
                }
            }
        }
        Ok(Some(OptionalContent {
            usage,
            groups: refs(properties.get("OCGs"))?,
            base_off: name(self, &d, "BaseState")?.as_deref() == Some(b"OFF".as_slice()),
            on: refs(d.get("ON"))?,
            off: refs(d.get("OFF"))?,
            intents,
        }))
    }

    /// Whether the content that the `/OC` value `oc` marks (an optional content group or a
    /// membership dictionary, by reference) is hidden in the default configuration, as the
    /// document opens: [`OptionalContent::visibility`] is [`Visibility::Hidden`]. `false` for a
    /// document without optional content and for anything that can't be decided.
    ///
    /// # Errors
    /// Only what must propagate (strict mode, pending data, a source error).
    ///
    /// Added in 0.6.0.
    pub fn optional_content_off(&self, oc: &Object) -> Result<bool> {
        let Some(config) = self.optional_content()? else {
            return Ok(false);
        };
        Ok(config.visibility(self, oc)? == Visibility::Hidden)
    }

    fn dict_of(&self, value: Option<&Object>) -> Result<Option<Dict>> {
        Ok(match value {
            Some(value) => self.read(value)?.and_then(|o| o.as_dict().cloned()),
            None => None,
        })
    }
}

#[cfg(test)]
#[path = "optional_content_tests.rs"]
mod tests;