diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 5793268..3cb72bb 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -2146,6 +2146,14 @@ impl Executor { self.reads.insert(Dependency::PdfRandomState); Ok(self.state.random_seed()) } + Meaning::Primitive(Primitive::Pdflastlink) => { + self.reads.insert(Dependency::PdfObjects); + Ok(self + .state + .pdf_objects + .as_deref() + .map_or(0, |objects| objects.last_link())) + } Meaning::Primitive(Primitive::Pdflastobj) => { self.reads.insert(Dependency::PdfObjects); Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last())) 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 158235b..4ed6896 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -76,6 +76,7 @@ impl ActiveLink { transformed: transform.1, }); output.annotations.push(LinkAnnotation { + object_number: None, rect: link_rect(rect, transform.0, margin), attributes: self.attributes.clone(), action: self.action.clone(), @@ -119,6 +120,13 @@ impl Executor { } let operation = match command { 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) + .map_err(|error| self.error(error, self.current))?; let (mut width, mut height, mut depth) = (None, None, None); loop { let target = if self.keyword("width", files)? { @@ -144,7 +152,13 @@ impl Executor { } else { return self.fail("expected a user or named goto PDF link action"); }; + self.state + .pdf_objects + .as_mut() + .expect("allocated PDF link object") + .record_last_link(object_number); LinkNode::Start(LinkStart { + object_number: Some(object_number), width, height, depth, @@ -258,6 +272,9 @@ impl Executor { let mut start = ActiveLink { layout: layout.clone(), attributes, action, level: row.level, segment: None }; start.start_segment(&mut output, row, [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; active.push(start); } LinkNode::End => { diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index cbcc328..bf96c13 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -209,6 +209,7 @@ impl Executor { | Primitive::Inputlineno | Primitive::Pdfrandomseed | Primitive::Pdflastobj + | Primitive::Pdflastlink | Primitive::Pdflastximage | Primitive::Pdflastximagepages | Primitive::Pdflastximagecolordepth diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 7259c4c..8187df7 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,8 +8,8 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 39; -const COMPATIBLE_SCHEMAS: [u32; 11] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, SCHEMA]; +const SCHEMA: u32 = 40; +const COMPATIBLE_SCHEMAS: [u32; 12] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, SCHEMA]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 66b0ff4..493e9d7 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -331,6 +331,7 @@ pub enum Primitive { Pdfliteral, Leftmarginkern, Rightmarginkern, + Pdflastlink, } impl Primitive { @@ -969,6 +970,7 @@ impl Default for State { ("pdfobj", Pdfobj), ("pdfrefobj", Pdfrefobj), ("pdflastobj", Pdflastobj), + ("pdflastlink", Pdflastlink), ("pdfrandomseed", Pdfrandomseed), ("pdfsetrandomseed", Pdfsetrandomseed), ("pdfuniformdeviate", Pdfuniformdeviate), @@ -1396,7 +1398,13 @@ impl State { self.output_mode_set = None; self.pdf_file_options = None; self.pdf_catalog = None; - self.pdf_objects = None; + if !self + .pdf_objects + .as_deref_mut() + .is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_links) + { + self.pdf_objects = None; + } self.pdf_info.clear(); self } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 361ff91..c5e87b0 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2207,15 +2207,28 @@ fn write_pdf( }) .collect::>(); let annotation_base = image_base + used.len(); - let annotation_count = links.len() + list.pdf_links.annotations.len(); - let annots = if annotation_count == 0 { + let native_annotation_base = annotation_base + links.len(); + let mut next_annotation = native_annotation_base; + 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()) + .unwrap_or_else(|| { + let id = next_annotation; + next_annotation += 1; + id + }) + }) + .collect(); + let annotation_refs = (annotation_base..native_annotation_base) + .chain(native_annotation_ids.iter().copied()) + .map(|id| format!("{id} 0 R")) + .collect::>() + .join(" "); + let annots = if annotation_refs.is_empty() { String::new() } else { - let refs = (0..annotation_count) - .map(|index| format!("{} 0 R", annotation_base + index)) - .collect::>() - .join(" "); - format!(" /Annots [{refs}]") + format!(" /Annots [{annotation_refs}]") }; page_ids.push(page_id); kids.push(format!("{page_id} 0 R")); @@ -2295,7 +2308,7 @@ fn write_pdf( .into_bytes(), ); } - for annotation in &list.pdf_links.annotations { + for (index, (annotation, id)) in list.pdf_links.annotations.iter().zip(native_annotation_ids).enumerate() { use crate::pdf_device::links::AnnotationAction; let [left, top, right, bottom] = annotation.rect; let coordinates = [left, height - bottom, right, height - top].map(physical); @@ -2304,8 +2317,25 @@ fn write_pdf( AnnotationAction::GotoName(name) => format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)), }; - objects.push(format!("<< /Type /Annot {} /Rect [{}] {} >>", - annotation.attributes, coordinates.join(" "), action).into_bytes()); + let entries = remapped.as_ref().and_then(|resources| + resources.annotations[page_index][index].as_deref()); + let body = if let Some(entries) = entries { + let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes(); + body.extend_from_slice(entries); + if matches!(annotation.action, AnnotationAction::GotoName(_)) { + body.extend_from_slice(action.as_bytes()); + } + body.extend_from_slice(b" >>"); + body + } else { + format!("<< /Type /Annot {} /Rect [{}] {} >>", + annotation.attributes, coordinates.join(" "), action).into_bytes() + }; + if id == objects.len() + 1 { + objects.push(body); + } else { + objects[id - 1] = body; + } } for destination in &list.pdf_links.destinations { use crate::pdf_device::links::DestinationView; diff --git a/crates/texrra-tex-core/src/pdf_device/links.rs b/crates/texrra-tex-core/src/pdf_device/links.rs index 59aba66..7080b14 100644 --- a/crates/texrra-tex-core/src/pdf_device/links.rs +++ b/crates/texrra-tex-core/src/pdf_device/links.rs @@ -9,6 +9,8 @@ pub enum LinkAction { #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct LinkStart { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub object_number: Option, pub width: Option, pub height: Option, pub depth: Option, @@ -53,6 +55,8 @@ pub enum AnnotationAction { #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LinkAnnotation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub object_number: Option, /// Left, top, right and bottom in TeX sp, with y measured down the page. pub rect: [i64; 4], pub attributes: String, 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 65cc1f7..bd039ed 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -12,6 +12,8 @@ use std::{ #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(crate) enum ObjectBody { Page, + Link, + FormatLink, Direct(Vec), Stream { attributes: Vec, @@ -27,7 +29,7 @@ pub(crate) enum ObjectBody { impl ObjectBody { fn len(&self) -> usize { match self { - Self::Page => 0, + Self::Page | Self::Link | Self::FormatLink => 0, Self::Direct(bytes) => bytes.len(), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), Self::File { @@ -44,7 +46,7 @@ impl ObjectBody { fn parse(&self) -> Result { match self { - Self::Page => Err("expected a generic native PDF object".into()), + Self::Page | Self::Link | Self::FormatLink => Err("expected a generic native PDF object".into()), Self::Direct(bytes) => parse_value(bytes), Self::File { .. } => Err("PDF object file payload was not read before export".into()), Self::Stream { attributes, bytes } => { @@ -64,6 +66,8 @@ pub struct PdfObjects { values: Vec>>, written: BTreeSet, last: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + last_link: Option, bytes: usize, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] page_references: BTreeMap, @@ -80,7 +84,9 @@ impl PdfObjects { pub(crate) fn contains(&self, number: u32) -> bool { self.entry(number) - .is_some_and(|entry| !matches!(entry.as_deref(), Some(ObjectBody::Page))) + .is_some_and(|entry| { + !matches!(entry.as_deref(), Some(ObjectBody::Page | ObjectBody::Link | ObjectBody::FormatLink)) + }) } pub(crate) fn is_reserved(&self, number: u32) -> bool { @@ -101,6 +107,47 @@ impl PdfObjects { Ok(number) } + pub(crate) fn reserve_link(&mut self, limit: usize) -> Result { + self.allocate(Some(Arc::new(ObjectBody::Link)), limit) + } + + pub(crate) fn record_last_link(&mut self, number: u32) { + self.last_link = Some(number); + } + + pub(crate) fn last_link(&self) -> i32 { + self.last_link.unwrap_or_default() as i32 + } + + pub(crate) fn retain_format_links(&mut self) -> bool { + let Some(last_link) = self + .values + .iter() + .rposition(|entry| matches!(entry.as_deref(), Some(ObjectBody::Link))) + else { + return false; + }; + // The reservation survives the format, but pdfTeX assigns a new + // object to the annotation when it ships the restored whatsit. + self.values.truncate(last_link + 1); + for entry in &mut self.values { + *entry = matches!(entry.as_deref(), Some(ObjectBody::Link)) + .then(|| Arc::new(ObjectBody::FormatLink)); + } + self.written.clear(); + self.last = 0; + self.last_link = None; + self.bytes = 0; + self.page_references.clear(); + true + } + + fn is_link(&self, number: u32) -> bool { + self.entry(number).is_some_and(|entry| { + matches!(entry.as_deref(), Some(ObjectBody::Link | ObjectBody::FormatLink)) + }) + } + pub(crate) fn page_reference(&mut self, page: u32, limit: usize) -> Result { if let Some(number) = self.page_references.get(&page) { return Ok(*number); @@ -356,7 +403,9 @@ impl PageResources { pub(crate) struct ResourceOutput { values: BTreeMap, page_references: BTreeMap, + link_references: BTreeMap>, page_entries: Vec, + annotation_entries: Vec>>, catalog: Option, info: Option, } @@ -364,6 +413,8 @@ pub(crate) struct ResourceOutput { pub(crate) struct RemappedResources { pub pages: Vec>, pub page_objects: BTreeMap, + pub link_objects: BTreeMap<(usize, usize), usize>, + pub annotations: Vec>>>, pub catalog: Option>, pub info: Option>, } @@ -398,8 +449,54 @@ impl ResourceOutput { } } let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect(); + let annotation_entries = pages + .iter() + .map(|page| { + page.pdf_links + .annotations + .iter() + .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() { + entries.set(key.clone(), value.clone()); + } + } + let mut related = BTreeSet::new(); + for (_, value) in entries.iter() { + references(value, &mut related)?; + } + if related.is_empty() { + return Ok(None); + } + pending.extend(related); + Ok(Some(entries)) + }) + .collect::, String>>() + }) + .collect::, String>>()?; + let mut link_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) + ) + { + link_references + .entry(number) + .or_insert(Some((page_index, annotation_index))); + } + } + } let mut values = BTreeMap::new(); while let Some(number) = pending.pop_first() { + if objects.is_link(number) { + link_references.entry(number).or_insert(None); + continue; + } if values.contains_key(&number) || page_objects.contains(&number) { continue; } @@ -410,7 +507,9 @@ impl ResourceOutput { Ok(Self { values, page_references: objects.page_references.clone(), + link_references, page_entries, + annotation_entries, catalog, info, }) @@ -435,6 +534,17 @@ impl ResourceOutput { } ids.insert(number, id as u32); } + let mut link_objects = BTreeMap::new(); + for (number, annotation) in self.link_references { + // Repeated copies get independent annotations. Only the first + // shipped occurrence fills the object reserved for the TeX link. + output.push(Vec::new()); + let id = output.len(); + if let Some(annotation) = annotation { + link_objects.insert(annotation, id); + } + ids.insert(number, id as u32); + } ids.extend( self.values .keys() @@ -458,6 +568,10 @@ impl ResourceOutput { RemappedResources { pages: self.page_entries.into_iter().map(&encode).collect(), page_objects, + link_objects, + annotations: self.annotation_entries.into_iter() + .map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect()) + .collect(), catalog: self.catalog.map(&encode), info: self.info.map(encode), } diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index f875e7c..07d9ded 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 39); + assert_eq!(payload["schema"], 40); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index 50f55cb..b6982bf 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 39); + assert_eq!(original["schema"], 40); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index e941350..385fac5 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 39); + assert_eq!(payload["schema"], 40); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 6ce37ea..fa284d5 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1126,6 +1126,32 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) +### 链接注释的扫描编号与 PDF 引用 + +`\pdflastlink` 从作业共有的 PDF 对象表读取最近一次成功扫描的链接编号。 +链接扫描保留真实编号,实际发页建立注释。目录、用户对象或注释字段中的 +间接引用都重映射到实际对象。复制同一个盒时,首个注释取得该次扫描的 +引用身份,后续副本和跨行注释拥有独立的 PDF 对象。未发页但被引用的 +链接留下空闲交叉引用项。 +[pdfTeX 对链接对象的扫描](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L34919-L34936) +[pdfTeX 对复制和跨行注释的处理](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L36522-L36534) + +schema40 保存格式中的链接保留项,并将最近链接恢复为0。实际重载后, +来自格式的旧编号保持空闲,原盒出页得到新注释编号,与 pdfTeX 的观察 +一致。新链接也得到独立注释。普通文件与格式重载文件共四页144 DPI +灰度图逐像素一致。检查验证目录、普通对象、注释和两页 `/Annots` 的 +实际对象图,保留初次验证对 PDF 合法紧凑词法的误判。原有真实跨行链接 +及命名目标对照通过。 + +编辑第二页的链接盒宽度时,复用1051步,只更新第二页,第二页注释仍引用 +第一张页面中的真实注释。PDF、SVG 与来源映射和独立零复用一致,来源 +映射只归一化会话修订号及测试目录。 + +`target/p3-pdf-lastlink-native` 的回执: + +- `receipt.json` 为 `c1fa0672ac47cf23093a4cb9d4d2e3c384c9a6ee6c9755a6bab3dd8ee60f6f20`。 +- `checkpoint/receipt.json` 为 `7d3af1417582a36aa782ce0f91354624d77e8492100286a1e941e8b072d17f36`。 + ### PDF 字面中的矩阵与来源映射 来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和