diff --git a/crates/texrra-tex-core/src/execution/boxes/native_words.rs b/crates/texrra-tex-core/src/execution/boxes/native_words.rs index af9447d..17a3534 100644 --- a/crates/texrra-tex-core/src/execution/boxes/native_words.rs +++ b/crates/texrra-tex-core/src/execution/boxes/native_words.rs @@ -63,7 +63,8 @@ pub(super) fn rejoin( text.push_str(&run.text); } } - let word = first.font.shape_mapped(text, sources, glyph_metrics)?; + let mut word = first.font.shape_mapped(text, sources, glyph_metrics)?; + word.actual_text = first.actual_text; if let Some((steps, limit)) = &mut shaping_budget { **steps = steps .checked_add(word.glyphs.len()) diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 3dd2537..c769c59 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -174,7 +174,9 @@ impl NativeShipout { let y = self.device.vertical_origin + self.box_node.height + p.y; if let MathItem::OpenType(run) = p.item { run.paint(x, y, |value| value, |item, source| { - page.sources.insert(page.items.len(), source); + if !matches!(item, DisplayItem::OpenTypeActualText(_)) { + page.sources.insert(page.items.len(), source); + } page.items.push(item); }); return; diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index 3e3b41a..027fcfe 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -389,6 +389,7 @@ impl Executor { if let Some(font) = opentype { if self.state.input_profile() == InputProfile::XeTeX { self.reads.insert(Dependency::Parameter(Parameter::XeTeXuseglyphmetrics)); + self.reads.insert(Dependency::Parameter(Parameter::XeTeXgenerateactualtext)); if !self.restricted() { self.reads.insert(Dependency::Parameter(Parameter::XeTeXdashbreakstate)); } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index c722f56..23c574c 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 71; -const COMPATIBLE_SCHEMAS: [u32; 38] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, SCHEMA, +const SCHEMA: u32 = 72; +const COMPATIBLE_SCHEMAS: [u32; 39] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index ed1174d..9574512 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -273,12 +273,10 @@ impl Builder { fn finish_opentype(&mut self, run: PendingOpenType, state: &State) -> Result<(), String> { let xetex = state.input_profile() == InputProfile::XeTeX; - let use_glyph_metrics = - xetex && state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0; let original_end = run.text.chars().next_back(); let (text, sources) = run.font.map_text(run.text, run.sources)?; if self.restricted || !xetex { - return self.push_opentype(&run.font, text, sources, use_glyph_metrics); + return self.push_opentype(&run.font, text, sources, state); } let dash_breaks = state.parameter(Parameter::XeTeXdashbreakstate).width() > 0; @@ -295,7 +293,7 @@ impl Builder { }); let mut ends = ends.peekable(); if ends.peek().is_none() { - self.push_opentype(&run.font, text, sources, use_glyph_metrics)?; + self.push_opentype(&run.font, text, sources, state)?; } else { let mut sources = sources.into_iter().peekable(); let mut start = 0; @@ -308,7 +306,7 @@ impl Builder { &run.font, text[start..end].to_owned(), fragment_sources, - use_glyph_metrics, + state, )?; if end != text.len() { self.push_explicit_hyphen_break(run.font.id); @@ -325,14 +323,52 @@ impl Builder { fn push_opentype( &mut self, font: &Arc, - text: String, - sources: Vec<(usize, PaintSource)>, - use_glyph_metrics: bool, + mut text: String, + mut sources: Vec<(usize, PaintSource)>, + state: &State, ) -> Result<(), String> { - let shaped = font.shape_mapped(text, sources, use_glyph_metrics)?; + let xetex = state.input_profile() == InputProfile::XeTeX; + let use_glyph_metrics = + xetex && state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0; + // A fresh word takes the current subtype, including when the scanner + // replaces the preceding word. Packing preserves the first subtype. + let previous = match self.nodes.as_slice() { + [.., preceding, TextNode::OpenType(run)] + if xetex && run.font.id == font.id + && !matches!(preceding, TextNode::Glyph { ligature: false, .. } + | TextNode::Discretionary { .. }) => + { + Some(run) + } + _ => None, + }.filter(|_| { + !self.nodes.iter().rev().skip(1).take(usize::from(u8::MAX)) + .enumerate().any(|(offset, node)| { + matches!(node, TextNode::Discretionary { replacement_count, .. } + if usize::from(*replacement_count) > offset) + }) + }); + if let Some(previous) = previous { + let offset = previous.text.len(); + let mut joined = previous.text.clone(); + joined.push_str(&text); + if joined.encode_utf16().count() > usize::from(u16::MAX) { + return Err("native OpenType word capacity exceeded".into()); + } + text = joined; + let mut joined_sources = previous.sources.clone(); + joined_sources.extend(sources.into_iter().map(|(at, source)| (at + offset, source))); + sources = joined_sources; + } + let replaced = previous.is_some(); + let mut shaped = font.shape_mapped(text, sources, use_glyph_metrics)?; + shaped.actual_text = xetex && state.parameter(Parameter::XeTeXgenerateactualtext).width() > 0; self.font_steps = self.font_steps.checked_add(shaped.glyphs.len()) .filter(|steps| *steps <= self.font_step_limit) .ok_or("native OpenType shaping step limit exceeded")?; + if replaced { + self.nodes.pop(); + } self.nodes.push(TextNode::OpenType(Arc::new(shaped))); Ok(()) } diff --git a/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs b/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs index 677c28d..fe457b1 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/native_hyphenation.rs @@ -12,6 +12,7 @@ pub(super) fn add_hyphens( let max_length = super::super::hyphenation::max_word_length(state); let uppercase = state.parameter(Parameter::Uchyph).width() > 0; let use_glyph_metrics = state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0; + let mapped_hyphen_actual_text = state.parameter(Parameter::XeTeXgenerateactualtext).width() > 0; let mut after_glue = false; let mut auto_breaking = true; let mut edits = Vec::new(); @@ -123,6 +124,7 @@ pub(super) fn add_hyphens( run.text[from..to].to_owned(), fragment_sources, use_glyph_metrics, + run.actual_text, steps, step_limit, )?); @@ -145,6 +147,7 @@ pub(super) fn add_hyphens( text, sources, use_glyph_metrics, + run.font.has_mapping() && mapped_hyphen_actual_text, steps, step_limit, )?], @@ -210,10 +213,12 @@ fn shape( text: String, sources: Vec<(usize, PaintSource)>, use_glyph_metrics: bool, + actual_text: bool, steps: &mut usize, step_limit: usize, ) -> Result { - let run = run.font.shape_mapped(text, sources, use_glyph_metrics)?; + let mut run = run.font.shape_mapped(text, sources, use_glyph_metrics)?; + run.actual_text = actual_text; *steps = steps .checked_add(run.glyphs.len()) .filter(|steps| *steps <= step_limit) diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 1b14e87..e2b8caa 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -126,6 +126,7 @@ pub enum Parameter { XeTeXinterchartokenstate, XeTeXprotrudechars, XeTeXhyphenatablelength, + XeTeXgenerateactualtext, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParameterValue { @@ -158,13 +159,14 @@ impl Parameter { ) } - pub(super) const XETEX: [Self; 6] = [ + pub(super) const XETEX: [Self; 7] = [ Self::XeTeXuseglyphmetrics, Self::XeTeXdashbreakstate, Self::Suppressfontnotfounderror, Self::XeTeXinterchartokenstate, Self::XeTeXprotrudechars, Self::XeTeXhyphenatablelength, + Self::XeTeXgenerateactualtext, ]; pub const ALL: &'static [Self] = &[ @@ -289,6 +291,7 @@ impl Parameter { Self::XeTeXinterchartokenstate, Self::XeTeXprotrudechars, Self::XeTeXhyphenatablelength, + Self::XeTeXgenerateactualtext, ]; pub fn name(self) -> String { match self { @@ -298,6 +301,7 @@ impl Parameter { Self::XeTeXinterchartokenstate => "XeTeXinterchartokenstate".into(), Self::XeTeXprotrudechars => "XeTeXprotrudechars".into(), Self::XeTeXhyphenatablelength => "XeTeXhyphenatablelength".into(), + Self::XeTeXgenerateactualtext => "XeTeXgenerateactualtext".into(), _ => format!("{self:?}").to_ascii_lowercase(), } } diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 14fde9d..d3e6db1 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -337,6 +337,10 @@ impl OpenTypeFont { } } + pub(crate) fn has_mapping(&self) -> bool { + self.mapping.is_some() + } + pub(crate) fn shape_mapped( self: &Arc, text: String, @@ -423,6 +427,7 @@ impl OpenTypeFont { width: x_origin, sources, glyph_extents, + actual_text: false, }) } } @@ -533,6 +538,8 @@ pub struct OpenTypeRun { pub sources: Vec<(usize, PaintSource)>, #[serde(default, skip_serializing_if = "Option::is_none")] glyph_extents: Option<[i64; 2]>, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) actual_text: bool, } impl OpenTypeRun { @@ -592,6 +599,13 @@ impl OpenTypeRun { scale: impl Fn(i64) -> i64, mut emit: impl FnMut(crate::render::DisplayItem, PaintSource), ) { + let marked = self.actual_text && (!self.text.is_empty() || !self.glyphs.is_empty()); + if marked { + emit( + crate::render::DisplayItem::OpenTypeActualText(Some(self.text.clone())), + PaintSource::default(), + ); + } for glyph in &self.glyphs { let first = self .sources @@ -620,6 +634,12 @@ impl OpenTypeRun { source.derived(crate::provenance::Derivation::FontProgram), ); } + if marked { + emit( + crate::render::DisplayItem::OpenTypeActualText(None), + PaintSource::default(), + ); + } } } diff --git a/crates/texrra-tex-core/src/opentype/math_layout.rs b/crates/texrra-tex-core/src/opentype/math_layout.rs index 2dee951..0463021 100644 --- a/crates/texrra-tex-core/src/opentype/math_layout.rs +++ b/crates/texrra-tex-core/src/opentype/math_layout.rs @@ -238,6 +238,7 @@ pub(crate) fn painted_glyph( width: advance, sources: vec![(0, source.clone())], glyph_extents: Some([height, depth]), + actual_text: false, }; ( MathGeometry { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index fe9846e..0efb050 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -851,6 +851,10 @@ fn page_content( let px = |x| pt(x - h); let py = |y| pt(height - y - v); match item { + DisplayItem::OpenTypeActualText(text) => match text { + Some(text) => opentype_fonts::begin_actual_text(&mut content, text, true), + None => content.push_str("EMC\n"), + }, DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => { opentype[&font.id].paint( &mut opentype_text, &mut content, font.id, *glyph, text, diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 76fde6e..2eb1cac 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -263,6 +263,16 @@ fn utf16_hex(value: &str) -> String { .collect() } +pub(super) fn begin_actual_text(output: &mut PageContent, text: &str, xdv: bool) { + // XDV uses PDFDocEncoding where it can use Unicode's low byte directly. + let encoded = if xdv && text.chars().all(|c| matches!(c as u32, 0..=0x7F | 0xA1..=0xFF)) { + text.chars().map(|c| format!("{:02X}", c as u8)).collect() + } else { + format!("FEFF{}", utf16_hex(text)) + }; + output.push_str(&format!("/Span << /ActualText <{encoded}> >> BDC\n")); +} + impl EmbeddedFont { pub(super) fn paint( &self, @@ -291,10 +301,7 @@ impl EmbeddedFont { TextRun::finish(run, output); } if override_text { - output.push_str(&format!( - "/Span << /ActualText >> BDC\n", - utf16_hex(text) - )); + begin_actual_text(output, text, false); } let state = run.get_or_insert_with(|| { let coordinates = [x, y].map(|value| { diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index fa28f91..db5d90f 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -60,6 +60,8 @@ pub enum DisplayItem { glyph: u16, text: String, }, + /// Word-level PDF replacement text. None closes the current word. + OpenTypeActualText(Option), /// A native math glyph. `face` preserves the optical master independently /// of the painted size; `slot` preserves CMEX next-larger selection. MathGlyph { @@ -344,7 +346,8 @@ impl DisplayList { fn svg_paint_items(&self) -> impl Iterator { self.items .iter() - .filter(|item| !matches!(item, DisplayItem::PdfImageObject(_))) + .filter(|item| !matches!(item, + DisplayItem::PdfImageObject(_) | DisplayItem::OpenTypeActualText(_))) } /// Compare the inputs consumed by SVG rendering. Font data for glyphs not @@ -431,7 +434,8 @@ impl DisplayList { *y += dy; } DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor(_) => {} - DisplayItem::Special(_) | DisplayItem::PdfImageObject(_) => {} + DisplayItem::Special(_) | DisplayItem::PdfImageObject(_) + | DisplayItem::OpenTypeActualText(_) => {} } } } @@ -715,7 +719,8 @@ impl DisplayList { *thickness as f64 / 65_536.0 )); } - DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} + DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } + | DisplayItem::OpenTypeActualText(_) => {} DisplayItem::Special(content) => { out.push_str(&format!( " diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index d1d59ee..31468b7 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,29 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX 词级 PDF ActualText + +`\XeTeXgenerateactualtext` 随真实整数赋值和分组生效。新建原生词 +记录当时的开关值。扫描期重新建词、装箱重接、断词分段和复制盒 +按对应规则保留标记,带标记的词在 PDF 中包住实际字形序列。内容 +使用字体映射后的词文本,按原版 PDFDocEncoding 范围选择单字节 +或 UTF-16BE。词级标记不参与可见 SVG 的绘制比对。 +[XeTeX 词节点类型](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L16595-L16615) +[xdvipdfmx 的 ActualText 编码](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdev.c#L1714-L1755) + +四组同源共 21 页,词级标记、字符编码、标记内字形个数和按版面 +抽取的文本全部与 XeTeX 一致。覆盖印地语、从右到左的阿拉伯语、 +连字、字体映射、补充平面、正负整数、嵌套分组、解箱和断词。 +schema72 重载后保留开关与别名,实际作业的已建盒保留原标记。 +12 项既有 XeTeX 定向测试通过。 + +三次跨文件修订各复用 66 步、重放 2 次调用,PDF、SVG 和来源 +映射与同版本独立全量一致。只改变标记时无需重发可见页,正文 +编辑与恢复各只刷新第二页。原样 ACL 继续加载同一个 schema71 +格式,观察真实初始辅助文件,默认 PDF 与上一版逐字节相同。 +回执 `target/p3-xetex-actual-text/receipt.json` 的 SHA-256 为 +`b0f852cdbf63efa9a02ba909accffe10a61d8041f02600ef675cc26436f31dcf`。 + ### XeTeX OpenType PDF Unicode 映射 XeTeX 的原生 PDF 导出使用实际字形编号,从原字体的 Unicode cmap、 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 24e3456..1f60207 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -758,6 +758,15 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX `target/p3-xdv-annotation/receipt.json`。 [链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形) +#### XeTeX 词级 PDF 标记复编 + +原样 ACL 继续加载同一 schema71 格式,以真实已收敛的生成文件 +为初态。最终 PDF 和 aux、out、bbl 与上一版逐字节相同。默认 PDF +没有 ActualText 标记,与冻结参考一致。上轮剩余的词框顺序和 +光栅差异仍计入整页门禁。 +回执 `target/p3-xetex-actual-text/receipt.json`。 +[词级标记阶段记录](P2_M1_PROGRESS.md#xetex-词级-pdf-actualtext) + #### OpenType PDF Unicode 映射复编 同一 schema71、十份原样项目文件和实际 BibTeX 产物,三轮原生 diff --git a/src/native_job.rs b/src/native_job.rs index 684d7f3..4902f3b 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -816,7 +816,8 @@ impl Files { "id":image.id, "page":image.image.page, "resource":image.image.version, })); } - DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor(_) | DisplayItem::PdfTextSpace { .. } => {} + DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor(_) | DisplayItem::PdfTextSpace { .. } + | DisplayItem::OpenTypeActualText(_) => {} DisplayItem::PdfGraphics { x, y, operation } => { paint_order.push(json!(["pdf_graphics", graphics.len()])); graphics.push(json!({"x": x, "y": y, "operation": operation}));