use std::fmt;
use std::ops;
use std::sync::Arc;
use laminapdf_cos::{ObjRef, Object, OpenOptions, Result, Source, Warning};
use crate::id::IdAllocator;
use crate::info::Info;
use crate::labels::PageLabels;
use crate::outline::Outline;
use crate::page::Pages;
use crate::tree::{NameTree, NumberTree};
use crate::xmp;
pub struct Document {
cos: laminapdf_cos::Document,
}
const _: () = {
const fn assert_send<T: Send>() {}
assert_send::<Document>();
};
impl fmt::Debug for Document {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Document")
.field("cos", &self.cos)
.finish_non_exhaustive()
}
}
impl From<laminapdf_cos::Document> for Document {
fn from(cos: laminapdf_cos::Document) -> Self {
Self { cos }
}
}
impl ops::Deref for Document {
type Target = laminapdf_cos::Document;
fn deref(&self) -> &laminapdf_cos::Document {
&self.cos
}
}
impl Document {
pub fn open(source: impl Into<Source>, options: OpenOptions) -> Result<Self> {
laminapdf_cos::Document::open(source, options).map(Self::from)
}
#[must_use]
pub const fn cos(&self) -> &laminapdf_cos::Document {
&self.cos
}
pub const fn cos_mut(&mut self) -> &mut laminapdf_cos::Document {
&mut self.cos
}
#[must_use]
pub fn into_cos(self) -> laminapdf_cos::Document {
self.cos
}
#[must_use]
pub const fn ids(&self) -> IdAllocator<'_> {
IdAllocator::new(&self.cos)
}
pub fn xmp_packet(&self) -> Result<Option<Vec<u8>>> {
let catalog = self.catalog()?;
let Some(metadata) = catalog.get("Metadata") else {
return Ok(None);
};
let Some(object) = self.read(metadata)? else {
return Ok(None);
};
let Object::Stream(stream) = &*object else {
return Ok(None);
};
tolerant(self.decode_stream(stream))
}
pub fn xmp(&self) -> Result<xmp::PacketState> {
let Some(bytes) = self.xmp_packet()? else {
return Ok(xmp::PacketState::Absent);
};
match xmp::Packet::parse(&bytes) {
Ok(packet) => {
let repairs = packet.repairs();
for (repaired, reason) in [
(repairs.header_encoding, "header-encoding"),
(repairs.undeclared_prefix, "undeclared-prefix"),
] {
if repaired {
let object = self.catalog()?.get("Metadata").and_then(Object::as_ref).map(|r| r.num);
self.warn(Warning::XmpRepaired { object, reason })?;
}
}
Ok(xmp::PacketState::Parsed(packet))
}
Err(error) => {
let object = self.catalog()?.get("Metadata").and_then(Object::as_ref).map(|r| r.num);
self.warn(Warning::XmpInvalid {
object,
offset: error.offset(),
reason: error.reason(),
})?;
Ok(xmp::PacketState::Malformed { bytes, error })
}
}
}
pub fn version(&self) -> Result<Option<String>> {
let header = self.header_version().filter(|v| version_number(v).is_some());
let catalog = self.catalog()?;
let declared = catalog
.get_name("Version")
.and_then(|name| std::str::from_utf8(name).ok())
.filter(|v| version_number(v).is_some());
let later = match (header, declared) {
(Some(header), Some(declared)) if version_number(declared) > version_number(header) => Some(declared),
(Some(header), _) => Some(header),
(None, declared) => declared,
};
Ok(later.map(str::to_owned))
}
pub fn is_pdf2(&self) -> Result<bool> {
Ok(self
.version()?
.as_deref()
.and_then(version_number)
.is_some_and(|(major, _)| major >= 2))
}
pub fn pages(&self) -> Result<Pages<'_>> {
Pages::new(self)
}
pub fn is_tagged(&self) -> Result<bool> {
let catalog = self.catalog()?;
let Some(mark_info) = catalog.get("MarkInfo") else {
return Ok(false);
};
let mark_info = self.deref(mark_info)?;
let marked = mark_info.as_dict().and_then(|d| d.get("Marked"));
Ok(matches!(marked, Some(Object::Bool(true))))
}
pub fn outline(&self) -> Result<Outline<'_>> {
Outline::new(self)
}
pub fn structure(&self) -> Result<Option<crate::StructTree>> {
crate::structure::read(self)
}
pub fn info(&self) -> Result<Option<Info<'_>>> {
Info::new(self)
}
pub fn page_labels(&self) -> Result<PageLabels> {
PageLabels::new(self)
}
pub fn name_tree(&self, key: &str) -> Result<Option<NameTree<'_>>> {
let catalog = self.catalog()?;
let Some(names) = catalog.get("Names") else {
return Ok(None);
};
let resolved = tolerant(self.cos.deref(names))?;
match resolved.as_deref() {
Some(Object::Dict(names)) => Ok(names.get(key).map(|root| NameTree::new(self, root.clone()))),
Some(Object::Null) => Ok(None),
_ => {
self.warn(Warning::InvalidEntry {
object: self.trailer().get("Root").and_then(Object::as_ref).map(|r| r.num),
key: "Names",
})?;
Ok(None)
}
}
}
#[must_use]
pub fn number_tree(&self, root: Object) -> NumberTree<'_> {
NumberTree::new(self, root)
}
pub(crate) fn warn(&self, warning: Warning) -> Result<()> {
self.cos.report(warning)
}
pub(crate) fn text_entry(&self, dict: &laminapdf_cos::Dict, key: &str) -> Result<Option<String>> {
let Some(value) = dict.get(key) else {
return Ok(None);
};
Ok(match self.read(value)?.as_deref() {
Some(Object::String(s)) => Some(laminapdf_syntax::text::decode_text_string(&s.bytes)),
_ => None,
})
}
pub(crate) fn read(&self, obj: &Object) -> Result<Option<Arc<Object>>> {
Ok(tolerant(self.cos.deref(obj))?.map(laminapdf_cos::Resolved::into_arc))
}
}
pub(crate) use laminapdf_cos::tolerant;
pub(crate) fn object_number(obj: &Object) -> Option<u32> {
obj.as_ref().map(|r: ObjRef| r.num)
}
fn version_number(version: &str) -> Option<(u32, u32)> {
let (major, minor) = version.split_once('.')?;
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
if !(digits(major) && digits(minor)) {
return None;
}
Some((major.parse().ok()?, minor.parse().ok()?))
}