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

+2 -2
View File
@@ -1166,8 +1166,8 @@ impl CompileJob {
.transpose()?;
let receipt = prepared.as_ref().map(|p| p.version(&output)).transpose()?;
let previous = self.compiler.latest();
// PDF-composited SVG is derived from the complete device output.
// Reuse it only when the bytes underlying this rendering agree.
// Identical PDF output allows direct reuse. When it differs,
// PDF previews validate the new page and its reachable objects.
let pdf_unchanged = pages.iter().any(DisplayList::has_embedded_pdf)
&& previous
.as_deref()
+91 -24
View File
@@ -2,9 +2,15 @@
use hayro_svg::{
RenderCache, SvgRenderSettings, hayro_interpret::InterpreterSettings, hayro_syntax::Pdf,
};
use std::sync::{Arc, OnceLock};
use std::{
collections::BTreeMap,
sync::{Arc, Mutex, OnceLock},
};
use texrra_tex_core::render::DisplayList;
mod pdf_dependencies;
use pdf_dependencies::{Fingerprint, PdfDependencies};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct PreviewPage {
pub index: usize,
@@ -23,15 +29,28 @@ pub struct PreviewUpdate {
pub pages: Vec<PreviewPage>,
}
type PageSvg = OnceLock<Result<Arc<str>, String>>;
struct CachedPage {
svg: Arc<str>,
pdf_page: Option<Fingerprint>,
reused_pdf_page: bool,
}
type PageSvg = OnceLock<Result<CachedPage, String>>;
type PriorPdfPage = (Fingerprint, Arc<str>);
struct PdfPreview<'a> {
bytes: Option<&'a Arc<[u8]>>,
document: OnceLock<Result<Pdf, String>>,
dependencies: PdfDependencies,
}
impl PdfPreview<'_> {
fn render_page(&self, index: usize, unit: f64) -> Result<Arc<str>, String> {
fn render_page(
&mut self,
index: usize,
unit: f64,
previous: Option<PriorPdfPage>,
) -> Result<CachedPage, String> {
let document = self
.document
.get_or_init(|| {
@@ -45,23 +64,39 @@ impl PdfPreview<'_> {
.map_err(Clone::clone)?;
let page = document
.pages()
.iter()
.nth(index)
.get(index)
.ok_or("preview PDF page is missing")?;
let pdf_page = self.dependencies.page(document, page, unit);
if let Some((prior_page, svg)) = previous
&& pdf_page == Some(prior_page)
{
return Ok(CachedPage {
svg,
pdf_page,
reused_pdf_page: true,
});
}
let svg = hayro_svg::convert(
page,
&RenderCache::new(),
&InterpreterSettings::default(),
&SvgRenderSettings::default(),
);
if unit == 1.0 {
return Ok(Arc::from(svg));
}
let (width, height) = page.render_dimensions();
let (width, height) = (f64::from(width) * unit, f64::from(height) * unit);
Ok(Arc::from(format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}pt\" height=\"{height}pt\" viewBox=\"0 0 {width} {height}\"><g transform=\"scale({unit})\">{svg}</g></svg>"
)))
let svg = if unit == 1.0 {
Arc::from(svg)
} else {
let (width, height) = page.render_dimensions();
let (width, height) = (f64::from(width) * unit, f64::from(height) * unit);
Arc::from(format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}pt\" height=\"{height}pt\" viewBox=\"0 0 {width} {height}\"><g transform=\"scale({unit})\">{svg}</g></svg>"
))
};
Ok(CachedPage {
svg,
pdf_page,
reused_pdf_page: false,
})
}
}
@@ -69,6 +104,7 @@ pub(crate) struct PreviewState {
previous_revision: Option<u64>,
changed: Vec<usize>,
slots: Vec<Arc<PageSvg>>,
prior_pdf: BTreeMap<usize, Mutex<Option<PriorPdfPage>>>,
}
impl PreviewState {
@@ -79,15 +115,24 @@ impl PreviewState {
) -> Self {
let mut changed = Vec::new();
let mut slots = Vec::with_capacity(pages.len());
let mut prior_pdf = BTreeMap::new();
for (index, page) in pages.iter().enumerate() {
let uses_pdf = page.has_embedded_pdf();
if let Some((_, old_pages, old)) = previous
&& (pdf_unchanged || !page.has_embedded_pdf())
&& (pdf_unchanged || !uses_pdf)
&& old_pages
.get(index)
.is_some_and(|old_page| old_page.same_svg_paint(page))
{
slots.push(old.slots[index].clone());
} else {
if uses_pdf
&& let Some((_, _, old)) = previous
&& let Some(Ok(cached)) = old.slots.get(index).and_then(|slot| slot.get())
&& let Some(fingerprint) = cached.pdf_page
{
prior_pdf.insert(index, Mutex::new(Some((fingerprint, cached.svg.clone()))));
}
changed.push(index);
slots.push(Arc::new(OnceLock::new()));
}
@@ -96,6 +141,7 @@ impl PreviewState {
previous_revision: previous.map(|(revision, _, _)| revision),
changed,
slots,
prior_pdf,
}
}
@@ -107,9 +153,10 @@ impl PreviewState {
visible: Option<u64>,
check: impl Fn() -> Result<(), String>,
) -> Result<PreviewUpdate, String> {
let pdf = PdfPreview {
let mut pdf = PdfPreview {
bytes: pdf,
document: OnceLock::new(),
dependencies: PdfDependencies::default(),
};
let mut rendered = Vec::new();
let base_revision = if visible == Some(revision) {
@@ -117,13 +164,23 @@ impl PreviewState {
} else if visible.is_some() && visible == self.previous_revision {
for &index in &self.changed {
check()?;
rendered.push(self.render_page(index, &pages[index], &pdf)?);
let cached = self.render_page(index, &pages[index], &mut pdf)?;
if !cached.reused_pdf_page {
rendered.push(PreviewPage {
index,
svg: cached.svg.clone(),
});
}
}
visible
} else {
for (index, page) in pages.iter().enumerate() {
check()?;
rendered.push(self.render_page(index, page, &pdf)?);
let cached = self.render_page(index, page, &mut pdf)?;
rendered.push(PreviewPage {
index,
svg: cached.svg.clone(),
});
}
None
};
@@ -140,17 +197,27 @@ impl PreviewState {
&self,
index: usize,
page: &DisplayList,
pdf: &PdfPreview<'_>,
) -> Result<PreviewPage, String> {
let svg = self.slots[index]
pdf: &mut PdfPreview<'_>,
) -> Result<&CachedPage, String> {
self.slots[index]
.get_or_init(|| {
if page.has_embedded_pdf() {
pdf.render_page(index, page.pdf_user_unit())
let prior = self.prior_pdf.get(&index).and_then(|entry| {
entry
.lock()
.unwrap_or_else(|error| error.into_inner())
.take()
});
pdf.render_page(index, page.pdf_user_unit(), prior)
} else {
page.try_to_svg().map(Arc::from)
page.try_to_svg().map(|svg| CachedPage {
svg: Arc::from(svg),
pdf_page: None,
reused_pdf_page: false,
})
}
})
.clone()?;
Ok(PreviewPage { index, svg })
.as_ref()
.map_err(Clone::clone)
}
}
+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(())
}