diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 60f2d17..115bcc9 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -243,7 +243,6 @@ pub struct Executor { pdf_outline_payload: usize, pdf_info_tokens: Vec, pdf_images: Vec, - pdf_forms: BTreeMap, restored_pdf_image_count: usize, format_image_warnings: Vec, pdf_force_pagebox_warned: bool, @@ -423,7 +422,6 @@ impl Executor { pdf_outline_payload: 0, pdf_info_tokens: Vec::new(), pdf_images: Vec::new(), - pdf_forms: BTreeMap::new(), restored_pdf_image_count: 0, format_image_warnings: Vec::new(), pdf_force_pagebox_warned: false, @@ -2389,7 +2387,7 @@ impl Executor { } Meaning::Primitive(Primitive::Pdflastxform) => { self.reads.insert(Dependency::PdfObjects); - Ok(self.pdf_forms.last_key_value().map_or(0, |(&number, _)| number as i32)) + Ok(self.state.pdf_forms.last_key_value().map_or(0, |(&number, _)| number as i32)) } Meaning::Primitive(Primitive::Pdflastobj) => { self.reads.insert(Dependency::PdfObjects); @@ -4052,9 +4050,6 @@ impl Executor { .fail("dump requires closed groups and conditionals"); } self.ensure_format_pdf_images()?; - if !self.pdf_forms.is_empty() { - return self.fail("cannot dump a format with registered PDF Forms"); - } self.reads.insert(Dependency::FontResources); if self.state.fonts.fonts().iter().any(|font| font.opentype().is_some()) { return self.fail("cannot dump a format with native OpenType fonts"); diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_form.rs b/crates/texrra-tex-core/src/execution/engine/pdf_form.rs index 291f03e..53710ad 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_form.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_form.rs @@ -1,19 +1,6 @@ //! pdfTeX Form registration and deferred output. use super::*; -use crate::pdf_device::forms::{FormUse, ShippedForm}; - -#[derive(Clone)] -pub(super) struct RegisteredForm { - form: FormUse, - body: Option, -} - -#[derive(Clone)] -struct FormBody { - box_node: NativeBox, - attributes: Vec, - resources: Vec, -} +use crate::pdf_device::forms::{FormBody, FormContents, FormUse, RegisteredForm, ShippedForm}; impl Executor { fn check_pdf_form(&mut self) -> Result<(), Error> { @@ -63,9 +50,9 @@ impl Executor { height: box_node.height, depth: box_node.depth, }; - self.pdf_forms.insert(number, RegisteredForm { + self.state.pdf_forms.insert(number, RegisteredForm { form, - body: Some(FormBody { box_node, attributes, resources }), + contents: FormContents::Pending(Arc::new(FormBody { box_node, attributes, resources })), }); if immediate { self.write_pdf_form(number, files)?; @@ -81,10 +68,13 @@ impl Executor { self.check_pdf_form()?; let requested = self.integer(files)?; self.reads.insert(Dependency::PdfObjects); - let form = u32::try_from(requested).ok() - .and_then(|number| self.pdf_forms.get(&number)) - .map(|entry| entry.form) + let entry = u32::try_from(requested).ok() + .and_then(|number| self.state.pdf_forms.get(&number)) .ok_or_else(|| self.error("cannot find referenced PDF Form", token.span))?; + if entry.contents == FormContents::DiscardedAtDump { + return self.fail("PDF Form was already written by the format job"); + } + let form = entry.form; self.defer_output(OutputNode { operation: OutputOperation::PdfForm { form, origin: token.into() }, span: token.span, @@ -97,13 +87,27 @@ impl Executor { files: &mut impl SourceProvider, ) -> Result<(), Error> { self.reads.insert(Dependency::PdfObjects); - let entry = self.pdf_forms.get_mut(&number).expect("registered Form reference"); + let Some(entry) = self.state.pdf_forms.get_mut(&number) else { + return self.fail("cannot find referenced PDF Form"); + }; let form = entry.form; - let Some(body) = entry.body.take() else { return Ok(()) }; + let body = match std::mem::replace(&mut entry.contents, FormContents::Shipped) { + FormContents::Pending(body) => Arc::unwrap_or_clone(body), + FormContents::Shipped => return Ok(()), + FormContents::DiscardedAtDump => { + return self.fail("PDF Form was already written by the format job"); + } + }; + let limit = self.limits.tokens; + let resource_number = self.state.pdf_objects.as_deref_mut().expect("existing PDF object table") + .reserve_form_resources(limit) + .map_err(|message| self.error(message, self.current))?; let attributes = self.pdf_token_bytes(&body.attributes)?; let resources = self.pdf_token_bytes(&body.resources)?.into(); let (canvas, children, probed) = self.ship_box_contents(body.box_node, Some(resources), files)?; - self.events.push(Event::PdfForm(Box::new(ShippedForm { form, attributes, canvas }))); + self.events.push(Event::PdfForm(Box::new(ShippedForm { + form, resource_number, attributes, canvas, + }))); if probed && let Some(probe) = self.pdf_space_probe.as_mut() { Arc::make_mut(probe).observed_events = self.events.len(); } diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs b/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs index 37605bf..0035d20 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs @@ -108,12 +108,11 @@ impl Executor { } self.reads.insert(Dependency::PdfObjects); let number = self.positive_pdf_number("object reference", files)? as u32; - if !self - .state - .pdf_objects - .as_deref() - .is_some_and(|objects| objects.contains(number)) - { + let objects = self.state.pdf_objects.as_deref(); + if objects.is_some_and(|objects| objects.is_discarded_at_dump(number)) { + return self.fail("PDF object belongs to the format job and cannot be reused"); + } + if !objects.is_some_and(|objects| objects.contains(number)) { return self.fail("cannot find referenced PDF object"); } self.defer_output(OutputNode { diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 9b1da49..edeb12b 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -14,9 +14,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 85; -const COMPATIBLE_SCHEMAS: [u32; 52] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, SCHEMA, +const SCHEMA: u32 = 86; +const COMPATIBLE_SCHEMAS: [u32; 53] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -207,6 +207,12 @@ impl FormatImage { return Err("invalid native format image registry".into()); } } + if (!image.state.pdf_forms.is_empty() + && (image.schema < 86 || image.state.input_profile() != InputProfile::TeX8Bit)) + || !image.state.validate_format_pdf_forms() + { + return Err("invalid native format PDF Form registry".into()); + } image.schema = SCHEMA; Ok(image) } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 2e0e847..50e8bf7 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -743,7 +743,9 @@ impl Execution { Error::at(&self.sources, self.state.input_profile(), message, form.canvas.box_node.span) })?; list.pdf_resources.attributes = form.attributes.clone().into(); - forms.push(crate::pdf_device::forms::FormDisplay { form: form.form, list }); + forms.push(crate::pdf_device::forms::FormDisplay { + form: form.form, resource_number: form.resource_number, list, + }); } if let Event::Shipout(b) = e { pages.push(b.display_list().map_err(|message| { diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 04d3f31..4ca0acc 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -804,6 +804,8 @@ pub struct State { pub(super) pdf_catalog: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_objects: Option>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(super) pdf_forms: BTreeMap, pub(super) pdf_info: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_pages_attributes: Vec, @@ -1008,6 +1010,7 @@ impl Default for State { xdv_navigation: None, pdf_catalog: None, pdf_objects: None, + pdf_forms: BTreeMap::new(), initial_random_seed: None, random: None, pdf_info: Vec::new(), @@ -1657,10 +1660,16 @@ impl State { if !self .pdf_objects .as_deref_mut() - .is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_links) + .is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_objects) { self.pdf_objects = None; } + use crate::pdf_device::forms::FormContents; + for form in self.pdf_forms.values_mut() { + if form.contents == FormContents::Shipped { + form.contents = FormContents::DiscardedAtDump; + } + } self.pdf_info.clear(); self.pdf_pages_attributes.clear(); self.fonts.reset_format_font_state(); @@ -1673,9 +1682,30 @@ impl State { for b in self.boxes.values_mut() { super::format_image::boxes::rebind(b, images)?; } + for form in self.pdf_forms.values_mut() { + if let crate::pdf_device::forms::FormContents::Pending(body) = &mut form.contents { + super::format_image::boxes::rebind(&mut std::sync::Arc::make_mut(body).box_node, images)?; + } + } Ok(()) } + pub(super) fn validate_format_pdf_forms(&self) -> bool { + use crate::pdf_device::forms::FormContents; + let registered = self.pdf_objects.iter().flat_map(|objects| objects.form_numbers()); + registered.eq(self.pdf_forms.keys().copied()) + && self.pdf_forms.iter().all(|(&number, form)| { + number == form.form.number && match &form.contents { + FormContents::Pending(body) => { + let b = &body.box_node; + [form.form.width, form.form.height, form.form.depth] == [b.width, b.height, b.depth] + } + FormContents::DiscardedAtDump => true, + FormContents::Shipped => false, + } + }) + } + pub(super) fn restore_legacy_format_fonts(&mut self) -> Result<(), String> { let replacements = self.fonts.restore_legacy_synthesized_fonts()?; if !replacements.is_empty() { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 22fc063..4bd1b83 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2415,8 +2415,15 @@ fn write_pdf( } else { resources }; + let mut device_objects = BTreeMap::new(); + for form in &forms { + for number in [form.form.number, form.resource_number] { + objects.push(Vec::new()); + device_objects.insert(number, objects.len() as u32); + } + } let remapped = resources - .map(|resources| resources.append(&mut objects, diagnostics)) + .map(|resources| resources.append(&mut objects, diagnostics, device_objects.clone())) .transpose()?; if let Some(resources) = &remapped { for (font, entries) in &resources.fonts { @@ -2458,11 +2465,6 @@ fn write_pdf( ); (id, object) }).collect(); - let mut xforms = BTreeMap::new(); - for form in &forms { - objects.push(Vec::new()); - xforms.insert(form.form.number, objects.len()); - } let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> { let images = list .items @@ -2480,7 +2482,7 @@ fn write_pdf( _ => None, }).collect(); for number in placements { - let id = xforms.get(&number).ok_or("missing native PDF Form canvas")?; + let id = device_objects.get(&number).ok_or("missing native PDF Form canvas")?; xobjects.push_str(&format!(" /Fm{number} {id} 0 R")); } Ok(()) @@ -2526,22 +2528,26 @@ fn write_pdf( let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits); let width = crate::pdf_device::print_sp(form.form.width, digits); let height = crate::pdf_device::print_sp(form.form.height + form.form.depth, digits); - let mut entries = format!( - "/Type /XObject /Subtype /Form /FormType 1 /BBox [0 0 {width} {height}] /Matrix [1 0 0 1 0 0]" - ).into_bytes(); + let resource_id = device_objects[&form.resource_number]; + let mut entries = b"/Type /XObject /Subtype /Form".to_vec(); let attributes = remapped.as_ref().map_or(&[][..], |r| r.page_attributes[slot].as_slice()); entries.extend_from_slice(attributes); - entries.extend_from_slice(format!(" /Resources << /Font << {fonts} >>").as_bytes()); + write!( + &mut entries, + " /BBox [0 0 {width} {height}] /FormType 1 /Matrix [1 0 0 1 0 0] /Resources {resource_id} 0 R" + ).unwrap(); + let mut resource_dictionary = format!("<< /Font << {fonts} >>").into_bytes(); if !xobjects.is_empty() { - entries.extend_from_slice(format!(" /XObject << {xobjects} >>").as_bytes()); + resource_dictionary.extend_from_slice(format!(" /XObject << {xobjects} >>").as_bytes()); } if let Some(remapped) = &remapped { - entries.extend_from_slice(&remapped.pages[slot]); + resource_dictionary.extend_from_slice(&remapped.pages[slot]); } if list.pdf.as_ref().is_some_and(|pdf| pdf.writes_procset()) { - append_page_procset(&mut entries, list, false); + append_page_procset(&mut resource_dictionary, list, false); } - entries.extend_from_slice(b" >>"); + resource_dictionary.extend_from_slice(b" >>"); + objects[resource_id as usize - 1] = resource_dictionary; let names = BTreeMap::new(); let no_font_opacity = BTreeMap::new(); let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]); @@ -2549,10 +2555,8 @@ fn write_pdf( list, list.height, &names, faces, &cm_views, &fallback_font_ids, PageOrigin::default(), &opentype, font_opacities, ); - let stream_entries = std::str::from_utf8(&entries) - .map_err(|_| "non-UTF8 captured PDF Form attributes")?; - objects[xforms[&form.form.number] - 1] = objects::stream( - stream_entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression), + objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes( + &entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression), ); } let mut png_group = None; diff --git a/crates/texrra-tex-core/src/pdf_device/forms.rs b/crates/texrra-tex-core/src/pdf_device/forms.rs index 2f30f29..b324ffc 100644 --- a/crates/texrra-tex-core/src/pdf_device/forms.rs +++ b/crates/texrra-tex-core/src/pdf_device/forms.rs @@ -1,7 +1,8 @@ //! Geometry and captured contents of a native PDF Form XObject. -use crate::{execution::NativeShipout, render::DisplayList}; +use crate::{execution::{NativeBox, NativeShipout, Token}, render::DisplayList}; use serde::{Deserialize, Serialize}; +use std::sync::Arc; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct FormUse { @@ -11,9 +12,30 @@ pub struct FormUse { pub depth: i64, } +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(crate) struct RegisteredForm { + pub form: FormUse, + pub contents: FormContents, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(crate) enum FormContents { + Pending(Arc), + Shipped, + DiscardedAtDump, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(crate) struct FormBody { + pub box_node: NativeBox, + pub attributes: Vec, + pub resources: Vec, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ShippedForm { pub form: FormUse, + pub resource_number: u32, pub attributes: Vec, pub canvas: NativeShipout, } @@ -21,5 +43,6 @@ pub struct ShippedForm { #[derive(Clone, Debug, PartialEq, Eq)] pub struct FormDisplay { pub form: FormUse, + pub resource_number: u32, pub list: DisplayList, } diff --git a/crates/texrra-tex-core/src/pdf_device/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/page_resources.rs index e1eed1c..d948364 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -16,6 +16,8 @@ pub(crate) enum ObjectBody { Link, FormatLink, Form, + FormResources, + DiscardedAtDump, Direct(Vec), Stream { attributes: Vec, @@ -31,7 +33,8 @@ pub(crate) enum ObjectBody { impl ObjectBody { fn len(&self) -> usize { match self { - Self::Page | Self::Link | Self::FormatLink | Self::Form => 0, + Self::Page | Self::Link | Self::FormatLink | Self::Form + | Self::FormResources | Self::DiscardedAtDump => 0, Self::Direct(bytes) => bytes.len(), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), Self::File { @@ -48,7 +51,10 @@ impl ObjectBody { fn parse(&self) -> Result { match self { - Self::Page | Self::Link | Self::FormatLink | Self::Form => Err("expected a generic native PDF object".into()), + Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources => { + Err("expected a generic native PDF object".into()) + } + Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()), Self::Direct(bytes) => parse_value(bytes), Self::File { .. } => Err("PDF object file payload was not read before export".into()), Self::Stream { attributes, bytes } => { @@ -85,10 +91,12 @@ impl PdfObjects { } pub(crate) fn contains(&self, number: u32) -> bool { - self.entry(number) - .is_some_and(|entry| { - !matches!(entry.as_deref(), Some(ObjectBody::Page | ObjectBody::Link | ObjectBody::FormatLink | ObjectBody::Form)) - }) + matches!(self.entry(number).map(Option::as_deref), + Some(None | Some(ObjectBody::Direct(_) | ObjectBody::Stream { .. } | ObjectBody::File { .. }))) + } + + pub(crate) fn is_discarded_at_dump(&self, number: u32) -> bool { + matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::DiscardedAtDump)) } pub(crate) fn is_reserved(&self, number: u32) -> bool { @@ -113,6 +121,16 @@ impl PdfObjects { self.allocate(Some(Arc::new(ObjectBody::Form)), limit) } + pub(crate) fn reserve_form_resources(&mut self, limit: usize) -> Result { + self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit) + } + + pub(crate) fn form_numbers(&self) -> impl Iterator + '_ { + self.values.iter().enumerate().filter_map(|(index, entry)| { + matches!(entry.as_deref(), Some(ObjectBody::Form)).then_some(index as u32 + 1) + }) + } + pub(crate) fn reserve_link(&mut self, limit: usize) -> Result { self.allocate(Some(Arc::new(ObjectBody::Link)), limit) } @@ -125,27 +143,23 @@ impl PdfObjects { self.last_link.unwrap_or_default() as i32 } - pub(crate) fn retain_format_links(&mut self) -> bool { - let Some(last_link) = self - .values - .iter() - .rposition(|entry| matches!(entry.as_deref(), Some(ObjectBody::Link))) - else { - return false; - }; - // The reservation survives the format, but pdfTeX assigns a new - // object to the annotation when it ships the restored whatsit. - self.values.truncate(last_link + 1); - for entry in &mut self.values { - *entry = matches!(entry.as_deref(), Some(ObjectBody::Link)) - .then(|| Arc::new(ObjectBody::FormatLink)); + pub(crate) fn retain_format_objects(&mut self) -> bool { + for (index, entry) in self.values.iter_mut().enumerate() { + let number = index as u32 + 1; + let replacement = match entry.as_deref() { + // A restored link whatsit gets its own annotation object when shipped. + Some(ObjectBody::Link) => ObjectBody::FormatLink, + Some(ObjectBody::Page | ObjectBody::FormResources) => ObjectBody::DiscardedAtDump, + _ if self.written.contains(&number) => ObjectBody::DiscardedAtDump, + _ => continue, + }; + *entry = Some(Arc::new(replacement)); } self.written.clear(); - self.last = 0; self.last_link = None; - self.bytes = 0; + self.bytes = self.values.iter().flatten().map(|body| body.len()).sum(); self.page_references.clear(); - true + !self.values.is_empty() } fn is_link(&self, number: u32) -> bool { @@ -530,6 +544,9 @@ impl ResourceOutput { } } let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect(); + let form_objects: BTreeSet<_> = pages.iter().flat_map(|page| { + page.forms.iter().flat_map(|form| [form.form.number, form.resource_number]) + }).collect(); let annotation_entries = pages .iter() .map(|page| { @@ -583,9 +600,12 @@ impl ResourceOutput { link_references.entry(number).or_insert(None); continue; } - if values.contains_key(&number) || page_objects.contains(&number) { + if values.contains_key(&number) || page_objects.contains(&number) || form_objects.contains(&number) { continue; } + if objects.is_discarded_at_dump(number) { + return Err(format!("PDF object {number} belongs to the format job and cannot be reused")); + } let value = objects.written_body(number)?.parse()?; references(&value, &mut pending)?; values.insert(number, value); @@ -622,8 +642,8 @@ impl ResourceOutput { self, output: &mut Vec>, diagnostics: &mut Vec, + mut ids: BTreeMap, ) -> Result { - let mut ids = BTreeMap::new(); let mut page_objects = BTreeMap::new(); for (page, number) in self.page_references { // The real Page dictionary fills this slot at export. A missing diff --git a/crates/texrra-tex-core/src/pdf_objects.rs b/crates/texrra-tex-core/src/pdf_objects.rs index f858912..200759b 100644 --- a/crates/texrra-tex-core/src/pdf_objects.rs +++ b/crates/texrra-tex-core/src/pdf_objects.rs @@ -3,6 +3,10 @@ use crate::pdf_device::PdfFileOptions; use std::io::Write; pub(crate) fn stream(extra: &str, data: &[u8], level: u8) -> Vec { + stream_bytes(extra.as_bytes(), data, level) +} + +pub(crate) fn stream_bytes(extra: &[u8], data: &[u8], level: u8) -> Vec { let encoded = if level == 0 { data.to_vec() } else { @@ -16,8 +20,10 @@ pub(crate) fn stream(extra: &str, data: &[u8], level: u8) -> Vec { } else { " /Filter /FlateDecode" }; - let mut result = - format!("<< /Length {} {extra}{filter} >>\nstream\n", encoded.len()).into_bytes(); + let mut result = format!("<< /Length {} ", encoded.len()).into_bytes(); + result.extend_from_slice(extra); + result.extend_from_slice(filter.as_bytes()); + result.extend_from_slice(b" >>\nstream\n"); result.extend_from_slice(&encoded); result.extend_from_slice(b"\nendstream"); result diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 8a4f775..7141fc4 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -777,12 +777,36 @@ Form 和页面使用同一套字体装载和字形绘制。使用实际 CMR10 回归通过。三页项目修改子文件定义后复用有效检查点,只更新第二 页。放置范围进入来源映射,PDF、SVG 和来源映射与独立全量一致。 -schema85 登记新增原语。已登记的 Form 随格式转储和重载仍待实现。 +schema85 登记新增原语。该版仍限制已登记 Form 的格式转储。 原版格式样例保留一个 Form 及一个引用它的盒子,重载后编号和 盒内引用有效,原生在转储处明确拒绝。同样保留 Form 内链接、 目标、内部字形到页面的逐字来源,以及通用 PDF 对象引用的剩余 范围。证据在 target/p3-pdf-form,回执 SHA-256 为 fd58aa92c93bd962eef9750ca64d79690dad7ca6ec38e10319e8edc0974d9717。 +### 原生格式重载 PDF Form 与延迟对象 + +schema86 将未发出的 Form 原始盒、属性和资源 token 纳入格式状态。 +保留嵌套引用、已装箱的引用、Form 和普通 PDF 对象编号。格式重载 +后由发页流程绘制,执行此时的延迟写入。Form 内登记的 PNG 重开 +当前文件,保留原装箱尺寸。普通文件型对象在重载作业首次使用时 +才读取实际文件。Form 的资源字典作为真正的间接对象写出,通用 +PDF 对象的引用进入同一重编号过程。边界框、矩阵和资源引用在用户 +属性之后写出,属性中的 PDF 字符串保留原字节。 +[TeX Live 的格式状态和 PDF 对象](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L33215-L33286) + +十组成功作业共十二页,144 DPI 灰度图与 pdfTeX 1.40.29 逐像素 +一致。两份在原版重载引用时崩溃的旧作业对象有明确诊断,已占用的 +编号仍保留。旧 schema85 格式在两版生成逐字节相同的 PDF。十一项 +图像、Form 和链接定向回归通过。编辑重载 Form 用到的文件型对象 +后,安全复用该文件首次读取前的检查点,只更新第二页。PDF、SVG +和来源映射与独立全量一致,实际辅助文件内容一致。 + +下一入口为图片与其它 PDF 对象共用编号。冻结用例的原版打印 +1/2/3/4,当前原生打印 1/1/2/3。首次发页后新原始对象的编号 +分别为 9 和 5。保留两端实际 PDF 与日志,并用真实页面资源和 +内容流补齐剩余的分配时机。回执 target/p3-pdf-form-format/receipt.json +的 SHA-256 为 9f58bf51a894b698a90640c65c8fd7a3a6877b244aaebe1c676f169b0d1fb423。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/tests/native_pdf_image.rs b/tests/native_pdf_image.rs index 0baafba..723c194 100644 --- a/tests/native_pdf_image.rs +++ b/tests/native_pdf_image.rs @@ -806,3 +806,103 @@ fn native_form_edit_updates_the_page_that_references_it() { ); fs::remove_dir_all(root).unwrap(); } + +#[test] +fn restored_form_reads_the_current_pdf_object_and_updates_only_its_page() { + use texrra_engine::native::dump_format; + use texrra_tex_core::execution::Cancellation; + + let root = std::env::temp_dir().join(format!("texrra-form-format-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + let root = root.canonicalize().unwrap(); + let seed = root.join("seed.tex"); + let format = root.join("seed.tfx"); + let entry = root.join("entry.tex"); + let paint = root.join("paint.obj"); + let effects = root.join("effects.aux"); + fs::write(&effects, b"OLD\n").unwrap(); + fs::write( + &seed, + r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=5 \pdfcompresslevel=0 +\def\space{ } +\pdfobj file{paint.obj} +\edef\paintid{\the\pdflastobj} +\setbox0=\hbox{\pdfrefobj\paintid\pdfliteral direct{/Alpha gs}% + \write1{\phase}\vrule width36pt height9pt depth2pt} +\pdfxform resources{/ExtGState << /Alpha \paintid\space 0 R >>} 0 +\setbox1=\hbox{\pdfrefxform\pdflastxform} +\dump +", + ) + .unwrap(); + let time = JobTime::new(2026, 11, 27, 0).unwrap(); + let world = WorldConfig::new(&root); + let mut dump = CompileRequest::new(world.clone(), &seed, &format, time); + dump.entry = Entry::Initex; + dump.etex = true; + // The deferred object file does not exist during the format dump. + dump_format(dump, Cancellation::default()).unwrap(); + let prefix = r"\pdfpagewidth=150pt \pdfpageheight=150pt +\shipout\hbox{\vrule width8pt height4pt} +"; + let padding = format!("{}\n", "\\relax ".repeat(32)).repeat(48); + let entry_text = format!( + "{prefix}{padding}\ + \\immediate\\openout1=effects.aux\n\ + \\def\\phase{{RELOAD}}\\shipout\\copy1\n\ + \\immediate\\closeout1\n\\end\n" + ); + let snapshot = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: [root.clone()].into(), + files: [ + (seed.clone(), fs::read(&seed).unwrap().into()), + (format.clone(), fs::read(&format).unwrap().into()), + (entry.clone(), entry_text.into_bytes().into()), + (paint.clone(), Arc::from(b"<< /Type /ExtGState /ca 0.25 >>".as_slice())), + ] + .into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [root.clone()].into(), + generated: [effects.clone()].into(), + }) + .unwrap(); + let mut request = CompileRequest::new(world, entry, "entry.pdf", time).observe_generated_initial(); + request.entry = Entry::Format(format); + request.etex = true; + let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() + 60); + let first = compiler + .compile(request.clone().with_project(snapshot.clone())) + .unwrap(); + assert_eq!(fs::read(&effects).unwrap(), b"RELOAD\n"); + let next_snapshot = snapshot + .with_file_edits( + 2, + [(paint, Arc::from(b"<< /Type /ExtGState /ca 0.75 >>".as_slice()))].into(), + ) + .unwrap(); + let revised = request.with_project(next_snapshot); + let next = compiler.compile(revised.clone()).unwrap(); + assert!( + next.entry_checkpoint_work.reused_steps > 0, + "first: {:?}, revised: {:?}", + first.entry_checkpoint_work, + next.entry_checkpoint_work + ); + let delta = next.preview_since(Some(first.revision())).unwrap(); + assert_eq!(delta.pages.iter().map(|page| page.index).collect::>(), [1]); + assert_ne!(next.pdf, first.pdf); + assert_eq!(fs::read(&effects).unwrap(), b"RELOAD\n"); + let full = NativeCompiler::default().compile(revised).unwrap(); + assert_eq!(next.pdf, full.pdf); + assert_eq!(next.execution.execution.io, full.execution.execution.io); + assert_eq!(next.source_map.pages, full.source_map.pages); + assert_eq!( + next.preview_since(None).unwrap().pages, + full.preview_since(None).unwrap().pages + ); + fs::remove_dir_all(root).unwrap(); +}