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()
|
||||
|
||||
@@ -548,3 +548,51 @@ fn xdv_destinations_use_shipped_page_ids_and_pdf_string_keys() {
|
||||
assert_eq!(xyz[4].as_f64().unwrap(), 1.5);
|
||||
assert!(output.diagnostics.iter().any(|text| text.contains("Object @A already defined")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdv_color_is_shipped_in_order_and_replayed_on_the_next_page() {
|
||||
use lopdf::Document;
|
||||
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
|
||||
|
||||
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
|
||||
let result = Executor::new(state, Limits::default())
|
||||
.with_native_pages()
|
||||
.run(
|
||||
source(
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\def\block{\vrule width8pt height6pt depth0pt}
|
||||
\setbox0=\hbox{\special{color push Blue}\special{background Black}}
|
||||
\shipout\hbox{\block\special{color push rgb 1 0 0}
|
||||
\special{x:gsave}\special{pdf:bc fill [0 1 0]}\block
|
||||
\special{x:grestore}\block\special{background gray .875}}
|
||||
\shipout\hbox{\block\special{pdf:ec}\block\special{color pop}\block}
|
||||
\shipout\hbox{\block\special{background White}}
|
||||
\end",
|
||||
),
|
||||
&mut TestDevice,
|
||||
)
|
||||
.unwrap();
|
||||
let pages = result.shipout_display_lists().unwrap();
|
||||
let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options())
|
||||
.unwrap();
|
||||
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||
let page_contents: Vec<_> = pdf.get_pages().values().map(|&id| {
|
||||
String::from_utf8(pdf.get_page_content(id).unwrap()).unwrap()
|
||||
}).collect();
|
||||
assert_eq!(page_contents.len(), 3);
|
||||
let first = &page_contents[0];
|
||||
assert!(first.find("0.875 g").unwrap() < first.find(" re f").unwrap());
|
||||
let green_fill = "1.000 0.000 0.000 RG 0.000 1.000 0.000 rg";
|
||||
assert!(first.contains(&format!("Q\n{green_fill}\n")));
|
||||
let second = &page_contents[1];
|
||||
let red = "1.000 0.000 0.000 RG 1.000 0.000 0.000 rg";
|
||||
assert!(second.find("0.875 g").unwrap() < second.find(green_fill).unwrap());
|
||||
assert!(second.find(green_fill).unwrap() < second.find(red).unwrap());
|
||||
assert!(!page_contents[2].contains("0.875 g"));
|
||||
let svg = pages[1].try_to_svg().unwrap();
|
||||
assert!(svg.contains("fill=\"#dfdfdf\""));
|
||||
assert!(svg.contains("fill=\"#00ff00\""));
|
||||
let mut without_background = pages[1].clone();
|
||||
without_background.pdf_background = None;
|
||||
assert!(!pages[1].same_svg_paint(&without_background));
|
||||
}
|
||||
@@ -2175,6 +2175,35 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### XDV 颜色栈与跨页背景
|
||||
|
||||
XDV 发页执行 `color push`、`color pop`、全局前景色和
|
||||
`background`,也执行 `pdf:bc`、`pdf:sc`、`pdf:ec`
|
||||
及 `pdf:bgcolor`。支持灰度、RGB、CMYK、HSB 和 dvips 命名色,
|
||||
以及分别设置 PDF 填充色和描边色。栈和背景在实际发页间续接。
|
||||
当前页最后设置的背景绘制于整个页面内容之前。图形状态恢复重装
|
||||
实际颜色栈的当前值。PDF 保留设备颜色空间,SVG 沿用现有 CMYK
|
||||
屏幕转换。资源型专色和 XDV 的编号颜色栈仍待接入。
|
||||
[TeX Live 的颜色和背景指令](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/spc_color.c)
|
||||
[TeX Live 的页面背景绘制](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdoc.c#L2632-L2704)
|
||||
|
||||
三份同源用例与 xdvipdfmx 20260113 对照。覆盖未发盒、嵌套颜色、
|
||||
命名 CMYK、HSB、图形状态恢复、背景续接及白底恢复。七页 144 DPI
|
||||
彩色光栅逐像素一致,10 项 XeTeX profile 测试通过。
|
||||
|
||||
四页两文件项目,两次连续修改被包含的源文件均复用 180 步,重放
|
||||
2 次宿主调用。只改背景时第二、三页更新,首尾页保留。随后改
|
||||
局部前景色只更新第二页。两次的 PDF、SVG 和来源映射均与独立
|
||||
全量编译一致。
|
||||
|
||||
在干净作业目录以原样 schema71 和十份相同源文件复编 ACL。
|
||||
首次发页越过颜色栈,在 `hxetex.def:232:19` 发出的
|
||||
`pdf:docview<</OpenAction[@page1/Fit]/PageMode/UseOutlines>>`
|
||||
停止。原生 ACL 尚未生成 PDF。下一阶段接通文档目录、打开动作和
|
||||
实际目标页引用。真实参考已记录目录合并、书签树及命名目标引用。
|
||||
回执 `target/p3-xdv-color/receipt.json`,SHA-256 为
|
||||
`a145f068c1c66d91d618377420a8f4c04820e8ed087c6d0584a6c60d366bceb2`。
|
||||
|
||||
### XDV 命名目标与 PDF 发页坐标
|
||||
|
||||
`pdf:dest` 和 `pdf:destination` 随实际发页记录。导出用真实页对象
|
||||
|
||||
@@ -735,6 +735,12 @@ XDV 命名目标接入后,用同一原样 schema71 与项目文件复编原样
|
||||
回执 `target/p3-xdv-dest/receipt.json` 记录实际版本、源文件与失败。
|
||||
[命名目标阶段记录](P2_M1_PROGRESS.md#xdv-命名目标与-pdf-发页坐标)
|
||||
|
||||
XDV 颜色设备接入后,在新作业目录使用同一份原样 schema71 和十份
|
||||
官方 ACL 文件复编。已越过 `color push`,首次发页停在
|
||||
`hxetex.def:232:19` 发出的 `pdf:docview`。原生尚未生成 PDF。
|
||||
回执 `target/p3-xdv-color/receipt.json`。
|
||||
[颜色阶段记录](P2_M1_PROGRESS.md#xdv-颜色栈与跨页背景)
|
||||
|
||||
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
|
||||
|
||||
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。
|
||||
|
||||
Reference in new issue
Block a user