Resolve XDV named destinations at PDF shipout

This commit is contained in:
gloamxun committed 2026-11-25 19:47:17 +08:00
1 parent dd695a8945
commit cc147e93d8
12 files changed
+456 -9

No files matched your search

@@ -276,9 +276,13 @@ impl Executor {
InputProfile::TeX8Bit => PdfDriver::PdfTeX,
InputProfile::UnicodeScalar | InputProfile::XeTeX => PdfDriver::Xdv,
};
let mut file = self.state.pdf_file_options.clone().unwrap();
if driver == PdfDriver::Xdv {
self.state.xdv_setup.apply_version(&mut file);
}
Ok(Some(PdfPageData {
driver,
file: self.state.pdf_file_options.clone().unwrap(),
file,
stream_compression: level.max(0) as u8,
}))
}
@@ -354,6 +354,7 @@ impl Executor {
let device = &shipout.device;
let mut graphics_stack = Vec::new();
let mut xdv_graphics_stack = Vec::new();
let mut xdv_transform = crate::pdf_device::Affine::IDENTITY;
let (mut outputs, has_leaders) = b.output_nodes();
let leader_effects = if has_leaders {
let limit = self
@@ -437,8 +438,16 @@ impl Executor {
let special = self.resolve_special(
output, position.expect("special needs a shipout position"), files,
)?;
let point = xdv_transform.point(
(special.position[0] + horizontal_origin) as f64,
(special.position[1] + vertical_origin + b.height) as f64,
).map(|coordinate| coordinate.round() as i64);
let graphics = if let Some(pdf) = &device.pdf {
if pdf.driver == crate::pdf_device::PdfDriver::Xdv
&& self.xdv_destination_special(&special, point, &mut shipout.pdf_links)?
{
None
} else if pdf.driver == crate::pdf_device::PdfDriver::Xdv
&& let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse(
&special.bytes, device.magnification,
).map_err(|error| self.error(error, special.span))?
@@ -461,11 +470,26 @@ impl Executor {
};
use crate::pdf_device::PdfGraphics;
match &graphics {
Some(PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) => {
xdv_graphics_stack.push(special.span);
Some(PdfGraphics::Save) => {
xdv_graphics_stack.push((special.span, xdv_transform));
}
Some(PdfGraphics::Restore { .. }) if xdv_graphics_stack.pop().is_none() => {
return Err(self.error("unmatched XDV graphics restore", special.span));
Some(operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix))) => {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
xdv_graphics_stack.push((special.span, xdv_transform));
}
let [x, y] = special.position;
let pivot = matrix.about(
(x + horizontal_origin) as f64,
(y + vertical_origin + b.height) as f64,
true,
);
xdv_transform = xdv_transform.concatenate(pivot);
}
Some(PdfGraphics::Restore { .. }) => {
let Some((_, previous)) = xdv_graphics_stack.pop() else {
return Err(self.error("unmatched XDV graphics restore", special.span));
};
xdv_transform = previous;
}
_ => {}
}
@@ -541,7 +565,7 @@ impl Executor {
if output_positions.next().is_some() {
return self.fail("unexpected positioned native output node");
}
if let Some(&span) = xdv_graphics_stack.last() {
if let Some(&(span, _)) = xdv_graphics_stack.last() {
return Err(self.error("unclosed XDV graphics save at page shipout", span));
}
if let Some((_, span)) = graphics_stack.last() {
@@ -575,9 +599,16 @@ impl Executor {
self.write_pdf_object(number, files)?;
}
if has_link_material {
shipout.pdf_links = self.ship_pdf_link_material(
let mut links = self.ship_pdf_link_material(
b, device, &shipout.pdf_graphics_steps, files,
)?;
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
shipout.pdf_links = links;
}
if let Some(pdf) = &mut shipout.device.pdf
&& pdf.driver == crate::pdf_device::PdfDriver::Xdv
{
self.state.xdv_setup.apply_version(&mut pdf.file);
}
self.current = current;
self.native_page.as_mut().unwrap().dead_cycles = 0;
@@ -49,6 +49,42 @@ impl Executor {
})
}
pub(super) fn xdv_destination_special(
&mut self,
special: &ShipoutSpecial,
point: [i64; 2],
links: &mut crate::pdf_device::links::PageLinks,
) -> Result<bool, Error> {
use crate::pdf_device::xdv_destination::Destination;
let data = special.bytes.trim_ascii_start();
if let Some(body) = data.strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start) {
if let Some(operands) = xdv_operand(body, b"dest").or_else(|| xdv_operand(body, b"destination")) {
let destination = Destination::parse(operands, self.shipped_pages + 1, point)
.map_err(|error| self.error(error, special.span))?;
links.xdv_destinations.push(destination);
return Ok(true);
}
for (name, major) in [(b"majorversion".as_slice(), true), (b"minorversion", false)] {
if let Some(operands) = xdv_operand(body, name) {
if self.shipped_pages == 0 {
self.state.xdv_setup.set_version(major, operands)
.map_err(|error| self.error(error, special.span))?;
}
return Ok(true);
}
}
} else if let Some(body) = data.strip_prefix(b"dvipdfmx:").map(<[u8]>::trim_ascii_start)
&& let Some(operands) = xdv_operand(body, b"config")
{
if self.shipped_pages == 0 {
self.state.xdv_setup.configure(operands)
.map_err(|error| self.error(error, special.span))?;
}
return Ok(true);
}
Ok(false)
}
pub(super) fn render_special(
&mut self,
special: &ShipoutSpecial,
@@ -748,6 +748,8 @@ pub struct State {
pub(super) magnification_set: Option<i32>,
pub(super) output_mode_set: Option<i32>,
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "crate::pdf_device::xdv_destination::Setup::is_default")]
pub(super) xdv_setup: crate::pdf_device::xdv_destination::Setup,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -946,6 +948,7 @@ impl Default for State {
magnification_set: None,
output_mode_set: None,
pdf_file_options: None,
xdv_setup: Default::default(),
pdf_catalog: None,
pdf_objects: None,
initial_random_seed: None,
@@ -1583,6 +1586,7 @@ impl State {
self.magnification_set = None;
self.output_mode_set = None;
self.pdf_file_options = None;
self.xdv_setup = Default::default();
self.pdf_catalog = None;
if !self
.pdf_objects
@@ -1634,6 +1638,7 @@ impl State {
glyph_unicode: &self.glyph_unicode,
fonts: &self.fonts,
page_tree_attributes: &self.pdf_pages_attributes,
xdv_keep_destinations: self.xdv_setup.keep_destinations,
catalog: self.pdf_catalog.as_deref(),
objects: self.pdf_objects.as_deref(),
info: crate::pdf_device::PdfInfo {
+29 -1
View File
@@ -2755,7 +2755,35 @@ fn write_pdf(
catalog.push_str(&format!(" /Threads {} 0 R", objects.len()));
}
let destinations = navigation.named;
if !destinations.is_empty() {
let mut xdv_destinations = BTreeMap::new();
for list in pages {
for destination in &list.pdf_links.xdv_destinations {
use std::collections::btree_map::Entry;
match xdv_destinations.entry(destination.name.as_slice()) {
Entry::Vacant(entry) => {
entry.insert((destination, list.height, list.magnification));
}
Entry::Occupied(entry) => diagnostics.push(format!(
"xdvipdfmx: warning: Object @{} already defined.",
String::from_utf8_lossy(entry.key()),
)),
}
}
}
if unicode.is_some_and(|options| options.xdv_keep_destinations) && !xdv_destinations.is_empty() {
let mut entries = Vec::with_capacity(xdv_destinations.len());
for (name, (destination, height, magnification)) in xdv_destinations {
let page_object = navigation.pages.get(destination.page - 1)
.ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?;
let name = format!("<{}>", name.iter().map(|byte| format!("{byte:02X}")).collect::<String>());
entries.push((name, destination.array(*page_object, height, magnification)));
}
let first = &entries.first().unwrap().0;
let last = &entries.last().unwrap().0;
let names = entries.iter().map(|(name, value)| format!("{name} {value}")).collect::<Vec<_>>().join(" ");
objects.push(format!("<< /Names [{names}] /Limits [{first} {last}] >>").into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
} else if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
let last = pdf_text(destinations.last_key_value().unwrap().0);
+1
View File
@@ -97,6 +97,7 @@ pub fn print_sp(value: i64, digits: u8) -> String {
}
}
mod color;
pub(crate) mod xdv_destination;
pub(crate) mod xdv_document;
pub(crate) mod xdv_image;
mod graphics;
@@ -101,10 +101,12 @@ pub struct PageDestination {
pub struct PageLinks {
pub annotations: Vec<LinkAnnotation>,
pub destinations: Vec<PageDestination>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) xdv_destinations: Vec<super::xdv_destination::Destination>,
}
impl PageLinks {
pub(crate) fn is_empty(&self) -> bool {
self.annotations.is_empty() && self.destinations.is_empty()
self.annotations.is_empty() && self.destinations.is_empty() && self.xdv_destinations.is_empty()
}
}
@@ -0,0 +1,247 @@
//! The symbolic operands of a shipped XDV named destination.
use lopdf::Object;
use serde::{Deserialize, Serialize};
use super::page_resources::{parse_name, parse_value};
use super::{PdfFileOptions, magnify, print_sp};
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct Setup {
major: Option<i32>,
minor: Option<u8>,
pub(crate) keep_destinations: bool,
}
impl Setup {
pub(crate) fn is_default(&self) -> bool {
self == &Self::default()
}
pub(crate) fn set_version(&mut self, major: bool, input: &[u8]) -> Result<(), String> {
let input = input.trim_ascii_start();
let input = input.strip_prefix(b"=").unwrap_or(input).trim_ascii();
let value = std::str::from_utf8(input)
.ok()
.and_then(|value| value.parse::<i32>().ok())
.ok_or("invalid XDV PDF version special")?;
if major && value >= 1 {
self.major = Some(value);
} else if !major && (0..=9).contains(&value) {
self.minor = Some(value as u8);
} else {
return Err("invalid XDV PDF version special".into());
}
Ok(())
}
pub(crate) fn configure(&mut self, input: &[u8]) -> Result<(), String> {
let mut words = input
.split(|b| b.is_ascii_whitespace())
.filter(|word| !word.is_empty());
if words.next() != Some(b"C") {
return Err("unsupported XDV configuration option".into());
}
let value = words
.next()
.and_then(|word| std::str::from_utf8(word).ok())
.ok_or("invalid XDV configuration flags")?;
let (sign, digits) = if let Some(rest) = value.strip_prefix('-') {
(-1, rest)
} else {
(1, value.strip_prefix('+').unwrap_or(value))
};
let (radix, digits) = if let Some(rest) = digits
.strip_prefix("0x")
.or_else(|| digits.strip_prefix("0X"))
{
(16, rest)
} else if digits.starts_with('0') {
(8, digits)
} else {
(10, digits)
};
let flags =
u32::from_str_radix(digits, radix).map_err(|_| "invalid XDV configuration flags")?;
if words.next().is_some() || flags & !0x10 != 0 {
return Err("unsupported XDV configuration flags".into());
}
if (sign < 0 && flags != 0) || flags & 0x10 != 0 {
self.keep_destinations = flags & 0x10 != 0;
}
Ok(())
}
pub(crate) fn apply_version(&self, options: &mut PdfFileOptions) {
if let Some(value) = self.major {
options.major = value;
}
if let Some(value) = self.minor {
options.minor = value;
}
if options.major == 1 && options.minor < 5 {
options.object_compression = 0;
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Destination {
pub(crate) name: Vec<u8>,
pub(crate) page: usize,
view: String,
operands: Vec<Operand>,
point: [i64; 2],
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum Operand {
Number(String),
Null,
CurrentX,
CurrentY,
}
fn trim_pdf(mut bytes: &[u8]) -> &[u8] {
loop {
bytes = bytes.trim_ascii_start();
if !bytes.starts_with(b"%") {
return bytes;
}
bytes = bytes
.iter()
.position(|byte| matches!(byte, b'\r' | b'\n'))
.map_or(&[][..], |end| &bytes[end + 1..]);
}
}
fn split_string(bytes: &[u8]) -> Result<(&[u8], &[u8]), String> {
let end = match bytes.first() {
Some(b'<') => bytes.iter().position(|&byte| byte == b'>'),
Some(b'(') => {
let mut depth = 1;
let mut cursor = bytes.iter().enumerate().skip(1);
loop {
match cursor.next() {
Some((_, b'\\')) => {
cursor.next();
}
Some((_, b'(')) => depth += 1,
Some((index, b')')) => {
depth -= 1;
if depth == 0 {
break Some(index);
}
}
Some(_) => {}
None => break None,
}
}
}
_ => None,
}
.ok_or("pdf:dest requires a destination string")?;
Ok(bytes.split_at(end + 1))
}
fn atom(bytes: &[u8]) -> (&[u8], &[u8]) {
let bytes = trim_pdf(bytes);
let end = bytes
.iter()
.skip(1)
.position(|&b| {
b.is_ascii_whitespace()
|| matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'/' | b'%')
})
.map_or(bytes.len(), |index| index + 1);
bytes.split_at(end)
}
impl Destination {
pub(crate) fn parse(
input: &[u8],
current_page: usize,
point: [i64; 2],
) -> Result<Self, String> {
let (name, rest) = split_string(trim_pdf(input))?;
let Object::String(name, _) = parse_value(name)? else {
return Err("pdf:dest requires a destination string".into());
};
let array = trim_pdf(rest)
.strip_prefix(b"[")
.ok_or("pdf:dest requires an array")?;
let (page, rest) = atom(array);
let page = match page {
b"@thispage" => Some(current_page),
b"@prevpage" => current_page.checked_sub(1).filter(|number| *number != 0),
b"@nextpage" => current_page.checked_add(1),
_ => page
.strip_prefix(b"@page")
.and_then(|number| std::str::from_utf8(number).ok())
.and_then(|number| number.parse::<usize>().ok())
.filter(|number| *number != 0),
}
.ok_or("pdf:dest requires an XDV page reference")?;
let (view, mut rest) = atom(rest);
let view = parse_name(view)?;
let count = match view.as_slice() {
b"Fit" | b"FitB" => 0,
b"FitH" | b"FitV" | b"FitBH" | b"FitBV" => 1,
b"XYZ" => 3,
b"FitR" => 4,
_ => return Err("unsupported XDV destination view".into()),
};
let mut operands = Vec::with_capacity(count);
for _ in 0..count {
let (token, tail) = atom(rest);
let operand = match token {
b"@xpos" => Operand::CurrentX,
b"@ypos" => Operand::CurrentY,
b"null" => Operand::Null,
number => match parse_value(number)? {
Object::Integer(_) | Object::Real(_) => Operand::Number(
std::str::from_utf8(number)
.map_err(|_| "invalid XDV destination number")?
.into(),
),
_ => return Err("invalid XDV destination coordinate".into()),
},
};
operands.push(operand);
rest = tail;
}
let tail = trim_pdf(rest)
.strip_prefix(b"]")
.ok_or("invalid XDV destination array length")?;
if !trim_pdf(tail).is_empty() {
return Err("unexpected material after XDV destination array".into());
}
let view = String::from_utf8(view).expect("known destination view is ASCII");
Ok(Self {
name,
page,
view,
operands,
point,
})
}
pub(crate) fn array(&self, page_object: usize, height: i64, magnification: i32) -> String {
let mut output = format!("[{page_object} 0 R /{}", self.view);
for operand in &self.operands {
use std::fmt::Write as _;
match operand {
Operand::Number(text) => write!(output, " {text}").unwrap(),
Operand::Null => output.push_str(" null"),
Operand::CurrentX | Operand::CurrentY => {
let value = match operand {
Operand::CurrentX => self.point[0],
_ => height - self.point[1],
};
write!(output, " {}", print_sp(magnify(value, magnification), 2)).unwrap();
}
}
}
output.push(']');
output
}
}
@@ -133,6 +133,7 @@ pub struct PdfFinalOptions<'a> {
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
pub info: crate::pdf_device::PdfInfo<'a>,
pub(crate) xdv_keep_destinations: bool,
}
#[cfg(test)]
@@ -492,3 +492,59 @@ fn xdv_docinfo_merges_shipped_dictionaries_into_pdf_info() {
}
assert!(output.diagnostics.iter().any(|text| text.contains("Author")));
}
#[test]
fn xdv_destinations_use_shipped_page_ids_and_pdf_string_keys() {
use lopdf::Document;
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
let state = State::initex()
.with_etex()
.with_input_profile(InputProfile::XeTeX);
let result = Executor::new(state, Limits::default())
.with_native_pages()
.run(
source(
r"\catcode123=1 \catcode125=2
\setbox0=\hbox{\special{pdf:dest (discarded) [@thispage /Fit]}}
\shipout\hbox{\special{dvipdfmx:config C 0x0010}
\special{pdf:minorversion=7}
\special{pdf:dest (A) [@nextpage/Fit]}
\special{pdf:dest <4100> [@thispage/FitB]}
\special{pdf:dest (AB) [@thispage /XYZ null 17.125 1.5]}
\vrule width5pt height3pt depth0pt}
\shipout\hbox{\special{pdf:minorversion 4}
\special{pdf:destination (A) [@prevpage /Fit]}
\vrule width5pt height3pt depth0pt}
\end",
),
&mut TestDevice,
)
.unwrap();
let pages: Vec<_> = result
.events
.iter()
.filter_map(|event| match event {
Event::Shipout(page) => Some(page.display_list().unwrap()),
_ => None,
})
.collect();
let output =
shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
let pdf = Document::load_mem(&output.bytes).unwrap();
assert_eq!(pdf.version, "1.7");
let names = pdf.catalog().unwrap().get(b"Names").unwrap().as_dict().unwrap();
let id = names.get(b"Dests").unwrap().as_reference().unwrap();
let destinations = pdf.get_object(id).unwrap().as_dict().unwrap()
.get(b"Names").unwrap().as_array().unwrap();
let keys: Vec<_> = destinations.iter().step_by(2).map(|item| item.as_str().unwrap()).collect();
assert_eq!(keys, [b"A".as_slice(), b"A\0", b"AB"]);
let page_ids = pdf.get_pages();
assert_eq!(destinations[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]);
assert_eq!(destinations[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]);
let xyz = destinations[5].as_array().unwrap();
assert!(xyz[2].is_null());
assert_eq!(xyz[3].as_f64().unwrap(), 17.125);
assert_eq!(xyz[4].as_f64().unwrap(), 1.5);
assert!(output.diagnostics.iter().any(|text| text.contains("Object @A already defined")));
}
+30
View File
@@ -2175,6 +2175,36 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XDV 命名目标与 PDF 发页坐标
`pdf:dest` 和 `pdf:destination` 随实际发页记录。导出用真实页对象
解析当前页、前一页、后一页或指定页引用。位置取自发出点,应用当时的
图形旋转和缩放。PDF 名称树按原始字符串字节排序,重名保留首次定义。
首页的 `pdf:majorversion`、`pdf:minorversion` 和
`dvipdfmx:config C 0x0010` 接入文档设备。其中 C 的该位保留未引用
目标,通常由 hyperref 设置。默认只移除当前用例中的未引用目标。随
注释与书签接入的目标引用跟踪、其他配置位及参考驱动的默认 PDF 版本
仍待对照。
[上游目标解析](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/spc_pdfm.c)
[上游页引用和设备坐标](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/specials.c#L173-L223)
四份双页同源用例直接读取 PDF,核对原始目标键、目标页对象、坐标和
视图参数。包括含零字节的字符串、重名、提前引用未来页、旋转及缩放。
显式 PDF 1.7 的用例也验证首页之后出现的版本设置不会改写文档版本。
八页 144 DPI 灰度图逐像素一致,9 项 XeTeX profile 测试通过。
三页原子项目两次连续编辑分别复用 151 步、重放 2 次宿主调用。
首次移动并重命名第二页的目标,PDF 更新而预览页不重绘。第二次改变
第二页规则宽度,只更新第二页。两次的 PDF、SVG 和来源映射都与
同版本独立全量编译一致。
使用原 schema71 格式与原样 ACL 的十份冻结文件继续复编。首次发页
越过命名目标,首次停止于 `graphics-def/xetex.def:79:2` 发出的
`color push`。原生 ACL 仍未生成 PDF。下一阶段接通 XDV 颜色
栈与发页续接,再按原样项目的首处差异继续。
回执 `target/p3-xdv-dest/receipt.json`,SHA-256 为
`45c937ba622c23881d2e2017ece2fda79dbe0796fb659eadcb78fe936207f1c3`。
### XDV 发页时合并 PDF 文档信息
`pdf:docinfo` 使用现有 PDF 对象解析与导出,按实际发页顺序合并
+6
View File
@@ -729,6 +729,12 @@ XDV 文档信息字典接入后,复用原样 schema71 格式与同一份 ACL
原生仍未生成 PDF。回执 `target/p3-xdv-docinfo/receipt.json`。
[XDV 文档信息阶段记录](P2_M1_PROGRESS.md#xdv-发页时合并-pdf-文档信息)
XDV 命名目标接入后,用同一原样 schema71 与项目文件复编原样 ACL。
已越过 `pdf:dest`,首次发页停在 `graphics-def/xetex.def:79:2`
的 `color push`。十份冻结源的摘要继续一致,仍未生成原生 PDF。
回执 `target/p3-xdv-dest/receipt.json` 记录实际版本、源文件与失败。
[命名目标阶段记录](P2_M1_PROGRESS.md#xdv-命名目标与-pdf-发页坐标)
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。