From 22154b53a67922c771ba736701210f6a0f35e9f5 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 05:04:54 +0800 Subject: [PATCH] Resolve native PDF structure destinations and local actions --- crates/texrra-tex-core/src/execution/boxes.rs | 7 +- .../src/execution/diagnostics.rs | 3 + .../src/execution/engine/pdf_catalog.rs | 21 ++- .../src/execution/engine/pdf_links.rs | 15 +- .../src/execution/format_image.rs | 6 +- crates/texrra-tex-core/src/pdf.rs | 176 ++++++++++++------ .../texrra-tex-core/src/pdf_device/catalog.rs | 19 +- .../texrra-tex-core/src/pdf_device/links.rs | 7 + .../src/pdf_device/page_resources.rs | 24 +++ docs/P2_M1_PROGRESS.md | 28 +++ tests/native_pdf_links.rs | 56 ++++++ 11 files changed, 284 insertions(+), 78 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 6ee60e9..8c72098 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -900,7 +900,12 @@ impl NativeBox { budget.leader_depth += 1; let result = self.walk_at(x, y, level, links, budget, &mut |x, y, paint| { if !matches!(paint, BoxPaint::Output(o) if matches!(o.operation, - OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. })) { + OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. })) + && !matches!(paint, BoxPaint::PdfLink(node, _) if matches!( + node.operation, + OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. }) + )) + { emit(x, y, paint); } }); diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index d85135d..2db964d 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -618,6 +618,9 @@ impl Printer<'_> { LinkNode::Running(true) => "pdfrunninglinkon", LinkNode::Destination { .. } => "pdfdest", }); + if let LinkNode::Destination { structure: Some(object), .. } = node { + self.literal(&format!(" struct{object}")); + } } OutputOperation::PdfLiteral { mode, shipout, tokens } => { use crate::pdf_device::PdfLiteralMode; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs index 435c6c3..539373c 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs @@ -1,6 +1,6 @@ use super::*; use crate::pdf_device::{ - catalog::{CatalogAction, CatalogTarget, PdfOutline}, + catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget}, links::DestinationId, }; @@ -78,7 +78,7 @@ impl Executor { } } - fn scan_catalog_action( + pub(super) fn scan_catalog_action( &mut self, files: &mut impl SourceProvider, ) -> Result { @@ -95,10 +95,21 @@ impl Executor { None }; let structure = if self.keyword("struct", files)? { - if !goto || file.is_none() { - return self.fail("current PDF structure actions require a remote GoTo"); + if !goto { + return self.fail("only PDF GoTo actions can target a structure"); } - Some(self.scan_pdf_bytes(files)?) + Some(if file.is_some() { + StructureTarget::Remote(self.scan_pdf_bytes(files)?) + } else if self.keyword("name", files)? { + let name = self.scan_pdf_tokens(files)?; + StructureTarget::Local(DestinationId::Name(self.token_list_text(&name))) + } else if self.keyword("num", files)? { + StructureTarget::Local(DestinationId::Number( + self.positive_pdf_number("structure destination number", files)?, + )) + } else { + return self.fail("PDF structure destination identifier type missing"); + }) } else { None }; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index 9e2ea92..6b83ad6 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -150,10 +150,8 @@ impl Executor { }; let action = if self.keyword("user", files)? { LinkAction::User(self.scan_pdf_tokens(files)?) - } else if self.keyword("goto", files)? && self.keyword("name", files)? { - LinkAction::GotoName(self.scan_pdf_tokens(files)?) } else { - return self.fail("expected a user or named goto PDF link action"); + LinkAction::Catalog(self.scan_catalog_action(files)?) }; self.state .pdf_objects @@ -174,6 +172,11 @@ impl Executor { LinkNode::Running(command == Primitive::Pdfrunninglinkon) } Primitive::Pdfdest => { + let structure = if self.keyword("struct", files)? { + Some(self.positive_pdf_number("structure object number", files)? as u32) + } else { + None + }; let destination = if self.keyword("name", files)? { DestinationId::Name(self.scan_pdf_tokens(files)?) } else if self.keyword("num", files)? { @@ -205,7 +208,7 @@ impl Executor { } view.ok_or_else(|| self.error("expected PDF destination view", span))? }; - LinkNode::Destination { destination, view } + LinkNode::Destination { destination, view, structure } } _ => unreachable!(), }; @@ -274,6 +277,7 @@ impl Executor { let action = match &layout.action { LinkAction::User(tokens) => AnnotationAction::User(self.token_list_text(tokens)), LinkAction::GotoName(tokens) => AnnotationAction::GotoName(self.token_list_text(tokens)), + LinkAction::Catalog(action) => AnnotationAction::Catalog(action.clone()), }; let mut start = ActiveLink { layout: layout.clone(), attributes, action, level: row.level, segment: None }; @@ -299,13 +303,14 @@ impl Executor { link.end_segment(&mut output, x, margin); } LinkNode::Running(enabled) => self.pdf_running_links = *enabled, - LinkNode::Destination { destination, view } => { + LinkNode::Destination { destination, view, structure } => { let destination = match destination { DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)), DestinationId::Number(number) => DestinationId::Number(*number), }; output.destinations.push(PageDestination { destination, point: map_point(transform.0, x, y), view: *view, + structure: *structure, }); } } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 9b3e835..5f5769c 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,8 +8,10 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 45; -const COMPATIBLE_SCHEMAS: [u32; 14] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, SCHEMA]; +const SCHEMA: u32 = 46; +const COMPATIBLE_SCHEMAS: [u32; 15] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, SCHEMA, +]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 309bf11..2dec1aa 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -14,7 +14,7 @@ use rusttype::Font; use crate::cmr10::Cmr10Metrics; use crate::pdf_device::{ - catalog::{CatalogAction, CatalogTarget, PdfOutline}, + catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget}, links::DestinationId, }; use crate::render::{DisplayItem, DisplayList, FontFace}; @@ -1393,7 +1393,8 @@ fn native_pdf( || !font_attributes.is_empty() || !page_tree.is_empty() || pages.iter().any(|page| !page.pdf_resources.entries.is_empty() - || !page.pdf_resources.attributes.is_empty()) + || !page.pdf_resources.attributes.is_empty() + || page.pdf_links.destinations.iter().any(|destination| destination.structure.is_some())) { let (catalog, info) = if raw_objects.is_some() { ( @@ -1694,15 +1695,29 @@ fn pdf_file_specification(out: &mut Vec, file: &[u8]) { out.push(b' '); } -fn write_catalog_action( +#[derive(Default)] +struct PdfNavigation { + pages: Vec, + named: BTreeMap, + numbered: BTreeMap, + structures: BTreeMap, usize>, + threads: BTreeMap, usize>, +} + +fn destination_identifier(id: &DestinationId) -> String { + match id { + DestinationId::Name(name) => format!("name{{{name}}}"), + DestinationId::Number(number) => format!("num{number}"), + } +} + +fn catalog_action_bytes( action: &CatalogAction, - page_ids: &[usize], - destinations: &mut BTreeMap, - numbers: &mut BTreeMap, - threads: &mut BTreeMap, usize>, + destinations: &mut PdfNavigation, objects: &mut Vec>, diagnostics: &mut Vec, -) -> usize { +) -> Vec { + let PdfNavigation { pages, named, numbered, structures, threads } = destinations; let mut output = b"<< ".to_vec(); match action { CatalogAction::User(object) => output.clone_from(object), @@ -1723,20 +1738,20 @@ fn write_catalog_action( } match target { CatalogTarget::Destination(DestinationId::Name(name)) => { - if file.is_none() && !destinations.contains_key(name) { + if file.is_none() && !named.contains_key(name) { diagnostics.push(format!( "destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one" )); - destinations.insert(name.clone(), format!("[{} 0 R /Fit]", page_ids[0])); + named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0])); } output.extend_from_slice(pdf_text(name).as_bytes()); } CatalogTarget::Destination(DestinationId::Number(number)) => { - let id = numbers.entry(*number).or_insert_with(|| { + let id = numbered.entry(*number).or_insert_with(|| { diagnostics.push(format!( "destination num{number} has been referenced but does not exist, replaced by a fixed one" )); - objects.push(format!("[{} 0 R /Fit]", page_ids[0]).into_bytes()); + objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes()); objects.len() }); write!(&mut output, "{id} 0 R").unwrap(); @@ -1746,7 +1761,7 @@ fn write_catalog_action( if file.is_some() { write!(&mut output, "[{index} ").unwrap(); } else { - let page = page_ids.get(index).copied().unwrap_or_else(|| { + let page = pages.get(index).copied().unwrap_or_else(|| { diagnostics.push(format!( "page {number} has been referenced but does not exist" )); @@ -1759,9 +1774,24 @@ fn write_catalog_action( output.push(b']'); } } - if let Some(structure) = structure { - output.extend_from_slice(b" /SD "); - output.extend_from_slice(structure); + match structure { + Some(StructureTarget::Local(destination)) => { + let id = structures.entry(destination.clone()).or_insert_with(|| { + diagnostics.push(format!( + "structure destination {} has been referenced but does not exist", + destination_identifier(destination) + )); + // pdfTeX leaves the missing destination in the free list. + objects.push(Vec::new()); + objects.len() + }); + write!(&mut output, " /SD {id} 0 R").unwrap(); + } + Some(StructureTarget::Remote(bytes)) => { + output.extend_from_slice(b" /SD "); + output.extend_from_slice(bytes); + } + None => {} } output.extend_from_slice(b"\n>>"); } @@ -1784,7 +1814,7 @@ fn write_catalog_action( objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes()); objects.push(format!( "<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>", - page_ids[0] + pages[0] ).into_bytes()); thread })); @@ -1803,8 +1833,7 @@ fn write_catalog_action( output.extend_from_slice(b" >>"); } } - objects.push(output); - objects.len() + output } #[derive(Clone, Default)] @@ -2180,9 +2209,8 @@ fn write_pdf( } } let mut kids = Vec::new(); - let mut page_ids: Vec = Vec::new(); - let mut destinations = BTreeMap::new(); - let mut numbers = BTreeMap::new(); + let mut navigation = PdfNavigation::default(); + let mut annotation_actions = Vec::new(); let pdf_version = pages .first() .and_then(|page| page.pdf.as_ref()) @@ -2342,7 +2370,7 @@ fn write_pdf( } else { format!(" /Annots [{annotation_refs}]") }; - page_ids.push(page_id); + navigation.pages.push(page_id); kids.push(format!("{page_id} 0 R")); let decorated = !list.pdf_resources.attributes.is_empty(); let mut page = b"<< /Type /Page".to_vec(); @@ -2435,25 +2463,33 @@ fn write_pdf( use crate::pdf_device::links::AnnotationAction; let [left, top, right, bottom] = annotation.rect; let coordinates = [left, height - bottom, right, height - top].map(physical); - let action = match &annotation.action { - AnnotationAction::User(raw) => raw.clone(), - AnnotationAction::GotoName(name) => - format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)), - }; let entries = remapped.as_ref().and_then(|resources| resources.annotations[page_index][index].as_deref()); - let body = if let Some(entries) = entries { + let mut body = if let Some(entries) = entries { let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes(); body.extend_from_slice(entries); - if matches!(annotation.action, AnnotationAction::GotoName(_)) { - body.extend_from_slice(action.as_bytes()); - } - body.extend_from_slice(b" >>"); body } else { - format!("<< /Type /Annot {} /Rect [{}] {} >>", - annotation.attributes, coordinates.join(" "), action).into_bytes() + format!("<< /Type /Annot {} /Rect [{}] ", + annotation.attributes, coordinates.join(" ")).into_bytes() }; + match &annotation.action { + AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()), + AnnotationAction::User(_) => {} + AnnotationAction::GotoName(name) => { + write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap(); + } + AnnotationAction::Catalog(action) => { + // A local action may use a structure or page in a later shipout. + body.extend_from_slice(b" /Subtype /Link /A "); + annotation_actions.push((id, body, action)); + if id == objects.len() + 1 { + objects.push(Vec::new()); + } + continue; + } + } + body.extend_from_slice(b" >>"); if id == objects.len() + 1 { objects.push(body); } else { @@ -2477,16 +2513,32 @@ fn write_pdf( DestinationView::FitBH => format!("/FitBH {y}"), DestinationView::FitBV => format!("/FitBV {x}"), }; - let object = || format!("[{page_id} 0 R {view}]"); - match &destination.destination { - DestinationId::Name(name) => { - destinations.entry(name.clone()).or_insert_with(object); + if let Some(number) = destination.structure { + use std::collections::btree_map::Entry; + match navigation.structures.entry(destination.destination.clone()) { + Entry::Vacant(entry) => { + let structure = remapped.as_ref().expect("structure objects were remapped") + .structure_objects[&number]; + objects.push(format!("[{structure} 0 R {view}]").into_bytes()); + entry.insert(objects.len()); + } + Entry::Occupied(entry) => diagnostics.push(format!( + "structure destination with the same identifier ({}) has been already used, duplicate ignored", + destination_identifier(entry.key()) + )), } - DestinationId::Number(number) => { - numbers.entry(*number).or_insert_with(|| { - objects.push(object().into_bytes()); - objects.len() - }); + } else { + let object = || format!("[{page_id} 0 R {view}]"); + match &destination.destination { + DestinationId::Name(name) => { + navigation.named.entry(name.clone()).or_insert_with(object); + } + DestinationId::Number(number) => { + navigation.numbered.entry(*number).or_insert_with(|| { + objects.push(object().into_bytes()); + objects.len() + }); + } } } } @@ -2503,6 +2555,11 @@ fn write_pdf( } objects[1].extend_from_slice(b" >>"); + for (id, mut body, action) in annotation_actions { + body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics)); + body.extend_from_slice(b" >>"); + objects[id - 1] = body; + } let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned(); if !metadata.outline.is_empty() { let root_id = objects.len() + 1; @@ -2538,9 +2595,9 @@ fn write_pdf( } for (index, entry) in metadata.outline.iter().enumerate() { - let page_id = page_ids + let page_id = navigation.pages .get(entry.page) - .or_else(|| page_ids.last()) + .or_else(|| navigation.pages.last()) .copied() .unwrap_or(0); let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]); @@ -2584,30 +2641,27 @@ fn write_pdf( catalog.push_str(&format!(" /Outlines {root_id} 0 R")); } let extra = unicode.and_then(|options| options.catalog); - let mut threads = BTreeMap::new(); - let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| { - write_catalog_action( - action, &page_ids, &mut destinations, &mut numbers, &mut threads, &mut objects, - diagnostics, - ) - }); + let mut action_object = |action| { + let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics); + objects.push(body); + objects.len() + }; + let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object); if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) { - let action_ids: Vec<_> = extra.outlines.iter().map(|outline| { - write_catalog_action( - &outline.action, &page_ids, &mut destinations, &mut numbers, &mut threads, - &mut objects, diagnostics, - ) - }).collect(); + let action_ids: Vec<_> = extra.outlines.iter() + .map(|outline| action_object(&outline.action)) + .collect(); let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects); catalog.push_str(&format!(" /Outlines {outlines} 0 R")); } - if !threads.is_empty() { - let mut ids: Vec<_> = threads.into_values().collect(); + if !navigation.threads.is_empty() { + let mut ids: Vec<_> = navigation.threads.into_values().collect(); ids.sort_unstable_by(|left, right| right.cmp(left)); let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect(); objects.push(format!("[{}]", references.join(" ")).into_bytes()); catalog.push_str(&format!(" /Threads {} 0 R", objects.len())); } + let destinations = navigation.named; if !destinations.is_empty() { let mut entries = Vec::with_capacity(destinations.len()); let first = pdf_text(destinations.first_key_value().unwrap().0); diff --git a/crates/texrra-tex-core/src/pdf_device/catalog.rs b/crates/texrra-tex-core/src/pdf_device/catalog.rs index a61df64..91dd804 100644 --- a/crates/texrra-tex-core/src/pdf_device/catalog.rs +++ b/crates/texrra-tex-core/src/pdf_device/catalog.rs @@ -17,13 +17,13 @@ pub(crate) struct PdfOutline { } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] -pub(crate) enum CatalogAction { +pub enum CatalogAction { User(Vec), GoTo { target: CatalogTarget, file: Option>, window: Option, - structure: Option>, + structure: Option, }, Thread { destination: DestinationId, @@ -48,7 +48,10 @@ impl CatalogAction { CatalogTarget::Page { view, .. } => view.len(), }; target_len + file.as_ref().map_or(0, Vec::len) - + structure.as_ref().map_or(0, Vec::len) + + structure.as_ref().map_or(0, |structure| match structure { + StructureTarget::Local(id) => destination_len(id), + StructureTarget::Remote(bytes) => bytes.len(), + }) } Self::Thread { destination, file } => { destination_len(destination) + file.as_ref().map_or(0, Vec::len) @@ -58,7 +61,15 @@ impl CatalogAction { } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] -pub(crate) enum CatalogTarget { +pub enum CatalogTarget { Destination(DestinationId), Page { number: i32, view: Vec }, } + +/// Local identifier or explicit remote PDF structure destination. +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum StructureTarget { + Local(DestinationId), + Remote(Vec), +} diff --git a/crates/texrra-tex-core/src/pdf_device/links.rs b/crates/texrra-tex-core/src/pdf_device/links.rs index e9399f0..5883b81 100644 --- a/crates/texrra-tex-core/src/pdf_device/links.rs +++ b/crates/texrra-tex-core/src/pdf_device/links.rs @@ -1,10 +1,12 @@ //! Typed link nodes and the annotations produced when TeX ships their lists. +use super::catalog::CatalogAction; use crate::execution::Token; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum LinkAction { User(Vec), GotoName(Vec), + Catalog(CatalogAction), } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -45,6 +47,8 @@ pub enum LinkNode { Destination { destination: DestinationId>, view: DestinationView, + #[serde(default, skip_serializing_if = "Option::is_none")] + structure: Option, }, } @@ -52,6 +56,7 @@ pub enum LinkNode { pub enum AnnotationAction { User(String), GotoName(String), + Catalog(CatalogAction), } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -69,6 +74,8 @@ pub struct PageDestination { pub destination: DestinationId, pub point: [i64; 2], pub view: DestinationView, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub structure: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/pdf_device/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/page_resources.rs index 78d68c0..00ac55e 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -427,6 +427,7 @@ pub(crate) struct ResourceOutput { values: BTreeMap, page_references: BTreeMap, link_references: BTreeMap>, + structure_references: BTreeSet, page_entries: Vec, page_attributes: Vec, page_tree_attributes: Dictionary, @@ -443,6 +444,7 @@ pub(crate) struct RemappedResources { pub fonts: BTreeMap>, pub page_objects: BTreeMap, pub link_objects: BTreeMap<(usize, usize), usize>, + pub structure_objects: BTreeMap, pub annotations: Vec>>>, pub catalog: Option>, pub info: Option>, @@ -537,6 +539,11 @@ impl ResourceOutput { } } } + let structure_references = pages + .iter() + .flat_map(|page| &page.pdf_links.destinations) + .filter_map(|destination| destination.structure) + .collect(); let mut values = BTreeMap::new(); while let Some(number) = pending.pop_first() { if objects.is_link(number) { @@ -554,6 +561,7 @@ impl ResourceOutput { values, page_references: objects.page_references.clone(), link_references, + structure_references, page_entries, page_attributes, page_tree_attributes, @@ -605,6 +613,21 @@ impl ResourceOutput { remap(&mut object, &ids); output.push(encode_value(object).expect("valid PDF object in memory")); } + let structure_objects = self + .structure_references + .into_iter() + .map(|number| { + let id = ids.get(&number).map_or_else( + || { + // A reference to an unwritten structure keeps a free entry. + output.push(Vec::new()); + output.len() + }, + |&id| id as usize, + ); + (number, id) + }) + .collect(); let encode = |dictionary: Dictionary| { if dictionary.is_empty() { return Vec::new(); @@ -623,6 +646,7 @@ impl ResourceOutput { .collect(), page_objects, link_objects, + structure_objects, annotations: self.annotation_entries.into_iter() .map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect()) .collect(), diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 205f4a0..9a8d872 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1384,6 +1384,34 @@ DVI 的坐标文件在 PDF 驱动报告 DVI 导出限制前完成,原生 DVI - `acm-format/receipt.json` 为 `9a2676974b4bfc2d42495ab171b2737ff186253bcb4c6266bc8224a1b0a41e56`。 - `acm-acmtog/receipt.json` 为 `7b135237b60b3e36ea16a464ea3be5dcf55043f837f03f377db7be26b3a59d0e`。 +### 本地 PDF 结构目的地 + +原生 `\pdfdest struct` 在发页时记录结构对象、位置和视图。普通目的地与 +结构目的地使用独立的名称和数字空间。书签、文档打开动作和链接共用 +本地 GoTo 的扫描和导出。链接可以指向后续页面或后发出的结构目的地。 +`/SD` 引用独立的间接数组,数组首项是由真实 PDF 对象表重编号的结构对象。 +远程动作仍使用显式 PDF 参数。未发出的结构目的地诊断并保留空闲引用。 +重复结构目的地以首个发出的定义为准,leaders 中的目的地被忽略。 +[pdfTeX 结构目的地和动作源代码](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web) + +三个 INITEX 对照验证了名称及数字目的地、远程动作、跨页链接、打开动作、 +未发出及重复定义。目标视图的数值和结构树的实际引用匹配 pdfTeX。 +比较时解析直接对象及对象引用,消除字典空白及数值尾零的差异。6项 PDF +配置和链接测试通过。保存的链接格式采用 schema46,已用旧 schema45 +中真正保存的命名链接盒加载并发页。原有冻结的出版格式可直接加载。 +已有的视图范围包括 XYZ、Fit 与 FitH/FitV 系列,FitR 仍待接通。 + +移动第二页结构位置,续编复用1156步,只重发第二页。第一页链接指向的 +结构目标从 9.963 bp 移到 13.948 bp。发布 PDF、SVG 与归一化来源映射 +与独立零复用编译一致。 + +回执在 `target/p3-pdf-structure-dest-native`。 + +- `implementation-receipt.json` 为 `557e7a371eb194a541a1018e5405d0a959aac69c629f31d377d13b651ab626d0`。 +- `checkpoint/receipt.json` 为 `6bebb085f684997f1845f3f8e3f917369384ca1efae5d3596768c4de14538a1a`。 +- `legacy-link/receipt.json` 为 `eefdee02507881e3901498626f23abf7772e9dad9f1b1e52dcb8a8f5248e7b9e`。 +- `related-tests.log` 为 `1c088e4dc5ae755a7f247e5b62be1867f12888b224d455834ddd465b775b62fb`。 + ### PDF 字面中的矩阵与来源映射 来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和 diff --git a/tests/native_pdf_links.rs b/tests/native_pdf_links.rs index b19f305..644d1eb 100644 --- a/tests/native_pdf_links.rs +++ b/tests/native_pdf_links.rs @@ -124,3 +124,59 @@ fn real_pdf_link_fragments_and_named_destination_match_pdftex() { assert_eq!(describe(&compile(&root, source, true)), expected); fs::remove_dir_all(root).unwrap(); } + +#[test] +fn local_structure_action_references_the_shipped_structure_and_later_page() { + let root = std::env::temp_dir().join(format!("texrra-pdf-structure-{}", std::process::id())); + let source = r"\catcode123=1 \catcode125=2 +\def\space{ } +\pdfoutput=1 \pdfmajorversion=2 \pdfminorversion=0 +\pdfcompresslevel=0 \pdfobjcompresslevel=0 +\pdfobj reserveobjnum \count10=\pdflastobj +\pdfobj reserveobjnum \count11=\pdflastobj +\edef\ROOT{\number\count10} \edef\CHILD{\number\count11} +\immediate\pdfobj useobjnum\count11{<< /Type /StructElem /S /Sect /P \ROOT\space 0 R >>} +\immediate\pdfobj useobjnum\count10{<< /Type /StructTreeRoot /K [\CHILD\space 0 R] >>} +\pdfcatalog{/StructTreeRoot \ROOT\space 0 R} openaction goto struct name{anchor} page 2 {/Fit} +\shipout\hbox{\pdfstartlink goto struct name{anchor} name{anchor} + \vrule width10pt height6pt \pdfendlink} +\shipout\hbox{\pdfdest name{anchor} xyz + \pdfdest struct \count11 name{anchor} fit \vrule width10pt height6pt} +\end"; + let doc = compile(&root, source, true); + let catalog = doc.catalog().unwrap(); + let pages = doc.get_pages(); + let page = doc.get_object(pages[&1]).unwrap().as_dict().unwrap(); + let annotations = resolve(&doc, page.get(b"Annots").unwrap()) + .as_array() + .unwrap(); + let link = resolve(&doc, &annotations[0]).as_dict().unwrap(); + let action = resolve(&doc, link.get(b"A").unwrap()).as_dict().unwrap(); + let opener = resolve(&doc, catalog.get(b"OpenAction").unwrap()) + .as_dict() + .unwrap(); + let page_destination = opener.get(b"D").unwrap().as_array().unwrap(); + assert_eq!(page_destination[0].as_reference().unwrap(), pages[&2]); + + let structure_destination = opener.get(b"SD").unwrap(); + assert_eq!( + action.get(b"SD").unwrap().as_reference().unwrap(), + structure_destination.as_reference().unwrap() + ); + let destination = resolve(&doc, structure_destination).as_array().unwrap(); + let structure = resolve(&doc, &destination[0]).as_dict().unwrap(); + assert_eq!( + structure.get(b"Type").unwrap().as_name().unwrap(), + b"StructElem" + ); + assert_eq!( + structure.get(b"P").unwrap().as_reference().unwrap(), + catalog + .get(b"StructTreeRoot") + .unwrap() + .as_reference() + .unwrap() + ); + assert_eq!(destination[1].as_name().unwrap(), b"Fit"); + fs::remove_dir_all(root).unwrap(); +}