Validate PDF page dependencies before reusing SVG previews
This commit is contained in:
1 parent
520e8eede2
commit
140bb19849
5 files changed
+339
-28
No files matched your search
@@ -621,6 +621,36 @@ SHA-256 为 `ae44671f7d0cee93ab3a32008ec4ef82ec52ef61020be6ecd3eac1d8512b5b72`
|
||||
[TeX Live 正则实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/utils.c#L762-L852)
|
||||
[GNU C 库匹配接口](https://sourceware.org/glibc/manual/latest/html_node/Matching-POSIX-Regexps.html)
|
||||
|
||||
### PDF 预览按实际页面资源复用
|
||||
|
||||
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
||||
内容流、图像、字体、颜色空间、遮罩和其他可达 PDF 对象均进入页面指纹。
|
||||
共享流在一次预览中只取一次指纹。可选图层、未知目录项、悬空引用及跨页对象
|
||||
无法完成校验时,继续以整份 PDF 作为复用条件。页面指纹匹配时复用原 SVG,
|
||||
差量只交付需要重新渲染的页。来源映射仍由当前修订的原生布局产生。
|
||||
|
||||
原三页对照中,前版重新发送第二、三页,当前只发送第二页。共享颜色对象、
|
||||
页面尺寸或全局图层变化时,两个实际受影响的页面均更新。仅改 PDF `Subject`
|
||||
时不发送任何页面。PDF 1.5 压缩对象流的定向修订也只更新第二页。各版逐页
|
||||
SVG、当前来源映射、PDF 和 aux 与独立全量一致。已有导入页测试覆盖第三页
|
||||
的实际 SVG 缓存复用。图像与原生预览两组共八个定向测试通过,含取消与发布。
|
||||
|
||||
三页性能用例的第三页使用未修改的 Elsevier CAS 5333 × 3000 JPEG。
|
||||
同机轮换顺序执行三组,每组每版十次热编辑。前版每次交付第二、三页,
|
||||
新版每次交付第二页。60 次逐次应用差量,结果与当前输入的独立全量一致。
|
||||
数据自库收到修订起计至 SVG 差量返回,单位 ms。
|
||||
|
||||
| 测量区间 | 前版 p50 | 前版 p95 | 新版 p50 | 新版 p95 |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 原生编译 | 237.081 | 1993.872 | 189.576 | 505.297 |
|
||||
| SVG 差量 | 461.354 | 519.298 | 0.790 | 1.002 |
|
||||
| 编译至 SVG 差量返回 | 681.792 | 2477.140 | 190.350 | 506.174 |
|
||||
|
||||
两版的编译阶段都有宿主波动,SVG 差量阶段单独计量。各批实际峰值 RSS
|
||||
与压力记录保存在回执目录。浏览器编辑至可见页面的正式延迟及分规模原样项目
|
||||
仍需统一验收。回执 `target/p4-pdf-preview-dependencies/receipt.json`
|
||||
的 SHA-256 为 `47b9e77cbf84c3181c710473c9fd081b721580abd62d6e95ae42b3b115212dae`。
|
||||
|
||||
### 单次 Unix 别名扫描共用固定目标的身份
|
||||
|
||||
固定路径的设备与 inode 观察只在同一轮扫描内共用。没有发现冲突时,
|
||||
|
||||
+2
-2
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -276,6 +276,7 @@ fn embedded_pdf_preview_uses_current_form_and_retains_the_other_page() {
|
||||
fs::create_dir(&root).unwrap();
|
||||
let vector = root.join("vector.pdf");
|
||||
rotated_document(&vector);
|
||||
fs::copy(&vector, root.join("stable.pdf")).unwrap();
|
||||
fs::write(
|
||||
root.join("probe.tex"),
|
||||
r"\catcode123=1 \catcode125=2
|
||||
@@ -284,7 +285,9 @@ fn embedded_pdf_preview_uses_current_form_and_retains_the_other_page() {
|
||||
\pdfximage page 1 trimbox {vector.pdf}
|
||||
\shipout\hbox{\pdfsave\pdfsetmatrix{0.75 0 0 0.75}
|
||||
\hbox to0pt{\pdfrefximage\pdflastximage\hss}\pdfrestore}
|
||||
\shipout\vbox{\hrule width12pt height20pt depth0pt}\end
|
||||
\shipout\vbox{\hrule width12pt height20pt depth0pt}
|
||||
\pdfximage page 1 trimbox {stable.pdf}
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}\end
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
@@ -302,7 +305,7 @@ fn embedded_pdf_preview_uses_current_form_and_retains_the_other_page() {
|
||||
let compiler = NativeCompiler::default();
|
||||
let first = compiler.compile(request.clone()).unwrap();
|
||||
let full = first.preview_since(None).unwrap();
|
||||
assert_eq!(full.page_count, 2);
|
||||
assert_eq!(full.page_count, 3);
|
||||
let art = full.pages[0].svg.to_ascii_lowercase();
|
||||
assert!(art.contains("<path"));
|
||||
assert!(art.contains("#ff0000"));
|
||||
@@ -338,6 +341,10 @@ fn embedded_pdf_preview_uses_current_form_and_retains_the_other_page() {
|
||||
&full.pages[1].svg,
|
||||
¤t_full.pages[1].svg
|
||||
));
|
||||
assert!(std::sync::Arc::ptr_eq(
|
||||
&full.pages[2].svg,
|
||||
¤t_full.pages[2].svg
|
||||
));
|
||||
let independent = NativeCompiler::default().compile(request).unwrap();
|
||||
assert_eq!(current.pdf, independent.pdf);
|
||||
assert_eq!(
|
||||
|
||||
Reference in new issue
Block a user