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)]