Execute positioned TeX specials through native PDF devices

This commit is contained in:
gloamxun committed 2026-11-21 11:24:46 +08:00
1 parent 05e633bb14
commit ce8a780031
21 files changed
+519 -29

No files matched your search

+17 -6
View File
@@ -15,6 +15,15 @@ pub struct ShipoutDevice {
pub pdf: Option<crate::pdf_device::PdfPageData>,
}
/// A resolved device special in packed-list order. The position is in
/// unscaled TeX sp relative to the box reference point, with y increasing down.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShipoutSpecial {
pub span: Span,
pub position: [i64; 2],
pub bytes: Arc<[u8]>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeShipout {
pub box_node: NativeBox,
@@ -30,7 +39,9 @@ pub struct NativeShipout {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_steps: Vec<Option<Arc<PdfColorProgram>>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_graphics_steps: Vec<PdfGraphics>,
pub(super) pdf_graphics_steps: Vec<Option<PdfGraphics>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub specials: Vec<ShipoutSpecial>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_text_spaces: Option<crate::pdf_device::text_spaces::SpaceSettings>,
#[serde(default, skip_serializing_if = "pdf_resource_entries_empty")]
@@ -116,14 +127,14 @@ impl NativeShipout {
return;
}
boxes::GeometryItem::PdfGraphics { x, y } => {
if let Some(operation) = graphics_steps.next() {
page.items.push(DisplayItem::PdfGraphics {
match graphics_steps.next() {
Some(Some(operation)) => page.items.push(DisplayItem::PdfGraphics {
x: self.device.horizontal_origin + x,
y: self.device.vertical_origin + self.box_node.height + y,
operation: operation.clone(),
});
} else {
missing_graphics_step = true;
}),
Some(None) => {}
None => missing_graphics_step = true,
}
return;
}
@@ -654,10 +654,18 @@ impl Printer<'_> {
PdfLiteralMode::Origin => {}
PdfLiteralMode::Page => self.literal(" page"),
PdfLiteralMode::Direct => self.literal(" direct"),
PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {}
}
self.tokens(tokens)?;
}
OutputOperation::PdfSavePosition => self.command("pdfsavepos"),
OutputOperation::Special { shipout, tokens } => {
self.command("special");
if *shipout {
self.literal(" shipout");
}
self.tokens(tokens)?;
}
OutputOperation::PdfSetMatrix(tokens) => {
self.command("pdfsetmatrix");
self.tokens(tokens)?;
@@ -33,6 +33,7 @@ mod quantities;
mod restores;
mod scanning;
mod scheduling;
mod specials;
mod statistics;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -2885,6 +2886,9 @@ impl Executor {
OutputOperation::PdfSavePosition => {
return self.fail("PDF position requires a positioned shipout");
}
OutputOperation::Special { .. } => {
return self.fail("special requires a positioned shipout");
}
OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore
@@ -1,5 +1,5 @@
use super::*;
use crate::pdf_device::{PdfFileOptions, PdfPageData};
use crate::pdf_device::{PdfDriver, PdfFileOptions, PdfPageData};
impl Executor {
/// TeX extension commands share the scanner and produce their normal
/// effects in math as well as in vertical and horizontal lists.
@@ -26,6 +26,7 @@ impl Executor {
span: token.span,
})?;
}
Special => self.scan_special(token.span, files)?,
Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => {
self.scan_pdf_graphics(primitive, token.span, files)?
}
@@ -259,7 +260,12 @@ impl Executor {
if level > 9 {
return self.fail("invalid native PDF compression level");
}
let driver = match self.state.input_profile() {
InputProfile::TeX8Bit => PdfDriver::PdfTeX,
InputProfile::UnicodeScalar => PdfDriver::Xdv,
};
Ok(Some(PdfPageData {
driver,
file: self.state.pdf_file_options.clone().unwrap(),
stream_compression: level.max(0) as u8,
}))
@@ -278,15 +278,23 @@ impl Executor {
}
let magnification = self.prepare_magnification()?;
let pdf = self.pdf_page_data(files)?;
let unicode_pages = self.state.input_profile() == InputProfile::UnicodeScalar;
// The XDV driver uses a physical sheet and origin, then applies
// magnification to the DVI movements relative to that origin.
let origin = |value| {
if unicode_pages {
crate::pdf_device::unmagnify(value, magnification)
} else {
value
}
};
let horizontal_origin =
i64::from(self.read_parameter(Parameter::Pdfhorigin).width()) + h_offset;
origin(i64::from(self.read_parameter(Parameter::Pdfhorigin).width())) + h_offset;
let vertical_origin =
i64::from(self.read_parameter(Parameter::Pdfvorigin).width()) + v_offset;
origin(i64::from(self.read_parameter(Parameter::Pdfvorigin).width())) + v_offset;
let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width());
let requested_page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
let unicode_pages = self.state.input_profile() == super::super::InputProfile::UnicodeScalar;
// The XeTeX PDF device uses the default letter canvas unless a page size was supplied.
let default_canvas = |bp: i64| bp * 803 * 65536 / 800;
let default_canvas = |bp: i64| origin(bp * 803 * 65536 / 800);
if page_width == 0 {
page_width = if unicode_pages { default_canvas(612) } else { b.width + 2 * horizontal_origin };
}
@@ -335,6 +343,7 @@ impl Executor {
pdf_color_start,
pdf_color_steps: Vec::new(),
pdf_graphics_steps: Vec::new(),
specials: Vec::new(),
pdf_text_spaces: None,
pdf_resource_entries,
pdf_page_attributes,
@@ -394,6 +403,7 @@ impl Executor {
&& matches!(
output.operation,
OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. }
| OutputOperation::Special { shipout: true, .. }
)
{
shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings();
@@ -421,16 +431,27 @@ impl Executor {
return self.fail("cannot ship a PDF color operation to DVI");
}
shipout.pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?);
} else if matches!(output.operation, OutputOperation::Special { .. }) {
let special = self.resolve_special(
output, position.expect("special needs a shipout position"), files,
)?;
let graphics = if let Some(pdf) = &device.pdf {
self.render_special(&special, pdf.driver, files)?
} else {
None
};
shipout.specials.push(special);
shipout.pdf_graphics_steps.push(graphics);
} else if output.is_pdf_graphics() {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI");
}
shipout.pdf_graphics_steps.push(self.ship_pdf_graphics(
shipout.pdf_graphics_steps.push(Some(self.ship_pdf_graphics(
output,
position.expect("PDF graphics need a shipout position"),
&mut graphics_stack,
files,
)?);
)?));
} else if let OutputOperation::PdfSavePosition = output.operation {
self.current = output.span;
self.tick()?;
@@ -229,7 +229,7 @@ impl Executor {
&mut self,
b: &NativeBox,
device: &ShipoutDevice,
graphics: &[PdfGraphics],
graphics: &[Option<PdfGraphics>],
files: &mut impl SourceProvider,
) -> Result<PageLinks, Error> {
let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width());
@@ -250,18 +250,18 @@ impl Executor {
row
};
match item {
BoxPaint::PdfGraphics => match graphics.next() {
Some(PdfGraphics::Save) => saved.push(transform),
Some(PdfGraphics::Matrix(matrix)) => {
BoxPaint::PdfGraphics => match graphics.next().map(Option::as_ref) {
Some(Some(PdfGraphics::Save)) => saved.push(transform),
Some(Some(PdfGraphics::Matrix(matrix))) => {
transform = (transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
}
Some(PdfGraphics::Restore { shift: [dx, dy] }) => {
Some(Some(PdfGraphics::Restore { shift: [dx, dy] })) => {
if let Some(previous) = saved.pop() {
transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)),
previous.1 || *dx != 0 || *dy != 0);
}
}
Some(PdfGraphics::Literal { .. }) => {}
Some(Some(PdfGraphics::Literal { .. }) | None) => {}
None => failure = Some(self.error("missing PDF transform at link shipout", self.current)),
},
BoxPaint::RowStart(row) if self.pdf_running_links => {
@@ -0,0 +1,134 @@
//! TeX special whatsits and PDF driver dispatch at shipout.
use super::*;
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode};
impl Executor {
pub(super) fn scan_special(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let shipout = self.keyword("shipout", files)?;
let tokens = if shipout {
self.scan_group(files)?
} else {
self.scan_expanded_group(files)?
};
self.defer_output(OutputNode {
operation: OutputOperation::Special { shipout, tokens },
span,
})
}
pub(super) fn resolve_special(
&mut self,
node: &OutputNode,
position: [i64; 2],
files: &mut impl SourceProvider,
) -> Result<ShipoutSpecial, Error> {
self.current = node.span;
self.tick()?;
let OutputOperation::Special { shipout, tokens } = &node.operation else {
unreachable!()
};
let expanded;
let tokens = if *shipout {
expanded = self.fully_expand(tokens.clone(), files)?;
&expanded
} else {
tokens
};
Ok(ShipoutSpecial {
span: node.span,
position,
bytes: self.pdf_token_bytes(tokens)?.into(),
})
}
pub(super) fn render_special(
&mut self,
special: &ShipoutSpecial,
driver: PdfDriver,
files: &mut impl SourceProvider,
) -> Result<Option<PdfGraphics>, Error> {
let data = special.bytes.as_ref();
let (mode, bytes) = if driver == PdfDriver::PdfTeX {
let Some(body) = data
.strip_prefix(b"pdf:")
.or_else(|| data.strip_prefix(b"PDF:"))
else {
if !data.is_empty() && !data.starts_with(b"src:") && !data.starts_with(b"SRC:") {
let preview: String =
data.iter().take(65).map(|&byte| char::from(byte)).collect();
let preview = self.external_print(&preview);
let ellipsis = if data.len() > 65 { "..." } else { "" };
let warning =
format!("Non-PDF special ignored!\n<special> {preview}{ellipsis}\n");
files
.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
.map_err(|error| self.error(error, special.span))?;
}
return Ok(None);
};
if let Some(body) = body.strip_prefix(b"direct:") {
(PdfLiteralMode::Direct, body)
} else if let Some(body) = body.strip_prefix(b"page:") {
(PdfLiteralMode::Page, body)
} else {
(PdfLiteralMode::Origin, body)
}
} else {
let data = data.trim_ascii_start();
if data.is_empty() {
return Ok(None);
}
let body = data.strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start);
let Some(mut body) =
body.and_then(|body| body.strip_prefix(b"literal"))
.filter(|body| {
!body
.first()
.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b':')
})
else {
let name = data
.split(|b| b.is_ascii_whitespace())
.next()
.unwrap_or(data);
return Err(self.error(
format!(
"unsupported native XeTeX device special: {}",
String::from_utf8_lossy(name)
),
special.span,
));
};
let mut mode = PdfLiteralMode::XdvOrigin;
body = body.trim_ascii_start();
loop {
if let Some(rest) = body.strip_prefix(b"direct") {
mode = PdfLiteralMode::XdvDirect;
body = rest.trim_ascii_start();
} else if let Some(rest) = body.strip_prefix(b"reverse") {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
"xdvipdfmx: warning: pdf:literal reverse is unsupported and ignored\n",
)
.map_err(|error| self.error(error, special.span))?;
body = rest.trim_ascii_start();
} else {
break;
}
}
if body.is_empty() {
return Ok(None);
}
(mode, body)
};
Ok(Some(PdfGraphics::Literal {
mode,
bytes: Arc::from(bytes),
}))
}
}
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 56;
const COMPATIBLE_SCHEMAS: [u32; 25] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, SCHEMA,
const SCHEMA: u32 = 57;
const COMPATIBLE_SCHEMAS: [u32; 26] = [
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, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -253,6 +253,10 @@ pub enum OutputOperation {
tokens: Vec<Token>,
},
PdfSavePosition,
Special {
shipout: bool,
tokens: Vec<Token>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -273,6 +277,7 @@ impl OutputNode {
| OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore
| OutputOperation::PdfLiteral { .. }
| OutputOperation::Special { .. }
)
}
+1 -1
View File
@@ -56,7 +56,7 @@ pub use boxes::{
pub use cancellation::Cancellation;
pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{EntryCheckpoint, Executor, Limits};
pub use font_catalog::{
@@ -352,6 +352,7 @@ pub enum Primitive {
Leftmarginkern,
Rightmarginkern,
Pdflastlink,
Special,
}
impl Primitive {
@@ -991,6 +992,7 @@ impl Default for State {
("openout", Openout),
("closeout", Closeout),
("write", Write),
("special", Special),
("immediate", Immediate),
("message", Message),
("errmessage", Errmessage),
@@ -175,7 +175,8 @@ impl Collector {
}
pub fn output(&mut self, n: &OutputNode) {
if let OutputOperation::Write { tokens, .. }
| OutputOperation::PdfLiteral { tokens, .. } = &n.operation
| OutputOperation::PdfLiteral { tokens, .. }
| OutputOperation::Special { tokens, .. } = &n.operation
{
self.usage.token_list_cells += tokens.len();
}
+21 -4
View File
@@ -704,7 +704,7 @@ fn page_content(
pt(n)
}
};
use crate::pdf_device::{PdfGraphics, PdfLiteralMode};
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode};
use crate::render::DisplayUnits;
let mut content = PageContent::default();
@@ -757,6 +757,8 @@ fn page_content(
} = item
{
NativeTextRun::flush(&mut native_text, &mut content);
let previous_origin = content.origin.position();
let special_origin = mode.xdv_origin([*x, height - *y], height, list.magnification);
match mode {
PdfLiteralMode::Direct => {
native_text::NativeText::break_string(&mut tex_text, &mut content);
@@ -767,9 +769,18 @@ fn page_content(
content.move_origin([*x, height - *y], list.units, digits);
}
}
PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {
native_text::NativeText::finish(&mut tex_text, &mut content);
if let Some(point) = special_origin {
content.move_origin(point, list.units, digits);
}
}
}
content.bytes.extend_from_slice(bytes);
content.push(b'\n');
if special_origin.is_some() {
content.move_origin(previous_origin, list.units, digits);
}
continue;
}
if list.units == DisplayUnits::TeX {
@@ -810,9 +821,15 @@ fn page_content(
} = item
{
let [h, v] = content.origin.position();
native_text::rule(
&mut content, *x - h, *y + v, *width, *rule_height, height, digits,
);
if list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv) {
native_text::xdv_rule(
&mut content, *x - h, height - *y - v - *rule_height, *width, *rule_height, digits,
);
} else {
native_text::rule(
&mut content, *x - h, *y + v, *width, *rule_height, height, digits,
);
}
continue;
}
}
+22
View File
@@ -13,8 +13,23 @@ pub struct PdfFileOptions {
pub decimal_digits: u8,
pub pk_resolution: u32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PdfDriver {
#[default]
PdfTeX,
Xdv,
}
impl PdfDriver {
fn is_pdftex(&self) -> bool {
*self == Self::PdfTeX
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfPageData {
#[serde(default, skip_serializing_if = "PdfDriver::is_pdftex")]
pub driver: PdfDriver,
pub file: PdfFileOptions,
pub stream_compression: u8,
}
@@ -28,6 +43,13 @@ pub fn magnify(value: i64, mag: i32) -> i64 {
((n + 500) / 1000) as i64
}
}
/// Convert a physical dimension to the logical coordinates of a magnified page.
pub(crate) fn unmagnify(value: i64, mag: i32) -> i64 {
let mag = i64::from(mag);
let n = value * 1000;
n.signum() * ((n.abs() + mag / 2) / mag)
}
pub fn divide_scaled(value: i64, denominator: i64, digits: u8) -> (i64, i64) {
let scale = 10i128.pow(u32::from(digits));
let n = i128::from(value).abs();
@@ -8,6 +8,26 @@ pub enum PdfLiteralMode {
Origin,
Page,
Direct,
XdvOrigin,
XdvDirect,
}
impl PdfLiteralMode {
pub(crate) fn xdv_origin(
self,
point: [i64; 2],
page_height: i64,
magnification: i32,
) -> Option<[i64; 2]> {
match self {
Self::XdvOrigin => Some(point),
Self::XdvDirect => {
let inch = super::unmagnify(4_736_286, magnification);
Some([inch, page_height - inch])
}
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+30
View File
@@ -437,3 +437,33 @@ pub(super) fn rule(
}
out.push_str("Q\n");
}
pub(super) fn xdv_rule(
out: &mut PageContent,
x: i64,
y: i64,
width: i64,
height: i64,
digits: u8,
) {
if width <= 0 || height <= 0 {
return;
}
out.push_str("q\n");
// The XDV driver strokes rules up to 5 bp wide and fills thicker rules.
if width.min(height) <= 5 * 6_578_176 / 100 {
let (thickness, points) = if width > height {
(height, [x, y + height / 2, x + width, y + height / 2])
} else {
(width, [x + width / 2, y, x + width / 2, y + height])
};
let [x1, y1, x2, y2] = points.map(|value| print_sp(value, digits));
let thickness = print_sp(thickness, digits + 1);
out.push_str(&format!("{thickness} w {x1} {y1} m {x2} {y2} l S\n"));
} else {
let [x, y, width, height] = [x, y, width, height].map(|value| print_sp(value, digits));
out.push_str(&format!("{x} {y} {width} {height} re f\n"));
}
out.push_str("Q\n");
}
@@ -19,6 +19,7 @@ pub(super) struct PdfProjection {
stack: Vec<GraphicsState>,
units: DisplayUnits,
height: i64,
magnification: i32,
digits: u8,
units_per_bp: f64,
text_active: bool,
@@ -48,6 +49,7 @@ impl PdfProjection {
stack: vec![graphics], // The page writer begins with q.
units: page.units,
height: page.height,
magnification: page.magnification,
digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits),
units_per_bp: 1.0 / page.units.bp(1),
text_active: false,
@@ -132,13 +134,20 @@ impl PdfProjection {
if *mode != PdfLiteralMode::Direct {
self.text_active = false;
}
let previous_origin = self.origin.position();
let special_origin = mode.xdv_origin([x, y], self.height, self.magnification);
if *mode == PdfLiteralMode::Origin {
self.move_origin([x, y]);
} else if let Some(point) = special_origin {
self.move_origin(point);
}
if self.apply_literal(bytes).is_none() {
self.graphics = None;
self.stack.clear();
}
if special_origin.is_some() {
self.move_origin(previous_origin);
}
return None;
}
self.text_active = false;