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
//! Which annotations lie wholly off their page: what `laminapdf reveal` counts and the
//! sanitiser removes (ISO 32000-2 §12.5, §14.11.2).

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

use laminapdf_cos::{Result, tolerant};

use crate::annot::{AnnotFlags, AnnotGeometry, AnnotLink, AnnotSubtype};
use crate::document::Document;
use crate::geometry::{PageFrame, Pt, RectPt, UserSpacePoint, UserSpaceRect};
use crate::id::AnnotId;
use crate::page::read_rect;

/// The smallest side, in user space units, a viewer is taken to draw a note's icon at: its
/// size is the viewer's choice, whatever `/Rect` says.
const ICON: f64 = 24.0;

/// How an annotation whose `/Rect` lies wholly outside the page stands.
///
/// Added in 0.9.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OffPage {
    /// Nothing of it reaches the page.
    Outside,
    /// A viewer may draw it onto the page. Either it doesn't scale or turn with the page
    /// (`NoZoom`, `NoRotate`, or a `Text` note, §12.5.3 and §12.5.6.4), and drawn at 100 %
    /// upright from its upper-left corner it reaches the page; or it has no appearance, and
    /// the points a viewer draws one from (`/QuadPoints`, `/InkList`, `/Vertices`, `/L`,
    /// `/CL`) reach the page.
    MayReach,
}

/// Whether `rect` shares nothing with a page of `width` by `height`. A rectangle without area
/// must lie past an edge, not on it: `[0 0 0 0]` marks a corner, not a place off the page.
fn beyond(rect: &RectPt, width: Pt, height: Pt) -> bool {
    if rect.x1 > rect.x0 && rect.y1 > rect.y0 {
        return rect.outside_page(width, height);
    }
    rect.x1 < Pt::ZERO || rect.y1 < Pt::ZERO || rect.x0 > width || rect.y0 > height
}

/// Where an annotation with this `/Rect`, subtype and flags stands on `frame`'s page; `None`
/// when its `/Rect` meets the page.
fn place(rect: &UserSpaceRect, subtype: &AnnotSubtype, flags: AnnotFlags, frame: &PageFrame) -> Option<OffPage> {
    let (width, height) = (frame.width(), frame.height());
    if !beyond(&frame.rect_to_page(rect), width, height) {
        return None;
    }
    let note = *subtype == AnnotSubtype::Text;
    if !note && !flags.has(AnnotFlags::NO_ZOOM) && !flags.has(AnnotFlags::NO_ROTATE) {
        return Some(OffPage::Outside);
    }
    let least = if note { ICON } else { 0.0 };
    let unit = frame.user_unit();
    let corner = frame.to_page(UserSpacePoint::new(rect.x0, rect.y1));
    let upright = RectPt::new(
        corner.x,
        corner.y,
        corner.x + Pt::new((rect.x1 - rect.x0).max(least) * unit),
        corner.y + Pt::new((rect.y1 - rect.y0).max(least) * unit),
    );
    Some(if beyond(&upright, width, height) {
        OffPage::Outside
    } else {
        OffPage::MayReach
    })
}

/// The smallest rectangle around the points of `geometry` that a viewer draws an annotation
/// without an appearance from.
fn bounds(geometry: &AnnotGeometry) -> Option<UserSpaceRect> {
    match geometry {
        AnnotGeometry::Quads(quads) => UserSpaceRect::around(quads.iter().flatten().copied()),
        AnnotGeometry::Ink(strokes) => UserSpaceRect::around(strokes.iter().flatten().copied()),
        AnnotGeometry::Vertices(points) | AnnotGeometry::Callout(points) => {
            UserSpaceRect::around(points.iter().copied())
        }
        AnnotGeometry::Line(ends) => UserSpaceRect::around(*ends),
        _ => None,
    }
}

impl Document {
    /// The annotations that lie wholly outside the page (its `CropBox`) on every page that
    /// lists them, by their `/Rect`. A popup with a parent that a page lists, by its `/Parent`
    /// or the parent's `/Popup`, isn't judged: it follows its parent, wherever its own window
    /// sits. An annotation without a readable `/Rect` isn't listed.
    ///
    /// # Errors
    /// The reading errors that must propagate.
    ///
    /// Added in 0.9.0.
    pub fn off_page_annotations(&self) -> Result<BTreeMap<AnnotId, OffPage>> {
        let pages = self.pages()?;
        let mut links: Vec<AnnotLink> = Vec::new();
        let mut places: Vec<(AnnotId, Option<OffPage>)> = Vec::new();
        for page in pages.iter() {
            let frame = tolerant(page.frame())?;
            self.each_annotation(&page, |id, index, dict| {
                let link = self.link(id.clone(), index, dict)?;
                let rect = match dict.get("Rect") {
                    Some(rect) => read_rect(self, rect)?,
                    None => None,
                };
                let mut at = rect
                    .zip(frame.as_ref())
                    .and_then(|(r, frame)| place(&r, &link.subtype, link.flags, frame));
                if at == Some(OffPage::Outside)
                    && !self.has_normal_appearance(dict)?
                    && let Some(frame) = &frame
                    && let Some(points) = bounds(&self.geometry(&link.subtype, dict)?)
                    && !beyond(&frame.rect_to_page(&points), frame.width(), frame.height())
                {
                    at = Some(OffPage::MayReach);
                }
                places.push((id, at));
                links.push(link);
                Ok(())
            })?;
        }
        let listed: BTreeSet<&AnnotId> = links.iter().map(|l| &l.id).collect();
        let followers: BTreeSet<&AnnotId> = links
            .iter()
            .flat_map(|l| {
                let by_parent = l
                    .parent
                    .as_ref()
                    .filter(|p| **p != l.id && listed.contains(p))
                    .map(|_| &l.id);
                let named = l.popup.as_ref().filter(|p| **p != l.id);
                by_parent.into_iter().chain(named)
            })
            .collect();
        let popups: BTreeSet<&AnnotId> = links
            .iter()
            .filter(|l| l.subtype == AnnotSubtype::Popup)
            .map(|l| &l.id)
            .collect();
        let mut out: BTreeMap<AnnotId, OffPage> = BTreeMap::new();
        let mut on_page: BTreeSet<AnnotId> = BTreeSet::new();
        for (id, at) in places {
            if popups.contains(&id) && followers.contains(&id) {
                continue;
            }
            match at {
                None => {
                    on_page.insert(id);
                }
                Some(at) => {
                    let known = out.entry(id).or_insert(at);
                    if at == OffPage::MayReach {
                        *known = at;
                    }
                }
            }
        }
        out.retain(|id, _| !on_page.contains(id));
        Ok(out)
    }
}