use laminapdf_cos::{Dict, Object, Result};
use crate::document::Document;
use crate::geometry::{UserSpacePoint, UserSpaceRect};
use crate::outline::{ActionKind, Destination, Outline};
use crate::page::{HIDDEN_ANNOT_FLAGS, Page, number, read_rect};
use crate::values::{file_spec_name, read_name, text_of};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Link {
pub rect: UserSpaceRect,
pub quads: Vec<[UserSpacePoint; 4]>,
pub contents: Option<String>,
pub action: LinkAction,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LinkAction {
GoTo(Destination),
Uri(Vec<u8>),
OtherFile(Option<String>),
Named(Vec<u8>),
Other(ActionKind),
None,
}
impl Outline<'_> {
pub(crate) fn links(&self, page: &Page<'_>) -> Result<Vec<Link>> {
let doc = self.doc();
let Some(annots) = page.dict().get("Annots") else {
return Ok(Vec::new());
};
let Some(annots) = doc.read(annots)? else {
return Ok(Vec::new());
};
let mut links = Vec::new();
for entry in annots.as_array().unwrap_or_default() {
let Some(annot) = doc.read(entry)? else { continue };
let Some(annot) = annot.as_dict() else { continue };
if let Some(link) = self.link(annot)? {
links.push(link);
}
}
Ok(links)
}
fn link(&self, annot: &Dict) -> Result<Option<Link>> {
let doc = self.doc();
if !matches!(read_name(doc, annot.get("Subtype"))?.as_deref(), Some(b"Link")) {
return Ok(None);
}
let flags = match annot.get("F") {
Some(f) => doc.read(f)?.and_then(|f| f.as_int()).unwrap_or(0),
None => 0,
};
if flags & HIDDEN_ANNOT_FLAGS != 0 {
return Ok(None);
}
let Some(rect) = (match annot.get("Rect") {
Some(rect) => read_rect(doc, rect)?,
None => None,
}) else {
return Ok(None);
};
let contents = match annot.get("Contents") {
Some(c) => doc
.read(c)?
.as_deref()
.and_then(text_of)
.filter(|s| !s.trim().is_empty()),
None => None,
};
Ok(Some(Link {
rect,
quads: quads(doc, annot.get("QuadPoints"))?,
contents,
action: self.link_action(annot)?,
}))
}
fn link_action(&self, annot: &Dict) -> Result<LinkAction> {
let doc = self.doc();
if let Some(dest) = annot.get("Dest")
&& let Some(dest) = self.destination(dest)?
{
return Ok(LinkAction::GoTo(dest));
}
let Some(action) = annot.get("A") else {
return Ok(LinkAction::None);
};
let Some(action) = doc.read(action)? else {
return Ok(LinkAction::None);
};
let Some(action) = action.as_dict() else {
return Ok(LinkAction::None);
};
let Some(kind) = read_name(doc, action.get("S"))? else {
return Ok(LinkAction::None);
};
Ok(match ActionKind::from_name(&kind) {
ActionKind::GoTo => match action.get("D") {
Some(d) => self.destination(d)?.map_or(LinkAction::None, LinkAction::GoTo),
None => LinkAction::None,
},
ActionKind::Uri => match read_bytes(doc, action.get("URI"))? {
Some(uri) => LinkAction::Uri(uri),
None => LinkAction::None,
},
ActionKind::GoToR => LinkAction::OtherFile(file_name(doc, action.get("F"))?),
ActionKind::Named => match read_name(doc, action.get("N"))? {
Some(name) => LinkAction::Named(name),
None => LinkAction::None,
},
other => LinkAction::Other(other),
})
}
}
fn read_bytes(doc: &Document, value: Option<&Object>) -> Result<Option<Vec<u8>>> {
let Some(value) = value else { return Ok(None) };
Ok(match doc.read(value)?.as_deref() {
Some(Object::String(s)) => Some(s.bytes.clone()),
Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
_ => None,
})
}
fn file_name(doc: &Document, value: Option<&Object>) -> Result<Option<String>> {
let Some(value) = value else { return Ok(None) };
let Some(spec) = doc.read(value)? else { return Ok(None) };
let name = match &*spec {
Object::Dict(d) => file_spec_name(doc, d)?,
other => text_of(other),
};
Ok(name.filter(|n| !n.is_empty()))
}
fn quads(doc: &Document, value: Option<&Object>) -> Result<Vec<[UserSpacePoint; 4]>> {
let Some(value) = value else { return Ok(Vec::new()) };
let Some(array) = doc.read(value)? else {
return Ok(Vec::new());
};
let Some(items) = array.as_array() else {
return Ok(Vec::new());
};
if items.is_empty() || items.len() % 8 != 0 {
return Ok(Vec::new());
}
let mut values = Vec::with_capacity(items.len());
for item in items {
match number(doc, item)? {
Some(v) => values.push(v),
None => return Ok(Vec::new()),
}
}
let (groups, _) = values.as_chunks::<8>();
Ok(groups
.iter()
.map(|&[x0, y0, x1, y1, x2, y2, x3, y3]| {
[
UserSpacePoint::new(x0, y0),
UserSpacePoint::new(x1, y1),
UserSpacePoint::new(x2, y2),
UserSpacePoint::new(x3, y3),
]
})
.collect())
}