use std::collections::BTreeSet;
use laminapdf_cos::{Dict, DirectPath, ObjRef, Object, PathSegment, Result, Warning};
use crate::document::Document;
use crate::geometry::{UserSpacePoint, UserSpaceRect};
use crate::id::AnnotId;
use crate::link::quads;
use crate::page::{Page, number, read_rect};
use crate::values::read_name;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Annot {
pub id: AnnotId,
pub index: usize,
pub subtype: AnnotSubtype,
pub rect: Option<UserSpaceRect>,
pub contents: Option<String>,
pub name: Option<String>,
pub modified: Option<String>,
pub flags: AnnotFlags,
pub color: Vec<f64>,
pub opacity: Option<f64>,
pub author: Option<String>,
pub subject: Option<String>,
pub created: Option<String>,
pub in_reply_to: Option<AnnotId>,
pub reply_type: ReplyType,
pub popup: Option<AnnotId>,
pub parent: Option<AnnotId>,
pub has_appearance: bool,
pub has_rich_text: bool,
pub geometry: AnnotGeometry,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AnnotLink {
pub id: AnnotId,
pub index: usize,
pub subtype: AnnotSubtype,
pub flags: AnnotFlags,
pub in_reply_to: Option<AnnotId>,
pub reply_type: ReplyType,
pub popup: Option<AnnotId>,
pub parent: Option<AnnotId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AnnotSubtype {
Text,
Link,
FreeText,
Line,
Square,
Circle,
Polygon,
PolyLine,
Highlight,
Underline,
Squiggly,
StrikeOut,
Caret,
Stamp,
Ink,
Popup,
FileAttachment,
Sound,
Widget,
Redact,
Other(Vec<u8>),
}
impl AnnotSubtype {
fn from_name(name: &[u8]) -> Self {
match name {
b"Text" => Self::Text,
b"Link" => Self::Link,
b"FreeText" => Self::FreeText,
b"Line" => Self::Line,
b"Square" => Self::Square,
b"Circle" => Self::Circle,
b"Polygon" => Self::Polygon,
b"PolyLine" => Self::PolyLine,
b"Highlight" => Self::Highlight,
b"Underline" => Self::Underline,
b"Squiggly" => Self::Squiggly,
b"StrikeOut" => Self::StrikeOut,
b"Caret" => Self::Caret,
b"Stamp" => Self::Stamp,
b"Ink" => Self::Ink,
b"Popup" => Self::Popup,
b"FileAttachment" => Self::FileAttachment,
b"Sound" => Self::Sound,
b"Widget" => Self::Widget,
b"Redact" => Self::Redact,
other => Self::Other(other.to_vec()),
}
}
#[must_use]
pub fn name(&self) -> &[u8] {
match self {
Self::Text => b"Text",
Self::Link => b"Link",
Self::FreeText => b"FreeText",
Self::Line => b"Line",
Self::Square => b"Square",
Self::Circle => b"Circle",
Self::Polygon => b"Polygon",
Self::PolyLine => b"PolyLine",
Self::Highlight => b"Highlight",
Self::Underline => b"Underline",
Self::Squiggly => b"Squiggly",
Self::StrikeOut => b"StrikeOut",
Self::Caret => b"Caret",
Self::Stamp => b"Stamp",
Self::Ink => b"Ink",
Self::Popup => b"Popup",
Self::FileAttachment => b"FileAttachment",
Self::Sound => b"Sound",
Self::Widget => b"Widget",
Self::Redact => b"Redact",
Self::Other(name) => name,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct AnnotFlags(pub u32);
impl AnnotFlags {
pub const INVISIBLE: u32 = 1;
pub const HIDDEN: u32 = 1 << 1;
pub const PRINT: u32 = 1 << 2;
pub const NO_ZOOM: u32 = 1 << 3;
pub const NO_ROTATE: u32 = 1 << 4;
pub const NO_VIEW: u32 = 1 << 5;
pub const READ_ONLY: u32 = 1 << 6;
pub const LOCKED: u32 = 1 << 7;
pub const TOGGLE_NO_VIEW: u32 = 1 << 8;
pub const LOCKED_CONTENTS: u32 = 1 << 9;
#[must_use]
pub const fn has(self, flag: u32) -> bool {
self.0 & flag == flag
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ReplyType {
#[default]
Reply,
Group,
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub enum AnnotGeometry {
#[default]
None,
Quads(Vec<[UserSpacePoint; 4]>),
Ink(Vec<Vec<UserSpacePoint>>),
Vertices(Vec<UserSpacePoint>),
Line([UserSpacePoint; 2]),
Callout(Vec<UserSpacePoint>),
}
impl Document {
pub fn annotations(&self, page: &Page<'_>) -> Result<Vec<Annot>> {
let mut found = Vec::new();
self.each_annotation(page, |id, index, dict| {
let link = self.link(id, index, dict)?;
found.push(self.annotation(link, dict)?);
Ok(())
})?;
pair_popups(&mut found, |a| (&a.id, a.parent.as_ref(), &mut a.popup));
self.check_names(&found)?;
Ok(found)
}
pub fn annotation_links(&self, page: &Page<'_>) -> Result<Vec<AnnotLink>> {
let mut found = Vec::new();
self.each_annotation(page, |id, index, dict| {
found.push(self.link(id, index, dict)?);
Ok(())
})?;
pair_popups(&mut found, |a| (&a.id, a.parent.as_ref(), &mut a.popup));
Ok(found)
}
fn each_annotation(&self, page: &Page<'_>, mut f: impl FnMut(AnnotId, usize, &Dict) -> Result<()>) -> Result<()> {
let Some(value) = page.dict().get("Annots") else {
return Ok(());
};
let Some(array) = self.read(value)? else {
return Ok(());
};
let array_ref = value.as_ref();
for (index, entry) in array.as_array().unwrap_or_default().iter().enumerate() {
let Some(dict) = self.read(entry)? else { continue };
let Some(dict) = dict.as_dict() else { continue };
let id = match entry.as_ref() {
Some(r) => AnnotId::object(r),
None => AnnotId::path(&direct_path(page, array_ref, index)),
};
f(id, index, dict)?;
}
Ok(())
}
fn link(&self, id: AnnotId, index: usize, dict: &Dict) -> Result<AnnotLink> {
let subtype = AnnotSubtype::from_name(&read_name(self, dict.get("Subtype"))?.unwrap_or_default());
let flags = match dict.get("F") {
Some(f) => self.read(f)?.and_then(|f| f.as_int()).unwrap_or(0),
None => 0,
};
Ok(AnnotLink {
id,
index,
flags: AnnotFlags(u32::try_from(flags).unwrap_or(0)),
in_reply_to: dict.get("IRT").and_then(Object::as_ref).map(AnnotId::object),
reply_type: match read_name(self, dict.get("RT"))?.as_deref() {
Some(b"Group") => ReplyType::Group,
_ => ReplyType::Reply,
},
popup: dict.get("Popup").and_then(Object::as_ref).map(AnnotId::object),
parent: if subtype == AnnotSubtype::Popup {
dict.get("Parent").and_then(Object::as_ref).map(AnnotId::object)
} else {
None
},
subtype,
})
}
fn annotation(&self, link: AnnotLink, dict: &Dict) -> Result<Annot> {
let geometry = self.geometry(&link.subtype, dict)?;
Ok(Annot {
rect: match dict.get("Rect") {
Some(rect) => read_rect(self, rect)?,
None => None,
},
contents: self.text_entry(dict, "Contents")?,
name: self.text_entry(dict, "NM")?,
modified: self.text_entry(dict, "M")?,
color: self.numbers(dict.get("C"))?.unwrap_or_default(),
opacity: match dict.get("CA") {
Some(ca) => number(self, ca)?,
None => None,
},
author: self.text_entry(dict, "T")?,
subject: self.text_entry(dict, "Subj")?,
created: self.text_entry(dict, "CreationDate")?,
has_appearance: self.has_normal_appearance(dict)?,
has_rich_text: dict.get("RC").is_some(),
id: link.id,
index: link.index,
subtype: link.subtype,
flags: link.flags,
in_reply_to: link.in_reply_to,
reply_type: link.reply_type,
popup: link.popup,
parent: link.parent,
geometry,
})
}
fn geometry(&self, subtype: &AnnotSubtype, dict: &Dict) -> Result<AnnotGeometry> {
Ok(match subtype {
AnnotSubtype::Highlight
| AnnotSubtype::Underline
| AnnotSubtype::Squiggly
| AnnotSubtype::StrikeOut
| AnnotSubtype::Redact => AnnotGeometry::Quads(quads(self, dict.get("QuadPoints"))?),
AnnotSubtype::Ink => {
let mut strokes = Vec::new();
if let Some(list) = dict.get("InkList")
&& let Some(list) = self.read(list)?
{
for stroke in list.as_array().unwrap_or_default() {
strokes.push(self.points(Some(stroke))?.unwrap_or_default());
}
}
AnnotGeometry::Ink(strokes)
}
AnnotSubtype::Polygon | AnnotSubtype::PolyLine => {
AnnotGeometry::Vertices(self.points(dict.get("Vertices"))?.unwrap_or_default())
}
AnnotSubtype::Line => match self.points(dict.get("L"))?.as_deref() {
Some(&[a, b]) => AnnotGeometry::Line([a, b]),
_ => AnnotGeometry::None,
},
AnnotSubtype::FreeText => match self.points(dict.get("CL"))? {
Some(points) if points.len() >= 2 => AnnotGeometry::Callout(points),
_ => AnnotGeometry::None,
},
_ => AnnotGeometry::None,
})
}
fn numbers(&self, value: Option<&Object>) -> Result<Option<Vec<f64>>> {
let Some(value) = value else { return Ok(None) };
let Some(array) = self.read(value)? else {
return Ok(None);
};
let Some(items) = array.as_array() else { return Ok(None) };
let mut out = Vec::with_capacity(items.len());
for item in items {
match number(self, item)? {
Some(v) => out.push(v),
None => return Ok(None),
}
}
Ok(Some(out))
}
fn points(&self, value: Option<&Object>) -> Result<Option<Vec<UserSpacePoint>>> {
Ok(self.numbers(value)?.filter(|n| n.len().is_multiple_of(2)).map(|n| {
let (pairs, _) = n.as_chunks::<2>();
pairs.iter().map(|&[x, y]| UserSpacePoint::new(x, y)).collect()
}))
}
fn has_normal_appearance(&self, dict: &Dict) -> Result<bool> {
let Some(ap) = dict.get("AP") else { return Ok(false) };
let Some(ap) = self.read(ap)? else { return Ok(false) };
Ok(ap.as_dict().and_then(|ap| ap.get("N")).is_some())
}
fn check_names(&self, found: &[Annot]) -> Result<()> {
let mut seen = BTreeSet::new();
for annot in found {
if let Some(name) = &annot.name
&& !seen.insert(name.as_str())
{
self.warn(Warning::AnnotNameDuplicate {
object: annot.id.as_lamina_id().obj_ref().map(|r: ObjRef| r.num),
})?;
}
}
Ok(())
}
}
fn direct_path(page: &Page<'_>, array: Option<ObjRef>, index: usize) -> DirectPath {
match array {
Some(array) => DirectPath::new(Some(array), vec![PathSegment::Index(index)]),
None => DirectPath::new(
page.obj_ref(),
vec![PathSegment::Key("Annots"), PathSegment::Index(index)],
),
}
}
fn pair_popups<T>(found: &mut [T], fields: impl Fn(&mut T) -> (&AnnotId, Option<&AnnotId>, &mut Option<AnnotId>)) {
let mut pairs = Vec::new();
for a in found.iter_mut() {
let (id, parent, _) = fields(a);
if let Some(parent) = parent {
pairs.push((parent.clone(), id.clone()));
}
}
for (parent, popup) in pairs {
for a in found.iter_mut() {
let (id, _, slot) = fields(a);
if *id == parent && slot.is_none() {
*slot = Some(popup);
break;
}
}
}
}