Apply XDV color state and page backgrounds at shipout
This commit is contained in:
1 parent
cc147e93d8
commit
8be7867b37
10 files changed
+590
-19
No files matched your search
@@ -41,6 +41,10 @@ pub struct NativeShipout {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) pdf_graphics_steps: Vec<Option<PdfGraphics>>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(super) xdv_color_steps: BTreeMap<usize, Arc<PdfColorProgram>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pdf_background: Option<Arc<PdfColorProgram>>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(super) pdf_special_images: BTreeMap<usize, (Arc<crate::pdf_image::PdfImageUse>, TokenOrigin)>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub specials: Vec<ShipoutSpecial>,
|
||||
@@ -77,6 +81,7 @@ impl NativeShipout {
|
||||
pdf: self.device.pdf.clone(),
|
||||
pdf_font_bindings: self.pdf_font_bindings.clone(),
|
||||
pdf_links: self.pdf_links.clone(),
|
||||
pdf_background: self.pdf_background.clone(),
|
||||
pdf_text_spaces: self.pdf_text_spaces.clone(),
|
||||
pdf_resources: crate::pdf_device::page_resources::PageResources {
|
||||
entries: self.pdf_resource_entries.clone(),
|
||||
@@ -130,12 +135,17 @@ impl NativeShipout {
|
||||
}
|
||||
boxes::GeometryItem::PdfGraphics { x, y } => {
|
||||
match graphics_steps.next() {
|
||||
Some((_, Some(operation))) => page.items.push(DisplayItem::PdfGraphics {
|
||||
x: self.device.horizontal_origin + x,
|
||||
y: self.device.vertical_origin + self.box_node.height + y,
|
||||
operation: operation.clone(),
|
||||
}),
|
||||
Some((step, None)) => {
|
||||
Some((step, operation)) => {
|
||||
if let Some(operation) = operation {
|
||||
page.items.push(DisplayItem::PdfGraphics {
|
||||
x: self.device.horizontal_origin + x,
|
||||
y: self.device.vertical_origin + self.box_node.height + y,
|
||||
operation: operation.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(program) = self.xdv_color_steps.get(&step) {
|
||||
page.items.push(DisplayItem::PdfColor(program.clone()));
|
||||
}
|
||||
if let Some((image, origin)) = self.pdf_special_images.get(&step) {
|
||||
let [left, bottom] = image.xdv.as_ref().unwrap().layout_offset;
|
||||
page.sources.insert(
|
||||
|
||||
@@ -225,6 +225,7 @@ pub struct Executor {
|
||||
expansion_depth: usize,
|
||||
io: IoState,
|
||||
pdf_colors: crate::pdf_device::PdfColorStacks,
|
||||
xdv_colors: crate::pdf_device::xdv_color::ColorState,
|
||||
pdf_link_stack: Vec<pdf_links::ActiveLink>,
|
||||
pdf_running_links: bool,
|
||||
pdf_interword_spaces: bool,
|
||||
@@ -399,6 +400,7 @@ impl Executor {
|
||||
expansion_depth: 0,
|
||||
io: IoState::default(),
|
||||
pdf_colors: Default::default(),
|
||||
xdv_colors: Default::default(),
|
||||
pdf_link_stack: Vec::new(),
|
||||
pdf_running_links: true,
|
||||
pdf_interword_spaces: false,
|
||||
|
||||
@@ -323,7 +323,11 @@ impl Executor {
|
||||
} else {
|
||||
(Default::default(), Default::default())
|
||||
};
|
||||
let pdf_color_start = if device.pdf.is_some() {
|
||||
use crate::pdf_device::PdfDriver;
|
||||
let xdv = device.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
|
||||
let pdf_color_start = if xdv {
|
||||
self.xdv_colors.start_page().into_iter().collect()
|
||||
} else if device.pdf.is_some() {
|
||||
self.pdf_colors.start_page()
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -343,6 +347,8 @@ impl Executor {
|
||||
pdf_color_start,
|
||||
pdf_color_steps: Vec::new(),
|
||||
pdf_graphics_steps: Vec::new(),
|
||||
xdv_color_steps: Default::default(),
|
||||
pdf_background: None,
|
||||
pdf_special_images: Default::default(),
|
||||
specials: Vec::new(),
|
||||
pdf_text_spaces: None,
|
||||
@@ -442,13 +448,22 @@ impl Executor {
|
||||
(special.position[0] + horizontal_origin) as f64,
|
||||
(special.position[1] + vertical_origin + b.height) as f64,
|
||||
).map(|coordinate| coordinate.round() as i64);
|
||||
let graphics_step = shipout.pdf_graphics_steps.len();
|
||||
let graphics = if let Some(pdf) = &device.pdf {
|
||||
if pdf.driver == crate::pdf_device::PdfDriver::Xdv
|
||||
&& self.xdv_destination_special(&special, point, &mut shipout.pdf_links)?
|
||||
{
|
||||
if let Some(color) = xdv.then(|| self.xdv_colors.apply(&special.bytes)).flatten() {
|
||||
let color = color.map_err(|error| self.error(error, special.span))?;
|
||||
if let Some(warning) = color.warning {
|
||||
files.observe_diagnostic(
|
||||
WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {warning}\n"),
|
||||
).map_err(|error| self.error(error, special.span))?;
|
||||
}
|
||||
if let Some(program) = color.program {
|
||||
shipout.xdv_color_steps.insert(graphics_step, program);
|
||||
}
|
||||
None
|
||||
} else if pdf.driver == crate::pdf_device::PdfDriver::Xdv
|
||||
&& let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse(
|
||||
} else if xdv && self.xdv_destination_special(&special, point, &mut shipout.pdf_links)? {
|
||||
None
|
||||
} else if xdv && let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse(
|
||||
&special.bytes, device.magnification,
|
||||
).map_err(|error| self.error(error, special.span))?
|
||||
{
|
||||
@@ -471,11 +486,11 @@ impl Executor {
|
||||
use crate::pdf_device::PdfGraphics;
|
||||
match &graphics {
|
||||
Some(PdfGraphics::Save) => {
|
||||
xdv_graphics_stack.push((special.span, xdv_transform));
|
||||
xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current()));
|
||||
}
|
||||
Some(operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix))) => {
|
||||
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
|
||||
xdv_graphics_stack.push((special.span, xdv_transform));
|
||||
xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current()));
|
||||
}
|
||||
let [x, y] = special.position;
|
||||
let pivot = matrix.about(
|
||||
@@ -486,10 +501,13 @@ impl Executor {
|
||||
xdv_transform = xdv_transform.concatenate(pivot);
|
||||
}
|
||||
Some(PdfGraphics::Restore { .. }) => {
|
||||
let Some((_, previous)) = xdv_graphics_stack.pop() else {
|
||||
let Some((_, previous, color_at_save)) = xdv_graphics_stack.pop() else {
|
||||
return Err(self.error("unmatched XDV graphics restore", special.span));
|
||||
};
|
||||
xdv_transform = previous;
|
||||
if let Some(program) = self.xdv_colors.restore_after_save(color_at_save) {
|
||||
shipout.xdv_color_steps.insert(graphics_step, program);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -565,7 +583,7 @@ impl Executor {
|
||||
if output_positions.next().is_some() {
|
||||
return self.fail("unexpected positioned native output node");
|
||||
}
|
||||
if let Some(&(span, _)) = xdv_graphics_stack.last() {
|
||||
if let Some(&(span, ..)) = xdv_graphics_stack.last() {
|
||||
return Err(self.error("unclosed XDV graphics save at page shipout", span));
|
||||
}
|
||||
if let Some((_, span)) = graphics_stack.last() {
|
||||
@@ -605,9 +623,8 @@ impl Executor {
|
||||
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
||||
shipout.pdf_links = links;
|
||||
}
|
||||
if let Some(pdf) = &mut shipout.device.pdf
|
||||
&& pdf.driver == crate::pdf_device::PdfDriver::Xdv
|
||||
{
|
||||
if let Some(pdf) = &mut shipout.device.pdf && xdv {
|
||||
shipout.pdf_background = self.xdv_colors.background();
|
||||
self.state.xdv_setup.apply_version(&mut pdf.file);
|
||||
}
|
||||
self.current = current;
|
||||
|
||||
@@ -713,6 +713,11 @@ fn page_content(
|
||||
let ratio = f64::from(list.magnification) / 1000.0;
|
||||
content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n"));
|
||||
}
|
||||
if let Some(color) = &list.pdf_background {
|
||||
content.push_str(&format!(
|
||||
"q\n{}\n0 0 {} {} re f\nQ\n", color.literal(), pt(list.width), pt(height)
|
||||
));
|
||||
}
|
||||
if let Some(DisplayItem::Background(color)) = list.items.first() {
|
||||
content.push_str(&format!(
|
||||
"{:.3} {:.3} {:.3} rg\n0 0 {} {} re f\n0 0 0 rg\n",
|
||||
|
||||
@@ -97,6 +97,7 @@ pub fn print_sp(value: i64, digits: u8) -> String {
|
||||
}
|
||||
}
|
||||
mod color;
|
||||
pub(crate) mod xdv_color;
|
||||
pub(crate) mod xdv_destination;
|
||||
pub(crate) mod xdv_document;
|
||||
pub(crate) mod xdv_image;
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
//! Colors in native XDV page specials.
|
||||
use std::{fmt::Write as _, sync::Arc};
|
||||
|
||||
use super::PdfColorProgram;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Color {
|
||||
Gray(u16),
|
||||
Rgb([u16; 3]),
|
||||
Cmyk([u16; 4]),
|
||||
}
|
||||
|
||||
impl Color {
|
||||
const BLACK: Self = Self::Gray(0);
|
||||
const WHITE: Self = Self::Gray(1000);
|
||||
|
||||
fn is_white(self) -> bool {
|
||||
matches!(
|
||||
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) {
|
||||
(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"),
|
||||
};
|
||||
for value in components {
|
||||
write!(output, "{:.3} ", f64::from(*value) / 1000.0).unwrap();
|
||||
}
|
||||
output.push_str(operator);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Colors {
|
||||
fill: Color,
|
||||
stroke: Color,
|
||||
}
|
||||
|
||||
impl Colors {
|
||||
const BLACK: Self = Self::same(Color::BLACK);
|
||||
|
||||
const fn same(color: Color) -> Self {
|
||||
Self {
|
||||
fill: color,
|
||||
stroke: color,
|
||||
}
|
||||
}
|
||||
|
||||
fn program(self) -> Arc<PdfColorProgram> {
|
||||
let mut literal = String::new();
|
||||
self.stroke.write(&mut literal, false);
|
||||
literal.push(' ');
|
||||
self.fill.write(&mut literal, true);
|
||||
program(literal)
|
||||
}
|
||||
}
|
||||
|
||||
fn program(literal: String) -> Arc<PdfColorProgram> {
|
||||
Arc::new(PdfColorProgram::parse(literal).expect("generated PDF device color"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ColorState {
|
||||
base: Colors,
|
||||
saved: Vec<Colors>,
|
||||
background: Color,
|
||||
}
|
||||
|
||||
impl Default for ColorState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
base: Colors::BLACK,
|
||||
saved: Vec::new(),
|
||||
background: Color::WHITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Applied {
|
||||
pub program: Option<Arc<PdfColorProgram>>,
|
||||
pub warning: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl ColorState {
|
||||
pub(crate) fn current(&self) -> Colors {
|
||||
self.saved.last().copied().unwrap_or(self.base)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_after_save(&self, previous: Colors) -> Option<Arc<PdfColorProgram>> {
|
||||
let current = self.current();
|
||||
(current != previous).then(|| current.program())
|
||||
}
|
||||
|
||||
pub(crate) fn start_page(&self) -> Option<Arc<PdfColorProgram>> {
|
||||
let colors = self.current();
|
||||
(colors != Colors::BLACK).then(|| colors.program())
|
||||
}
|
||||
|
||||
pub(crate) fn background(&self) -> Option<Arc<PdfColorProgram>> {
|
||||
if self.background.is_white() {
|
||||
return None;
|
||||
}
|
||||
let mut literal = String::new();
|
||||
self.background.write(&mut literal, true);
|
||||
Some(program(literal))
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&mut self, special: &[u8]) -> 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,
|
||||
};
|
||||
Some(action.and_then(|action| {
|
||||
if tokens.next().is_some() {
|
||||
return Err("unexpected material after XDV color specification".into());
|
||||
}
|
||||
let mut warning = None;
|
||||
match action {
|
||||
Action::Push(colors) => {
|
||||
if self.saved.len() == 127 {
|
||||
return Ok(Applied {
|
||||
program: None,
|
||||
warning: Some("Color stack overflow. Just ignore."),
|
||||
});
|
||||
}
|
||||
self.saved.push(colors);
|
||||
}
|
||||
Action::Pop => {
|
||||
if self.saved.pop().is_none() {
|
||||
return Ok(Applied {
|
||||
program: None,
|
||||
warning: Some("Color stack underflow. Just ignore."),
|
||||
});
|
||||
}
|
||||
}
|
||||
Action::Set(colors) => *self.saved.last_mut().unwrap_or(&mut self.base) = colors,
|
||||
Action::Reset(color) => {
|
||||
if !self.saved.is_empty() {
|
||||
warning = Some(
|
||||
"You've mistakenly made a global color change within nested colors.",
|
||||
);
|
||||
self.saved.clear();
|
||||
}
|
||||
self.base = Colors::same(color);
|
||||
}
|
||||
Action::Background(color) => {
|
||||
self.background = color;
|
||||
return Ok(Applied {
|
||||
program: None,
|
||||
warning: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Applied {
|
||||
program: Some(self.current().program()),
|
||||
warning,
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
enum Action {
|
||||
Push(Colors),
|
||||
Pop,
|
||||
Set(Colors),
|
||||
Reset(Color),
|
||||
Background(Color),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Tokens<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> Tokens<'a> {
|
||||
fn peek(self) -> Option<&'a [u8]> {
|
||||
let mut tokens = self;
|
||||
tokens.next()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<&'a [u8]> {
|
||||
let rest = self.0.trim_ascii_start();
|
||||
let first = *rest.first()?;
|
||||
let separator = |byte| matches!(byte, b'[' | b']' | b':');
|
||||
let end = if separator(first) {
|
||||
1
|
||||
} else {
|
||||
rest.iter()
|
||||
.position(|&byte| separator(byte) || byte.is_ascii_whitespace())
|
||||
.unwrap_or(rest.len())
|
||||
};
|
||||
let (token, rest) = rest.split_at(end);
|
||||
self.0 = rest;
|
||||
Some(token)
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<f64, String> {
|
||||
let token = self.next().ok_or("missing XDV color component")?;
|
||||
let unsigned = token
|
||||
.strip_prefix(b"+")
|
||||
.or_else(|| token.strip_prefix(b"-"))
|
||||
.unwrap_or(token);
|
||||
if !unsigned
|
||||
.iter()
|
||||
.all(|byte| byte.is_ascii_digit() || *byte == b'.')
|
||||
{
|
||||
return Err("invalid XDV color component".into());
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
fn numbers<const N: usize>(&mut self) -> Result<[f64; N], String> {
|
||||
let mut values = [0.0; N];
|
||||
for value in &mut values {
|
||||
*value = self.number()?;
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
|
||||
fn quantize(value: f64) -> u16 {
|
||||
(value * 1000.0).round() as u16
|
||||
}
|
||||
|
||||
fn parse_dvips(tokens: &mut Tokens<'_>) -> Result<Color, String> {
|
||||
match tokens.next().ok_or("missing XDV color specification")? {
|
||||
b"gray" => Ok(Color::Gray(quantize(tokens.number()?))),
|
||||
b"rgb" => Ok(Color::Rgb(tokens.numbers::<3>()?.map(quantize))),
|
||||
b"cmyk" => Ok(Color::Cmyk(tokens.numbers::<4>()?.map(quantize))),
|
||||
b"hsb" => {
|
||||
let [hue, saturation, brightness] = tokens.numbers::<3>()?;
|
||||
let chroma = brightness * saturation;
|
||||
let sector = hue * 6.0;
|
||||
let middle = chroma * (1.0 - (sector % 2.0 - 1.0).abs());
|
||||
let rgb = match sector as u8 {
|
||||
0 | 6 => [chroma, middle, 0.0],
|
||||
1 => [middle, chroma, 0.0],
|
||||
2 => [0.0, chroma, middle],
|
||||
3 => [0.0, middle, chroma],
|
||||
4 => [middle, 0.0, chroma],
|
||||
_ => [chroma, 0.0, middle],
|
||||
};
|
||||
Ok(Color::Rgb(rgb.map(|component| {
|
||||
quantize(component + brightness - chroma)
|
||||
})))
|
||||
}
|
||||
b"spot" => Err("XDV spot color requires a supported color-space resource".into()),
|
||||
name => named(name),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_pair(tokens: &mut Tokens<'_>, current: Colors) -> 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)?,
|
||||
_ => return Err("expected fill or stroke in XDV color specification".into()),
|
||||
}
|
||||
}
|
||||
Ok(colors)
|
||||
} else {
|
||||
let fill = parse_pdf_color(tokens)?;
|
||||
let stroke = if tokens.peek().is_some() {
|
||||
parse_pdf_color(tokens)?
|
||||
} else {
|
||||
fill
|
||||
};
|
||||
Ok(Colors { fill, stroke })
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_pdf_color(tokens: &mut Tokens<'_>) -> Result<Color, String> {
|
||||
let device = match tokens.peek() {
|
||||
Some(b"/DeviceGray") => Some(1),
|
||||
Some(b"/DeviceRGB") => Some(3),
|
||||
Some(b"/DeviceCMYK") => Some(4),
|
||||
Some(name) if name.starts_with(b"@") || name.starts_with(b"/") => {
|
||||
return Err("unsupported XDV color-space resource".into());
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if device.is_some() {
|
||||
tokens.next();
|
||||
}
|
||||
let bracketed = tokens.peek() == Some(b"[");
|
||||
if bracketed {
|
||||
tokens.next();
|
||||
}
|
||||
let mut components = [0; 4];
|
||||
let mut count = 0;
|
||||
while count < device.unwrap_or(4)
|
||||
&& tokens
|
||||
.peek()
|
||||
.and_then(|word| word.first())
|
||||
.is_some_and(|byte| byte.is_ascii_digit() || matches!(byte, b'.' | b'+' | b'-'))
|
||||
{
|
||||
components[count] = quantize(tokens.number()?);
|
||||
count += 1;
|
||||
}
|
||||
let color = if let Some(expected) = device
|
||||
&& count != expected
|
||||
{
|
||||
return Err("wrong number of XDV device-color components".into());
|
||||
} else {
|
||||
match (count, components) {
|
||||
(1, [gray, ..]) => Color::Gray(gray),
|
||||
(3, [red, green, blue, _]) => Color::Rgb([red, green, blue]),
|
||||
(4, cmyk) => Color::Cmyk(cmyk),
|
||||
(0, _) => named(tokens.next().ok_or("missing XDV PDF color")?)?,
|
||||
_ => return Err("wrong number of XDV device-color components".into()),
|
||||
}
|
||||
};
|
||||
if bracketed && tokens.next() != Some(b"]") {
|
||||
return Err("unbalanced XDV PDF color array".into());
|
||||
}
|
||||
Ok(color)
|
||||
}
|
||||
|
||||
fn named(name: &[u8]) -> Result<Color, String> {
|
||||
let color = match name {
|
||||
b"Black" => Color::BLACK,
|
||||
b"Gray" => Color::Gray(500),
|
||||
b"White" => Color::WHITE,
|
||||
_ => {
|
||||
let name = String::from_utf8_lossy(name);
|
||||
let index = DVIPS_COLORS
|
||||
.binary_search_by_key(&name.as_ref(), |(key, _)| *key)
|
||||
.map_err(|_| format!("unrecognized XDV color name {name}"))?;
|
||||
Color::Cmyk(DVIPS_COLORS[index].1.map(|value| u16::from(value) * 10))
|
||||
}
|
||||
};
|
||||
Ok(color)
|
||||
}
|
||||
|
||||
// The dvips named CMYK palette, in hundredths of full ink.
|
||||
const DVIPS_COLORS: &[(&str, [u8; 4])] = &[
|
||||
("Apricot", [0, 32, 52, 0]),
|
||||
("Aquamarine", [82, 0, 30, 0]),
|
||||
("Bittersweet", [0, 75, 100, 24]),
|
||||
("Blue", [100, 100, 0, 0]),
|
||||
("BlueGreen", [85, 0, 33, 0]),
|
||||
("BlueViolet", [86, 91, 0, 4]),
|
||||
("BrickRed", [0, 89, 94, 28]),
|
||||
("Brown", [0, 81, 100, 60]),
|
||||
("BurntOrange", [0, 51, 100, 0]),
|
||||
("CadetBlue", [62, 57, 23, 0]),
|
||||
("CarnationPink", [0, 63, 0, 0]),
|
||||
("Cerulean", [94, 11, 0, 0]),
|
||||
("CornflowerBlue", [65, 13, 0, 0]),
|
||||
("Cyan", [100, 0, 0, 0]),
|
||||
("Dandelion", [0, 29, 84, 0]),
|
||||
("DarkOrchid", [40, 80, 20, 0]),
|
||||
("Emerald", [100, 0, 50, 0]),
|
||||
("ForestGreen", [91, 0, 88, 12]),
|
||||
("Fuchsia", [47, 91, 0, 8]),
|
||||
("Goldenrod", [0, 10, 84, 0]),
|
||||
("Green", [100, 0, 100, 0]),
|
||||
("GreenYellow", [15, 0, 69, 0]),
|
||||
("JungleGreen", [99, 0, 52, 0]),
|
||||
("Lavender", [0, 48, 0, 0]),
|
||||
("LimeGreen", [50, 0, 100, 0]),
|
||||
("Magenta", [0, 100, 0, 0]),
|
||||
("Mahogany", [0, 85, 87, 35]),
|
||||
("Maroon", [0, 87, 68, 32]),
|
||||
("Melon", [0, 46, 50, 0]),
|
||||
("MidnightBlue", [98, 13, 0, 43]),
|
||||
("Mulberry", [34, 90, 0, 2]),
|
||||
("NavyBlue", [94, 54, 0, 0]),
|
||||
("OliveGreen", [64, 0, 95, 40]),
|
||||
("Orange", [0, 61, 87, 0]),
|
||||
("OrangeRed", [0, 100, 50, 0]),
|
||||
("Orchid", [32, 64, 0, 0]),
|
||||
("Peach", [0, 50, 70, 0]),
|
||||
("Periwinkle", [57, 55, 0, 0]),
|
||||
("PineGreen", [92, 0, 59, 25]),
|
||||
("Plum", [50, 100, 0, 0]),
|
||||
("ProcessBlue", [96, 0, 0, 0]),
|
||||
("Purple", [45, 86, 0, 0]),
|
||||
("RawSienna", [0, 72, 100, 45]),
|
||||
("Red", [0, 100, 100, 0]),
|
||||
("RedOrange", [0, 77, 87, 0]),
|
||||
("RedViolet", [7, 90, 0, 34]),
|
||||
("Rhodamine", [0, 82, 0, 0]),
|
||||
("RoyalBlue", [100, 50, 0, 0]),
|
||||
("RoyalPurple", [75, 90, 0, 0]),
|
||||
("RubineRed", [0, 100, 13, 0]),
|
||||
("Salmon", [0, 53, 38, 0]),
|
||||
("SeaGreen", [69, 0, 50, 0]),
|
||||
("Sepia", [0, 83, 100, 70]),
|
||||
("SkyBlue", [62, 0, 12, 0]),
|
||||
("SpringGreen", [26, 0, 76, 0]),
|
||||
("Tan", [14, 42, 56, 0]),
|
||||
("TealBlue", [86, 0, 34, 2]),
|
||||
("Thistle", [12, 59, 0, 0]),
|
||||
("Turquoise", [85, 0, 20, 0]),
|
||||
("Violet", [79, 88, 0, 0]),
|
||||
("VioletRed", [0, 81, 0, 0]),
|
||||
("WildStrawberry", [0, 96, 39, 0]),
|
||||
("Yellow", [0, 0, 100, 0]),
|
||||
("YellowGreen", [44, 0, 74, 0]),
|
||||
("YellowOrange", [0, 42, 100, 0]),
|
||||
];
|
||||
@@ -267,6 +267,7 @@ pub struct DisplayList {
|
||||
#[doc(hidden)]
|
||||
pub pdf_font_bindings: Option<std::sync::Arc<crate::native_font::PdfFontBindings>>,
|
||||
pub pdf_links: crate::pdf_device::links::PageLinks,
|
||||
pub pdf_background: Option<std::sync::Arc<crate::pdf_device::PdfColorProgram>>,
|
||||
pub pdf_text_spaces: Option<crate::pdf_device::text_spaces::SpaceSettings>,
|
||||
pub pdf_space_plan: Option<crate::pdf_device::text_spaces::SpacePlan>,
|
||||
pub pdf_resources: crate::pdf_device::page_resources::PageResources,
|
||||
@@ -285,6 +286,7 @@ impl Default for DisplayList {
|
||||
pdf: None,
|
||||
pdf_font_bindings: None,
|
||||
pdf_links: Default::default(),
|
||||
pdf_background: None,
|
||||
pdf_text_spaces: None,
|
||||
pdf_space_plan: None,
|
||||
pdf_resources: Default::default(),
|
||||
@@ -354,6 +356,7 @@ impl DisplayList {
|
||||
&& self.units == other.units
|
||||
&& self.magnification == other.magnification
|
||||
&& self.images == other.images
|
||||
&& self.pdf_background == other.pdf_background
|
||||
&& self.pdf_resources.opacity == other.pdf_resources.opacity
|
||||
&& self.pdf_resources.viewport == other.pdf_resources.viewport
|
||||
&& self.pdf_resources.needs_pdf_for_preview == other.pdf_resources.needs_pdf_for_preview
|
||||
@@ -482,6 +485,12 @@ impl DisplayList {
|
||||
if self.magnification != 1000 || self.units == DisplayUnits::TeX {
|
||||
out.push_str(&format!("<g transform=\"scale({mag:.12})\">\n"));
|
||||
}
|
||||
if let Some(color) = self.pdf_background.as_ref().and_then(|color| color.fill) {
|
||||
let [r, g, b] = color;
|
||||
out.push_str(&format!(
|
||||
"<rect width=\"{width:.6}\" height=\"{height:.6}\" fill=\"#{r:02x}{g:02x}{b:02x}\"/>\n"
|
||||
));
|
||||
}
|
||||
let glyphs: std::collections::BTreeSet<_> = self
|
||||
.items
|
||||
.iter()
|
||||
|
||||
Reference in new issue
Block a user