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

@@ -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),
}))
}
}