Fit and clip captured XeLaTeX forms in their device coordinates

This commit is contained in:
gloamxun committed 2026-11-28 19:47:20 +08:00
1 parent c0e2346b05
commit 5ad5c40002
5 files changed
+303 -98

No files matched your search

+29 -13
View File
@@ -735,7 +735,7 @@ fn page_content(
xdv_font_aliases: &BTreeMap<crate::execution::FontId, crate::execution::FontId>, xdv_font_aliases: &BTreeMap<crate::execution::FontId, crate::execution::FontId>,
opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>, opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>,
font_opacities: &BTreeMap<u8, String>, font_opacities: &BTreeMap<u8, String>,
xdv_form: bool, form_origin: Option<[i64; 2]>,
) -> Vec<u8> { ) -> Vec<u8> {
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits); let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
let pt = |n: i64| { let pt = |n: i64| {
@@ -750,10 +750,10 @@ fn page_content(
let text_origin = xdv_page_origin(list.units, height, list.magnification); let text_origin = xdv_page_origin(list.units, height, list.magnification);
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv); let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
let page_origin = if xdv { text_origin } else { [0, 0] }; let page_origin = form_origin.unwrap_or(if xdv { text_origin } else { [0, 0] });
let mut content = PageContent::default(); let mut content = PageContent::default();
content.push_str("q\n0 0 0 rg\n"); content.push_str("q\n0 0 0 rg\n");
if list.magnification != 1000 { if list.magnification != 1000 && form_origin.is_none() {
let ratio = f64::from(list.magnification) / 1000.0; let ratio = f64::from(list.magnification) / 1000.0;
content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n")); content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n"));
} }
@@ -779,7 +779,7 @@ fn page_content(
pt(-origin.v_offset) pt(-origin.v_offset)
)); ));
} }
if xdv_form { if form_origin.is_some() {
// Captured XDV content uses device-relative coordinates. Keep the // Captured XDV content uses device-relative coordinates. Keep the
// logical origin used by glyphs and specials without emitting the // logical origin used by glyphs and specials without emitting the
// enclosing sheet's translation into the Form stream. // enclosing sheet's translation into the Form stream.
@@ -1224,11 +1224,27 @@ fn page_content(
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {}
DisplayItem::PdfForm { x, y, form } => { DisplayItem::PdfForm { x, y, form } => {
if let Some(placement) = form.xdv { if let Some(placement) = form.xdv {
let [a,b,c,d,e,f] = placement.matrix.map(f64::from_bits); let [a, b, c, d, e, f] = placement.matrix.map(f64::from_bits);
let tx = px(*x).parse::<f64>().expect("formatted XDV x") + e; let round = |value: f64, factor: f64| (value * factor).round() / factor;
let ty = py(*y).parse::<f64>().expect("formatted XDV y") + f; let [a, b, c, d] = [a, b, c, d].map(|value| {
let [a,b,c,d,tx,ty] = [a,b,c,d,tx,ty].map(crate::pdf_image::real); crate::pdf_image::real(round(value, 100_000.0))
content.push_str(&format!("q {a} {b} {c} {d} {tx} {ty} cm /Fm{} Do Q\n", form.number)); });
let [origin_x, origin_y] =
xdv_content_scopes.last().map_or(page_origin, |&(_, point)| point);
let tx = round(list.units.bp(*x - origin_x) + e, 1000.0)
+ round(list.units.bp(origin_x - h), 1000.0);
let ty = round(list.units.bp(height - *y - origin_y) + f, 1000.0)
+ round(list.units.bp(origin_y - v), 1000.0);
let [tx, ty] = [tx, ty].map(crate::pdf_image::real);
content.push_str(&format!("q {a} {b} {c} {d} {tx} {ty} cm "));
if let Some(clip) = placement.clip {
let [x0, y0, x1, y1] = clip.map(f64::from_bits);
let [x, y, width, height] = [x0, y0, x1 - x0, y1 - y0].map(|value| {
crate::pdf_image::real(round(value, 1000.0))
});
content.push_str(&format!("n {x} {y} {width} {height} re W n "));
}
content.push_str(&format!("/Fm{} Do Q\n", form.number));
continue; continue;
} }
content.push_str(&format!( content.push_str(&format!(
@@ -3032,14 +3048,14 @@ fn write_pdf(
let mut xobjects = String::new(); let mut xobjects = String::new();
append_xobjects(list, &mut xobjects)?; append_xobjects(list, &mut xobjects)?;
let fonts = mapped_font_resources(list); let fonts = mapped_font_resources(list);
if form.xdv.is_some() { if let Some(geometry) = form.xdv {
let mut resources = format!("<< /Font << {fonts} >>"); let mut resources = format!("<< /Font << {fonts} >>");
if !xobjects.is_empty() { if !xobjects.is_empty() {
resources.push_str(&format!(" /XObject << {xobjects} >>")); resources.push_str(&format!(" /XObject << {xobjects} >>"));
} }
resources.push_str(" >>"); resources.push_str(" >>");
let content = page_content(list, list.height, &BTreeMap::new(), faces, &cm_views, let content = page_content(list, list.height, &BTreeMap::new(), faces, &cm_views,
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, &BTreeMap::new(), true); &fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, &BTreeMap::new(), Some(geometry.origin));
xdv_forms.push((form, resources, content)); xdv_forms.push((form, resources, content));
continue; continue;
} }
@@ -3071,7 +3087,7 @@ fn write_pdf(
let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]); let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]);
let content = page_content( let content = page_content(
list, list.height, &names, faces, &cm_views, list, list.height, &names, faces, &cm_views,
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities, false, &fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities, None,
); );
objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes( 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), &entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
@@ -3262,7 +3278,7 @@ fn write_pdf(
&xdv_font_aliases, &xdv_font_aliases,
&opentype, &opentype,
font_opacities, font_opacities,
false, None,
); );
let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression)); let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression));
if let Some(id) = content_slot { if let Some(id) = content_slot {
@@ -18,12 +18,15 @@ pub struct FormUse {
pub(crate) struct XdvPlacement { pub(crate) struct XdvPlacement {
pub(crate) matrix: [u64; 6], pub(crate) matrix: [u64; 6],
pub(crate) bounds: [i64; 4], pub(crate) bounds: [i64; 4],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) clip: Option<[u64; 4]>,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct XdvCanvas { pub(crate) struct XdvCanvas {
pub(crate) anchor: [i64; 2], pub(crate) anchor: [i64; 2],
pub(crate) bounds: [i64; 4], pub(crate) origin: [i64; 2],
pub(crate) bounds: [u64; 4],
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::{ use crate::{
execution::TokenOrigin, execution::TokenOrigin,
pdf_device::{ pdf_device::{
Affine, DeviceOrigin, PdfGraphics, Affine, PdfGraphics, PdfLiteralMode,
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement}, forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
xdv_image::{length, number}, xdv_image::{length, number},
xdv_page_origin, xdv_page_origin,
@@ -27,13 +27,15 @@ const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0;
pub struct FormOptions { pub struct FormOptions {
bbox: Option<[u64; 4]>, bbox: Option<[u64; 4]>,
size: [Option<u64>; 3], size: [Option<u64>; 3],
scale: [Option<u64>; 2], scale: Option<u64>,
offset: [u64; 2], axis_scale: [Option<u64>; 2],
rotation: u64, rotation: Option<u64>,
matrix: Option<[u64; 6]>,
clip: Option<bool>,
} }
impl FormOptions { impl FormOptions {
fn parse(input: &[u8], magnification: i32) -> Result<Self, String> { fn parse(input: &[u8], magnification: i32) -> Result<(Self, Vec<String>), String> {
let mut words = std::str::from_utf8(input) let mut words = std::str::from_utf8(input)
.map_err(|_| "invalid XDV form options")? .map_err(|_| "invalid XDV form options")?
.split_ascii_whitespace() .split_ascii_whitespace()
@@ -56,81 +58,150 @@ impl FormOptions {
}; };
options.size[index] = Some(length(&mut words, magnification)?.to_bits()); options.size[index] = Some(length(&mut words, magnification)?.to_bits());
} }
"xoffset" | "yoffset" => { "scale" => options.scale = Some(number(words.next())?.to_bits()),
options.offset[usize::from(word == "yoffset")] =
length(&mut words, magnification)?.to_bits();
}
"scale" => options.scale = [Some(number(words.next())?.to_bits()); 2],
"xscale" | "yscale" => { "xscale" | "yscale" => {
options.scale[usize::from(word == "yscale")] = options.axis_scale[usize::from(word == "yscale")] =
Some(number(words.next())?.to_bits()); Some(number(words.next())?.to_bits());
} }
"rotate" => options.rotation = number(words.next())?.to_bits(), "rotate" => options.rotation = Some(number(words.next())?.to_bits()),
"matrix" => {
let mut matrix = [0; 6];
for entry in &mut matrix {
*entry = number(words.next())?.to_bits();
}
options.matrix = Some(matrix);
}
"clip" => options.clip = Some(number(words.next())? != 0.0),
"hide" => {}
_ => return Err(format!("unsupported XDV form option {word}")), _ => return Err(format!("unsupported XDV form option {word}")),
} }
} }
Ok(options) if let Some(bounds) = options.bbox {
checked_box(bounds.map(f64::from_bits))?;
}
let [width, height, depth] = options.size;
let [sx, sy] = options.axis_scale;
let warning = if width.is_some() && sx.is_some() {
options.axis_scale[0] = Some(1.0f64.to_bits());
Some("Can't supply both width and xscale. Ignore xscale.")
} else if (height.is_some() || depth.is_some()) && sy.is_some() {
options.axis_scale[1] = Some(1.0f64.to_bits());
Some("Can't supply both height/depth and yscale. Ignore yscale.")
} else if options.scale.is_some() && (sx.is_some() || sy.is_some()) {
return Err("XDV form scale conflicts with an axis scale".into());
} else if options.matrix.is_some()
&& (sx.is_some()
|| sy.is_some()
|| options.scale.is_some()
|| options.rotation.is_some())
{
Some(
"Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.",
)
} else {
None
};
Ok((options, warning.into_iter().map(String::from).collect()))
} }
fn capture_bounds(self) -> Result<[i64; 4], String> { fn capture_bounds(self) -> Result<[u64; 4], String> {
let [width, height, depth] = self.size.map(|v| v.map_or(0.0, f64::from_bits)); let [width, height, depth] = self.size.map(|v| v.map_or(0.0, f64::from_bits));
let bbox = self let bounds = self
.bbox .bbox
.map_or([0.0, -depth, width, height], |v| v.map(f64::from_bits)); .unwrap_or([0.0, -depth, width, height].map(f64::to_bits));
let [left, bottom, right, top] = checked_box(bbox)?; let [left, bottom, right, top] = bounds.map(f64::from_bits);
checked_box([left, bottom, right, top])?;
if left >= right || bottom >= top { if left >= right || bottom >= top {
return Err("XDV form bounding box must have positive dimensions".into()); return Err("XDV form bounding box must have positive dimensions".into());
} }
Ok([left, bottom, right, top]) Ok(bounds)
} }
fn place(self, number: u32, bounds: [i64; 4]) -> Result<FormUse, String> { fn place(
if self.bbox.is_some() { self,
return Err("unsupported XDV form placement bounding box".into()); number: u32,
captured: [u64; 4],
capture_y: Option<f64>,
) -> Result<FormUse, String> {
let captured = captured.map(f64::from_bits);
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
let transform = if let Some(matrix) = self.matrix {
Affine(matrix.map(f64::from_bits))
} else {
let [sx, sy] = self
.axis_scale
.map(|value| value.or(self.scale).map_or(1.0, f64::from_bits));
let (sin, cos) = self
.rotation
.map_or(0.0, f64::from_bits)
.to_radians()
.sin_cos();
Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])
};
// A reserved forward XObject uses the external matrix and explicit
// clip at its use site. The driver has no Form dimensions there yet.
let transform = if let Some(capture_y) = capture_y {
let [left, bottom, right, top] = captured;
// xdvipdfmx 20260113 fits against a separate stored extent.
// Its vertical samples are the unshifted lower edge and the
// capture-origin-adjusted zero and upper edge (pdf_ximage_set_form).
let y = [-capture_y, top - capture_y];
let extent = y[0].max(y[1]).max(bottom) - y[0].min(y[1]).min(bottom);
let (natural, offset) = if let Some([x0, y0, x1, y1]) = user_bbox {
([x1 - x0, y1 - y0], [-x0, -y0])
} else {
([right - left, extent], [0.0, 0.0])
};
let [natural_x, natural_y] = natural.map(|n| if n == 0.0 { 1.0 } else { n });
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
let depth_value = depth.unwrap_or(0.0);
let vertical = height
.or(depth)
.map(|_| (height.unwrap_or(0.0) + depth_value) / natural_y);
let horizontal = width.map(|value| value / natural_x);
let sx = horizontal.or(vertical).unwrap_or(1.0);
let sy = vertical.or(horizontal).unwrap_or(1.0);
let depth_shift = vertical.map_or(0.0, |_| depth_value);
transform.concatenate(Affine([
sx,
0.0,
0.0,
sy,
sx * offset[0],
sy * offset[1] - depth_shift,
]))
} else {
transform
};
let matrix = transform.0;
if !matrix.iter().all(|value| value.is_finite()) {
return Err("XDV form placement transform out of range".into());
} }
let [left, bottom, right, top] = bounds.map(|p| p as f64 / SP_PER_BP);
let natural = [right - left, top - bottom]; let clip = user_bbox.filter(|_| self.clip.unwrap_or(true));
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits)); let [left, bottom, right, top] = if let Some([x0, y0, x1, y1]) = clip {
let vertical = height let [left, bottom, right, top] = captured;
.or(depth.map(|_| 0.0)) let left = left.max(x0.min(x1));
.map(|h| h + depth.unwrap_or(0.0)); let bottom = bottom.max(y0.min(y1));
let requested = [ [
width.map(|w| w / natural[0]), left,
vertical.map(|h| h / natural[1]), bottom,
]; left.max(right.min(x0.max(x1))),
let scales = self.scale.map(|v| v.map(f64::from_bits)); bottom.max(top.min(y0.max(y1))),
let sx = requested[0].or(scales[0]).or(requested[1]).unwrap_or(1.0); ]
let sy = requested[1].or(scales[1]).or(requested[0]).unwrap_or(1.0); } else {
if sx == 0.0 || sy == 0.0 { captured
return Err("zero XDV form placement scale".into()); };
} let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] =
let [dx, dy] = self.offset.map(f64::from_bits); [[left, bottom], [left, top], [right, bottom], [right, top]]
let (sin, cos) = f64::from_bits(self.rotation).to_radians().sin_cos(); .map(|[x, y]| transform.point(x, y));
let matrix = [ let bounds = checked_box([
cos * sx, x0.min(x1).min(x2).min(x3),
sin * sx, y0.min(y1).min(y2).min(y3),
-sin * sy, x0.max(x1).max(x2).max(x3),
cos * sy, y0.max(y1).max(y2).max(y3),
dx, ])?;
dy + vertical.map_or(0.0, |_| -depth.unwrap_or(0.0) - bottom * sy),
];
let transform = Affine(matrix);
let mut extent = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
for [x, y] in [[left, bottom], [left, top], [right, bottom], [right, top]] {
let [x, y] = transform.point(x, y);
extent = [
extent[0].min(x),
extent[1].min(y),
extent[2].max(x),
extent[3].max(y),
];
}
let bounds = checked_box(extent)?;
Ok(FormUse { Ok(FormUse {
number, number,
width: bounds[2] - bounds[0], width: bounds[2] - bounds[0],
@@ -139,6 +210,7 @@ impl FormOptions {
xdv: Some(XdvPlacement { xdv: Some(XdvPlacement {
matrix: matrix.map(f64::to_bits), matrix: matrix.map(f64::to_bits),
bounds, bounds,
clip: clip.map(|v| v.map(f64::to_bits)),
}), }),
}) })
} }
@@ -167,13 +239,13 @@ pub(super) struct Forms {
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct Active { struct Active {
number: u32, number: u32,
bounds: [i64; 4], bounds: [u64; 4],
outer_resources: Dictionary, outer_resources: Dictionary,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct Definition { struct Definition {
bounds: [i64; 4], bounds: [u64; 4],
attributes: Dictionary, attributes: Dictionary,
resources: Dictionary, resources: Dictionary,
} }
@@ -242,7 +314,7 @@ impl Navigation {
return Ok((PdfGraphics::XdvFormEnd(form.number), warnings)); return Ok((PdfGraphics::XdvFormEnd(form.number), warnings));
} }
let (name, rest) = identifier(input)?; let (name, rest) = identifier(input)?;
let options = FormOptions::parse(rest, position.magnification)?; let (options, warnings) = FormOptions::parse(rest, position.magnification)?;
let number = self.forms.register(name)?; let number = self.forms.register(name)?;
let command = if kind == b"bxobj" { let command = if kind == b"bxobj" {
if self.forms.definitions.contains_key(&number) if self.forms.definitions.contains_key(&number)
@@ -269,7 +341,7 @@ impl Navigation {
source, source,
} }
}; };
Ok((command, Vec::new())) Ok((command, warnings))
} }
pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> { pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> {
@@ -288,13 +360,32 @@ impl Navigation {
return Ok(Vec::new()); return Ok(Vec::new());
} }
let mut forms = Vec::new(); let mut forms = Vec::new();
let mut capture_positions = BTreeMap::new();
for page in pages { for page in pages {
let page_origin = xdv_page_origin(page.units, page.height, page.magnification);
let mut content_origins = Vec::new();
let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new(); let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new();
let mut sources = std::mem::take(&mut page.sources); let mut sources = std::mem::take(&mut page.sources);
let mut packets = page.prepared_virtual_glyphs.as_mut().map(std::mem::take); let mut packets = page.prepared_virtual_glyphs.as_mut().map(std::mem::take);
for (index, item) in std::mem::take(&mut page.items).into_iter().enumerate() { for (index, item) in std::mem::take(&mut page.items).into_iter().enumerate() {
let origin = sources.remove(&index); let origin = sources.remove(&index);
let packet = packets.as_mut().and_then(|packets| packets.remove(&index)); let packet = packets.as_mut().and_then(|packets| packets.remove(&index));
if let DisplayItem::PdfGraphics {
x,
y,
operation: PdfGraphics::Literal { mode, .. },
} = &item
{
match mode {
PdfLiteralMode::XdvBeginContent => {
content_origins.push([*x, page.height - *y])
}
PdfLiteralMode::XdvEndContent => {
content_origins.pop();
}
_ => {}
}
}
let (item, origin) = match item { let (item, origin) = match item {
DisplayItem::PdfGraphics { DisplayItem::PdfGraphics {
x, x,
@@ -302,6 +393,9 @@ impl Navigation {
operation: PdfGraphics::XdvFormBegin(number), operation: PdfGraphics::XdvFormBegin(number),
} => { } => {
let bounds = self.forms.definitions[&number].bounds; 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 { let list = DisplayList {
width: page.width, width: page.width,
height: page.height, height: page.height,
@@ -316,6 +410,7 @@ impl Navigation {
number, number,
XdvCanvas { XdvCanvas {
anchor: [x, y], anchor: [x, y],
origin,
bounds, bounds,
}, },
list, list,
@@ -331,7 +426,7 @@ impl Navigation {
if number != expected { if number != expected {
return Err("mismatched XDV form capture".into()); return Err("mismatched XDV form capture".into());
} }
let form = FormOptions::default().place(number, geometry.bounds)?; let form = FormOptions::default().place(number, geometry.bounds, None)?;
forms.push(FormDisplay { forms.push(FormDisplay {
form, form,
resource_number: 0, resource_number: 0,
@@ -356,7 +451,11 @@ impl Navigation {
.get(&number) .get(&number)
.ok_or("referenced XDV form is undefined")? .ok_or("referenced XDV form is undefined")?
.bounds; .bounds;
let form = options.place(number, bounds)?; let form = options.place(
number,
bounds,
capture_positions.get(&number).copied(),
)?;
( (
DisplayItem::PdfForm { x, y, form }, DisplayItem::PdfForm { x, y, form },
Some(PaintSource::token(source)), Some(PaintSource::token(source)),
@@ -399,20 +498,12 @@ impl Navigation {
) -> Result<Vec<u8>, String> { ) -> Result<Vec<u8>, String> {
let geometry = form.xdv.expect("XDV form geometry"); let geometry = form.xdv.expect("XDV form geometry");
let list = &form.list; let list = &form.list;
let magnification = f64::from(list.magnification) / 1000.0;
let scale = magnification / SP_PER_BP;
let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
let mut origin = DeviceOrigin::default();
origin.move_to(
xdv_page_origin(list.units, list.height, list.magnification),
list.units,
digits,
);
let [x, y] = geometry.anchor; let [x, y] = geometry.anchor;
let anchor = origin let [origin_x, origin_y] = geometry.origin;
.move_to([x, list.height - y], list.units, digits) let anchor = [
.unwrap_or([0, 0]) list.units.bp(x - origin_x),
.map(|value| value as f64 * magnification / 10f64.powi(i32::from(digits))); list.units.bp(list.height - y - origin_y),
];
let round = |value: f64| (value * 1000.0).round() / 1000.0; let round = |value: f64| (value * 1000.0).round() / 1000.0;
let mut attributes = PdfDictionary::new(); let mut attributes = PdfDictionary::new();
attributes.set("Type", Object::Name(b"XObject".to_vec())); attributes.set("Type", Object::Name(b"XObject".to_vec()));
@@ -422,7 +513,7 @@ impl Navigation {
.bounds .bounds
.into_iter() .into_iter()
.enumerate() .enumerate()
.map(|(axis, n)| Object::Real(round(anchor[axis % 2] + scale * n as f64))) .map(|(axis, n)| Object::Real(round(anchor[axis % 2] + f64::from_bits(n))))
.collect(); .collect();
attributes.set("BBox", Object::Array(bbox)); attributes.set("BBox", Object::Array(bbox));
attributes.set( attributes.set(
@@ -1054,3 +1054,69 @@ fn xdv_form_capture_isolated_and_reused_as_one_indirect_object() {
assert!(resources.get(b"ExtGState").unwrap().as_dict().unwrap().has(b"A")); assert!(resources.get(b"ExtGState").unwrap().as_dict().unwrap().has(b"A"));
assert!(stream.dict.get(b"Group").unwrap().as_dict().unwrap().has(b"S")); assert!(stream.dict.get(b"Group").unwrap().as_dict().unwrap().has(b"S"));
} }
#[test]
fn xdv_form_placement_respects_definition_order_and_crop() {
use lopdf::{Document, Object, content::Content};
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
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 @inner bbox 2 1 12 11 width 30bp height 20bp}%
\special{pdf:bxobj @outer bbox 0 -4 80 35}%
\special{pdf:bxobj @inner width 20bp height 12bp depth 2bp}%
\hbox to0pt{\vrule width19pt height11pt\hfil}%
\special{pdf:exobj}%
\kern8pt\special{pdf:uxobj @inner width 35bp height 18bp depth 2bp}%
\special{pdf:exobj}%
\special{pdf:uxobj @outer}}
\shipout\hbox{%
\special{pdf:uxobj @inner bbox 2 1 12 11 width 30bp height 20bp}%
\kern40pt\special{pdf:uxobj @inner bbox 2 1 12 11 matrix 1 .25 -.2 1 4 3 clip 0}}
\shipout\hbox{%
\kern20pt\special{pdf:bcontent}%
\kern10pt\special{pdf:bxobj @local width 40bp height 20bp depth 2bp}%
\special{pdf:code 0 0 1 rg 12 1 7 9 re f}%
\hbox to0pt{\vrule width30pt height7pt\hss}%
\special{pdf:exobj}%
\kern75pt\special{pdf:uxobj @local width 50bp height 23bp depth 2bp}%
\special{pdf:econtent}}
\end"),
&mut TestDevice,
)
.unwrap();
let pages = result.shipout_display_lists().unwrap();
let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
let pdf = Document::load_mem(&output.bytes).unwrap();
let ids = pdf.get_pages();
let page = |id| Content::decode(&pdf.get_page_content(id).unwrap()).unwrap().operations;
let first = page(ids[&1]);
let second = page(ids[&2]);
let numeric = |values: &[Object]| -> Vec<f64> {
values.iter().map(|value| value.as_i64().map(|n| n as f64).or_else(|_| value.as_f64()).unwrap()).collect()
};
let matrices = |operations: &[lopdf::content::Operation]| -> Vec<Vec<f64>> {
operations.iter().filter(|op| op.operator == "cm")
.map(|op| numeric(&op.operands)).collect()
};
assert_eq!(&matrices(&first)[1][..4], &[1.0, 0.0, 0.0, 1.0]);
assert_eq!(numeric(&first.iter().find(|op| op.operator == "re").unwrap().operands),
[2.0, 1.0, 10.0, 10.0]);
assert_eq!(&matrices(&second)[1][..4], &[3.0, 0.0, 0.0, 2.0]);
assert_eq!(&matrices(&second)[2][..4], &[1.0, 0.25, -0.2, 1.0]);
assert_eq!(second.iter().filter(|op| op.operator == "W").count(), 1);
let local = page(ids[&3]);
assert_eq!(matrices(&local)[2], [1.25, 0.0, 0.0, 1.13636, 84.682, -2.0]);
let outer = pdf.objects.values().filter_map(|value| value.as_stream().ok()).find(|stream| {
stream.dict.get(b"Resources").and_then(Object::as_dict)
.and_then(|resources| resources.get(b"XObject")).is_ok()
}).unwrap();
let contents = outer.decompressed_content().unwrap();
let operations = Content::decode(&contents).unwrap().operations;
assert_eq!(&matrices(&operations)[0][..4], &[1.75, 0.0, 0.0, 0.80132]);
}
+29
View File
@@ -18,6 +18,35 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-28 XeLaTeX PDF Form 尺寸、裁切与局部坐标
Form 放置按出页指令顺序判定目标是否已定义。显式宽、高、深
按参考驱动保存的固有范围计算,前向引用保留放置当时的变换。
用户框、裁切开关、轴向缩放、旋转和通用矩阵进入实际 PDF 绘制。
测量页和来源映射使用裁切后的范围。局部绘图作用域为捕获和放置
提供坐标原点,整个 Form 随页缩放一次,普通单位和 true 单位
分别使用驱动对应的尺寸语义。
[参考放置逻辑](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfximage.c)
[参考尺寸与变换语法](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/spc_util.c)
此前嵌套同时指定宽、高、深的纵向因子从 1.428570870 修正到
参考的 0.80132,两页彩色逐像素一致。其余直接出页对照包含
裁切、旋转、前向与后续放置、正负捕获坐标、局部绘图作用域和
放大文档。中途局部坐标的 841 个差异像素和裁切的一处差异均
归零。与原样 PGF 3.1.12 的渐变、透明组和淡入遮罩合计十四页
144 DPI 彩色图逐像素一致,两份 article 的 aux 与参考逐字节
一致。开发构建与十项定向回归通过。
三页会话修改共享 Form 只更新两处使用页,单独收窄局部裁切
只更新所在页,恢复更新两个使用页。三个修订各复用 1,168 步,
PDF、测量页、预览、来源映射和 aux 与同版本独立全量一致。
回执在 `target/p3-xdv-form-placement/receipt.json`,SHA-256 为
`2adeef4a880407cc084fba8325e9b4f1ef79ab9b2bea0d7a299b714e73b49f69`。下一入口为命名 PDF 导入。已有冻结两页 PDF 资源
和选页、裁切、跨页前向引用对照,原生在 `pdf:epdf` 明确失败。
证据位于 `target/p3-xdv-named-pdf-import`。原样出版模板矩阵、
发布版整体验收和 100 ms 可见时延继续按总目标执行。
## 2026-11-28 XeLaTeX 捕获式 PDF Form 与 TikZ 渐变 ## 2026-11-28 XeLaTeX 捕获式 PDF Form 与 TikZ 渐变
出页时执行 `pdf:bxobj`、`pdf:exobj` 和 `pdf:uxobj`,把实际 出页时执行 `pdf:bxobj`、`pdf:exobj` 和 `pdf:uxobj`,把实际