use std::collections::{BTreeMap, BTreeSet};
use laminapdf_cos::{Dict, ObjRef, Object, Result};
use crate::document::Document;
use crate::id::{OutlineItemId, PageId};
use crate::outline::{ActionKind, Destination, Outline};
use crate::page::Pages;
use crate::structure::kids_of;
use crate::values::read_name;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PageReference {
pub page: PageId,
pub kind: ReferenceKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReferenceKind {
OutlineItem {
item: OutlineItemId,
via: Via,
},
Link {
annot: ObjRef,
on: PageId,
via: Via,
},
NamedDestination {
name: Vec<u8>,
store: NameStore,
},
OpenAction {
via: Via,
},
StructElem {
elem: Option<ObjRef>,
},
StructContentRef {
elem: Option<ObjRef>,
index: usize,
kid: Option<ObjRef>,
},
Widget {
widget: ObjRef,
field: ObjRef,
by: WidgetLink,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Via {
Dest {
name: Option<Vec<u8>>,
},
GoTo {
action: Option<ObjRef>,
name: Option<Vec<u8>>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NameStore {
NameTree,
DestsDict,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WidgetLink {
P,
Annots,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PageReferences {
entries: Vec<PageReference>,
}
impl PageReferences {
#[must_use]
pub fn entries(&self) -> &[PageReference] {
&self.entries
}
pub fn to_page<'a>(&'a self, page: &'a PageId) -> impl Iterator<Item = &'a PageReference> + 'a {
self.entries.iter().filter(move |e| &e.page == page)
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl Document {
pub fn page_references(&self, pages: &[PageId]) -> Result<PageReferences> {
let all = self.pages()?;
let outline = all.outline()?;
let mut finder = Finder {
doc: self,
outline: &outline,
targets: pages.iter().cloned().collect(),
out: Vec::new(),
};
finder.outline_items()?;
let annots = finder.annotations(&all)?;
finder.named()?;
finder.open_action()?;
finder.structure()?;
finder.widgets(&all, &annots)?;
Ok(PageReferences { entries: finder.out })
}
}
struct Finder<'a, 'd> {
doc: &'d Document,
outline: &'a Outline<'d>,
targets: BTreeSet<PageId>,
out: Vec<PageReference>,
}
impl Finder<'_, '_> {
fn push(&mut self, dest: Option<&Destination>, kind: ReferenceKind) {
if let Some(page) = dest.and_then(|d| d.page.clone()).filter(|p| self.targets.contains(p)) {
self.out.push(PageReference { page, kind });
}
}
fn outline_items(&mut self) -> Result<()> {
let outline = self.outline;
for item in outline.iter() {
let (Some(id), Some(dict)) = (item.id(), item.dict()) else {
continue;
};
if let Some((dest, via)) = self.target(dict)? {
self.push(Some(&dest), ReferenceKind::OutlineItem { item: id.clone(), via });
}
}
Ok(())
}
fn annotations(&mut self, pages: &Pages<'_>) -> Result<BTreeMap<ObjRef, PageId>> {
let mut listed = BTreeMap::new();
for page in pages.iter() {
for annot in page.annots()? {
listed.entry(annot).or_insert_with(|| page.id().clone());
let Some(dict) = self.dict(&Object::Ref(annot))? else {
continue;
};
if let Some((dest, via)) = self.target(&dict)? {
let kind = ReferenceKind::Link {
annot,
on: page.id().clone(),
via,
};
self.push(Some(&dest), kind);
}
}
}
Ok(listed)
}
fn named(&mut self) -> Result<()> {
let doc = self.doc;
if let Some(tree) = doc.name_tree("Dests")? {
for (name, value) in tree.entries()? {
let dest = self.outline.destination(&value)?;
self.push(
dest.as_ref(),
ReferenceKind::NamedDestination {
name,
store: NameStore::NameTree,
},
);
}
}
let catalog = doc.catalog()?;
if let Some(dests) = catalog.get("Dests")
&& let Some(dests) = self.dict(dests)?
{
for (name, value) in dests.iter() {
let dest = self.outline.destination(value)?;
self.push(
dest.as_ref(),
ReferenceKind::NamedDestination {
name: name.as_bytes().to_vec(),
store: NameStore::DestsDict,
},
);
}
}
Ok(())
}
fn open_action(&mut self) -> Result<()> {
let catalog = self.doc.catalog()?;
let Some(value) = catalog.get("OpenAction") else {
return Ok(());
};
let Some(resolved) = self.doc.read(value)? else {
return Ok(());
};
let found = match &*resolved {
Object::Array(_) => self
.outline
.destination(value)?
.map(|dest| (Via::Dest { name: None }, dest)),
Object::Dict(action) => self.go_to(action, value.as_ref())?.map(|(dest, via)| (via, dest)),
_ => None,
};
if let Some((via, dest)) = found {
self.push(Some(&dest), ReferenceKind::OpenAction { via });
}
Ok(())
}
fn structure(&mut self) -> Result<()> {
let doc = self.doc;
let catalog = doc.catalog()?;
let Some(root) = catalog.get("StructTreeRoot") else {
return Ok(());
};
let Some(root) = self.dict(root)? else {
return Ok(());
};
let Some(k) = root.get("K") else {
return Ok(());
};
let max_depth = doc.limits().max_tree_depth();
let mut visited = BTreeSet::new();
let mut kids_found = Vec::new();
let mut stack: Vec<(Object, usize)> = kids_of(doc, k)?.into_iter().rev().map(|o| (o, 1)).collect();
while let Some((obj, depth)) = stack.pop() {
if depth > max_depth || obj.as_ref().is_some_and(|r| !visited.insert(r.num)) {
continue;
}
let Some(dict) = self.dict(&obj)? else { continue };
if is_content_ref(&dict) {
continue;
}
let elem = obj.as_ref();
if let Some(page) = self.own_page(&dict) {
self.out.push(PageReference {
page,
kind: ReferenceKind::StructElem { elem },
});
}
let items = match dict.get("K") {
Some(k) => kids_of(doc, k)?,
None => Vec::new(),
};
let mut children = Vec::new();
for (index, item) in items.into_iter().enumerate() {
if matches!(item, Object::Integer(_) | Object::Null) {
continue;
}
let Some(kid_dict) = self.dict(&item)? else { continue };
if !is_content_ref(&kid_dict) {
children.push((item, depth + 1));
} else if let Some(page) = self.own_page(&kid_dict) {
let kind = ReferenceKind::StructContentRef {
elem,
index,
kid: item.as_ref(),
};
kids_found.push(PageReference { page, kind });
}
}
stack.extend(children.into_iter().rev());
}
self.out.extend(kids_found);
Ok(())
}
fn own_page(&self, dict: &Dict) -> Option<PageId> {
dict.get("Pg")
.and_then(Object::as_ref)
.map(PageId::object)
.filter(|p| self.targets.contains(p))
}
fn widgets(&mut self, pages: &Pages<'_>, listed: &BTreeMap<ObjRef, PageId>) -> Result<()> {
let doc = self.doc;
let catalog = doc.catalog()?;
let Some(form) = catalog.get("AcroForm") else {
return Ok(());
};
let Some(form) = self.dict(form)? else {
return Ok(());
};
let fields = match form.get("Fields") {
Some(f) => doc.read(f)?.and_then(|a| a.as_array().map(<[Object]>::to_vec)),
None => None,
}
.unwrap_or_default();
let max_depth = doc.limits().max_tree_depth();
let mut seen = BTreeSet::new();
let mut stack: Vec<(Object, usize)> = fields.into_iter().rev().map(|f| (f, 0)).collect();
while let Some((obj, depth)) = stack.pop() {
let Some(r) = obj.as_ref() else { continue };
if depth > max_depth || !seen.insert(r.num) {
continue;
}
let Some(dict) = self.dict(&obj)? else { continue };
let kids = self.kids(&dict)?;
if kids.is_empty() {
if is_widget(&dict) {
self.widget(pages, listed, r, &dict, r);
}
continue;
}
let mut fields = Vec::new();
for (kid, kid_dict) in kids {
if !kid_dict.contains_key("T") && is_widget(&kid_dict) {
self.widget(pages, listed, kid, &kid_dict, r);
} else {
fields.push((Object::Ref(kid), depth + 1));
}
}
stack.extend(fields.into_iter().rev());
}
Ok(())
}
fn widget(
&mut self,
pages: &Pages<'_>,
listed: &BTreeMap<ObjRef, PageId>,
widget: ObjRef,
dict: &Dict,
field: ObjRef,
) {
let by_p = dict
.get("P")
.and_then(Object::as_ref)
.map(PageId::object)
.filter(|p| pages.index_of(p).is_some());
let (page, by) = match by_p {
Some(page) => (Some(page), WidgetLink::P),
None => (listed.get(&widget).cloned(), WidgetLink::Annots),
};
if let Some(page) = page.filter(|p| self.targets.contains(p)) {
self.out.push(PageReference {
page,
kind: ReferenceKind::Widget { widget, field, by },
});
}
}
fn kids(&self, dict: &Dict) -> Result<Vec<(ObjRef, Dict)>> {
let Some(kids) = dict.get("Kids") else {
return Ok(Vec::new());
};
let Some(kids) = self.doc.read(kids)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for kid in kids.as_array().unwrap_or_default() {
if let (Some(r), Some(d)) = (kid.as_ref(), self.dict(kid)?) {
out.push((r, d));
}
}
Ok(out)
}
fn target(&self, dict: &Dict) -> Result<Option<(Destination, Via)>> {
if let Some(dest) = dict.get("Dest")
&& let Some(dest) = self.outline.destination(dest)?
{
let name = dest.name.clone();
return Ok(Some((dest, Via::Dest { name })));
}
let Some(action) = dict.get("A") else {
return Ok(None);
};
let Some(resolved) = self.dict(action)? else {
return Ok(None);
};
self.go_to(&resolved, action.as_ref())
}
fn go_to(&self, action: &Dict, object: Option<ObjRef>) -> Result<Option<(Destination, Via)>> {
let kind = read_name(self.doc, action.get("S"))?;
if kind.map(|k| ActionKind::from_name(&k)) != Some(ActionKind::GoTo) {
return Ok(None);
}
let Some(d) = action.get("D") else {
return Ok(None);
};
Ok(self.outline.destination(d)?.map(|dest| {
let name = dest.name.clone();
(dest, Via::GoTo { action: object, name })
}))
}
fn dict(&self, value: &Object) -> Result<Option<Dict>> {
Ok(self.doc.read(value)?.and_then(|o| o.as_dict().cloned()))
}
}
fn is_content_ref(dict: &Dict) -> bool {
matches!(dict.get_name("Type"), Some(b"MCR" | b"OBJR"))
}
fn is_widget(dict: &Dict) -> bool {
dict.get_name("Subtype") == Some(b"Widget") || (dict.contains_key("Rect") && !dict.contains_key("Kids"))
}