Validate PDF page dependencies before reusing SVG previews

This commit is contained in:
gloamxun committed 2026-11-26 18:36:10 +08:00
1 parent 520e8eede2
commit 140bb19849
5 files changed
+339 -28

No files matched your search

+207
View File
@@ -0,0 +1,207 @@
//! Page inputs consumed by the pinned PDF-to-SVG renderer.
use hayro_svg::hayro_syntax::{
Pdf,
object::{Dict, MaybeRef, Name, Object, ObjectIdentifier},
page::Page,
};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
pub(super) type Fingerprint = [u8; 32];
struct ObjectDependencies {
fingerprint: Fingerprint,
references: Vec<ObjectIdentifier>,
}
#[derive(Default)]
pub(super) struct PdfDependencies {
catalog: Option<Option<Fingerprint>>,
objects: BTreeMap<ObjectIdentifier, Option<ObjectDependencies>>,
}
impl PdfDependencies {
pub(super) fn page(&mut self, pdf: &Pdf, page: &Page<'_>, unit: f64) -> Option<Fingerprint> {
let catalog = (*self.catalog.get_or_insert_with(|| catalog_fingerprint(pdf)))?;
let mut hash = Sha256::new();
hash.update(catalog);
hash.update(unit.to_bits().to_le_bytes());
hash.update([page.rotation() as u8]);
for rect in [page.media_box(), page.crop_box()] {
for coordinate in [rect.x0, rect.y0, rect.x1, rect.y1] {
hash.update(coordinate.to_bits().to_le_bytes());
}
}
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"))?;
let resources = page.resources();
for dictionary in [
&resources.ext_g_states,
&resources.fonts,
&resources.properties,
&resources.color_spaces,
&resources.x_objects,
&resources.patterns,
&resources.shadings,
] {
hash_bytes(&mut hash, dictionary.data());
dictionary_references(dictionary, &mut references, 0, None)?;
}
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;
}
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());
}
Some(hash.finalize().into())
}
}
fn catalog_fingerprint(pdf: &Pdf) -> Option<Fingerprint> {
let xref = pdf.xref();
let catalog = xref.get::<Dict<'_>>(xref.root_id())?;
// Optional content and unknown catalog entries can change global
// rendering state. The listed keys have no such inputs in Hayro 0.9.
if xref.has_optional_content_groups()
|| catalog.keys().any(|key| {
!matches!(
key.as_ref(),
b"Type"
| b"Pages"
| b"Version"
| b"Names"
| b"Dests"
| b"OpenAction"
| b"Outlines"
| b"PageLabels"
| b"PageMode"
| b"PageLayout"
| b"ViewerPreferences"
| b"Lang"
| b"Metadata"
| b"MarkInfo"
| b"StructTreeRoot"
)
})
{
return None;
}
let mut hash = Sha256::new();
hash.update([pdf.version() as u8]);
hash_bytes(&mut hash, catalog.data());
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_bytes(hash: &mut Sha256, bytes: &[u8]) {
hash.update((bytes.len() as u64).to_le_bytes());
hash.update(bytes);
}
fn object_dependencies(object: Object<'_>) -> Option<ObjectDependencies> {
let mut hash = Sha256::new();
match &object {
Object::Null(_) => hash.update([0]),
Object::Boolean(value) => hash.update([1, u8::from(*value)]),
Object::Number(value) => {
hash.update([2]);
// Hayro's number printer preserves the integer/real distinction.
hash_bytes(&mut hash, value.to_string().as_bytes());
}
Object::Name(name) => {
hash.update([3]);
hash_bytes(&mut hash, name.as_ref());
}
Object::String(value) => {
hash.update([4]);
hash_bytes(&mut hash, value.as_bytes());
}
Object::Array(array) => {
hash.update([5]);
hash_bytes(&mut hash, array.data());
}
Object::Dict(dictionary) => {
if matches!(
dictionary.get::<Name<'_>>(b"Type").as_deref(),
Some(b"Page" | b"Pages" | b"Catalog")
) {
return None;
}
hash.update([6]);
hash_bytes(&mut hash, dictionary.data());
}
Object::Stream(stream) => {
hash.update([7]);
hash_bytes(&mut hash, stream.dict().data());
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<'_>,
references: &mut Vec<ObjectIdentifier>,
depth: usize,
skip: Option<&[u8]>,
) -> 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)?;
}
}
Some(())
}
fn value_references(
value: MaybeRef<Object<'_>>,
references: &mut Vec<ObjectIdentifier>,
depth: usize,
) -> Option<()> {
if depth == 64 {
return None;
}
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)?;
}
}
MaybeRef::NotRef(_) => {}
}
Some(())
}