Handle unclaimed XeTeX specials at shipout

This commit is contained in:
gloamxun committed 2026-11-28 06:04:09 +08:00
1 parent e2af618e65
commit 885911485e
10 files changed
+273 -21

No files matched your search

@@ -627,7 +627,11 @@ impl Executor {
_ => {}
}
shipout.specials.push(special);
shipout.pdf_graphics_steps.push(graphics);
// The XDV driver enters graphics mode for every special, even
// an empty special or one consumed without painting.
shipout.pdf_graphics_steps.push(graphics.or_else(|| {
xdv.then_some(PdfGraphics::TextBoundary)
}));
} else if output.is_pdf_graphics() {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI");
@@ -355,7 +355,7 @@ impl PdfLinkShipout {
previous.1 || *dx != 0 || *dy != 0);
}
}
Some(PdfGraphics::Literal { .. }) | None => {}
Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary) | None => {}
}
}
LinkPaint::RowStart(row) if executor.pdf_running_links => {
@@ -141,12 +141,17 @@ impl Executor {
(PdfLiteralMode::Origin, body)
}
} else {
let data = data.trim_ascii_start();
if data.is_empty() {
let raw = data;
let data = xdv_skip_white(raw);
if data.is_empty()
|| [b"src:".as_slice(), b"pos:", b"om:"]
.iter()
.any(|prefix| data.starts_with(*prefix))
{
return Ok(None);
}
if let Some(graphics) = xdv_transform(data)
.map_err(|message| self.error(message, special.span))?
if let Some(graphics) =
xdv_transform(data).map_err(|message| self.error(message, special.span))?
{
return Ok(Some(graphics));
}
@@ -159,7 +164,8 @@ impl Executor {
return self.fail("native PDF information payload limit exceeded");
}
for warning in warnings {
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
files
.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
.map_err(|error| self.error(error, special.span))?;
}
self.reads.insert(Dependency::PdfInfoState);
@@ -167,17 +173,30 @@ impl Executor {
return Ok(None);
}
let Some(mut body) = body.and_then(|body| xdv_operand(body, b"literal")) 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,
));
if xdv_claims_special(raw, data) {
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,
));
}
// The raw whatsit stays in the shipout. An unclaimed special
// has a diagnostic and no PDF paint or resource effect.
let preview = String::from_utf8_lossy(&data[..data.len().min(50)]);
let ellipsis = if data.len() >= 50 { "..." } else { "" };
let warning = format!(
"xdvipdfmx:warning: Unparsed material at end of special ignored.\n\nCurrent input buffer is -->{preview}{ellipsis}<--\n"
);
files
.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
.map_err(|error| self.error(error, special.span))?;
return Ok(None);
};
let mut mode = PdfLiteralMode::XdvOrigin;
body = body.trim_ascii_start();
@@ -209,6 +228,80 @@ impl Executor {
}
}
fn xdv_is_space(byte: u8) -> bool {
matches!(byte, 0 | b'\t' | b'\n' | 12 | b'\r' | b' ')
}
fn xdv_skip_white(mut data: &[u8]) -> &[u8] {
loop {
data = &data[data.iter().take_while(|&&byte| xdv_is_space(byte)).count()..];
if data.first() != Some(&b'%') {
return data;
}
data = &data[data
.iter()
.position(|&byte| matches!(byte, b'\n' | b'\r'))
.unwrap_or(data.len())..];
}
}
fn xdv_identifier(data: &[u8]) -> &[u8] {
&data[..data
.iter()
.take_while(|byte| byte.is_ascii_alphanumeric() || **byte == b'_')
.count()]
}
// Keep an explicit failure for device protocols with a claiming handler
// whose operation has yet to be implemented. The prefixes and identifiers
// follow xdvipdfmx's PDF, XeTeX, dvips, color, tpic, HTML and compat probes.
fn xdv_claims_special(raw: &[u8], data: &[u8]) -> bool {
let prefixes: &[&[u8]] = &[
b"pdf:",
b"x:",
b"dvipdfmx:",
b"ps:",
b"PS:",
b"pst:",
b"PST:",
b"header",
b"PSfile",
b"psfile",
&[b'"', b' '],
b"postscriptbox",
b"pdfcolorstackinit",
b"pdfcolorstack",
b"pdffontattr",
b"landscape",
b"papersize",
];
let blank = &raw[raw.iter().take_while(|&&byte| xdv_is_space(byte)).count()..];
let html = &raw[raw
.iter()
.take_while(|byte| byte.is_ascii_whitespace() || **byte == 11)
.count()..];
let tpic = blank.strip_prefix(b"tpic:").unwrap_or(blank);
prefixes.iter().any(|prefix| data.starts_with(prefix))
|| html.starts_with(b"html:")
|| matches!(xdv_identifier(blank), b"color" | b"background")
|| matches!(
xdv_identifier(tpic),
b"pn"
| b"pa"
| b"fp"
| b"ip"
| b"da"
| b"dt"
| b"sp"
| b"ar"
| b"ia"
| b"sh"
| b"wh"
| b"bk"
| b"tx",
)
}
fn xdv_pdf_body(data: &[u8]) -> Option<&[u8]> {
data.trim_ascii_start().strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start)
}
+5 -1
View File
@@ -1201,6 +1201,8 @@ fn page_content(
content.push(b'\n');
}
DisplayItem::PdfColor { .. } => unreachable!("color handled before text"),
// The text runs above are closed without changing the graphics transform.
DisplayItem::PdfGraphics { operation: PdfGraphics::TextBoundary, .. } => {}
DisplayItem::PdfGraphics { x, y, operation } => {
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
let device_origin = list.units == DisplayUnits::TeX && !xdv;
@@ -1238,7 +1240,9 @@ fn page_content(
.map(crate::pdf_image::real);
content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n"));
}
PdfGraphics::Literal { .. } => unreachable!("literal handled before text"),
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
unreachable!("handled before graphics transforms")
}
}
}
}
@@ -37,6 +37,8 @@ pub enum PdfGraphics {
Restore { shift: [i64; 2] },
Literal { mode: PdfLiteralMode, bytes: Arc<[u8]> },
SaveMatrix(PdfMatrix),
/// An XDV special switched the device from text to graphics mode.
TextBoundary,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+1
View File
@@ -812,6 +812,7 @@ impl DisplayList {
DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics;
match operation {
PdfGraphics::TextBoundary => {}
PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"),
PdfGraphics::Save | PdfGraphics::Matrix(_) | PdfGraphics::SaveMatrix(_) => {
if matches!(operation, PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) {
+1 -1
View File
@@ -343,7 +343,7 @@ impl SourceMap {
continue;
}
match operation {
PdfGraphics::Literal { .. } => {}
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {}
PdfGraphics::Save => graphics_stack.push(transform),
PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
@@ -153,6 +153,9 @@ impl PdfProjection {
return None;
}
self.text_active = false;
if matches!(operation, PdfGraphics::TextBoundary) {
return None;
}
let native = self.units == DisplayUnits::TeX && !self.xdv;
if native {
self.move_origin([x, y]);
@@ -174,7 +177,9 @@ impl PdfProjection {
let [x, y] = if native { [0, 0] } else { [x, y] };
self.concatenate(matrix.about(x as f64, y as f64, false));
}
PdfGraphics::Literal { .. } => unreachable!("handled before typed graphics"),
PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {
unreachable!("handled before graphics transforms")
}
}
return None;
}
+57
View File
@@ -819,6 +819,63 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
### XeTeX 出页的未认领 special
按 xdvipdfmx 的分派语法识别 PDF、XeTeX、dvips、颜色、tpic、
HTML 和兼容命令。在出页时保留原始 whatsit 的字节和位置,
对无处理器的载荷发出警告,按照 PDF 空白和注释规则截取
诊断文本。设备识别到的未实现命令继续给出错误。src、pos、
om 沿用驱动的纯元数据语义。实际警告与生成文件进入现有
会话发布和错误恢复路径。每个 XDV special 都进入图形模式。
纯诊断、空载荷及元数据形成只结束文字对象的设备步骤,使用
现有出页顺序和文字状态,不改变变换或绘制内容。
[参考驱动进入图形模式](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/dvi.c#L902-L923)
[参考驱动分派](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/specials.c)
[参考驱动的空白和诊断](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/pdfparse.c)
三项 XeTeX 定向回归通过。三个未认领载荷的诊断逐条与
xdvipdfmx 一致,页图逐像素相同。真实 FandolSong 的汉字
间插对照使用同一字体和类寄存器。带标记与无标记的盒宽
分别为 1966080 和 1769472 sp,两端词框和像素相同。
以真实 Latin Modern CFF 的四个 A 验证未认领、空载荷和源位置
三种边界。首版生成一个 PDF 文本对象,修正后与参考一样生成
四个,词框及 144 DPI 灰度图相同。源、PDF 内容流和先前结果
保留在 text-boundary,final-probe.log 为
b4b5e5e782a4c57421aa05702745620d750109c1e2decbe72f509b07534ab0e6。
四页连续编辑中,只改标记时实际日志更新,页面差量为空。
移动正文及从未实现设备命令恢复时只替换第 2 页,两轮各
复用 66 步。三次成功修订的 PDF、测量页面、SVG、
来源映射、日志与 aux 都等于独立全量。失败保留已发布
预览与 aux。证据在 target/p3-xecjk-project,
revision.log 的 SHA-256 为 cd4741a8364c70318ae742105c15dd4e11c2916cdb8bbb77e6e232e011e8fa8e。
官方 xeCJK 3.10.6 的 xeCJK-example-boundary-register.tex
保持原字节,使用真实 xeCJK、ctexhook、ctexpatch、fontspec、
Fandol 字体及发行版 Article。沿用含实际 XeTeXglyphbounds
别名的 schema74,并加入系统 updmap 的实际 pdftex.map 与
cmmi9.pfb。两端生成一页,40 条警告逐条一致,380 个词
的文本和顺序一致,aux 逐字节相同。文本对象边界修正后,
8 个 AA 词框的差异消失,24 处词框差异降为 16 处,剩余
都含 CMMI9 的 x。144 DPI 仍有 174 个像素不同,集中在
两个字母 B 的字形范围。该定位记录位于
boundary-final/raster-location.log,摘要为
c65735ab03547c6083fc66dd683b18ece02b7b745a1fe849403dc4405eb6f97a。
保留旧格式缺别名、调试步数限制以及缺实际数学字体映射的
原始失败记录。最终 receipt.json 为
bf8170ce91eb00bbb2e54b6dbf30c1994f3b4de438c11c54142e8196193e7b37,
之前的 before-text-boundaries.json 为
132e6d51dcb9e98a1dbba015c91400f5a288f3e717053e641cb6fa3903e52674。
[xeCJK 官方发布](https://ctan.org/pkg/xecjk)
下一入口留在 next-type1-horizontal。实际 cmmi9 和 cmr10 的
TeX 盒宽分别为 25.59085 pt 和 33.88892 pt,两端一致。原版 PDF
的嵌入 Type1C 使用已编码 CharString 的字宽,原生 Type 1 字典
目前使用 TFM。x 的实际字体宽度为 582,原生 PDF 为 582.6。
Y、v、W 也复现区别。按实际字体程序导出度量并保留 TeX 位置,
另通过 XDV 与 PDF 字形位置对照跟进两个 B 的灰度差异。
[参考驱动写入实际 Type 1 字宽](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/type1.c#L258-L331)
### XeTeX 的 OpenType 纵排
字体请求记录文字方向,真实字体版本与纵排请求共同参与会话身份。
+86
View File
@@ -707,6 +707,92 @@ fn font_mapping_changes_recover_and_update_the_page_that_used_the_resource() {
fs::remove_dir_all(p).unwrap();
}
#[test]
fn xetex_unclaimed_special_warns_at_shipout_and_retains_the_whatsit() {
use texrra_tex_core::execution::{Event, InputProfile};
let root = directory("xetex-unclaimed-special");
let mut job = request(&root);
job.world = WorldConfig::new(&root);
job.input_profile = InputProfile::XeTeX;
let entry = root.join("main.tex");
fs::write(
root.join("face.ttf"),
include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf"),
)
.unwrap();
fs::write(
&entry,
br#"\catcode123=1 \catcode125=2 \catcode37=12
\setbox0=\hbox{\special{unshipped marker}}
\font\face="[face.ttf]" at 9pt
\shipout\hbox{\face A\special{ vendor: marker}A\special{src:1 source.tex}A
\special{% comment-only}A\special{}A}
\end"#,
)
.unwrap();
let compiler = NativeCompiler::default();
let result = compiler.compile(job.clone()).unwrap();
let shipout = result
.execution
.execution
.events
.iter()
.find_map(|event| {
if let Event::Shipout(page) = event {
Some(page)
} else {
None
}
})
.unwrap();
let specials: Vec<_> = shipout
.specials
.iter()
.map(|special| special.bytes.as_ref())
.collect();
assert_eq!(
specials,
[
b" vendor: marker".as_slice(),
b"src:1 source.tex",
b"% comment-only",
b"",
]
);
let log = fs::read_to_string(root.join("job.log")).unwrap();
assert_eq!(
log.matches("Unparsed material at end of special ignored.")
.count(),
1
);
assert!(log.contains("Current input buffer is -->vendor: marker<--"));
let pdf = result.pdf.as_deref().unwrap();
let pdf = lopdf::Document::load_mem(pdf).unwrap();
let content = pdf.get_page_content(pdf.get_pages()[&1]).unwrap();
let content = String::from_utf8(content).unwrap();
assert_eq!(content.matches("BT /U").count(), 5);
assert!(!content.contains("vendor:"));
fs::write(
&entry,
br"\catcode123=1 \catcode125=2 \shipout\hbox{\special{tpic:pn 5}}\end",
)
.unwrap();
let error = compiler
.compile_detailed(job)
.err()
.unwrap()
.error
.to_string();
assert!(
error.contains("unsupported native XeTeX device special: tpic:pn"),
"{error}"
);
assert!(Arc::ptr_eq(&result, &compiler.latest().unwrap()));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn xetex_vertical_font_uses_tex_box_metrics_and_pdf_writing_mode() {
use texrra_tex_core::execution::{Event, InputProfile};