diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 7f3607a..f042db1 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -242,6 +242,8 @@ pub struct Executor { pdf_outline_payload: usize, pdf_info_tokens: Vec, pdf_images: Vec, + restored_pdf_image_count: usize, + format_image_warnings: Vec, pdf_force_pagebox_warned: bool, input_position: Option<(usize, usize)>, paragraph: Option, @@ -419,6 +421,8 @@ impl Executor { pdf_outline_payload: 0, pdf_info_tokens: Vec::new(), pdf_images: Vec::new(), + restored_pdf_image_count: 0, + format_image_warnings: Vec::new(), pdf_force_pagebox_warned: false, input_position: None, paragraph: None, @@ -3170,8 +3174,10 @@ impl Executor { self.output_node(node, files)?; } self.collect_meaning_reads(); + let format_pdf_images = self.captured_format_pdf_images(); Ok(Execution { format_dumped: self.format_dumped, + format_pdf_images, job_name: self.job_name, interaction_mode: self.interaction_mode, native_page: self.native_page, @@ -3623,8 +3629,10 @@ impl Executor { let outgoing_state = previous .filter(|last| last.state == self.state) .map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state); + let format_pdf_images = self.captured_format_pdf_images(); Ok(Execution { format_dumped: self.format_dumped, + format_pdf_images, job_name: self.job_name, interaction_mode: self.interaction_mode, after_assignment: self.after_assignment, @@ -3653,6 +3661,7 @@ impl Executor { self.check_cancellation()?; self.change_interaction_mode(self.interaction_mode, files)?; let result = self.prepare_input(file, files).and_then(|initial_depth| { + self.emit_format_image_warnings(files)?; self.run_active_input(initial_depth, files, capture_boundary) }); self.finish_observed_input(result, files) @@ -4031,10 +4040,7 @@ impl Executor { return self .fail("dump requires closed groups and conditionals"); } - if !self.pdf_images.is_empty() { - return self - .fail("PDF image objects require a job-local PDF device"); - } + self.ensure_format_pdf_images()?; 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_image.rs b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs index c82e59b..02bac5c 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs @@ -1,5 +1,6 @@ use super::*; use crate::{ + execution::format_image::{FormatImageKind, FormatPdfImage}, pdf_image::{PageBox, PageSelection, PdfImage, PdfImageObject, PdfImageUse, XdvImagePlacement}, resources::ResourceKind, }; @@ -8,11 +9,64 @@ use crate::{ pub(super) struct RegisteredImage { image: Arc, attributes: Option>, + saved: Option, } impl Executor { + pub(in crate::execution) fn with_format_pdf_images( + mut self, + definitions: &[FormatPdfImage], + images: Vec>, + warnings: Vec, + ) -> Self { + self.restored_pdf_image_count = images.len(); + self.pdf_images = definitions.iter().zip(images).map(|(saved, image)| { + RegisteredImage { + image, + attributes: Some(saved.attributes.clone()), + saved: None, + } + }).collect(); + self.format_image_warnings = warnings; + self + } + + pub(super) fn ensure_format_pdf_images(&self) -> Result<(), Error> { + for image in &self.pdf_images { + if image.saved.is_none() { + return self.fail("cannot dump a format with XeTeX image objects"); + } + if image.image.image.color_space.is_some() { + return self.fail("cannot dump a format with image color-space object references"); + } + } + Ok(()) + } + + pub(super) fn captured_format_pdf_images(&self) -> Vec { + if !self.format_dumped { + return Vec::new(); + } + self.pdf_images.iter().filter_map(|image| image.saved.clone()).collect() + } + + pub(super) fn emit_format_image_warnings( + &mut self, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + for warning in std::mem::take(&mut self.format_image_warnings) { + self.pdf_image_warning(self.current, warning, files)?; + } + Ok(()) + } + pub(super) fn pdf_image_quantity(&mut self, command: Primitive) -> i32 { self.reads.insert(Dependency::PdfImages); + if command != Primitive::Pdflastximage + && self.pdf_images.len() == self.restored_pdf_image_count + { + return 0; + } match (command, self.pdf_images.last()) { (Primitive::Pdflastximage, Some(image)) => image.image.id as i32, (Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32, @@ -109,16 +163,23 @@ impl Executor { name: filename.clone(), from: from.clone(), }); + let kind = if pdftex { ResourceKind::PdfImage } else { ResourceKind::Tex }; let source = files - .resource(ResourceKind::Tex, &filename, &from) + .resource(kind, &filename, &from) .map_err(|error| { self.error( format!("cannot find image file {filename}: {error}"), token.span, ) })?; - let png = PdfImage::is_png(&source); - let image = if png || PdfImage::is_jpeg(&source) { + let format_kind = if PdfImage::is_png(&source) { + FormatImageKind::Png + } else if PdfImage::is_jpeg(&source) { + FormatImageKind::Jpeg + } else { + FormatImageKind::Pdf { page_box, remap_type1 } + }; + let image = if !matches!(format_kind, FormatImageKind::Pdf { .. }) { let resolution = self.read_parameter(Parameter::Pdfimageresolution).width(); let version = header.map_or_else( || ( @@ -127,7 +188,7 @@ impl Executor { ), |header| (header.major, i32::from(header.minor)), ); - let decoded = if png { + let decoded = if matches!(format_kind, FormatImageKind::Png) { PdfImage::read_png(source, resolution, color_space) } else { PdfImage::read_jpeg(source, resolution, version, color_space) @@ -146,16 +207,10 @@ impl Executor { let doc = PdfImage::open_pdf(&source) .map_err(|error| self.error(error, token.span))?; if let Some(header) = header { - let found = doc.version.parse::() - .map_err(|_| self.error("invalid imported PDF version", token.span))?; - let wanted = f64::from(header.major) + f64::from(header.minor) / 10.0; - if found > wanted + 0.01 && error_level >= 0 { - let message = format!( - "PDF inclusion: found PDF version <{found:.1}>, but at most version <{wanted:.1}> allowed" - ); - if error_level > 0 { - return Err(self.error(message, token.span)); - } + let version = (header.major, i32::from(header.minor)); + if let Some(message) = PdfImage::check_pdf_version(&doc, version, error_level) + .map_err(|error| self.error(error, token.span))? + { self.pdf_image_warning( token.span, format!("pdfTeX warning: pdftex (file {filename}): {message}"), @@ -169,9 +224,12 @@ impl Executor { let image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions) .map_err(|error| self.error(error, token.span))?; let id = image.id; + let saved = (pdftex && self.state.is_initex()) + .then(|| FormatPdfImage::capture(&image, &attributes, format_kind)); self.pdf_images.push(RegisteredImage { image: Arc::new(image), attributes: Some(attributes), + saved, }); if immediate { self.declare_pdf_image(id, files)?; @@ -344,6 +402,7 @@ impl Executor { self.pdf_images.push(RegisteredImage { image: image.clone(), attributes: Some(Vec::new()), + saved: None, }); self.defer_image(image, token) } @@ -404,6 +463,7 @@ impl Executor { self.pdf_images.push(RegisteredImage { image: image.clone(), attributes: None, + saved: None, }); let hidden = special.hidden; self.emit_pdf_image_object(image.clone(), special.attributes); diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 561cccc..e462ae2 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -1,6 +1,12 @@ //! Versioned format state kept separately from a live native execution. use super::*; -use crate::resources::{ResourceReadRange, ResourceVersion}; +use crate::{ + pdf_image::PdfImageUse, + resources::{ResourceKind, ResourceReadRange, ResourceTrace, ResourceVersion}, +}; +pub(super) mod boxes; +mod images; +pub(super) use images::{FormatImageKind, FormatPdfImage}; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -8,9 +14,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 82; -const COMPATIBLE_SCHEMAS: [u32; 49] = [ - 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, SCHEMA, +const SCHEMA: u32 = 83; +const COMPATIBLE_SCHEMAS: [u32; 50] = [ + 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, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -26,6 +32,8 @@ pub struct FormatImage { resources: Vec, stream_reads: Vec, file_dates: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pdf_images: Vec, #[serde(skip)] input_checks: OnceLock>, } @@ -53,6 +61,24 @@ struct Envelope { } impl FormatImage { + /// The format reopens its declared images by resolved path in the new + /// job. Keep version checks for all other reads, including a path also + /// used in some other role during the dump. + pub fn from_dump_with_trace(execution: Execution, trace: &ResourceTrace) -> Result { + let mut resources = trace.reads.clone(); + if !execution.format_pdf_images.is_empty() { + let declared: BTreeSet<_> = execution.format_pdf_images.iter() + .map(|image| &image.image.image.version.path).collect(); + let other: BTreeSet<_> = trace.lookups.iter() + .filter(|lookup| lookup.kind != ResourceKind::PdfImage) + .filter_map(|lookup| lookup.resolved.as_ref()).collect(); + resources.retain(|version| { + !declared.contains(&version.path) || other.contains(&version.path) + }); + } + Self::from_dump(execution, resources, trace.stream_reads.clone()) + } + pub fn from_dump( execution: Execution, resources: Vec, @@ -74,16 +100,23 @@ impl FormatImage { _ => None, }) .collect(); + let pdf_images = execution.format_pdf_images; + let mut state = execution.state.into_format_state(); + if !pdf_images.is_empty() { + let images: Vec<_> = pdf_images.iter().map(|saved| saved.image.clone()).collect(); + state.rebind_format_images(&images)?; + } Ok(Self { schema: SCHEMA, engine: ENGINE.into(), - state: execution.state.into_format_state(), + state, sources: execution.sources, stream_sources: execution.stream_sources, generated_inputs: execution.generated_inputs, resources, stream_reads, file_dates, + pdf_images, input_checks: OnceLock::new(), }) } @@ -158,6 +191,17 @@ impl FormatImage { Parameter::Pdfoptionalwaysusepdfpagebox, ]); } + if !image.pdf_images.is_empty() && (image.schema < 83 + || image.state.input_profile() != InputProfile::TeX8Bit + || image.pdf_images.iter().enumerate().any(|(index, saved)| { + saved.image.id != index + 1 + || saved.image.xdv.is_some() + || saved.image.image.color_space.is_some() + || saved.image.image.version.path.as_os_str().is_empty() + })) + { + return Err("invalid native format image registry".into()); + } image.schema = SCHEMA; Ok(image) } @@ -189,17 +233,22 @@ impl FormatImage { time: JobTime, limits: Limits, files: &mut F, - read: impl FnMut(&mut F, &Path) -> Result, + mut read: impl FnMut(&mut F, &Path) -> Result, date: impl FnMut(&mut F, &str, &str) -> Result, String>, ) -> Result { - self.validate_job_inputs(profile, input_profile, files, read, date)?; + self.validate_job_inputs(profile, input_profile, files, &mut read, date)?; + let (images, warnings) = self.restore_pdf_images(files, read)?; + let mut state = self.state.with_job_time(time); + if !images.is_empty() { + state.rebind_format_images(&images)?; + } Ok(Executor::new_format_job( - self.state.with_job_time(time), + state, self.sources, self.stream_sources, self.generated_inputs, limits, - )) + ).with_format_pdf_images(&self.pdf_images, images, warnings)) } /// Open a fresh job from a decoded seed after revalidating its actual inputs. @@ -229,20 +278,42 @@ impl FormatImage { time: JobTime, limits: Limits, files: &mut F, - read: impl FnMut(&mut F, &Path) -> Result, + mut read: impl FnMut(&mut F, &Path) -> Result, date: impl FnMut(&mut F, &str, &str) -> Result, String>, ) -> Result { - self.validate_job_inputs(profile, input_profile, files, read, date)?; + self.validate_job_inputs(profile, input_profile, files, &mut read, date)?; + let (images, warnings) = self.restore_pdf_images(files, read)?; + let mut state = self.state.clone().with_job_time(time); + if !images.is_empty() { + state.rebind_format_images(&images)?; + } Ok(Executor::new_format_job( - self.state.clone().with_job_time(time), + state, self.sources.clone(), self.stream_sources.clone(), self.generated_inputs.clone(), limits, - )) + ).with_format_pdf_images(&self.pdf_images, images, warnings)) } - /// Check the format profile and every required input without forking a job. + fn restore_pdf_images>( + &self, + files: &mut F, + mut read: impl FnMut(&mut F, &Path) -> Result, + ) -> Result<(Vec>, Vec), String> { + let mut images = Vec::with_capacity(self.pdf_images.len()); + let mut warnings = Vec::new(); + for saved in &self.pdf_images { + let path = saved.path(); + let bytes = read(files, path).map_err(|error| image_read_error(path, error))?; + let image = saved.restore(&self.state, bytes.as_ref(), &mut warnings) + .map_err(|error| format!("cannot load format image {}: {error}", path.display()))?; + images.push(image); + } + Ok((images, warnings)) + } + + /// Check the format profile and its recorded immutable inputs without forking a job. pub fn validate_job_inputs>( &self, profile: Profile, @@ -288,7 +359,15 @@ impl FormatImage { Ok(()) }, date, - ) + )?; + // Include each current image version in the host's checkpoint guard. + // The checkpoint owns the decoded payload and can only be reused when + // that guard accepts these actual reads. + for saved in &self.pdf_images { + let path = saved.path(); + read(files, path).map_err(|error| image_read_error(path, error))?; + } + Ok(()) } fn validate_inputs( @@ -389,6 +468,10 @@ impl FormatImage { } } +fn image_read_error(path: &Path, error: String) -> String { + format!("cannot find image file {}: {error}", path.display()) +} + fn digest(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } @@ -408,6 +491,7 @@ mod tests { stream_sources: BTreeSet::new(), generated_inputs: BTreeMap::new(), resources: Vec::new(), + pdf_images: Vec::new(), stream_reads: vec![ResourceReadRange { path: path.clone(), offset: 1, diff --git a/crates/texrra-tex-core/src/execution/format_image/boxes.rs b/crates/texrra-tex-core/src/execution/format_image/boxes.rs new file mode 100644 index 0000000..9f4cc29 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/format_image/boxes.rs @@ -0,0 +1,109 @@ +//! Rebind job-owned image payloads without changing packed dimensions. +use crate::{ + execution::{ + BoxContent, DiagnosticNode, LeaderGlue, LeaderPattern, NativeBox, + NativeVerticalNode, OutputNode, OutputOperation, TextNode, + }, + math_engine_tex::MathItem, + pdf_image::PdfImageUse, +}; +use std::sync::Arc; + +pub(in crate::execution) fn rebind( + b: &mut NativeBox, + images: &[Arc], +) -> Result<(), String> { + match &mut b.content { + BoxContent::Horizontal(nodes) => horizontal(nodes, images)?, + BoxContent::Vertical(nodes) => vertical(nodes, images)?, + } + diagnostics(&mut b.diagnostic, images) +} + +fn replace(image: &mut Arc, images: &[Arc]) -> Result<(), String> { + let replacement = image + .id + .checked_sub(1) + .and_then(|index| images.get(index)) + .filter(|replacement| replacement.dimensions() == image.dimensions()) + .ok_or_else(|| format!("invalid native format image placement {}", image.id))?; + *image = replacement.clone(); + Ok(()) +} + +fn output(node: &mut OutputNode, images: &[Arc]) -> Result<(), String> { + if let OutputOperation::PdfImage { image, .. } = &mut node.operation { + replace(image, images)?; + } + Ok(()) +} + +fn horizontal(nodes: &mut [TextNode], images: &[Arc]) -> Result<(), String> { + for node in nodes { + match node { + TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => { + if let Some(b) = &mut glyph.native_box { + rebind(b, images)?; + } + if let Some(geometry) = &mut glyph.math_geometry { + for item in &mut geometry.items { + if let MathItem::PdfImage(image) = &mut item.item { + replace(image, images)?; + } + } + } + } + TextNode::Discretionary { pre_break, post_break, .. } => { + horizontal(pre_break, images)?; + horizontal(post_break, images)?; + } + TextNode::Adjustment(value) => vertical(&mut value.nodes, images)?, + TextNode::Insertion(value) => vertical(&mut value.nodes, images)?, + TextNode::Leaders(pattern) => leader(pattern, images)?, + TextNode::Output(node) => output(node, images)?, + _ => {} + } + } + Ok(()) +} + +fn vertical(nodes: &mut [NativeVerticalNode], images: &[Arc]) -> Result<(), String> { + for node in nodes { + match node { + NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => rebind(b, images)?, + NativeVerticalNode::Insertion(value) => vertical(&mut value.nodes, images)?, + NativeVerticalNode::Leaders(pattern) => leader(pattern, images)?, + NativeVerticalNode::Output(node) => output(node, images)?, + _ => {} + } + } + Ok(()) +} + +fn leader(pattern: &mut LeaderGlue, images: &[Arc]) -> Result<(), String> { + if let LeaderPattern::Box(b) = &mut pattern.pattern { + rebind(b, images)?; + } + Ok(()) +} + +fn diagnostics(nodes: &mut [DiagnosticNode], images: &[Arc]) -> Result<(), String> { + for node in nodes { + match node { + DiagnosticNode::Box(b) => diagnostics(&mut b.nodes, images)?, + DiagnosticNode::Leaders { pattern, .. } => { + diagnostics(std::slice::from_mut(pattern.as_mut()), images)?; + } + DiagnosticNode::Discretionary { pre, post, .. } => { + diagnostics(pre, images)?; + diagnostics(post, images)?; + } + DiagnosticNode::Adjustment { nodes, .. } | DiagnosticNode::Insertion { nodes, .. } => { + diagnostics(nodes, images)?; + } + DiagnosticNode::Output(node) => output(node, images)?, + _ => {} + } + } + Ok(()) +} diff --git a/crates/texrra-tex-core/src/execution/format_image/images.rs b/crates/texrra-tex-core/src/execution/format_image/images.rs new file mode 100644 index 0000000..de2580f --- /dev/null +++ b/crates/texrra-tex-core/src/execution/format_image/images.rs @@ -0,0 +1,96 @@ +//! The format keeps declared page selections and TeX dimensions. The new +//! job reads the current resource before it can use any saved image node. +use super::digest; +use crate::{ + execution::{Parameter, State, Token}, + pdf_image::{PdfImage, PdfImageUse}, + resources::{LoadedResource, ResourceVersion}, +}; +use serde::{Deserialize, Serialize}; +use std::{path::Path, sync::Arc}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(in crate::execution) enum FormatImageKind { + Pdf { page_box: i32, remap_type1: bool }, + Png, + Jpeg, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(in crate::execution) struct FormatPdfImage { + pub image: Arc, + pub attributes: Vec, + pub kind: FormatImageKind, +} + +impl FormatPdfImage { + pub(in crate::execution) fn capture( + place: &PdfImageUse, + attributes: &[Token], + kind: FormatImageKind, + ) -> Self { + Self { + image: Arc::new(PdfImageUse { + image: Arc::new(place.image.without_payload()), + ..place.clone() + }), + attributes: attributes.to_vec(), + kind, + } + } + + pub(super) fn path(&self) -> &Path { + &self.image.image.version.path + } + + pub(super) fn restore( + &self, + state: &State, + data: &[u8], + warnings: &mut Vec, + ) -> Result, String> { + let path = &self.image.image.version.path; + let resolution = state.parameter(Parameter::Pdfimageresolution).width(); + let version = ( + state.parameter(Parameter::Pdfmajorversion).width(), + state.parameter(Parameter::Pdfminorversion).width(), + ); + let resource = LoadedResource { + version: ResourceVersion { + path: path.clone(), + bytes: data.len() as u64, + sha256: digest(data), + }, + data: data.to_vec(), + }; + let color_space = self.image.image.color_space; + let image = match self.kind { + FormatImageKind::Pdf { page_box, remap_type1 } => { + let source = PdfImage::open_pdf(&resource)?; + let error_level = state.parameter(Parameter::Pdfinclusionerrorlevel).width(); + if let Some(message) = PdfImage::check_pdf_version(&source, version, error_level)? { + warnings.push(format!( + "pdfTeX warning: pdftex (file {}): {message}", + path.display(), + )); + } + PdfImage::read_format_page(resource, source, self.image.image.page, page_box, remap_type1)? + } + FormatImageKind::Png | FormatImageKind::Jpeg => { + let (image, warning) = if matches!(self.kind, FormatImageKind::Png) { + PdfImage::read_png(resource, resolution, color_space)? + } else { + PdfImage::read_jpeg(resource, resolution, version, color_space)? + }; + if let Some(warning) = warning { + warnings.push(format!("pdfTeX warning: pdftex: {warning}")); + } + image + } + }; + Ok(Arc::new(PdfImageUse { + image: Arc::new(image), + ..self.image.as_ref().clone() + })) + } +} diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index edb40f4..f93a9a5 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -582,6 +582,8 @@ fn default_interaction_mode() -> u8 { pub struct Execution { #[serde(default)] pub format_dumped: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + format_pdf_images: Vec, #[serde(default)] pub job_name: Option, #[serde(default = "default_interaction_mode")] diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 7c79b87..b31d8db 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1660,6 +1660,16 @@ impl State { self.fonts.reset_format_font_state(); self } + pub(super) fn rebind_format_images( + &mut self, + images: &[std::sync::Arc], + ) -> Result<(), String> { + for b in self.boxes.values_mut() { + super::format_image::boxes::rebind(b, images)?; + } + Ok(()) + } + 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 47135ac..c6031ab 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1144,11 +1144,19 @@ fn page_content( crate::pdf_image::real(list.units.bp(*image_height) / natural_height), ] }; + let [dx, dy] = image.image.restored_pdf_origin.map_or([0, 0], |origin| { + let placed = [*width, *image_height]; + std::array::from_fn(|axis| { + crate::pdf_device::divide_scaled( + placed[axis] * origin[axis], image.image.natural[axis], 0, + ).0 + }) + }); let name = image.id; content.push_str(&format!( "q {sx} 0 0 {sy} {} {} cm /PI{name} Do Q\n", - px(*x), - py(*y + *image_height) + px(*x - dx), + py(*y + *image_height + dy) )); } DisplayItem::Frame { diff --git a/crates/texrra-tex-core/src/pdf_image.rs b/crates/texrra-tex-core/src/pdf_image.rs index 5c596b6..9b67725 100644 --- a/crates/texrra-tex-core/src/pdf_image.rs +++ b/crates/texrra-tex-core/src/pdf_image.rs @@ -36,6 +36,7 @@ pub(crate) enum PageBox { enum PageBoxSelection { PdfTeX(i32), + RestoredPdfTeX(i32), Xdv(PageBox), } @@ -46,6 +47,8 @@ pub struct PdfImage { pub page_count: usize, pub natural: [i64; 2], extent: [u64; 2], + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) restored_pdf_origin: Option<[i64; 2]>, objects: Vec>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) color_space: Option, @@ -353,6 +356,40 @@ pub(crate) fn real(value: f64) -> String { } impl PdfImage { + pub(crate) fn without_payload(&self) -> Self { + Self { + version: self.version.clone(), + page: self.page, + page_count: self.page_count, + natural: self.natural, + extent: self.extent, + restored_pdf_origin: self.restored_pdf_origin, + objects: Vec::new(), + color_space: self.color_space, + imported_fonts: Vec::new(), + } + } + + pub(crate) fn check_pdf_version( + doc: &Document, + (major, minor): (i32, i32), + error_level: i32, + ) -> Result, String> { + let found = doc.version.parse::() + .map_err(|_| "invalid imported PDF version")?; + let wanted = f64::from(major) + f64::from(minor) / 10.0; + if found <= wanted + 0.01 || error_level < 0 { + return Ok(None); + } + let message = format!( + "PDF inclusion: found PDF version <{found:.1}>, but at most version <{wanted:.1}> allowed" + ); + if error_level > 0 { + return Err(message); + } + Ok(Some(message)) + } + pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool { resource.data.starts_with(jpeg::SIGNATURE) || (!resource.data.starts_with(b"%PDF-") @@ -464,6 +501,7 @@ impl PdfImage { page_count: 1, natural, extent: extent.map(f64::to_bits), + restored_pdf_origin: None, objects, color_space, imported_fonts: Vec::new(), @@ -511,6 +549,7 @@ impl PdfImage { page_count: 1, natural: natural(bp), extent: bp.map(f64::to_bits), + restored_pdf_origin: None, objects: vec![vec![part]], color_space: None, imported_fonts: Vec::new(), @@ -585,6 +624,20 @@ impl PdfImage { .map(|(image, _)| image) } + pub(crate) fn read_format_page( + resource: LoadedResource, + doc: Document, + page: usize, + page_box: i32, + remap_type1: bool, + ) -> Result { + let page = u32::try_from(page).map_err(|_| "invalid saved PDF page number")?; + Self::read_page( + resource, doc, PageBoxSelection::RestoredPdfTeX(page_box), remap_type1, |_, _| Ok(page), + ) + .map(|(image, _)| image) + } + pub(crate) fn read_xdv( resource: LoadedResource, page: i32, @@ -636,11 +689,12 @@ impl PdfImage { .ok_or("required page does not exist")?; let chain = page_chain(&doc, page_id)?; let inherited = |name: &[u8]| chain.iter().find_map(|dict| dict.get(name).ok()); + let restored = matches!(box_selection, PageBoxSelection::RestoredPdfTeX(_)); let ([left, bottom, right, top], rotation, keep_page_origin) = match box_selection { - PageBoxSelection::PdfTeX(spec) => ( + PageBoxSelection::PdfTeX(spec) | PageBoxSelection::RestoredPdfTeX(spec) => ( page_boxes::pdftex(&doc, &chain, spec)?, page_boxes::pdftex_rotation(&doc, &chain), - false, + restored, ), PageBoxSelection::Xdv(kind) => ( page_boxes::xdv(&doc, &chain, kind)?, @@ -675,8 +729,7 @@ impl PdfImage { _ => return Err("PDF image rotation must be a multiple of 90 degrees".into()), }; if keep_page_origin { - // XDV pictures place the PDF page using a matrix that already - // accounts for the selected page-box origin. + // The outer placement accounts for the selected page-box origin. matrix[4] += left; matrix[5] += bottom; } @@ -687,7 +740,24 @@ impl PdfImage { } Ok(value as i64) }; - let natural = [sp(width)?, sp(height)?]; + // pdfTeX reopens the PDF with unrotated dimensions for the outer + // placement. The actual page rotation still belongs to the Form. + let (natural, restored_pdf_origin) = if restored { + let source_sp = |bp: f64| { + (f64::from(bp as f32) * 6_578_176.0 / 100.0).round() + }; + let [width, height] = [source_sp(right - left), source_sp(top - bottom)]; + if ![width, height].into_iter().all(|n| (1.0..=1073741823.0).contains(&n)) { + return Err("invalid image dimensions".into()); + } + let origin = [source_sp(left), source_sp(bottom)]; + if !origin.into_iter().all(|n| (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&n)) { + return Err("invalid image origin".into()); + } + ([width as i64, height as i64], Some(origin.map(|n| n as i64))) + } else { + ([sp(width)?, sp(height)?], None) + }; let mut contents = Vec::new(); if let Ok(content) = chain[0].get(b"Contents") { read_contents(&doc, content, &mut contents, 0)?; @@ -736,6 +806,7 @@ impl PdfImage { page_count: pages.len(), natural, extent: [width.to_bits(), height.to_bits()], + restored_pdf_origin, objects: graph.bodies, color_space: None, imported_fonts, diff --git a/crates/texrra-tex-core/src/pdf_image/png.rs b/crates/texrra-tex-core/src/pdf_image/png.rs index 06a2320..057cb86 100644 --- a/crates/texrra-tex-core/src/pdf_image/png.rs +++ b/crates/texrra-tex-core/src/pdf_image/png.rs @@ -143,6 +143,7 @@ pub(super) fn read( objects: vec![vec![Part::Png(image)]], color_space, imported_fonts: Vec::new(), + restored_pdf_origin: None, }, warning, )) diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index adf8011..68887ea 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -33,11 +33,12 @@ pub enum ResourceKind { Format, Config, FontMapping, + PdfImage, } impl ResourceKind { fn directory(self) -> &'static str { match self { - Self::Tex => "tex", + Self::Tex | Self::PdfImage => "tex", Self::Tfm => "fonts/tfm", Self::Vf => "fonts/vf", Self::Type1 => "fonts/type1", @@ -52,7 +53,7 @@ impl ResourceKind { } fn environment(self) -> &'static str { match self { - Self::Tex => "TEXINPUTS", + Self::Tex | Self::PdfImage => "TEXINPUTS", Self::Tfm => "TFMFONTS", Self::Vf => "VFFONTS", Self::Type1 => "T1FONTS", @@ -68,7 +69,7 @@ impl ResourceKind { } fn extensions(self) -> &'static [&'static str] { match self { - Self::Tex => &["tex"], + Self::Tex | Self::PdfImage => &["tex"], Self::Tfm => &["tfm"], Self::Vf => &["vf"], Self::Type1 => &["pfb", "pfa"], @@ -1238,6 +1239,12 @@ impl FileWorld { } } fn paths(&self, kind: ResourceKind, from: &Path) -> Vec { + // Images use the TeX namespace and have their own dependency role. + let kind = if kind == ResourceKind::PdfImage { + ResourceKind::Tex + } else { + kind + }; let mut defaults = vec![SearchPath::directory(&self.config.cwd, false)]; if kind == ResourceKind::Tex && self.config.input_policy == InputPolicy::Project { if let Some(parent) = from.parent() { diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index ed41661..33549d6 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -655,6 +655,40 @@ p95 为 396.861 ms。阶段边界按每次实际观测计算。 2654623 sp 并产生一页 PDF。原生从同一输入执行到 `\dump` 时拒绝 注册过的图像;保留失败诊断和原版格式镜像以供后续对照。 +### 原生格式重载已登记的图像 + +schema83 保存 pdfTeX profile 的 PDF、PNG、JPEG 图像登记、属性、 +已选数字页和已装箱尺寸。加载时在启动正文前按已解析的路径重开当前 +字节,并用新作业的 PDF 版本规则检查资源。PDF 的页面和裁边保留 +转储时的选择,命名目标改绑后也不重选。旋转页按实际重载行为, +用未旋转的页框尺寸和来源坐标计算放置,Form 内部仍应用源页旋转。 +盒子和诊断节点换绑到重载的图像,镜像中的图像登记只保存元数据。立即写出的图像 +在新作业需要时重新生成。缺失资源在读取正文前报告,包括登记后从未放置的图像。 +[TeX Live 图像重载实现](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writeimg.c#L420-L529) + +以 pdfTeX 1.40.29 和原生优化版独立转储、重载,八个成功用例的 +16 页在 144 DPI 灰度下逐像素一致。覆盖命名目标改绑、实际内容与裁边 +改变、选择 MediaBox 和实际 Form 属性、立即登记、PNG 透明度和 JPEG。 +盒尺寸、以保存编号引用的尺寸、初始查询和下一图像的页数与位深一致。 +记录保留后续图像编号的差异,原生使用图像登记编号,参考端使用 PDF 全局 +对象编号。透明 PNG 的参考 PDF 触发 Poppler 对缺失交叉引用的恢复警告, +原生 PDF 可直接渲染。颜色空间跨格式引用和 XeTeX 图像转储仍明确拒绝。 +格式样稿的普通输入角色仍校验原字节版本,schema82 实际存档仍能重载。 + +同一原子项目的尾部子文件修改继续从原检查点续跑。随后修改登记图片, +旧检查点因实际图片版本改变被拒绝,仅替换第二页的 SVG。使用同版本独立 +全量核对完整 PDF、页面 SVG 和来源映射。旧差分、两例缺失图像、原版 +颜色空间探针的崩溃及定向回归留在 `target/p3-format-images`。 +图像回归 5 项与核心格式回归 4 项通过,CLI 优化编译检查通过。 +回执 `receipt.json` SHA-256 为 `3b85cf0ccc8bf999bdb28d459ba11bc8801d7bca9d941516e99fb145c497363a`。 +统一项目与实时性能门禁保持原计划。 + +下一处差异由同一原样 XeTeX 小作业复现。PDF 与 PNG 在原版和原生的 +装箱尺寸相同。参考 XeTeX 0.999998 转储和重载两个盒子已通过, +xdvipdfmx 生成两页 PDF。原生停在转储。另一个确实加载了 OpenType +并装箱文字的原版 INITEX 作业拒绝转储。两组独立记录分别保存在 +`target/p3-format-images/next-xetex-image` 和 `next-xetex-font`。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/src/native.rs b/src/native.rs index 189863f..bec7d4c 100644 --- a/src/native.rs +++ b/src/native.rs @@ -1344,12 +1344,8 @@ fn dump_format_observed( let trace = files.resource_trace(); // Keep the completed kernel result available if format validation/encoding // fails. This extra offline copy is not part of interactive compilation. - let bytes = FormatImage::from_dump( - execution.execution.clone(), - trace.reads.clone(), - trace.stream_reads.clone(), - )? - .encode()?; + let bytes = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)? + .encode()?; evidence.phase = AttemptPhase::Finishing; let finished = files.finish(); let reported = report(&files, &request); diff --git a/tests/native_pdf_image.rs b/tests/native_pdf_image.rs index 070e20b..d248a90 100644 --- a/tests/native_pdf_image.rs +++ b/tests/native_pdf_image.rs @@ -451,3 +451,137 @@ fn png_project_edit_updates_only_the_page_using_the_image() { assert_eq!(images[0].1.content, [255, 128]); fs::remove_dir_all(root).unwrap(); } + +#[test] +fn format_image_resource_edits_invalidate_checkpoints_and_update_the_picture_page() { + use texrra_engine::native::dump_format; + use texrra_tex_core::{execution::Cancellation, render::DisplayItem}; + + let root = std::env::temp_dir().join(format!("texrra-format-image-{}", 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 figure = root.join("picture.pdf"); + let input = root.join("entry.tex"); + let tail = root.join("tail.tex"); + fs::write( + &seed, + r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=5 +\pdfximage width40pt trimbox {picture.pdf} +\setbox0=\hbox{\pdfrefximage\pdflastximage} +\dump +", + ) + .unwrap(); + rotated_document(&figure); + let time = JobTime::new(2026, 11, 26, 0).unwrap(); + let world = WorldConfig::new(&root); + let mut dump = CompileRequest::new(world.clone(), &seed, &format, time); + dump.entry = Entry::Initex; + dump.etex = true; + dump_format(dump, Cancellation::default()).unwrap(); + + let prefix = r"\pdfpagewidth=150pt \pdfpageheight=150pt +\shipout\hbox{\vrule width10pt height4pt} +"; + let padding = format!("{}\n", "\\relax ".repeat(32)).repeat(48); + let entry = format!( + "{prefix}{padding}\\shipout\\copy0\n\\input tail.tex\n\\shipout\\hbox{{\\vrule width\\tailwidth pt height4pt}}\n\\end\n" + ); + let original = fs::read(&figure).unwrap(); + let mut edited = Document::load_mem(&original).unwrap(); + let mut changed = false; + for object in edited.objects.values_mut() { + let Ok(stream) = object.as_stream_mut() else { + continue; + }; + if stream.content.starts_with(b"1 0 0 rg") { + stream.content[..8].copy_from_slice(b"0 0 1 rg"); + changed = true; + } + } + assert!(changed); + let mut recolored = Vec::new(); + edited.save_to(&mut recolored).unwrap(); + + let files = [ + (seed.clone(), fs::read(&seed).unwrap().into()), + (format.clone(), fs::read(&format).unwrap().into()), + (figure.clone(), original.into()), + (input.clone(), entry.into_bytes().into()), + (tail.clone(), Arc::from(br"\def\tailwidth{12}".as_slice())), + ] + .into(); + let snapshot = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: [root.clone()].into(), + files, + directories: Default::default(), + aliases: Default::default(), + generated_roots: [root.clone()].into(), + generated: Default::default(), + }) + .unwrap(); + let mut request = + CompileRequest::new(world, &input, "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!(first.entry_checkpoint_work.captured_frontier.is_some()); + let edits = [(tail, Some(Arc::from(br"\def\tailwidth{18}".as_slice())))].into(); + let snapshot = snapshot.with_file_changes(2, edits).unwrap(); + let second = compiler + .compile(request.clone().with_project(snapshot.clone())) + .unwrap(); + assert!(second.entry_checkpoint_work.reused_steps > 0); + let edits = [(figure.clone(), Some(recolored.into()))].into(); + let snapshot = snapshot.with_file_changes(3, edits).unwrap(); + let revised = request.with_project(snapshot); + let third = compiler.compile(revised.clone()).unwrap(); + assert_eq!(third.entry_checkpoint_work.reused_steps, 0); + assert!( + third + .entry_checkpoint_work + .rejection + .as_deref() + .unwrap_or_default() + .contains("checkpoint observed input changed"), + "{:?}", + third.entry_checkpoint_work + ); + + let image_page = &third.pages[1]; + let image = image_page + .items + .iter() + .find_map(|item| match item { + DisplayItem::PdfImage { image, .. } => Some(image), + _ => None, + }) + .unwrap(); + // Reloading a rotated PDF uses the new unrotated trim-box measures. + assert_eq!(image.image.natural, [8_222_720, 3_683_779]); + assert_eq!(image.image.version.path, figure); + assert!(third.resources.trace.reads.contains(&image.image.version)); + assert_ne!(third.pdf, second.pdf); + + let delta = third.preview_since(Some(second.revision())).unwrap(); + let pages: Vec<_> = delta.pages.iter().map(|page| page.index).collect(); + assert_eq!(pages, [1]); + let full = NativeCompiler::default().compile(revised).unwrap(); + assert_eq!(third.pdf, full.pdf); + assert_eq!(third.source_map.sources, full.source_map.sources); + assert_eq!(third.source_map.pages, full.source_map.pages); + assert_eq!( + third.preview_since(None).unwrap().pages, + full.preview_since(None).unwrap().pages, + ); + fs::remove_dir_all(root).unwrap(); +}