diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 7cd3037..c47ffda 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -1111,7 +1111,8 @@ impl NativeBox { OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. })) && !matches!(paint, BoxPaint::PdfLink(node, _) if matches!( node.operation, - OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. }) + OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. } + | crate::pdf_device::links::LinkNode::Annotation { .. }) )) { 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 4dab6f3..c86d69c 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -680,13 +680,28 @@ impl Printer<'_> { use crate::pdf_device::links::LinkNode; self.command(match node { LinkNode::Start(_) => "pdfstartlink", + LinkNode::Annotation { .. } => "pdfannot", LinkNode::End => "pdfendlink", LinkNode::Running(false) => "pdfrunninglinkoff", LinkNode::Running(true) => "pdfrunninglinkon", LinkNode::Destination { .. } => "pdfdest", }); - if let LinkNode::Destination { structure: Some(object), .. } = node { - self.literal(&format!(" struct{object}")); + match node { + LinkNode::Annotation { dimensions: [width, height, depth], entries, .. } => { + for (separator, dimension) in [("(", height), ("+", depth), (")x", width)] { + self.literal(separator); + if let Some(value) = dimension { + self.number(i64::from(*value)); + } else { + self.literal("*"); + } + } + self.tokens(entries)?; + } + LinkNode::Destination { structure: Some(object), .. } => { + self.literal(&format!(" struct{object}")); + } + _ => {} } } OutputOperation::PdfLiteral { mode, shipout, tokens } => { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 9921d65..5777810 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -2463,6 +2463,10 @@ impl Executor { self.reads.insert(Dependency::PdfLastPosition); Ok(self.state.pdf_last_position[usize::from(p == Primitive::Pdflastypos)]) } + Meaning::Primitive(Primitive::Pdflastannot) => { + self.reads.insert(Dependency::PdfObjects); + Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last_annotation())) + } Meaning::Primitive(Primitive::Pdflastlink) => { self.reads.insert(Dependency::PdfObjects); Ok(self diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index a6e01c9..2a10264 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -30,7 +30,7 @@ impl Executor { Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => { self.scan_pdf_graphics(primitive, token.span, files)? } - Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => { + Pdfannot | Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => { 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 a1651a0..b54a60c 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -741,6 +741,14 @@ impl Executor { } self.current = current; if has_link_material && for_form { + let first = outputs.iter().find(|node| node.is_pdf_link()); + if let Some(node) = first + && matches!(node.operation, OutputOperation::PdfLink( + crate::pdf_device::links::LinkNode::Annotation { .. } + )) + { + return Err(self.error("annotations 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_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index 0f9e7c1..5f66d3b 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -41,6 +41,7 @@ pub(super) struct PdfLinkShipout { page_height: i64, graphics_index: usize, output: PageLinks, + direct_annotations: Vec, origin: [i64; 2], margin: i64, numbered: bool, @@ -79,6 +80,15 @@ impl NavigationGeometry { } } +fn rule_rectangle(row: BoxLayout, [x, y]: [i64; 2], [width, height, depth]: [Option; 3]) -> [i64; 4] { + [ + x, + height.map_or(row.baseline - row.height, |h| y - i64::from(h)), + width.map_or(row.left + row.width, |w| x + i64::from(w)), + depth.map_or(row.baseline + row.depth, |d| y + i64::from(d)), + ] +} + impl ActiveLink { fn start_segment( &mut self, @@ -89,19 +99,7 @@ impl ActiveLink { page_height: i64, margin: i64, ) { - let [x, y] = point; - let rect = [ - x, - self.layout - .height - .map_or(row.baseline - row.height, |h| y - i64::from(h)), - self.layout - .width - .map_or(row.left + row.width, |w| x + i64::from(w)), - self.layout - .depth - .map_or(row.baseline + row.depth, |d| y + i64::from(d)), - ]; + let rect = rule_rectangle(row, point, [self.layout.width, self.layout.height, self.layout.depth]); self.segment = Some(output.annotations.len()); output.annotations.push(LinkAnnotation { object_number: None, @@ -147,7 +145,11 @@ impl Executor { files: &mut impl SourceProvider, ) -> Result<(), Error> { if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 { - return self.fail("PDF link operation not allowed in DVI mode"); + return self.fail(if command == Primitive::Pdfannot { + "\\pdfannot not allowed in DVI mode" + } else { + "PDF link operation not allowed in DVI mode" + }); } if matches!(command, Primitive::Pdfstartlink | Primitive::Pdfendlink) && self.paragraph.is_none() @@ -160,13 +162,35 @@ impl Executor { }); } let operation = match command { + Primitive::Pdfannot => { + self.reads.insert(Dependency::PdfObjects); + let limit = self.limits.tokens; + if self.keyword("reserveobjnum", files)? { + self.state.pdf_objects.get_or_insert_with(Default::default) + .reserve_annotation_number(limit) + .map_err(|error| self.error(error, span))?; + return self.optional_space(files); + } + let requested = if self.keyword("useobjnum", files)? { + Some(self.integer(files)? as u32) + } else { + None + }; + let object_number = self.state.pdf_objects.get_or_insert_with(Default::default) + .begin_annotation(requested, limit) + .map_err(|error| self.error(error, span))?; + let dimensions = self.scan_pdf_rule(files)?; + let entries = self.scan_pdf_tokens(files)?; + self.state.pdf_objects.as_mut().unwrap().record_last_annotation(object_number); + LinkNode::Annotation { object_number, dimensions, entries } + } Primitive::Pdfstartlink => { self.reads.insert(Dependency::PdfObjects); let object_number = self .state .pdf_objects .get_or_insert_with(Default::default) - .reserve_link(self.limits.tokens) + .allocate_annotation(self.limits.tokens) .map_err(|error| self.error(error, self.current))?; let [width, height, depth] = self.scan_pdf_rule(files)?; let attributes = if self.keyword("attr", files)? { @@ -281,10 +305,10 @@ impl Executor { Ok(()) } - pub(super) fn register_pdf_link(&mut self, number: Option) -> Result { + pub(super) fn register_pdf_annotation(&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) + .ship_annotation(number, self.limits.tokens) .map_err(|message| self.error(message, self.current)) } @@ -350,6 +374,7 @@ impl Executor { page_height: device.page_height, graphics_index: 0, output: PageLinks::default(), + direct_annotations: Vec::new(), origin: [device.horizontal_origin, device.vertical_origin + b.height], margin: i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()), numbered, @@ -403,7 +428,7 @@ impl PdfLinkShipout { for link in self.active.iter_mut().filter(|link| { link.level == row.level && link.layout.width.is_none() }) { - let number = if self.numbered { Some(executor.register_pdf_link(None)?) } else { None }; + let number = if self.numbered { Some(executor.register_pdf_annotation(None)?) } else { None }; link.start_segment(&mut self.output, absolute_row(row), [x, y], &mut self.geometry, self.page_height, self.margin); self.output.annotations.last_mut().unwrap().object_number = number; @@ -417,6 +442,16 @@ impl PdfLinkShipout { let container = absolute_row(container); executor.current = node.span; match link { + LinkNode::Annotation { object_number, dimensions, entries } => { + let number = executor.register_pdf_annotation(Some(*object_number))?; + let rect = rule_rectangle(container, [x, y], *dimensions); + self.direct_annotations.push(LinkAnnotation { + object_number: Some(number), + rect: self.geometry.rectangle(rect, self.page_height, 0), + attributes: String::new(), + action: AnnotationAction::Direct(executor.pdf_token_bytes(entries)?), + }); + } LinkNode::Start(layout) => { if self.active.len() == 10 { return executor.fail("PDF link stack capacity exceeded"); @@ -425,7 +460,7 @@ impl PdfLinkShipout { return executor.fail("PDF link start arrived outside a horizontal list"); } let number = if self.numbered { - Some(executor.register_pdf_link(layout.object_number)?) + Some(executor.register_pdf_annotation(layout.object_number)?) } else { layout.object_number }; @@ -479,12 +514,10 @@ impl PdfLinkShipout { point } }); - let view = view.map_rectangle(|[width, height, depth]| { + let view = view.map_rectangle(|dimensions| { let margin = i64::from(executor.read_parameter(Parameter::Pdfdestmargin).width()); - let top = height.map_or(container.baseline - container.height, |h| y - i64::from(h)); - let right = width.map_or(container.left + container.width, |w| x + i64::from(w)); - let bottom = depth.map_or(container.baseline + container.depth, |d| y + i64::from(d)); - self.geometry.rectangle([x, top, right, bottom], self.page_height, margin) + let rect = rule_rectangle(container, [x, y], dimensions); + self.geometry.rectangle(rect, self.page_height, margin) }); self.output.destinations.push(PageDestination { object_number, destination, point, view, @@ -516,6 +549,10 @@ impl PdfLinkShipout { if self.numbered { executor.pdf_navigation_geometry = self.geometry; } + if !self.direct_annotations.is_empty() { + self.direct_annotations.append(&mut self.output.annotations); + self.output.annotations = self.direct_annotations; + } Ok(self.output) } } diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index 3b1a2b1..c6f3c42 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -220,6 +220,7 @@ impl Executor { | Primitive::Pdfrandomseed | Primitive::Pdflastobj | Primitive::Pdflastlink + | Primitive::Pdflastannot | Primitive::Pdflastxform | Primitive::Pdflastximage | Primitive::Pdflastximagepages diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index bc2e232..28f7e0c 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 = 103; -const COMPATIBLE_SCHEMAS: [u32; 69] = [ - 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, SCHEMA, +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 ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -223,6 +223,9 @@ impl FormatImage { if image.schema < 103 { image.state.restore_legacy_pdf_parameters(&[Parameter::Pdfsuppresswarningdupdest]); } + if image.schema < 104 { + image.state.install_pdf_annotation_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/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 97b7434..3beb356 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -116,6 +116,7 @@ pub enum Primitive { Pdfcolorstack, Pdfsave, Pdfstartlink, + Pdfannot, Pdfendlink, Pdfrunninglinkoff, Pdfrunninglinkon, @@ -366,6 +367,7 @@ pub enum Primitive { Leftmarginkern, Rightmarginkern, Pdflastlink, + Pdflastannot, Special, Umathcode, Umathcodenum, @@ -958,6 +960,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = { ("pdfrefobj", Pdfrefobj), ("pdflastobj", Pdflastobj), ("pdflastlink", Pdflastlink), + ("pdflastannot", Pdflastannot), ("pdfrandomseed", Pdfrandomseed), ("pdfsetrandomseed", Pdfsetrandomseed), ("pdfuniformdeviate", Pdfuniformdeviate), @@ -968,6 +971,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = { ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), ("pdfstartlink", Pdfstartlink), + ("pdfannot", Pdfannot), ("pdfendlink", Pdfendlink), ("pdfrunninglinkoff", Pdfrunninglinkoff), ("pdfrunninglinkon", Pdfrunninglinkon), @@ -1975,6 +1979,16 @@ impl State { } } + pub(super) fn install_pdf_annotation_commands(&mut self) { + let enabled = self.input_profile != super::InputProfile::XeTeX; + for (name, primitive) in [ + ("pdfannot", Primitive::Pdfannot), + ("pdflastannot", Primitive::Pdflastannot), + ] { + self.update_profile_command(name, Meaning::Primitive(primitive), 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 6769554..f2ca069 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -3079,7 +3079,7 @@ fn write_pdf( let native_annotation_ids: Vec<_> = list.pdf_links.annotations.iter().enumerate() .map(|(index, _)| { remapped.as_ref() - .and_then(|resources| resources.link_objects.get(&(page_index, index)).copied()) + .and_then(|resources| resources.annotation_objects.get(&(page_index, index)).copied()) .unwrap_or_else(|| { let id = next_annotation; next_annotation += 1; @@ -3215,7 +3215,12 @@ fn write_pdf( let coordinates = [left, height - bottom, right, height - top].map(physical); let entries = remapped.as_ref().and_then(|resources| resources.annotations[page_index][index].as_deref()); - let mut body = if let Some(entries) = entries { + let mut body = if let AnnotationAction::Direct(raw) = &annotation.action { + let mut body = b"<< /Type /Annot\n".to_vec(); + body.extend_from_slice(entries.unwrap_or(raw)); + write!(&mut body, "\n/Rect [{}]", coordinates.join(" ")).unwrap(); + body + } else if let Some(entries) = entries { let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes(); body.extend_from_slice(entries); body @@ -3225,7 +3230,7 @@ fn write_pdf( }; match &annotation.action { AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()), - AnnotationAction::User(_) => {} + AnnotationAction::User(_) | AnnotationAction::Direct(_) => {} AnnotationAction::GotoName(name) => { write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap(); } diff --git a/crates/texrra-tex-core/src/pdf_device/links.rs b/crates/texrra-tex-core/src/pdf_device/links.rs index 6450f65..1d88bfa 100644 --- a/crates/texrra-tex-core/src/pdf_device/links.rs +++ b/crates/texrra-tex-core/src/pdf_device/links.rs @@ -60,6 +60,11 @@ pub enum DestinationId { #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum LinkNode { + Annotation { + object_number: u32, + dimensions: [Option; 3], + entries: Vec, + }, Start(LinkStart), End, Running(bool), @@ -73,6 +78,7 @@ pub enum LinkNode { #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum AnnotationAction { + Direct(Vec), User(String), GotoName(String), Catalog(CatalogAction), 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 26f0515..16eba78 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -18,8 +18,11 @@ use std::{ #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(crate) enum ObjectBody { Page, - Link, - FormatLink, + #[serde(alias = "Link")] + Annotation, + #[serde(alias = "FormatLink")] + FormatAnnotation, + ReservedAnnotation, Form, FormResources, Image(usize), @@ -49,7 +52,7 @@ pub(crate) enum ObjectBody { impl ObjectBody { fn len(&self) -> usize { match self { - Self::Page | Self::Link | Self::FormatLink | Self::Form + 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, @@ -69,7 +72,7 @@ impl ObjectBody { fn parse(&self) -> Result { match self { - Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources + 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 => { @@ -115,6 +118,8 @@ pub struct PdfObjects { last: i32, #[serde(default, skip_serializing_if = "Option::is_none")] last_link: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + last_annotation: Option, bytes: usize, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] page_references: BTreeMap, @@ -135,7 +140,7 @@ pub struct PdfObjects { #[serde(skip)] destination_numbers: BTreeMap<(DestinationId, bool), (u32, bool)>, #[serde(skip)] - shipped_links: BTreeSet, + shipped_annotations: BTreeSet, // Source object numbers belong to one particular version of one file. #[serde(skip)] imported_images: BTreeMap>>, @@ -162,7 +167,8 @@ impl PdfObjects { } pub(crate) fn is_reserved(&self, number: u32) -> bool { - self.entry(number).is_some_and(Option::is_none) + matches!(self.entry(number).map(Option::as_deref), + Some(None | Some(ObjectBody::ReservedAnnotation))) } fn allocate(&mut self, body: Option>, limit: usize) -> Result { @@ -388,22 +394,50 @@ impl PdfObjects { }) } - pub(crate) fn reserve_link(&mut self, limit: usize) -> Result { - self.allocate(Some(Arc::new(ObjectBody::Link)), limit) + pub(crate) fn allocate_annotation(&mut self, limit: usize) -> Result { + self.allocate(Some(Arc::new(ObjectBody::Annotation)), limit) } - pub(crate) fn ship_link(&mut self, number: Option, limit: usize) -> Result { + pub(crate) fn ship_annotation(&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) + && matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::Annotation)) + && self.shipped_annotations.insert(number) { return Ok(number); } - let number = self.reserve_link(limit)?; - self.shipped_links.insert(number); + let number = self.allocate_annotation(limit)?; + self.shipped_annotations.insert(number); Ok(number) } + pub(crate) fn reserve_annotation_number(&mut self, limit: usize) -> Result<(), String> { + let number = self.allocate(Some(Arc::new(ObjectBody::ReservedAnnotation)), limit)?; + self.record_last_annotation(number); + Ok(()) + } + + pub(crate) fn begin_annotation(&mut self, requested: Option, limit: usize) -> Result { + let Some(number) = requested else { + return self.allocate_annotation(limit); + }; + if self.shipped_annotations.contains(&number) + || !matches!(self.entry(number).map(Option::as_deref), + Some(None | Some(ObjectBody::ReservedAnnotation | ObjectBody::Annotation))) + { + return Err("pdfTeX error (ext1): invalid object number.".into()); + } + self.values[number as usize - 1] = Some(Arc::new(ObjectBody::Annotation)); + Ok(number) + } + + pub(crate) fn record_last_annotation(&mut self, number: u32) { + self.last_annotation = Some(number); + } + + pub(crate) fn last_annotation(&self) -> i32 { + self.last_annotation.unwrap_or_default() as i32 + } + pub(crate) fn destination_is_defined(&self, id: DestinationId, structure: bool) -> bool { self.destination_numbers .get(&(id, structure)) @@ -441,8 +475,8 @@ impl PdfObjects { for (index, entry) in self.values.iter_mut().enumerate() { let number = index as u32 + 1; let replacement = match entry.as_deref() { - // A restored link whatsit gets its own annotation object when shipped. - Some(ObjectBody::Link) => ObjectBody::FormatLink, + // A restored annotation whatsit gets its own annotation object when shipped. + Some(ObjectBody::Annotation) => ObjectBody::FormatAnnotation, Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources | ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_) | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination @@ -456,6 +490,7 @@ impl PdfObjects { } self.written.clear(); self.last_link = None; + self.last_annotation = None; self.bytes = self.values.iter().flatten().map(|body| body.len()).sum(); self.page_references.clear(); self.page_parent = None; @@ -465,15 +500,15 @@ impl PdfObjects { self.written_png_group = None; self.object_streams.clear(); self.destination_numbers.clear(); - self.shipped_links.clear(); + self.shipped_annotations.clear(); self.imported_images.clear(); self.imported_type1.clear(); !self.values.is_empty() } - fn is_link(&self, number: u32) -> bool { + fn is_annotation(&self, number: u32) -> bool { self.entry(number).is_some_and(|entry| { - matches!(entry.as_deref(), Some(ObjectBody::Link | ObjectBody::FormatLink)) + matches!(entry.as_deref(), Some(ObjectBody::Annotation | ObjectBody::FormatAnnotation | ObjectBody::ReservedAnnotation)) }) } @@ -761,7 +796,7 @@ pub(crate) struct ResourceOutput { actual_pages: usize, values: BTreeMap, page_references: BTreeMap, - link_references: BTreeMap>, + annotation_references: BTreeMap>, structure_references: BTreeSet, image_color_space_objects: BTreeSet, page_entries: Vec, @@ -781,7 +816,7 @@ pub(crate) struct RemappedResources { pub page_tree_attributes: Vec, pub fonts: BTreeMap>, pub page_objects: BTreeMap, - pub link_objects: BTreeMap<(usize, usize), usize>, + pub annotation_objects: BTreeMap<(usize, usize), usize>, pub structure_objects: BTreeMap, pub object_numbers: BTreeMap, pub annotations: Vec>>>, @@ -880,8 +915,13 @@ impl ResourceOutput { .map(|annotation| { use crate::pdf_device::links::AnnotationAction; let mut entries = parse_entries(annotation.attributes.as_bytes())?; - if let AnnotationAction::User(action) = &annotation.action { - for (key, value) in parse_entries(action.as_bytes())?.iter() { + let raw = match &annotation.action { + AnnotationAction::Direct(entries) => Some(entries.as_slice()), + AnnotationAction::User(action) => Some(action.as_bytes()), + _ => None, + }; + if let Some(raw) = raw { + for (key, value) in parse_entries(raw)?.iter() { entries.set(key.clone(), value.clone()); } } @@ -898,16 +938,16 @@ impl ResourceOutput { .collect::, String>>() }) .collect::, String>>()?; - let mut link_references = BTreeMap::new(); + let mut annotation_references = BTreeMap::new(); for (page_index, page) in pages.iter().enumerate() { for (annotation_index, annotation) in page.pdf_links.annotations.iter().enumerate() { if let Some(number) = annotation.object_number && matches!( objects.entry(number).and_then(Option::as_deref), - Some(ObjectBody::Link) + Some(ObjectBody::Annotation) ) { - link_references + annotation_references .entry(number) .or_insert(Some((page_index, annotation_index))); } @@ -920,8 +960,8 @@ impl ResourceOutput { .collect(); let mut values = BTreeMap::new(); while let Some(number) = pending.pop_first() { - if objects.is_link(number) { - link_references.entry(number).or_insert(None); + if objects.is_annotation(number) { + annotation_references.entry(number).or_insert(None); continue; } if values.contains_key(&number) || page_objects.contains(&number) @@ -953,7 +993,7 @@ impl ResourceOutput { actual_pages, values, page_references: objects.page_references.clone(), - link_references, + annotation_references, structure_references, image_color_space_objects, page_entries, @@ -986,14 +1026,14 @@ impl ResourceOutput { } ids.insert(number, id as u32); } - let mut link_objects = BTreeMap::new(); - for (number, annotation) in self.link_references { + let mut annotation_objects = BTreeMap::new(); + for (number, annotation) in self.annotation_references { // Repeated copies get independent annotations. Only the first - // shipped occurrence fills the object reserved for the TeX link. + // shipped occurrence fills the object originally reserved at scan time. output.push(Vec::new()); let id = output.len(); if let Some(annotation) = annotation { - link_objects.insert(annotation, id); + annotation_objects.insert(annotation, id); } ids.insert(number, id as u32); } @@ -1057,7 +1097,7 @@ impl ResourceOutput { .map(|(font, dictionary)| (font, encode(dictionary))) .collect(), page_objects, - link_objects, + annotation_objects, structure_objects, annotations: self.annotation_entries.into_iter() .map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect()) diff --git a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs index e5bee4a..4d00547 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs @@ -797,3 +797,66 @@ fn running_links_use_the_current_matrix_and_last_device_rectangle() { assert_eq!(expected.iter().map(Vec::len).collect::>(), [1, 1, 2, 0, 1]); assert_eq!(page_rectangles(&native), expected); } + +#[test] +fn direct_annotations_keep_reserved_references_and_copy_geometry() { + let (reference, native, diagnostics) = pair( + r"\pdfpagewidth=200pt \pdfpageheight=200pt + \def\space{ } + \pdfobj reserveobjnum \edef\general{\the\pdflastobj} + \pdfannot reserveobjnum \edef\parent{\the\pdflastannot} + \pdfannot reserveobjnum \edef\popup{\the\pdflastannot} + \ifnum\pdflastobj=\general\relax\else\errmessage{annotation changed last generic object}\fi + \setbox0=\hbox{ + \pdfstartlink width6pt height3pt depth1pt user{/Subtype /Link /Border [0 0 0]} + \vrule width6pt height3pt\pdfendlink + \pdfsave\pdfsetmatrix{0 1 -1 0} + \pdfannot useobjnum\parent width9pt height5pt depth1pt + {/Subtype /Text /Contents (old^^e9) /Popup \popup\space 0 R} + \pdfannot useobjnum\parent width8pt height4pt depth2pt + {/Subtype /Text /Contents (duplicate) /IRT \parent\space 0 R} + \pdfrestore + \pdfannot useobjnum\popup width7pt height3pt depth1pt + {/Subtype /Popup /Parent \parent\space 0 R} + \pdfannot useobjnum\general width5pt height2pt depth1pt + {/Subtype /Text /Contents (generic)} + \vrule width10pt height5pt} + \shipout\copy0\shipout\box0 + \ifnum\pdflastannot=\general\relax\else\errmessage{shipout changed last annotation}\fi", + ); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + let inspect = |pdf: &Document| { + let mut previous = Vec::new(); + let mut rectangles = Vec::new(); + for page in pdf.get_pages().into_values() { + let page = pdf.get_dictionary(page).unwrap(); + let annots = get(pdf, page, b"Annots").as_array().unwrap(); + assert_eq!(annots.len(), 5); + let ids: Vec<_> = annots.iter().map(|value| value.as_reference().unwrap()).collect(); + assert!(ids.iter().all(|id| !previous.contains(id))); + assert_eq!(ids.iter().copied().collect::>().len(), 5); + let parent = previous.first().copied().unwrap_or(ids[0]); + let popup = previous.get(2).copied().unwrap_or(ids[2]); + let attrs: Vec<_> = ids.iter().map(|id| pdf.get_dictionary(*id).unwrap()).collect(); + for (dict, subtype) in attrs.iter().zip([b"Text".as_slice(), b"Text", b"Popup", b"Text", b"Link"]) { + assert_eq!(dict.get(b"Subtype").unwrap().as_name().unwrap(), subtype); + let rectangle = get(pdf, dict, b"Rect").as_array().unwrap().iter().map(|coordinate| { + match coordinate { + Object::Integer(value) => *value as f64, + Object::Real(value) => f64::from(*value), + other => panic!("expected a numeric coordinate, found {other:?}"), + } + }).collect::>(); + rectangles.push(rectangle); + } + assert_eq!(attrs[0].get(b"Contents").unwrap().as_str().unwrap(), b"old\xe9"); + assert_eq!(attrs[0].get(b"Popup").unwrap().as_reference().unwrap(), popup); + assert_eq!(attrs[1].get(b"IRT").unwrap().as_reference().unwrap(), parent); + assert_eq!(attrs[2].get(b"Parent").unwrap().as_reference().unwrap(), parent); + previous = ids; + } + assert_eq!(rectangles.len(), 10); + rectangles + }; + assert_eq!(inspect(&native), inspect(&reference)); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index e798520..9dfaa77 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,41 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 原生 PDF 注释 + +pdfTeX 模式执行 \pdfannot、reserveobjnum、useobjnum 和 +\pdflastannot。注释和链接共享对象登记、出页坐标和引用重映射。 +扫描阶段能保留编号,同一待出页编号可被多个节点引用。首个出页 +节点使用该编号,后续副本各分配编号。页面 Annots 按原版顺序 +列出普通注释与链接。直接注释保留实际 8 位字节和间接引用, +并参与活动矩阵下的最近矩形计算。 +[pdfTeX 的注释扫描与编号](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L34890-L34913) +· [出页与注释矩形](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L36460-L36472) + +原版最小用例现已输出 Text 注释。2 页复制盒对照逐项核对 10 个 +注释的坐标、顺序和对象关系。同一 PDF 的弹出窗口、父注释和 +一般 PDF 对象的间接引用均指向实际输出对象。保留编号、备用 +一般对象槽、leader 抑制和盒列表诊断有实跑记录。三类拒绝覆盖 +已占用编号、DVI 和 XForm。发布构建与 26 项定向回归通过。 + +schema104 保存实际盒节点,格式重载后两页光栅一致。参考和 +原生的查询均为转储前 1、重载后 0、出两页后再次保留为 11。 +schema103 须保留的同名用户宏经过重载检验。由原样 pdflatex.ini +生成 schema104 后,用原样 LaTeX 的 l3backend-pdftex.def 调用 +底层注释,得到与参考相同的 1 0 R、注释矩形、aux 和一页 +144 DPI 光栅。实际 class、后端与格式资源身份留存。 + +三页项目首段保留注释编号,第二页子文件使用它。两次编辑各 +复用 1,144 步,只更新第二页。PDF、页面、SVG、日志、辅助 +文件和来源映射与独立全量一致,检查点后使用同一个真实编号。 + +下一处原语缺口保存在 next-thread。原版 \pdfthread 对同名 +文章线程输出跨两页的实际 B、Threads 和双向 bead 引用。 +当前原生在该原语停止。首条失败和参考 PDF 均保留。 + +回执在 target/p3-native-pdf-annotation,receipt.json 的 +SHA-256 为 7a6bb4b6a50f41e24692e49fa5d58d61a2d15533680f1fc5aad050aa53324acb。 + ## 2026-11-28 自动宽度 PDF 链接的收尾矩形 自动宽度链接在结束节点读取当前变换。活动矩阵下,结束处的横坐标