Save the TeX cursor in native shipout order

This commit is contained in:
gloamxun committed 2026-11-21 04:27:06 +08:00
1 parent 555a029505
commit 413939911f
12 files changed
+173 -28

No files matched your search

+11 -11
View File
@@ -192,7 +192,7 @@ impl WalkBudget<'_> {
pub(super) struct LeaderEffects {
pub outputs: Vec<OutputNode>,
pub graphics_positions: Vec<[i64; 2]>,
pub output_positions: Vec<[i64; 2]>,
pub work: usize,
}
@@ -262,7 +262,7 @@ impl NativeBox {
cancellation: Option<&Cancellation>,
) -> Result<LeaderEffects, &'static str> {
let mut outputs = Vec::new();
let mut graphics_positions = Vec::new();
let mut output_positions = Vec::new();
let mut budget = WalkBudget {
remaining: limit,
cancellation,
@@ -270,15 +270,15 @@ impl NativeBox {
};
self.walk_at(0, 0, 0, false, &mut budget, &mut |x, y, item| {
if let BoxPaint::Output(o) = item {
if o.is_pdf_graphics() {
graphics_positions.push([x, y]);
if o.needs_shipout_position() {
output_positions.push([x, y]);
}
outputs.push(o.clone());
}
})?;
Ok(LeaderEffects {
outputs,
graphics_positions,
output_positions,
work: limit - budget.remaining,
})
}
@@ -762,15 +762,15 @@ impl NativeBox {
}
}
pub(super) fn pdf_graphics_positions(&self) -> Vec<[i64; 2]> {
let mut all = Vec::new();
pub(super) fn positioned_outputs(&self) -> Vec<[i64; 2]> {
let mut positions = Vec::new();
self.walk(0, 0, &mut |x, y, node| {
if matches!(node, BoxPaint::PdfGraphics) {
all.push([x, y]);
if matches!(node, BoxPaint::Output(node) if node.needs_shipout_position()) {
positions.push([x, y]);
}
})
.expect("graphics traversal of an already measured list");
all
.expect("output traversal of an already measured list");
positions
}
fn walk(
@@ -632,6 +632,7 @@ impl Printer<'_> {
}
self.tokens(tokens)?;
}
OutputOperation::PdfSavePosition => self.command("pdfsavepos"),
OutputOperation::PdfSetMatrix(tokens) => {
self.command("pdfsetmatrix");
self.tokens(tokens)?;
@@ -2152,6 +2152,10 @@ impl Executor {
self.reads.insert(Dependency::PdfRandomState);
Ok(self.state.random_seed())
}
Meaning::Primitive(p @ (Primitive::Pdflastxpos | Primitive::Pdflastypos)) => {
self.reads.insert(Dependency::PdfLastPosition);
Ok(self.state.pdf_last_position[usize::from(p == Primitive::Pdflastypos)])
}
Meaning::Primitive(Primitive::Pdflastlink) => {
self.reads.insert(Dependency::PdfObjects);
Ok(self
@@ -2824,6 +2828,9 @@ impl Executor {
OutputOperation::PdfLink(_) => {
return self.fail("PDF link operation requires a positioned shipout");
}
OutputOperation::PdfSavePosition => {
return self.fail("PDF position requires a positioned shipout");
}
OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore
@@ -19,6 +19,12 @@ impl Executor {
self.output_command(primitive, token.span, files)?
}
Pdfcolorstack => self.scan_pdf_color_action(token.span, files)?,
Pdfsavepos => {
self.defer_output(OutputNode {
operation: OutputOperation::PdfSavePosition,
span: token.span,
})?;
}
Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => {
self.scan_pdf_graphics(primitive, token.span, files)?
}
@@ -247,13 +247,15 @@ impl Executor {
let vertical_origin =
i64::from(self.read_parameter(Parameter::Pdfvorigin).width()) + v_offset;
let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width());
let mut page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
let requested_page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
if page_width == 0 {
page_width = b.width + 2 * horizontal_origin;
}
if page_height == 0 {
page_height = b.height + b.depth + 2 * vertical_origin;
}
let page_height = if requested_page_height == 0 {
b.height + b.depth + 2 * vertical_origin
} else {
requested_page_height
};
let device = ShipoutDevice {
magnification,
page_width,
@@ -300,10 +302,10 @@ impl Executor {
}
let mut link_depth = self.pdf_link_stack.len();
let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link());
let mut graphics_positions = if let Some(effects) = &leader_effects {
effects.graphics_positions.clone().into_iter()
} else if outputs.iter().any(|node| node.is_pdf_graphics()) {
b.pdf_graphics_positions().into_iter()
let mut output_positions = if let Some(effects) = &leader_effects {
effects.output_positions.clone().into_iter()
} else if outputs.iter().any(|node| node.needs_shipout_position()) {
b.positioned_outputs().into_iter()
} else {
Vec::new().into_iter()
};
@@ -313,6 +315,13 @@ impl Executor {
let mut has_space_nodes = false;
let mut pdf_objects = Vec::new();
for output in outputs {
let position = if output.needs_shipout_position() {
Some(output_positions.next().ok_or_else(|| {
self.error("missing positioned native output node", output.span)
})?)
} else {
None
};
if let OutputOperation::PdfObject(number) = output.operation {
self.current = output.span;
self.tick()?;
@@ -329,15 +338,34 @@ impl Executor {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI");
}
let point = graphics_positions.next().ok_or_else(|| {
self.error("missing positioned PDF graphics node", output.span)
})?;
pdf_graphics_steps.push(self.ship_pdf_graphics(
output,
point,
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()?;
let [x, y] = position.expect("savepos needs a shipout position");
let (left, top, height) = if device.pdf.is_some() {
(horizontal_origin, vertical_origin, page_height)
} else {
const DVI_ORIGIN: i64 = 4_736_286;
let top = v_offset + DVI_ORIGIN;
let height = if requested_page_height == 0 {
b.height + b.depth + 2 * top
} else {
requested_page_height
};
(h_offset + DVI_ORIGIN, top, height)
};
self.state.pdf_last_position = [
i32::try_from(left + x)
.map_err(|_| self.error("horizontal saved position overflow", output.span))?,
i32::try_from(height - top - b.height - y)
.map_err(|_| self.error("vertical saved position overflow", output.span))?,
];
} else if let OutputOperation::PdfTextSpace(operation) = output.operation {
self.current = output.span;
self.tick()?;
@@ -371,8 +399,8 @@ impl Executor {
self.output_node(output, files)?;
}
}
if graphics_positions.next().is_some() {
return self.fail("unexpected positioned PDF graphics node");
if output_positions.next().is_some() {
return self.fail("unexpected positioned native output node");
}
if let Some((_, span)) = graphics_stack.last() {
return Err(self.error(
@@ -213,6 +213,8 @@ impl Executor {
| Primitive::Pdflastximage
| Primitive::Pdflastximagepages
| Primitive::Pdflastximagecolordepth
| Primitive::Pdflastxpos
| Primitive::Pdflastypos
| Primitive::Numexpr
| Primitive::Etexversion
| Primitive::Currentgrouplevel
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 43;
const COMPATIBLE_SCHEMAS: [u32; 12] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, SCHEMA];
const SCHEMA: u32 = 44;
const COMPATIBLE_SCHEMAS: [u32; 13] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -252,6 +252,7 @@ pub enum OutputOperation {
shipout: bool,
tokens: Vec<Token>,
},
PdfSavePosition,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -275,6 +276,10 @@ impl OutputNode {
)
}
pub(super) fn needs_shipout_position(&self) -> bool {
self.is_pdf_graphics() || matches!(self.operation, OutputOperation::PdfSavePosition)
}
pub(super) fn dimensions(&self) -> Option<(i64, i64, i64)> {
match &self.operation {
OutputOperation::PdfImage { image, .. } => Some(image.dimensions()),
@@ -370,6 +370,7 @@ pub enum Dependency {
PdfCatalogState,
PdfObjects,
PdfImages,
PdfLastPosition,
GlyphUnicode,
ResourceStatistics,
PdfDeviceConfiguration {
@@ -118,6 +118,9 @@ pub enum Primitive {
Pdfoutline,
Pdfinfo,
Pdfsetmatrix,
Pdfsavepos,
Pdflastxpos,
Pdflastypos,
Pdfrestore,
Pdfglyphtounicode,
Pdffontattr,
@@ -637,6 +640,8 @@ pub struct State {
#[serde(with = "ordered_map")]
mathfonts: BTreeMap<(u8, u8), FontId>,
pub(super) last_badness: i32,
#[serde(default)]
pub(super) pdf_last_position: [i32; 2],
/// TeX prepare_mag freeze, independent of ordinary grouping/assignments.
pub(super) magnification_set: Option<i32>,
pub(super) output_mode_set: Option<i32>,
@@ -745,6 +750,7 @@ impl Default for State {
case_codes: BTreeMap::new(),
mathfonts: BTreeMap::new(),
last_badness: 0,
pdf_last_position: [0, 0],
magnification_set: None,
output_mode_set: None,
pdf_file_options: None,
@@ -1006,6 +1012,9 @@ impl Default for State {
("pdfoutline", Pdfoutline),
("pdfinfo", Pdfinfo),
("pdfsetmatrix", Pdfsetmatrix),
("pdfsavepos", Pdfsavepos),
("pdflastxpos", Pdflastxpos),
("pdflastypos", Pdflastypos),
("pdfrestore", Pdfrestore),
("pdfglyphtounicode", Pdfglyphtounicode),
("pdffontattr", Pdffontattr),
@@ -1413,6 +1422,7 @@ impl State {
self.split_marks.clear();
self.page_marks.clear();
self.last_badness = 0;
self.pdf_last_position = [0, 0];
self.magnification_set = None;
self.output_mode_set = None;
self.pdf_file_options = None;
+28 -1
View File
@@ -1308,7 +1308,7 @@ INITEX 对照。11 页的原始 sp 尺寸、查询值、设备图像属性及 14
`target/p3-png-native/comparison.json`,回执 SHA-256
`084c547620db998a0284b54d465f2b5b1d3e056b0e7cbfdaf21c3bbc38605a32`。
图片测试共4项通过,覆盖原有 JPEG、旋转 PDF、PDF 预览与本轮 PNG。
在同一原子项目版本中替换 PNG 二进制,续编实用检查点,只重发引用该资源的
在同一原子项目版本中替换 PNG 二进制,续编复用检查点,只重发引用该资源的
第二页,PDF、SVG 与来源映射同独立零复用编译一致。重读生成的对象确认 RGB
与蒙版字节均来自更新后的图像。验证保留了 INITEX 缺类别码、从错误字段读取
断言及设备对象声明使两页重发的初次记录。最终日志 SHA-256 为
@@ -1317,6 +1317,33 @@ INITEX 对照。11 页的原始 sp 尺寸、查询值、设备图像属性及 14
本轮沿用冻结 schema43。原样 ACM 双栏已完成图片读取,并停在图像位置记录的
`\tex_savepos:D`。下一入口为实现随实际发页更新的位置状态和延迟引用。
### 发页保存位置
pdfTeX profile 的 `\pdfsavepos` 产生零尺寸输出节点。盒被实际发出时,
节点与 PDF 图形扩展共用原始盒和已定胶水的定位遍历。最后位置为算过页原点后
的 TeX 游标,纵坐标从纸底量起。批次中的延迟写出按节点顺序立即读到最新位置,
没有发出的盒不更新值。leaders 中的每次实际输出仍更新位置,内部流写出沿用
既有抑制规则。`\pdflastxpos`/`\pdflastypos` 进入真实整数扫描和原生状态指纹。
新原语纳入格式 schema44。已有 schema43 格式保留原能力,新的原语绑定要求重新转储。
[pdfTeX 的发页位置原语](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L37035-L37068)
[LaTeX 在发页时读取位置属性](https://github.com/latex3/latex2e/blob/develop/base/ltproperties.dtx)
INITEX 对照的 23 条位置记录逐字节一致,涵盖未发盒、嵌套盒、定宽胶水、
垂直游标、leaders、PDF 矩阵、跨页及即时和延迟读出。两场景分别使用 PDF
页原点和 DVI 的一英寸原点。三页 PDF 灰度图在 144 DPI 逐像素一致。
DVI 的坐标文件在 PDF 驱动报告 DVI 导出限制前完成,原生 DVI 文件导出仍待实现。
复验第二页水平位移复用 893 步,只重发第二页,保留第一页位置。
发布 PDF、SVG、归一化来源映射和位置文件与独立零复用编译一致。
发页、PDF 配置、链接及图片的13项定向测试通过。冻结 schema43 的小格式在
新构建中重载并生成 PDF。原样 LaTeX 格式转储及 ACM 的后续状态见出版模板矩阵。
回执在 `target/p3-savepos-native`。
- `receipt.json` 为 `3e1b1f51bf799618522258397ed793dd5f2d34007b5dec33e78d5ba196b61fb7`。
- `page-comparison.json` 为 `37311dca4bcaa9eb170638a0b9c2be27a9bfd806b3caa7a97a54822135e64d6d`。
- `checkpoint/receipt.json` 为 `631387e96d11459db3fa7f315a69682e020d536587fb27e8aecd7483a5abb217`。
- `legacy/receipt.json` 为 `c37757041645dd61160c0df47254bdef806a4da904b1f5c3aad18fd50001f2cb`。
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
+58
View File
@@ -181,3 +181,61 @@ fn initex_page_parameters_are_not_seeded_from_the_pdf_driver() {
);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn saved_pdf_position_is_observed_in_shipout_order() {
let work = directory();
let source = r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfpageheight=100pt \pdfhorigin=10pt \pdfvorigin=12pt
\immediate\openout5=positions.dat
\setbox5=\hbox{\kern32pt\pdfsavepos}
\immediate\write5{\the\pdflastxpos,\the\pdflastypos}
\shipout\hbox to40pt{\vrule width8pt height9pt
\hskip 2pt plus1fil \pdfsavepos\write5{\the\pdflastxpos,\the\pdflastypos}
\hbox{\kern3pt\pdfsavepos\write5{\the\pdflastxpos,\the\pdflastypos}}
\kern7pt}
\immediate\write5{\the\pdflastxpos,\the\pdflastypos}
\immediate\closeout5
\end";
fs::write(work.join("probe.tex"), source).unwrap();
let output = native_fonts::command()
.args([
"native",
"--job",
"--initex",
"--etex",
"probe.tex",
"native.pdf",
])
.current_dir(&work)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let native = fs::read(work.join("positions.dat")).unwrap();
let output = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&work)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stdout)
);
assert_eq!(native, fs::read(work.join("positions.dat")).unwrap());
assert_eq!(
native,
b"0,0\n2621440,5177344\n2818048,5177344\n2818048,5177344\n"
);
fs::remove_dir_all(work).unwrap();
}