diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index 17678ad..1665282 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -690,7 +690,8 @@ impl Printer<'_> { PdfLiteralMode::Origin => {} PdfLiteralMode::Page => self.literal(" page"), PdfLiteralMode::Direct => self.literal(" direct"), - PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {} + PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect + | PdfLiteralMode::XdvContent => {} } self.tokens(tokens)?; } diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index d0c94da..f5353a3 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -155,7 +155,14 @@ impl Executor { { return Ok(Some(graphics)); } - let body = data.strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start); + let body = data.strip_prefix(b"pdf:").map(xdv_skip_white); + if let Some(content) = body.and_then(|body| xdv_operand(body, b"content")) { + let bytes = xdv_skip_white(content); + return Ok((!bytes.is_empty()).then(|| PdfGraphics::Literal { + mode: PdfLiteralMode::XdvContent, + bytes: Arc::from(bytes), + })); + } if let Some(dictionary) = body.and_then(|body| xdv_operand(body, b"docinfo")) { use crate::pdf_device::xdv_document::merge_docinfo; let (entries, warnings) = merge_docinfo(&self.state.pdf_info, dictionary) diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index cf2f2a8..9c24708 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -743,9 +743,12 @@ fn page_content( pt(n) } }; - use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode}; + use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode, xdv_page_origin}; 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 page_origin = if xdv { text_origin } else { [0, 0] }; let mut content = PageContent::default(); content.push_str("q\n0 0 0 rg\n"); if list.magnification != 1000 { @@ -774,12 +777,11 @@ fn page_content( pt(-origin.v_offset) )); } + content.move_origin(page_origin, list.units, digits); let mut native_text: Option = None; let mut tex_text: Option = None; let mut opentype_text = opentype_fonts::TextState::default(); let bp_per_unit = list.units.bp(1); - let one_inch = (72_000. / (bp_per_unit * f64::from(list.magnification))).round() as i64; - let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv); for (index, item) in list.items.iter().enumerate() { if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) { opentype_text.finish(&mut content); @@ -795,7 +797,7 @@ fn page_content( && *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit { if tex_text.is_none() { - content.move_origin([0, 0], list.units, digits); + content.move_origin(page_origin, list.units, digits); } native_text::NativeText::explicit_space( &mut tex_text, &mut content, *x, *y, height, digits, dedicated, @@ -816,8 +818,8 @@ fn page_content( }; if let Some((x, y, mode, bytes)) = literal { NativeTextRun::flush(&mut native_text, &mut content); - let previous_origin = content.origin.position(); - let special_origin = mode.xdv_origin([x, height - y], height, list.magnification); + let previous_origin = content.origin; + let special_origin = mode.xdv_origin([x, height - y], page_origin); match mode { PdfLiteralMode::Direct => { native_text::NativeText::break_string(&mut tex_text, &mut content); @@ -828,8 +830,11 @@ fn page_content( content.move_origin([x, height - y], list.units, digits); } } - PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => { + PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect | PdfLiteralMode::XdvContent => { native_text::NativeText::finish(&mut tex_text, &mut content); + if mode == PdfLiteralMode::XdvContent { + content.push_str("q\n"); + } if let Some(point) = special_origin { content.move_origin(point, list.units, digits); } @@ -837,8 +842,11 @@ fn page_content( } content.bytes.extend_from_slice(bytes); content.push(b'\n'); - if special_origin.is_some() { - content.move_origin(previous_origin, list.units, digits); + if mode == PdfLiteralMode::XdvContent { + content.push_str("Q\n"); + content.origin = previous_origin; + } else if special_origin.is_some() { + content.move_origin(previous_origin.position(), list.units, digits); } continue; } @@ -854,7 +862,7 @@ fn page_content( { assert!(paint.is_some(), "native glyph program must be resolved"); if tex_text.is_none() { - content.move_origin([0, 0], list.units, digits); + content.move_origin(page_origin, list.units, digits); } native_text::NativeText::glyph( &mut tex_text, @@ -865,7 +873,7 @@ fn page_content( paint.as_ref().unwrap(), *slot, height, - xdv.then_some(one_inch), + xdv.then_some(text_origin[0]), digits, list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(), list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()), @@ -881,7 +889,7 @@ fn page_content( } = item { let [h, v] = content.origin.position(); - if list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv) { + if xdv { native_text::xdv_rule( &mut content, *x - h, height - *y - v - *rule_height, *width, *rule_height, digits, ); @@ -923,7 +931,7 @@ fn page_content( opentype[&font.id].paint( &mut opentype_text, &mut content, font, *glyph, text, *size, *x - h, height - *y - v, bp_per_unit, - [one_inch - h, height - one_inch - v], xdv, !font_opacities.is_empty(), + [text_origin[0] - h, text_origin[1] - v], xdv, !font_opacities.is_empty(), ); } DisplayItem::NativeGlyph { @@ -1204,12 +1212,11 @@ fn page_content( // The text runs above are closed without changing the graphics transform. DisplayItem::PdfGraphics { operation: PdfGraphics::TextBoundary, .. } => {} DisplayItem::PdfGraphics { x, y, operation } => { - let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv); let device_origin = list.units == DisplayUnits::TeX && !xdv; if device_origin { content.move_origin([*x, height - *y], list.units, digits); } else if xdv { - content.move_origin([0, 0], list.units, digits); + content.move_origin(page_origin, list.units, digits); } match operation { PdfGraphics::Save => content.push_str("q\n"), @@ -1228,7 +1235,8 @@ fn page_content( let coordinates = if device_origin { [0.0, 0.0] } else if xdv { - [list.units.bp(*x), list.units.bp(height - *y)] + let [h, v] = content.origin.position(); + [list.units.bp(*x - h), list.units.bp(height - *y - v)] } else { [*x, height - *y].map(|coordinate| { pt(coordinate).parse::().expect("formatted PDF dimension") diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index 2fa1883..fa60dca 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -131,7 +131,7 @@ pub mod forms; mod graphics; pub(crate) use color::{ColorResult, PdfColorStacks, ShippedColor}; pub use color::{PdfColorProgram, PdfColorStackAction}; -pub(crate) use graphics::{Affine, DeviceOrigin}; +pub(crate) use graphics::{Affine, DeviceOrigin, xdv_page_origin}; pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix}; pub mod catalog; pub mod text_spaces; diff --git a/crates/texrra-tex-core/src/pdf_device/graphics.rs b/crates/texrra-tex-core/src/pdf_device/graphics.rs index 804c49e..6dbc426 100644 --- a/crates/texrra-tex-core/src/pdf_device/graphics.rs +++ b/crates/texrra-tex-core/src/pdf_device/graphics.rs @@ -10,26 +10,30 @@ pub enum PdfLiteralMode { Direct, XdvOrigin, XdvDirect, + /// XDV page content relative to the special, inside a local graphics state. + XdvContent, } impl PdfLiteralMode { pub(crate) fn xdv_origin( self, point: [i64; 2], - page_height: i64, - magnification: i32, + page_origin: [i64; 2], ) -> Option<[i64; 2]> { match self { - Self::XdvOrigin => Some(point), - Self::XdvDirect => { - let inch = super::unmagnify(4_736_286, magnification); - Some([inch, page_height - inch]) - } + Self::XdvOrigin | Self::XdvContent => Some(point), + Self::XdvDirect => Some(page_origin), _ => None, } } } +/// The XDV device writes content relative to the one-inch page origin. +pub(crate) fn xdv_page_origin(units: DisplayUnits, height: i64, magnification: i32) -> [i64; 2] { + let inch = (72_000. / (units.bp(1) * f64::from(magnification))).round() as i64; + [inch, height - inch] +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum PdfGraphics { Save, @@ -83,7 +87,7 @@ 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(Default)] +#[derive(Clone, Copy, Default)] pub(crate) struct DeviceOrigin([i64; 2]); impl DeviceOrigin { diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index 466057f..aadf78d 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -41,10 +41,11 @@ impl NativeText { let state = text.get_or_insert_with(|| { out.push_str("BT\n"); if let Some(origin) = xdv_origin { + let [h, v] = out.origin.position(); out.push_str(&format!( "1 0 0 1 {} {} Tm\n", - print_sp(origin, digits), - print_sp(height - origin, digits), + print_sp(origin - h, digits), + print_sp(height - origin - v, digits), )); } Self { 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 99ffdd0..1648335 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -1,7 +1,8 @@ //! Project TeX paint through the PDF device and any literal graphics state. use crate::{ pdf_device::{ - Affine, DeviceOrigin, PdfDriver, PdfGraphics, PdfLiteralMode, page_resources::check_pdf_nesting, + Affine, DeviceOrigin, PdfDriver, PdfGraphics, PdfLiteralMode, + page_resources::check_pdf_nesting, xdv_page_origin, }, render::{DisplayItem, DisplayList, DisplayUnits}, }; @@ -18,9 +19,8 @@ pub(super) struct PdfProjection { graphics: Option, stack: Vec, units: DisplayUnits, - xdv: bool, + xdv_origin: Option<[i64; 2]>, height: i64, - magnification: i32, digits: u8, units_per_bp: f64, text_active: bool, @@ -44,19 +44,23 @@ impl PdfProjection { matrix: Affine::IDENTITY, modified_text_parameters: false, }; - Some(Self { + let xdv_origin = page.pdf.as_ref() + .filter(|pdf| pdf.driver == PdfDriver::Xdv) + .map(|_| xdv_page_origin(page.units, page.height, page.magnification)); + let mut projection = Self { origin: DeviceOrigin::default(), graphics: Some(graphics), stack: vec![graphics], // The page writer begins with q. units: page.units, - xdv: page.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv), + xdv_origin, height: page.height, - magnification: page.magnification, digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits), units_per_bp: 1.0 / page.units.bp(1), text_active: false, modified_text_position: false, - }) + }; + projection.move_origin(xdv_origin.unwrap_or([0, 0])); + Some(projection) } fn concatenate(&mut self, matrix: Affine) { @@ -136,8 +140,11 @@ impl PdfProjection { if *mode != PdfLiteralMode::Direct { self.text_active = false; } - let previous_origin = self.origin.position(); - let special_origin = mode.xdv_origin([x, y], self.height, self.magnification); + let previous_origin = self.origin; + if *mode == PdfLiteralMode::XdvContent { + self.save(); + } + let special_origin = mode.xdv_origin([x, y], self.xdv_origin.unwrap_or([0, 0])); if *mode == PdfLiteralMode::Origin { self.move_origin([x, y]); } else if let Some(point) = special_origin { @@ -147,8 +154,11 @@ impl PdfProjection { self.graphics = None; self.stack.clear(); } - if special_origin.is_some() { - self.move_origin(previous_origin); + if *mode == PdfLiteralMode::XdvContent { + self.restore(); + self.origin = previous_origin; + } else if special_origin.is_some() { + self.move_origin(previous_origin.position()); } return None; } @@ -156,11 +166,11 @@ impl PdfProjection { if matches!(operation, PdfGraphics::TextBoundary) { return None; } - let native = self.units == DisplayUnits::TeX && !self.xdv; + let native = self.units == DisplayUnits::TeX && self.xdv_origin.is_none(); if native { self.move_origin([x, y]); - } else if self.xdv { - self.move_origin([0, 0]); + } else if let Some(origin) = self.xdv_origin { + self.move_origin(origin); } match operation { PdfGraphics::Save => self.save(), @@ -174,7 +184,12 @@ impl PdfProjection { if matches!(operation, PdfGraphics::SaveMatrix(_)) { self.save(); } - let [x, y] = if native { [0, 0] } else { [x, y] }; + let [x, y] = if native { + [0, 0] + } else { + let [h, v] = self.origin.position(); + [x - h, y - v] + }; self.concatenate(matrix.about(x as f64, y as f64, false)); } PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => { @@ -187,7 +202,7 @@ impl PdfProjection { if *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit && self.units == DisplayUnits::TeX && !self.text_active { - self.move_origin([0, 0]); + self.move_origin(self.xdv_origin.unwrap_or([0, 0])); self.text_active = true; self.modified_text_position = false; } @@ -195,7 +210,7 @@ impl PdfProjection { } DisplayItem::NativeGlyph { .. } if self.units == DisplayUnits::TeX => { if !self.text_active { - self.move_origin([0, 0]); + self.move_origin(self.xdv_origin.unwrap_or([0, 0])); self.text_active = true; self.modified_text_position = false; } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3f19962..07af8df 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,35 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### XeTeX 局部 PDF 内容和标记文本 + +pdf:content 在实际出页位置保存图形状态、平移并写出原始字节, +再恢复绘制状态。空载荷仍结束当前文本对象。不同载荷中的 +BDC 和 EMC 可以跨图形状态包围实际字形。XDV 的 PDF 页面从 +驱动的一英寸原点写出局部文字、规则及矩阵坐标。来源投影使用 +同一原点,并在局部 PDF 内容结束时恢复外层图形状态。 +[参考 PDF 内容指令](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/spc_pdfm.c#L1520-L1549) +[参考页原点](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/dvi.c#L1860-L1881) + +两个原版直测的 144 DPI 灰度图和抽取文本逐字节一致,覆盖 +局部颜色、XDV 缩放、图形保存恢复和跨载荷的 ActualText。 +初版绝对坐标的像素相同,提取文本为空。最终直接样例提取 +Accessible。三份既有字体切换探针的灰度光栅仍逐像素一致。 +六项 XeTeX 定向管线回归通过。四页项目改变局部颜色、移动 +标记文本并从出页错误恢复,三次成功修订都只更新第 2 页, +后两次各复用 66 步。PDF、测量页面、SVG、来源映射和 aux +与独立全量一致。失败时保持已发布预览和 aux。 + +原样 xeCJK-example-CJKfntef.tex 在接入局部内容的首轮候选 +上已越过首次出页的 pdf:content,保留了两页的出页状态。源第 +56 行 CJKsout 触发 latex.ltx:20514:5 的原生盒节点容量错误。 +此次未生成 PDF,冻结参考为六页。失败时执行保留 1,768,696 +条材料记录,活动材料为 209,508 条。下一步按实际事件归因 +保留材料成本,并对照该段落的拆行与 shrink,保留默认容量下的 +原始失败。初版和最终直接对照、原样失败日志及编辑序列在 +target/p3-xdv-scoped-content,receipt.json 为 +3134e70c59d37c5cf9f6203a663aaf24faf6c02160f520bd051a1e527aaf574a。 + ### 宏定义扫描读取参数标记的命令含义 宏参数模板与正文按读取时的命令含义识别参数标记。控制序列 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 473d2f5..4ffcba9 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -822,6 +822,71 @@ fn xetex_opentype_font_switch_uses_the_current_text_line_origin() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn xetex_content_special_scopes_graphics_and_emits_marked_content() { + use lopdf::{Document, content::Content}; + use texrra_tex_core::{ + execution::InputProfile, + pdf_device::{PdfGraphics, PdfLiteralMode}, + render::DisplayItem, + source_map::PaintKind, + }; + + let root = directory("xetex-content"); + let mut job = request(&root); + job.input_profile = InputProfile::XeTeX; + fs::write( + root.join("main.tex"), + br"\catcode123=1 \catcode125=2 +\font\face=cmr10 +\shipout\hbox{\kern10pt% +\special{pdf:content 2 0 0 2 3 4 cm 5 Tw 1 0 0 rg 0 0 8 8 re f}% +\special{pdf:content /Span << /ActualText (Accessible) >> BDC}% +\face X\special{pdf:content EMC}\kern3pt\vrule width5pt height2pt depth0pt} +\end", + ) + .unwrap(); + + let result = NativeCompiler::default().compile(job).unwrap(); + let page = &result.pages[0]; + let payloads = page + .items + .iter() + .filter_map(|item| match item { + DisplayItem::PdfGraphics { + operation: PdfGraphics::Literal { mode, bytes }, + .. + } => Some((*mode, bytes.as_ref())), + _ => None, + }) + .collect::>(); + assert_eq!(payloads.len(), 3); + assert!(payloads.iter().all(|(mode, _)| *mode == PdfLiteralMode::XdvContent)); + assert_eq!(payloads[2].1, b"EMC"); + assert!(page.has_embedded_pdf()); + assert!(result.preview_since(None).unwrap().pages[0].svg.contains(">(); + assert!(ops.starts_with(&["q", "rg", "cm"])); + assert!(matches!( + content.operations[2].operands[4], + lopdf::Object::Real(value) if value == 72. + )); + assert!(ops.windows(8).any(|ops| ops == ["q", "cm", "cm", "Tw", "rg", "re", "f", "Q"])); + assert!(ops.windows(5).any(|ops| ops == ["q", "cm", "BDC", "Q", "BT"])); + assert!(ops.windows(5).any(|ops| ops == ["ET", "q", "cm", "EMC", "Q"])); + let sources = &result.source_map.pages[0]; + assert!(sources.entries.iter().any(|entry| matches!(entry.kind, PaintKind::Glyph { slot: b'X', .. }))); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn xetex_unclaimed_special_warns_at_shipout_and_retains_the_whatsit() { use texrra_tex_core::execution::{Event, InputProfile};