Resolve named XeTeX colors in native PDF and preview

This commit is contained in:
gloamxun committed 2026-11-28 23:45:56 +08:00
1 parent d6ab5a025f
commit 74eb1e9fc4
12 files changed
+723 -97

No files matched your search

+143 -3
View File
@@ -2,15 +2,143 @@ use super::PdfLiteralMode;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
/// A device-color program. The PDF receives the original operators and
/// component precision. SVG projects the same device colors to screen RGB.
/// PDF color operators and their device resources. Ordinary device colors
/// also have a direct SVG projection.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
#[serde(try_from = "ColorProgramWire", into = "ColorProgramWire")]
pub struct PdfColorProgram {
literal: String,
pub(crate) fill: Option<[u8; 3]>,
pub(crate) stroke: Option<[u8; 3]>,
pub(crate) graphics_states: Vec<Vec<u8>>,
pub(crate) xdv_resources: Vec<XdvColorResource>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) enum XdvColorCategory {
ColorSpace,
Pattern,
}
impl XdvColorCategory {
pub(crate) fn name(self) -> &'static [u8] {
match self {
Self::ColorSpace => b"ColorSpace",
Self::Pattern => b"Pattern",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct XdvColorResource {
pub(crate) category: XdvColorCategory,
pub(crate) alias: String,
pub(crate) object: Vec<u8>,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum ColorProgramWire {
Device(String),
Resources { literal: String, resources: Vec<XdvColorResource> },
}
impl TryFrom<ColorProgramWire> for PdfColorProgram {
type Error = String;
fn try_from(wire: ColorProgramWire) -> Result<Self, Self::Error> {
match wire {
ColorProgramWire::Device(literal) => Self::parse(literal),
ColorProgramWire::Resources { literal, resources } => {
validate_xdv_color(&literal, &resources)?;
Ok(Self::xdv(literal, resources))
}
}
}
}
impl From<PdfColorProgram> for ColorProgramWire {
fn from(program: PdfColorProgram) -> Self {
if program.xdv_resources.is_empty() {
Self::Device(program.literal)
} else {
Self::Resources { literal: program.literal, resources: program.xdv_resources }
}
}
}
// Resource operands in a saved display list must match its typed bindings.
fn validate_xdv_color(literal: &str, resources: &[XdvColorResource]) -> Result<(), String> {
let invalid = || "invalid saved XDV color program".to_string();
if resources.is_empty() {
return Err(invalid());
}
let mut tokens = literal.split_ascii_whitespace().peekable();
let mut bindings = resources.iter();
while let Some(first) = tokens.peek().copied() {
let stroke = if let Some(space) = first.strip_prefix('/') {
tokens.next();
if space != "Pattern" {
let resource = bindings.next().ok_or_else(invalid)?;
if resource.category != XdvColorCategory::ColorSpace
|| resource.alias != space
|| !space.strip_prefix("XC").is_some_and(color_resource_number)
{
return Err(invalid());
}
}
match tokens.next() {
Some("CS") => Some(true),
Some("cs") => Some(false),
_ => return Err(invalid()),
}
} else {
None
};
let mut components = 0;
while tokens.peek().is_some_and(|token| color_component(token)) {
tokens.next();
components += 1;
if components > super::xdv_navigation::MAX_COLOR_COMPONENTS {
return Err(invalid());
}
}
let pattern = tokens.peek().and_then(|token| token.strip_prefix('/'));
if let Some(pattern) = pattern {
tokens.next();
let resource = bindings.next().ok_or_else(invalid)?;
if resource.category != XdvColorCategory::Pattern
|| resource.alias != pattern
|| !pattern.strip_prefix("XP").is_some_and(color_resource_number)
{
return Err(invalid());
}
}
match (stroke, tokens.next(), pattern.is_some(), components) {
(None, Some("G" | "g"), false, 1)
| (None, Some("RG" | "rg"), false, 3)
| (None, Some("K" | "k"), false, 4)
| (Some(true), Some("SCN"), true, _)
| (Some(false), Some("scn"), true, _)
| (Some(true), Some("SCN" | "SC"), false, 1..)
| (Some(false), Some("scn" | "sc"), false, 1..) => {}
_ => return Err(invalid()),
}
}
if bindings.next().is_some() {
return Err(invalid());
}
Ok(())
}
fn color_resource_number(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())
}
fn color_component(token: &str) -> bool {
let unsigned = token.strip_prefix(['+', '-']).unwrap_or(token);
unsigned.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.')
&& token.parse::<f64>().is_ok_and(f64::is_finite)
}
impl PdfColorProgram {
@@ -71,9 +199,20 @@ impl PdfColorProgram {
fill,
stroke,
graphics_states,
xdv_resources: Vec::new(),
})
}
pub(crate) fn xdv(literal: String, xdv_resources: Vec<XdvColorResource>) -> Self {
Self {
literal,
fill: None,
stroke: None,
graphics_states: Vec::new(),
xdv_resources,
}
}
pub fn literal(&self) -> &str {
&self.literal
}
@@ -156,6 +295,7 @@ impl Default for PdfColorStacks {
fill: Some([0; 3]),
stroke: Some([0; 3]),
graphics_states: Vec::new(),
xdv_resources: Vec::new(),
}),
saved: Vec::new(),
}])
@@ -1,34 +1,70 @@
//! Colors in native XDV page specials.
use std::{fmt::Write as _, sync::Arc};
use super::PdfColorProgram;
use super::{
PdfColorProgram, color::XdvColorResource,
xdv_navigation::{ColorSpace, Navigation}, xdv_object::identifier,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
enum Color {
Gray(u16),
Rgb([u16; 3]),
Cmyk([u16; 4]),
Named(Arc<NamedColor>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct NamedColor {
space: Option<XdvColorResource>,
components: Vec<u64>,
pattern: Option<XdvColorResource>,
special: bool,
}
impl Color {
const BLACK: Self = Self::Gray(0);
const WHITE: Self = Self::Gray(1000);
fn is_white(self) -> bool {
fn is_white(&self) -> bool {
matches!(
self,
*self,
Self::WHITE | Self::Rgb([1000, 1000, 1000]) | Self::Cmyk([0, 0, 0, 0])
)
}
fn write(self, output: &mut String, fill: bool) {
let (components, operator) = match (&self, fill) {
fn write(&self, output: &mut String, fill: bool, resources: &mut Vec<XdvColorResource>) {
let (components, operator) = match (self, fill) {
(Self::Gray(value), true) => (std::slice::from_ref(value), "g"),
(Self::Gray(value), false) => (std::slice::from_ref(value), "G"),
(Self::Rgb(value), true) => (value.as_slice(), "rg"),
(Self::Rgb(value), false) => (value.as_slice(), "RG"),
(Self::Cmyk(value), true) => (value.as_slice(), "k"),
(Self::Cmyk(value), false) => (value.as_slice(), "K"),
(Self::Named(color), _) => {
let name = if let Some(space) = &color.space {
resources.push(space.clone());
&space.alias
} else {
"Pattern"
};
let select = if fill { "cs" } else { "CS" };
write!(output, "/{name} {select} ").unwrap();
for &component in &color.components {
write!(output, "{} ", f64::from_bits(component)).unwrap();
}
if let Some(pattern) = &color.pattern {
write!(output, "/{} ", pattern.alias).unwrap();
resources.push(pattern.clone());
}
output.push_str(match (color.special, fill) {
(true, true) => "scn",
(true, false) => "SCN",
(false, true) => "sc",
(false, false) => "SC",
});
return;
},
};
for value in components {
write!(output, "{:.3} ", f64::from(*value) / 1000.0).unwrap();
@@ -37,33 +73,35 @@ impl Color {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Colors {
fill: Color,
stroke: Color,
}
impl Colors {
const BLACK: Self = Self::same(Color::BLACK);
const BLACK: Self = Self { fill: Color::BLACK, stroke: Color::BLACK };
const fn same(color: Color) -> Self {
Self {
fill: color,
stroke: color,
}
fn same(color: Color) -> Self {
Self { stroke: color.clone(), fill: color }
}
fn program(self) -> Arc<PdfColorProgram> {
let mut literal = String::new();
self.stroke.write(&mut literal, false);
let mut resources = Vec::new();
self.stroke.write(&mut literal, false, &mut resources);
literal.push(' ');
self.fill.write(&mut literal, true);
program(literal)
self.fill.write(&mut literal, true, &mut resources);
program(literal, resources)
}
}
fn program(literal: String) -> Arc<PdfColorProgram> {
Arc::new(PdfColorProgram::parse(literal).expect("generated PDF device color"))
fn program(literal: String, resources: Vec<XdvColorResource>) -> Arc<PdfColorProgram> {
Arc::new(if resources.is_empty() {
PdfColorProgram::parse(literal).expect("generated PDF device color")
} else {
PdfColorProgram::xdv(literal, resources)
})
}
#[derive(Clone, Debug)]
@@ -90,7 +128,7 @@ pub(crate) struct Applied {
impl ColorState {
pub(crate) fn current(&self) -> Colors {
self.saved.last().copied().unwrap_or(self.base)
self.saved.last().unwrap_or(&self.base).clone()
}
pub(crate) fn restore_after_save(&self, previous: Colors) -> Option<Arc<PdfColorProgram>> {
@@ -108,45 +146,27 @@ impl ColorState {
return None;
}
let mut literal = String::new();
self.background.write(&mut literal, true);
Some(program(literal))
let mut resources = Vec::new();
self.background.write(&mut literal, true, &mut resources);
Some(program(literal, resources))
}
pub(crate) fn apply(&mut self, special: &[u8]) -> Option<Result<Applied, String>> {
pub(crate) fn recognizes(special: &[u8]) -> bool {
ActionKind::read(&mut Tokens(special)).is_some()
}
pub(crate) fn apply(
&mut self, special: &[u8], navigation: &mut Option<Arc<Navigation>>,
) -> Option<Result<Applied, String>> {
let mut tokens = Tokens(special);
let command = tokens.next()?;
let action = match command {
b"color" => match tokens.peek() {
Some(b"push") => {
tokens.next();
parse_dvips(&mut tokens).map(|color| Action::Push(Colors::same(color)))
}
Some(b"pop") => {
tokens.next();
Ok(Action::Pop)
}
_ => parse_dvips(&mut tokens).map(Action::Reset),
},
b"background" => parse_dvips(&mut tokens).map(Action::Background),
b"pdf" if tokens.peek() == Some(b":") => {
tokens.next();
match tokens.next()? {
b"bc" | b"bcolor" | b"begincolor" | b"bg" | b"bgray" | b"begingray" => {
read_pair(&mut tokens, self.current()).map(Action::Push)
}
b"sc" | b"scolor" | b"setcolor" => {
read_pair(&mut tokens, self.current()).map(Action::Set)
}
b"ec" | b"ecolor" | b"endcolor" | b"eg" | b"egray" | b"endgray" => {
Ok(Action::Pop)
}
b"bgc" | b"bgcolor" | b"bbc" | b"bbg" => {
parse_pdf_color(&mut tokens).map(Action::Background)
}
_ => return None,
}
}
_ => return None,
let action = match ActionKind::read(&mut tokens)? {
ActionKind::DvipsPush => parse_dvips(&mut tokens).map(|color| Action::Push(Colors::same(color))),
ActionKind::DvipsReset => parse_dvips(&mut tokens).map(Action::Reset),
ActionKind::DvipsBackground => parse_dvips(&mut tokens).map(Action::Background),
ActionKind::PdfPush => read_pair(&mut tokens, self.current(), navigation).map(Action::Push),
ActionKind::PdfSet => read_pair(&mut tokens, self.current(), navigation).map(Action::Set),
ActionKind::PdfBackground => parse_pdf_color(&mut tokens, navigation).map(Action::Background),
ActionKind::Pop => Ok(Action::Pop),
};
Some(action.and_then(|action| {
if tokens.next().is_some() {
@@ -197,6 +217,43 @@ impl ColorState {
}
}
enum ActionKind {
DvipsPush,
DvipsReset,
DvipsBackground,
PdfPush,
PdfSet,
PdfBackground,
Pop,
}
impl ActionKind {
fn read(tokens: &mut Tokens<'_>) -> Option<Self> {
Some(match tokens.next()? {
b"color" => match tokens.peek() {
Some(b"push") => {
tokens.next();
Self::DvipsPush
}
Some(b"pop") => {
tokens.next();
Self::Pop
}
_ => Self::DvipsReset,
},
b"background" => Self::DvipsBackground,
b"pdf" if tokens.next() == Some(b":") => match tokens.next()? {
b"bc" | b"bcolor" | b"begincolor" | b"bg" | b"bgray" | b"begingray" => Self::PdfPush,
b"sc" | b"scolor" | b"setcolor" => Self::PdfSet,
b"ec" | b"ecolor" | b"endcolor" | b"eg" | b"egray" | b"endgray" => Self::Pop,
b"bgc" | b"bgcolor" | b"bbc" | b"bbg" => Self::PdfBackground,
_ => return None,
},
_ => return None,
})
}
}
enum Action {
Push(Colors),
Pop,
@@ -231,6 +288,14 @@ impl<'a> Tokens<'a> {
}
fn number(&mut self) -> Result<f64, String> {
let value = self.real()?;
if !(0.0..=1.0).contains(&value) {
return Err("XDV color component must be between 0 and 1".into());
}
Ok(value)
}
fn real(&mut self) -> Result<f64, String> {
let token = self.next().ok_or("missing XDV color component")?;
let unsigned = token
.strip_prefix(b"+")
@@ -245,8 +310,8 @@ impl<'a> Tokens<'a> {
std::str::from_utf8(token)
.ok()
.and_then(|value| value.parse::<f64>().ok())
.filter(|value| (0.0..=1.0).contains(value))
.ok_or_else(|| "XDV color component must be between 0 and 1".into())
.filter(|value| value.is_finite())
.ok_or_else(|| "invalid XDV color component".into())
}
fn numbers<const N: usize>(&mut self) -> Result<[f64; N], String> {
@@ -289,29 +354,68 @@ fn parse_dvips(tokens: &mut Tokens<'_>) -> Result<Color, String> {
}
}
fn read_pair(tokens: &mut Tokens<'_>, current: Colors) -> Result<Colors, String> {
fn read_pair(
tokens: &mut Tokens<'_>, current: Colors, navigation: &mut Option<Arc<Navigation>>,
) -> Result<Colors, String> {
if matches!(tokens.peek(), Some(b"fill" | b"stroke")) {
let mut colors = current;
while let Some(target) = tokens.next() {
match target {
b"fill" => colors.fill = parse_pdf_color(tokens)?,
b"stroke" => colors.stroke = parse_pdf_color(tokens)?,
b"fill" => colors.fill = parse_pdf_color(tokens, navigation)?,
b"stroke" => colors.stroke = parse_pdf_color(tokens, navigation)?,
_ => return Err("expected fill or stroke in XDV color specification".into()),
}
}
Ok(colors)
} else {
let fill = parse_pdf_color(tokens)?;
let fill = parse_pdf_color(tokens, navigation)?;
let stroke = if tokens.peek().is_some() {
parse_pdf_color(tokens)?
parse_pdf_color(tokens, navigation)?
} else {
fill
fill.clone()
};
Ok(Colors { fill, stroke })
}
}
fn parse_pdf_color(tokens: &mut Tokens<'_>) -> Result<Color, String> {
fn parse_pdf_color(
tokens: &mut Tokens<'_>, navigation: &mut Option<Arc<Navigation>>,
) -> Result<Color, String> {
let space = match tokens.peek() {
Some(name) if name.starts_with(b"@") => {
let (name, rest) = identifier(tokens.0)?;
tokens.0 = rest;
let navigation = navigation.as_mut().ok_or("undefined XDV named color space")?;
let (space, reference) = Arc::make_mut(navigation).named_color_space(name)?;
Some((space, Some(reference)))
}
Some(b"/Pattern") => {
tokens.next();
Some((ColorSpace { components: 0, special: true, pattern: true }, None))
}
_ => None,
};
if let Some((kind, space)) = space {
let bracketed = tokens.peek() == Some(b"[");
if bracketed {
tokens.next();
}
let components = (0..kind.components)
.map(|_| tokens.real().map(f64::to_bits))
.collect::<Result<_, _>>()?;
let pattern = if kind.pattern {
let (name, rest) = identifier(tokens.0)?;
tokens.0 = rest;
let navigation = navigation.as_mut().ok_or("undefined XDV named pattern")?;
Some(Arc::make_mut(navigation).named_color_pattern(name)?)
} else {
None
};
if bracketed && tokens.next() != Some(b"]") {
return Err("unbalanced XDV PDF color array".into());
}
return Ok(Color::Named(Arc::new(NamedColor { space, components, pattern, special: kind.special })));
}
let device = match tokens.peek() {
Some(b"/DeviceGray") => Some(1),
Some(b"/DeviceRGB") => Some(3),
@@ -11,6 +11,7 @@ use super::xdv_object::{
output_with_destination, target_name, trim_pdf,
};
mod color_resources;
mod named_objects;
mod name_trees;
mod page_dictionaries;
@@ -23,6 +24,7 @@ use page_resources::PageResources;
use page_dictionaries::PageDictionaries;
pub(crate) use named_objects::ObjectCommand;
use named_objects::NamedObject;
pub(crate) use color_resources::{ColorSpace, MAX_COLOR_COMPONENTS, color_uses};
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct Navigation {
@@ -32,6 +34,10 @@ pub(crate) struct Navigation {
payload: usize,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
objects: BTreeMap<Vec<u8>, NamedObject>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
color_spaces: BTreeMap<Vec<u8>, usize>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
color_patterns: BTreeMap<Vec<u8>, usize>,
#[serde(default, skip_serializing_if = "PageDictionaries::is_empty")]
page_dictionaries: PageDictionaries,
#[serde(default, skip_serializing_if = "PageResources::is_empty")]
@@ -0,0 +1,192 @@
use super::{Dictionary, NamedObject, Navigation, Value};
use crate::{
pdf_device::color::{XdvColorCategory, XdvColorResource},
render::{DisplayItem, DisplayList},
};
pub(crate) const MAX_COLOR_COMPONENTS: usize = 32;
pub(crate) struct ColorSpace {
pub(crate) components: usize,
pub(crate) special: bool,
pub(crate) pattern: bool,
}
impl Navigation {
pub(crate) fn has_color_resources(&self) -> bool {
!self.color_spaces.is_empty() || !self.color_patterns.is_empty()
}
pub(crate) fn named_color_space(
&mut self,
name: &[u8],
) -> Result<(ColorSpace, XdvColorResource), String> {
let value = self
.objects
.get(name)
.and_then(NamedObject::value)
.ok_or_else(|| {
format!(
"XDV color space @{} is not defined",
String::from_utf8_lossy(name)
)
})?;
if !matches!(value, Value::Array(_)) {
return Err("XDV named color space requires an array object".into());
}
let space = self.color_space(value, 0)?;
Ok((
space,
color_resource(
&mut self.color_spaces,
name,
XdvColorCategory::ColorSpace,
"XC",
)?,
))
}
pub(crate) fn named_color_pattern(&mut self, name: &[u8]) -> Result<XdvColorResource, String> {
let object = self.objects.get(name).ok_or_else(|| {
format!(
"XDV pattern @{} is not defined",
String::from_utf8_lossy(name)
)
})?;
let dictionary = object.stream_attributes().or_else(|| match object.value() {
Some(Value::Dictionary(fields)) => Some(fields),
_ => None,
});
if !matches!(
dictionary.and_then(|dict| dict.get(b"PatternType".as_slice())),
Some(Value::Integer(1 | 2))
) {
return Err("XDV color pattern has no valid PatternType".into());
}
color_resource(
&mut self.color_patterns,
name,
XdvColorCategory::Pattern,
"XP",
)
}
fn color_space(&self, value: &Value, depth: usize) -> Result<ColorSpace, String> {
if depth == 32 {
return Err("XDV color-space reference nesting limit exceeded".into());
}
let (name, parameters) = match value {
Value::Name(name) => (name.as_slice(), &[][..]),
Value::Named(name) => {
let source = self
.objects
.get(name)
.and_then(NamedObject::value)
.ok_or("undefined nested XDV color space")?;
return self.color_space(source, depth + 1);
}
Value::Array(items) => match items.split_first() {
Some((Value::Name(name), operands)) => (name.as_slice(), operands),
_ => return Err("invalid XDV color-space array".into()),
},
_ => return Err("invalid XDV color-space value".into()),
};
let components = match name {
b"DeviceGray" | b"CalGray" | b"Separation" | b"Indexed" => 1,
b"DeviceRGB" | b"CalRGB" | b"Lab" | b"LAB" => 3,
b"DeviceCMYK" => 4,
b"DeviceN" => match parameters.first() {
Some(Value::Array(names)) if names.iter().all(|v| matches!(v, Value::Name(_))) => {
names.len()
}
_ => return Err("XDV DeviceN requires a colorant name array".into()),
},
b"ICCBased" => {
let Some(Value::Named(profile)) = parameters.first() else {
return Err("XDV ICCBased requires a profile stream reference".into());
};
let Some(Value::Integer(count)) = self
.objects
.get(profile)
.and_then(NamedObject::stream_attributes)
.and_then(|attrs| attrs.get(b"N".as_slice()))
else {
return Err("XDV ICC profile requires a component count".into());
};
usize::try_from(*count).map_err(|_| "invalid XDV ICC profile component count")?
}
b"Pattern" => match parameters {
[] => 0,
[base] => {
let base = self.color_space(base, depth + 1)?;
if base.pattern {
return Err("XDV pattern cannot use a pattern base color space".into());
}
base.components
}
_ => return Err("invalid XDV pattern color space".into()),
},
_ => {
return Err(format!(
"unsupported named XDV color-space type {}",
String::from_utf8_lossy(name)
));
}
};
let pattern = name == b"Pattern";
if (!pattern && components == 0) || components > MAX_COLOR_COMPONENTS {
return Err("XDV color-space component count out of range".into());
}
Ok(ColorSpace {
components,
special: matches!(name, b"Separation" | b"DeviceN" | b"Pattern"),
pattern,
})
}
}
fn color_resource(
bindings: &mut std::collections::BTreeMap<Vec<u8>, usize>,
name: &[u8],
category: XdvColorCategory,
prefix: &str,
) -> Result<XdvColorResource, String> {
let next = bindings.len();
// The low-level XDV device has at most one resource per resolved identifier.
if !bindings.contains_key(name) && next >= 65_535 {
return Err("XDV color resource capacity exceeded".into());
}
let index = *bindings.entry(name.to_vec()).or_insert(next);
Ok(XdvColorResource {
category,
alias: format!("{prefix}{index}"),
object: name.to_vec(),
})
}
pub(crate) fn color_uses(list: &DisplayList) -> impl Iterator<Item = &XdvColorResource> {
list.pdf_background
.iter()
.map(|program| program.as_ref())
.chain(list.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor { program, .. } => Some(program.as_ref()),
_ => None,
}))
.flat_map(|program| &program.xdv_resources)
}
pub(super) fn color_dictionary(list: &DisplayList) -> Dictionary {
let mut fields = Dictionary::new();
for binding in color_uses(list) {
let Value::Dictionary(entries) = fields
.entry(binding.category.name().to_vec())
.or_insert_with(|| Value::Dictionary(Dictionary::new()))
else {
unreachable!()
};
entries
.entry(binding.alias.as_bytes().to_vec())
.or_insert_with(|| Value::Named(binding.object.clone()));
}
fields
}
@@ -739,6 +739,15 @@ impl Navigation {
let Object::Dictionary(mut resources) = parse_value(resources)? else {
unreachable!("generated XDV form resources");
};
if self.has_color_resources() {
merge_output_resources(
&mut resources,
&super::color_resources::color_dictionary(list),
references,
objects,
diagnostics,
)?;
}
merge_output_resources(
&mut resources,
&definition.resources,
@@ -227,6 +227,13 @@ impl NamedObject {
}
}
pub(super) fn stream_attributes(&self) -> Option<&Dictionary> {
match &self.data {
ObjectData::Stream { attributes, .. } => Some(attributes),
_ => None,
}
}
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
match &self.data {
ObjectData::Value(value) => value.collect_references(pending),
@@ -115,14 +115,24 @@ impl Navigation {
pub(crate) fn write_page_resources(
&self,
pages: &[crate::render::DisplayList],
references: &References<'_>,
objects: &mut [Vec<u8>],
diagnostics: &mut Vec<String>,
) -> Result<(), String> {
for (&page, fields) in &self.page_resources.pages {
let uses_colors = self.has_color_resources();
if !uses_colors && self.page_resources.pages.is_empty() {
return Ok(());
}
for (index, page) in pages.iter().enumerate() {
let colors = uses_colors.then(|| super::color_resources::color_dictionary(page));
let fields = self.page_resources.pages.get(&(index + 1));
if fields.is_none() && colors.as_ref().is_none_or(Dictionary::is_empty) {
continue;
}
let id = *references
.pages
.get(page - 1)
.get(index)
.ok_or("unallocated XDV resource page")?;
let mut dictionary = pdf_dictionary(&objects[id - 1])?;
let mut resources = dictionary
@@ -131,7 +141,12 @@ impl Navigation {
.as_dict()
.map_err(|_| "expected inline XDV resource dictionary")?
.clone();
merge_output_resources(&mut resources, fields, references, objects, diagnostics)?;
if let Some(colors) = colors {
merge_output_resources(&mut resources, &colors, references, objects, diagnostics)?;
}
if let Some(fields) = fields {
merge_output_resources(&mut resources, fields, references, objects, diagnostics)?;
}
dictionary.set("Resources", Object::Dictionary(resources));
objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?;
}