From 330c4bde5119c18c2c7e505bf47d5c5602d122b5 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 10:32:34 +0800 Subject: [PATCH] Match pdfTeX graphics-origin movement thresholds --- crates/texrra-tex-core/src/pdf.rs | 70 +++++++++++++------ .../src/pdf_device/graphics.rs | 65 ++++++++++------- crates/texrra-tex-core/src/pdf_text.rs | 43 +++++------- .../src/source_map/pdf_projection.rs | 13 ++-- docs/P2_M1_PROGRESS.md | 25 +++++++ docs/PUBLISHER_TEMPLATE_MATRIX.md | 5 ++ tests/native_pages.rs | 49 +++++++++++++ 7 files changed, 195 insertions(+), 75 deletions(-) diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 988577d..a7ce22f 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -624,17 +624,35 @@ fn write_type0_font( /// The PDF stream can contain an 8-bit TeX literal. Keep its bytes alongside /// the device origin used by subsequent positioned text, rules, and images. -#[derive(Default)] struct PageContent { bytes: Vec, origin: crate::pdf_device::DeviceOrigin, + digits: u8, measuring: bool, track_legacy_cids: bool, } impl PageContent { - fn measuring() -> Self { - Self { measuring: true, ..Self::default() } + fn new( + units: crate::render::DisplayUnits, + digits: u8, + driver: crate::pdf_device::PdfDriver, + ) -> Self { + Self { + bytes: Vec::new(), + origin: crate::pdf_device::DeviceOrigin::new(units, digits, driver), + digits, + measuring: false, + track_legacy_cids: false, + } + } + + fn measuring( + units: crate::render::DisplayUnits, + digits: u8, + driver: crate::pdf_device::PdfDriver, + ) -> Self { + Self { measuring: true, ..Self::new(units, digits, driver) } } fn push_str(&mut self, text: &str) { @@ -649,14 +667,23 @@ impl PageContent { } } - fn move_origin(&mut self, point: [i64; 2], units: crate::render::DisplayUnits, digits: u8) { - let Some([h, v]) = self.origin.move_to(point, units, digits) else { - return; - }; + fn move_origin(&mut self, point: [i64; 2]) { + if let Some(operands) = self.origin.move_to(point) { + self.write_translation(operands); + } + } + + fn move_origin_temporarily(&mut self, point: [i64; 2]) { + if let Some(operands) = self.origin.temporary_translation(point) { + self.write_translation(operands); + } + } + + fn write_translation(&mut self, [h, v]: [i64; 2]) { self.push_str(&format!( "1 0 0 1 {} {} cm\n", - crate::pdf_device::print_decimal(h, digits), - crate::pdf_device::print_decimal(v, digits), + crate::pdf_device::print_decimal(h, self.digits), + crate::pdf_device::print_decimal(v, self.digits), )); } } @@ -755,9 +782,10 @@ fn page_content( use crate::render::DisplayUnits; let text_origin = xdv_page_origin(list.units, height, list.magnification); - let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv); + let driver = list.pdf.as_ref().map_or(PdfDriver::PdfTeX, |pdf| pdf.driver); + let xdv = driver == PdfDriver::Xdv; let page_origin = form_origin.unwrap_or(if xdv { text_origin } else { [0, 0] }); - let mut content = PageContent::default(); + let mut content = PageContent::new(list.units, digits, driver); content.push_str("q\n0 0 0 rg\n"); if list.magnification != 1000 && form_origin.is_none() { let ratio = f64::from(list.magnification) / 1000.0; @@ -789,9 +817,9 @@ fn page_content( // Captured XDV content uses device-relative coordinates. Keep the // logical origin used by glyphs and specials without emitting the // enclosing sheet's translation into the Form stream. - content.origin.move_to(page_origin, list.units, digits); + content.origin.move_to(page_origin); } else { - content.move_origin(page_origin, list.units, digits); + content.move_origin(page_origin); } let mut native_text: Option = None; let mut tex_text: Option = None; @@ -844,7 +872,7 @@ fn page_content( PdfLiteralMode::Page | PdfLiteralMode::Origin => { native_text::NativeText::finish(&mut tex_text, &mut content); if mode == PdfLiteralMode::Origin { - content.move_origin([x, height - y], list.units, digits); + content.move_origin([x, height - y]); } } PdfLiteralMode::XdvBeginContent => { @@ -852,7 +880,7 @@ fn page_content( let point = [x, height - y]; xdv_content_scopes.push((previous_origin, point)); content.push_str("q\n"); - content.move_origin(point, list.units, digits); + content.move_origin(point); continue; } PdfLiteralMode::XdvEndContent => { @@ -870,7 +898,7 @@ fn page_content( content.push_str("q\n"); } if let Some(point) = special_origin { - content.move_origin(point, list.units, digits); + content.move_origin(point); } } } @@ -880,7 +908,7 @@ fn page_content( content.push_str("Q\n"); content.origin = previous_origin; } else if special_origin.is_some() { - content.move_origin(previous_origin.position(), list.units, digits); + content.move_origin(previous_origin.position()); } continue; } @@ -896,7 +924,7 @@ fn page_content( { assert!(paint.is_some(), "native glyph program must be resolved"); if xdv && tex_text.is_none() { - content.move_origin(page_origin, list.units, digits); + content.move_origin(page_origin); } let _ = native_text::NativeText::glyph( &mut tex_text, @@ -930,7 +958,7 @@ fn page_content( ); } else { native_text::rule( - &mut content, *x - h, *y + v, *width, *rule_height, height, digits, + &mut content, *x, *y, *width, *rule_height, height, digits, ); } continue; @@ -1273,9 +1301,9 @@ fn page_content( DisplayItem::PdfGraphics { x, y, operation } => { let device_origin = list.units == DisplayUnits::TeX && !xdv; if device_origin { - content.move_origin([*x, height - *y], list.units, digits); + content.move_origin([*x, height - *y]); } else if xdv { - content.move_origin(page_origin, list.units, digits); + content.move_origin(page_origin); } match operation { PdfGraphics::Save => content.push_str("q\n"), diff --git a/crates/texrra-tex-core/src/pdf_device/graphics.rs b/crates/texrra-tex-core/src/pdf_device/graphics.rs index 2366f59..2ff95a6 100644 --- a/crates/texrra-tex-core/src/pdf_device/graphics.rs +++ b/crates/texrra-tex-core/src/pdf_device/graphics.rs @@ -1,5 +1,6 @@ //! Graphics state produced by PDF extension whatsits and device specials. +use super::PdfDriver; use crate::render::DisplayUnits; use std::sync::Arc; @@ -97,38 +98,54 @@ impl PdfMatrix { } } -/// Native device origin in logical scaled units, with the same rounding as -/// the emitted PDF translation. The returned operands have \`digits\` decimals. -#[derive(Clone, Copy, Default)] -pub(crate) struct DeviceOrigin([i64; 2]); +/// Tracks the logical position represented by the PDF device's translations. +#[derive(Clone, Copy)] +pub(crate) struct DeviceOrigin { + position: [i64; 2], + scale: i64, + precision: u8, + minimum_move: i64, +} impl DeviceOrigin { - pub(crate) fn position(&self) -> [i64; 2] { - self.0 - } - - pub(crate) fn move_to( - &mut self, - point: [i64; 2], - units: DisplayUnits, - digits: u8, - ) -> Option<[i64; 2]> { - let delta = [point[0] - self.0[0], point[1] - self.0[1]]; - if delta == [0, 0] { - return None; - } + pub(crate) fn new(units: DisplayUnits, digits: u8, driver: PdfDriver) -> Self { let (scale, precision) = match units { DisplayUnits::TeX => (6_578_176, digits + 2), DisplayUnits::PostScript => (65_536, digits), }; - let [(h, h_sp), (v, v_sp)] = - delta.map(|value| super::divide_scaled(value, scale, precision)); - if h == 0 && v == 0 { + // pdfTeX decides whether to move before rounding either operand. + // If one axis qualifies, the device rounds and emits both axes. + let minimum_move = if units == DisplayUnits::TeX && driver == PdfDriver::PdfTeX { + super::divide_scaled(scale, 10i64.pow(u32::from(precision)), 0).0 + } else { + 0 + }; + Self { position: [0, 0], scale, precision, minimum_move } + } + + pub(crate) fn position(&self) -> [i64; 2] { + self.position + } + + pub(crate) fn move_to(&mut self, point: [i64; 2]) -> Option<[i64; 2]> { + let (operands, advance) = self.translation(point)?; + self.position[0] += advance[0]; + self.position[1] += advance[1]; + Some(operands) + } + + pub(crate) fn temporary_translation(&self, point: [i64; 2]) -> Option<[i64; 2]> { + self.translation(point).map(|(operands, _)| operands) + } + + fn translation(&self, point: [i64; 2]) -> Option<([i64; 2], [i64; 2])> { + let delta = [point[0] - self.position[0], point[1] - self.position[1]]; + if delta == [0, 0] || delta.iter().all(|d| d.abs() < self.minimum_move) { return None; } - self.0[0] += h_sp; - self.0[1] += v_sp; - Some([h, v]) + let [(h, h_sp), (v, v_sp)] = + delta.map(|value| super::divide_scaled(value, self.scale, self.precision)); + (h != 0 || v != 0).then_some(([h, v], [h_sp, v_sp])) } } diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index 6e4c1e9..8b89aff 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -4,10 +4,10 @@ use crate::{ execution::FontId, native_font::{NativeFont, XdvFontMatrix}, pdf_device::{ - PdfGraphics, PdfLiteralMode, divide_scaled, print_decimal, print_sp, + PdfDriver, PdfGraphics, PdfLiteralMode, divide_scaled, print_decimal, print_sp, text_spaces::{ResolvedSpaceFont, SpaceOperation, SpacePlan, SpaceUse}, }, - render::{DisplayItem, DisplayList, DisplayUnits}, + render::{DisplayItem, DisplayList}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -58,7 +58,7 @@ impl NativeText { let first = text.is_none(); let state = text.get_or_insert_with(|| { if xdv_origin.is_none() { - out.move_origin([0, 0], DisplayUnits::TeX, digits); + out.move_origin([0, 0]); } let [h, v] = out.origin.position(); out.push_str("BT\n"); @@ -376,8 +376,9 @@ pub(crate) fn legacy_cid_positions(page: &DisplayList) -> BTreeMap = None; - let mut out = PageContent::measuring(); + let mut out = PageContent::measuring(page.units, digits, PdfDriver::PdfTeX); for (index, item) in page.items.iter().enumerate() { match item { DisplayItem::PdfTextSpace { @@ -590,7 +591,7 @@ pub(crate) fn plan_spaces( .. } => { NativeText::finish(&mut text, &mut out); - out.move_origin([*x, page.height - *y], page.units, digits); + out.move_origin([*x, page.height - *y]); } _ => NativeText::finish(&mut text, &mut out), } @@ -612,29 +613,23 @@ pub(super) fn rule( } let bottom = page_height - top - h; out.push_str("q\n"); - if h <= 65_782 { + if h <= ONE_BP { + out.move_origin_temporarily([x, bottom + (h + 1) / 2]); out.push_str(&format!( - "1 0 0 1 {} {} cm []0 d 0 J {} w 0 0 m {} 0 l S\n", - print_sp(x, digits), - print_sp(bottom + (h + 1) / 2, digits), - print_sp(h, digits), - print_sp(w, digits) + "[]0 d 0 J {} w 0 0 m {} 0 l S\n", + print_sp(h, digits), print_sp(w, digits), )); - } else if w <= 65_782 { + } else if w <= ONE_BP { + out.move_origin_temporarily([x + (w + 1) / 2, bottom]); out.push_str(&format!( - "1 0 0 1 {} {} cm []0 d 0 J {} w 0 0 m 0 {} l S\n", - print_sp(x + (w + 1) / 2, digits), - print_sp(bottom, digits), - print_sp(w, digits), - print_sp(h, digits) + "[]0 d 0 J {} w 0 0 m 0 {} l S\n", + print_sp(w, digits), print_sp(h, digits), )); } else { + out.move_origin_temporarily([x, bottom]); out.push_str(&format!( - "1 0 0 1 {} {} cm 0 0 {} {} re f\n", - print_sp(x, digits), - print_sp(bottom, digits), - print_sp(w, digits), - print_sp(h, digits) + "0 0 {} {} re f\n", + print_sp(w, digits), print_sp(h, digits), )); } out.push_str("Q\n"); diff --git a/crates/texrra-tex-core/src/source_map/pdf_projection.rs b/crates/texrra-tex-core/src/source_map/pdf_projection.rs index 57086e4..43737cd 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -45,18 +45,19 @@ impl PdfProjection { matrix: Affine::IDENTITY, modified_text_parameters: false, }; - let xdv_origin = page.pdf.as_ref() - .filter(|pdf| pdf.driver == PdfDriver::Xdv) - .map(|_| xdv_page_origin(page.units, page.height, page.magnification)); + let (driver, digits) = page.pdf.as_ref() + .map_or((PdfDriver::PdfTeX, 3), |pdf| (pdf.driver, pdf.file.decimal_digits)); + let xdv_origin = (driver == PdfDriver::Xdv) + .then(|| xdv_page_origin(page.units, page.height, page.magnification)); let mut projection = Self { - origin: DeviceOrigin::default(), + origin: DeviceOrigin::new(page.units, digits, driver), graphics: Some(graphics), stack: vec![graphics], // The page writer begins with q. units: page.units, xdv_origin, xdv_content_scopes: Vec::new(), height: page.height, - digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits), + digits, units_per_bp: 1.0 / page.units.bp(1), text_active: false, modified_text_position: false, @@ -72,7 +73,7 @@ impl PdfProjection { } fn move_origin(&mut self, point: [i64; 2]) { - if let Some(translation) = self.origin.move_to(point, self.units, self.digits) { + if let Some(translation) = self.origin.move_to(point) { let scale = self.units_per_bp / 10f64.powi(i32::from(self.digits)); let [x, y] = translation.map(|value| value as f64 * scale); self.concatenate(Affine::translation(x, y)); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 174423a..a86de69 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,31 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 PDF 图形原点的双轴移动阈值 + +pdfTeX 以输出精度对应的最小 sp 位移检查两轴。两轴均低于阈值时 +省略平移,任一轴达到阈值时对两轴一起舍入。当前点处的 PDF 字面 +指令与规则线共用计算,规则线在局部图形状态内移动。来源映射使用 +同一持久原点。XDV 保持自己的图形坐标规则。0 至 4 位小数对照覆盖 +正负位移及双轴舍入,另有规则线与字面指令交错的参考用例。3 份 XDV +候选 PDF 与各自原生基线字节一致,144 DPI 渲染与各自冻结参考一致。 +28 项定向检查通过。 +[pdfTeX 原点及临时移位](https://github.com/TeX-Live/texlive-source/blob/5aa90aa0e1c8e743b85ed8a94ea77531edadefd5/texk/web2c/pdftexdir/pdftex.web#L16012-L16039) + +同一原样 OUP 的首轮从空辅助文件开始,10 页、32,262 个字形及坐标、 +所有词框和 144 DPI 灰度图均与参考一致,aux 和 out 也逐字节一致。 +原生原始布局清单与此前首轮一致。三轮收敛证据保留于下节。 + +同一次首轮编译执行 171,226,512 步,共录得 25,773 个 CPU 样本。 +读取 token 的执行函数命中 3,232 次,命令绑定查找和底层哈希表查找 +分别命中 1,753 和 1,605 次。下一批优先减少命令名查找及 token +读取的开销,用同版原样作业对照执行与输出。编辑到页面可见的正式 +时延验收仍待完成。 + +证据在 target/p3-pdf-origin-threshold/,包括最小见证、定向检查、 +原样首轮页面与采样原始记录。SHA256SUMS 指纹为 +a42391b7deeac6be9fce141d4073370ec078d59452b514ab40d86ea0d5e72a9c。 + ## 2026-11-29 PDF 文字游标沿用舍入后的原点 图形指令回到页原点时,打印的平移可以抵消,内部仍会留下 sp 级余量。 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 875d9af..23ab25c 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -1395,6 +1395,11 @@ target/p3-oup-journals/。SHA256SUMS 指纹为 页的 761 个位置差异,以及同源三轮实际作业和结果指纹。 [文字游标与差异追踪](P2_M1_PROGRESS.md#2026-11-29-pdf-文字游标沿用舍入后的原点) +之后核对 PDF 图形原点的双轴移动阈值。用同一原样交付从空辅助 +文件执行首轮,10 页、32,262 个字形及坐标、所有词框与 144 DPI +灰度图逐项一致,aux 和 out 逐字节一致。上段保留三轮收敛证据。 +[双轴移动阈值及冷编译采样](P2_M1_PROGRESS.md#2026-11-29-pdf-图形原点的双轴移动阈值) + 单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、 双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源 与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量, diff --git a/tests/native_pages.rs b/tests/native_pages.rs index baa47ca..9b606dc 100644 --- a/tests/native_pages.rs +++ b/tests/native_pages.rs @@ -288,6 +288,55 @@ fn native_pdf_text_uses_the_rounded_origin_after_positioned_literals() { fs::remove_dir_all(work).unwrap(); } +#[test] +fn pdftex_origin_uses_the_two_axis_threshold_for_literals_and_rules() { + let work = directory(); + let source = work.join("origin.tex"); + fs::write( + &source, + r"\catcode123=1 \catcode125=2 \catcode35=6 \catcode37=14 +\pdfoutput=1 \pdfdecimaldigits=3 \pdfpagewidth=200pt \pdfpageheight=200pt +\pdfhorigin=0sp \pdfvorigin=0sp +\def\place#1#2#3{\hbox to0sp{\kern#1sp\lower#2sp\hbox{#3}\hss}} +\shipout\hbox{% + \place{33}{13107200}{\pdfliteral{1 1 m 40 1 l S}}% + \place{33}{13107528}{\vrule width20pt height655sp depth0sp}% + \place{66}{13107167}{\pdfliteral{1 2 m 40 2 l S}}% + \place{0}{13107200}{\pdfliteral{1 3 m 40 3 l S}}} +\end", + ) + .unwrap(); + let result = native_fonts::command() + .args(["native", "--job", "--initex", "--etex"]) + .arg(&source) + .arg("origin.pdf") + .current_dir(&work) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + let pdf = lopdf::Document::load(work.join("origin.pdf")).unwrap(); + let contents = pdf.get_page_content(pdf.get_pages()[&1]).unwrap(); + let stream = lopdf::content::Content::decode(&contents).unwrap(); + let ordered: Vec<_> = stream.operations.iter() + .filter(|op| matches!(op.operator.as_str(), "cm" | "S")) + .collect(); + let operators: Vec<_> = ordered.iter().map(|op| op.operator.as_str()).collect(); + assert_eq!(operators, ["S", "S", "cm", "S", "cm", "S"]); + assert!(matches!( + &ordered[2].operands[4..], + [lopdf::Object::Real(0.001), lopdf::Object::Real(0.001)] + )); + assert!(matches!( + &ordered[4].operands[4..], + [lopdf::Object::Real(-0.001), lopdf::Object::Real(-0.001)] + )); + fs::remove_dir_all(work).unwrap(); +} + #[test] fn shipped_pdf_spaces_take_a_real_font_slot_in_output_order() { let work = directory();