Measure XeLaTeX graphics links from device placement

This commit is contained in:
gloamxun committed 2026-11-28 20:38:11 +08:00
1 parent d875b69280
commit d627614af8
12 files changed
+295 -149

No files matched your search

@@ -547,6 +547,7 @@ impl Executor {
let mut pdf_objects = Vec::new();
let mut pdf_images = Vec::new();
let mut pdf_forms = Vec::new();
let mut content_origins = Vec::new();
let mut xdv_annotations = std::collections::BTreeMap::new();
let mut reopened_images = false;
let mut xdv_paper_specials = Vec::new();
@@ -642,7 +643,7 @@ impl Executor {
(special.position[0] + horizontal_origin) as f64,
(special.position[1] + vertical_origin + b.height) as f64,
).map(|coordinate| coordinate.round() as i64);
xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin));
xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin, content_origins.last().copied()));
None
} else if xdv && self.xdv_setup_special(&special)? {
None
@@ -653,6 +654,13 @@ impl Executor {
None
};
use crate::pdf_device::{PdfGraphics, PdfLiteralMode};
if let Some(PdfGraphics::Literal { mode, .. }) = &graphics {
match mode {
PdfLiteralMode::XdvBeginContent => content_origins.push(special.position),
PdfLiteralMode::XdvEndContent => { content_origins.pop(); }
_ => {}
}
}
match &graphics {
Some(PdfGraphics::Save | PdfGraphics::Literal { mode: PdfLiteralMode::XdvBeginContent, .. }) => {
xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current()));
@@ -845,7 +853,14 @@ impl Executor {
device.vertical_origin = offset + v_offset;
}
let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin];
for (index, graphics_step, [x, y], origin) in xdv_navigation {
let [origin_x, origin_y] = crate::pdf_device::xdv_page_origin(
crate::render::DisplayUnits::TeX, device.page_height, magnification,
);
let default_content_origin = [
origin_x - device.horizontal_origin,
device.page_height - origin_y - device.vertical_origin - shipout.box_node.height,
];
for (index, graphics_step, [x, y], origin, content_origin) in xdv_navigation {
let special = &shipout.specials[index];
let position = crate::pdf_device::xdv_object::Position {
page: self.shipped_pages + 1,
@@ -862,10 +877,16 @@ impl Executor {
if let Some(raster) = raster {
shipout.pdf_special_images.insert(graphics_step, (raster, source));
}
} else if let Some(operation) = self.ship_xdv_navigation(
special, position, graphics_step, &mut shipout.pdf_links, origin, files,
)? {
shipout.pdf_graphics_steps[graphics_step] = Some(operation);
} else {
let [left, top] = content_origin.unwrap_or(default_content_origin);
let [x, y] = special.position;
let capture_origin = [x - left, top - y]
.map(|coordinate| crate::render::DisplayUnits::TeX.bp(coordinate));
if let Some(operation) = self.ship_xdv_navigation(
special, position, graphics_step, capture_origin, &mut shipout.pdf_links, origin, files,
)? {
shipout.pdf_graphics_steps[graphics_step] = Some(operation);
}
}
}
if let Some(navigation) = &self.state.xdv_navigation {
@@ -407,14 +407,14 @@ impl Executor {
.map_err(|message| self.error(message, token.span))?;
(resource, None)
};
let (image, source_origin) = if let FormatImageKind::XdvPdf { page_box } = format_kind {
let (image, origin) = PdfImage::read_xdv(resource, page, page_box)
let (image, source_geometry) = if let FormatImageKind::XdvPdf { page_box } = format_kind {
let (image, geometry) = PdfImage::read_xdv(resource, page, page_box)
.map_err(|message| self.error(message, token.span))?;
(Arc::new(image), origin)
(Arc::new(image), Some(geometry))
} else {
(self.decode_xdv_raster(resource, token.span)?, [0.0; 2])
(self.decode_xdv_raster(resource, token.span)?, None)
};
let mut placement = XdvImagePlacement::new(&image, source_origin);
let mut placement = XdvImagePlacement::new(&image, source_geometry);
loop {
if self.keyword("scaled", files)? {
let scale = f64::from(self.integer(files)?) / 1000.0;
@@ -660,14 +660,14 @@ impl Executor {
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 {
let (actual, geometry) = match *kind {
FormatImageKind::XdvPdf { page_box } => {
PdfImage::read_xdv(resource, page, page_box).map(|(image, _)| image)
PdfImage::read_xdv(resource, page, page_box).map(|(image, geometry)| (image, Some(geometry)))
}
FormatImageKind::XdvRaster => PdfImage::read_xdv_raster(resource),
FormatImageKind::XdvRaster => PdfImage::read_xdv_raster(resource).map(|image| (image, None)),
_ => 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 placed = Arc::new(saved.with_current_xdv_image(actual, geometry));
let registered = &mut self.pdf_images[id - 1];
registered.image = placed;
registered.pending_xdv = None;
@@ -55,6 +55,7 @@ impl Executor {
special: &ShipoutSpecial,
position: crate::pdf_device::xdv_object::Position,
graphics_step: usize,
capture_origin: [f64; 2],
links: &mut crate::pdf_device::links::PageLinks,
origin: Option<TokenOrigin>,
files: &mut impl SourceProvider,
@@ -74,7 +75,7 @@ impl Executor {
let warnings = if matches!(kind, b"bxobj" | b"exobj" | b"uxobj") {
let source = origin.unwrap_or(TokenOrigin { span: special.span, invocation: None });
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
let (operation, warnings) = navigation.form_special(kind, operands, position, source, self.limits.tokens)
let (operation, warnings) = navigation.form_special(kind, operands, position, capture_origin, source, self.limits.tokens)
.map_err(|error| self.error(error, special.span))?;
graphics = Some(operation);
Ok(warnings)
@@ -88,9 +88,13 @@ impl Executor {
})
} else if let Some(operation) = shipout.pdf_graphics_steps.get(step) {
match operation {
Some(PdfGraphics::Save | PdfGraphics::Literal {
mode: crate::pdf_device::PdfLiteralMode::XdvBeginContent, ..
}) => saved.push(frame.transform),
Some(
PdfGraphics::Save
| PdfGraphics::Literal {
mode: crate::pdf_device::PdfLiteralMode::XdvBeginContent,
..
},
) => saved.push(frame.transform),
Some(
operation @ (PdfGraphics::SaveMatrix(matrix)
| PdfGraphics::Matrix(matrix)),
@@ -102,9 +106,13 @@ impl Executor {
.transform
.concatenate(matrix.about(point[0], point[1], true));
}
Some(PdfGraphics::Restore { .. } | PdfGraphics::Literal {
mode: crate::pdf_device::PdfLiteralMode::XdvEndContent, ..
}) => {
Some(
PdfGraphics::Restore { .. }
| PdfGraphics::Literal {
mode: crate::pdf_device::PdfLiteralMode::XdvEndContent,
..
},
) => {
frame.transform =
saved.pop().expect("validated graphics stack");
}
@@ -113,9 +121,33 @@ impl Executor {
if page.tracking()
&& let Some((image, _)) = shipout.pdf_special_images.get(&step)
{
frame.raster(&mut page, point, image);
frame.image(&mut page, point, image);
}
if page.tracking()
&& let Some(PdfGraphics::XdvFormUse {
number,
options,
available,
..
}) = operation
{
self.state
.xdv_navigation
.as_ref()
.expect("XDV XObject registry")
.xobject_transform(*number, *options, *available)
.map(|placement| {
let [l, b, r, t] = placement.area;
frame.object(
&mut page,
point,
[l, b, r - l, t - b],
placement.matrix,
);
})
} else {
Ok(())
}
Ok(())
} else {
Err("missing XDV annotation graphic position".into())
}
@@ -165,16 +197,23 @@ impl Frame {
));
}
fn raster(&self, page: &mut Page<'_>, [x, y]: [f64; 2], image: &crate::pdf_image::PdfImageUse) {
let placement = image.xdv.as_ref().expect("XDV special image placement");
// The driver obtains the link rectangle by converting the lower
// corner and each extent to DVI units before the image transform.
let unit = f64::from(self.magnification) / 1000.0 * (800.0 / 803.0) / 65536.0;
let [left, bottom, width, height] = placement
.annotation_box()
.map(|coordinate| (coordinate / unit).round() * unit);
let [right, top] = [left + width, bottom + height];
let placement = Affine(placement.paint_matrix());
fn image(&self, page: &mut Page<'_>, point: [f64; 2], image: &crate::pdf_image::PdfImageUse) {
if let Some(placement) = &image.xdv {
self.object(
page,
point,
placement.annotation_box(),
Affine(placement.paint_matrix()),
);
}
}
fn object(&self, page: &mut Page<'_>, [x, y]: [f64; 2], area: [f64; 4], placement: Affine) {
// The DVI driver quantizes the lower corner and two extents
// separately before applying the current transformation.
let unit = crate::render::DisplayUnits::TeX.bp(1);
let [l, b, width, height] = area.map(|coordinate| (coordinate / unit).round() * unit);
let [left, bottom, right, top] = [l, b, l + width, b + height];
let corners = [[left, bottom], [left, top], [right, bottom], [right, top]].map(|[u, v]| {
let [dx, dy] = placement.point(u, v);
[
@@ -240,6 +279,7 @@ impl Frame {
);
}
}
MathItem::PdfImage(image) => self.image(page, [x, y], image),
_ => {}
}
}
+13 -7
View File
@@ -1144,11 +1144,11 @@ fn page_content(
// to its page origin, with three decimals by default.
let round = |value: f64| (value * 1000.0).round() / 1000.0;
let [left, bottom] = placement.layout_offset;
let x = round(list.units.bp(*x - left) + tx - origin_x) + round(origin_x)
- list.units.bp(h);
let x = round(list.units.bp(*x - left) + tx - origin_x)
+ round(round(origin_x) - list.units.bp(h));
let y = round(
list.units.bp(height - *y - *image_height - bottom) + ty - origin_y,
) + round(origin_y) - list.units.bp(v);
) + round(round(origin_y) - list.units.bp(v));
let [a, b, c, d, x, y] = [a, b, c, d, x, y].map(crate::pdf_image::real);
content.push_str(&format!("q {a} {b} {c} {d} {x} {y} cm "));
if let Some(clip) = placement.clip() {
@@ -1298,10 +1298,16 @@ fn page_content(
pt(coordinate).parse::<f64>().expect("formatted PDF dimension")
})
};
let [a, b, c, d, e, f] = matrix
.about(coordinates[0], coordinates[1], false)
.0
.map(crate::pdf_image::real);
let mut coefficients = matrix.about(coordinates[0], coordinates[1], false).0;
if xdv {
// The device keeps the full transform for geometry but
// serializes the linear and translation terms separately.
for (index, value) in coefficients.iter_mut().enumerate() {
let precision = if index < 4 { 100_000.0 } else { 1000.0 };
*value = (*value * precision).round() / precision;
}
}
let [a, b, c, d, e, f] = coefficients.map(crate::pdf_image::real);
content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n"));
}
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
@@ -52,8 +52,8 @@ pub enum PdfGraphics {
number: u32,
options: super::xdv_navigation::FormOptions,
source: crate::execution::TokenOrigin,
#[serde(default)]
imported_available: bool,
#[serde(default, alias = "imported_available")]
available: bool,
},
}
@@ -1,7 +1,7 @@
//! Image selection and placement from the xdvipdfmx device specials.
use super::{
Affine,
xdv_navigation::FormOptions,
xdv_navigation::{FormOptions, XObjectTransform},
xdv_object::{
Dictionary, Position, Value, dictionary, identifier, parse_object_prefix, trim_pdf,
},
@@ -266,7 +266,6 @@ pub(crate) enum ImportGeometry {
impl ImportGeometry {
fn page(geometry: PdfPageGeometry, attributes: &Dictionary) -> Self {
let [left, bottom, right, top] = geometry.bounds;
let rect = |points: [[f64; 2]; 4]| {
let [x, y] = points[0];
points[1..]
@@ -276,45 +275,36 @@ impl ImportGeometry {
})
.map(f64::to_bits)
};
let normal = [[left, bottom], [right, bottom], [right, top], [left, top]]
.map(|[x, y]| geometry.matrix.point(x, y));
let mut sizing = normal;
// The reference driver's stored fitting rectangle also samples the
// unshifted lower edge and the transformed lower-right x-axis point.
sizing[0][1] = bottom;
sizing[1] = geometry.matrix.point(right, 0.0);
let [l, b, r, t] = numeric_attribute(attributes, b"BBox").unwrap_or(geometry.bounds);
let matrix = numeric_attribute(attributes, b"Matrix").map_or(geometry.matrix, Affine);
let painted = [[l, b], [r, b], [r, t], [l, t]].map(|[x, y]| matrix.point(x, y));
Self::Page {
bounds: rect(painted),
fitting: rect(sizing),
fitting: geometry.xdv_fitting_box().map(f64::to_bits),
}
}
pub(crate) fn place(
&self,
number: u32,
options: FormOptions,
available: bool,
) -> Result<crate::pdf_device::forms::FormUse, String> {
pub(crate) fn paint_bounds(&self) -> [f64; 4] {
match *self {
Self::Page { bounds, fitting } => options.place_xobject(
number,
bounds.map(f64::from_bits),
available.then(|| fitting.map(f64::from_bits)),
),
Self::Page { bounds, .. } => bounds.map(f64::from_bits),
Self::Raster { .. } => [0.0, 0.0, 1.0, 1.0],
}
}
pub(crate) fn transform(&self, options: FormOptions) -> Result<XObjectTransform, String> {
match *self {
Self::Page { fitting, .. } => {
Ok(options.xobject_transform(Some(fitting.map(f64::from_bits))))
}
Self::Raster { extent, pixels } => {
let bounds = [0.0, 0.0, 1.0, 1.0];
if !available {
return options.place_xobject(number, bounds, None);
}
let (matrix, clip) =
let (matrix, bbox) =
options.raster_transform(extent.map(f64::from_bits), pixels)?;
let clip = clip
.filter(|_| options.clip_enabled())
.map(|[x, y, width, height]| [x, y, x + width, y + height]);
FormOptions::placed(number, bounds, matrix, clip)
let [x, y, width, height] = bbox.unwrap_or([0.0, 0.0, 1.0, 1.0]);
Ok(XObjectTransform {
matrix,
area: [x, y, x + width, y + height],
clip: bbox.is_some() && options.clip_enabled(),
})
}
}
}
@@ -16,6 +16,7 @@ mod page_dictionaries;
mod page_resources;
mod forms;
pub use forms::FormOptions;
pub(crate) use forms::XObjectTransform;
use forms::Forms;
use page_resources::PageResources;
use page_dictionaries::PageDictionaries;
@@ -132,35 +132,8 @@ impl FormOptions {
Ok(bounds)
}
fn place(
self,
number: u32,
captured: [u64; 4],
capture_y: Option<f64>,
) -> Result<FormUse, String> {
let captured = captured.map(f64::from_bits);
let fitting = capture_y.map(|capture_y| {
let [left, bottom, right, top] = captured;
// The reference Form extent uses the unshifted lower edge and
// the capture-origin-adjusted zero and upper edge.
let y = [-capture_y, top - capture_y];
[
left,
y[0].min(y[1]).min(bottom),
right,
y[0].max(y[1]).max(bottom),
]
});
self.place_xobject(number, captured, fitting)
}
pub(crate) fn place_xobject(
self,
number: u32,
captured: [f64; 4],
fitting: Option<[f64; 4]>,
) -> Result<FormUse, String> {
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
pub(crate) fn xobject_transform(self, fitting: Option<[f64; 4]>) -> XObjectTransform {
let user_bbox = self.requested_box();
let transform = self.affine();
// A reserved forward reference has no natural dimensions yet.
let transform = if let Some([left, bottom, right, top]) = fitting {
@@ -190,20 +163,29 @@ impl FormOptions {
} else {
transform
};
let clip = user_bbox.filter(|_| self.clip_enabled());
Self::placed(number, captured, transform, clip)
XObjectTransform {
matrix: transform,
area: user_bbox.or(fitting).unwrap_or([0.0, 0.0, 1.0, 1.0]),
clip: user_bbox.is_some() && self.clip_enabled(),
}
}
}
pub(crate) fn placed(
number: u32,
captured: [f64; 4],
transform: Affine,
clip: Option<[f64; 4]>,
) -> Result<FormUse, String> {
#[derive(Clone, Copy)]
pub(crate) struct XObjectTransform {
pub(crate) matrix: Affine,
pub(crate) area: [f64; 4],
pub(crate) clip: bool,
}
impl XObjectTransform {
pub(crate) fn place(self, number: u32, captured: [f64; 4]) -> Result<FormUse, String> {
let transform = self.matrix;
let matrix = transform.0;
if !matrix.iter().all(|value| value.is_finite()) {
return Err("XDV form placement transform out of range".into());
}
let clip = self.clip.then_some(self.area);
let [left, bottom, right, top] = if let Some([x0, y0, x1, y1]) = clip {
let [left, bottom, right, top] = captured;
let left = left.max(x0.min(x1));
@@ -238,7 +220,9 @@ impl FormOptions {
}),
})
}
}
impl FormOptions {
pub(crate) fn affine(self) -> Affine {
if let Some(matrix) = self.matrix {
return Affine(matrix.map(f64::from_bits));
@@ -297,16 +281,36 @@ pub(super) struct Forms {
struct Active {
number: u32,
bounds: [u64; 4],
capture_origin: [u64; 2],
outer_resources: Dictionary,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct Definition {
bounds: [u64; 4],
#[serde(default)]
capture_origin: [u64; 2],
attributes: Dictionary,
resources: Dictionary,
}
impl Definition {
fn fitting_box(&self) -> [f64; 4] {
let [left, bottom, right, top] = self.bounds.map(f64::from_bits);
// The reference's stored fit range samples the unshifted lower
// edge and the capture-origin-adjusted zero and upper edge.
let [x, y] = self
.capture_origin
.map(|coordinate| -f64::from_bits(coordinate));
[
left + x,
y.min(y + top).min(bottom),
right + x,
y.max(y + top).max(bottom),
]
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct ImportedImage {
geometry: ImportGeometry,
@@ -404,7 +408,7 @@ impl Navigation {
number,
options: special.placement,
source,
imported_available: true,
available: true,
}))
}
@@ -460,6 +464,7 @@ impl Navigation {
kind: &[u8],
input: &[u8],
position: Position,
capture_origin: [f64; 2],
source: TokenOrigin,
limit: usize,
) -> Result<(PdfGraphics, Vec<String>), String> {
@@ -482,6 +487,7 @@ impl Navigation {
form.number,
Definition {
bounds: form.bounds,
capture_origin: form.capture_origin,
attributes,
resources,
},
@@ -507,6 +513,7 @@ impl Navigation {
self.forms.active.push(Active {
number,
bounds,
capture_origin: capture_origin.map(f64::to_bits),
outer_resources,
});
PdfGraphics::XdvFormBegin(number)
@@ -515,7 +522,9 @@ impl Navigation {
number,
options,
source,
imported_available: self.forms.imports.contains_key(&number),
available: self.forms.imports.contains_key(&number)
|| self.forms.definitions.contains_key(&number)
|| self.forms.active.iter().any(|form| form.number == number),
}
};
Ok((command, warnings))
@@ -529,6 +538,26 @@ impl Navigation {
}
}
pub(crate) fn xobject_transform(
&self,
number: u32,
options: FormOptions,
available: bool,
) -> Result<XObjectTransform, String> {
if !available {
return Ok(options.xobject_transform(None));
}
if let Some(id) = self.forms.imports.get(&number) {
return self.forms.images[id].geometry.transform(options);
}
let definition = self
.forms
.definitions
.get(&number)
.ok_or("referenced XDV form is undefined")?;
Ok(options.xobject_transform(Some(definition.fitting_box())))
}
pub(crate) fn split_forms(
&self,
pages: &mut [DisplayList],
@@ -537,7 +566,6 @@ impl Navigation {
return Ok(Vec::new());
}
let mut forms = Vec::new();
let mut capture_positions = BTreeMap::new();
for page in pages {
let page_origin = xdv_page_origin(page.units, page.height, page.magnification);
let mut content_origins = Vec::new();
@@ -571,8 +599,6 @@ impl Navigation {
} => {
let bounds = self.forms.definitions[&number].bounds;
let origin = content_origins.last().copied().unwrap_or(page_origin);
capture_positions
.insert(number, page.units.bp(page.height - y - origin[1]));
let list = DisplayList {
width: page.width,
height: page.height,
@@ -603,7 +629,9 @@ impl Navigation {
if number != expected {
return Err("mismatched XDV form capture".into());
}
let form = FormOptions::default().place(number, geometry.bounds, None)?;
let form = FormOptions::default()
.xobject_transform(None)
.place(number, geometry.bounds.map(f64::from_bits))?;
forms.push(FormDisplay {
form,
resource_number: 0,
@@ -620,28 +648,22 @@ impl Navigation {
number,
options,
source,
imported_available,
available,
},
} => {
let form = if let Some(import) = self.forms.imports.get(&number) {
self.forms.images[import].geometry.place(
number,
options,
imported_available,
)?
let bounds = if let Some(import) = self.forms.imports.get(&number) {
self.forms.images[import].geometry.paint_bounds()
} else {
let bounds = self
.forms
self.forms
.definitions
.get(&number)
.ok_or("referenced XDV form is undefined")?
.bounds;
options.place(
number,
bounds,
capture_positions.get(&number).copied(),
)?
.bounds
.map(f64::from_bits)
};
let form = self
.xobject_transform(number, options, available)?
.place(number, bounds)?;
(
DisplayItem::PdfForm { x, y, form },
Some(PaintSource::token(source)),
+36 -14
View File
@@ -49,6 +49,26 @@ pub(crate) struct PdfPageGeometry {
pub(crate) matrix: Affine,
}
impl PdfPageGeometry {
fn xdv_annotation_box(&self) -> [u64; 4] {
let [l, b, r, t] = self.xdv_fitting_box();
[l, b, r - l, t - b].map(f64::to_bits)
}
pub(crate) fn xdv_fitting_box(&self) -> [f64; 4] {
let [left, bottom, right, top] = self.bounds;
let mut points = [[left, bottom], [right, 0.0], [right, top], [left, top]]
.map(|[x, y]| self.matrix.point(x, y));
// The driver's stored Form fit samples the unshifted lower
// edge and the transformed lower-right x-axis point.
points[0][1] = bottom;
let [x, y] = points[0];
points[1..].iter().fold([x, y, x, y], |[l, b, r, t], &[x, y]| {
[l.min(x), b.min(y), r.max(x), t.max(y)]
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfImage {
pub version: ResourceVersion,
@@ -233,7 +253,7 @@ impl PdfImageUse {
matrix: matrix.map(f64::to_bits),
raster_source_matrix: raster_source_matrix.map(|matrix| matrix.map(f64::to_bits)),
clip: None,
annotation_box: None,
annotation_box: placement.annotation_box,
layout_offset: [0, 0],
}),
})
@@ -295,13 +315,16 @@ impl PdfImageUse {
.map(|value| (value * 100_000.0).round() / 100_000.0)
}
pub(crate) fn with_current_xdv_image(&self, image: PdfImage) -> Self {
pub(crate) fn with_current_xdv_image(&self, image: PdfImage, geometry: Option<PdfPageGeometry>) -> 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);
if let Some(placement) = &mut placed.xdv {
if let Some(matrix) = placement.raster_source_matrix {
placement.matrix = Self::scale_xdv_raster(matrix.map(f64::from_bits), image.extent())
.map(f64::to_bits);
}
if let Some(geometry) = geometry {
placement.annotation_box = Some(geometry.xdv_annotation_box());
}
}
placed.image = Arc::new(image);
placed
@@ -316,18 +339,21 @@ pub(crate) struct XdvImagePlacement {
corners: [[f32; 2]; 4],
transform: Affine,
requested: [Option<f64>; 2],
annotation_box: Option<[u64; 4]>,
}
impl XdvImagePlacement {
pub(crate) fn new(image: &PdfImage, source_origin: [f64; 2]) -> Self {
pub(crate) fn new(image: &PdfImage, geometry: Option<PdfPageGeometry>) -> Self {
// XeTeX's realrect and realpoint store coordinates as float.
let points = |bp| (bp * 803.0 / 800.0) as f32;
let [width, height] = image.extent().map(points);
let [left, bottom] = source_origin.map(points);
let [left, bottom] = geometry.as_ref().map_or([0.0, 0.0], |g| [g.bounds[0], g.bounds[1]]).map(points);
let annotation_box = geometry.map(|geometry| geometry.xdv_annotation_box());
Self {
corners: Self::rectangle([left, bottom, left + width, bottom + height]),
transform: Affine::IDENTITY,
requested: [None; 2],
annotation_box,
}
}
@@ -737,7 +763,7 @@ impl PdfImage {
resource: LoadedResource,
page: i32,
kind: PageBox,
) -> Result<(Self, [f64; 2]), String> {
) -> Result<(Self, PdfPageGeometry), String> {
let doc = Self::open_pdf(&resource)?;
Self::read_page(resource, doc, PageBoxSelection::Xdv(kind), false, |_, pages| {
let pages = i64::try_from(pages.len()).map_err(|_| "required page does not exist")?;
@@ -750,10 +776,6 @@ impl PdfImage {
.then(|| page.clamp(1, pages) as u32)
.ok_or_else(|| "required page does not exist".into())
})
.map(|(image, geometry)| {
let [left, bottom, ..] = geometry.bounds;
(image, [left, bottom])
})
}
pub(crate) fn read_xdv_special(
@@ -1169,9 +1169,14 @@ fn xdv_imported_image_matches_forward_catalog_and_page_references() {
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
let result = Executor::new(state, Limits::default()).with_native_pages().run(
source(r"\catcode123=1 \catcode125=2
\shipout\hbox{\special{pdf:uxobj @Sheet}\special{pdf:put @catalog << /Sheet @Sheet >>}}
\shipout\hbox{%
\special{pdf:bann << /Subtype /Link /A << /S /URI /URI (https://example.org/before) >> >>}%
\special{pdf:uxobj @Sheet}\special{pdf:eann}%
\special{pdf:put @catalog << /Sheet @Sheet >>}}
\shipout\hbox{\special{pdf:epdf @Sheet pagebox mediabox hide (drawing.pdf) << /Stamp @Tag >>}%
\special{pdf:obj @Tag (proof)}\special{pdf:usexobj @Sheet width 36bp}}
\special{pdf:obj @Tag (proof)}%
\special{pdf:bann << /Subtype /Link /A << /S /URI /URI (https://example.org/after) >> >>}%
\special{pdf:usexobj @Sheet width 36bp}\special{pdf:eann}}
\end"),
&mut device,
).unwrap();
@@ -1179,12 +1184,20 @@ fn xdv_imported_image_matches_forward_catalog_and_page_references() {
let pdf = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
let pdf = Document::load_mem(&pdf.bytes).unwrap();
let reference = pdf.catalog().unwrap().get(b"Sheet").unwrap().as_reference().unwrap();
for page in pdf.get_pages().into_values() {
let page = pdf.get_dictionary(page).unwrap();
for (index, id) in pdf.get_pages() {
let page = pdf.get_dictionary(id).unwrap();
let xobjects = page.get(b"Resources").unwrap().as_dict().unwrap()
.get(b"XObject").unwrap().as_dict().unwrap();
assert_eq!(xobjects.len(), 1);
assert_eq!(xobjects.iter().next().unwrap().1.as_reference().unwrap(), reference);
let entries = page.get(b"Annots").unwrap().as_array().unwrap();
assert_eq!(entries.len(), 1);
let link = pdf.get_dictionary(entries[0].as_reference().unwrap()).unwrap();
let rect: Vec<_> = link.get(b"Rect").unwrap().as_array().unwrap().iter()
.map(|value| value.as_i64().map(|n| n as f64).or_else(|_| value.as_f64()).unwrap()).collect();
let expected = if index == 1 { [72.0, 720.0, 73.0, 721.0] } else { [72.0, 720.0, 108.0, 760.0] };
assert_eq!(rect, expected);
}
let form = pdf.get_object(reference).unwrap().as_stream().unwrap();
let stamp = form.dict.get(b"Stamp").unwrap().as_reference().unwrap();
+30
View File
@@ -18,6 +18,36 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-28 XeLaTeX 图形链接与设备坐标
出页时,图形链接从实际 XObject 放置获得注释范围。前向引用
使用当时的保留尺寸,已登记对象使用捕获坐标及固有尺寸,显式
页面框参与几何。已连通导入 PDF、命名位图、捕获 Form 以及
XeTeX 的 PDF 和位图原语。PDF 输出沿用实际范围和链接目标。
[参考设备的图形链接几何](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfdev.c)
五组对照共六页,14 个链接的页号、顺序、目标和 0.001 bp
精度的矩形均一致。包括原样 graphicx 和 hyperref、跨页及前向
放置、旋转、裁切、显式关闭链接与放大。原样 LaTeX 的 aux
与参考逐字节一致。六页的 144 DPI 彩色渲染逐像素相同。
图像及透明蒙版的原始样本已与参考相同。图形流的平移按三位
小数写出,旋转与缩放的线性项按五位小数写出。旧位图样例的
680 个差异像素、原样链接插图的 11 个差异像素均归零。开发
构建与十一项定向回归通过。
三页会话从前页保存的真实 Form 恢复。调整放置高度或恢复
初始尺寸时只刷新第 2 页。单改链接地址更新 PDF,预览画面
保持一致。三个修订的 PDF、测量页、SVG、来源映射和 aux
均与独立全量一致。每轮均复用 465 个执行步。
回执在 `target/p3-xdv-import-link-bounds/receipt.json`,
SHA-256 为 `e2ca4409e9d1398d0f23822983343cfc339801101f22e637edf6b0e00255bcc8`。下一入口为 `pdf:names`。参考从
两页的原样特指令作业中列出三个不同文件名,提取文件均匹配
实际负载,且同时保留跳转目标。原生停在首个 `pdf:names`。
样例和对照在 `target/p3-xdv-name-trees`。原样出版矩阵、
发布版整体验收和 100 ms 可见延迟门槛继续按总目标执行。
## 2026-11-28 XeLaTeX 命名 PDF 和位图导入
`pdf:image`、`pdf:img` 和 `pdf:epdf` 按出页顺序执行。PDF 直接