Build native PDF article threads and bead rings

This commit is contained in:
gloamxun committed 2026-11-28 16:03:37 +08:00
1 parent de4bd1fa76
commit 4fb0f2c89b
15 files changed
+528 -28

No files matched your search

@@ -65,6 +65,13 @@ pub enum LinkNode {
dimensions: [Option<i32>; 3],
entries: Vec<Token>,
},
Thread {
destination: DestinationId<Vec<Token>>,
dimensions: [Option<i32>; 3],
attributes: Option<Vec<Token>>,
running: bool,
},
EndThread,
Start(LinkStart),
End,
Running(bool),
@@ -105,11 +112,24 @@ pub struct PageDestination {
pub structure: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ThreadBead {
pub number: u32,
pub thread: u32,
pub destination: DestinationId<String>,
/// 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<Vec<u8>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PageLinks {
pub annotations: Vec<LinkAnnotation>,
pub destinations: Vec<PageDestination>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub thread_beads: Vec<ThreadBead>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) xdv_destinations: Vec<super::xdv_destination::Destination>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) xdv_annotations: Vec<super::xdv_annotation::Annotation>,
@@ -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()
}
@@ -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<String>, bool), (u32, bool)>,
#[serde(skip)]
thread_numbers: BTreeMap<DestinationId<String>, u32>,
#[serde(skip)]
bead_rectangles: BTreeMap<u32, u32>,
#[serde(skip)]
thread_open_action: Option<u32>,
#[serde(skip)]
thread_array: Option<u32>,
#[serde(skip)]
bead_owners: BTreeMap<u32, u32>,
#[serde(skip)]
shipped_annotations: BTreeSet<u32>,
// 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<u32, String> {
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<u32> {
self.thread_open_action
}
pub(crate) fn thread_number(&mut self, destination: DestinationId<String>, limit: usize) -> Result<u32, String> {
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<u32, String> {
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<u32> {
self.thread_array
}
pub(crate) fn new_bead_rectangle(&mut self, bead: u32, limit: usize) -> Result<u32, String> {
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<Item = (&DestinationId<String>, u32)> {
self.thread_numbers.iter().map(|(destination, &number)| (destination, number))
}
pub(crate) fn bead_rectangles(&self) -> impl Iterator<Item = (u32, u32)> + '_ {
self.bead_rectangles.iter().map(|(&bead, &rectangle)| (bead, rectangle))
}
pub(crate) fn destination_is_defined(&self, id: DestinationId<String>, 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<FontId, Dictionary>,
annotation_entries: Vec<Vec<Option<Dictionary>>>,
thread_attributes: BTreeMap<u32, Dictionary>,
catalog: Option<Dictionary>,
info: Option<Dictionary>,
}
@@ -820,6 +911,7 @@ pub(crate) struct RemappedResources {
pub structure_objects: BTreeMap<u32, usize>,
pub object_numbers: BTreeMap<u32, u32>,
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
pub thread_attributes: BTreeMap<u32, Vec<u8>>,
pub catalog: Option<Vec<u8>>,
pub info: Option<Vec<u8>>,
}
@@ -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::<BTreeMap<_, _>>()
.into_iter().map(|(thread, entries)| Ok((thread, parse_entries(entries)?)))
.collect::<Result<BTreeMap<_, _>, 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,