Write XeLaTeX named PDF objects and streams in native shipout

This commit is contained in:
gloamxun committed 2026-11-28 18:22:15 +08:00
1 parent c02f678bf7
commit e14361fec6
8 files changed
+551 -43

No files matched your search

@@ -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") {