Write XeLaTeX named PDF objects and streams in native shipout
This commit is contained in:
1 parent
c02f678bf7
commit
e14361fec6
8 files changed
+551
-43
No files matched your search
@@ -1,6 +1,7 @@
|
||||
//! TeX special whatsits and PDF driver dispatch at shipout.
|
||||
use super::*;
|
||||
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode, PdfMatrix};
|
||||
use crate::resources::ResourceKind;
|
||||
|
||||
impl Executor {
|
||||
pub(super) fn scan_special(
|
||||
@@ -68,11 +69,30 @@ impl Executor {
|
||||
return Ok(());
|
||||
}
|
||||
self.reads.insert(Dependency::PdfCatalogState);
|
||||
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||
let warnings = if kind == b"docview" {
|
||||
navigation.merge_catalog(operands, position, self.limits.tokens)
|
||||
let warnings = if matches!(kind, b"docview" | b"outline") {
|
||||
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||
if kind == b"docview" {
|
||||
navigation.merge_catalog(operands, position, self.limits.tokens)
|
||||
} else {
|
||||
navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
||||
}
|
||||
} else {
|
||||
navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
||||
use crate::pdf_device::xdv_navigation::ObjectCommand;
|
||||
let mut command = ObjectCommand::parse(kind, operands, position)
|
||||
.map_err(|error| self.error(error, special.span))?;
|
||||
let size = command.load_file(|name| {
|
||||
let from = self.source_name(special.span);
|
||||
self.reads.insert(Dependency::FileLookup {
|
||||
name: name.to_owned(),
|
||||
from: from.clone(),
|
||||
});
|
||||
files.resource(ResourceKind::PdfImage, name, &from)
|
||||
.map(|resource| resource.data)
|
||||
.map_err(|error| format!("cannot open XDV PDF stream file {name}: {error}"))
|
||||
}).map_err(|error| self.error(error, special.span))?;
|
||||
self.check_cancellation()?;
|
||||
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||
navigation.apply_object(command, operands.len().saturating_add(size), self.limits.tokens)
|
||||
}.map_err(|error| self.error(error, special.span))?;
|
||||
for warning in warnings {
|
||||
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
|
||||
@@ -318,6 +338,8 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8
|
||||
for (name, kind) in [
|
||||
(b"dest".as_slice(), b"dest".as_slice()), (b"destination", b"dest"),
|
||||
(b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"),
|
||||
(b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"),
|
||||
(b"stream", b"stream"), (b"fstream", b"fstream"),
|
||||
] {
|
||||
if let Some(operands) = xdv_operand(body, name) {
|
||||
return Some((kind, operands));
|
||||
|
||||
@@ -3510,13 +3510,27 @@ fn write_pdf(
|
||||
xdv_names.entry(name.to_vec()).or_insert_with(|| format!("{index:x}").into_bytes());
|
||||
}
|
||||
}
|
||||
let empty_xdv = crate::pdf_device::xdv_navigation::Navigation::default();
|
||||
let xdv_objects = xdv.unwrap_or(&empty_xdv);
|
||||
let mut pending = Vec::new();
|
||||
xdv_objects.collect_references(&mut pending);
|
||||
for (_, annotation) in &xdv_annotations {
|
||||
annotation.collect_references(&mut pending);
|
||||
}
|
||||
let named_objects = xdv_objects.reserve_objects(pending, &mut objects)?;
|
||||
let references = crate::pdf_device::xdv_object::References {
|
||||
pages: &navigation.pages,
|
||||
named: &named_objects,
|
||||
};
|
||||
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
||||
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
|
||||
for (id, annotation) in xdv_annotations {
|
||||
objects[id - 1] = annotation.pdf(&navigation.pages, &xdv_names)?;
|
||||
objects[id - 1] = annotation.pdf(&references, &xdv_names)?;
|
||||
}
|
||||
if let Some(xdv) = xdv {
|
||||
let open_depth = unicode.unwrap().xdv_outline_open_depth;
|
||||
if let Some(outlines) = xdv.write_outlines(
|
||||
&navigation.pages, &mut objects, &xdv_names, open_depth,
|
||||
&references, &mut objects, &xdv_names, open_depth,
|
||||
)? {
|
||||
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
|
||||
}
|
||||
@@ -3593,7 +3607,7 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
objects[0] = if let Some(xdv) = xdv {
|
||||
xdv.finish_catalog(&catalog, &navigation.pages)?
|
||||
xdv.finish_catalog(&catalog, &references)?
|
||||
} else {
|
||||
let mut catalog = catalog.into_bytes();
|
||||
if let Some(extra) = extra {
|
||||
|
||||
@@ -5,7 +5,7 @@ use lopdf::Object;
|
||||
|
||||
use super::xdv_navigation::read_fields;
|
||||
use super::xdv_object::{
|
||||
Dictionary, Position, atom, encode_device_value, output_with_destination, target_name, trim_pdf,
|
||||
Dictionary, Position, References, atom, encode_device_value, output_with_destination, target_name, trim_pdf,
|
||||
};
|
||||
use super::{Affine, xdv_image};
|
||||
|
||||
@@ -50,12 +50,18 @@ impl Annotation {
|
||||
target_name(&self.fields).map(|name| (self.order, name))
|
||||
}
|
||||
|
||||
pub(crate) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
for value in self.fields.values() {
|
||||
value.collect_references(pending);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pdf(
|
||||
&self,
|
||||
pages: &[usize],
|
||||
references: &References<'_>,
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut dictionary = output_with_destination(&self.fields, pages, names)?;
|
||||
let mut dictionary = output_with_destination(&self.fields, references, names)?;
|
||||
dictionary.set(
|
||||
"Rect",
|
||||
Object::Array(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Document-view state and outlines produced by XDV specials.
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use lopdf::Object;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -7,16 +7,22 @@ use serde::{Deserialize, Serialize};
|
||||
use super::page_resources::parse_value;
|
||||
use super::xdv_annotation::Order;
|
||||
use super::xdv_object::{
|
||||
Dictionary, Position, Value, atom, dictionary, encode_device_value, output_dictionary,
|
||||
Dictionary, Position, References, Value, atom, dictionary, encode_device_value, output_dictionary,
|
||||
output_with_destination, target_name, trim_pdf,
|
||||
};
|
||||
|
||||
mod named_objects;
|
||||
pub(crate) use named_objects::ObjectCommand;
|
||||
use named_objects::NamedObject;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(crate) struct Navigation {
|
||||
catalog: Dictionary,
|
||||
outlines: Vec<Outline>,
|
||||
lowest_level: Option<i32>,
|
||||
payload: usize,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
objects: BTreeMap<Vec<u8>, NamedObject>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -92,11 +98,66 @@ impl Navigation {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn finish_catalog(&self, base: &str, pages: &[usize]) -> Result<Vec<u8>, String> {
|
||||
pub(crate) fn apply_object(
|
||||
&mut self,
|
||||
command: ObjectCommand,
|
||||
bytes: usize,
|
||||
limit: usize,
|
||||
) -> Result<Vec<String>, String> {
|
||||
self.add_payload(bytes, limit)?;
|
||||
command.apply(&mut self.catalog, &mut self.objects)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
for value in self.catalog.values().chain(self.outlines.iter().flat_map(|o| o.fields.values())) {
|
||||
value.collect_references(pending);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_objects<'a>(
|
||||
&'a self,
|
||||
mut pending: Vec<&'a [u8]>,
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
) -> Result<BTreeMap<Vec<u8>, u32>, String> {
|
||||
let mut names = BTreeSet::new();
|
||||
while let Some(name) = pending.pop() {
|
||||
if names.insert(name) && let Some(object) = self.objects.get(name) {
|
||||
object.collect_references(&mut pending);
|
||||
}
|
||||
}
|
||||
names.into_iter().map(|name| {
|
||||
objects.push(Vec::new());
|
||||
let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?;
|
||||
Ok((name.to_vec(), id))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn write_objects(
|
||||
&self,
|
||||
references: &References<'_>,
|
||||
objects: &mut [Vec<u8>],
|
||||
compression: u8,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
for (name, &id) in references.named {
|
||||
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
||||
object.pdf(references, compression)?
|
||||
} else {
|
||||
diagnostics.push(format!(
|
||||
"xdvipdfmx: warning: Object @{} used, but not defined. Replaced by null.",
|
||||
String::from_utf8_lossy(name)
|
||||
));
|
||||
b"null".to_vec()
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn finish_catalog(&self, base: &str, references: &References<'_>) -> Result<Vec<u8>, String> {
|
||||
let Object::Dictionary(mut catalog) = parse_value(format!("{base} >>").as_bytes())? else {
|
||||
unreachable!("native PDF catalog is a dictionary");
|
||||
};
|
||||
let additions = output_dictionary(&self.catalog, pages)?;
|
||||
let additions = output_dictionary(&self.catalog, references)?;
|
||||
for (key, value) in &additions {
|
||||
match key.as_slice() {
|
||||
b"Type" | b"Pages" => {}
|
||||
@@ -124,7 +185,7 @@ impl Navigation {
|
||||
|
||||
pub(crate) fn write_outlines(
|
||||
&self,
|
||||
pages: &[usize],
|
||||
references: &References<'_>,
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
open_depth: usize,
|
||||
@@ -181,7 +242,7 @@ impl Navigation {
|
||||
objects.push(encode_device_value(Object::Dictionary(fields))?);
|
||||
for (offset, outline) in self.outlines.iter().enumerate() {
|
||||
let entry = &entries[offset + 1];
|
||||
let mut fields = output_with_destination(&outline.fields, pages, names)?;
|
||||
let mut fields = output_with_destination(&outline.fields, references, names)?;
|
||||
fields.set("Parent", object(entry.parent));
|
||||
for field in [b"Prev".as_slice(), b"Next", b"First", b"Last", b"Count"] {
|
||||
fields.remove(field);
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::pdf::objects::stream_bytes;
|
||||
|
||||
use super::super::xdv_object::{identifier, parse_object, parse_object_prefix, trim_pdf};
|
||||
use super::{Dictionary, Position, References, Value, encode_device_value, output_dictionary};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct NamedObject {
|
||||
data: ObjectData,
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
enum ObjectData {
|
||||
Value(Value),
|
||||
Stream {
|
||||
attributes: Dictionary,
|
||||
data: Arc<[u8]>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) struct ObjectCommand {
|
||||
name: Vec<u8>,
|
||||
change: Change,
|
||||
}
|
||||
|
||||
enum Change {
|
||||
Define(ObjectData),
|
||||
FileStream {
|
||||
attributes: Dictionary,
|
||||
filename: String,
|
||||
},
|
||||
Put(Vec<Value>),
|
||||
Close,
|
||||
}
|
||||
|
||||
impl ObjectCommand {
|
||||
pub(crate) fn parse(kind: &[u8], bytes: &[u8], position: Position) -> Result<Self, String> {
|
||||
let (name, rest) = identifier(bytes)?;
|
||||
let rest = trim_pdf(rest);
|
||||
let change = match kind {
|
||||
b"obj" => Change::Define(ObjectData::Value(parse_object(rest, position)?)),
|
||||
b"stream" | b"fstream" => {
|
||||
let (input, trailing) = parse_object_prefix(rest, position)?;
|
||||
let Value::String(input) = input else {
|
||||
return Err("expected a PDF string for XDV stream input".into());
|
||||
};
|
||||
let attributes = if trailing.is_empty() {
|
||||
Dictionary::new()
|
||||
} else {
|
||||
super::dictionary(trailing, position)?
|
||||
};
|
||||
if kind == b"fstream" {
|
||||
let filename =
|
||||
String::from_utf8(input).map_err(|_| "XDV stream filename is not UTF-8")?;
|
||||
Change::FileStream {
|
||||
attributes,
|
||||
filename,
|
||||
}
|
||||
} else {
|
||||
Change::Define(ObjectData::Stream {
|
||||
attributes,
|
||||
data: input.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
b"put" => {
|
||||
let mut values = Vec::new();
|
||||
let mut remaining = rest;
|
||||
while !remaining.is_empty() {
|
||||
let (value, trailing) = parse_object_prefix(remaining, position)?;
|
||||
values.push(value);
|
||||
remaining = trailing;
|
||||
}
|
||||
if values.is_empty() {
|
||||
return Err("missing object to put into XDV PDF object".into());
|
||||
}
|
||||
Change::Put(values)
|
||||
}
|
||||
b"close" if rest.is_empty() => Change::Close,
|
||||
b"close" => return Err("unexpected material after XDV PDF object identifier".into()),
|
||||
_ => unreachable!("recognized XDV PDF object special"),
|
||||
};
|
||||
Ok(Self {
|
||||
name: name.to_vec(),
|
||||
change,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn load_file(
|
||||
&mut self,
|
||||
read: impl FnOnce(&str) -> Result<Vec<u8>, String>,
|
||||
) -> Result<usize, String> {
|
||||
let Change::FileStream {
|
||||
attributes,
|
||||
filename,
|
||||
} = &mut self.change
|
||||
else {
|
||||
return Ok(0);
|
||||
};
|
||||
let data = read(filename)?;
|
||||
let length = data.len();
|
||||
self.change = Change::Define(ObjectData::Stream {
|
||||
attributes: std::mem::take(attributes),
|
||||
data: data.into(),
|
||||
});
|
||||
Ok(length)
|
||||
}
|
||||
|
||||
pub(super) fn apply(
|
||||
self,
|
||||
catalog: &mut Dictionary,
|
||||
objects: &mut BTreeMap<Vec<u8>, NamedObject>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let Self { name, change } = self;
|
||||
let display = String::from_utf8_lossy(&name);
|
||||
let warning = |message: String| vec![format!("xdvipdfmx: warning: {message}\n")];
|
||||
if name == b"catalog"
|
||||
&& let Change::Put(values) = change
|
||||
{
|
||||
catalog.append(&mut only_dictionary(values)?);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if matches!(
|
||||
name.as_slice(),
|
||||
b"catalog"
|
||||
| b"pages"
|
||||
| b"thispage"
|
||||
| b"prevpage"
|
||||
| b"nextpage"
|
||||
| b"names"
|
||||
| b"resources"
|
||||
| b"docinfo"
|
||||
| b"xpos"
|
||||
| b"ypos",
|
||||
) {
|
||||
return Err(format!(
|
||||
"unsupported mutation of XDV PDF device object @{display}"
|
||||
));
|
||||
}
|
||||
|
||||
match change {
|
||||
Change::Define(data) => {
|
||||
use std::collections::btree_map::Entry;
|
||||
match objects.entry(name.clone()) {
|
||||
Entry::Occupied(_) => {
|
||||
return Ok(warning(format!("Object @{display} already defined.")));
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(NamedObject {
|
||||
data,
|
||||
closed: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Change::Put(values) => {
|
||||
let object = objects
|
||||
.get_mut(&name)
|
||||
.ok_or_else(|| format!("XDV PDF object @{display} is not defined"))?;
|
||||
if object.closed {
|
||||
return Err(format!("XDV PDF object @{display} is closed"));
|
||||
}
|
||||
match &mut object.data {
|
||||
ObjectData::Value(Value::Array(items)) => items.extend(values),
|
||||
ObjectData::Value(Value::Dictionary(fields))
|
||||
| ObjectData::Stream {
|
||||
attributes: fields, ..
|
||||
} => {
|
||||
fields.append(&mut only_dictionary(values)?);
|
||||
}
|
||||
_ => return Err(format!("XDV PDF object @{display} cannot be extended")),
|
||||
}
|
||||
}
|
||||
Change::Close => match objects.get_mut(&name) {
|
||||
Some(object) if !object.closed => object.closed = true,
|
||||
Some(_) => return Ok(warning(format!("Object @{display} already closed."))),
|
||||
None => {
|
||||
return Ok(warning(format!(
|
||||
"Cannot close undefined object @{display}."
|
||||
)));
|
||||
}
|
||||
},
|
||||
Change::FileStream { .. } => unreachable!("file stream was loaded at shipout"),
|
||||
}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn only_dictionary(values: Vec<Value>) -> Result<Dictionary, String> {
|
||||
let mut values = values.into_iter();
|
||||
match (values.next(), values.next()) {
|
||||
(Some(Value::Dictionary(fields)), None) => Ok(fields),
|
||||
_ => Err("XDV PDF dictionary merge requires one dictionary".into()),
|
||||
}
|
||||
}
|
||||
|
||||
impl NamedObject {
|
||||
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
match &self.data {
|
||||
ObjectData::Value(value) => value.collect_references(pending),
|
||||
ObjectData::Stream { attributes, .. } => {
|
||||
for value in attributes.values() {
|
||||
value.collect_references(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn pdf(
|
||||
&self,
|
||||
references: &References<'_>,
|
||||
compression: u8,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
match &self.data {
|
||||
ObjectData::Value(value) => encode_device_value(value.output(references)?),
|
||||
ObjectData::Stream { attributes, data } => {
|
||||
let mut attributes = output_dictionary(attributes, references)?;
|
||||
attributes.remove(b"Length");
|
||||
let compression = if attributes.has(b"Filter") {
|
||||
0
|
||||
} else {
|
||||
compression
|
||||
};
|
||||
let dictionary = encode_device_value(lopdf::Object::Dictionary(attributes))?;
|
||||
Ok(stream_bytes(
|
||||
&dictionary[2..dictionary.len() - 2],
|
||||
data,
|
||||
compression,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,23 @@ pub(super) fn page_reference(page: &[u8], current_page: usize) -> Option<usize>
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the same identifier alphabet as the device's special scanner.
|
||||
pub(super) fn identifier(input: &[u8]) -> Result<(&[u8], &[u8]), String> {
|
||||
let name = trim_pdf(input)
|
||||
.strip_prefix(b"@")
|
||||
.ok_or("missing XDV PDF object identifier")?;
|
||||
let length = name
|
||||
.iter()
|
||||
.take_while(|byte| {
|
||||
byte.is_ascii_alphanumeric() || b"!\"#$&'*+,-.:;=?@\\^_`|~".contains(byte)
|
||||
})
|
||||
.count();
|
||||
if length == 0 {
|
||||
return Err("empty XDV PDF object identifier".into());
|
||||
}
|
||||
Ok(name.split_at(length))
|
||||
}
|
||||
|
||||
pub(super) type Dictionary = BTreeMap<Vec<u8>, Value>;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -89,6 +106,7 @@ pub(super) enum Value {
|
||||
Page(usize),
|
||||
Catalog,
|
||||
PageTree,
|
||||
Named(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -119,32 +137,41 @@ impl Position {
|
||||
}
|
||||
b"@catalog" => Ok(Value::Catalog),
|
||||
b"@pages" => Ok(Value::PageTree),
|
||||
_ => page_reference(token, self.page)
|
||||
.map(Value::Page)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"unsupported XDV PDF object reference {}",
|
||||
String::from_utf8_lossy(token)
|
||||
)
|
||||
}),
|
||||
b"@prevpage" => self.page.checked_sub(1).filter(|page| *page > 0)
|
||||
.map(Value::Page).ok_or_else(|| "XDV has no previous page".into()),
|
||||
b"@names" | b"@resources" | b"@docinfo" => Err(format!(
|
||||
"unsupported XDV PDF device reference {}",
|
||||
String::from_utf8_lossy(token)
|
||||
)),
|
||||
_ => Ok(match page_reference(token, self.page) {
|
||||
Some(page) => Value::Page(page),
|
||||
None => Value::Named(token[1..].to_vec()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dictionary(input: &[u8], position: Position) -> Result<Dictionary, String> {
|
||||
let mut parser = Parser {
|
||||
rest: input,
|
||||
position,
|
||||
};
|
||||
let Value::Dictionary(dictionary) = parser.value(0)? else {
|
||||
let Value::Dictionary(dictionary) = parse_object(input, position)? else {
|
||||
return Err("expected an XDV PDF dictionary".into());
|
||||
};
|
||||
if !trim_pdf(parser.rest).is_empty() {
|
||||
return Err("unexpected material after XDV PDF dictionary".into());
|
||||
}
|
||||
Ok(dictionary)
|
||||
}
|
||||
|
||||
pub(super) fn parse_object(bytes: &[u8], position: Position) -> Result<Value, String> {
|
||||
let (value, rest) = parse_object_prefix(bytes, position)?;
|
||||
if !rest.is_empty() {
|
||||
return Err("unexpected material after XDV PDF object".into());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> Result<(Value, &[u8]), String> {
|
||||
let mut parser = Parser { rest: bytes, position };
|
||||
let value = parser.value(0)?;
|
||||
Ok((value, trim_pdf(parser.rest)))
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
rest: &'a [u8],
|
||||
position: Position,
|
||||
@@ -184,15 +211,18 @@ impl Parser<'_> {
|
||||
return Ok(Value::Array(array));
|
||||
}
|
||||
|
||||
if self.rest.starts_with(b"@") {
|
||||
let (name, rest) = identifier(self.rest)?;
|
||||
let token = &self.rest[..name.len() + 1];
|
||||
self.rest = rest;
|
||||
return self.position.reference(token);
|
||||
}
|
||||
let (token, rest) = match self.rest.first() {
|
||||
Some(b'(' | b'<') => split_string(self.rest)?,
|
||||
Some(_) => atom(self.rest),
|
||||
None => return Err("unexpected end of XDV PDF object".into()),
|
||||
};
|
||||
self.rest = rest;
|
||||
if token.starts_with(b"@") {
|
||||
return self.position.reference(token);
|
||||
}
|
||||
match parse_value(token)? {
|
||||
Object::Null => Ok(Value::Null),
|
||||
Object::Boolean(value) => Ok(Value::Boolean(value)),
|
||||
@@ -205,18 +235,23 @@ impl Parser<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct References<'a> {
|
||||
pub(crate) pages: &'a [usize],
|
||||
pub(crate) named: &'a BTreeMap<Vec<u8>, u32>,
|
||||
}
|
||||
|
||||
pub(super) fn output_dictionary(
|
||||
dictionary: &Dictionary,
|
||||
pages: &[usize],
|
||||
references: &References<'_>,
|
||||
) -> Result<lopdf::Dictionary, String> {
|
||||
dictionary
|
||||
.iter()
|
||||
.map(|(key, value)| Ok((key.clone(), value.output(pages)?)))
|
||||
.map(|(key, value)| Ok((key.clone(), value.output(references)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Value {
|
||||
fn output(&self, pages: &[usize]) -> Result<Object, String> {
|
||||
pub(super) fn output(&self, references: &References<'_>) -> Result<Object, String> {
|
||||
Ok(match self {
|
||||
Self::Null => Object::Null,
|
||||
Self::Boolean(value) => Object::Boolean(*value),
|
||||
@@ -227,14 +262,14 @@ impl Value {
|
||||
Self::Array(values) => Object::Array(
|
||||
values
|
||||
.iter()
|
||||
.map(|value| value.output(pages))
|
||||
.map(|value| value.output(references))
|
||||
.collect::<Result<_, _>>()?,
|
||||
),
|
||||
Self::Dictionary(dictionary) => {
|
||||
Object::Dictionary(output_dictionary(dictionary, pages)?)
|
||||
Object::Dictionary(output_dictionary(dictionary, references)?)
|
||||
}
|
||||
Self::Page(page) => {
|
||||
let id = pages
|
||||
let id = references.pages
|
||||
.get(page - 1)
|
||||
.ok_or_else(|| format!("XDV PDF object refers to nonexistent page {page}"))?;
|
||||
Object::Reference((
|
||||
@@ -244,11 +279,32 @@ impl Value {
|
||||
}
|
||||
Self::Catalog => Object::Reference((1, 0)),
|
||||
Self::PageTree => Object::Reference((2, 0)),
|
||||
Self::Named(name) => Object::Reference((
|
||||
*references.named.get(name).ok_or("unallocated XDV PDF object reference")?,
|
||||
0,
|
||||
)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
match self {
|
||||
Self::Named(name) => pending.push(name),
|
||||
Self::Array(items) => {
|
||||
for item in items {
|
||||
item.collect_references(pending);
|
||||
}
|
||||
}
|
||||
Self::Dictionary(fields) => {
|
||||
for field in fields.values() {
|
||||
field.collect_references(pending);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec<String>) {
|
||||
match self {
|
||||
Self::String(bytes) => {
|
||||
@@ -293,10 +349,10 @@ pub(super) fn target_name(fields: &Dictionary) -> Option<&[u8]> {
|
||||
|
||||
pub(super) fn output_with_destination(
|
||||
fields: &Dictionary,
|
||||
pages: &[usize],
|
||||
references: &References<'_>,
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
) -> Result<lopdf::Dictionary, String> {
|
||||
let mut dictionary = output_dictionary(fields, pages)?;
|
||||
let mut dictionary = output_dictionary(fields, references)?;
|
||||
if let Some(compact) = target_name(fields).and_then(|name| names.get(name)) {
|
||||
let compact = Object::String(compact.clone(), StringFormat::Hexadecimal);
|
||||
if dictionary.has(b"Dest") {
|
||||
|
||||
@@ -814,3 +814,87 @@ fn xdv_root_annotation_keeps_its_extent_and_destination_across_shipouts() {
|
||||
assert_eq!(names[2].as_str().unwrap(), b"1");
|
||||
assert_eq!(names[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdv_named_objects_keep_forward_edges_and_file_streams_at_shipout() {
|
||||
use lopdf::{Document, Object};
|
||||
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
|
||||
use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion};
|
||||
|
||||
struct Device;
|
||||
impl SourceProvider for Device {
|
||||
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
|
||||
Err(format!("unexpected input {name}"))
|
||||
}
|
||||
|
||||
fn default_pk_resolution(&mut self) -> Result<i32, String> {
|
||||
Ok(600)
|
||||
}
|
||||
|
||||
fn resource(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<LoadedResource, String> {
|
||||
assert_eq!((kind, name, from), (ResourceKind::PdfImage, "object.bin", "profile.tex"));
|
||||
Ok(LoadedResource {
|
||||
version: ResourceVersion {
|
||||
path: name.into(),
|
||||
bytes: 3,
|
||||
sha256: "5240672d7b51756b829ad0ef8d9468b7a078afa2f410484fd3892dab47becb72".into(),
|
||||
},
|
||||
data: vec![0, 128, 255],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
|
||||
let result = Executor::new(state, Limits::default())
|
||||
.with_native_pages()
|
||||
.run(
|
||||
source(
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\setbox0=\hbox{\special{pdf:obj @discarded << /bad true >>}}
|
||||
\shipout\hbox{
|
||||
\special{pdf:put @catalog << /Data @root /Missing @missing >>}
|
||||
\special{pdf:object @root << /Self @root /Page @nextpage /Items @items >>}
|
||||
\special{pdf:obj @items [1]}
|
||||
\special{pdf:put @items 2 @binary}
|
||||
\special{pdf:fstream @binary (object.bin) << /Tag /First >>}
|
||||
\special{pdf:put @binary << /Tag /Final >>}
|
||||
\special{pdf:close @root}
|
||||
\vrule width7pt height8pt}
|
||||
\shipout\hbox{
|
||||
\special{pdf:put @catalog << /Same @root >>}
|
||||
\vrule width9pt height8pt}
|
||||
\end",
|
||||
),
|
||||
&mut Device,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.reads.contains(&Dependency::FileLookup {
|
||||
name: "object.bin".to_owned(),
|
||||
from: "profile.tex".to_owned(),
|
||||
}));
|
||||
|
||||
let pages = result.shipout_display_lists().unwrap();
|
||||
let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
|
||||
assert!(output.diagnostics.iter().any(|warning| warning.contains("Object @missing used, but not defined")));
|
||||
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||
let catalog = pdf.catalog().unwrap();
|
||||
let id = catalog.get(b"Data").unwrap().as_reference().unwrap();
|
||||
assert_eq!(catalog.get(b"Same").unwrap().as_reference().unwrap(), id);
|
||||
let root = pdf.get_object(id).unwrap().as_dict().unwrap();
|
||||
assert_eq!(root.get(b"Self").unwrap().as_reference().unwrap(), id);
|
||||
assert_eq!(root.get(b"Page").unwrap().as_reference().unwrap(), pdf.get_pages()[&2]);
|
||||
let items = pdf.get_object(root.get(b"Items").unwrap().as_reference().unwrap()).unwrap().as_array().unwrap();
|
||||
assert_eq!(items[0].as_i64().unwrap(), 1);
|
||||
assert_eq!(items[1].as_i64().unwrap(), 2);
|
||||
let stream = pdf.get_object(items[2].as_reference().unwrap()).unwrap().as_stream().unwrap();
|
||||
assert_eq!(stream.dict.get(b"Tag").unwrap().as_name().unwrap(), b"Final");
|
||||
let bytes = if stream.dict.has(b"Filter") {
|
||||
stream.decompressed_content().unwrap()
|
||||
} else {
|
||||
stream.content.clone()
|
||||
};
|
||||
assert_eq!(bytes, [0, 128, 255]);
|
||||
let missing = catalog.get(b"Missing").unwrap().as_reference().unwrap();
|
||||
assert!(matches!(pdf.get_object(missing), Ok(Object::Null)));
|
||||
assert!(!output.bytes.windows(4).any(|window| window == b"/bad"));
|
||||
}
|
||||
Reference in new issue
Block a user