Keep native PDF navigation transforms across page output

This commit is contained in:
gloamxun committed 2026-11-28 15:03:18 +08:00
1 parent 0e71c15b01
commit cb8ed90df2
6 files changed
+155 -46

No files matched your search

@@ -230,6 +230,7 @@ pub struct Executor {
xdv_colors: crate::pdf_device::xdv_color::ColorState,
xdv_annotations: crate::pdf_device::xdv_annotation::AnnotationState,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
pdf_navigation_matrix: Option<crate::pdf_device::Affine>,
pdf_running_links: bool,
pdf_interword_spaces: bool,
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>,
@@ -414,6 +415,7 @@ impl Executor {
xdv_colors: Default::default(),
xdv_annotations: Default::default(),
pdf_link_stack: Vec::new(),
pdf_navigation_matrix: None,
pdf_running_links: true,
pdf_interword_spaces: false,
pdf_space_font: None,
@@ -490,7 +490,10 @@ impl Executor {
}
let output_count = outputs.len();
let has_link_material = !self.pdf_link_stack.is_empty() || outputs.iter().any(|node| node.is_pdf_link());
let mut pdf_link_shipout = (has_link_material && !for_form && device.pdf.is_some())
let mut pdf_link_shipout = (!for_form && device.pdf.is_some()
&& (has_link_material || outputs.iter().any(|node| {
matches!(node.operation, OutputOperation::PdfSetMatrix(_))
})))
.then(|| self.begin_pdf_link_shipout(b, device));
let mut output_positions = if let Some(effects) = &leader_effects {
effects.output_positions.clone().into_iter()
@@ -13,8 +13,7 @@ use crate::execution::boxes::{BoxPaint, BoxLayout};
struct Segment {
index: usize,
rect: [i64; 4],
transform: Affine,
transformed: bool,
transform: Option<Affine>,
}
#[derive(Clone)]
@@ -36,8 +35,10 @@ pub(super) struct PdfLinkShipout {
events: std::iter::Peekable<std::vec::IntoIter<((usize, usize), i64, i64, LinkPaint)>>,
output_count: usize,
active: Vec<ActiveLink>,
transform: (Affine, bool),
saved: Vec<(Affine, bool)>,
// pdfTeX retains the navigation matrix in PDF coordinates across shipouts.
transform: Option<Affine>,
saved: Vec<Option<Affine>>,
page_height: i64,
graphics_index: usize,
output: PageLinks,
origin: [i64; 2],
@@ -45,26 +46,23 @@ pub(super) struct PdfLinkShipout {
numbered: bool,
}
fn map_point(matrix: Affine, x: i64, y: i64) -> [i64; 2] {
matrix
.point(x as f64, y as f64)
.map(|value| value.round() as i64)
fn map_point(matrix: Affine, page_height: i64, [x, y]: [i64; 2]) -> [i64; 2] {
let [x, y] = matrix.point(x as f64, (page_height - y) as f64);
// The PDF device rounds transformed positions to scaled TeX integers.
[i64::from(x.round() as i32), page_height - i64::from(y.round() as i32)]
}
fn link_rect(rect: [i64; 4], matrix: Affine, margin: i64) -> [i64; 4] {
let [left, top, right, bottom] = rect;
let corners = [
map_point(matrix, left, top),
map_point(matrix, right, top),
map_point(matrix, left, bottom),
map_point(matrix, right, bottom),
];
[
corners.iter().map(|p| p[0]).min().unwrap() - margin,
corners.iter().map(|p| p[1]).min().unwrap() - margin,
corners.iter().map(|p| p[0]).max().unwrap() + margin,
corners.iter().map(|p| p[1]).max().unwrap() + margin,
]
fn link_rect(rect: [i64; 4], matrix: Option<Affine>, page_height: i64, margin: i64) -> [i64; 4] {
let [mut left, mut top, mut right, mut bottom] = rect;
if let Some(matrix) = matrix {
let corners = [[left, top], [right, top], [left, bottom], [right, bottom]]
.map(|point| map_point(matrix, page_height, point));
left = corners.iter().map(|p| p[0]).min().unwrap();
top = corners.iter().map(|p| p[1]).min().unwrap();
right = corners.iter().map(|p| p[0]).max().unwrap();
bottom = corners.iter().map(|p| p[1]).max().unwrap();
}
[left - margin, top - margin, right + margin, bottom + margin]
}
impl ActiveLink {
@@ -73,7 +71,8 @@ impl ActiveLink {
output: &mut PageLinks,
row: BoxLayout,
point: [i64; 2],
transform: (Affine, bool),
transform: Option<Affine>,
page_height: i64,
margin: i64,
) {
let [x, y] = point;
@@ -92,28 +91,27 @@ impl ActiveLink {
self.segment = Some(Segment {
index: output.annotations.len(),
rect,
transform: transform.0,
transformed: transform.1,
transform,
});
output.annotations.push(LinkAnnotation {
object_number: None,
rect: link_rect(rect, transform.0, margin),
rect: link_rect(rect, transform, page_height, margin),
attributes: self.attributes.clone(),
action: self.action.clone(),
});
}
fn end_segment(self, output: &mut PageLinks, x: i64, margin: i64) {
fn end_segment(self, output: &mut PageLinks, x: i64, page_height: i64, margin: i64) {
if let Some(segment) = self.segment
&& self.layout.width.is_none()
{
let painted = &mut output.annotations[segment.index].rect;
if segment.transformed {
if segment.transform.is_some() {
let mut rect = segment.rect;
// The device extends the running right edge before recalculating
// the transformed rectangle, then applies the annotation margins.
rect[2] = x + margin;
*painted = link_rect(rect, segment.transform, margin);
*painted = link_rect(rect, segment.transform, page_height, margin);
} else {
painted[2] = x + margin;
}
@@ -339,17 +337,19 @@ impl Executor {
BoxPaint::PdfGraphics => events.push(((output_count, paint_count), x, y, LinkPaint::Graphics)),
_ => {}
});
let numbered = self.state.input_profile() == InputProfile::TeX8Bit;
PdfLinkShipout {
events: events.into_iter().peekable(),
output_count,
active: std::mem::take(&mut self.pdf_link_stack),
transform: (Affine::IDENTITY, false),
transform: if numbered { self.pdf_navigation_matrix } else { None },
saved: Vec::new(),
page_height: device.page_height,
graphics_index: 0,
output: PageLinks::default(),
origin: [device.horizontal_origin, device.vertical_origin + b.height],
margin: i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()),
numbered: self.state.input_profile() == InputProfile::TeX8Bit,
numbered,
}
}
}
@@ -382,12 +382,14 @@ impl PdfLinkShipout {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
self.saved.push(self.transform);
}
self.transform = (self.transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
let incoming = matrix.about(x as f64, (self.page_height - y) as f64, false);
self.transform = Some(self.transform.unwrap_or(Affine::IDENTITY).concatenate(incoming));
}
Some(PdfGraphics::Restore { shift: [dx, dy] }) => {
Some(PdfGraphics::Restore { .. }) => {
if let Some(previous) = self.saved.pop() {
self.transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)),
previous.1 || *dx != 0 || *dy != 0);
// The graphics restore shift compensates the drawing origin.
// Navigation still uses TeX's logical position.
self.transform = previous;
}
}
Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary) | None => {}
@@ -398,7 +400,8 @@ impl PdfLinkShipout {
link.level == row.level && link.layout.width.is_none()
}) {
let number = if self.numbered { Some(executor.register_pdf_link(None)?) } else { None };
link.start_segment(&mut self.output, absolute_row(row), [x, y], self.transform, self.margin);
link.start_segment(&mut self.output, absolute_row(row), [x, y], self.transform,
self.page_height, self.margin);
self.output.annotations.last_mut().unwrap().object_number = number;
}
}
@@ -430,7 +433,8 @@ impl PdfLinkShipout {
};
let mut start = ActiveLink { layout: layout.clone(), attributes,
action, level: container.level, segment: None };
start.start_segment(&mut self.output, container, [x, y], self.transform, self.margin);
start.start_segment(&mut self.output, container, [x, y], self.transform,
self.page_height, self.margin);
self.output.annotations.last_mut().unwrap().object_number = number;
self.active.push(start);
}
@@ -443,7 +447,7 @@ impl PdfLinkShipout {
"pdfTeX warning: pdftex: \\pdfendlink ended up in different nesting level than \\pdfstartlink\n")
.map_err(|error| executor.error(error, node.span))?;
}
link.end_segment(&mut self.output, x, self.margin);
link.end_segment(&mut self.output, x, self.page_height, self.margin);
}
LinkNode::Running(enabled) => executor.pdf_running_links = *enabled,
LinkNode::Destination { destination, view, structure } => {
@@ -457,20 +461,27 @@ impl PdfLinkShipout {
} else {
None
};
let transform = self.transform;
let point = self.transform.map_or([x, y], |matrix| {
let point = map_point(matrix, self.page_height, [x, y]);
if matches!(view, DestinationView::Xyz(_) | DestinationView::FitH
| DestinationView::FitBH | DestinationView::FitV | DestinationView::FitBV)
{
// Point views have no explicit width, height or depth.
let margin = i64::from(executor.read_parameter(Parameter::Pdfdestmargin).width());
point.map(|coordinate| coordinate - margin)
} else {
point
}
});
let view = view.map_rectangle(|[width, height, depth]| {
let margin = i64::from(executor.read_parameter(Parameter::Pdfdestmargin).width());
let top = height.map_or(container.baseline - container.height, |h| y - i64::from(h));
let right = width.map_or(container.left + container.width, |w| x + i64::from(w));
let bottom = depth.map_or(container.baseline + container.depth, |d| y + i64::from(d));
if transform.1 {
link_rect([x, top, right, bottom], transform.0, margin)
} else {
[x - margin, top - margin, right + margin, bottom + margin]
}
link_rect([x, top, right, bottom], self.transform, self.page_height, margin)
});
self.output.destinations.push(PageDestination {
object_number, destination, point: map_point(transform.0, x, y), view,
object_number, destination, point, view,
structure: *structure,
});
}
@@ -496,6 +507,9 @@ impl PdfLinkShipout {
link.segment = None;
}
executor.pdf_link_stack = self.active;
if self.numbered {
executor.pdf_navigation_matrix = self.transform;
}
Ok(self.output)
}
}
@@ -697,3 +697,56 @@ fn duplicate_destinations_are_discarded_after_the_first_definition() {
assert_eq!(pages[1].pdf_links.destinations.len(), 1);
assert!(export_native(&execution).diagnostics.is_empty());
}
#[test]
fn pdf_navigation_uses_the_logical_matrix_across_shipouts() {
let (reference, native, diagnostics) = pair(
r"\pdfdecimaldigits=4 \pdfpagewidth=200pt \pdfpageheight=200pt
\pdfdestmargin=1.25pt \pdflinkmargin=1.25pt
\shipout\hbox{\pdfsave\pdfsetmatrix{0 1 -1 0}
\kern6pt\pdfdest name{outer} fitr width6pt height9pt depth3pt
\pdfsave\pdfsetmatrix{2 .5 -.25 1}
\kern4pt\pdfdest name{inner} fitr width5pt height7pt depth1pt\kern-4pt
\pdfrestore\kern-6pt
\pdfrestore\kern4pt\pdfdest name{restored} fitr width6pt height9pt depth3pt
\vrule width10pt height6pt}
\shipout\hbox{\pdfsave\pdfsetmatrix{2 -.5 .25 1}
\kern5pt\pdfrestore
\pdfdest name{after-shift} fitr width6pt height9pt depth3pt
\pdfstartlink width6pt height9pt depth3pt goto name{inner}\kern6pt\pdfendlink
\vrule width10pt height6pt}
\shipout\hbox{\vrule width10pt height6pt\pdfsetmatrix{0 1 -1 0}}
\pdfpageheight=230pt
\shipout\hbox{\kern10pt\pdfdest name{next-page} fitr width6pt height9pt depth3pt
\pdfstartlink width6pt height9pt depth3pt goto name{inner}\kern6pt\pdfendlink
\vrule width10pt height6pt}",
);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let navigation = |doc: &Document| {
let pages = doc.get_pages();
let names = get(doc, doc.catalog().unwrap(), b"Names").as_dict().unwrap();
let dests = get(doc, names, b"Dests").as_dict().unwrap();
let targets = get(doc, dests, b"Names").as_array().unwrap();
let resolve = |object: &Object| doc.get_object(object.as_reference().unwrap()).unwrap();
let targets: Vec<_> = targets.chunks_exact(2).map(|target| {
let dictionary = resolve(&target[1]).as_dict().unwrap();
let view = get(doc, dictionary, b"D").as_array().unwrap();
let page = view[0].as_reference().unwrap();
let page_number = pages.iter().find(|(_, id)| **id == page).unwrap().0;
let view = view[1..].iter().map(comparable).collect::<Vec<_>>();
(target[0].as_str().unwrap().to_vec(), *page_number, view)
}).collect();
let rects: Vec<_> = pages.values().filter_map(|id| {
let page = doc.get_dictionary(*id).unwrap();
let annotations = page.get(b"Annots").ok()?.as_array().unwrap();
assert_eq!(annotations.len(), 1);
let link = resolve(&annotations[0]).as_dict().unwrap();
Some(comparable(get(doc, link, b"Rect")))
}).collect();
(targets, rects)
};
let expected = navigation(&reference);
assert_eq!(expected.0.len(), 5);
assert_eq!(expected.1.len(), 2);
assert_eq!(navigation(&native), expected);
}
+29
View File
@@ -18,6 +18,35 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-28 PDF 导航变换与跨页保留
pdfTeX 模式在 PDF 坐标系计算目标和链接的逻辑变换。矩阵在同一
作业内跨页保留,保存和恢复按当时的逻辑矩阵进行。错位恢复对绘图
原点的补偿继续由绘图路径处理。活动矩阵下按四角计算 FitR 及链接
边界,圆整逻辑坐标后应用边距。点目标 XYZ、FitH、FitBH、FitV、
FitBV 从实际出页位置换算,再应用活动变换下的 pdfdestmargin。
[pdfTeX 的矩阵与恢复实现](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/utils.c#L1276-L1538)
· [目标和链接的出页规则](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L36428-L36552)
同源对照的五种点目标、四页的六个 FitR 目标和两个固定宽度链接
矩形与参考一致。用例覆盖嵌套旋转与缩放、错位恢复以及前页没有
导航节点但改变矩阵、后页改变页高的场景。四页含注释外观的
144 DPI 灰度图逐像素一致。发布构建及 24 项定向回归通过。
三页编辑会话的首个页面只设置矩阵,第二页从子文件读取目标与绘制
规则。往返编辑第二页两轮各复用 1,159 步,仅更新第二页。恢复
检查点后,旋转矩形的实际宽高、PDF、页面、SVG、来源映射、辅助
文件和日志与独立全量一致。
原样 Springer Nature 三轮 LaTeX、实际 BibTeX 和 12 页对照保持。
旋转表格 table.3 的既有坐标差仍可复现。另一个实际最小用例在
自动宽度链接结束前恢复矩阵,原版与当前原生的注释矩形还有差异。
后续核对链接结束节点的当前矩阵及原版保留的最近一次逻辑矩形。
[出版模板对照](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-28-springer-nature-主线复验)
证据在 target/p3-pdf-navigation-matrix,receipt.json 的 SHA-256
为 525ca203ec9b83caddddffc09cc712c464dc0b4935330347cb8889acd989f73a。
## 2026-11-28 重复 PDF 目标与 Springer Nature
pdfTeX 模式在扫描及出页时按真实目标登记检查重复声明。已出页的
+8
View File
@@ -1026,6 +1026,14 @@ bbl 及全部版面对照保持。旋转目标的已知差距保留。
verification.json 的 SHA-256 为
87828d8f19c087c3755b341cc155ce616884b643f131a8b775d31fec5e373cee。
活动矩阵候选再次用同一批输入、格式、字体和 EPS 转换件运行三轮
LaTeX 与实际 BibTeX。原生 PDF 与上一轮逐字节相同。三轮 aux、bbl、
全部字形、词框、光栅和链接对照保持,table.3 的原坐标差继续保留。
该轮回执在 target/p3-pdf-named-pages/springer-navigation-candidate,
receipt.json 的 SHA-256 为
19a9b756028c422ac8bb7e24b8c8628e8173a49b3423de48f69667ecf000bb3b。
[逻辑矩阵和编辑复验](P2_M1_PROGRESS.md#2026-11-28-pdf-导航变换与跨页保留)
### Springer LNCS 的实际 PDF 导入复验
原样 Springer LNCS 会议样稿沿用冻结的格式、字体映射和官方