From 74eb1e9fc4c23e04c3bf2163b3624f41ff0e42c7 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 23:45:56 +0800 Subject: [PATCH] Resolve named XeTeX colors in native PDF and preview --- .../src/execution/engine/page.rs | 107 ++++++-- crates/texrra-tex-core/src/pdf.rs | 8 +- .../texrra-tex-core/src/pdf_device/color.rs | 146 ++++++++++- .../src/pdf_device/xdv_color.rs | 232 +++++++++++++----- .../src/pdf_device/xdv_navigation.rs | 6 + .../xdv_navigation/color_resources.rs | 192 +++++++++++++++ .../src/pdf_device/xdv_navigation/forms.rs | 9 + .../xdv_navigation/named_objects.rs | 7 + .../xdv_navigation/page_resources.rs | 21 +- crates/texrra-tex-core/src/render.rs | 4 +- .../tests/execution_xetex_profile.rs | 65 +++++ docs/P2_M1_PROGRESS.md | 23 ++ 12 files changed, 723 insertions(+), 97 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/xdv_navigation/color_resources.rs diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 57b007b..96a545e 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -38,6 +38,22 @@ pub(super) struct PdfSpaceProbe { pub(super) observed_events: usize, } +// PDF object and color specials need a settled paper size and one shared +// execution order, including live color across captures and graphics saves. +enum XdvOutput { + Color(usize, usize), + SaveColor, + RestoreColor(usize), + Navigation { + index: usize, + graphics_step: usize, + point: [i64; 2], + origin: Option, + content_origin: Option<[i64; 2]>, + text: Option, + }, +} + struct ShipoutFontUse { before_output: usize, before_paint: usize, @@ -429,9 +445,11 @@ impl Executor { 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() + let initial = self.xdv_colors.start_page(); + if initial.as_ref().is_some_and(|program| !program.xdv_resources.is_empty()) { + self.reads.insert(Dependency::PdfCatalogState); + } + initial.into_iter() .map(crate::pdf_device::ShippedColor::Page) .collect() } else if device.pdf.is_some() && !for_form { @@ -551,7 +569,7 @@ impl Executor { let mut xdv_annotations = std::collections::BTreeMap::new(); let mut reopened_images = false; let mut xdv_paper_specials = Vec::new(); - let mut xdv_navigation = Vec::new(); + let mut xdv_output = Vec::new(); for (index, output) in outputs.iter().copied().enumerate() { while font_uses.peek().is_some_and(|usage| usage.before_output == index) { let usage = font_uses.next().unwrap(); @@ -618,16 +636,8 @@ impl Executor { )?; let graphics_step = shipout.pdf_graphics_steps.len(); let graphics = if let Some(pdf) = &device.pdf { - 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); - } + if xdv && crate::pdf_device::xdv_color::ColorState::recognizes(&special.bytes) { + xdv_output.push(XdvOutput::Color(shipout.specials.len(), graphics_step)); None } else if xdv && crate::pdf_device::xdv_annotation::Command::recognize(&special.bytes).is_some() { xdv_annotations.insert(graphics_step, (shipout.specials.len(), self.xdv_text.clone())); @@ -636,15 +646,19 @@ impl Executor { xdv_paper_specials.push(shipout.specials.len()); None } else if xdv && let Some((kind, _)) = super::specials::xdv_navigation_operand(&special.bytes) { - if kind == b"bxobj" && let Some(program) = self.xdv_colors.start_page() { - shipout.xdv_color_steps.insert(graphics_step, program); - } let point = xdv_transform.point( (special.position[0] + horizontal_origin) as f64, (special.position[1] + vertical_origin + b.height) as f64, ).map(|coordinate| coordinate.round() as i64); let text = matches!(kind, b"docview" | b"outline").then(|| self.xdv_text.clone()); - xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin, content_origins.last().copied(), text)); + xdv_output.push(XdvOutput::Navigation { + index: shipout.specials.len(), + graphics_step, + point, + origin: *origin, + content_origin: content_origins.last().copied(), + text, + }); None } else if xdv && self.xdv_setup_special(&special)? { None @@ -664,11 +678,13 @@ impl Executor { } match &graphics { Some(PdfGraphics::Save | PdfGraphics::Literal { mode: PdfLiteralMode::XdvBeginContent, .. }) => { - xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current())); + xdv_graphics_stack.push((special.span, xdv_transform)); + xdv_output.push(XdvOutput::SaveColor); } Some(operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix))) => { if matches!(operation, PdfGraphics::SaveMatrix(_)) { - xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current())); + xdv_graphics_stack.push((special.span, xdv_transform)); + xdv_output.push(XdvOutput::SaveColor); } let [x, y] = special.position; let pivot = matrix.about( @@ -679,13 +695,11 @@ impl Executor { xdv_transform = xdv_transform.concatenate(pivot); } Some(PdfGraphics::Restore { .. } | PdfGraphics::Literal { mode: PdfLiteralMode::XdvEndContent, .. }) => { - let Some((_, previous, color_at_save)) = xdv_graphics_stack.pop() else { + let Some((_, previous)) = 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); - } + xdv_output.push(XdvOutput::RestoreColor(graphics_step)); } _ => {} } @@ -861,8 +875,48 @@ impl Executor { origin_x - device.horizontal_origin, device.page_height - origin_y - device.vertical_origin - shipout.box_node.height, ]; - for (index, graphics_step, [x, y], origin, content_origin, text) in xdv_navigation { + let mut saved_colors = Vec::new(); + for operation in xdv_output { + let (index, graphics_step, [x, y], origin, content_origin, text) = match operation { + XdvOutput::SaveColor => { + saved_colors.push(self.xdv_colors.current()); + continue; + } + XdvOutput::RestoreColor(step) => { + let previous = saved_colors.pop().expect("matched XDV graphics restore"); + if let Some(program) = self.xdv_colors.restore_after_save(previous) { + shipout.xdv_color_steps.insert(step, program); + } + continue; + } + XdvOutput::Color(index, step) => { + let special = &shipout.specials[index]; + let color = self.xdv_colors.apply(&special.bytes, &mut self.state.xdv_navigation) + .expect("classified XDV 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 { + if !program.xdv_resources.is_empty() { + self.reads.insert(Dependency::PdfCatalogState); + } + shipout.xdv_color_steps.insert(step, program); + } + continue; + } + XdvOutput::Navigation { index, graphics_step, point, origin, content_origin, text } => { + (index, graphics_step, point, origin, content_origin, text) + } + }; let special = &shipout.specials[index]; + if let Some((b"bxobj", _)) = super::specials::xdv_navigation_operand(&special.bytes) + && let Some(program) = self.xdv_colors.start_page() + { + shipout.xdv_color_steps.insert(graphics_step, program); + } let position = crate::pdf_device::xdv_object::Position { page: self.shipped_pages + 1, coordinates: [x + delta[0], y + delta[1]], @@ -911,6 +965,9 @@ impl Executor { } if let Some(pdf) = &mut shipout.device.pdf && xdv { shipout.pdf_background = self.xdv_colors.background(); + if shipout.pdf_background.as_ref().is_some_and(|program| !program.xdv_resources.is_empty()) { + self.reads.insert(Dependency::PdfCatalogState); + } self.state.xdv_setup.apply_version(&mut pdf.file); } self.current = current; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 9d9d61a..0dd8580 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -3670,6 +3670,12 @@ fn write_pdf( destination.collect_references(&mut pending); } } + if xdv_objects.has_color_resources() { + for list in &paint_lists { + pending.extend(crate::pdf_device::xdv_navigation::color_uses(list) + .map(|resource| resource.object.as_slice())); + } + } let named_objects = xdv_objects.reserve_objects(pending, &mut objects, &xdv_xobjects)?; let references = crate::pdf_device::xdv_object::References { pages: &navigation.pages, @@ -3684,7 +3690,7 @@ fn write_pdf( objects[id - 1] = xdv.write_form(form, resources.as_bytes(), &content, &references, &mut objects, diagnostics)?; } xdv.write_page_dictionaries(pages, &references, &mut objects)?; - xdv.write_page_resources(&references, &mut objects, diagnostics)?; + xdv.write_page_resources(pages, &references, &mut objects, diagnostics)?; } for (id, annotation) in xdv_annotations { objects[id - 1] = annotation.pdf(&references, &xdv_names)?; diff --git a/crates/texrra-tex-core/src/pdf_device/color.rs b/crates/texrra-tex-core/src/pdf_device/color.rs index 450211c..3aa7c32 100644 --- a/crates/texrra-tex-core/src/pdf_device/color.rs +++ b/crates/texrra-tex-core/src/pdf_device/color.rs @@ -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>, + pub(crate) xdv_resources: Vec, +} + +#[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, +} + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum ColorProgramWire { + Device(String), + Resources { literal: String, resources: Vec }, +} + +impl TryFrom for PdfColorProgram { + type Error = String; + + fn try_from(wire: ColorProgramWire) -> Result { + match wire { + ColorProgramWire::Device(literal) => Self::parse(literal), + ColorProgramWire::Resources { literal, resources } => { + validate_xdv_color(&literal, &resources)?; + Ok(Self::xdv(literal, resources)) + } + } + } +} + +impl From 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::().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) -> 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(), }]) diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_color.rs b/crates/texrra-tex-core/src/pdf_device/xdv_color.rs index 89d81a5..d8c034d 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_color.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_color.rs @@ -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), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct NamedColor { + space: Option, + components: Vec, + pattern: Option, + 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) { + 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 { 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 { - Arc::new(PdfColorProgram::parse(literal).expect("generated PDF device color")) +fn program(literal: String, resources: Vec) -> Arc { + 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> { @@ -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> { + 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>, + ) -> Option> { 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 { + 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 { + 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 { 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::().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(&mut self) -> Result<[f64; N], String> { @@ -289,29 +354,68 @@ fn parse_dvips(tokens: &mut Tokens<'_>) -> Result { } } -fn read_pair(tokens: &mut Tokens<'_>, current: Colors) -> Result { +fn read_pair( + tokens: &mut Tokens<'_>, current: Colors, navigation: &mut Option>, +) -> Result { 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 { +fn parse_pdf_color( + tokens: &mut Tokens<'_>, navigation: &mut Option>, +) -> Result { + 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::>()?; + 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), diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs index 74dee41..cd21304 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -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, NamedObject>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + color_spaces: BTreeMap, usize>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + color_patterns: BTreeMap, usize>, #[serde(default, skip_serializing_if = "PageDictionaries::is_empty")] page_dictionaries: PageDictionaries, #[serde(default, skip_serializing_if = "PageResources::is_empty")] diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/color_resources.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/color_resources.rs new file mode 100644 index 0000000..4c36320 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/color_resources.rs @@ -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 { + 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 { + 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, usize>, + name: &[u8], + category: XdvColorCategory, + prefix: &str, +) -> Result { + 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 { + 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 +} diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs index da38feb..d1aca22 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs @@ -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, diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs index 88d61cf..c2c81ac 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs @@ -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), diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs index 1e42015..bf3222a 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs @@ -115,14 +115,24 @@ impl Navigation { pub(crate) fn write_page_resources( &self, + pages: &[crate::render::DisplayList], references: &References<'_>, objects: &mut [Vec], diagnostics: &mut Vec, ) -> 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))?; } diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index a246000..4d9094a 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -354,10 +354,12 @@ impl DisplayList { /// Whether this page needs the complete PDF device output for SVG preview. pub fn has_embedded_pdf(&self) -> bool { self.pdf_resources.needs_pdf_for_preview + || self.pdf_background.as_ref().is_some_and(|program| !program.xdv_resources.is_empty()) || self .items .iter() - .any(|item| matches!(item, DisplayItem::PdfImage { .. } | DisplayItem::PdfForm { .. } + .any(|item| matches!(item, DisplayItem::PdfColor { program, .. } if !program.xdv_resources.is_empty()) + || matches!(item, DisplayItem::PdfImage { .. } | DisplayItem::PdfForm { .. } | DisplayItem::PdfGraphics { operation: crate::pdf_device::PdfGraphics::Literal { .. }, .. diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index fc903bc..71743f2 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -692,6 +692,71 @@ fn xdv_color_is_shipped_in_order_and_replayed_on_the_next_page() { assert!(!pages[1].same_svg_paint(&without_background)); } +#[test] +fn xdv_named_color_tracks_page_and_form_resources() { + use lopdf::Document; + use texrra_tex_core::{ + pdf::shipout_lists_to_native_pdf_document, + pdf_device::PdfColorProgram, + render::DisplayItem, + }; + + 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} + \shipout\hbox{ + \special{pdf:obj @ink [/Separation /Orange /DeviceCMYK + << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 .7 1 0] /N 1 >>]} + \special{pdf:obj @cal [/CalGray << /WhitePoint [.95 1 1.08] >>]} + \special{pdf:bc @ink .75}\block + \special{pdf:bxobj @art width 8pt height 6pt} + \special{pdf:bc @cal .4}\block\special{pdf:ec} + \special{pdf:exobj}\special{pdf:uxobj @art}} + \shipout\hbox{\block\special{pdf:ec}\block} + \end"), + &mut TestDevice, + ) + .unwrap(); + let pages = result.shipout_display_lists().unwrap(); + assert!(pages[1].has_embedded_pdf()); + assert!(pages[1].try_to_svg().is_err()); + let color = pages[1].items.iter().find_map(|item| match item { + DisplayItem::PdfColor { program, .. } => Some(program.as_ref()), + _ => None, + }).unwrap(); + let mut saved = serde_json::to_value(color).unwrap(); + assert_eq!(&serde_json::from_value::(saved.clone()).unwrap(), color); + saved["literal"] = serde_json::Value::String(format!("{} q", color.literal())); + assert!(serde_json::from_value::(saved).is_err()); + 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_resources = |id| pdf.get_dictionary(id).unwrap() + .get(b"Resources").unwrap().as_dict().unwrap(); + let ids = pdf.get_pages(); + let first = page_resources(ids[&1]); + let second = page_resources(ids[&2]); + let form_id = first.get(b"XObject").unwrap().as_dict().unwrap() + .get(b"Fm1").unwrap().as_reference().unwrap(); + let form = pdf.get_object(form_id).unwrap().as_stream().unwrap(); + let form_resources = form.dict.get(b"Resources").unwrap().as_dict().unwrap(); + let colors = |resources: &lopdf::Dictionary| { + resources.get(b"ColorSpace").unwrap().as_dict().unwrap().clone() + }; + let ink = colors(first).get(b"XC0").unwrap().as_reference().unwrap(); + assert_eq!(colors(second).len(), 1); + assert_eq!(colors(second).get(b"XC0").unwrap().as_reference().unwrap(), ink); + assert_eq!(colors(first).len(), 1); + assert_eq!(colors(form_resources).get(b"XC0").unwrap().as_reference().unwrap(), ink); + let calibrated = colors(form_resources).get(b"XC1").unwrap().as_reference().unwrap(); + assert_eq!(pdf.get_object(calibrated).unwrap().as_array().unwrap()[0].as_name().unwrap(), b"CalGray"); + assert_eq!(pdf.get_object(ink).unwrap().as_array().unwrap()[0].as_name().unwrap(), b"Separation"); + let content = String::from_utf8(pdf.get_page_content(ids[&2]).unwrap()).unwrap(); + assert!(content.contains("/XC0 cs 0.75 scn")); +} + #[test] fn xdv_catalog_and_outlines_resolve_live_pages_and_retain_referenced_names() { use lopdf::Document; diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index cba9f52..5a01207 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,29 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeTeX 命名色彩空间与页面资源 + +XeTeX 的 PDF 颜色指令按实际出页顺序解析命名对象。专色、校准色、索引色、 +DeviceN、ICC 及图案通过 PDF 的 ColorSpace 或 Pattern 资源输出。PDF 页面及 +Form 引用实际对象及其依赖。独立填充与描边、跨页颜色栈以及 Form 中的颜色 +继承接入同一套状态。实时预览使用发布 PDF 中的资源,颜色定义变化也会触发 +相关页面更新。 + +原版 XeTeX 和 xdvipdfmx 对照样例涵盖 CalRGB、CalGray、Indexed、图案、 +专色 Form 及跨页还原,两页的 144 DPI 像素一致。另一份专色与旧 /LAB 样例 +的第一页像素一致。参考驱动写出旧拼写 /LAB,两端保留该资源并被 Poppler +报为无效,第二页有 2,016 个像素的回退色差异。保留该差异和原始失败日志。 +[参考驱动的色彩空间解析](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/spc_util.c) + +在三页项目中修改第二页的专色定义。两次成功修订均复用检查点并只刷新 +第 2 页,PDF、绘制列表、SVG 和来源映射与独立全量一致。未定义资源时保留 +上一版发布。XDV 定向回归 16 项通过。证据见 target/p3-xdv-resource-colors/。 + +ACM 三类样稿与 Elsevier CAS 单、双栏均已在后续单项复验中达到稳定版面。 +下一批把真实格式、类和资源、导出及连续编辑接到同一份原样 XeLaTeX 多文件 +项目,按首个可复现的通用缺口推进。功能接齐后在同版运行原样出版模板矩阵、 +正式编辑到可见页面的 p50/p95 与内存验收。 [出版模板记录](PUBLISHER_TEMPLATE_MATRIX.md) + ## 2026-11-28 发布来源与指纹复用 成功执行和失败证据都直接交付内核的来源对象,以 Arc 保存条目。