diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index c47ffda..2464abf 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -1013,6 +1013,9 @@ impl NativeBox { level, }; let mut cursor = y - self.height; + if links { + emit(edge, cursor, BoxPaint::RowStart(container)); + } let (mut cumulative, mut previous) = (0, 0); for node in nodes.iter() { budget.inside_leader(1)?; @@ -1112,7 +1115,8 @@ impl NativeBox { && !matches!(paint, BoxPaint::PdfLink(node, _) if matches!( node.operation, OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. } - | crate::pdf_device::links::LinkNode::Annotation { .. }) + | crate::pdf_device::links::LinkNode::Annotation { .. } + | crate::pdf_device::links::LinkNode::Thread { .. }) )) { 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 c86d69c..0ec6fff 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -681,6 +681,9 @@ impl Printer<'_> { self.command(match node { LinkNode::Start(_) => "pdfstartlink", LinkNode::Annotation { .. } => "pdfannot", + LinkNode::Thread { running: false, .. } => "pdfthread", + LinkNode::Thread { running: true, .. } => "pdfstartthread", + LinkNode::EndThread => "pdfendthread", LinkNode::End => "pdfendlink", LinkNode::Running(false) => "pdfrunninglinkoff", LinkNode::Running(true) => "pdfrunninglinkon", diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 5777810..3781ea0 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -230,6 +230,7 @@ pub struct Executor { xdv_colors: crate::pdf_device::xdv_color::ColorState, xdv_annotations: crate::pdf_device::xdv_annotation::AnnotationState, pdf_link_stack: Vec, + pdf_active_thread: Option, pdf_navigation_geometry: pdf_links::NavigationGeometry, pdf_running_links: bool, pdf_interword_spaces: bool, @@ -415,6 +416,7 @@ impl Executor { xdv_colors: Default::default(), xdv_annotations: Default::default(), pdf_link_stack: Vec::new(), + pdf_active_thread: None, pdf_navigation_geometry: Default::default(), pdf_running_links: true, pdf_interword_spaces: false, @@ -3713,6 +3715,16 @@ impl Executor { previous: Option<&Execution>, ) -> Result { self.collect_meaning_reads(); + let result = result.and_then(|()| { + if self.shipped_pages > 0 && !self.format_dumped + && let Some(objects) = self.state.pdf_objects.as_deref_mut() + { + let compress = self.state.pdf_header_options.is_some_and(|header| header.object_compression > 0); + objects.finish_threads(compress, self.limits.tokens) + .map_err(|message| self.error(message, self.current))?; + } + Ok(()) + }); if let Err(error) = result { use sha2::{Digest, Sha256}; let source_versions = self diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index 2a10264..bbad230 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -30,7 +30,8 @@ impl Executor { Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => { self.scan_pdf_graphics(primitive, token.span, files)? } - Pdfannot | Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => { + Pdfannot | Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon + | Pdfthread | Pdfstartthread | Pdfendthread => { self.scan_pdf_link(primitive, token.span, files)?; } Pdfinterwordspaceon | Pdfinterwordspaceoff | Pdffakespace | Pdfspacefont => { diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index b54a60c..478b602 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -289,13 +289,15 @@ impl Executor { 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()), + AnnotationAction::Catalog(action @ (CatalogAction::GoTo { file: None, .. } + | CatalogAction::Thread { 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(); + let beads: Vec<_> = shipout.pdf_links.thread_beads.iter().map(|bead| bead.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(); @@ -311,6 +313,13 @@ impl Executor { for number in destinations { self.pack_pdf_object(number)?; } + for bead in beads { + self.reads.insert(Dependency::PdfObjects); + let rectangle = self.state.pdf_objects.as_deref_mut().expect("registered thread bead") + .new_bead_rectangle(bead, self.limits.tokens) + .map_err(|error| self.error(error, self.current))?; + self.pack_pdf_object(rectangle)?; + } self.pack_pdf_object(resources)?; } self.statistics_after_shipout(before, files)?; @@ -491,10 +500,17 @@ impl Executor { let output_count = outputs.len(); let has_link_material = !self.pdf_link_stack.is_empty() || outputs.iter().any(|node| node.is_pdf_link()); let mut pdf_link_shipout = (!for_form && device.pdf.is_some() - && (has_link_material || outputs.iter().any(|node| { + && (has_link_material || self.pdf_active_thread.is_some() || outputs.iter().any(|node| { matches!(node.operation, OutputOperation::PdfSetMatrix(_)) }))) - .then(|| self.begin_pdf_link_shipout(b, device)); + .then(|| { + let thread_rows = self.pdf_active_thread.is_some() || outputs.iter().any(|node| { + matches!(node.operation, OutputOperation::PdfLink( + crate::pdf_device::links::LinkNode::Thread { running: true, .. } + )) + }); + self.begin_pdf_link_shipout(b, device, thread_rows) + }); let mut output_positions = if let Some(effects) = &leader_effects { effects.output_positions.clone().into_iter() } else if outputs.iter().any(|node| node.needs_shipout_position()) { @@ -749,6 +765,13 @@ impl Executor { { return Err(self.error("annotations cannot be inside an XForm", node.span)); } + if let Some(node) = first + && matches!(node.operation, OutputOperation::PdfLink( + crate::pdf_device::links::LinkNode::Thread { .. } + )) + { + return Err(self.error("threads cannot be inside an XForm", node.span)); + } return self.fail("PDF page links and destinations require a page shipout"); } for usage in font_uses { 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 e95b78d..300cb4d 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs @@ -209,6 +209,14 @@ impl Executor { if enabled { // An action allocates a PDF object at the command boundary. self.pdf_page_data(files)?; + if matches!(&action, CatalogAction::Thread { .. }) { + self.reads.insert(Dependency::PdfObjects); + let number = self.state.pdf_objects.get_or_insert_with(Default::default) + .allocate_thread_open_action(self.limits.tokens) + .map_err(|message| self.error(message, self.current))?; + self.pack_pdf_object(number)?; + self.write_pdf_link_action(&action)?; + } self.state .pdf_catalog .get_or_insert_with(Default::default) 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 5f66d3b..56b4429 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -4,7 +4,7 @@ use crate::pdf_device::{ catalog::{CatalogAction, CatalogTarget, StructureTarget}, links::{ AnnotationAction, DestinationId, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart, - PageDestination, PageLinks, + PageDestination, PageLinks, ThreadBead, }, }; use crate::execution::boxes::{BoxPaint, BoxLayout}; @@ -26,6 +26,13 @@ pub(super) struct ActiveLink { segment: Option, } +#[derive(Clone)] +pub(super) struct ActiveThread { + destination: DestinationId, + dimensions: [Option; 3], + level: usize, +} + enum LinkPaint { Graphics, RowStart(BoxLayout), @@ -36,6 +43,7 @@ pub(super) struct PdfLinkShipout { events: std::iter::Peekable>, output_count: usize, active: Vec, + thread: Option, geometry: NavigationGeometry, saved: Vec>, page_height: i64, @@ -184,6 +192,23 @@ impl Executor { self.state.pdf_objects.as_mut().unwrap().record_last_annotation(object_number); LinkNode::Annotation { object_number, dimensions, entries } } + Primitive::Pdfthread | Primitive::Pdfstartthread => { + let dimensions = self.scan_pdf_rule(files)?; + let attributes = self.keyword("attr", files)?.then(|| self.scan_pdf_tokens(files)).transpose()?; + let destination = if self.keyword("num", files)? { + let number = self.positive_pdf_number("thread identifier", files)?; + if number > 268_435_455 { + return self.fail("PDF thread number too big"); + } + DestinationId::Number(number) + } else if self.keyword("name", files)? { + DestinationId::Name(self.scan_pdf_tokens(files)?) + } else { + return self.fail("expected a PDF thread identifier"); + }; + LinkNode::Thread { destination, dimensions, attributes, running: command == Primitive::Pdfstartthread } + } + Primitive::Pdfendthread => LinkNode::EndThread, Primitive::Pdfstartlink => { self.reads.insert(Dependency::PdfObjects); let object_number = self @@ -322,6 +347,13 @@ impl Executor { } pub(super) fn write_pdf_link_action(&mut self, action: &CatalogAction) -> Result<(), Error> { + if let CatalogAction::Thread { destination, file: None } = action { + self.reads.insert(Dependency::PdfObjects); + self.state.pdf_objects.get_or_insert_with(Default::default) + .thread_number(destination.clone(), self.limits.tokens) + .map_err(|message| self.error(message, self.current))?; + return Ok(()); + } let CatalogAction::GoTo { target, file: None, structure, .. } = action else { return Ok(()); }; @@ -349,7 +381,7 @@ impl Executor { } pub(super) fn begin_pdf_link_shipout( - &mut self, b: &NativeBox, device: &ShipoutDevice, + &mut self, b: &NativeBox, device: &ShipoutDevice, thread_rows: bool, ) -> PdfLinkShipout { let mut output_count = 0; let mut paint_count = 0; @@ -359,7 +391,8 @@ impl Executor { b.walk_pdf_links(&mut |x, y, item| match item { BoxPaint::Output(_) => output_count += 1, BoxPaint::Box(_) => paint_count += 1, - BoxPaint::RowStart(row) => events.push(((output_count, paint_count), x, y, LinkPaint::RowStart(row))), + BoxPaint::RowStart(row) if row.horizontal || thread_rows => + events.push(((output_count, paint_count), x, y, LinkPaint::RowStart(row))), BoxPaint::PdfLink(_, row) => events.push(((output_count, paint_count), x, y, LinkPaint::Node(row))), BoxPaint::PdfGraphics => events.push(((output_count, paint_count), x, y, LinkPaint::Graphics)), _ => {} @@ -369,6 +402,7 @@ impl Executor { events: events.into_iter().peekable(), output_count, active: std::mem::take(&mut self.pdf_link_stack), + thread: self.pdf_active_thread.take(), geometry: if numbered { self.pdf_navigation_geometry } else { NavigationGeometry::default() }, saved: Vec::new(), page_height: device.page_height, @@ -383,6 +417,23 @@ impl Executor { } impl PdfLinkShipout { + fn add_bead( + &mut self, executor: &mut Executor, destination: DestinationId, rect: [i64; 4], attributes: Option>, + ) -> Result<(), Error> { + executor.reads.insert(Dependency::PdfObjects); + let margin = i64::from(executor.read_parameter(Parameter::Pdfthreadmargin).width()); + let limit = executor.limits.tokens; + let objects = executor.state.pdf_objects.get_or_insert_with(Default::default); + let allocation = objects.thread_number(destination.clone(), limit) + .and_then(|thread| objects.new_bead(thread, limit).map(|number| (thread, number))); + let (thread, number) = allocation.map_err(|error| executor.error(error, executor.current))?; + self.output.thread_beads.push(ThreadBead { + number, thread, destination, attributes, + rect: self.geometry.rectangle(rect, self.page_height, margin), + }); + Ok(()) + } + pub(super) fn advance( &mut self, executor: &mut Executor, through: (usize, usize), outputs: &[&OutputNode], graphics: &[Option], @@ -424,6 +475,15 @@ impl PdfLinkShipout { Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary) | None => {} } } + LinkPaint::RowStart(row) if !row.horizontal => { + if let Some(thread) = &self.thread + && thread.level == row.level && thread.dimensions[2].is_none() + && !self.output.thread_beads.is_empty() + { + let rect = rule_rectangle(absolute_row(row), [x, y], thread.dimensions); + self.add_bead(executor, thread.destination.clone(), rect, None)?; + } + } LinkPaint::RowStart(row) if executor.pdf_running_links => { for link in self.active.iter_mut().filter(|link| { link.level == row.level && link.layout.width.is_none() @@ -452,6 +512,35 @@ impl PdfLinkShipout { action: AnnotationAction::Direct(executor.pdf_token_bytes(entries)?), }); } + LinkNode::Thread { destination, dimensions, attributes, running } => { + if *running && container.horizontal { + return executor.fail("\\pdfstartthread ended up in hlist"); + } + let destination = executor.pdf_destination_id(destination); + let attributes = attributes.as_deref() + .map(|tokens| executor.pdf_token_bytes(tokens)).transpose()?; + let rect = rule_rectangle(container, [x, y], *dimensions); + if *running { + self.thread = Some(ActiveThread { + destination: destination.clone(), dimensions: *dimensions, + level: container.level, + }); + } + self.add_bead(executor, destination, rect, attributes)?; + } + LinkNode::EndThread => { + if container.horizontal { + return executor.fail("\\pdfendthread ended up in hlist"); + } + let Some(thread) = self.thread.take().filter(|thread| thread.level == container.level) else { + return executor.fail("\\pdfendthread ended up in different nesting level than \\pdfstartthread"); + }; + if thread.dimensions[2].is_none() + && let Some(bead) = self.output.thread_beads.last_mut() + { + bead.rect[3] = y + i64::from(executor.read_parameter(Parameter::Pdfthreadmargin).width()); + } + } LinkNode::Start(layout) => { if self.active.len() == 10 { return executor.fail("PDF link stack capacity exceeded"); @@ -546,6 +635,7 @@ impl PdfLinkShipout { link.segment = None; } executor.pdf_link_stack = self.active; + executor.pdf_active_thread = self.thread; if self.numbered { executor.pdf_navigation_geometry = self.geometry; } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 28f7e0c..7cbaddb 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -16,9 +16,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 104; -const COMPATIBLE_SCHEMAS: [u32; 70] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, SCHEMA, +const SCHEMA: u32 = 105; +const COMPATIBLE_SCHEMAS: [u32; 71] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -226,6 +226,9 @@ impl FormatImage { if image.schema < 104 { image.state.install_pdf_annotation_commands(); } + if image.schema < 105 { + image.state.install_pdf_thread_commands(); + } let pdf_objects = image.state.pdf_objects.as_deref(); let mut numbered_images = 0; for (index, saved) in image.pdf_images.iter().enumerate() { diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 7fd4620..6ec4d89 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -47,6 +47,7 @@ pub enum Parameter { Pdfvorigin, Pdflinkmargin, Pdfdestmargin, + Pdfthreadmargin, Errorcontextlines, Showboxbreadth, Showboxdepth, @@ -185,6 +186,7 @@ impl Parameter { | Self::Pdfvorigin | Self::Pdflinkmargin | Self::Pdfdestmargin + | Self::Pdfthreadmargin | Self::Pdfprotrudechars | Self::Pdfprependkern | Self::Pdfappendkern @@ -252,6 +254,7 @@ impl Parameter { Self::Pdfvorigin, Self::Pdflinkmargin, Self::Pdfdestmargin, + Self::Pdfthreadmargin, Self::Errorcontextlines, Self::Showboxbreadth, Self::Showboxdepth, @@ -377,6 +380,7 @@ impl Parameter { | Self::Pdfvorigin | Self::Pdflinkmargin | Self::Pdfdestmargin + | Self::Pdfthreadmargin | Self::Delimitershortfall | Self::Predisplaysize | Self::Displaywidth diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 3beb356..75489b5 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -117,6 +117,9 @@ pub enum Primitive { Pdfsave, Pdfstartlink, Pdfannot, + Pdfthread, + Pdfstartthread, + Pdfendthread, Pdfendlink, Pdfrunninglinkoff, Pdfrunninglinkon, @@ -972,6 +975,9 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = { ("pdfsave", Pdfsave), ("pdfstartlink", Pdfstartlink), ("pdfannot", Pdfannot), + ("pdfthread", Pdfthread), + ("pdfstartthread", Pdfstartthread), + ("pdfendthread", Pdfendthread), ("pdfendlink", Pdfendlink), ("pdfrunninglinkoff", Pdfrunninglinkoff), ("pdfrunninglinkon", Pdfrunninglinkon), @@ -1989,6 +1995,18 @@ impl State { } } + pub(super) fn install_pdf_thread_commands(&mut self) { + let enabled = self.input_profile != super::InputProfile::XeTeX; + for (name, primitive) in [ + ("pdfthread", Primitive::Pdfthread), + ("pdfstartthread", Primitive::Pdfstartthread), + ("pdfendthread", Primitive::Pdfendthread), + ] { + self.update_profile_command(name, Meaning::Primitive(primitive), enabled); + } + self.update_profile_command("pdfthreadmargin", Meaning::Parameter(Parameter::Pdfthreadmargin), enabled); + } + fn install_pdftex_primitives(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; for &(name, primitive) in PDFTEX_ONLY_PRIMITIVES { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index f2ca069..0296fb2 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2042,6 +2042,7 @@ struct PdfNavigation { structures: BTreeMap, usize>, pending_destinations: BTreeMap<(DestinationId, bool), usize>, threads: BTreeMap, usize>, + pending_threads: BTreeMap, usize>, } fn write_destination(objects: &mut Vec>, slot: Option, body: String) -> usize { @@ -2067,7 +2068,7 @@ fn catalog_action_bytes( objects: &mut Vec>, diagnostics: &mut Vec, ) -> Vec { - let PdfNavigation { pages, named, numbered, structures, pending_destinations, threads } = destinations; + let PdfNavigation { pages, named, numbered, structures, pending_destinations, threads, pending_threads } = destinations; let mut output = b"<< ".to_vec(); match action { CatalogAction::User(object) => output.clone_from(object), @@ -2165,9 +2166,12 @@ fn catalog_action_bytes( "thread destination {identifier} has been referenced but does not exist, replaced by a fixed one" )); // Link the missing thread's single empty bead to the first page. - let thread = objects.len() + 1; - let bead = thread + 1; - objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes()); + let thread = pending_threads.get(destination).copied().unwrap_or_else(|| { + objects.push(Vec::new()); + objects.len() + }); + let bead = objects.len() + 1; + objects[thread - 1] = 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] >>", pages[0] @@ -2815,6 +2819,31 @@ fn write_pdf( } } } + let mut bead_slots = BTreeMap::new(); + if let Some(registry) = registry { + let defined: BTreeSet<_> = pages.iter().flat_map(|page| &page.pdf_links.thread_beads) + .map(|bead| bead.thread).collect(); + let mut threads: Vec<_> = registry.threads().collect(); + threads.sort_unstable_by_key(|&(_, number)| number); + for (id, number) in threads { + objects.push(Vec::new()); + let slot = objects.len(); + device_objects.insert(number, slot as u32); + let map = if defined.contains(&number) { &mut navigation.threads } else { &mut navigation.pending_threads }; + map.insert(id.clone(), slot); + } + for (bead, rectangle) in registry.bead_rectangles() { + objects.extend([Vec::new(), Vec::new()]); + let slots = (objects.len() - 1, objects.len()); + device_objects.insert(bead, slots.0 as u32); + device_objects.insert(rectangle, slots.1 as u32); + bead_slots.insert(bead, slots); + } + for number in registry.thread_open_action().into_iter().chain(registry.thread_array()) { + objects.push(Vec::new()); + device_objects.insert(number, objects.len() as u32); + } + } let parents: BTreeSet<_> = pages.iter().filter_map(|page| { page.pdf_resources.objects.map(|allocation| allocation.parent) }).collect(); @@ -2852,6 +2881,8 @@ fn write_pdf( let mut page_groups = BTreeMap::>::new(); let mut annotation_actions = Vec::new(); let mut xdv_annotations = Vec::new(); + // Each triple records the bead, its page, and its rectangle object. + let mut thread_rings: BTreeMap> = BTreeMap::new(); let pdf_version = pages .first() .and_then(|page| page.pdf.as_ref()) @@ -3099,6 +3130,16 @@ fn write_pdf( } else { format!(" /Annots [{annotation_refs}]") }; + let mut bead_references = String::new(); + for bead in &list.pdf_links.thread_beads { + let &(bead_id, rectangle_id) = bead_slots.get(&bead.number).ok_or("missing PDF bead allocation")?; + bead_references.push_str(&format!(" {bead_id} 0 R")); + let [left, top, right, bottom] = bead.rect; + let rect = [left, height - bottom, right, height - top].map(physical).join(" "); + objects[rectangle_id - 1] = format!("[{rect}]").into_bytes(); + thread_rings.entry(bead.thread).or_default().push((bead_id, page_id, rectangle_id)); + } + let beads = if bead_references.is_empty() { String::new() } else { format!(" /B [{bead_references} ]") }; navigation.pages.push(page_id); kids.push(page_id); if parent != 2 { @@ -3135,9 +3176,9 @@ fn write_pdf( if decorated { page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes()); page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]); - page.extend_from_slice(format!(" /Parent {parent} 0 R{annots}{png_group_ref} >>").as_bytes()); + page.extend_from_slice(format!(" /Parent {parent} 0 R{annots}{beads}{png_group_ref} >>").as_bytes()); } else { - page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes()); + page.extend_from_slice(format!("{annots}{beads} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes()); } if let Some(id) = reserved_page { objects[id - 1] = page; @@ -3321,6 +3362,33 @@ fn write_pdf( } objects[1].extend_from_slice(b" >>"); + if let Some(registry) = registry { + for (destination, number) in registry.threads() { + let Some(ring) = thread_rings.remove(&number) else { continue }; + let thread = device_objects[&number] as usize; + let first = ring[0].0; + let mut body = b"<< ".to_vec(); + if let Some(entries) = remapped.as_ref().and_then(|resources| resources.thread_attributes.get(&number)) { + body.extend_from_slice(entries); + } else { + let title = match destination { + DestinationId::Name(name) => name.clone(), + DestinationId::Number(number) => number.to_string(), + }; + write!(&mut body, "/I << /Title {} >>", pdf_text(&title)).unwrap(); + } + write!(&mut body, " /F {first} 0 R >>").unwrap(); + objects[thread - 1] = body; + for (index, &(bead, page, rectangle)) in ring.iter().enumerate() { + let previous = ring[(index + ring.len() - 1) % ring.len()].0; + let next = ring[(index + 1) % ring.len()].0; + let owner = if index == 0 { format!("/T {thread} 0 R ") } else { String::new() }; + objects[bead - 1] = format!( + "<< {owner}/V {previous} 0 R /N {next} 0 R /P {page} 0 R /R {rectangle} 0 R >>" + ).into_bytes(); + } + } + } 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)); @@ -3408,15 +3476,23 @@ fn write_pdf( catalog.push_str(&format!(" /Outlines {root_id} 0 R")); } let extra = unicode.and_then(|options| options.catalog); - let mut action_object = |action| { + let mut action_object = |action, slot: Option| { let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics); - objects.push(body); - objects.len() + if let Some(slot) = slot { + objects[slot - 1] = body; + slot + } else { + objects.push(body); + objects.len() + } }; - let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object); + let open_action_slot = registry.and_then(|registry| registry.thread_open_action()) + .map(|number| device_objects[&number] as usize); + let action = extra.and_then(|extra| extra.open_action.as_ref()) + .map(|action| action_object(action, open_action_slot)); if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) { let action_ids: Vec<_> = extra.outlines.iter() - .map(|outline| action_object(&outline.action)) + .map(|outline| action_object(&outline.action, None)) .collect(); let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects); catalog.push_str(&format!(" /Outlines {outlines} 0 R")); @@ -3449,8 +3525,10 @@ fn write_pdf( 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 slot = registry.and_then(|registry| registry.thread_array()) + .map(|number| device_objects[&number] as usize); + let id = write_destination(&mut objects, slot, format!("[{}]", references.join(" "))); + catalog.push_str(&format!(" /Threads {id} 0 R")); } let destinations = navigation.named; let mut xdv_destinations = BTreeMap::new(); diff --git a/crates/texrra-tex-core/src/pdf_device/links.rs b/crates/texrra-tex-core/src/pdf_device/links.rs index 1d88bfa..17f983c 100644 --- a/crates/texrra-tex-core/src/pdf_device/links.rs +++ b/crates/texrra-tex-core/src/pdf_device/links.rs @@ -65,6 +65,13 @@ pub enum LinkNode { dimensions: [Option; 3], entries: Vec, }, + Thread { + destination: DestinationId>, + dimensions: [Option; 3], + attributes: Option>, + running: bool, + }, + EndThread, Start(LinkStart), End, Running(bool), @@ -105,11 +112,24 @@ pub struct PageDestination { pub structure: Option, } +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ThreadBead { + pub number: u32, + pub thread: u32, + pub destination: DestinationId, + /// Left, top, right and bottom in TeX sp, with y measured down the page. + pub rect: [i64; 4], + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attributes: Option>, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct PageLinks { pub annotations: Vec, pub destinations: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub thread_beads: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) xdv_destinations: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) xdv_annotations: Vec, @@ -119,6 +139,7 @@ impl PageLinks { pub(crate) fn is_empty(&self) -> bool { self.annotations.is_empty() && self.destinations.is_empty() + && self.thread_beads.is_empty() && self.xdv_destinations.is_empty() && self.xdv_annotations.is_empty() } 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 16eba78..9a44972 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -45,6 +45,11 @@ pub(crate) enum ObjectBody { }, ObjectStream, Destination, + Thread, + Bead, + BeadRectangle, + ThreadOpenAction, + ThreadArray, ImportedImage, ImportedFont, } @@ -55,7 +60,8 @@ impl ObjectBody { Self::Page | Self::Annotation | Self::FormatAnnotation | Self::ReservedAnnotation | Self::Form | Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream - | Self::Destination | Self::ImportedImage | Self::ImportedFont | Self::DiscardedAtDump => 0, + | Self::Destination | Self::Thread | Self::Bead | Self::BeadRectangle + | Self::ThreadOpenAction | Self::ThreadArray | Self::ImportedImage | Self::ImportedFont | Self::DiscardedAtDump => 0, Self::Direct(bytes) => bytes.len(), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), Self::File { @@ -75,7 +81,8 @@ impl ObjectBody { Self::Page | Self::Annotation | Self::FormatAnnotation | Self::ReservedAnnotation | Self::Form | Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream - | Self::Destination | Self::ImportedImage | Self::ImportedFont => { + | Self::Destination | Self::Thread | Self::Bead | Self::BeadRectangle + | Self::ThreadOpenAction | Self::ThreadArray | Self::ImportedImage | Self::ImportedFont => { Err("expected a generic native PDF object".into()) } Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()), @@ -140,6 +147,16 @@ pub struct PdfObjects { #[serde(skip)] destination_numbers: BTreeMap<(DestinationId, bool), (u32, bool)>, #[serde(skip)] + thread_numbers: BTreeMap, u32>, + #[serde(skip)] + bead_rectangles: BTreeMap, + #[serde(skip)] + thread_open_action: Option, + #[serde(skip)] + thread_array: Option, + #[serde(skip)] + bead_owners: BTreeMap, + #[serde(skip)] shipped_annotations: BTreeSet, // Source object numbers belong to one particular version of one file. #[serde(skip)] @@ -438,6 +455,72 @@ impl PdfObjects { self.last_annotation.unwrap_or_default() as i32 } + pub(crate) fn allocate_thread_open_action(&mut self, limit: usize) -> Result { + let number = self.allocate(Some(Arc::new(ObjectBody::ThreadOpenAction)), limit)?; + self.thread_open_action = Some(number); + Ok(number) + } + + pub(crate) fn thread_open_action(&self) -> Option { + self.thread_open_action + } + + pub(crate) fn thread_number(&mut self, destination: DestinationId, limit: usize) -> Result { + if let Some(&number) = self.thread_numbers.get(&destination) { + return Ok(number); + } + let number = self.allocate(Some(Arc::new(ObjectBody::Thread)), limit)?; + self.thread_numbers.insert(destination, number); + Ok(number) + } + + pub(crate) fn new_bead(&mut self, thread: u32, limit: usize) -> Result { + let bead = self.allocate(Some(Arc::new(ObjectBody::Bead)), limit)?; + self.bead_owners.insert(bead, thread); + Ok(bead) + } + + pub(crate) fn finish_threads(&mut self, compress: bool, limit: usize) -> Result<(), String> { + if self.thread_numbers.is_empty() { + return Ok(()); + } + let array = self.allocate(Some(Arc::new(ObjectBody::ThreadArray)), limit)?; + self.thread_array = Some(array); + if compress { + self.pack_object(array, limit)?; + let mut threads: BTreeMap<_, Vec<_>> = self.thread_numbers.values() + .map(|&thread| (thread, Vec::new())).collect(); + for (&bead, &thread) in &self.bead_owners { + threads.get_mut(&thread).expect("registered article thread").push(bead); + } + for (thread, beads) in threads.into_iter().rev() { + self.pack_object(thread, limit)?; + for bead in beads { + self.pack_object(bead, limit)?; + } + } + } + Ok(()) + } + + pub(crate) fn thread_array(&self) -> Option { + self.thread_array + } + + pub(crate) fn new_bead_rectangle(&mut self, bead: u32, limit: usize) -> Result { + let rectangle = self.allocate(Some(Arc::new(ObjectBody::BeadRectangle)), limit)?; + self.bead_rectangles.insert(bead, rectangle); + Ok(rectangle) + } + + pub(crate) fn threads(&self) -> impl Iterator, u32)> { + self.thread_numbers.iter().map(|(destination, &number)| (destination, number)) + } + + pub(crate) fn bead_rectangles(&self) -> impl Iterator + '_ { + self.bead_rectangles.iter().map(|(&bead, &rectangle)| (bead, rectangle)) + } + pub(crate) fn destination_is_defined(&self, id: DestinationId, structure: bool) -> bool { self.destination_numbers .get(&(id, structure)) @@ -480,7 +563,9 @@ impl PdfObjects { Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources | ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_) | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination - | ObjectBody::ImportedImage | ObjectBody::ImportedFont) => { + | ObjectBody::ImportedImage | ObjectBody::ImportedFont + | ObjectBody::Thread | ObjectBody::Bead | ObjectBody::BeadRectangle + | ObjectBody::ThreadOpenAction | ObjectBody::ThreadArray) => { ObjectBody::DiscardedAtDump } _ if self.written.contains(&number) => ObjectBody::DiscardedAtDump, @@ -500,6 +585,11 @@ impl PdfObjects { self.written_png_group = None; self.object_streams.clear(); self.destination_numbers.clear(); + self.thread_numbers.clear(); + self.bead_rectangles.clear(); + self.thread_open_action = None; + self.thread_array = None; + self.bead_owners.clear(); self.shipped_annotations.clear(); self.imported_images.clear(); self.imported_type1.clear(); @@ -805,6 +895,7 @@ pub(crate) struct ResourceOutput { page_tree_attributes: Dictionary, font_entries: BTreeMap, annotation_entries: Vec>>, + thread_attributes: BTreeMap, catalog: Option, info: Option, } @@ -820,6 +911,7 @@ pub(crate) struct RemappedResources { pub structure_objects: BTreeMap, pub object_numbers: BTreeMap, pub annotations: Vec>>>, + pub thread_attributes: BTreeMap>, pub catalog: Option>, pub info: Option>, } @@ -881,11 +973,17 @@ impl ResourceOutput { let page_tree_attributes = parse_entries(page_tree)?; let catalog = catalog.map(parse_entries).transpose()?; let info = info.map(parse_entries).transpose()?; + let thread_attributes = pages.iter().flat_map(|page| &page.pdf_links.thread_beads) + .filter_map(|bead| bead.attributes.as_deref().map(|entries| (bead.thread, entries))) + .collect::>() + .into_iter().map(|(thread, entries)| Ok((thread, parse_entries(entries)?))) + .collect::, String>>()?; let mut pending = objects.written.clone(); for dictionary in page_entries.iter() .chain(&page_attributes) .chain(std::iter::once(&page_tree_attributes)) .chain(font_entries.values()) + .chain(thread_attributes.values()) .chain(&catalog) .chain(&info) { @@ -968,7 +1066,9 @@ impl ResourceOutput { || 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 - | ObjectBody::Destination | ObjectBody::ImportedImage | ObjectBody::ImportedFont)) + | ObjectBody::Destination | ObjectBody::ImportedImage | ObjectBody::ImportedFont + | ObjectBody::Thread | ObjectBody::Bead | ObjectBody::BeadRectangle + | ObjectBody::ThreadOpenAction | ObjectBody::ThreadArray)) { continue; } @@ -1002,6 +1102,7 @@ impl ResourceOutput { page_tree_attributes, font_entries, annotation_entries, + thread_attributes, catalog, info, }) @@ -1102,6 +1203,8 @@ impl ResourceOutput { annotations: self.annotation_entries.into_iter() .map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect()) .collect(), + thread_attributes: self.thread_attributes.into_iter() + .map(|(thread, dictionary)| (thread, encode(dictionary))).collect(), catalog: self.catalog.map(&encode), info: self.info.map(encode), object_numbers: ids, diff --git a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs index 4d00547..a0f5dbf 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs @@ -860,3 +860,105 @@ fn direct_annotations_keep_reserved_references_and_copy_geometry() { }; assert_eq!(inspect(&native), inspect(&reference)); } + +#[test] +fn article_thread_links_real_beads_between_boxes_and_pages() { + let body = r"\pdfpagewidth=200pt \pdfpageheight=200pt \pdfthreadmargin=1pt + \def\space{ } + \immediate\pdfobj{(Creator)}\edef\author{\the\pdflastobj} + \pdfcatalog{} openaction thread num7 + \shipout\vbox{ + \vbox{\pdfstartthread width20pt attr{/I << /Title (start) >>} num7 + \hbox{\vrule width20pt height5pt depth2pt}\kern3pt} + \kern6pt + \vbox{\hbox{\vrule width21pt height7pt}\kern4pt\pdfendthread\kern11pt}} + \pdfpageheight=230pt + \shipout\hbox{\pdfsave\pdfsetmatrix{0 1 -1 0}\kern9pt + \pdfthread width13pt height6pt depth2pt + attr{/I << /Title (final) /Creator \author\space 0 R >>} num7 + \kern-9pt\pdfrestore\vrule width15pt height5pt}"; + + let inspect = |pdf: &Document| { + let catalog = pdf.catalog().unwrap(); + let threads = get(pdf, catalog, b"Threads").as_array().unwrap(); + let [thread] = threads.as_slice() else { + panic!("expected one article thread"); + }; + let thread_id = thread.as_reference().unwrap(); + let thread = pdf.get_dictionary(thread_id).unwrap(); + let info = get(pdf, thread, b"I").as_dict().unwrap(); + assert_eq!(get(pdf, info, b"Title").as_str().unwrap(), b"final"); + assert_eq!(get(pdf, info, b"Creator").as_str().unwrap(), b"Creator"); + let open = get(pdf, catalog, b"OpenAction").as_dict().unwrap(); + assert_eq!(get(pdf, open, b"S").as_name().unwrap(), b"Thread"); + assert_eq!(open.get(b"D").unwrap().as_reference().unwrap(), thread_id); + + let pages: Vec<_> = pdf.get_pages().into_values().collect(); + let beads: Vec<_> = pages + .iter() + .map(|page| { + get(pdf, pdf.get_dictionary(*page).unwrap(), b"B") + .as_array() + .unwrap() + }) + .collect(); + assert_eq!( + beads.iter().map(|beads| beads.len()).collect::>(), + [2, 1] + ); + let ring: Vec<_> = beads + .iter() + .flat_map(|beads| beads.iter()) + .map(|bead| bead.as_reference().unwrap()) + .collect(); + assert_eq!(ring[0], thread.get(b"F").unwrap().as_reference().unwrap()); + ring.iter() + .enumerate() + .map(|(index, id)| { + let bead = pdf.get_dictionary(*id).unwrap(); + assert_eq!( + bead.get(b"V").unwrap().as_reference().unwrap(), + ring[(index + 2) % 3] + ); + assert_eq!( + bead.get(b"N").unwrap().as_reference().unwrap(), + ring[(index + 1) % 3] + ); + assert_eq!( + bead.get(b"P").unwrap().as_reference().unwrap(), + pages[usize::from(index == 2)] + ); + if index == 0 { + assert_eq!(bead.get(b"T").unwrap().as_reference().unwrap(), thread_id); + } else { + assert!(bead.get(b"T").is_err()); + } + get(pdf, bead, b"R") + .as_array() + .unwrap() + .iter() + .map(|coordinate| match coordinate { + Object::Integer(value) => *value as f64, + Object::Real(value) => f64::from(*value), + other => panic!("expected a bead coordinate, found {other:?}"), + }) + .collect::>() + }) + .collect::>() + }; + let (reference, native, diagnostics) = pair(body); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + let expected = inspect(&reference); + assert_eq!(inspect(&native), expected); + + // lopdf 0.26 cannot resolve the catalog in pdfTeX's compressed output. + let compressed = [r"\pdfminorversion=5 \pdfobjcompresslevel=3 ", body].concat(); + let (_, native, diagnostics) = pair(&compressed); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + assert!(native.objects.values().any(|object| { + object + .as_stream() + .is_ok_and(|stream| stream.dict.type_is(b"ObjStm")) + })); + assert_eq!(inspect(&native), expected); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9dfaa77..24fd232 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,36 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 原生 PDF 阅读线程 + +pdfTeX 模式执行 \pdfthread、\pdfstartthread、\pdfendthread 和 +\pdfthreadmargin。显式阅读区域按线程号或名称跨页组成双向环。 +同一页上,未指定深度的活动线程在相同嵌套层的竖直盒续接。 +出页生成目录 /Threads、页面 /B、区域矩形和实际对象引用。前置 +数字跳转或 OpenAction 先保留线程编号,后续区域复用该编号。 +最后一次显式属性一并解析其中的间接引用。线程、区域和矩形 +按设备设置进入 PDF 对象流。 +[pdfTeX 的线程出页实现](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L36588-L36671) +· [线程字典及属性](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L35464-L35531) + +七组参考对照共 14 页。核对了矩形、旋转和页高、线程属性、 +页面归属、双向引用及跳转,并逐页比较 144 DPI 灰度光栅。 +实际 article.cls 作业加载已有原样 pdflatex.ini 生成的格式, +两页的 41 个原始字形、aux 和光栅一致。schema105 保存实际 +线程盒,重载后的两页结果和对象查询 13 一致。旧 schema104 +的同名用户宏保持原定义。发布构建及 27 项定向回归通过。 +lopdf 0.26 无法读取该参考 PDF 的压缩目录,保留首次失败。 +压缩图分别解包两端的对象流核对全部线程引用,并由 Poppler +实际渲染两页比对。 + +三页项目先在首页定义线程,第二页从子文件追加区域。往返 +编辑各复用 1,192 步,仅更新第二页。每轮 PDF、页面、SVG、 +来源映射、日志和辅助文件与独立全量一致,前后两页保留同一 +线程身份。此次未做整批模板回归或正式延迟采样。 + +回执在 target/p3-native-pdf-thread,receipt.json 的 SHA-256 为 +8058f98f51987ab9c0b25f9009665e1e7a38667128617033a584489e891bca15。 + ## 2026-11-28 原生 PDF 注释 pdfTeX 模式执行 \pdfannot、reserveobjnum、useobjnum 和