Restore XeTeX picture boxes at native shipout

This commit is contained in:
gloamxun committed 2026-11-27 13:41:27 +08:00
1 parent c2f18f50dc
commit 9da2ee41cd
7 files changed
+308 -35

No files matched your search

@@ -413,6 +413,7 @@ impl Executor {
let mut has_explicit_space = false;
let mut pdf_objects = Vec::new();
let mut xdv_annotations = std::collections::BTreeMap::new();
let mut reopened_images = false;
for (index, output) in outputs.into_iter().enumerate() {
while font_uses.peek().is_some_and(|usage| usage.before_output == index) {
self.current = current;
@@ -604,6 +605,9 @@ impl Executor {
LinkNode::Running(_) | LinkNode::Destination { .. } => {}
}
} else {
if let OutputOperation::PdfImage { image, .. } = &output.operation {
reopened_images |= image.xdv.is_some() && image.image.is_metadata_only();
}
self.output_node(output, files)?;
}
}
@@ -650,6 +654,9 @@ impl Executor {
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
shipout.pdf_links = links;
}
if reopened_images {
self.rebind_shipped_format_images(&mut shipout.box_node)?;
}
if xdv && (!xdv_annotations.is_empty() || self.xdv_annotations.is_active()) {
shipout.pdf_links.xdv_annotations = self.ship_xdv_annotations(&shipout, &xdv_annotations, files)?;
}
@@ -10,6 +10,7 @@ pub(super) struct RegisteredImage {
image: Arc<PdfImageUse>,
attributes: Option<Vec<Token>>,
saved: Option<FormatPdfImage>,
pending_xdv: Option<FormatImageKind>,
}
impl Executor {
@@ -23,8 +24,10 @@ impl Executor {
self.pdf_images = definitions.iter().zip(images).map(|(saved, image)| {
RegisteredImage {
image,
attributes: Some(saved.attributes.clone()),
attributes: (!matches!(saved.kind, FormatImageKind::XdvShippedSpecial))
.then(|| saved.attributes.clone()),
saved: None,
pending_xdv: (!saved.kind.reads_at_load()).then_some(saved.kind),
}
}).collect();
self.format_image_warnings = warnings;
@@ -34,7 +37,7 @@ impl Executor {
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");
return self.fail("cannot dump a format with an unrecorded image object");
}
if image.image.image.color_space.is_some() {
return self.fail("cannot dump a format with image color-space object references");
@@ -230,6 +233,7 @@ impl Executor {
image: Arc::new(image),
attributes: Some(attributes),
saved,
pending_xdv: None,
});
if immediate {
self.declare_pdf_image(id, files)?;
@@ -341,7 +345,7 @@ impl Executor {
return self.fail("XeTeX image is illegal in math mode");
}
let (name, from) = self.xdv_image_filename(token, files)?;
let (image, source_origin, page) = if pdf {
let (image, source_origin, page, format_kind) = if pdf {
let page = if self.keyword("page", files)? {
self.integer(files)?
} else {
@@ -361,13 +365,16 @@ impl Executor {
}
}
let resource = files
.resource(ResourceKind::Tex, &name, &from)
.resource(ResourceKind::PdfImage, &name, &from)
.map_err(|message| self.error(message, token.span))?;
let (image, source_origin) = PdfImage::read_xdv(resource, page, box_type)
.map_err(|message| self.error(message, token.span))?;
(Arc::new(image), source_origin, page)
(Arc::new(image), source_origin, page, FormatImageKind::XdvPdf { page_box: box_type })
} else {
(self.xdv_raster_source(&name, &from, token.span, files)?, [0.0; 2], 0)
(
self.xdv_raster_source(&name, &from, token.span, files)?,
[0.0; 2], 0, FormatImageKind::XdvRaster,
)
};
let mut placement = XdvImagePlacement::new(&image, source_origin);
loop {
@@ -399,10 +406,12 @@ impl Executor {
let image = PdfImageUse::new_xdv(self.pdf_images.len() + 1, image, placement, page)
.map_err(|message| self.error(message, token.span))?;
let image = Arc::new(image);
let saved = self.state.is_initex().then(|| FormatPdfImage::capture(&image, &[], format_kind));
self.pdf_images.push(RegisteredImage {
image: image.clone(),
attributes: Some(Vec::new()),
saved: None,
saved,
pending_xdv: None,
});
self.defer_image(image, token)
}
@@ -415,7 +424,7 @@ impl Executor {
files: &mut impl SourceProvider,
) -> Result<Arc<PdfImage>, Error> {
let resource = files
.resource(ResourceKind::Tex, name, from)
.resource(ResourceKind::PdfImage, name, from)
.map_err(|message| self.error(message, span))?;
// A layout measurement and later shipout share the decoded pixels
// only if the resource provider returns the same version.
@@ -460,10 +469,14 @@ impl Executor {
let image = special.place(self.pdf_images.len() + 1, resource)
.map_err(|error| self.error(error, span))?;
let image = Arc::new(image);
let saved = self.state.is_initex().then(|| {
FormatPdfImage::capture(&image, &[], FormatImageKind::XdvShippedSpecial)
});
self.pdf_images.push(RegisteredImage {
image: image.clone(),
attributes: None,
saved: None,
saved,
pending_xdv: None,
});
let hidden = special.hidden;
self.emit_pdf_image_object(image.clone(), special.attributes);
@@ -476,6 +489,9 @@ impl Executor {
pub(super) fn declare_pdf_image(
&mut self, id: usize, files: &mut impl SourceProvider,
) -> Result<(), Error> {
if let Some(kind) = self.pdf_images[id - 1].pending_xdv {
self.open_format_xdv_image(id, kind, files)?;
}
let registered = &mut self.pdf_images[id - 1];
let Some(tokens) = registered.attributes.take() else {
return Ok(());
@@ -519,6 +535,42 @@ impl Executor {
Ok(())
}
fn open_format_xdv_image(
&mut self,
id: usize,
kind: FormatImageKind,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let saved = &self.pdf_images[id - 1].image;
let path = saved.image.version.path.to_string_lossy();
let from = self.source_name(self.current);
self.reads.insert(Dependency::FileLookup {
name: path.to_string(),
from: from.clone(),
});
let resource = files.resource(ResourceKind::PdfImage, &path, &from)
.map_err(|message| self.error(message, self.current))?;
let page = saved.xdv.as_ref().expect("registered XDV placement").page_request;
let actual = match kind {
FormatImageKind::XdvPdf { page_box } => {
PdfImage::read_xdv(resource, page, page_box).map(|(image, _)| image)
}
FormatImageKind::XdvRaster => PdfImage::read_xdv_raster(resource),
_ => return self.fail("missing saved XDV image declaration"),
}.map_err(|message| self.error(message, self.current))?;
let placed = Arc::new(saved.with_current_xdv_image(actual));
let registered = &mut self.pdf_images[id - 1];
registered.image = placed;
registered.pending_xdv = None;
Ok(())
}
pub(super) fn rebind_shipped_format_images(&self, b: &mut NativeBox) -> Result<(), Error> {
let images: Vec<_> = self.pdf_images.iter().map(|entry| entry.image.clone()).collect();
crate::execution::format_image::boxes::rebind(b, &images)
.map_err(|message| self.error(message, b.span))
}
fn emit_pdf_image_object(&mut self, image: Arc<PdfImageUse>, attributes: Vec<u8>) {
let compression = self
.read_parameter(Parameter::Pdfcompresslevel)
@@ -14,9 +14,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
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 SCHEMA: u32 = 84;
const COMPATIBLE_SCHEMAS: [u32; 51] = [
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, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -191,16 +191,21 @@ 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());
for (index, saved) in image.pdf_images.iter().enumerate() {
let valid_profile = if saved.kind.reads_at_load() {
image.schema >= 83 && image.state.input_profile() == InputProfile::TeX8Bit
&& saved.image.xdv.is_none()
} else {
image.schema >= 84 && image.state.input_profile() == InputProfile::XeTeX
&& saved.image.xdv.is_some()
};
if !valid_profile
|| saved.image.id != index + 1
|| saved.image.image.color_space.is_some()
|| saved.path().as_os_str().is_empty()
{
return Err("invalid native format image registry".into());
}
}
image.schema = SCHEMA;
Ok(image)
@@ -304,6 +309,10 @@ impl FormatImage {
let mut images = Vec::with_capacity(self.pdf_images.len());
let mut warnings = Vec::new();
for saved in &self.pdf_images {
if !saved.kind.reads_at_load() {
images.push(saved.image.clone());
continue;
}
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)
@@ -363,7 +372,7 @@ impl FormatImage {
// 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 {
for saved in self.pdf_images.iter().filter(|saved| saved.kind.reads_at_load()) {
let path = saved.path();
read(files, path).map_err(|error| image_read_error(path, error))?;
}
@@ -3,17 +3,28 @@
use super::digest;
use crate::{
execution::{Parameter, State, Token},
pdf_image::{PdfImage, PdfImageUse},
pdf_image::{PageBox, PdfImage, PdfImageUse},
resources::{LoadedResource, ResourceVersion},
};
use serde::{Deserialize, Serialize};
use std::{path::Path, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::execution) enum FormatImageKind {
Pdf { page_box: i32, remap_type1: bool },
Png,
Jpeg,
XdvPdf { page_box: PageBox },
XdvRaster,
// An earlier shipout may have allocated a device slot. Its original
// special remains a special in saved boxes and runs again if shipped.
XdvShippedSpecial,
}
impl FormatImageKind {
pub(in crate::execution) fn reads_at_load(self) -> bool {
matches!(self, Self::Pdf { .. } | Self::Png | Self::Jpeg)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -87,6 +98,8 @@ impl FormatPdfImage {
}
image
}
FormatImageKind::XdvPdf { .. } | FormatImageKind::XdvRaster
| FormatImageKind::XdvShippedSpecial => return Err("XDV images require shipout".into()),
};
Ok(Arc::new(PdfImageUse {
image: Arc::new(image),
+32 -10
View File
@@ -23,7 +23,7 @@ pub(crate) enum PageSelection {
Named(Vec<u8>),
}
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(i32)]
pub(crate) enum PageBox {
Media = 1,
@@ -72,6 +72,8 @@ pub(crate) struct XdvPdfPlacement {
pub(crate) page_request: i32,
matrix: [u64; 6],
#[serde(default, skip_serializing_if = "Option::is_none")]
raster_source_matrix: Option<[u64; 6]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
clip: Option<[u64; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
annotation_box: Option<[u64; 4]>,
@@ -174,15 +176,10 @@ impl PdfImageUse {
.parse()
.expect("printed 16.16 value")
});
let matrix = if image.raster_frame().is_some() {
let [width, height] = image.extent();
Affine(matrix)
.concatenate(Affine([width, 0.0, 0.0, height, 0.0, 0.0]))
.0
.map(|value| (value * 100_000.0).round() / 100_000.0)
} else {
matrix
};
let raster_source_matrix = image.raster_frame().is_some().then_some(matrix);
let matrix = raster_source_matrix.map_or(matrix, |matrix| {
Self::scale_xdv_raster(matrix, image.extent())
});
Ok(Self {
id,
image,
@@ -192,6 +189,7 @@ impl PdfImageUse {
xdv: Some(XdvPdfPlacement {
page_request,
matrix: matrix.map(f64::to_bits),
raster_source_matrix: raster_source_matrix.map(|matrix| matrix.map(f64::to_bits)),
clip: None,
annotation_box: None,
layout_offset: [0, 0],
@@ -237,6 +235,7 @@ impl PdfImageUse {
xdv: Some(XdvPdfPlacement {
page_request: 0,
matrix: matrix.map(f64::to_bits),
raster_source_matrix: None,
clip: clip.map(|rect| rect.map(f64::to_bits)),
annotation_box: annotation_box.map(|rect| rect.map(f64::to_bits)),
layout_offset: [left as i64, bottom as i64],
@@ -244,6 +243,25 @@ impl PdfImageUse {
})
}
fn scale_xdv_raster(matrix: [f64; 6], [width, height]: [f64; 2]) -> [f64; 6] {
Affine(matrix)
.concatenate(Affine([width, 0.0, 0.0, height, 0.0, 0.0]))
.0
.map(|value| (value * 100_000.0).round() / 100_000.0)
}
pub(crate) fn with_current_xdv_image(&self, image: PdfImage) -> Self {
let mut placed = self.clone();
if let Some(placement) = &mut placed.xdv
&& let Some(matrix) = placement.raster_source_matrix
{
placement.matrix = Self::scale_xdv_raster(matrix.map(f64::from_bits), image.extent())
.map(f64::to_bits);
}
placed.image = Arc::new(image);
placed
}
pub(crate) fn dimensions(&self) -> (i64, i64, i64) {
(self.width, self.height, self.depth)
}
@@ -356,6 +374,10 @@ pub(crate) fn real(value: f64) -> String {
}
impl PdfImage {
pub(crate) fn is_metadata_only(&self) -> bool {
self.objects.is_empty()
}
pub(crate) fn without_payload(&self) -> Self {
Self {
version: self.version.clone(),