From 7ff988031faf4a4a3a8b69894dfd34e761b493f1 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 27 Nov 2026 14:47:39 +0800 Subject: [PATCH] Handle legacy XeTeX paper and landscape specials --- .../src/execution/engine/page.rs | 77 +++++++---- .../src/execution/engine/specials.rs | 4 - .../src/pdf_device/xdv_paper.rs | 129 ++++++++++++++++-- docs/P2_M1_PROGRESS.md | 26 ++++ tests/native_device.rs | 93 ++++++++++--- 5 files changed, 274 insertions(+), 55 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index bbd995a..c889c89 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -415,17 +415,8 @@ impl Executor { let mut pdf_objects = Vec::new(); let mut xdv_annotations = std::collections::BTreeMap::new(); let mut reopened_images = false; - let mut xdv_paper = self.state.xdv_setup.paper; - if xdv { - // XeTeX emits an implicit pagesize at the start of every page. - if requested_page_width > 0 && requested_page_height > 0 { - xdv_paper.size = [Some(requested_page_width), Some(requested_page_height)]; - } else { - xdv_paper.offset = [None; 2]; - } - } + let mut xdv_paper_specials = Vec::new(); let mut xdv_navigation = Vec::new(); - let first_page = self.shipped_pages == 0; for (index, output) in outputs.into_iter().enumerate() { while font_uses.peek().is_some_and(|usage| usage.before_output == index) { self.current = current; @@ -486,14 +477,8 @@ impl Executor { } else if xdv && crate::pdf_device::xdv_annotation::Command::recognize(&special.bytes).is_some() { xdv_annotations.insert(graphics_step, shipout.specials.len()); None - } else if xdv && let Some(operands) = super::specials::xdv_pagesize_operand(&special.bytes) { - if let Err(message) = xdv_paper.read( - operands, magnification, (!first_page).then_some(self.state.xdv_setup.paper.size), - ) { - files.observe_diagnostic( - WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {message}\n"), - ).map_err(|error| self.error(error, special.span))?; - } + } else if xdv && crate::pdf_device::xdv_paper::Special::parse(&special.bytes).is_some() { + xdv_paper_specials.push(shipout.specials.len()); None } else if xdv && super::specials::xdv_navigation_operand(&special.bytes).is_some() { let point = xdv_transform.point( @@ -673,11 +658,14 @@ impl Executor { if xdv { // Page setup applies to the entire page, including graphics and // destination specials emitted before the paper special. - let setup = &mut self.state.xdv_setup.paper; - if first_page { - setup.size = xdv_paper.size; - } - setup.offset = xdv_paper.offset; + let xdv_paper = self.ship_xdv_paper( + &shipout.specials, + &xdv_paper_specials, + [requested_page_width, requested_page_height], + [default_canvas(612), default_canvas(792)], + magnification, + files, + )?; let device = &mut shipout.device; if let Some(width) = xdv_paper.size[0] { device.page_width = width; @@ -724,6 +712,49 @@ impl Executor { Ok(()) } + fn ship_xdv_paper( + &mut self, + specials: &[ShipoutSpecial], + indices: &[usize], + requested: [i64; 2], + fallback: [i64; 2], + magnification: i32, + files: &mut impl SourceProvider, + ) -> Result { + use crate::pdf_device::xdv_paper::Special; + let mut document = self.state.xdv_setup.paper; + // The driver's initial scan also buffers the first page for output. + // Its orientation establishes the global paper before later pages. + let first_page = self.shipped_pages == 0; + if first_page { + document.size = fallback.map(Some); + } + let mut page = document; + page.start_page(requested); + for &index in indices { + let special = &specials[index]; + let command = Special::parse(&special.bytes).expect("recognized paper special"); + let global = (!first_page).then_some(&mut document); + if let Err(message) = page.read(command, magnification, global) { + files.observe_diagnostic( + WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {message}\n"), + ).map_err(|error| self.error(error, special.span))?; + } + } + if first_page { + if page.landscape { + page.size.swap(0, 1); + } + document = page; + } else if page.landscape != document.landscape { + page.size.swap(0, 1); + document.landscape = page.landscape; + } + document.offset = page.offset; + self.state.xdv_setup.paper = document; + Ok(page) + } + fn pdf_space_settings( &mut self, automatic_at_start: bool, diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 54e4a08..28fe431 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -213,10 +213,6 @@ fn xdv_pdf_body(data: &[u8]) -> Option<&[u8]> { data.trim_ascii_start().strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start) } -pub(super) fn xdv_pagesize_operand(data: &[u8]) -> Option<&[u8]> { - xdv_operand(xdv_pdf_body(data)?, b"pagesize") -} - pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8])> { let body = xdv_pdf_body(data)?; for (name, kind) in [ diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_paper.rs b/crates/texrra-tex-core/src/pdf_device/xdv_paper.rs index 345a99d..27799da 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_paper.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_paper.rs @@ -7,25 +7,137 @@ pub(crate) struct Paper { pub(crate) size: [Option; 2], /// Driver origin, independent of TeX's horizontal and vertical moves. pub(crate) offset: [Option; 2], + #[serde(default, skip_serializing_if = "is_false")] + pub(crate) landscape: bool, } +fn is_false(value: &bool) -> bool { + !value +} + +#[derive(Clone, Copy)] +pub(crate) enum Special<'a> { + PageSize(&'a [u8]), + PaperSize(&'a [u8]), + Landscape, +} + +impl<'a> Special<'a> { + pub(crate) fn parse(data: &'a [u8]) -> Option { + let (name, rest) = identifier(data); + let mut pdf = false; + let (name, rest) = if matches!(name, b"pdf" | b"x" | b"dvipdfmx") + && let Some(body) = rest.trim_ascii_start().strip_prefix(b":") + { + pdf = name == b"pdf"; + identifier(body) + } else { + (name, rest) + }; + match name { + b"pagesize" if pdf => Some(Self::PageSize(rest)), + b"papersize" => Some(Self::PaperSize(rest)), + b"landscape" => Some(Self::Landscape), + _ => None, + } + } +} + +fn identifier(input: &[u8]) -> (&[u8], &[u8]) { + let input = input.trim_ascii_start(); + let end = input + .iter() + .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_')) + .unwrap_or(input.len()); + input.split_at(end) +} + +const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0; + impl Paper { pub(crate) fn is_default(&self) -> bool { *self == Self::default() } - /// The first page updates its own defaults. Subsequent pages start from - /// those dimensions, while the physical origin carries across pages. + pub(crate) fn start_page(&mut self, requested: [i64; 2]) { + if requested.into_iter().all(|length| length > 0) { + self.size = requested.map(Some); + } else { + // XeTeX writes an implicit "pdf:pagesize default" before the + // box. Keep the configured native origin for this implicit reset. + self.offset = [None; 2]; + } + } + + /// During the pre-scan, the first page is also the document default. + /// Later scans keep a separate current sheet and mutable document paper. pub(crate) fn read( + &mut self, + special: Special<'_>, + magnification: i32, + document: Option<&mut Paper>, + ) -> Result<(), &'static str> { + match special { + Special::PageSize(input) => self.read_pagesize(input, magnification, document), + Special::PaperSize(input) => self.read_papersize(input, magnification, document), + Special::Landscape => { + self.landscape = true; + Ok(()) + } + } + } + + fn read_papersize( &mut self, input: &[u8], magnification: i32, - document_size: Option<[Option; 2]>, + document: Option<&mut Paper>, + ) -> Result<(), &'static str> { + let input = std::str::from_utf8(input).map_err(|_| "invalid XDV papersize operands")?; + let input = input.trim_ascii_start(); + let input = input.strip_prefix('=').unwrap_or(input).trim_ascii_start(); + let (lengths, closed) = match input.chars().next() { + Some(quote @ ('\'' | '"')) => (&input[1..]) + .split_once(quote) + .map_or((&input[1..], false), |(lengths, _)| (lengths, true)), + _ => (input, true), + }; + let lengths = lengths.replace(',', " , "); + let mut words = lengths.split_ascii_whitespace().peekable(); + let width = super::xdv_image::length(&mut words, 1000) + .map_err(|_| "invalid XDV papersize width")?; + if words.peek() == Some(&",") { + words.next(); + } + let height = super::xdv_image::length(&mut words, 1000) + .map_err(|_| "invalid XDV papersize height")?; + let unit = SP_PER_BP * 1000.0 / f64::from(magnification); + let size = [width, height].map(|bp| (bp * unit).round()); + if !size + .into_iter() + .all(|length| (1.0..=1_073_741_823.0).contains(&length)) + { + return Err("XDV papersize length out of range"); + } + self.size = size.map(|length| Some(length as i64)); + if !closed || (input.starts_with(['\'', '"']) && words.next().is_some()) { + return Err("unclosed XDV papersize quote"); + } + if let Some(document) = document { + document.size = self.size; + } + Ok(()) + } + + fn read_pagesize( + &mut self, + input: &[u8], + magnification: i32, + document: Option<&mut Paper>, ) -> Result<(), &'static str> { let data = std::str::from_utf8(input).map_err(|_| "invalid XDV pagesize operands")?; let mut words = data.split_ascii_whitespace().peekable(); - let sp_per_bp = 65536.0 * 803.0 / 800.0; - let default_offset = (72.0 * sp_per_bp * 1000.0 / f64::from(magnification)).round() as i64; + let default_offset = (72.0 * SP_PER_BP * 1000.0 / f64::from(magnification)).round() as i64; while let Some(word) = words.next() { let destination = match word { "width" => &mut self.size[0], @@ -33,8 +145,9 @@ impl Paper { "xoffset" => &mut self.offset[0], "yoffset" => &mut self.offset[1], "default" => { - if let Some(size) = document_size { - self.size = size; + if let Some(document) = document.as_deref() { + self.size = document.size; + self.landscape = document.landscape; } self.offset = [Some(default_offset); 2]; continue; @@ -44,7 +157,7 @@ impl Paper { }; let bp = super::xdv_image::length(&mut words, magnification) .map_err(|_| "invalid XDV pagesize length")?; - let value = (bp * sp_per_bp).round(); + let value = (bp * SP_PER_BP).round(); let size = matches!(word, "width" | "height"); if !(-1_073_741_823.0..=1_073_741_823.0).contains(&value) || (size && value <= 0.0) { return Err("XDV pagesize length out of range"); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 51f74d4..24df488 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -735,6 +735,32 @@ PDF、SVG、来源映射以及纸张指令前后的命名目标使用同一页 回执 `target/p3-xdv-pagesize/receipt.json` 的 SHA-256 为 `72494e67dc133a1139cb8280a37547fc9fe4ffb832c6c40bfc8098bb4a7e8bc6`。 +### XeTeX 旧式纸张与横向设置 + +旧式 `papersize` 接入发页时的纸张扫描,支持逗号、空白、引号及物理 +单位。成功设置同时改变当页和文档纸张,后续 `pdf:pagesize` 仍可覆盖 +当页。缺少闭合引号时保留当页已解析的尺寸并报告警告,后续沿用原有 +默认。首页沿用驱动的缓冲预扫,横向只交换一次宽高。后续页在方向变动 +时交换当前宽高,并保留方向状态供后续页使用。PDF 和预览继续消费同一 +页设备状态。 +[TeX Live 纸张解析与首页缓存](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/dvi.c#L2486-L2605) + +新作业六组 23 页和原纸张作业七组 24 页的纸张尺寸均与参考相同。 +46 页 144 DPI 灰度逐像素一致。120% 放大的一页在坐标 (43,72) 有 +一个像素的灰度差。上一发布版以同等 `pdf:pagesize` 设置复现同一 +像素差,保留两版和参考的真实规则坐标。四项设备定向回归通过。 +修改子文件中的全局纸张后,会话安全 +续跑,预览只更新第二至第五页。后续明确设置另一纸张后,第六页保持 +原结果。PDF、SVG 和逐页来源映射与同版独立全量一致。 + +下一个 PDF 缺口在 `target/p3-xdv-legacy-paper/next-pdf-xform`。 +原版消费盒寄存器并用同一 Form 生成两页,引用盒尺寸为 +1966080、524288、131072 sp,实际输出含 Form 属性和 BBox。原生在 +`\pdfxform` 拒绝。统一出版模板与性能验收按原计划继续。 + +回执 `target/p3-xdv-legacy-paper/receipt.json` 的 SHA-256 为 +`e467f511de220a9ceccc1ff3f480f278be587cc2324ad5e45e5f9b0b594d5c16`。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/tests/native_device.rs b/tests/native_device.rs index d92d816..d3611bb 100644 --- a/tests/native_device.rs +++ b/tests/native_device.rs @@ -139,6 +139,64 @@ fn illegal_or_incompatible_magnification_and_huge_pages_protect_existing_pdf() { #[test] fn xdv_page_setup_edit_updates_the_local_sheet_and_inherited_origin() { + let prefix = r"\catcode123=1 \catcode125=2 +\pdfpagewidth=11182899sp \pdfpageheight=16445440sp +\shipout\hbox{\special{pdf:pagesize width 170bp height 250bp xoffset 24bp}\vrule width10pt height4pt} +"; + let tail = r"\input sheet.tex +\shipout\hbox{\sheet\vrule width10pt height4pt} +\shipout\hbox{\vrule width10pt height4pt} +\shipout\hbox{\special{pdf:pagesize default}\vrule width10pt height4pt} +\end +"; + check_xdv_paper_revisions( + prefix, + tail, + [ + "pdf:pagesize width 190bp xoffset 36bp", + "pdf:pagesize width 205bp xoffset 46bp", + ], + &[[170, 250], [205, 250], [170, 250], [170, 250]], + &[1, 2], + ); +} + +#[test] +fn xdv_legacy_paper_edit_propagates_until_the_next_document_default() { + let prefix = r"\catcode123=1 \catcode125=2 +\shipout\hbox{\special{papersize=200bp,300bp}\vrule width10pt height4pt} +"; + let tail = r"\input sheet.tex +\shipout\hbox{\sheet\vrule width10pt height4pt} +\shipout\hbox{\vrule width10pt height4pt} +\shipout\hbox{\special{landscape}\vrule width10pt height4pt} +\shipout\hbox{\special{landscape}\vrule width10pt height4pt} +\shipout\hbox{\special{papersize=200bp,300bp}\vrule width10pt height4pt} +\end +"; + check_xdv_paper_revisions( + prefix, + tail, + ["papersize=160bp,230bp", "papersize=165bp,240bp"], + &[ + [200, 300], + [165, 240], + [165, 240], + [240, 165], + [165, 240], + [200, 300], + ], + &[1, 2, 3, 4], + ); +} + +fn check_xdv_paper_revisions( + prefix: &str, + tail: &str, + specials: [&str; 2], + expected_sizes: &[[i32; 2]], + expected_delta: &[usize], +) { use std::sync::Arc; use texrra_engine::native::{ CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot, @@ -151,19 +209,9 @@ fn xdv_page_setup_edit_updates_the_local_sheet_and_inherited_origin() { let root = directory().canonicalize().unwrap(); let entry = root.join("probe.tex"); let sheet = root.join("sheet.tex"); - let prefix = r"\catcode123=1 \catcode125=2 -\pdfpagewidth=11182899sp \pdfpageheight=16445440sp -\shipout\hbox{\special{pdf:pagesize width 170bp height 250bp xoffset 24bp}\vrule width10pt height4pt} -"; let padding = format!("{}\n", "\\relax ".repeat(32)).repeat(48); - let tail = r"\input sheet.tex -\shipout\hbox{\sheet\vrule width10pt height4pt} -\shipout\hbox{\vrule width10pt height4pt} -\shipout\hbox{\special{pdf:pagesize default}\vrule width10pt height4pt} -\end -"; - let from_sheet = |width, x| -> Arc<[u8]> { - format!("\\def\\sheet{{\\special{{pdf:pagesize width {width}bp xoffset {x}bp}}}}\n") + let sheet_source = |text: &str| -> Arc<[u8]> { + format!("\\def\\sheet{{\\special{{{text}}}}}\n") .into_bytes() .into() }; @@ -177,7 +225,7 @@ fn xdv_page_setup_edit_updates_the_local_sheet_and_inherited_origin() { entry.clone(), format!("{prefix}{padding}{tail}").into_bytes().into(), ), - (sheet.clone(), from_sheet(190, 36)), + (sheet.clone(), sheet_source(specials[0])), ] .into(), directories: Default::default(), @@ -196,19 +244,24 @@ fn xdv_page_setup_edit_updates_the_local_sheet_and_inherited_origin() { .compile(request.clone().with_project(snapshot.clone())) .unwrap(); let updated = snapshot - .with_file_edits(2, [(sheet, from_sheet(205, 46))].into()) + .with_file_edits(2, [(sheet, sheet_source(specials[1]))].into()) .unwrap(); let revised = request.with_project(updated); let next = compiler.compile(revised.clone()).unwrap(); assert!(next.entry_checkpoint_work.reused_steps > 0); - let widths: Vec<_> = next.pages.iter().map(|page| page.width).collect(); - assert_eq!( - widths, - [170, 205, 170, 170].map(|bp| (f64::from(bp) * 65_781.76).round() as i64) - ); + let sizes: Vec<_> = next + .pages + .iter() + .map(|page| [page.width, page.height]) + .collect(); + let expected: Vec<_> = expected_sizes + .iter() + .map(|size| size.map(|bp| (f64::from(bp) * 65_781.76).round() as i64)) + .collect(); + assert_eq!(sizes, expected); let delta = next.preview_since(Some(first.revision())).unwrap(); let changed: Vec<_> = delta.pages.iter().map(|page| page.index).collect(); - assert_eq!(changed, [1, 2]); + assert_eq!(changed, expected_delta); let full = NativeCompiler::default().compile(revised).unwrap(); assert_eq!(next.pdf, full.pdf);