Reuse PDF preview pages across object renumbering
This commit is contained in:
1 parent
c1c3c25b3f
commit
6a118d3b60
3 files changed
+204
-59
No files matched your search
@@ -1,11 +1,12 @@
|
||||
//! Page inputs consumed by the pinned PDF-to-SVG renderer.
|
||||
use hayro_svg::hayro_syntax::{
|
||||
Pdf,
|
||||
object::{Dict, MaybeRef, Name, Object, ObjectIdentifier},
|
||||
object::{Dict, MaybeRef, Name, ObjRef, Object, ObjectIdentifier},
|
||||
page::Page,
|
||||
reader::{Reader, ReaderExt},
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, HashMap, hash_map::Entry};
|
||||
|
||||
pub(super) type Fingerprint = [u8; 32];
|
||||
|
||||
@@ -36,11 +37,8 @@ impl PdfDependencies {
|
||||
let mut references = Vec::new();
|
||||
let raw = page.raw();
|
||||
let page_id = raw.obj_id()?;
|
||||
hash_id(&mut hash, page_id);
|
||||
hash_bytes(&mut hash, raw.data());
|
||||
// The renderer's reader has already resolved inherited boxes,
|
||||
// rotation and resources. Parent otherwise reaches unrelated pages.
|
||||
dictionary_references(raw, &mut references, 0, Some(b"Parent"))?;
|
||||
// The reader has resolved inherited boxes, rotation and resources.
|
||||
hash_dictionary(&mut hash, &mut references, raw, true)?;
|
||||
let resources = page.resources();
|
||||
for dictionary in [
|
||||
&resources.ext_g_states,
|
||||
@@ -51,24 +49,24 @@ impl PdfDependencies {
|
||||
&resources.patterns,
|
||||
&resources.shadings,
|
||||
] {
|
||||
hash_bytes(&mut hash, dictionary.data());
|
||||
dictionary_references(dictionary, &mut references, 0, None)?;
|
||||
hash_dictionary(&mut hash, &mut references, dictionary, false)?;
|
||||
}
|
||||
|
||||
let mut pending: BTreeSet<_> = references.into_iter().collect();
|
||||
let mut visited = BTreeSet::from([page_id]);
|
||||
while let Some(id) = pending.pop_first() {
|
||||
if !visited.insert(id) {
|
||||
continue;
|
||||
}
|
||||
// Number objects in traversal order from this page. Repeated edges
|
||||
// keep the same ordinal even when objects are shared or refer back.
|
||||
let mut ordinals = HashMap::from([(page_id, 0)]);
|
||||
let mut pending = vec![page_id];
|
||||
hash_edges(&mut hash, &references, &mut ordinals, &mut pending);
|
||||
let mut next = 1;
|
||||
while let Some(&id) = pending.get(next) {
|
||||
next += 1;
|
||||
let object = self
|
||||
.objects
|
||||
.entry(id)
|
||||
.or_insert_with(|| object_dependencies(pdf.xref().get::<Object<'_>>(id)?))
|
||||
.as_ref()?;
|
||||
hash_id(&mut hash, id);
|
||||
hash.update(object.fingerprint);
|
||||
pending.extend(object.references.iter().copied());
|
||||
hash_edges(&mut hash, &object.references, &mut ordinals, &mut pending);
|
||||
}
|
||||
Some(hash.finalize().into())
|
||||
}
|
||||
@@ -105,13 +103,32 @@ fn catalog_fingerprint(pdf: &Pdf) -> Option<Fingerprint> {
|
||||
}
|
||||
let mut hash = Sha256::new();
|
||||
hash.update([pdf.version() as u8]);
|
||||
hash_bytes(&mut hash, catalog.data());
|
||||
let mut references = Vec::new();
|
||||
hash_dictionary(&mut hash, &mut references, &catalog, false)?;
|
||||
// With optional content disabled, the renderer never follows the
|
||||
// catalog's allowed document-level references as part of page painting.
|
||||
hash_edges(&mut hash, &references, &mut HashMap::new(), &mut Vec::new());
|
||||
Some(hash.finalize().into())
|
||||
}
|
||||
|
||||
fn hash_id(hash: &mut Sha256, id: ObjectIdentifier) {
|
||||
hash.update(id.obj_number.to_le_bytes());
|
||||
hash.update(id.gen_number.to_le_bytes());
|
||||
fn hash_edges(
|
||||
hash: &mut Sha256,
|
||||
references: &[ObjectIdentifier],
|
||||
ordinals: &mut HashMap<ObjectIdentifier, usize>,
|
||||
pending: &mut Vec<ObjectIdentifier>,
|
||||
) {
|
||||
hash.update((references.len() as u64).to_le_bytes());
|
||||
for &id in references {
|
||||
let ordinal = match ordinals.entry(id) {
|
||||
Entry::Occupied(entry) => *entry.get(),
|
||||
Entry::Vacant(entry) => {
|
||||
let ordinal = pending.len();
|
||||
pending.push(id);
|
||||
*entry.insert(ordinal)
|
||||
}
|
||||
};
|
||||
hash.update((ordinal as u64).to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_bytes(hash: &mut Sha256, bytes: &[u8]) {
|
||||
@@ -121,6 +138,7 @@ fn hash_bytes(hash: &mut Sha256, bytes: &[u8]) {
|
||||
|
||||
fn object_dependencies(object: Object<'_>) -> Option<ObjectDependencies> {
|
||||
let mut hash = Sha256::new();
|
||||
let mut references = Vec::new();
|
||||
match &object {
|
||||
Object::Null(_) => hash.update([0]),
|
||||
Object::Boolean(value) => hash.update([1, u8::from(*value)]),
|
||||
@@ -139,7 +157,9 @@ fn object_dependencies(object: Object<'_>) -> Option<ObjectDependencies> {
|
||||
}
|
||||
Object::Array(array) => {
|
||||
hash.update([5]);
|
||||
hash_bytes(&mut hash, array.data());
|
||||
let mut input = ObjectBytes::new(array.data(), &mut hash, &mut references);
|
||||
input.array_items(None, 0)?;
|
||||
input.finish()?;
|
||||
}
|
||||
Object::Dict(dictionary) => {
|
||||
if matches!(
|
||||
@@ -149,59 +169,140 @@ fn object_dependencies(object: Object<'_>) -> Option<ObjectDependencies> {
|
||||
return None;
|
||||
}
|
||||
hash.update([6]);
|
||||
hash_bytes(&mut hash, dictionary.data());
|
||||
hash_dictionary(&mut hash, &mut references, dictionary, false)?;
|
||||
}
|
||||
Object::Stream(stream) => {
|
||||
hash.update([7]);
|
||||
hash_bytes(&mut hash, stream.dict().data());
|
||||
hash_dictionary(&mut hash, &mut references, stream.dict(), false)?;
|
||||
hash_bytes(&mut hash, &stream.raw_data());
|
||||
}
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
value_references(MaybeRef::NotRef(object), &mut references, 0)?;
|
||||
Some(ObjectDependencies {
|
||||
fingerprint: hash.finalize().into(),
|
||||
references,
|
||||
})
|
||||
}
|
||||
|
||||
fn dictionary_references(
|
||||
dictionary: &Dict<'_>,
|
||||
fn hash_dictionary(
|
||||
hash: &mut Sha256,
|
||||
references: &mut Vec<ObjectIdentifier>,
|
||||
depth: usize,
|
||||
skip: Option<&[u8]>,
|
||||
dictionary: &Dict<'_>,
|
||||
skip_page_parent: bool,
|
||||
) -> Option<()> {
|
||||
for key in dictionary.keys() {
|
||||
if Some(key.as_ref()) != skip {
|
||||
let value = dictionary.get_raw::<Object<'_>>(key.as_ref())?;
|
||||
value_references(value, references, depth + 1)?;
|
||||
}
|
||||
let mut input = ObjectBytes::new(dictionary.data(), hash, references);
|
||||
if !dictionary.data().is_empty() {
|
||||
input.dictionary(skip_page_parent, 0)?;
|
||||
}
|
||||
Some(())
|
||||
input.finish()
|
||||
}
|
||||
|
||||
fn value_references(
|
||||
value: MaybeRef<Object<'_>>,
|
||||
references: &mut Vec<ObjectIdentifier>,
|
||||
depth: usize,
|
||||
) -> Option<()> {
|
||||
if depth == 64 {
|
||||
return None;
|
||||
/// Keep literal bytes for the renderer's raw dictionary and array cache keys.
|
||||
/// Use its PDF lexer to find reference spans outside strings, names and comments.
|
||||
struct ObjectBytes<'a, 'b> {
|
||||
reader: Reader<'a>,
|
||||
literal_start: usize,
|
||||
hash: &'b mut Sha256,
|
||||
references: &'b mut Vec<ObjectIdentifier>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> ObjectBytes<'a, 'b> {
|
||||
fn new(
|
||||
data: &'a [u8],
|
||||
hash: &'b mut Sha256,
|
||||
references: &'b mut Vec<ObjectIdentifier>,
|
||||
) -> Self {
|
||||
Self {
|
||||
reader: Reader::new(data),
|
||||
literal_start: 0,
|
||||
hash,
|
||||
references,
|
||||
}
|
||||
}
|
||||
match value {
|
||||
MaybeRef::Ref(reference) => references.push(reference.into()),
|
||||
MaybeRef::NotRef(Object::Dict(dictionary)) => {
|
||||
dictionary_references(&dictionary, references, depth, None)?;
|
||||
}
|
||||
MaybeRef::NotRef(Object::Stream(stream)) => {
|
||||
dictionary_references(stream.dict(), references, depth, None)?;
|
||||
}
|
||||
MaybeRef::NotRef(Object::Array(array)) => {
|
||||
for value in array.raw_iter() {
|
||||
value_references(value, references, depth + 1)?;
|
||||
|
||||
fn dictionary(&mut self, skip_page_parent: bool, depth: usize) -> Option<()> {
|
||||
self.reader.forward_tag(b"<<")?;
|
||||
loop {
|
||||
self.reader.skip_white_spaces_and_comments();
|
||||
if self.reader.forward_tag(b">>").is_some() {
|
||||
return Some(());
|
||||
}
|
||||
let key = self.reader.read_without_context::<Name<'_>>()?;
|
||||
self.reader.skip_white_spaces_and_comments();
|
||||
if skip_page_parent && key.as_ref() == b"Parent" {
|
||||
let start = self.reader.offset();
|
||||
self.reader.skip::<MaybeRef<Object<'_>>>(false)?;
|
||||
self.replace(start, 2)?;
|
||||
} else {
|
||||
self.value(depth + 1)?;
|
||||
}
|
||||
}
|
||||
MaybeRef::NotRef(_) => {}
|
||||
}
|
||||
Some(())
|
||||
|
||||
fn array_items(&mut self, end: Option<u8>, depth: usize) -> Option<()> {
|
||||
loop {
|
||||
self.reader.skip_white_spaces_and_comments();
|
||||
if self.reader.peek_byte() == end {
|
||||
if end.is_some() {
|
||||
self.reader.forward();
|
||||
}
|
||||
return Some(());
|
||||
}
|
||||
self.value(depth + 1)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn value(&mut self, depth: usize) -> Option<()> {
|
||||
if depth >= 64 {
|
||||
return None;
|
||||
}
|
||||
match self.reader.peek_byte()? {
|
||||
b'[' => {
|
||||
self.reader.forward();
|
||||
self.array_items(Some(b']'), depth)?;
|
||||
}
|
||||
b'<' if self.reader.peek_tag(b"<<").is_some() => {
|
||||
self.dictionary(false, depth)?;
|
||||
}
|
||||
b'+' | b'-' | b'0'..=b'9' => {
|
||||
let start = self.reader.offset();
|
||||
if let Some(reference) = self.reader.read_without_context::<ObjRef>() {
|
||||
// The native writer uses a single spelling per ID. A
|
||||
// noncanonical spelling could change raw cache identity
|
||||
// independently of the reference graph.
|
||||
if self.reader.range(start..self.reader.offset())?
|
||||
!= reference.to_string().as_bytes()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.replace(start, 1)?;
|
||||
self.references.push(reference.into());
|
||||
} else {
|
||||
self.reader.skip::<Object<'_>>(false)?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.reader.skip::<Object<'_>>(false)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn replace(&mut self, start: usize, tag: u8) -> Option<()> {
|
||||
hash_bytes(self.hash, self.reader.range(self.literal_start..start)?);
|
||||
self.hash.update([tag]);
|
||||
self.literal_start = self.reader.offset();
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn finish(self) -> Option<()> {
|
||||
if !self.reader.at_end() {
|
||||
return None;
|
||||
}
|
||||
hash_bytes(
|
||||
self.hash,
|
||||
self.reader.range(self.literal_start..self.reader.len())?,
|
||||
);
|
||||
self.hash.update([0]);
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user