Bind native last-link numbers to shipped PDF annotations

This commit is contained in:
gloamxun committed 2026-11-21 02:31:43 +08:00
1 parent 7f74251c8a
commit 60d7411dfe
12 files changed
+227 -19

No files matched your search

@@ -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<u32>,
pub width: Option<i32>,
pub height: Option<i32>,
pub depth: Option<i32>,
@@ -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<u32>,
/// Left, top, right and bottom in TeX sp, with y measured down the page.
pub rect: [i64; 4],
pub attributes: String,
@@ -12,6 +12,8 @@ use std::{
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) enum ObjectBody {
Page,
Link,
FormatLink,
Direct(Vec<u8>),
Stream {
attributes: Vec<u8>,
@@ -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<Object, String> {
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<Option<Arc<ObjectBody>>>,
written: BTreeSet<u32>,
last: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_link: Option<u32>,
bytes: usize,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
page_references: BTreeMap<u32, u32>,
@@ -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<u32, String> {
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<u32, String> {
if let Some(number) = self.page_references.get(&page) {
return Ok(*number);
@@ -356,7 +403,9 @@ impl PageResources {
pub(crate) struct ResourceOutput {
values: BTreeMap<u32, Object>,
page_references: BTreeMap<u32, u32>,
link_references: BTreeMap<u32, Option<(usize, usize)>>,
page_entries: Vec<Dictionary>,
annotation_entries: Vec<Vec<Option<Dictionary>>>,
catalog: Option<Dictionary>,
info: Option<Dictionary>,
}
@@ -364,6 +413,8 @@ pub(crate) struct ResourceOutput {
pub(crate) struct RemappedResources {
pub pages: Vec<Vec<u8>>,
pub page_objects: BTreeMap<usize, usize>,
pub link_objects: BTreeMap<(usize, usize), usize>,
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
pub catalog: Option<Vec<u8>>,
pub info: Option<Vec<u8>>,
}
@@ -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::<Result<Vec<_>, String>>()
})
.collect::<Result<Vec<_>, 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),
}