#[cfg(not(feature = "qtest-driver"))]
pub(crate) mod repair;
#[cfg(feature = "qtest-driver")]
#[doc(hidden)]
pub mod repair;
pub mod tree_rebuild;
use crate::object_handle::ObjectHandleIdentity;
use crate::pipeline::buffer::Buffer;
use crate::{Error, ObjectHandle, ObjectRef, Pdf, Result};
use std::collections::{BTreeSet, HashSet};
use std::fmt;
use std::io::{Read, Seek};
pub const DEFAULT_MAX_PAGE_TREE_DEPTH: usize = 100;
#[derive(Debug, Clone)]
pub(crate) struct PageParentCursor {
handle: ObjectHandle,
}
impl PageParentCursor {
pub(crate) fn from_handle(handle: ObjectHandle) -> Self {
Self { handle }
}
pub(crate) fn handle(&self) -> ObjectHandle {
self.handle.clone()
}
}
impl fmt::Display for PageParentCursor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.handle.object_ref() {
Some(reference) => write!(f, "{reference}"),
None => f.write_str("direct page-tree dictionary"),
}
}
}
pub(crate) fn page_parent_entries<R: Read + Seek>(
pdf: &mut Pdf<R>,
cursor: &PageParentCursor,
key: &[u8],
) -> Result<Option<(ObjectHandle, ObjectHandle)>> {
let dict = cursor.handle();
pdf.resolve(&dict)?;
Ok(Some((
dict.try_get_key(key)?,
dict.try_get_key(b"/Parent")?,
)))
}
pub(crate) fn next_page_parent(parent: ObjectHandle) -> Result<Option<PageParentCursor>> {
if parent.is_null() {
return Ok(None);
}
if parent.is_indirect() && !parent.is_resolved() {
return Ok(Some(PageParentCursor::from_handle(parent)));
}
if parent.as_dictionary().is_none() {
return Ok(None);
}
Ok(Some(PageParentCursor::from_handle(parent)))
}
pub(crate) fn is_inheritable_page_attribute(key: &[u8]) -> bool {
matches!(key, b"/MediaBox" | b"/CropBox" | b"/Resources" | b"/Rotate")
}
pub(crate) fn resolve_inherited_handle_from_node_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
node: ObjectHandle,
key: &[u8],
max_depth: usize,
) -> Result<Option<ObjectHandle>> {
let mut seen: Vec<ObjectHandle> = Vec::new();
let mut current = PageParentCursor::from_handle(node);
let mut depth = 0usize;
let inheritable = is_inheritable_page_attribute(key);
loop {
if depth >= max_depth {
return Err(Error::Unsupported(format!(
"page tree depth exceeds maximum of {max_depth} at {current}"
)));
}
let current_handle = current.handle();
if seen
.iter()
.any(|seen_handle| seen_handle.is_same_object_as(¤t_handle))
{
return Ok(None);
}
seen.push(current_handle);
let Some((value, parent)) = page_parent_entries(pdf, ¤t, key)? else {
return Ok(None);
};
let terminal = pdf.resolve_handle(&value)?;
if !terminal.try_is_null()? {
return Ok(Some(value));
}
if !inheritable {
return Ok(None);
}
let Some(parent) = next_page_parent(parent)? else {
return Ok(None);
};
current = parent;
depth += 1;
}
}
pub(crate) fn resolve_inherited_handle_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
key: &[u8],
max_depth: usize,
) -> Result<Option<ObjectHandle>> {
let page = pdf.get_object_handle(page_ref);
resolve_inherited_handle_from_node_with_max_depth(pdf, page, key, max_depth)
}
pub fn page_refs<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Vec<ObjectRef>> {
page_refs_with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn page_refs_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
max_depth: usize,
) -> Result<Vec<ObjectRef>> {
pdf.mark_get_all_pages_called();
PageWalk::with_max_depth(pdf, max_depth)?.collect()
}
pub fn page_content_bytes<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<Vec<u8>> {
let page = pdf.get_object_handle(page_ref);
pdf.resolve(&page)?;
if page.as_dictionary().is_none() {
return Err(Error::Unsupported(format!(
"object {page_ref} is not a dictionary, cannot extract /Contents"
)));
}
let page_type = page.try_get_key(b"/Type")?;
match page_type.try_as_name()? {
Some(name) if name.as_slice() == b"Page" => {}
Some(name) => {
return Err(Error::Unsupported(format!(
"object {page_ref} has /Type /{}, expected /Page",
String::from_utf8_lossy(&name)
)));
}
None if page.has_key(b"/Type") => {
return Err(Error::Unsupported(format!(
"object {page_ref} has a non-name /Type entry"
)));
}
None => {
return Err(Error::Unsupported(format!(
"object {page_ref} has no /Type entry"
)));
}
}
let streams = page.get_page_contents()?;
if streams.is_empty() {
return Ok(Vec::new());
}
let normalized_contents = ObjectHandle::array(streams);
let mut buffer = Buffer::new("page content bytes", None);
let mut all_description = String::new();
normalized_contents.pipe_content_streams(
&mut buffer,
&format!("page object {page_ref}"),
&mut all_description,
)?;
Ok(buffer.take_buffer()?)
}
#[derive(Clone)]
enum PageNode {
Indirect(ObjectRef),
Direct(ObjectHandle),
}
impl PageNode {
fn from_handle(handle: ObjectHandle) -> Self {
match handle.object_ref() {
Some(object_ref) => Self::Indirect(object_ref),
None => Self::Direct(handle),
}
}
fn handle<R: Read + Seek>(&self, pdf: &mut Pdf<R>) -> ObjectHandle {
match self {
Self::Indirect(object_ref) => pdf.get_object_handle(*object_ref),
Self::Direct(handle) => handle.clone(),
}
}
fn object_ref(&self) -> Option<ObjectRef> {
match self {
Self::Indirect(object_ref) => Some(*object_ref),
Self::Direct(_) => None,
}
}
fn label(&self) -> String {
self.object_ref().map_or_else(
|| "direct page-tree object".to_owned(),
|reference| reference.to_string(),
)
}
}
pub struct PageWalk<'a, R: Read + Seek + 'static> {
pdf: &'a mut Pdf<R>,
stack: Vec<(PageNode, usize)>,
seen: BTreeSet<ObjectRef>,
#[allow(
clippy::mutable_key_type,
reason = "direct page-tree cycle detection keys on canonical handle identity"
)]
seen_direct: HashSet<ObjectHandleIdentity>,
max_depth: usize,
done: bool,
}
impl<'a, R: Read + Seek> PageWalk<'a, R> {
pub fn new(pdf: &'a mut Pdf<R>) -> Result<Self> {
Self::with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn with_max_depth(pdf: &'a mut Pdf<R>, max_depth: usize) -> Result<Self> {
let root = pdf.trailer_key_handle(b"Root");
if root.is_null() {
return Err(Error::Missing("/Root"));
}
let catalog = pdf.root_handle()?;
let pages = catalog.try_get_key(b"/Pages")?;
if pages.is_null() {
return Err(Error::Missing("/Pages"));
}
let pages = PageNode::from_handle(pages);
Ok(PageWalk {
pdf,
stack: vec![(pages, 0)],
seen: BTreeSet::new(),
seen_direct: HashSet::new(),
max_depth,
done: false,
})
}
fn visit_node(&mut self, node: &PageNode, depth: usize) -> Result<Option<ObjectRef>> {
let node_obj = node.handle(self.pdf);
self.pdf.resolve(&node_obj)?;
if node_obj.as_dictionary().is_none() {
return Ok(None); }
let node_type = node_obj.try_get_key(b"/Type")?;
self.pdf.resolve(&node_type)?;
if node_type.as_name().as_deref() == Some(b"Pages") {
let kids = node_obj.try_get_key(b"/Kids")?;
self.pdf.resolve(&kids)?;
if let Some(kids) = kids.as_array() {
for kid in kids.iter().rev() {
if let Some(r) = kid.object_ref() {
self.stack.push((PageNode::Indirect(r), depth + 1));
} else if kid.as_dictionary().is_some() {
self.stack.push((PageNode::Direct(kid.clone()), depth + 1));
}
}
}
return Ok(None);
}
if node_type.as_name().as_deref() == Some(b"Page") {
return Ok(node.object_ref());
}
Ok(None)
}
}
impl<'a, R: Read + Seek> Iterator for PageWalk<'a, R> {
type Item = Result<ObjectRef>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
loop {
let (node, depth) = self.stack.pop()?;
if depth >= self.max_depth {
self.done = true;
return Some(Err(Error::Unsupported(format!(
"page tree depth exceeds maximum of {} at {}",
self.max_depth,
node.label()
))));
}
let first_visit = match &node {
PageNode::Indirect(reference) => self.seen.insert(*reference),
PageNode::Direct(handle) => self.seen_direct.insert(handle.identity_key()),
};
if !first_visit {
continue; }
match self.visit_node(&node, depth) {
Ok(Some(page)) => return Some(Ok(page)),
Ok(None) => continue,
Err(error) => {
self.done = true;
return Some(Err(error));
}
}
}
}
}