diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 73dd69d..d7a9699 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -461,7 +461,17 @@ impl Executor { shipout.xdv_color_steps.insert(graphics_step, program); } None - } else if xdv && self.xdv_destination_special(&special, point, &mut shipout.pdf_links)? { + } else if xdv && self.xdv_page_special( + &special, + crate::pdf_device::xdv_object::Position { + page: self.shipped_pages + 1, + coordinates: point, + height: device.page_height, + magnification: device.magnification, + }, + &mut shipout.pdf_links, + files, + )? { None } else if xdv && let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse( &special.bytes, device.magnification, diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index f113a46..1c458cb 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -49,17 +49,18 @@ impl Executor { }) } - pub(super) fn xdv_destination_special( + pub(super) fn xdv_page_special( &mut self, special: &ShipoutSpecial, - point: [i64; 2], + position: crate::pdf_device::xdv_object::Position, links: &mut crate::pdf_device::links::PageLinks, + files: &mut impl SourceProvider, ) -> Result { 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) + let destination = Destination::parse(operands, position.page, position.coordinates) .map_err(|error| self.error(error, special.span))?; links.xdv_destinations.push(destination); return Ok(true); @@ -73,6 +74,22 @@ impl Executor { return Ok(true); } } + let catalog = xdv_operand(body, b"docview"); + let outline = xdv_operand(body, b"outline").or_else(|| xdv_operand(body, b"out")); + if let Some(operands) = catalog.or(outline) { + self.reads.insert(Dependency::PdfCatalogState); + let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); + let warnings = if catalog.is_some() { + navigation.merge_catalog(operands, position, self.limits.tokens) + } else { + navigation.add_outline(operands, position, self.limits.tokens) + }.map_err(|error| self.error(error, special.span))?; + for warning in warnings { + files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning) + .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") { diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index bd0cbfb..868e445 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -751,6 +751,8 @@ pub struct State { #[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) xdv_navigation: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_catalog: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_objects: Option>, @@ -949,6 +951,7 @@ impl Default for State { output_mode_set: None, pdf_file_options: None, xdv_setup: Default::default(), + xdv_navigation: None, pdf_catalog: None, pdf_objects: None, initial_random_seed: None, @@ -1587,6 +1590,7 @@ impl State { self.output_mode_set = None; self.pdf_file_options = None; self.xdv_setup = Default::default(); + self.xdv_navigation = None; self.pdf_catalog = None; if !self .pdf_objects @@ -1639,6 +1643,8 @@ impl State { fonts: &self.fonts, page_tree_attributes: &self.pdf_pages_attributes, xdv_keep_destinations: self.xdv_setup.keep_destinations, + xdv_outline_open_depth: self.xdv_setup.outline_open_depth.unwrap_or_default(), + xdv_navigation: self.xdv_navigation.as_deref(), catalog: self.pdf_catalog.as_deref(), objects: self.pdf_objects.as_deref(), info: crate::pdf_device::PdfInfo { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 7df2dcc..4fd5bc0 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2752,6 +2752,19 @@ fn write_pdf( let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects); catalog.push_str(&format!(" /Outlines {outlines} 0 R")); } + let xdv = unicode.and_then(|options| options.xdv_navigation); + let keep_xdv_destinations = unicode.is_some_and(|options| options.xdv_keep_destinations); + let mut xdv_names = BTreeMap::new(); + if let Some(xdv) = xdv { + let open_depth = unicode.unwrap().xdv_outline_open_depth; + let (outlines, names) = xdv.write_outlines( + &navigation.pages, &mut objects, keep_xdv_destinations, open_depth, + )?; + if let Some(outlines) = outlines { + catalog.push_str(&format!(" /Outlines {outlines} 0 R")); + } + xdv_names = names; + } if !navigation.threads.is_empty() { let mut ids: Vec<_> = navigation.threads.into_values().collect(); ids.sort_unstable_by(|left, right| right.cmp(left)); @@ -2775,14 +2788,30 @@ fn write_pdf( } } } - 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::()); - entries.push((name, destination.array(*page_object, height, magnification))); + for name in xdv_names.keys() { + if !xdv_destinations.contains_key(name.as_slice()) { + diagnostics.push(format!("xdvipdfmx: warning: PDF destination {:?} not defined.", + String::from_utf8_lossy(name))); } + } + let mut retained = BTreeMap::new(); + for (name, (destination, height, magnification)) in xdv_destinations { + let name = if keep_xdv_destinations { + name + } else if let Some(reference) = xdv_names.get(name) { + reference + } else { + continue; + }; + let page_object = navigation.pages.get(destination.page - 1) + .ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?; + retained.insert(name, destination.array(*page_object, height, magnification)); + } + if !retained.is_empty() { + let entries: Vec<_> = retained.into_iter().map(|(name, value)| { + let name = format!("<{}>", name.iter().map(|byte| format!("{byte:02X}")).collect::()); + (name, value) + }).collect(); let first = &entries.first().unwrap().0; let last = &entries.last().unwrap().0; let names = entries.iter().map(|(name, value)| format!("{name} {value}")).collect::>().join(" "); @@ -2800,21 +2829,25 @@ fn write_pdf( entries.join(" ")).into_bytes()); catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len())); } - let mut catalog = catalog.into_bytes(); - if let Some(extra) = extra { - let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref()) - .unwrap_or(&extra.entries); - if !entries.is_empty() { - catalog.push(b'\n'); - catalog.extend_from_slice(entries); - catalog.push(b'\n'); + objects[0] = if let Some(xdv) = xdv { + xdv.finish_catalog(&catalog, &navigation.pages)? + } else { + let mut catalog = catalog.into_bytes(); + if let Some(extra) = extra { + let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref()) + .unwrap_or(&extra.entries); + if !entries.is_empty() { + catalog.push(b'\n'); + catalog.extend_from_slice(entries); + catalog.push(b'\n'); + } + if let Some(id) = action { + write!(&mut catalog, " /OpenAction {id} 0 R").unwrap(); + } } - if let Some(id) = action { - write!(&mut catalog, " /OpenAction {id} 0 R").unwrap(); - } - } - catalog.extend_from_slice(b" >>"); - objects[0] = catalog; + catalog.extend_from_slice(b" >>"); + catalog + }; if let Some(level) = final_compression { let device = pages[0].pdf.as_ref().expect("validated native PDF options"); diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index ac207ef..e2048fb 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -101,6 +101,8 @@ pub(crate) mod xdv_color; pub(crate) mod xdv_destination; pub(crate) mod xdv_document; pub(crate) mod xdv_image; +pub(crate) mod xdv_navigation; +pub(crate) mod xdv_object; mod graphics; pub(crate) use color::{ColorResult, PdfColorStacks}; pub use color::{PdfColorProgram, PdfColorStackAction}; diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs b/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs index 249066c..2b279ed 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs @@ -4,12 +4,15 @@ use serde::{Deserialize, Serialize}; use super::page_resources::{parse_name, parse_value}; use super::{PdfFileOptions, magnify, print_sp}; +use super::xdv_object::{atom, page_reference, split_string, trim_pdf}; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(crate) struct Setup { major: Option, minor: Option, pub(crate) keep_destinations: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) outline_open_depth: Option, } impl Setup { @@ -38,13 +41,22 @@ impl Setup { 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 option = words.next().ok_or("missing XDV configuration option")?; let value = words .next() .and_then(|word| std::str::from_utf8(word).ok()) - .ok_or("invalid XDV configuration flags")?; + .ok_or("invalid XDV configuration value")?; + if words.next().is_some() { + return Err("unexpected material after XDV configuration value".into()); + } + if option == b"O" { + let depth = value.parse::().map_err(|_| "invalid XDV outline open depth")?; + self.outline_open_depth = Some(if depth < 0 { 256 } else { depth as usize }); + return Ok(()); + } + if option != b"C" { + return Err("unsupported XDV configuration option".into()); + } let (sign, digits) = if let Some(rest) = value.strip_prefix('-') { (-1, rest) } else { @@ -62,7 +74,7 @@ impl Setup { }; let flags = u32::from_str_radix(digits, radix).map_err(|_| "invalid XDV configuration flags")?; - if words.next().is_some() || flags & !0x10 != 0 { + if flags & !0x10 != 0 { return Err("unsupported XDV configuration flags".into()); } if (sign < 0 && flags != 0) || flags & 0x10 != 0 { @@ -101,61 +113,6 @@ enum Operand { 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], @@ -170,17 +127,8 @@ impl Destination { .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::().ok()) - .filter(|number| *number != 0), - } - .ok_or("pdf:dest requires an XDV page reference")?; + let page = page_reference(page, current_page) + .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() { diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs index 46b638f..9b1d2b0 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs @@ -57,22 +57,9 @@ pub(crate) fn merge_docinfo( fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec) -> Result<(), String> { match value { - Object::String(bytes, format) - if TEXT_KEYS.contains(&key) - && !bytes.starts_with(&[0xfe, 0xff]) - && !bytes.is_ascii() => - { - if let Ok(text) = std::str::from_utf8(bytes) { - *bytes = [0xfe, 0xff] - .into_iter() - .chain(text.encode_utf16().flat_map(u16::to_be_bytes)) - .collect(); + Object::String(bytes, format) => { + if normalize_text(key, bytes, warnings) { *format = StringFormat::Hexadecimal; - } else { - warnings.push(format!( - "xdvipdfmx: warning: Input string conversion (to UTF16BE) failed for {}...\n", - String::from_utf8_lossy(key), - )); } } Object::Array(values) => { @@ -93,6 +80,25 @@ fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec) -> R Ok(()) } +pub(super) fn normalize_text(key: &[u8], bytes: &mut Vec, warnings: &mut Vec) -> bool { + if !TEXT_KEYS.contains(&key) || bytes.starts_with(&[0xfe, 0xff]) || bytes.is_ascii() { + return false; + } + if let Ok(text) = std::str::from_utf8(bytes) { + *bytes = [0xfe, 0xff] + .into_iter() + .chain(text.encode_utf16().flat_map(u16::to_be_bytes)) + .collect(); + true + } else { + warnings.push(format!( + "xdvipdfmx: warning: Input string conversion (to UTF16BE) failed for {}...\n", + String::from_utf8_lossy(key), + )); + false + } +} + pub(crate) fn information_dictionary( info: PdfInfo<'_>, diagnostics: &mut Vec, diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs new file mode 100644 index 0000000..553a082 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -0,0 +1,237 @@ +//! Document-view state and outlines produced by XDV specials. +use std::collections::BTreeMap; + +use lopdf::Object; +use serde::{Deserialize, Serialize}; + +use super::page_resources::{encode_value, parse_value}; +use super::xdv_object::{ + Dictionary, Position, Value, atom, dictionary, output_dictionary, trim_pdf, +}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(crate) struct Navigation { + catalog: Dictionary, + outlines: Vec, + lowest_level: Option, + payload: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct Outline { + depth: usize, + force_open: bool, + fields: Dictionary, +} + +impl Navigation { + pub(crate) fn merge_catalog( + &mut self, + bytes: &[u8], + position: Position, + limit: usize, + ) -> Result, String> { + let (mut additions, warnings) = read_fields(bytes, position)?; + if let (Some(Value::Dictionary(old)), Some(Value::Dictionary(new))) = ( + self.catalog.get_mut(b"ViewerPreferences".as_slice()), + additions.get_mut(b"ViewerPreferences".as_slice()), + ) { + old.append(new); + additions.remove(b"ViewerPreferences".as_slice()); + } + self.catalog.append(&mut additions); + self.add_payload(bytes.len(), limit)?; + Ok(warnings) + } + + pub(crate) fn add_outline( + &mut self, + bytes: &[u8], + position: Position, + limit: usize, + ) -> Result, String> { + let (force_open, rest) = match trim_pdf(bytes) { + rest if rest.starts_with(b"[]") => (true, &rest[2..]), + rest if rest.starts_with(b"[-]") => (false, &rest[3..]), + rest => (false, rest), + }; + let (level, rest) = atom(rest); + let level = match parse_value(level)? { + Object::Integer(level) => { + i32::try_from(level).map_err(|_| "XDV outline level out of range")? + } + _ => return Err("invalid XDV outline level".into()), + }; + let lowest = self.lowest_level.map_or(level, |old| old.min(level)); + let depth = i64::from(level) - i64::from(lowest) + 1; + let previous_depth = self.outlines.last().map_or(0, |outline| outline.depth); + if depth > 256 || depth as usize > previous_depth + 1 { + return Err("XDV outline jumps more than one level or exceeds depth limit".into()); + } + let (fields, warnings) = read_fields(rest, position)?; + self.add_payload(bytes.len(), limit)?; + self.lowest_level = Some(lowest); + self.outlines.push(Outline { + depth: depth as usize, + force_open, + fields, + }); + Ok(warnings) + } + + fn add_payload(&mut self, bytes: usize, limit: usize) -> Result<(), String> { + self.payload = self.payload.saturating_add(bytes); + if self.payload > limit { + return Err("native XDV navigation payload limit exceeded".into()); + } + Ok(()) + } + + pub(crate) fn finish_catalog(&self, base: &str, pages: &[usize]) -> Result, String> { + let Object::Dictionary(mut catalog) = parse_value(format!("{base} >>").as_bytes())? else { + unreachable!("native PDF catalog is a dictionary"); + }; + let additions = output_dictionary(&self.catalog, pages)?; + for (key, value) in &additions { + match key.as_slice() { + b"Type" | b"Pages" => {} + b"Outlines" | b"Threads" if catalog.has(key) => {} + b"Names" if catalog.has(key) => { + if let (Ok(Object::Dictionary(generated)), Object::Dictionary(extra)) = + (catalog.get_mut(key), value) + { + for (name, value) in extra { + generated.set(name.clone(), value.clone()); + } + } + } + _ => catalog.set(key.clone(), value.clone()), + } + } + encode_value(Object::Dictionary(catalog)) + } + + pub(crate) fn write_outlines( + &self, + pages: &[usize], + objects: &mut Vec>, + keep_destinations: bool, + open_depth: usize, + ) -> Result<(Option, BTreeMap, Vec>), String> { + let mut names = BTreeMap::new(); + if self.outlines.is_empty() { + return Ok((None, names)); + } + let root = objects.len() + 1; + let mut entries: Vec<_> = (0..=self.outlines.len()) + .map(|_| OutlineLinks::default()) + .collect(); + let mut parents = vec![0]; + for (offset, outline) in self.outlines.iter().enumerate() { + let index = offset + 1; + parents.truncate(outline.depth); + let parent = *parents.last().expect("validated outline depth"); + entries[index].parent = parent; + if let Some(previous) = entries[parent].last { + entries[previous].next = Some(index); + entries[index].previous = Some(previous); + } else { + entries[parent].first = Some(index); + } + entries[parent].last = Some(index); + parents.push(index); + } + for (offset, outline) in self.outlines.iter().enumerate().rev() { + let index = offset + 1; + let entry = &entries[index]; + let visible = if outline.force_open || outline.depth <= open_depth { + entry.count + } else { + 0 + }; + let parent = entry.parent; + entries[parent].count += visible + 1; + } + let object = |index: usize| Object::Reference(((root + index) as u32, 0)); + let links = |fields: &mut lopdf::Dictionary, entry: &OutlineLinks| { + for (name, target) in [ + ("Prev", entry.previous), + ("Next", entry.next), + ("First", entry.first), + ("Last", entry.last), + ] { + if let Some(target) = target { + fields.set(name, object(target)); + } + } + }; + let mut fields = lopdf::Dictionary::new(); + links(&mut fields, &entries[0]); + fields.set("Count", entries[0].count); + objects.push(encode_value(Object::Dictionary(fields))?); + for (offset, outline) in self.outlines.iter().enumerate() { + let entry = &entries[offset + 1]; + let mut fields = output_dictionary(&outline.fields, pages)?; + if !keep_destinations { + remap_outline_destination(&mut fields, &mut names); + } + fields.set("Parent", object(entry.parent)); + for field in [b"Prev".as_slice(), b"Next", b"First", b"Last", b"Count"] { + fields.remove(field); + } + links(&mut fields, entry); + if entry.count != 0 { + let sign = if outline.force_open || outline.depth <= open_depth { + 1 + } else { + -1 + }; + fields.set("Count", sign * entry.count); + } + objects.push(encode_value(Object::Dictionary(fields))?); + } + Ok((Some(root), names)) + } +} + +#[derive(Default)] +struct OutlineLinks { + parent: usize, + previous: Option, + next: Option, + first: Option, + last: Option, + count: i64, +} + +fn read_fields(bytes: &[u8], position: Position) -> Result<(Dictionary, Vec), String> { + let mut fields = dictionary(bytes, position)?; + let mut warnings = Vec::new(); + for (key, value) in &mut fields { + value.normalize_text(key, &mut warnings); + } + Ok((fields, warnings)) +} + +fn remap_outline_destination( + fields: &mut lopdf::Dictionary, + names: &mut BTreeMap, Vec>, +) { + let named = if fields.has(b"Dest") && !fields.has(b"A") { + fields.get_mut(b"Dest").ok() + } else if !fields.has(b"Dest") + && let Ok(Object::Dictionary(action)) = fields.get_mut(b"A") + && action.get(b"S").ok().and_then(|kind| kind.as_name().ok()) == Some(b"GoTo".as_slice()) + { + action.get_mut(b"D").ok() + } else { + None + }; + if let Some(Object::String(name, _)) = named { + let index = names.len(); + *name = names + .entry(name.clone()) + .or_insert_with(|| format!("{index:x}").into_bytes()) + .clone(); + } +} diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs new file mode 100644 index 0000000..c96512c --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs @@ -0,0 +1,270 @@ +//! PDF objects in XDV specials, including typed references to shipped pages. +use lopdf::{Object, StringFormat}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +use super::page_resources::{parse_name, parse_value}; +use super::{magnify, print_sp}; + +pub(super) 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..]); + } +} + +pub(super) 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("unterminated or missing PDF string")?; + Ok(bytes.split_at(end + 1)) +} + +pub(super) 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) +} + +pub(super) fn page_reference(page: &[u8], current_page: usize) -> Option { + 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::().ok()) + .filter(|number| *number != 0), + } +} + +pub(super) type Dictionary = BTreeMap, Value>; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(super) enum Value { + Null, + Boolean(bool), + Integer(i64), + Real(u64), + Name(Vec), + String(Vec), + Array(Vec), + Dictionary(Dictionary), + Page(usize), + Catalog, + PageTree, +} + +#[derive(Clone, Copy)] +pub(crate) struct Position { + pub(crate) page: usize, + pub(crate) coordinates: [i64; 2], + pub(crate) height: i64, + pub(crate) magnification: i32, +} + +impl Position { + fn reference(self, token: &[u8]) -> Result { + let y = self.height - self.coordinates[1]; + match token { + b"@xpos" | b"@ypos" => { + let coordinate = if token == b"@xpos" { + self.coordinates[0] + } else { + y + }; + let physical = print_sp(magnify(coordinate, self.magnification), 2); + Ok(Value::Real( + physical + .parse::() + .expect("device coordinate") + .to_bits(), + )) + } + b"@catalog" => Ok(Value::Catalog), + b"@pages" => Ok(Value::PageTree), + _ => page_reference(token, self.page) + .map(Value::Page) + .ok_or_else(|| { + format!( + "unsupported XDV PDF object reference {}", + String::from_utf8_lossy(token) + ) + }), + } + } +} + +pub(super) fn dictionary(input: &[u8], position: Position) -> Result { + let mut parser = Parser { + rest: input, + position, + }; + let Value::Dictionary(dictionary) = parser.value(0)? else { + return Err("expected an XDV PDF dictionary".into()); + }; + if !trim_pdf(parser.rest).is_empty() { + return Err("unexpected material after XDV PDF dictionary".into()); + } + Ok(dictionary) +} + +struct Parser<'a> { + rest: &'a [u8], + position: Position, +} + +impl Parser<'_> { + fn take(&mut self, token: &[u8]) -> bool { + self.rest = trim_pdf(self.rest); + if let Some(rest) = self.rest.strip_prefix(token) { + self.rest = rest; + true + } else { + false + } + } + + fn value(&mut self, depth: usize) -> Result { + if depth >= 64 { + return Err("native PDF object nesting limit exceeded".into()); + } + if self.take(b"<<") { + let mut dictionary = Dictionary::new(); + while !self.take(b">>") { + let (key, rest) = atom(self.rest); + let key = parse_name(key)?; + self.rest = rest; + let value = self.value(depth + 1)?; + dictionary.insert(key, value); + } + return Ok(Value::Dictionary(dictionary)); + } + if self.take(b"[") { + let mut array = Vec::new(); + while !self.take(b"]") { + array.push(self.value(depth + 1)?); + } + return Ok(Value::Array(array)); + } + + let (token, rest) = match self.rest.first() { + Some(b'(' | b'<') => split_string(self.rest)?, + Some(_) => atom(self.rest), + None => return Err("unexpected end of XDV PDF object".into()), + }; + self.rest = rest; + if token.starts_with(b"@") { + return self.position.reference(token); + } + match parse_value(token)? { + Object::Null => Ok(Value::Null), + Object::Boolean(value) => Ok(Value::Boolean(value)), + Object::Integer(value) => Ok(Value::Integer(value)), + Object::Real(value) if value.is_finite() => Ok(Value::Real(value.to_bits())), + Object::Name(value) => Ok(Value::Name(value)), + Object::String(value, _) => Ok(Value::String(value)), + _ => Err("unsupported XDV PDF object".into()), + } + } +} + +pub(super) fn output_dictionary( + dictionary: &Dictionary, + pages: &[usize], +) -> Result { + dictionary + .iter() + .map(|(key, value)| Ok((key.clone(), value.output(pages)?))) + .collect() +} + +impl Value { + fn output(&self, pages: &[usize]) -> Result { + Ok(match self { + Self::Null => Object::Null, + Self::Boolean(value) => Object::Boolean(*value), + Self::Integer(value) => Object::Integer(*value), + Self::Real(value) => Object::Real(f64::from_bits(*value)), + Self::Name(value) => Object::Name(value.clone()), + Self::String(value) => Object::String(value.clone(), StringFormat::Hexadecimal), + Self::Array(values) => Object::Array( + values + .iter() + .map(|value| value.output(pages)) + .collect::>()?, + ), + Self::Dictionary(dictionary) => { + Object::Dictionary(output_dictionary(dictionary, pages)?) + } + Self::Page(page) => { + let id = pages + .get(page - 1) + .ok_or_else(|| format!("XDV PDF object refers to nonexistent page {page}"))?; + Object::Reference(( + u32::try_from(*id).map_err(|_| "PDF object ID out of range")?, + 0, + )) + } + Self::Catalog => Object::Reference((1, 0)), + Self::PageTree => Object::Reference((2, 0)), + }) + } +} + +impl Value { + pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec) { + match self { + Self::String(bytes) => { + super::xdv_document::normalize_text(key, bytes, warnings); + } + Self::Array(values) => { + for value in values { + value.normalize_text(key, warnings); + } + } + Self::Dictionary(values) => { + for (key, value) in values { + value.normalize_text(key, warnings); + } + } + _ => {} + } + } +} diff --git a/crates/texrra-tex-core/src/pdf_unicode.rs b/crates/texrra-tex-core/src/pdf_unicode.rs index 449ccad..180eee8 100644 --- a/crates/texrra-tex-core/src/pdf_unicode.rs +++ b/crates/texrra-tex-core/src/pdf_unicode.rs @@ -134,6 +134,8 @@ pub struct PdfFinalOptions<'a> { pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>, pub info: crate::pdf_device::PdfInfo<'a>, pub(crate) xdv_keep_destinations: bool, + pub(crate) xdv_outline_open_depth: usize, + pub(crate) xdv_navigation: Option<&'a crate::pdf_device::xdv_navigation::Navigation>, } #[cfg(test)] diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 7d01863..8fc3081 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -596,3 +596,67 @@ fn xdv_color_is_shipped_in_order_and_replayed_on_the_next_page() { without_background.pdf_background = None; assert!(!pages[1].same_svg_paint(&without_background)); } + +#[test] +fn xdv_catalog_and_outlines_resolve_live_pages_and_retain_referenced_names() { + 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:docview<>}} + \shipout\hbox{\special{pdf:docview<>>>} + \special{pdf:outline [-] 1</A<>>>} + \special{pdf:dest (unused) [@thispage/Fit]} + \vrule width7pt height8pt} + \shipout\hbox{\special{pdf:docview<>>>} + \special{pdf:out [] 2<>} + \special{pdf:dest (topic) [@thispage/Fit]} + \special{pdf:outline 1<>} + \vrule width9pt height8pt} + \end", + ), + &mut TestDevice, + ) + .unwrap(); + assert!(result.reads.contains(&Dependency::PdfCatalogState)); + let pages = result.shipout_display_lists().unwrap(); + let output = + shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let catalog = pdf.catalog().unwrap(); + let page_ids = pdf.get_pages(); + let open = catalog.get(b"OpenAction").unwrap().as_array().unwrap(); + assert_eq!(open[0].as_reference().unwrap(), page_ids[&2]); + assert_eq!(open[1].as_name().unwrap(), b"Fit"); + assert!(!catalog.has(b"Discard")); + let preferences = catalog.get(b"ViewerPreferences").unwrap().as_dict().unwrap(); + assert!(matches!(preferences.get(b"HideToolbar"), Ok(lopdf::Object::Boolean(true)))); + assert!(matches!(preferences.get(b"DisplayDocTitle"), Ok(lopdf::Object::Boolean(true)))); + let dictionary = |parent: &lopdf::Dictionary, key: &[u8]| { + let id = parent.get(key).unwrap().as_reference().unwrap(); + pdf.get_object(id).unwrap().as_dict().unwrap() + }; + let outlines = dictionary(catalog, b"Outlines"); + assert_eq!(outlines.get(b"Count").unwrap().as_i64().unwrap(), 2); + let first = dictionary(outlines, b"First"); + assert_eq!(first.get(b"Title").unwrap().as_str().unwrap(), [254, 255, 0, 65, 3, 169]); + assert_eq!(first.get(b"Count").unwrap().as_i64().unwrap(), -1); + let remapped = first.get(b"A").unwrap().as_dict().unwrap().get(b"D").unwrap(); + let child = dictionary(first, b"First"); + let previous = child.get(b"Dest").unwrap().as_array().unwrap(); + assert_eq!(previous[0].as_reference().unwrap(), page_ids[&1]); + let sibling = dictionary(first, b"Next"); + assert_eq!(sibling.get(b"Title").unwrap().as_str().unwrap(), b"Sibling"); + let names = catalog.get(b"Names").unwrap().as_dict().unwrap(); + let names = dictionary(names, b"Dests").get(b"Names").unwrap().as_array().unwrap(); + assert_eq!(names.len(), 2); + assert_eq!(names[0].as_str().unwrap(), b"0"); + assert_eq!(remapped.as_str().unwrap(), names[0].as_str().unwrap()); + assert_eq!(names[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 5999475..6e86e90 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,35 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XDV 文档目录、打开动作和书签 + +`pdf:docview` 按真实发页更新目录。同名字段由后一次发页覆盖, +`ViewerPreferences` 保留未覆盖的子字段。打开动作支持直接目标 +数组和 PDF 动作字典。XDV PDF 对象解析区分字面字符串、十六进制 +字符串与设备引用,目标页在实际出页完成后绑定页对象,设备坐标 +来自发出位置,包含图形变换。`pdf:outline` 与 `pdf:out` +输出书签层级、同级链接和展开计数,支持首发页配置的默认展开深度。 +默认按书签引用保留并重编号命名目标。`C 0x0010` 保留原目标名。 +注释引用、自定义 XDV 对象引用及跳级书签的参考占位行为仍待接入。 +[TeX Live 的目录、书签和引用](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/spc_pdfm.c) +[TeX Live 的书签链接与目标名](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdoc.c) + +三份同源用例的目录、书签、链接关系及命名目标与 xdvipdfmx +20260113 一致,九页 144 DPI 彩色光栅逐像素一致。11 项 XeTeX +定向测试及 1 项 pdfTeX 打开动作回归通过。三页两文件项目连续 +修改目标页与书签标题时只更新 PDF,随后改规则宽度只更新第二页。 +两次各复用 184 步、重放 2 次宿主调用,PDF、SVG 和来源映射均 +与独立全量编译一致。 + +原样 ACL 使用同一 schema71 格式与十份冻结源。首轮生成 1 页 +原生 PDF。真实 BibTeX 生成的 `.bbl` 与冻结参考逐字节一致。 +第二轮生成 1 页带参考文献的 PDF。第三轮加载引文后,在 +`hxetex.def:232:19` 的 `pdf:bann` 停止,未生成新 PDF。 +同轮参考与原生首轮都为 A4 一页,仍有可见的断行差异。 +下一阶段接入 XDV 注释的实际字形范围、分行矩形和命名目标引用。 +回执 `target/p3-xdv-navigation/receipt.json`,SHA-256 为 +`489531730a1fd3c05ad5014bae9dfb69252988b128a4d06a6570865874e093ce`。 + ### XDV 颜色栈与跨页背景 XDV 发页执行 `color push`、`color pop`、全局前景色和 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index ad3e9e2..897d522 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -741,6 +741,14 @@ XDV 颜色设备接入后,在新作业目录使用同一份原样 schema71 和 回执 `target/p3-xdv-color/receipt.json`。 [颜色阶段记录](P2_M1_PROGRESS.md#xdv-颜色栈与跨页背景) +XDV 文档目录和书签接入后,原样 ACL 以同一 schema71 和官方归档 +首次出页。首轮与实际 BibTeX 后的第二轮均生成 1 页原生 PDF。 +生成的 `.bbl` 与冻结参考逐字节一致。第三轮加载引文后在 +`hxetex.def:232:19` 的 `pdf:bann` 停止,未生成新 PDF。 +首轮参考与原生均为 A4 一页,断行仍有差异,多轮作业及排版验收仍开放。 +回执 `target/p3-xdv-navigation/receipt.json`。 +[目录、打开动作和书签阶段记录](P2_M1_PROGRESS.md#xdv-文档目录打开动作和书签) + ### 原样 Elsevier CAS 双栏与 NeurIPS 2025 以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。