Render XeLaTeX shared page resources and scoped graphics
This commit is contained in:
1 parent
e20acc3eb9
commit
009fde04f7
13 files changed
+445
-12
No files matched your search
@@ -12,6 +12,9 @@ pub enum PdfLiteralMode {
|
||||
XdvDirect,
|
||||
/// XDV page content relative to the special, inside a local graphics state.
|
||||
XdvContent,
|
||||
XdvBeginContent,
|
||||
XdvEndContent,
|
||||
XdvCode,
|
||||
}
|
||||
|
||||
impl PdfLiteralMode {
|
||||
|
||||
@@ -13,6 +13,8 @@ use super::xdv_object::{
|
||||
|
||||
mod named_objects;
|
||||
mod page_dictionaries;
|
||||
mod page_resources;
|
||||
use page_resources::PageResources;
|
||||
use page_dictionaries::PageDictionaries;
|
||||
pub(crate) use named_objects::ObjectCommand;
|
||||
use named_objects::NamedObject;
|
||||
@@ -27,6 +29,8 @@ pub(crate) struct Navigation {
|
||||
objects: BTreeMap<Vec<u8>, NamedObject>,
|
||||
#[serde(default, skip_serializing_if = "PageDictionaries::is_empty")]
|
||||
page_dictionaries: PageDictionaries,
|
||||
#[serde(default, skip_serializing_if = "PageResources::is_empty")]
|
||||
page_resources: PageResources,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -118,6 +122,7 @@ impl Navigation {
|
||||
value.collect_references(pending);
|
||||
}
|
||||
self.page_dictionaries.collect_references(pending);
|
||||
self.page_resources.collect_references(pending);
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_objects<'a>(
|
||||
|
||||
@@ -131,6 +131,11 @@ impl ObjectCommand {
|
||||
fields.append(&mut only_dictionary(values)?);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if name == b"resources"
|
||||
&& let Change::Put(values) = change
|
||||
{
|
||||
return navigation.put_resources(only_dictionary(values)?);
|
||||
}
|
||||
let objects = &mut navigation.objects;
|
||||
if matches!(
|
||||
name.as_slice(),
|
||||
@@ -207,6 +212,13 @@ fn only_dictionary(values: Vec<Value>) -> Result<Dictionary, String> {
|
||||
}
|
||||
|
||||
impl NamedObject {
|
||||
pub(super) fn dictionary_mut(&mut self) -> Option<&mut Dictionary> {
|
||||
match &mut self.data {
|
||||
ObjectData::Value(Value::Dictionary(fields)) if !self.closed => Some(fields),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn value(&self) -> Option<&Value> {
|
||||
match &self.data {
|
||||
ObjectData::Value(value) => Some(value),
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
use std::collections::{BTreeMap, btree_map::Entry};
|
||||
use std::sync::Arc;
|
||||
|
||||
use lopdf::{Dictionary as PdfDictionary, Object};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
Dictionary, NamedObject, Navigation, Position, References, Value, dictionary,
|
||||
encode_device_value, output_dictionary, parse_value,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct PageResources {
|
||||
current: Dictionary,
|
||||
defaults: Arc<Dictionary>,
|
||||
pages: BTreeMap<usize, Dictionary>,
|
||||
}
|
||||
|
||||
impl PageResources {
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.current.is_empty() && self.defaults.is_empty() && self.pages.is_empty()
|
||||
}
|
||||
|
||||
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
for field in self.pages.values().flat_map(Dictionary::values) {
|
||||
field.collect_references(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Navigation {
|
||||
pub(super) fn put_resources(&mut self, additions: Dictionary) -> Result<Vec<String>, String> {
|
||||
self.merge_resources(additions, false)
|
||||
}
|
||||
|
||||
pub(crate) fn set_page_resources(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
position: Position,
|
||||
limit: usize,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let defaults = dictionary(bytes, position)?;
|
||||
self.add_payload(bytes.len(), limit)?;
|
||||
self.page_resources.defaults = Arc::new(defaults);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
pub(crate) fn has_pending_page_resources(&self) -> bool {
|
||||
!self.page_resources.current.is_empty() || !self.page_resources.defaults.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn finish_page_resources(&mut self, page: usize) -> Result<Vec<String>, String> {
|
||||
let messages = self.merge_resources((*self.page_resources.defaults).clone(), true)?;
|
||||
let resources = std::mem::take(&mut self.page_resources.current);
|
||||
if !resources.is_empty() {
|
||||
self.page_resources.pages.insert(page, resources);
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn merge_resources(
|
||||
&mut self,
|
||||
additions: Dictionary,
|
||||
deferred: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut messages = Vec::new();
|
||||
for (category, value) in additions {
|
||||
let current = self.page_resources.current.entry(category);
|
||||
match (current, value) {
|
||||
(Entry::Vacant(entry), Value::Dictionary(data)) => {
|
||||
entry.insert(Value::Dictionary(data));
|
||||
}
|
||||
(Entry::Vacant(entry), Value::Named(name)) => {
|
||||
if deferred {
|
||||
category_fields(&self.objects, &name)?;
|
||||
}
|
||||
entry.insert(Value::Named(name));
|
||||
}
|
||||
(Entry::Occupied(mut entry), Value::Dictionary(data)) => {
|
||||
let existing = match entry.get_mut() {
|
||||
Value::Dictionary(fields) => fields,
|
||||
Value::Named(name) => category_fields_mut(&mut self.objects, name)?,
|
||||
_ => unreachable!("validated resource category"),
|
||||
};
|
||||
append_missing(existing, data, deferred, &mut messages);
|
||||
}
|
||||
(Entry::Occupied(mut entry), Value::Named(name)) => {
|
||||
let old = match entry.get() {
|
||||
Value::Dictionary(fields) => fields.clone(),
|
||||
Value::Named(old) if *old == name => continue,
|
||||
Value::Named(old) => category_fields(&self.objects, old)?.clone(),
|
||||
_ => unreachable!("validated resource category"),
|
||||
};
|
||||
let destination = category_fields_mut(&mut self.objects, &name)?;
|
||||
append_missing(destination, old, deferred, &mut messages);
|
||||
entry.insert(Value::Named(name));
|
||||
}
|
||||
(_, _) => {
|
||||
return Err(
|
||||
"XDV resource category requires a dictionary or named reference".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
pub(crate) fn mark_resource_previews(&self, pages: &mut [crate::render::DisplayList]) {
|
||||
for &page in self.page_resources.pages.keys() {
|
||||
if let Some(list) = pages.get_mut(page - 1) {
|
||||
list.pdf_resources.needs_pdf_for_preview = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_page_resources(
|
||||
&self,
|
||||
references: &References<'_>,
|
||||
objects: &mut [Vec<u8>],
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
for (&page, fields) in &self.page_resources.pages {
|
||||
let id = *references
|
||||
.pages
|
||||
.get(page - 1)
|
||||
.ok_or("unallocated XDV resource page")?;
|
||||
let mut dictionary = pdf_dictionary(&objects[id - 1])?;
|
||||
let mut resources = dictionary
|
||||
.remove(b"Resources")
|
||||
.ok_or("XDV page is missing its generated resource dictionary")?
|
||||
.as_dict()
|
||||
.map_err(|_| "expected inline XDV resource dictionary")?
|
||||
.clone();
|
||||
for (category, new) in &output_dictionary(fields, references)? {
|
||||
let generated = resources.remove(category);
|
||||
let generated = generated
|
||||
.as_ref()
|
||||
.map(Object::as_dict)
|
||||
.transpose()
|
||||
.map_err(|_| "cannot merge a non-dictionary generated resource category")?;
|
||||
let effective = match new {
|
||||
Object::Dictionary(fields) => {
|
||||
if let Some(generated) = generated {
|
||||
let mut combined = generated.clone();
|
||||
merge_pdf_entries(&mut combined, fields, diagnostics);
|
||||
Object::Dictionary(combined)
|
||||
} else {
|
||||
new.clone()
|
||||
}
|
||||
}
|
||||
Object::Reference((number, 0)) => {
|
||||
if let Some(generated) = generated {
|
||||
let slot = &mut objects[*number as usize - 1];
|
||||
let mut shared = pdf_dictionary(slot)?;
|
||||
merge_pdf_entries(&mut shared, generated, diagnostics);
|
||||
*slot = encode_device_value(Object::Dictionary(shared))?;
|
||||
}
|
||||
new.clone()
|
||||
}
|
||||
_ => unreachable!("typed PDF resource category"),
|
||||
};
|
||||
resources.set(category.clone(), effective);
|
||||
}
|
||||
dictionary.set("Resources", Object::Dictionary(resources));
|
||||
objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn category_fields<'a>(
|
||||
objects: &'a BTreeMap<Vec<u8>, NamedObject>,
|
||||
name: &[u8],
|
||||
) -> Result<&'a Dictionary, String> {
|
||||
match objects.get(name).and_then(NamedObject::value) {
|
||||
Some(Value::Dictionary(fields)) => Ok(fields),
|
||||
_ => Err(category_error(name)),
|
||||
}
|
||||
}
|
||||
|
||||
fn category_fields_mut<'a>(
|
||||
objects: &'a mut BTreeMap<Vec<u8>, NamedObject>,
|
||||
name: &[u8],
|
||||
) -> Result<&'a mut Dictionary, String> {
|
||||
objects
|
||||
.get_mut(name)
|
||||
.and_then(NamedObject::dictionary_mut)
|
||||
.ok_or_else(|| category_error(name))
|
||||
}
|
||||
|
||||
fn category_error(name: &[u8]) -> String {
|
||||
format!(
|
||||
"invalid XDV resource category object @{}",
|
||||
String::from_utf8_lossy(name)
|
||||
)
|
||||
}
|
||||
|
||||
fn append_missing(
|
||||
existing: &mut Dictionary,
|
||||
data: Dictionary,
|
||||
deferred: bool,
|
||||
messages: &mut Vec<String>,
|
||||
) {
|
||||
for (key, value) in data {
|
||||
match existing.entry(key) {
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(value);
|
||||
}
|
||||
Entry::Occupied(entry) if !deferred || entry.get() != &value => {
|
||||
messages.push(format!(
|
||||
"xdvipdfmx: warning: Object \"{}\" already defined in dict! (ignored)\n",
|
||||
String::from_utf8_lossy(entry.key()),
|
||||
));
|
||||
}
|
||||
Entry::Occupied(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_pdf_entries(
|
||||
target: &mut PdfDictionary,
|
||||
additions: &PdfDictionary,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) {
|
||||
for (name, value) in additions {
|
||||
if let Ok(existing) = target.get(name) {
|
||||
if !matches!((existing.as_reference(), value.as_reference()), (Ok(left), Ok(right)) if left == right)
|
||||
{
|
||||
diagnostics.push(format!(
|
||||
"xdvipdfmx: warning: Object \"{}\" already defined in dict! (ignored)",
|
||||
String::from_utf8_lossy(name),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
target.set(name.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pdf_dictionary(bytes: &[u8]) -> Result<PdfDictionary, String> {
|
||||
match parse_value(bytes)? {
|
||||
Object::Dictionary(fields) => Ok(fields),
|
||||
_ => Err("expected an XDV PDF resource dictionary".into()),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user