Ship native PDF annotations with reserved object numbers

This commit is contained in:
gloamxun committed 2026-11-28 15:39:27 +08:00
1 parent 975dbc8060
commit de4bd1fa76
14 files changed
+299 -67

No files matched your search

@@ -60,6 +60,11 @@ pub enum DestinationId<T> {
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LinkNode {
Annotation {
object_number: u32,
dimensions: [Option<i32>; 3],
entries: Vec<Token>,
},
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<u8>),
User(String),
GotoName(String),
Catalog(CatalogAction),
@@ -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<Object, String> {
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<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_annotation: Option<u32>,
bytes: usize,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
page_references: BTreeMap<u32, u32>,
@@ -135,7 +140,7 @@ pub struct PdfObjects {
#[serde(skip)]
destination_numbers: BTreeMap<(DestinationId<String>, bool), (u32, bool)>,
#[serde(skip)]
shipped_links: BTreeSet<u32>,
shipped_annotations: BTreeSet<u32>,
// Source object numbers belong to one particular version of one file.
#[serde(skip)]
imported_images: BTreeMap<PathBuf, BTreeMap<String, BTreeMap<ObjectId, u32>>>,
@@ -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<Arc<ObjectBody>>, limit: usize) -> Result<u32, String> {
@@ -388,22 +394,50 @@ impl PdfObjects {
})
}
pub(crate) fn reserve_link(&mut self, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Link)), limit)
pub(crate) fn allocate_annotation(&mut self, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Annotation)), limit)
}
pub(crate) fn ship_link(&mut self, number: Option<u32>, limit: usize) -> Result<u32, String> {
pub(crate) fn ship_annotation(&mut self, number: Option<u32>, limit: usize) -> Result<u32, String> {
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<u32>, limit: usize) -> Result<u32, String> {
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<String>, 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<u32, Object>,
page_references: BTreeMap<u32, u32>,
link_references: BTreeMap<u32, Option<(usize, usize)>>,
annotation_references: BTreeMap<u32, Option<(usize, usize)>>,
structure_references: BTreeSet<u32>,
image_color_space_objects: BTreeSet<u32>,
page_entries: Vec<Dictionary>,
@@ -781,7 +816,7 @@ pub(crate) struct RemappedResources {
pub page_tree_attributes: Vec<u8>,
pub fonts: BTreeMap<FontId, Vec<u8>>,
pub page_objects: BTreeMap<usize, usize>,
pub link_objects: BTreeMap<(usize, usize), usize>,
pub annotation_objects: BTreeMap<(usize, usize), usize>,
pub structure_objects: BTreeMap<u32, usize>,
pub object_numbers: BTreeMap<u32, u32>,
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
@@ -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::<Result<Vec<_>, String>>()
})
.collect::<Result<Vec<_>, 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())