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

@@ -18,12 +18,15 @@ pub struct FormUse {
pub(crate) struct XdvPlacement {
pub(crate) matrix: [u64; 6],
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)]
pub(crate) struct XdvCanvas {
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)]
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::{
execution::TokenOrigin,
pdf_device::{
Affine, DeviceOrigin, PdfGraphics,
Affine, PdfGraphics, PdfLiteralMode,
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
xdv_image::{length, number},
xdv_page_origin,
@@ -27,13 +27,15 @@ const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0;
pub struct FormOptions {
bbox: Option<[u64; 4]>,
size: [Option<u64>; 3],
scale: [Option<u64>; 2],
offset: [u64; 2],
rotation: u64,
scale: Option<u64>,
axis_scale: [Option<u64>; 2],
rotation: Option<u64>,
matrix: Option<[u64; 6]>,
clip: Option<bool>,
}
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)
.map_err(|_| "invalid XDV form options")?
.split_ascii_whitespace()
@@ -56,81 +58,150 @@ impl FormOptions {
};
options.size[index] = Some(length(&mut words, magnification)?.to_bits());
}
"xoffset" | "yoffset" => {
options.offset[usize::from(word == "yoffset")] =
length(&mut words, magnification)?.to_bits();
}
"scale" => options.scale = [Some(number(words.next())?.to_bits()); 2],
"scale" => options.scale = Some(number(words.next())?.to_bits()),
"xscale" | "yscale" => {
options.scale[usize::from(word == "yscale")] =
options.axis_scale[usize::from(word == "yscale")] =
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}")),
}
}
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 bbox = self
let bounds = self
.bbox
.map_or([0.0, -depth, width, height], |v| v.map(f64::from_bits));
let [left, bottom, right, top] = checked_box(bbox)?;
.unwrap_or([0.0, -depth, width, height].map(f64::to_bits));
let [left, bottom, right, top] = bounds.map(f64::from_bits);
checked_box([left, bottom, right, top])?;
if left >= right || bottom >= top {
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> {
if self.bbox.is_some() {
return Err("unsupported XDV form placement bounding box".into());
fn place(
self,
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 [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
let vertical = height
.or(depth.map(|_| 0.0))
.map(|h| h + depth.unwrap_or(0.0));
let requested = [
width.map(|w| w / natural[0]),
vertical.map(|h| h / natural[1]),
];
let scales = self.scale.map(|v| v.map(f64::from_bits));
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);
if sx == 0.0 || sy == 0.0 {
return Err("zero XDV form placement scale".into());
}
let [dx, dy] = self.offset.map(f64::from_bits);
let (sin, cos) = f64::from_bits(self.rotation).to_radians().sin_cos();
let matrix = [
cos * sx,
sin * sx,
-sin * sy,
cos * sy,
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)?;
let clip = user_bbox.filter(|_| self.clip.unwrap_or(true));
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));
let bottom = bottom.max(y0.min(y1));
[
left,
bottom,
left.max(right.min(x0.max(x1))),
bottom.max(top.min(y0.max(y1))),
]
} else {
captured
};
let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] =
[[left, bottom], [left, top], [right, bottom], [right, top]]
.map(|[x, y]| transform.point(x, y));
let bounds = checked_box([
x0.min(x1).min(x2).min(x3),
y0.min(y1).min(y2).min(y3),
x0.max(x1).max(x2).max(x3),
y0.max(y1).max(y2).max(y3),
])?;
Ok(FormUse {
number,
width: bounds[2] - bounds[0],
@@ -139,6 +210,7 @@ impl FormOptions {
xdv: Some(XdvPlacement {
matrix: matrix.map(f64::to_bits),
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)]
struct Active {
number: u32,
bounds: [i64; 4],
bounds: [u64; 4],
outer_resources: Dictionary,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct Definition {
bounds: [i64; 4],
bounds: [u64; 4],
attributes: Dictionary,
resources: Dictionary,
}
@@ -242,7 +314,7 @@ impl Navigation {
return Ok((PdfGraphics::XdvFormEnd(form.number), warnings));
}
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 command = if kind == b"bxobj" {
if self.forms.definitions.contains_key(&number)
@@ -269,7 +341,7 @@ impl Navigation {
source,
}
};
Ok((command, Vec::new()))
Ok((command, warnings))
}
pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> {
@@ -288,13 +360,32 @@ 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();
let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new();
let mut sources = std::mem::take(&mut page.sources);
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() {
let origin = sources.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 {
DisplayItem::PdfGraphics {
x,
@@ -302,6 +393,9 @@ impl Navigation {
operation: PdfGraphics::XdvFormBegin(number),
} => {
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,
@@ -316,6 +410,7 @@ impl Navigation {
number,
XdvCanvas {
anchor: [x, y],
origin,
bounds,
},
list,
@@ -331,7 +426,7 @@ impl Navigation {
if number != expected {
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 {
form,
resource_number: 0,
@@ -356,7 +451,11 @@ impl Navigation {
.get(&number)
.ok_or("referenced XDV form is undefined")?
.bounds;
let form = options.place(number, bounds)?;
let form = options.place(
number,
bounds,
capture_positions.get(&number).copied(),
)?;
(
DisplayItem::PdfForm { x, y, form },
Some(PaintSource::token(source)),
@@ -399,20 +498,12 @@ impl Navigation {
) -> Result<Vec<u8>, String> {
let geometry = form.xdv.expect("XDV form geometry");
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 anchor = origin
.move_to([x, list.height - y], list.units, digits)
.unwrap_or([0, 0])
.map(|value| value as f64 * magnification / 10f64.powi(i32::from(digits)));
let [origin_x, origin_y] = geometry.origin;
let anchor = [
list.units.bp(x - origin_x),
list.units.bp(list.height - y - origin_y),
];
let round = |value: f64| (value * 1000.0).round() / 1000.0;
let mut attributes = PdfDictionary::new();
attributes.set("Type", Object::Name(b"XObject".to_vec()));
@@ -422,7 +513,7 @@ impl Navigation {
.bounds
.into_iter()
.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();
attributes.set("BBox", Object::Array(bbox));
attributes.set(