Apply XDV color state and page backgrounds at shipout

This commit is contained in:
gloamxun committed 2026-11-25 20:09:15 +08:00
1 parent cc147e93d8
commit 8be7867b37
10 files changed
+590 -19

No files matched your search

@@ -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]),
];