Include PDF graphics in the native XeTeX device

This commit is contained in:
gloamxun committed 2026-11-21 13:34:55 +08:00
1 parent facecbf790
commit 794c2f9b2c
19 files changed
+545 -37

No files matched your search

@@ -1,6 +1,6 @@
//! TeX special whatsits and PDF driver dispatch at shipout.
use super::*;
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode};
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode, PdfMatrix};
impl Executor {
pub(super) fn scan_special(
@@ -82,6 +82,11 @@ impl Executor {
if data.is_empty() {
return Ok(None);
}
if let Some(graphics) = xdv_transform(data)
.map_err(|message| self.error(message, special.span))?
{
return Ok(Some(graphics));
}
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"))
@@ -132,3 +137,43 @@ impl Executor {
}))
}
}
fn xdv_transform(data: &[u8]) -> Result<Option<PdfGraphics>, &'static str> {
let Some(separator) = data.iter().position(|&byte| byte == b':') else {
return Ok(None);
};
let (driver, body) = data.split_at(separator);
let mut words = body[1..]
.split(|byte| byte.is_ascii_whitespace())
.filter(|word| !word.is_empty());
let command = words.next().unwrap_or_default();
let number = |word: Option<&[u8]>| {
word.and_then(|word| std::str::from_utf8(word).ok())
.and_then(|word| word.parse::<f64>().ok())
.filter(|value| value.is_finite())
.ok_or("invalid XDV graphics transformation number")
};
let graphics = match (driver, command) {
(b"pdf", b"btrans" | b"begintransform" | b"begintrans" | b"bt") => match words.next() {
None => PdfGraphics::Save,
Some(b"rotate") => {
PdfGraphics::SaveMatrix(PdfMatrix::rotation(number(words.next())?))
}
_ => return Err("unsupported XDV begintransform arguments"),
},
(b"x", b"gsave") => PdfGraphics::Save,
(b"pdf", b"etrans" | b"endtransform" | b"endtrans" | b"et") | (b"x", b"grestore") => {
PdfGraphics::Restore { shift: [0, 0] }
}
(b"x", b"scale") => PdfGraphics::Matrix(PdfMatrix::scale(
number(words.next())?,
number(words.next())?,
)),
(b"x", b"rotate") => PdfGraphics::Matrix(PdfMatrix::rotation(number(words.next())?)),
_ => return Ok(None),
};
if words.next().is_some() {
return Err("unexpected XDV graphics transformation argument");
}
Ok(Some(graphics))
}