diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 349d163..85b8b7f 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -269,12 +269,32 @@ impl Executor { let before = self.statistics_before_shipout(&shipout.box_node, files)?; self.shipped_pages += 1; let page_resources = shipout.pdf_objects.map(|objects| objects.resources); + let links: Vec<_> = shipout.pdf_links.annotations.iter().filter_map(|annotation| { + use crate::pdf_device::{catalog::CatalogAction, links::AnnotationAction}; + let number = annotation.object_number?; + let action = match &annotation.action { + AnnotationAction::Catalog(action @ CatalogAction::GoTo { file: None, .. }) => Some(action.clone()), + _ => None, + }; + Some((number, action)) + }).collect(); + let destinations: Vec<_> = shipout.pdf_links.destinations.iter() + .filter_map(|destination| destination.object_number).collect(); self.events.push(Event::Shipout(Box::new(shipout))); if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() { Arc::make_mut(probe).observed_events = self.events.len(); } self.write_shipout_forms(forms, files)?; if let Some(resources) = page_resources { + for (number, action) in links { + self.pack_pdf_object(number)?; + if let Some(action) = action { + self.write_pdf_link_action(&action)?; + } + } + for number in destinations { + self.pack_pdf_object(number)?; + } self.pack_pdf_object(resources)?; } self.statistics_after_shipout(before, files)?; @@ -435,6 +455,7 @@ impl Executor { if let Some(effects) = &leader_effects { outputs = effects.outputs.iter().collect(); } + let mut navigation_numbers = (Vec::new(), Vec::new()); let mut link_depth = self.pdf_link_stack.len(); let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link()); let mut output_positions = if let Some(effects) = &leader_effects { @@ -655,11 +676,19 @@ impl Executor { LinkNode::Start(_) if link_depth == 10 => { return self.fail("PDF link stack capacity exceeded"); } - LinkNode::Start(_) => link_depth += 1, + LinkNode::Start(layout) => { + link_depth += 1; + if !unicode_pages && !for_form { + navigation_numbers.0.push(self.register_pdf_link(layout.object_number)?); + } + } LinkNode::End if link_depth == 0 => { return self.fail("\\pdfendlink used without \\pdfstartlink"); } LinkNode::End => link_depth -= 1, + LinkNode::Destination { destination, structure, .. } if !unicode_pages && !for_form => { + navigation_numbers.1.push(self.register_pdf_destination(destination, structure.is_some())?); + } LinkNode::Running(_) | LinkNode::Destination { .. } => {} } } else { @@ -706,7 +735,7 @@ impl Executor { return self.fail("PDF page links and destinations require a page shipout"); } let mut links = self.ship_pdf_link_material( - b, device, &shipout.pdf_graphics_steps, files, + b, device, &shipout.pdf_graphics_steps, navigation_numbers, files, )?; links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations); shipout.pdf_links = links; 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 e9e0f95..f44787c 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -1,6 +1,7 @@ use super::*; use crate::pdf_device::{ Affine, PdfGraphics, + catalog::{CatalogAction, CatalogTarget, StructureTarget}, links::{ AnnotationAction, DestinationId, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart, PageDestination, PageLinks, @@ -225,14 +226,63 @@ impl Executor { }) } + pub(super) fn register_pdf_link(&mut self, number: Option) -> Result { + self.reads.insert(Dependency::PdfObjects); + self.state.pdf_objects.get_or_insert_with(Default::default) + .ship_link(number, self.limits.tokens) + .map_err(|message| self.error(message, self.current)) + } + + pub(super) fn register_pdf_destination( + &mut self, id: &DestinationId>, structure: bool, + ) -> Result, Error> { + self.reads.insert(Dependency::PdfObjects); + let id = self.pdf_destination_id(id); + self.state.pdf_objects.get_or_insert_with(Default::default) + .destination_number(id, structure, true, self.limits.tokens) + .map_err(|message| self.error(message, self.current)) + } + + pub(super) fn write_pdf_link_action(&mut self, action: &CatalogAction) -> Result<(), Error> { + let CatalogAction::GoTo { target, file: None, structure, .. } = action else { + return Ok(()); + }; + self.reads.insert(Dependency::PdfObjects); + let limit = self.limits.tokens; + let objects = self.state.pdf_objects.as_deref_mut().expect("registered PDF link"); + let allocation = match target { + CatalogTarget::Page { number, .. } => objects.page_reference(*number as u32, limit).map(Some), + CatalogTarget::Destination(id) => objects.destination_number(id.clone(), false, false, limit), + }; + allocation.map_err(|message| self.error(message, self.current))?; + if let Some(StructureTarget::Local(id)) = structure { + self.state.pdf_objects.as_deref_mut().expect("registered PDF link") + .destination_number(id.clone(), true, false, limit) + .map_err(|message| self.error(message, self.current))?; + } + Ok(()) + } + + fn pdf_destination_id(&mut self, id: &DestinationId>) -> DestinationId { + match id { + DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)), + DestinationId::Number(number) => DestinationId::Number(*number), + } + } + pub(super) fn ship_pdf_link_material( &mut self, b: &NativeBox, device: &ShipoutDevice, graphics: &[Option], + numbers: (Vec, Vec>), files: &mut impl SourceProvider, ) -> Result { let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()); + let numbered = self.state.input_profile() == InputProfile::TeX8Bit; + let (links, destinations) = numbers; + let mut links = links.into_iter(); + let mut destinations = destinations.into_iter(); let mut active = std::mem::take(&mut self.pdf_link_stack); let mut graphics = graphics.iter(); let mut transform = (Affine::IDENTITY, false); @@ -271,7 +321,16 @@ impl Executor { for link in active.iter_mut().filter(|link| { link.level == row.level && link.layout.width.is_none() }) { + let number = if numbered { + match self.register_pdf_link(None) { + Ok(number) => Some(number), + Err(error) => { failure = Some(error); return; } + } + } else { + None + }; link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin); + output.annotations.last_mut().unwrap().object_number = number; } } BoxPaint::PdfLink(node, container) => { @@ -293,9 +352,12 @@ impl Executor { let mut start = ActiveLink { layout: layout.clone(), attributes, action, level: container.level, segment: None }; start.start_segment(&mut output, container, [x, y], transform, margin); - // The scan-time object number belongs only to the - // initial annotation, never to a continuation row. - output.annotations.last_mut().unwrap().object_number = layout.object_number; + let number = if numbered { links.next() } else { layout.object_number }; + if numbered && number.is_none() { + failure = Some(self.error("missing PDF link number at shipout", node.span)); + return; + } + output.annotations.last_mut().unwrap().object_number = number; active.push(start); } LinkNode::End => { @@ -315,9 +377,15 @@ impl Executor { } LinkNode::Running(enabled) => self.pdf_running_links = *enabled, 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), + let destination = self.pdf_destination_id(destination); + let object_number = if numbered { + let Some(number) = destinations.next() else { + failure = Some(self.error("missing PDF destination number at shipout", node.span)); + return; + }; + number + } else { + None }; let view = view.map_rectangle(|[width, height, depth]| { let margin = i64::from(self.read_parameter(Parameter::Pdfdestmargin).width()); @@ -331,7 +399,7 @@ impl Executor { } }); output.destinations.push(PageDestination { - destination, point: map_point(transform.0, x, y), view, + object_number, destination, point: map_point(transform.0, x, y), view, structure: *structure, }); } @@ -343,6 +411,9 @@ impl Executor { if let Some(error) = failure { return Err(error); } + if links.next().is_some() || destinations.next().is_some() { + return self.fail("unused PDF navigation numbers at shipout"); + } for link in &mut active { link.segment = None; } diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs b/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs index 783c2a9..94a8927 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_objects.rs @@ -60,6 +60,9 @@ impl Executor { } else { None }; + let number = self.state.pdf_objects.get_or_insert_with(Default::default) + .begin_definition(requested, self.limits.tokens) + .map_err(|error| self.error(error, self.current))?; let declaration = self.current; let attributes = if self.keyword("stream", files)? { Some(if self.keyword("attr", files)? { @@ -85,11 +88,8 @@ impl Executor { None => ObjectBody::Direct(bytes), } }; - let number = self - .state - .pdf_objects - .get_or_insert_with(Default::default) - .define(requested, value, self.limits.tokens) + self.state.pdf_objects.as_deref_mut().expect("registered PDF object") + .define(number, value, self.limits.tokens) .map_err(|error| self.error(error, self.current))?; if immediate { self.pdf_page_data(files)?; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 98e49fc..9620e97 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1867,12 +1867,23 @@ fn pdf_file_specification(out: &mut Vec, file: &[u8]) { #[derive(Default)] struct PdfNavigation { pages: Vec, - named: BTreeMap, + named: BTreeMap, numbered: BTreeMap, structures: BTreeMap, usize>, + pending_destinations: BTreeMap<(DestinationId, bool), usize>, threads: BTreeMap, usize>, } +fn write_destination(objects: &mut Vec>, slot: Option, body: String) -> usize { + if let Some(id) = slot { + objects[id - 1] = body.into_bytes(); + id + } else { + objects.push(body.into_bytes()); + objects.len() + } +} + fn destination_identifier(id: &DestinationId) -> String { match id { DestinationId::Name(name) => format!("name{{{name}}}"), @@ -1886,7 +1897,7 @@ fn catalog_action_bytes( objects: &mut Vec>, diagnostics: &mut Vec, ) -> Vec { - let PdfNavigation { pages, named, numbered, structures, threads } = destinations; + let PdfNavigation { pages, named, numbered, structures, pending_destinations, threads } = destinations; let mut output = b"<< ".to_vec(); match action { CatalogAction::User(object) => output.clone_from(object), @@ -1911,7 +1922,10 @@ fn catalog_action_bytes( diagnostics.push(format!( "destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one" )); - named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0])); + let slot = pending_destinations.get(&(DestinationId::Name(name.clone()), false)).copied(); + let view = format!("[{} 0 R /Fit]", pages[0]); + let body = if slot.is_some() { format!("<< /D {view} >>") } else { view }; + named.insert(name.clone(), write_destination(objects, slot, body)); } output.extend_from_slice(pdf_text(name).as_bytes()); } @@ -1920,8 +1934,8 @@ fn catalog_action_bytes( diagnostics.push(format!( "destination num{number} has been referenced but does not exist, replaced by a fixed one" )); - objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes()); - objects.len() + let slot = pending_destinations.get(&(DestinationId::Number(*number), false)).copied(); + write_destination(objects, slot, format!("[{} 0 R /Fit]", pages[0])) }); write!(&mut output, "{id} 0 R").unwrap(); } @@ -1951,8 +1965,11 @@ fn catalog_action_bytes( destination_identifier(destination) )); // pdfTeX leaves the missing destination in the free list. - objects.push(Vec::new()); - objects.len() + pending_destinations.get(&(destination.clone(), true)).copied() + .unwrap_or_else(|| { + objects.push(Vec::new()); + objects.len() + }) }); write!(&mut output, " /SD {id} 0 R").unwrap(); } @@ -2563,6 +2580,17 @@ fn write_pdf( device_objects.insert(stream.number, objects.len() as u32); } } + let mut navigation = PdfNavigation::default(); + if let Some(registry) = registry { + for (key, number, defined) in registry.destinations() { + objects.push(Vec::new()); + let id = objects.len(); + device_objects.insert(number, id as u32); + if !defined { + navigation.pending_destinations.insert(key.clone(), id); + } + } + } let parents: BTreeSet<_> = pages.iter().filter_map(|page| { page.pdf_resources.objects.map(|allocation| allocation.parent) }).collect(); @@ -2598,7 +2626,6 @@ fn write_pdf( } let mut kids = Vec::new(); let mut page_groups = BTreeMap::>::new(); - let mut navigation = PdfNavigation::default(); let mut annotation_actions = Vec::new(); let mut xdv_annotations = Vec::new(); let pdf_version = pages @@ -3014,14 +3041,14 @@ fn write_pdf( format!("/FitR {}", coordinates.join(" ")) } }; + let slot = destination.object_number.map(|number| device_objects[&number] as usize); 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.insert(write_destination(&mut objects, slot, format!("[{structure} 0 R {view}]"))); } Entry::Occupied(entry) => diagnostics.push(format!( "structure destination with the same identifier ({}) has been already used, duplicate ignored", @@ -3032,12 +3059,14 @@ fn write_pdf( let object = || format!("[{page_id} 0 R {view}]"); match &destination.destination { DestinationId::Name(name) => { - navigation.named.entry(name.clone()).or_insert_with(object); + navigation.named.entry(name.clone()).or_insert_with(|| { + let body = if slot.is_some() { format!("<< /D {} >>", object()) } else { object() }; + write_destination(&mut objects, slot, body) + }); } DestinationId::Number(number) => { navigation.numbered.entry(*number).or_insert_with(|| { - objects.push(object().into_bytes()); - objects.len() + write_destination(&mut objects, slot, object()) }); } } @@ -3056,6 +3085,7 @@ fn write_pdf( } objects[1].extend_from_slice(b" >>"); + let after_pages_tree = objects.len() + 1; for (id, mut body, action) in annotation_actions { body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics)); body.extend_from_slice(b" >>"); @@ -3236,12 +3266,17 @@ fn write_pdf( let first = pdf_text(destinations.first_key_value().unwrap().0); let last = pdf_text(destinations.last_key_value().unwrap().0); for (name, destination) in destinations { - objects.push(destination.into_bytes()); - entries.push(format!("{} {} 0 R", pdf_text(&name), objects.len())); + entries.push(format!("{} {destination} 0 R", pdf_text(&name))); } objects.push(format!("<< /Names [{}] /Limits [{first} {last}] >>", entries.join(" ")).into_bytes()); - catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len())); + let tree = objects.len(); + if pages[0].pdf.as_ref().is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::PdfTeX) { + objects.push(format!("<< /Dests {tree} 0 R >>").into_bytes()); + catalog.push_str(&format!(" /Names {} 0 R", objects.len())); + } else { + catalog.push_str(&format!(" /Names << /Dests {tree} 0 R >>")); + } } objects[0] = if let Some(xdv) = xdv { xdv.finish_catalog(&catalog, &navigation.pages)? @@ -3305,7 +3340,7 @@ fn write_pdf( } else { None }; - Some(objects::ObjectPacking { streams, uncompressed }) + Some(objects::ObjectPacking { streams, uncompressed, after_pages_tree }) } else { None }; diff --git a/crates/texrra-tex-core/src/pdf_device/links.rs b/crates/texrra-tex-core/src/pdf_device/links.rs index f608d33..6450f65 100644 --- a/crates/texrra-tex-core/src/pdf_device/links.rs +++ b/crates/texrra-tex-core/src/pdf_device/links.rs @@ -90,6 +90,8 @@ pub struct LinkAnnotation { #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct PageDestination { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub object_number: Option, pub destination: DestinationId, pub point: [i64; 2], pub view: DestinationView<[i64; 4]>, 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 168ac1e..d9ac29f 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -1,5 +1,6 @@ //! Native PDF objects and extra resources captured at page shipout. use crate::execution::FontId; +use super::links::DestinationId; use lopdf::{ Dictionary, Object, Stream, content::{Content, Operation}, @@ -36,6 +37,7 @@ pub(crate) enum ObjectBody { from: String, }, ObjectStream, + Destination, } impl ObjectBody { @@ -44,7 +46,7 @@ impl ObjectBody { Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream - | Self::DiscardedAtDump => 0, + | Self::Destination | Self::DiscardedAtDump => 0, Self::Direct(bytes) => bytes.len(), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), Self::File { @@ -63,7 +65,8 @@ impl ObjectBody { match self { Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents - | Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream => { + | Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream + | Self::Destination => { Err("expected a generic native PDF object".into()) } Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()), @@ -123,6 +126,10 @@ pub struct PdfObjects { // previous output file's pending stream or its cross references. #[serde(skip)] object_streams: Vec>, + #[serde(skip)] + destination_numbers: BTreeMap<(DestinationId, bool), (u32, bool)>, + #[serde(skip)] + shipped_links: BTreeSet, } impl PdfObjects { @@ -307,6 +314,37 @@ impl PdfObjects { self.allocate(Some(Arc::new(ObjectBody::Link)), limit) } + pub(crate) fn ship_link(&mut self, number: Option, limit: usize) -> Result { + if let Some(number) = number + && matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::Link)) + && self.shipped_links.insert(number) + { + return Ok(number); + } + let number = self.reserve_link(limit)?; + self.shipped_links.insert(number); + Ok(number) + } + + pub(crate) fn destination_number( + &mut self, id: DestinationId, structure: bool, define: bool, limit: usize, + ) -> Result, String> { + let key = (id, structure); + if let Some((number, defined)) = self.destination_numbers.get_mut(&key) { + if define && std::mem::replace(defined, true) { + return Ok(None); + } + return Ok(Some(*number)); + } + let number = self.allocate(Some(Arc::new(ObjectBody::Destination)), limit)?; + self.destination_numbers.insert(key, (number, define)); + Ok(Some(number)) + } + + pub(crate) fn destinations(&self) -> impl Iterator, bool), u32, bool)> { + self.destination_numbers.iter().map(|(key, &(number, defined))| (key, number, defined)) + } + pub(crate) fn record_last_link(&mut self, number: u32) { self.last_link = Some(number); } @@ -323,7 +361,7 @@ impl PdfObjects { Some(ObjectBody::Link) => ObjectBody::FormatLink, Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources | ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_) - | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream) => { + | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination) => { ObjectBody::DiscardedAtDump } _ if self.written.contains(&number) => ObjectBody::DiscardedAtDump, @@ -341,6 +379,8 @@ impl PdfObjects { self.png_group = None; self.written_png_group = None; self.object_streams.clear(); + self.destination_numbers.clear(); + self.shipped_links.clear(); !self.values.is_empty() } @@ -359,25 +399,27 @@ impl PdfObjects { Ok(number) } + pub(crate) fn begin_definition(&mut self, requested: Option, limit: usize) -> Result { + requested.map_or_else(|| self.allocate(None, limit), Ok) + } + pub(crate) fn define( &mut self, - requested: Option, + number: u32, value: ObjectBody, limit: usize, - ) -> Result { + ) -> Result<(), String> { let bytes = self.bytes.saturating_add(value.len()); if bytes > limit { return Err("native PDF object payload capacity exceeded".into()); } - let number = match requested { - Some(number) if self.is_reserved(number) => number, - Some(_) => return Err("native PDF object was already defined".into()), - None => self.reserve(limit)?, - }; + if !self.is_reserved(number) { + return Err("native PDF object was already defined".into()); + } self.values[number as usize - 1] = Some(Arc::new(value)); self.bytes = bytes; self.last = number as i32; - Ok(number) + Ok(()) } pub(crate) fn unwritten(&self, number: u32) -> Result, String> { @@ -798,7 +840,8 @@ impl ResourceOutput { if values.contains_key(&number) || page_objects.contains(&number) || device_objects.contains(&number) || objects.font_owner(number).is_some() || matches!(objects.entry(number).and_then(Option::as_deref), - Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream)) + Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream + | ObjectBody::Destination)) { continue; } diff --git a/crates/texrra-tex-core/src/pdf_objects.rs b/crates/texrra-tex-core/src/pdf_objects.rs index c8cae50..db3c0e4 100644 --- a/crates/texrra-tex-core/src/pdf_objects.rs +++ b/crates/texrra-tex-core/src/pdf_objects.rs @@ -33,6 +33,7 @@ pub(crate) fn stream_bytes(extra: &[u8], data: &[u8], level: u8) -> Vec { pub(super) struct ObjectPacking { pub streams: Vec<(usize, Vec)>, pub uncompressed: Option, + pub after_pages_tree: usize, } pub(super) fn serialize( @@ -47,7 +48,7 @@ pub(super) fn serialize( let mut stream_slots = vec![false; objects.len() + 1]; let mut next_stream = objects.len() + 1; let execution_order = packing.is_some(); - let ObjectPacking { streams: mut groups, uncompressed } = packing.unwrap_or_default(); + let ObjectPacking { streams: mut groups, uncompressed, after_pages_tree } = packing.unwrap_or_default(); for (id, members) in &groups { if *id == 0 || *id > objects.len() || !objects[*id - 1].is_empty() || std::mem::replace(&mut stream_slots[*id], true) @@ -67,10 +68,13 @@ pub(super) fn serialize( } if options.object_compression > 0 { // The page tree precedes the catalog. Info, when eligible, is last. - let document_tail = [Some(2), Some(1), info]; - let order = (1..=objects.len()) - .filter(|id| !execution_order || !document_tail.contains(&Some(*id))) - .chain(document_tail.into_iter().flatten().filter(|_| execution_order)); + let early = (1..=objects.len()).filter(|id| { + !execution_order || (*id >= 3 && *id < after_pages_tree && Some(*id) != info) + }); + let late = (after_pages_tree..=objects.len()) + .filter(|id| execution_order && Some(*id) != info); + let order = early.chain(execution_order.then_some(2)).chain(late) + .chain(execution_order.then_some(1)).chain(info.filter(|_| execution_order)); for id in order { let body = &objects[id - 1]; if body.is_empty() || packed[id].is_some() || Some(id) == uncompressed diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4246bc0..521e7ea 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -919,6 +919,27 @@ target/p3-pdf-object-streams/first-candidate。最终回执 SHA-256 next-raw-options 重现通用 PDF 对象在展开主体时与页面分配 顺序相反。pdfdraftmode 原语尚未接入。 +### pdfTeX 通用对象与页面导航编号 + +通用对象在展开主体或流属性前取得共享对象编号,主体完成后 +更新最后对象查询。实际发页登记命名、数字和结构目标,本地 +链接在写出动作时预留尚未出现的目标。复制链接的注释使用独立 +对象。注释和目标按实际写出顺序进入同一对象流,名字树通过 +真实间接引用连接目标,延迟写入可观察先前登记的编号。 +[pdfTeX 出页目标登记流程](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L34075-L34094) + +八组同源对照关闭八处编号差异,十四页 144 DPI 灰度图 +逐像素一致,核对 164 项压缩 XRef。二十一项链接、设备 +和图像定向回归通过。从检查点恢复后,先前页链接预留的目标 +保留,第二页更新,PDF、SVG 和来源映射与独立全量一致。 +回执在 target/p3-pdf-navigation-objects,SHA-256 为 502599fd1419ad22c5f3e87b7a4d680cecc71e5aac2a652bb7d5450e37b83f69。 + +续行注释的分配仍需与行首及延迟 I/O 共用遍历顺序。 +next-continuation 保留同一输入的两套 aux 差异。常规重复 +目标的警告细节和 pdfdraftmode 也仍待补齐。后者有七组原版 +对照检查已有 PDF、辅助文件、DVI 与锁定时机,记录在 +target/p3-pdf-draft-mode/reference.json。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/tests/native_pdf_links.rs b/tests/native_pdf_links.rs index 9c6b861..fbdb594 100644 --- a/tests/native_pdf_links.rs +++ b/tests/native_pdf_links.rs @@ -103,6 +103,103 @@ fn compile(root: &Path, source: &str, native: bool) -> Document { Document::load(work.join("probe.pdf")).unwrap() } +#[test] +fn raw_objects_and_destinations_allocate_before_later_page_queries() { + let root = std::env::temp_dir().join(format!("texrra-pdf-destination-order-{}", std::process::id())); + let source = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=5 \pdfcompresslevel=0 \pdfobjcompresslevel=1 +\pdfpagewidth=72bp \pdfpageheight=72bp \pdfhorigin=4bp \pdfvorigin=4bp +\def\space{ } +\pdfobj{<< /Probe \pdfpageref1 \space 0 R >>} +\count0=\pdflastobj +\message{MARK=\the\count0/\pdfpageref1;} +\immediate\openout0=probe.aux +\shipout\hbox{\pdfdest name{anchor} xyz \write0{MARK=\pdfpageref2;}\pdfrefobj\count0 + \vrule width4pt height6pt depth0pt} +\shipout\hbox{\vrule width4pt height6pt depth0pt} +\immediate\closeout0 +\end"; + compile(&root, source, false); + let pdf = compile(&root, source, true); + for engine in ["reference", "native"] { + let log = fs::read_to_string(root.join(engine).join("probe.log")).unwrap(); + assert!(log.contains("MARK=1/2;"), "{log}"); + } + let expected = fs::read(root.join("reference/probe.aux")).unwrap(); + assert_eq!(expected, b"MARK=6;\n"); + assert_eq!(fs::read(root.join("native/probe.aux")).unwrap(), expected); + let page = pdf.get_pages()[&1]; + let probe = pdf.objects.values().find_map(|object| { + object.as_dict().ok()?.get(b"Probe").ok()?.as_reference().ok() + }); + assert_eq!(probe, Some(page)); + let catalog = pdf.catalog().unwrap(); + let names = resolve(&pdf, catalog.get(b"Names").unwrap()).as_dict().unwrap(); + let dests = resolve(&pdf, names.get(b"Dests").unwrap()).as_dict().unwrap(); + let pairs = dests.get(b"Names").unwrap().as_array().unwrap(); + assert_eq!(pairs[0].as_str().unwrap(), b"anchor"); + let id = pairs[1].as_reference().unwrap(); + assert!(pdf.reference_table.get(id.0).unwrap().is_compressed()); + let dest = resolve(&pdf, &pairs[1]).as_dict().unwrap().get(b"D").unwrap().as_array().unwrap(); + assert_eq!(dest[0].as_reference().unwrap(), page); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn checkpoint_retains_a_link_target_reserved_by_an_earlier_page() { + use std::sync::Arc; + use texrra_engine::native::{ + CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot, + }; + use texrra_tex_core::{execution::JobTime, resources::WorldConfig}; + + let root = std::env::temp_dir().join(format!("texrra-pdf-link-checkpoint-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + let entry = root.join("probe.tex"); + let second = root.join("second.tex"); + let configuration = WorldConfig::new(&root); + let mut source = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=5 \pdfobjcompresslevel=1 +\pdfpagewidth=80pt \pdfpageheight=80pt \pdfhorigin=6pt \pdfvorigin=6pt +\shipout\hbox{\pdfstartlink goto name{anchor}\vrule width4pt height5pt \pdfendlink} +".to_owned(); + let line = format!("{}\n", "\\relax ".repeat(26)); + source.push_str(&line.repeat(40)); + source.push_str("\\input second.tex\n\\end\n"); + let original = br"\shipout\hbox{\pdfdest name{anchor} xyz \vrule width4pt height5pt}"; + let changed = br"\shipout\hbox{\kern6pt\pdfdest name{anchor} xyz \vrule width8pt height5pt}"; + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: configuration.clone(), + revision: 1, + roots: [root.clone()].into(), + files: [ + (entry.clone(), Arc::<[u8]>::from(source.into_bytes())), + (second.clone(), Arc::from(original.as_slice())), + ].into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [root.clone()].into(), + generated: Default::default(), + }).unwrap(); + let updated = project.with_file_edits(2, [(second, Arc::from(changed.as_slice()))].into()).unwrap(); + let time = JobTime::new(2026, 11, 27, 600).unwrap().with_pdf_clock(0, 0).unwrap(); + let mut request = CompileRequest::new(configuration, entry, "probe.pdf", time); + request.entry = Entry::Initex; + request.etex = true; + let live = NativeCompiler::default().with_automatic_entry_checkpoints(); + let first = live.compile(request.clone().with_project(project)).unwrap(); + let next = live.compile(request.clone().with_project(updated.clone())).unwrap(); + let cold = NativeCompiler::default().compile(request.with_project(updated)).unwrap(); + assert!(next.entry_checkpoint_work.reused_steps > 0); + assert_ne!(first.pdf, next.pdf); + assert_eq!(next.pdf, cold.pdf); + assert_eq!(next.source_map.pages, cold.source_map.pages); + assert_eq!(next.preview_since(None).unwrap().pages, cold.preview_since(None).unwrap().pages); + let patch = next.preview_since(Some(first.revision())).unwrap(); + assert_eq!(patch.pages.iter().map(|page| page.index).collect::>(), [1]); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn real_pdf_link_fragments_and_named_destination_match_pdftex() { let root = std::env::temp_dir().join(format!("texrra-pdf-links-{}", std::process::id()));