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();
}