Register native PDF navigation and raw objects in write order
This commit is contained in:
1 parent
70ebacb056
commit
e95d1264da
9 files changed
+350
-48
No files matched your search
@@ -269,12 +269,32 @@ impl Executor {
|
||||
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
|
||||
self.shipped_pages += 1;
|
||||
let page_resources = shipout.pdf_objects.map(|objects| objects.resources);
|
||||
let links: Vec<_> = shipout.pdf_links.annotations.iter().filter_map(|annotation| {
|
||||
use crate::pdf_device::{catalog::CatalogAction, links::AnnotationAction};
|
||||
let number = annotation.object_number?;
|
||||
let action = match &annotation.action {
|
||||
AnnotationAction::Catalog(action @ CatalogAction::GoTo { file: None, .. }) => Some(action.clone()),
|
||||
_ => None,
|
||||
};
|
||||
Some((number, action))
|
||||
}).collect();
|
||||
let destinations: Vec<_> = shipout.pdf_links.destinations.iter()
|
||||
.filter_map(|destination| destination.object_number).collect();
|
||||
self.events.push(Event::Shipout(Box::new(shipout)));
|
||||
if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() {
|
||||
Arc::make_mut(probe).observed_events = self.events.len();
|
||||
}
|
||||
self.write_shipout_forms(forms, files)?;
|
||||
if let Some(resources) = page_resources {
|
||||
for (number, action) in links {
|
||||
self.pack_pdf_object(number)?;
|
||||
if let Some(action) = action {
|
||||
self.write_pdf_link_action(&action)?;
|
||||
}
|
||||
}
|
||||
for number in destinations {
|
||||
self.pack_pdf_object(number)?;
|
||||
}
|
||||
self.pack_pdf_object(resources)?;
|
||||
}
|
||||
self.statistics_after_shipout(before, files)?;
|
||||
@@ -435,6 +455,7 @@ impl Executor {
|
||||
if let Some(effects) = &leader_effects {
|
||||
outputs = effects.outputs.iter().collect();
|
||||
}
|
||||
let mut navigation_numbers = (Vec::new(), Vec::new());
|
||||
let mut link_depth = self.pdf_link_stack.len();
|
||||
let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link());
|
||||
let mut output_positions = if let Some(effects) = &leader_effects {
|
||||
@@ -655,11 +676,19 @@ impl Executor {
|
||||
LinkNode::Start(_) if link_depth == 10 => {
|
||||
return self.fail("PDF link stack capacity exceeded");
|
||||
}
|
||||
LinkNode::Start(_) => link_depth += 1,
|
||||
LinkNode::Start(layout) => {
|
||||
link_depth += 1;
|
||||
if !unicode_pages && !for_form {
|
||||
navigation_numbers.0.push(self.register_pdf_link(layout.object_number)?);
|
||||
}
|
||||
}
|
||||
LinkNode::End if link_depth == 0 => {
|
||||
return self.fail("\\pdfendlink used without \\pdfstartlink");
|
||||
}
|
||||
LinkNode::End => link_depth -= 1,
|
||||
LinkNode::Destination { destination, structure, .. } if !unicode_pages && !for_form => {
|
||||
navigation_numbers.1.push(self.register_pdf_destination(destination, structure.is_some())?);
|
||||
}
|
||||
LinkNode::Running(_) | LinkNode::Destination { .. } => {}
|
||||
}
|
||||
} else {
|
||||
@@ -706,7 +735,7 @@ impl Executor {
|
||||
return self.fail("PDF page links and destinations require a page shipout");
|
||||
}
|
||||
let mut links = self.ship_pdf_link_material(
|
||||
b, device, &shipout.pdf_graphics_steps, files,
|
||||
b, device, &shipout.pdf_graphics_steps, navigation_numbers, files,
|
||||
)?;
|
||||
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
||||
shipout.pdf_links = links;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::*;
|
||||
use crate::pdf_device::{
|
||||
Affine, PdfGraphics,
|
||||
catalog::{CatalogAction, CatalogTarget, StructureTarget},
|
||||
links::{
|
||||
AnnotationAction, DestinationId, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
|
||||
PageDestination, PageLinks,
|
||||
@@ -225,14 +226,63 @@ impl Executor {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn register_pdf_link(&mut self, number: Option<u32>) -> Result<u32, Error> {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.ship_link(number, self.limits.tokens)
|
||||
.map_err(|message| self.error(message, self.current))
|
||||
}
|
||||
|
||||
pub(super) fn register_pdf_destination(
|
||||
&mut self, id: &DestinationId<Vec<Token>>, structure: bool,
|
||||
) -> Result<Option<u32>, Error> {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
let id = self.pdf_destination_id(id);
|
||||
self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.destination_number(id, structure, true, self.limits.tokens)
|
||||
.map_err(|message| self.error(message, self.current))
|
||||
}
|
||||
|
||||
pub(super) fn write_pdf_link_action(&mut self, action: &CatalogAction) -> Result<(), Error> {
|
||||
let CatalogAction::GoTo { target, file: None, structure, .. } = action else {
|
||||
return Ok(());
|
||||
};
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
let limit = self.limits.tokens;
|
||||
let objects = self.state.pdf_objects.as_deref_mut().expect("registered PDF link");
|
||||
let allocation = match target {
|
||||
CatalogTarget::Page { number, .. } => objects.page_reference(*number as u32, limit).map(Some),
|
||||
CatalogTarget::Destination(id) => objects.destination_number(id.clone(), false, false, limit),
|
||||
};
|
||||
allocation.map_err(|message| self.error(message, self.current))?;
|
||||
if let Some(StructureTarget::Local(id)) = structure {
|
||||
self.state.pdf_objects.as_deref_mut().expect("registered PDF link")
|
||||
.destination_number(id.clone(), true, false, limit)
|
||||
.map_err(|message| self.error(message, self.current))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pdf_destination_id(&mut self, id: &DestinationId<Vec<Token>>) -> DestinationId<String> {
|
||||
match id {
|
||||
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
|
||||
DestinationId::Number(number) => DestinationId::Number(*number),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn ship_pdf_link_material(
|
||||
&mut self,
|
||||
b: &NativeBox,
|
||||
device: &ShipoutDevice,
|
||||
graphics: &[Option<PdfGraphics>],
|
||||
numbers: (Vec<u32>, Vec<Option<u32>>),
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<PageLinks, Error> {
|
||||
let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width());
|
||||
let numbered = self.state.input_profile() == InputProfile::TeX8Bit;
|
||||
let (links, destinations) = numbers;
|
||||
let mut links = links.into_iter();
|
||||
let mut destinations = destinations.into_iter();
|
||||
let mut active = std::mem::take(&mut self.pdf_link_stack);
|
||||
let mut graphics = graphics.iter();
|
||||
let mut transform = (Affine::IDENTITY, false);
|
||||
@@ -271,7 +321,16 @@ impl Executor {
|
||||
for link in active.iter_mut().filter(|link| {
|
||||
link.level == row.level && link.layout.width.is_none()
|
||||
}) {
|
||||
let number = if numbered {
|
||||
match self.register_pdf_link(None) {
|
||||
Ok(number) => Some(number),
|
||||
Err(error) => { failure = Some(error); return; }
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin);
|
||||
output.annotations.last_mut().unwrap().object_number = number;
|
||||
}
|
||||
}
|
||||
BoxPaint::PdfLink(node, container) => {
|
||||
@@ -293,9 +352,12 @@ impl Executor {
|
||||
let mut start = ActiveLink { layout: layout.clone(), attributes,
|
||||
action, level: container.level, segment: None };
|
||||
start.start_segment(&mut output, container, [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;
|
||||
let number = if numbered { links.next() } else { layout.object_number };
|
||||
if numbered && number.is_none() {
|
||||
failure = Some(self.error("missing PDF link number at shipout", node.span));
|
||||
return;
|
||||
}
|
||||
output.annotations.last_mut().unwrap().object_number = number;
|
||||
active.push(start);
|
||||
}
|
||||
LinkNode::End => {
|
||||
@@ -315,9 +377,15 @@ impl Executor {
|
||||
}
|
||||
LinkNode::Running(enabled) => self.pdf_running_links = *enabled,
|
||||
LinkNode::Destination { destination, view, structure } => {
|
||||
let destination = match destination {
|
||||
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
|
||||
DestinationId::Number(number) => DestinationId::Number(*number),
|
||||
let destination = self.pdf_destination_id(destination);
|
||||
let object_number = if numbered {
|
||||
let Some(number) = destinations.next() else {
|
||||
failure = Some(self.error("missing PDF destination number at shipout", node.span));
|
||||
return;
|
||||
};
|
||||
number
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let view = view.map_rectangle(|[width, height, depth]| {
|
||||
let margin = i64::from(self.read_parameter(Parameter::Pdfdestmargin).width());
|
||||
@@ -331,7 +399,7 @@ impl Executor {
|
||||
}
|
||||
});
|
||||
output.destinations.push(PageDestination {
|
||||
destination, point: map_point(transform.0, x, y), view,
|
||||
object_number, destination, point: map_point(transform.0, x, y), view,
|
||||
structure: *structure,
|
||||
});
|
||||
}
|
||||
@@ -343,6 +411,9 @@ impl Executor {
|
||||
if let Some(error) = failure {
|
||||
return Err(error);
|
||||
}
|
||||
if links.next().is_some() || destinations.next().is_some() {
|
||||
return self.fail("unused PDF navigation numbers at shipout");
|
||||
}
|
||||
for link in &mut active {
|
||||
link.segment = None;
|
||||
}
|
||||
|
||||
@@ -60,6 +60,9 @@ impl Executor {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let number = self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.begin_definition(requested, self.limits.tokens)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
let declaration = self.current;
|
||||
let attributes = if self.keyword("stream", files)? {
|
||||
Some(if self.keyword("attr", files)? {
|
||||
@@ -85,11 +88,8 @@ impl Executor {
|
||||
None => ObjectBody::Direct(bytes),
|
||||
}
|
||||
};
|
||||
let number = self
|
||||
.state
|
||||
.pdf_objects
|
||||
.get_or_insert_with(Default::default)
|
||||
.define(requested, value, self.limits.tokens)
|
||||
self.state.pdf_objects.as_deref_mut().expect("registered PDF object")
|
||||
.define(number, value, self.limits.tokens)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
if immediate {
|
||||
self.pdf_page_data(files)?;
|
||||
|
||||
@@ -1867,12 +1867,23 @@ fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
|
||||
#[derive(Default)]
|
||||
struct PdfNavigation {
|
||||
pages: Vec<usize>,
|
||||
named: BTreeMap<String, String>,
|
||||
named: BTreeMap<String, usize>,
|
||||
numbered: BTreeMap<i32, usize>,
|
||||
structures: BTreeMap<DestinationId<String>, usize>,
|
||||
pending_destinations: BTreeMap<(DestinationId<String>, bool), usize>,
|
||||
threads: BTreeMap<DestinationId<String>, usize>,
|
||||
}
|
||||
|
||||
fn write_destination(objects: &mut Vec<Vec<u8>>, slot: Option<usize>, body: String) -> usize {
|
||||
if let Some(id) = slot {
|
||||
objects[id - 1] = body.into_bytes();
|
||||
id
|
||||
} else {
|
||||
objects.push(body.into_bytes());
|
||||
objects.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn destination_identifier(id: &DestinationId<String>) -> String {
|
||||
match id {
|
||||
DestinationId::Name(name) => format!("name{{{name}}}"),
|
||||
@@ -1886,7 +1897,7 @@ fn catalog_action_bytes(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Vec<u8> {
|
||||
let PdfNavigation { pages, named, numbered, structures, threads } = destinations;
|
||||
let PdfNavigation { pages, named, numbered, structures, pending_destinations, threads } = destinations;
|
||||
let mut output = b"<< ".to_vec();
|
||||
match action {
|
||||
CatalogAction::User(object) => output.clone_from(object),
|
||||
@@ -1911,7 +1922,10 @@ fn catalog_action_bytes(
|
||||
diagnostics.push(format!(
|
||||
"destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one"
|
||||
));
|
||||
named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0]));
|
||||
let slot = pending_destinations.get(&(DestinationId::Name(name.clone()), false)).copied();
|
||||
let view = format!("[{} 0 R /Fit]", pages[0]);
|
||||
let body = if slot.is_some() { format!("<< /D {view} >>") } else { view };
|
||||
named.insert(name.clone(), write_destination(objects, slot, body));
|
||||
}
|
||||
output.extend_from_slice(pdf_text(name).as_bytes());
|
||||
}
|
||||
@@ -1920,8 +1934,8 @@ fn catalog_action_bytes(
|
||||
diagnostics.push(format!(
|
||||
"destination num{number} has been referenced but does not exist, replaced by a fixed one"
|
||||
));
|
||||
objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes());
|
||||
objects.len()
|
||||
let slot = pending_destinations.get(&(DestinationId::Number(*number), false)).copied();
|
||||
write_destination(objects, slot, format!("[{} 0 R /Fit]", pages[0]))
|
||||
});
|
||||
write!(&mut output, "{id} 0 R").unwrap();
|
||||
}
|
||||
@@ -1951,8 +1965,11 @@ fn catalog_action_bytes(
|
||||
destination_identifier(destination)
|
||||
));
|
||||
// pdfTeX leaves the missing destination in the free list.
|
||||
objects.push(Vec::new());
|
||||
objects.len()
|
||||
pending_destinations.get(&(destination.clone(), true)).copied()
|
||||
.unwrap_or_else(|| {
|
||||
objects.push(Vec::new());
|
||||
objects.len()
|
||||
})
|
||||
});
|
||||
write!(&mut output, " /SD {id} 0 R").unwrap();
|
||||
}
|
||||
@@ -2563,6 +2580,17 @@ fn write_pdf(
|
||||
device_objects.insert(stream.number, objects.len() as u32);
|
||||
}
|
||||
}
|
||||
let mut navigation = PdfNavigation::default();
|
||||
if let Some(registry) = registry {
|
||||
for (key, number, defined) in registry.destinations() {
|
||||
objects.push(Vec::new());
|
||||
let id = objects.len();
|
||||
device_objects.insert(number, id as u32);
|
||||
if !defined {
|
||||
navigation.pending_destinations.insert(key.clone(), id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let parents: BTreeSet<_> = pages.iter().filter_map(|page| {
|
||||
page.pdf_resources.objects.map(|allocation| allocation.parent)
|
||||
}).collect();
|
||||
@@ -2598,7 +2626,6 @@ fn write_pdf(
|
||||
}
|
||||
let mut kids = Vec::new();
|
||||
let mut page_groups = BTreeMap::<usize, Vec<usize>>::new();
|
||||
let mut navigation = PdfNavigation::default();
|
||||
let mut annotation_actions = Vec::new();
|
||||
let mut xdv_annotations = Vec::new();
|
||||
let pdf_version = pages
|
||||
@@ -3014,14 +3041,14 @@ fn write_pdf(
|
||||
format!("/FitR {}", coordinates.join(" "))
|
||||
}
|
||||
};
|
||||
let slot = destination.object_number.map(|number| device_objects[&number] as usize);
|
||||
if let Some(number) = destination.structure {
|
||||
use std::collections::btree_map::Entry;
|
||||
match navigation.structures.entry(destination.destination.clone()) {
|
||||
Entry::Vacant(entry) => {
|
||||
let structure = remapped.as_ref().expect("structure objects were remapped")
|
||||
.structure_objects[&number];
|
||||
objects.push(format!("[{structure} 0 R {view}]").into_bytes());
|
||||
entry.insert(objects.len());
|
||||
entry.insert(write_destination(&mut objects, slot, format!("[{structure} 0 R {view}]")));
|
||||
}
|
||||
Entry::Occupied(entry) => diagnostics.push(format!(
|
||||
"structure destination with the same identifier ({}) has been already used, duplicate ignored",
|
||||
@@ -3032,12 +3059,14 @@ fn write_pdf(
|
||||
let object = || format!("[{page_id} 0 R {view}]");
|
||||
match &destination.destination {
|
||||
DestinationId::Name(name) => {
|
||||
navigation.named.entry(name.clone()).or_insert_with(object);
|
||||
navigation.named.entry(name.clone()).or_insert_with(|| {
|
||||
let body = if slot.is_some() { format!("<< /D {} >>", object()) } else { object() };
|
||||
write_destination(&mut objects, slot, body)
|
||||
});
|
||||
}
|
||||
DestinationId::Number(number) => {
|
||||
navigation.numbered.entry(*number).or_insert_with(|| {
|
||||
objects.push(object().into_bytes());
|
||||
objects.len()
|
||||
write_destination(&mut objects, slot, object())
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3056,6 +3085,7 @@ fn write_pdf(
|
||||
}
|
||||
objects[1].extend_from_slice(b" >>");
|
||||
|
||||
let after_pages_tree = objects.len() + 1;
|
||||
for (id, mut body, action) in annotation_actions {
|
||||
body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics));
|
||||
body.extend_from_slice(b" >>");
|
||||
@@ -3236,12 +3266,17 @@ fn write_pdf(
|
||||
let first = pdf_text(destinations.first_key_value().unwrap().0);
|
||||
let last = pdf_text(destinations.last_key_value().unwrap().0);
|
||||
for (name, destination) in destinations {
|
||||
objects.push(destination.into_bytes());
|
||||
entries.push(format!("{} {} 0 R", pdf_text(&name), objects.len()));
|
||||
entries.push(format!("{} {destination} 0 R", pdf_text(&name)));
|
||||
}
|
||||
objects.push(format!("<< /Names [{}] /Limits [{first} {last}] >>",
|
||||
entries.join(" ")).into_bytes());
|
||||
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
|
||||
let tree = objects.len();
|
||||
if pages[0].pdf.as_ref().is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::PdfTeX) {
|
||||
objects.push(format!("<< /Dests {tree} 0 R >>").into_bytes());
|
||||
catalog.push_str(&format!(" /Names {} 0 R", objects.len()));
|
||||
} else {
|
||||
catalog.push_str(&format!(" /Names << /Dests {tree} 0 R >>"));
|
||||
}
|
||||
}
|
||||
objects[0] = if let Some(xdv) = xdv {
|
||||
xdv.finish_catalog(&catalog, &navigation.pages)?
|
||||
@@ -3305,7 +3340,7 @@ fn write_pdf(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(objects::ObjectPacking { streams, uncompressed })
|
||||
Some(objects::ObjectPacking { streams, uncompressed, after_pages_tree })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -90,6 +90,8 @@ pub struct LinkAnnotation {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PageDestination {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub object_number: Option<u32>,
|
||||
pub destination: DestinationId<String>,
|
||||
pub point: [i64; 2],
|
||||
pub view: DestinationView<[i64; 4]>,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Native PDF objects and extra resources captured at page shipout.
|
||||
use crate::execution::FontId;
|
||||
use super::links::DestinationId;
|
||||
use lopdf::{
|
||||
Dictionary, Object, Stream,
|
||||
content::{Content, Operation},
|
||||
@@ -36,6 +37,7 @@ pub(crate) enum ObjectBody {
|
||||
from: String,
|
||||
},
|
||||
ObjectStream,
|
||||
Destination,
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
@@ -44,7 +46,7 @@ impl ObjectBody {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
||||
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::DiscardedAtDump => 0,
|
||||
| Self::Destination | Self::DiscardedAtDump => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -63,7 +65,8 @@ impl ObjectBody {
|
||||
match self {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
|
||||
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream => {
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::Destination => {
|
||||
Err("expected a generic native PDF object".into())
|
||||
}
|
||||
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
||||
@@ -123,6 +126,10 @@ pub struct PdfObjects {
|
||||
// previous output file's pending stream or its cross references.
|
||||
#[serde(skip)]
|
||||
object_streams: Vec<Arc<PdfObjectStream>>,
|
||||
#[serde(skip)]
|
||||
destination_numbers: BTreeMap<(DestinationId<String>, bool), (u32, bool)>,
|
||||
#[serde(skip)]
|
||||
shipped_links: BTreeSet<u32>,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
@@ -307,6 +314,37 @@ impl PdfObjects {
|
||||
self.allocate(Some(Arc::new(ObjectBody::Link)), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn ship_link(&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)
|
||||
{
|
||||
return Ok(number);
|
||||
}
|
||||
let number = self.reserve_link(limit)?;
|
||||
self.shipped_links.insert(number);
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn destination_number(
|
||||
&mut self, id: DestinationId<String>, structure: bool, define: bool, limit: usize,
|
||||
) -> Result<Option<u32>, String> {
|
||||
let key = (id, structure);
|
||||
if let Some((number, defined)) = self.destination_numbers.get_mut(&key) {
|
||||
if define && std::mem::replace(defined, true) {
|
||||
return Ok(None);
|
||||
}
|
||||
return Ok(Some(*number));
|
||||
}
|
||||
let number = self.allocate(Some(Arc::new(ObjectBody::Destination)), limit)?;
|
||||
self.destination_numbers.insert(key, (number, define));
|
||||
Ok(Some(number))
|
||||
}
|
||||
|
||||
pub(crate) fn destinations(&self) -> impl Iterator<Item = (&(DestinationId<String>, bool), u32, bool)> {
|
||||
self.destination_numbers.iter().map(|(key, &(number, defined))| (key, number, defined))
|
||||
}
|
||||
|
||||
pub(crate) fn record_last_link(&mut self, number: u32) {
|
||||
self.last_link = Some(number);
|
||||
}
|
||||
@@ -323,7 +361,7 @@ impl PdfObjects {
|
||||
Some(ObjectBody::Link) => ObjectBody::FormatLink,
|
||||
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
|
||||
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream) => {
|
||||
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination) => {
|
||||
ObjectBody::DiscardedAtDump
|
||||
}
|
||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||
@@ -341,6 +379,8 @@ impl PdfObjects {
|
||||
self.png_group = None;
|
||||
self.written_png_group = None;
|
||||
self.object_streams.clear();
|
||||
self.destination_numbers.clear();
|
||||
self.shipped_links.clear();
|
||||
!self.values.is_empty()
|
||||
}
|
||||
|
||||
@@ -359,25 +399,27 @@ impl PdfObjects {
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn begin_definition(&mut self, requested: Option<u32>, limit: usize) -> Result<u32, String> {
|
||||
requested.map_or_else(|| self.allocate(None, limit), Ok)
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
&mut self,
|
||||
requested: Option<u32>,
|
||||
number: u32,
|
||||
value: ObjectBody,
|
||||
limit: usize,
|
||||
) -> Result<u32, String> {
|
||||
) -> Result<(), String> {
|
||||
let bytes = self.bytes.saturating_add(value.len());
|
||||
if bytes > limit {
|
||||
return Err("native PDF object payload capacity exceeded".into());
|
||||
}
|
||||
let number = match requested {
|
||||
Some(number) if self.is_reserved(number) => number,
|
||||
Some(_) => return Err("native PDF object was already defined".into()),
|
||||
None => self.reserve(limit)?,
|
||||
};
|
||||
if !self.is_reserved(number) {
|
||||
return Err("native PDF object was already defined".into());
|
||||
}
|
||||
self.values[number as usize - 1] = Some(Arc::new(value));
|
||||
self.bytes = bytes;
|
||||
self.last = number as i32;
|
||||
Ok(number)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn unwritten(&self, number: u32) -> Result<Option<&ObjectBody>, String> {
|
||||
@@ -798,7 +840,8 @@ impl ResourceOutput {
|
||||
if values.contains_key(&number) || page_objects.contains(&number)
|
||||
|| 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))
|
||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream
|
||||
| ObjectBody::Destination))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(crate) fn stream_bytes(extra: &[u8], data: &[u8], level: u8) -> Vec<u8> {
|
||||
pub(super) struct ObjectPacking {
|
||||
pub streams: Vec<(usize, Vec<usize>)>,
|
||||
pub uncompressed: Option<usize>,
|
||||
pub after_pages_tree: usize,
|
||||
}
|
||||
|
||||
pub(super) fn serialize(
|
||||
@@ -47,7 +48,7 @@ pub(super) fn serialize(
|
||||
let mut stream_slots = vec![false; objects.len() + 1];
|
||||
let mut next_stream = objects.len() + 1;
|
||||
let execution_order = packing.is_some();
|
||||
let ObjectPacking { streams: mut groups, uncompressed } = packing.unwrap_or_default();
|
||||
let ObjectPacking { streams: mut groups, uncompressed, after_pages_tree } = packing.unwrap_or_default();
|
||||
for (id, members) in &groups {
|
||||
if *id == 0 || *id > objects.len() || !objects[*id - 1].is_empty()
|
||||
|| std::mem::replace(&mut stream_slots[*id], true)
|
||||
@@ -67,10 +68,13 @@ pub(super) fn serialize(
|
||||
}
|
||||
if options.object_compression > 0 {
|
||||
// The page tree precedes the catalog. Info, when eligible, is last.
|
||||
let document_tail = [Some(2), Some(1), info];
|
||||
let order = (1..=objects.len())
|
||||
.filter(|id| !execution_order || !document_tail.contains(&Some(*id)))
|
||||
.chain(document_tail.into_iter().flatten().filter(|_| execution_order));
|
||||
let early = (1..=objects.len()).filter(|id| {
|
||||
!execution_order || (*id >= 3 && *id < after_pages_tree && Some(*id) != info)
|
||||
});
|
||||
let late = (after_pages_tree..=objects.len())
|
||||
.filter(|id| execution_order && Some(*id) != info);
|
||||
let order = early.chain(execution_order.then_some(2)).chain(late)
|
||||
.chain(execution_order.then_some(1)).chain(info.filter(|_| execution_order));
|
||||
for id in order {
|
||||
let body = &objects[id - 1];
|
||||
if body.is_empty() || packed[id].is_some() || Some(id) == uncompressed
|
||||
|
||||
Reference in new issue
Block a user