From e9893a5c1b9cf73b5ea38ec207d508cf65a8f2f2 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 02:35:22 +0800 Subject: [PATCH] Ship named PDF color spaces and patterns from native color stacks --- .../texrra-tex-core/src/pdf_device/color.rs | 52 +++++++++++++++++-- crates/texrra-tex-core/src/render.rs | 4 +- .../tests/execution_pdf_color.rs | 28 ++++++++++ .../fixtures/pdf-color/pattern-stack.tex | 15 ++++++ docs/P2_M1_PROGRESS.md | 30 +++++++++++ 5 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 crates/texrra-tex-core/tests/fixtures/pdf-color/pattern-stack.tex diff --git a/crates/texrra-tex-core/src/pdf_device/color.rs b/crates/texrra-tex-core/src/pdf_device/color.rs index 3aa7c32..0d02d5a 100644 --- a/crates/texrra-tex-core/src/pdf_device/color.rs +++ b/crates/texrra-tex-core/src/pdf_device/color.rs @@ -11,6 +11,7 @@ pub struct PdfColorProgram { pub(crate) fill: Option<[u8; 3]>, pub(crate) stroke: Option<[u8; 3]>, pub(crate) graphics_states: Vec>, + uses_pdf_color_space: bool, pub(crate) xdv_resources: Vec, } @@ -141,19 +142,59 @@ fn color_component(token: &str) -> bool { && token.parse::().is_ok_and(f64::is_finite) } +fn color_tokens(literal: &str) -> impl Iterator { + let pdf_space = |c| matches!(c, '\0' | '\t' | '\n' | '\r' | '\x0c' | ' '); + let mut rest = literal; + std::iter::from_fn(move || { + loop { + rest = rest.trim_start_matches(pdf_space); + if !rest.starts_with('%') { + break; + } + rest = rest.find(['\r', '\n']).map_or("", |end| &rest[end..]); + } + if rest.is_empty() { + return None; + } + let start = usize::from(rest.starts_with('/')); + let end = rest[start..] + .find(|c| pdf_space(c) || matches!(c, '/' | '%')) + .map_or(rest.len(), |offset| start + offset); + let (token, tail) = rest.split_at(end); + rest = tail; + Some(token) + }) +} + impl PdfColorProgram { + pub(crate) fn needs_pdf_for_preview(&self) -> bool { + self.uses_pdf_color_space || !self.xdv_resources.is_empty() + } + pub(crate) fn parse(literal: String) -> Result { let mut fill = None; let mut stroke = None; let mut operands = Vec::with_capacity(4); let mut graphics_states = Vec::new(); + let mut uses_pdf_color_space = false; let mut name = None; - for token in literal.split_ascii_whitespace() { + for token in color_tokens(&literal) { if token == "gs" && operands.is_empty() { graphics_states.push(name.take().ok_or("PDF gs requires a resource name")?); + } else if matches!(token, "cs" | "CS") && operands.is_empty() { + name.take().ok_or("PDF color-space operator requires one name")?; + uses_pdf_color_space = true; + } else if matches!(token, "sc" | "SC" | "scn" | "SCN") { + let allows_pattern = matches!(token, "scn" | "SCN"); + let pattern = name.take().is_some(); + if (!pattern && operands.is_empty()) || (pattern && !allows_pattern) { + return Err(format!("invalid operands for PDF color operator {token}")); + } + operands.clear(); + uses_pdf_color_space = true; } else if name.is_some() { - return Err("PDF resource name must be followed by gs".into()); - } else if token.starts_with('/') && operands.is_empty() { + return Err("unexpected token after PDF color resource name".into()); + } else if token.starts_with('/') { name = Some(super::page_resources::parse_name(token.as_bytes())?); } else if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") { let rgb = match (token, operands.as_slice()) { @@ -174,7 +215,7 @@ impl PdfColorProgram { operands.clear(); } else { let number = token.strip_prefix(['+', '-']).unwrap_or(token); - if operands.len() == 4 + if operands.len() == super::xdv_navigation::MAX_COLOR_COMPONENTS || !number .bytes() .all(|byte| byte.is_ascii_digit() || byte == b'.') @@ -199,6 +240,7 @@ impl PdfColorProgram { fill, stroke, graphics_states, + uses_pdf_color_space, xdv_resources: Vec::new(), }) } @@ -209,6 +251,7 @@ impl PdfColorProgram { fill: None, stroke: None, graphics_states: Vec::new(), + uses_pdf_color_space: false, xdv_resources, } } @@ -295,6 +338,7 @@ impl Default for PdfColorStacks { fill: Some([0; 3]), stroke: Some([0; 3]), graphics_states: Vec::new(), + uses_pdf_color_space: false, xdv_resources: Vec::new(), }), saved: Vec::new(), diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 4d9094a..8b803c4 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -354,11 +354,11 @@ 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.pdf_background.as_ref().is_some_and(|program| program.needs_pdf_for_preview()) || self .items .iter() - .any(|item| matches!(item, DisplayItem::PdfColor { program, .. } if !program.xdv_resources.is_empty()) + .any(|item| matches!(item, DisplayItem::PdfColor { program, .. } if program.needs_pdf_for_preview()) || matches!(item, DisplayItem::PdfImage { .. } | DisplayItem::PdfForm { .. } | DisplayItem::PdfGraphics { operation: crate::pdf_device::PdfGraphics::Literal { .. }, diff --git a/crates/texrra-tex-core/tests/execution_pdf_color.rs b/crates/texrra-tex-core/tests/execution_pdf_color.rs index 6416f34..1e00a82 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_color.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_color.rs @@ -226,6 +226,34 @@ fn actual_color_stack_ships_and_replays_in_pdf_and_svg() { } } +#[test] +fn pattern_stack_uses_the_actual_pdf_resources_for_preview() { + let directory = std::env::temp_dir().join(format!("texrra-color-pattern-{}", std::process::id())); + let data = fixture("pattern-stack.tex"); + let reference = reference_pdf(&directory, "reference", &data); + let mut host = Host::default(); + let execution = run(data, &mut host).unwrap(); + let pages = execution.shipout_display_lists().unwrap(); + assert_eq!(pages.len(), 1); + assert!(pages[0].has_embedded_pdf()); + assert!(pages[0].try_to_svg().is_err()); + assert!(pages[0].items.iter().any(|item| matches!( + item, DisplayItem::PdfColor { program, .. } + if program.literal() == "/Pattern cs/Hatch scn" + ))); + let native = directory.join("native.pdf"); + fs::write( + &native, + pdf::shipout_lists_to_native_pdf(&pages, execution.state.pdf_final_options()).unwrap(), + ).unwrap(); + raster(&reference, &directory.join("reference")); + raster(&native, &directory.join("native")); + assert_eq!( + fs::read(directory.join("reference-1.ppm")).unwrap(), + fs::read(directory.join("native-1.ppm")).unwrap(), + ); +} + #[test] fn loaded_format_retains_color_nodes_but_allocates_stacks_per_job() { let reference = diff --git a/crates/texrra-tex-core/tests/fixtures/pdf-color/pattern-stack.tex b/crates/texrra-tex-core/tests/fixtures/pdf-color/pattern-stack.tex new file mode 100644 index 0000000..b7c974a --- /dev/null +++ b/crates/texrra-tex-core/tests/fixtures/pdf-color/pattern-stack.tex @@ -0,0 +1,15 @@ +\catcode123=1 \catcode125=2 \catcode35=6 +\def\space{ } +\pdfoutput=1 +\pdfcompresslevel=0 \pdfobjcompresslevel=0 +\pdfpagewidth=144bp \pdfpageheight=144bp +\pdfhorigin=12bp \pdfvorigin=12bp +\immediate\pdfobj stream attr + {/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox[0 0 8 8] /XStep 8 /YStep 8 /Resources<<>>} + {0 0 1 rg 0 0 4 8 re f} +\edef\resources{/Pattern<< /Hatch \the\pdflastobj\space 0 R >>} +\pdfpageresources=\expandafter{\resources} +\shipout\vbox{\hbox{\pdfcolorstack0 push{/Pattern cs/Hatch scn}% + \vrule width90bp height36bp depth0bp \pdfcolorstack0 pop}% + \prevdepth=-1000pt\hbox{\vrule width90bp height24bp depth0bp}} +\end diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index cf305c7..2166c49 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,36 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 PDF 命名色彩空间、图案与跨栏浮动复核 + +pdfTeX 颜色栈可以选择命名色彩空间,应用单一或多分量颜色以及 PDF +图案。填充和描边操作按扫描顺序写入原生页面。原始 PDF 字面量及 +间接对象图经既有资源导出路径保存,实时预览用当前发布 PDF 解释该页 +真实引用的色彩空间和图案。 +[pdfTeX 的颜色栈行为](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/web2c/pdftexdir/utils.c#L1087-L1155) + +原样 colorspace.sty 的专色和混合油墨项目以及 INITEX 图案项目合计 +四页。144 DPI 彩色光栅均与 pdfTeX 逐像素一致。核对 PDF 的 Separation、 +DeviceN 和混合油墨页的叠印状态。三页会话在实际外部色板修改同名专色。 +两次编辑和恢复都只更新第 2 页,PDF、绘制列表、预览、来源映射、 +aux 和日志与独立全量一致。非法色板保留完整发布。色板在导言区读取, +这些修订仍需重新执行正文。颜色专项四项通过,一项旧的库级操作序列断言 +比较平移命令的分解时失败。两版 CLI 对照的默认颜色栈内容流逐字节一致, +保留断言、原版、发布生成物和失败日志。 +[CTAN Colorspace](https://ctan.org/pkg/colorspace) + +五份真实 LaTeX 浮动与分页组合用未修改的 stfloats、cuted、ftnright +和 rotating。跨栏底部和顶部浮动、浮动页、贯穿双栏的段落、右栏脚注、 +旋转表格、页边批注和拆分长脚注分别进入实际输出例程。首轮参考与原生 +各生成 13 页,2,425 个词框及 aux 一致。最新基线在 +target/p3-cross-column-output/baseline-comparison.json。 +[CTAN Sttools](https://ctan.org/pkg/sttools) + +图形证据存于 target/p3-pdf-named-colors/。原样 colorspace 的默认 +ICC 配置仍在二进制文件头读取处停止,已保存 TeX Live 原始 rgb.icc 及 +实际参考 PDF。接续 pdfTeX 和 XeTeX 的二进制范围读取、真实资源失效与 +ICC 生效后的输出和预览。原样出版矩阵及正式实时延迟继续按原门禁验收。 + ## 2026-11-29 条件数学胶水与双栏表格 两种 profile 支持 TeX 的 Nonscript 原语。扫描标记时保留真实零胶水,