use crate::page_object_helper::PageBox;
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
use crate::{Dictionary, Error, Object, ObjectRef, Pdf, Result};
use std::collections::BTreeSet;
use std::io::{Read, Seek};
pub struct AnnotationObjectHelper<'a, R: Read + Seek> {
annot_ref: ObjectRef,
pdf: &'a mut Pdf<R>,
}
impl<'a, R: Read + Seek> AnnotationObjectHelper<'a, R> {
pub fn new(annot_ref: ObjectRef, pdf: &'a mut Pdf<R>) -> Self {
Self { annot_ref, pdf }
}
fn resolve_dict(&mut self) -> Result<Dictionary> {
match self.pdf.resolve_borrowed(self.annot_ref)? {
Object::Dictionary(d) => Ok(d.clone()),
_ => Err(Error::Unsupported(format!(
"annotation object {} is not a dictionary",
self.annot_ref
))),
}
}
pub fn subtype(&mut self) -> Result<Option<Vec<u8>>> {
let dict = self.resolve_dict()?;
Ok(match dict.get("Subtype") {
Some(Object::Name(bytes)) => Some(bytes.clone()),
_ => None,
})
}
pub fn rect(&mut self) -> Result<Option<PageBox>> {
let dict = self.resolve_dict()?;
let val = match dict.get("Rect").cloned() {
None | Some(Object::Null) => return Ok(None),
Some(v) => v,
};
let arr = resolve_to_array(val, self.pdf, self.annot_ref, "Rect")?;
parse_rect_array(&arr, b"Rect").map(Some)
}
pub fn appearance(&mut self) -> Result<Option<Dictionary>> {
let dict = self.resolve_dict()?;
resolve_optional_dict(dict.get("AP").cloned(), self.pdf, self.annot_ref, "AP")
}
pub fn action(&mut self) -> Result<Option<Dictionary>> {
let dict = self.resolve_dict()?;
resolve_optional_dict(dict.get("A").cloned(), self.pdf, self.annot_ref, "A")
}
}
pub struct FormFieldObjectHelper<'a, R: Read + Seek> {
field_ref: ObjectRef,
pdf: &'a mut Pdf<R>,
}
impl<'a, R: Read + Seek> FormFieldObjectHelper<'a, R> {
pub fn new(field_ref: ObjectRef, pdf: &'a mut Pdf<R>) -> Self {
Self { field_ref, pdf }
}
pub fn field_type(&mut self) -> Result<Option<Vec<u8>>> {
self.resolve_inherited_name(b"FT")
}
pub fn field_value(&mut self) -> Result<Option<Object>> {
self.resolve_inherited_object(b"V")
}
pub fn field_default_value(&mut self) -> Result<Option<Object>> {
self.resolve_inherited_object(b"DV")
}
pub fn field_flags(&mut self) -> Result<Option<i64>> {
self.resolve_inherited_integer(b"Ff")
}
fn resolve_inherited_name(&mut self, key: &[u8]) -> Result<Option<Vec<u8>>> {
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut current = self.field_ref;
let mut depth: usize = 0;
loop {
if depth >= DEFAULT_MAX_PAGE_TREE_DEPTH {
return Err(Error::Unsupported(format!(
"field tree depth exceeds maximum of {} at {}",
DEFAULT_MAX_PAGE_TREE_DEPTH, current
)));
}
if !seen.insert(current) {
return Ok(None); }
let node_obj = self.pdf.resolve_borrowed(current)?;
let Some(dict) = node_obj.as_dict() else {
return Err(Error::Unsupported(format!(
"field tree node {current} is not a dictionary"
)));
};
if let Some(val) = dict.get(key).cloned() {
match val {
Object::Null => {} Object::Name(bytes) => return Ok(Some(bytes)),
_ => {} }
}
match dict.get("Parent").cloned() {
Some(Object::Reference(r)) => {
current = r;
depth += 1;
}
_ => return Ok(None),
}
}
}
fn resolve_inherited_object(&mut self, key: &[u8]) -> Result<Option<Object>> {
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut current = self.field_ref;
let mut depth: usize = 0;
loop {
if depth >= DEFAULT_MAX_PAGE_TREE_DEPTH {
return Err(Error::Unsupported(format!(
"field tree depth exceeds maximum of {} at {}",
DEFAULT_MAX_PAGE_TREE_DEPTH, current
)));
}
if !seen.insert(current) {
return Ok(None);
}
let node_obj = self.pdf.resolve_borrowed(current)?;
let Some(dict) = node_obj.as_dict() else {
return Err(Error::Unsupported(format!(
"field tree node {current} is not a dictionary"
)));
};
if let Some(val) = dict.get(key).cloned() {
match val {
Object::Null => {} other => return Ok(Some(other)),
}
}
match dict.get("Parent").cloned() {
Some(Object::Reference(r)) => {
current = r;
depth += 1;
}
_ => return Ok(None),
}
}
}
fn resolve_inherited_integer(&mut self, key: &[u8]) -> Result<Option<i64>> {
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut current = self.field_ref;
let mut depth: usize = 0;
loop {
if depth >= DEFAULT_MAX_PAGE_TREE_DEPTH {
return Err(Error::Unsupported(format!(
"field tree depth exceeds maximum of {} at {}",
DEFAULT_MAX_PAGE_TREE_DEPTH, current
)));
}
if !seen.insert(current) {
return Ok(None);
}
let node_obj = self.pdf.resolve_borrowed(current)?;
let Some(dict) = node_obj.as_dict() else {
return Err(Error::Unsupported(format!(
"field tree node {current} is not a dictionary"
)));
};
if let Some(val) = dict.get(key).cloned() {
match val {
Object::Null => {}
Object::Integer(n) => return Ok(Some(n)),
_ => {} }
}
match dict.get("Parent").cloned() {
Some(Object::Reference(r)) => {
current = r;
depth += 1;
}
_ => return Ok(None),
}
}
}
}
fn resolve_to_array<R: Read + Seek>(
val: Object,
pdf: &mut Pdf<R>,
origin: ObjectRef,
key: &str,
) -> Result<Vec<Object>> {
match val {
Object::Array(arr) => Ok(arr),
Object::Reference(r) => match pdf.resolve_borrowed(r)? {
Object::Array(arr) => Ok(arr.clone()),
_ => Err(Error::Unsupported(format!(
"/{key} reference {r} on object {origin} does not resolve to an array"
))),
},
_ => Err(Error::Unsupported(format!(
"/{key} on object {origin} has unexpected type"
))),
}
}
fn resolve_optional_dict<R: Read + Seek>(
val: Option<Object>,
pdf: &mut Pdf<R>,
origin: ObjectRef,
key: &str,
) -> Result<Option<Dictionary>> {
match val {
None | Some(Object::Null) => Ok(None),
Some(Object::Dictionary(d)) => Ok(Some(d)),
Some(Object::Reference(r)) => match pdf.resolve_borrowed(r)? {
Object::Dictionary(d) => Ok(Some(d.clone())),
Object::Null => Ok(None),
_ => Err(Error::Unsupported(format!(
"/{key} reference {r} on object {origin} does not resolve to a dictionary"
))),
},
Some(_) => Err(Error::Unsupported(format!(
"/{key} on object {origin} has unexpected type"
))),
}
}
fn parse_rect_array(arr: &[Object], key: &[u8]) -> Result<PageBox> {
if arr.len() != 4 {
return Err(Error::Unsupported(format!(
"/{} rectangle array has {} elements, expected 4",
String::from_utf8_lossy(key),
arr.len()
)));
}
let mut coords = [0f64; 4];
for (i, elem) in arr.iter().take(4).enumerate() {
coords[i] = match elem {
Object::Integer(n) => *n as f64,
Object::Real(r) => *r,
other => {
return Err(Error::Unsupported(format!(
"/{} rectangle element {i} has unexpected type {:?}",
String::from_utf8_lossy(key),
std::mem::discriminant(other)
)));
}
};
}
Ok(PageBox::new(coords[0], coords[1], coords[2], coords[3]))
}