Recover XeTeX PDF Unicode from actual OpenType glyph mappings

This commit is contained in:
gloamxun committed 2026-11-25 23:16:13 +08:00
1 parent c52ad71bad
commit 97319d751b
8 files changed
+375 -13

No files matched your search

@@ -1642,6 +1642,8 @@ impl State {
glyph_unicode: &self.glyph_unicode,
fonts: &self.fonts,
page_tree_attributes: &self.pdf_pages_attributes,
xdv_glyph_names: None,
xdv_font_unicode: self.input_profile == super::InputProfile::XeTeX,
xdv_keep_destinations: self.xdv_setup.keep_destinations,
xdv_outline_open_depth: self.xdv_setup.outline_open_depth.unwrap_or_default(),
xdv_navigation: self.xdv_navigation.as_deref(),
+7 -1
View File
@@ -27,6 +27,8 @@ pub(crate) mod objects;
mod pk_fonts;
#[path = "pdf_opentype.rs"]
mod opentype_fonts;
#[path = "pdf_opentype_unicode.rs"]
pub(crate) mod opentype_unicode;
const FACE_COUNT: usize = 17;
@@ -2093,7 +2095,11 @@ fn write_pdf(
}
}
}
let opentype = opentype_used.write(&mut objects, final_compression.unwrap_or(0).clamp(0, 9) as u8)?;
let opentype = opentype_used.write(
&mut objects,
final_compression.unwrap_or(0).clamp(0, 9) as u8,
unicode,
)?;
for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) {
for id in &plan.in_font {
native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' ');
+29 -10
View File
@@ -1,5 +1,5 @@
//! Embedding for glyphs selected by the native OpenType shaper.
use super::{PageContent, native_pdf_name, objects, to_unicode_map};
use super::{PageContent, native_pdf_name, objects, opentype_unicode, to_unicode_map};
use crate::{execution::FontId, opentype::OpenTypeFont};
use read_fonts::{
FontData, FontRead,
@@ -19,7 +19,7 @@ pub(super) struct EmbeddedFont {
struct EmbeddedGlyph {
cid: u16,
advance: u16,
text: String,
cluster_text: Option<String>,
}
pub(super) struct TextRun {
@@ -65,11 +65,12 @@ impl<'a> UsedFonts<'a> {
self,
objects: &mut Vec<Vec<u8>>,
compression: u8,
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
) -> Result<BTreeMap<FontId, EmbeddedFont>, String> {
self.0
.into_iter()
.map(|(id, (font, glyphs))| {
write_font(objects, font, glyphs, compression).map(|face| (id, face))
write_font(objects, font, glyphs, compression, options).map(|face| (id, face))
})
.collect()
}
@@ -80,8 +81,13 @@ fn write_font(
font: &OpenTypeFont,
glyphs: BTreeMap<u16, &str>,
compression: u8,
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
) -> Result<EmbeddedFont, String> {
let face = font.face()?;
let xdv = options.filter(|options| options.xdv_font_unicode);
let font_unicode = xdv.map(|options| {
opentype_unicode::map_glyphs(&face, glyphs.keys().copied(), options.xdv_glyph_names)
});
let mut remapper = GlyphRemapper::new();
let mut fingerprint = Sha256::new();
fingerprint.update(font.resource.version.sha256.as_bytes());
@@ -100,15 +106,19 @@ fn write_font(
let cid = remapper.remap(glyph);
fingerprint.update(glyph.to_be_bytes());
write!(widths, "{cid} [{}] ", width(i64::from(advance))).unwrap();
if !source.is_empty() {
cmap.insert(cid, utf16_hex(source));
let unicode = match &font_unicode {
Some(mapping) => mapping.get(&glyph).map(String::as_str),
None => (!source.is_empty()).then_some(source),
};
if let Some(unicode) = unicode {
cmap.insert(cid, utf16_hex(unicode));
}
embedded.insert(
glyph,
EmbeddedGlyph {
cid,
advance,
text: source.to_owned(),
cluster_text: xdv.is_none().then(|| source.to_owned()),
},
);
}
@@ -146,16 +156,22 @@ fn write_font(
let cid_font = object + 1;
let descriptor = object + 2;
let font_file = object + 3;
let to_unicode = object + 4;
let unicode_reference = if xdv.is_some() && cmap.is_empty() {
String::new()
} else {
format!(" /ToUnicode {} 0 R", object + 4)
};
objects.push(format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R] /ToUnicode {to_unicode} 0 R >>"
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R]{unicode_reference} >>"
).into_bytes());
objects.push(format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /W [{widths}]{mapping} >>"
).into_bytes());
objects.push(font_descriptor(&face, &name, file_key, font_file));
objects.push(objects::stream(&file_options, program, compression));
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
if !unicode_reference.is_empty() {
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
}
Ok(EmbeddedFont {
object,
glyphs: embedded,
@@ -261,7 +277,10 @@ impl EmbeddedFont {
bp_per_unit: f64,
) {
let glyph = &self.glyphs[&glyph];
let override_text = text != glyph.text;
let override_text = glyph
.cluster_text
.as_deref()
.is_some_and(|mapped| text != mapped);
if run.as_ref().is_some_and(|state| {
override_text
|| state.font != font
@@ -0,0 +1,281 @@
//! Unicode recovery for OpenType glyph IDs carried by native XDV runs.
use crate::{execution::SourceProvider, resources::ResourceKind};
use read_fonts::{
FontData, FontRead,
tables::cmap::{Cmap, CmapIterLimits, CmapSubtable, PlatformId},
};
use rustybuzz::ttf_parser::{
Face, GlyphId, Tag,
gsub::{SingleSubstitution, SubstitutionSubtable},
opentype_layout::Coverage,
};
use std::collections::{BTreeMap, BTreeSet};
/// Optional Adobe Glyph List resources from the current job's font map search path.
pub struct XdvGlyphNames(BTreeMap<String, String>);
impl XdvGlyphNames {
pub fn load(files: &mut impl SourceProvider, from: &str) -> Result<Self, String> {
let mut names = BTreeMap::new();
for list in ["texglyphlist.txt", "pdfglyphlist.txt", "glyphlist.txt"] {
let Some(resource) = files.optional_font_file(ResourceKind::Map, list, from)? else {
continue;
};
for line in resource.data.split(|byte| *byte == b'\n') {
let Ok(line) = std::str::from_utf8(line) else {
continue;
};
let line = line.trim();
if line.starts_with('#') {
continue;
}
let Some((name, values)) = line.split_once(';') else {
continue;
};
let scalars: String = values
.split(';')
.next()
.unwrap_or_default()
.split_ascii_whitespace()
.map_while(parse_scalar)
.take(16)
.collect();
if !scalars.is_empty() {
names.entry(name.trim().to_owned()).or_insert(scalars);
}
}
}
Ok(Self(names))
}
}
pub(super) fn map_glyphs(
face: &Face<'_>,
glyphs: impl Iterator<Item = u16>,
names: Option<&XdvGlyphNames>,
) -> BTreeMap<u16, String> {
use PlatformId::{Unicode, Windows};
let Some(tables) = face
.raw_face()
.table(Tag::from_bytes(b"cmap"))
.and_then(|data| Cmap::read(FontData::new(data)).ok())
else {
return BTreeMap::new();
};
let preferences = [
(Windows, 10),
(Unicode, 3),
(Unicode, 4),
(Unicode, 0),
(Windows, 1),
(Unicode, 1),
];
let Some(table) = preferences.into_iter().find_map(|(platform, encoding)| {
tables
.encoding_records()
.iter()
.find(|record| record.platform_id() == platform && record.encoding_id() == encoding)
.and_then(|record| record.subtable(tables.offset_data()).ok())
.filter(|table| matches!(table, CmapSubtable::Format4(_) | CmapSubtable::Format12(_)))
}) else {
return BTreeMap::new();
};
let glyph_count = face.number_of_glyphs();
let mut nominal = vec![[None, None]; usize::from(glyph_count)];
let limits = CmapIterLimits {
max_char: char::MAX as u32,
glyph_count: u32::from(glyph_count),
};
for (codepoint, glyph) in table.iter_with_limits(limits) {
if let Some(entry) = nominal.get_mut(glyph.to_u32() as usize) {
entry[usize::from(low_priority(codepoint))] = char::from_u32(codepoint);
}
}
let mut mapping = BTreeMap::new();
let mut unresolved = BTreeSet::new();
for glyph in glyphs {
let Some(entry) = nominal.get(usize::from(glyph)) else {
continue;
};
if let Some(character) = entry[0] {
mapping.insert(glyph, character.to_string());
} else {
unresolved.insert(glyph);
}
}
if !unresolved.is_empty() {
map_substitutions(face, &nominal, &mut unresolved, &mut mapping);
}
for glyph in unresolved {
if let Some(text) = face
.glyph_name(GlyphId(glyph))
.and_then(|name| glyph_text(name, names))
{
mapping.insert(glyph, text);
} else if let Some(character) = nominal[usize::from(glyph)][1] {
mapping.insert(glyph, character.to_string());
}
}
mapping
}
fn low_priority(codepoint: u32) -> bool {
matches!(codepoint,
0x00AD | 0x2E80..=0x2EF3 | 0x2F00..=0x2FD5 | 0xE000..=0xF8FF
| 0xFB00..=0xFB4F | 0xF900..=0xFAFF | 0x2F800..=0x2FA1F
| 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD)
}
fn map_substitutions(
face: &Face<'_>,
nominal: &[[Option<char>; 2]],
unresolved: &mut BTreeSet<u16>,
mapping: &mut BTreeMap<u16, String>,
) {
let Some(gsub) = face.tables().gsub else {
return;
};
let features: BTreeSet<_> = gsub
.scripts
.into_iter()
.flat_map(|script| script.default_language.into_iter().chain(script.languages))
.flat_map(|language| {
language
.required_feature
.into_iter()
.chain(language.feature_indices)
})
.collect();
let mut lookups = BTreeSet::new();
let character = |glyph: GlyphId| {
let [base, fallback] = *nominal.get(usize::from(glyph.0))?;
base.or(fallback)
};
for index in features
.into_iter()
.filter_map(|index| gsub.features.get(index))
.flat_map(|feature| feature.lookup_indices)
{
if unresolved.is_empty() {
break;
}
if !lookups.insert(index) {
continue;
}
let Some(lookup) = gsub.lookups.get(index) else {
continue;
};
for subtable in lookup.subtables.into_iter::<SubstitutionSubtable<'_>>() {
for_covered(subtable.coverage(), |index, input| {
let Some(first) = character(input) else {
return;
};
// Only nominal characters participate in the inverse. Derived
// sequences are output mappings and cannot feed another lookup.
match subtable {
SubstitutionSubtable::Single(SingleSubstitution::Format1 { delta, .. }) => {
let output = GlyphId(input.0.wrapping_add_signed(delta));
if unresolved.remove(&output.0) {
mapping.insert(output.0, first.to_string());
}
}
SubstitutionSubtable::Single(SingleSubstitution::Format2 {
substitutes,
..
}) => {
if let Some(output) = substitutes.get(index)
&& unresolved.remove(&output.0)
{
mapping.insert(output.0, first.to_string());
}
}
SubstitutionSubtable::Alternate(table) => {
if let Some(alternates) = table.alternate_sets.get(index) {
for output in alternates.alternates {
if unresolved.remove(&output.0) {
mapping.insert(output.0, first.to_string());
}
}
}
}
SubstitutionSubtable::Ligature(table) => {
if let Some(ligatures) = table.ligature_sets.get(index) {
for ligature in ligatures {
let output = ligature.glyph.0;
if unresolved.contains(&output)
&& let Some(text) = std::iter::once(Some(first))
.chain(ligature.components.into_iter().map(character))
.collect::<Option<String>>()
{
unresolved.remove(&output);
mapping.insert(output, text);
}
}
}
}
_ => {}
}
});
}
}
}
fn for_covered(coverage: Coverage<'_>, mut visit: impl FnMut(u16, GlyphId)) {
match coverage {
Coverage::Format1 { glyphs } => {
for (index, glyph) in glyphs.into_iter().enumerate() {
visit(index as u16, glyph);
}
}
Coverage::Format2 { records } => {
for record in records {
for glyph in record.start.0..=record.end.0 {
if let Some(index) = record.value.checked_add(glyph - record.start.0) {
visit(index, GlyphId(glyph));
}
}
}
}
}
}
fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option<String> {
let name = name.split('.').next()?;
if name.is_empty() {
return None;
}
let mut text = String::new();
for part in name.split('_') {
if let Some(hex) = part
.strip_prefix("uni")
.filter(|hex| !hex.is_empty() && hex.len() % 4 == 0 && hex.bytes().all(uppercase_hex))
{
for at in (0..hex.len()).step_by(4) {
text.push(parse_scalar(&hex[at..at + 4])?);
}
} else if let Some(hex) = part
.strip_prefix('u')
.filter(|hex| (4..=6).contains(&hex.len()) && hex.bytes().all(uppercase_hex))
{
text.push(parse_scalar(hex)?);
} else {
text.push_str(names?.0.get(part)?);
}
}
Some(text)
}
fn uppercase_hex(byte: u8) -> bool {
byte.is_ascii_digit() || (b'A'..=b'F').contains(&byte)
}
fn parse_scalar(value: &str) -> Option<char> {
if !value.bytes().all(uppercase_hex) {
return None;
}
char::from_u32(u32::from_str_radix(value, 16).ok()?)
}
@@ -122,6 +122,8 @@ impl GlyphUnicodeMap {
}
}
pub use crate::pdf::opentype_unicode::XdvGlyphNames;
/// Parameters and job data consumed by the PDF writer after all shipouts.
#[derive(Clone, Copy)]
pub struct PdfFinalOptions<'a> {
@@ -133,6 +135,8 @@ pub struct PdfFinalOptions<'a> {
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
pub info: crate::pdf_device::PdfInfo<'a>,
pub xdv_glyph_names: Option<&'a XdvGlyphNames>,
pub(crate) xdv_font_unicode: bool,
pub(crate) xdv_keep_destinations: bool,
pub(crate) xdv_outline_open_depth: usize,
pub(crate) xdv_navigation: Option<&'a crate::pdf_device::xdv_navigation::Navigation>,
+25
View File
@@ -2175,6 +2175,31 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX OpenType PDF Unicode 映射
XeTeX 的原生 PDF 导出使用实际字形编号,从原字体的 Unicode cmap、
GSUB 单字形替换、备选和连字表、字形名称恢复 Unicode,再映射到
实际写出的子集 CID。低优先级 cmap 项作为最后的候选。
按作业字体映射路径查找字形名表,文件存在时记录读取的实际版本。
默认字形序列直接写入 PDF,词级 ActualText 原语留待独立实现。
[xdvipdfmx 的 cmap 优先级与恢复顺序](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/tt_cmap.c#L1041-L1205)
[xdvipdfmx 的 GSUB 逆向映射](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/tt_gsub.c#L1991-L2026)
四种同源字体按原始 GID 核对 56 条实际映射,覆盖天城体、阿拉伯语、
CFF 拉丁连字和补充平面。加入同一份字形名表后,双方多出相同的
两条天城体映射。两次跨文件语言变更各复用 66 步、重放 2 次调用,
只更新第二页。加入及移除字形名表也各复用 66 步,PDF 映射随实际
资源变化,可见页面无需重发。四次修订的 PDF、SVG 和来源映射均与
同版本全量编译一致。12 项既有 XeTeX 定向测试通过。
原样 ACL 的印地语 17 条、阿拉伯语 19 条映射与参考逐字形一致。
按版面提取的整页文本逐字节一致。589 个原始字形、字号和坐标
继续一致,收敛后的 aux、out、bbl 也一致。144 DPI 灰度差异从
168 降到 98 个像素。按词框输出的 119 项中有 118 项按顺序配对,
已配对词框的最大偏差为 0.056791 bp,整页等价继续开放。
回执 `target/p3-xetex-pdf-unicode/receipt.json` 的 SHA-256 为
`9ab7a6fa802bea639187db38fb6bd87eba8f2b661b893d424b5418089840f291`。
### XeTeX OpenType 脚本和语言标签
将真实字体选项中的 OpenType 标签转换为塑形缓冲区的脚本、语言
+11
View File
@@ -758,6 +758,17 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### OpenType PDF Unicode 映射复编
同一 schema71、十份原样项目文件和实际 BibTeX 产物,三轮原生
编译完成。后两轮 aux 和 out 内容相同,最终 aux、out、bbl
均与冻结参考逐字节一致。589 个原始字形、字号和坐标保持一致。
印地语和阿拉伯语共 36 条 ToUnicode 项逐字形对应。按版面提取的
整页文本一致,词框输出仍有一项顺序差异,灰度图仍有 98 个差异
像素,整页等价门禁继续开放。
回执 `target/p3-xetex-pdf-unicode/receipt.json`。
[OpenType PDF Unicode 阶段记录](P2_M1_PROGRESS.md#xetex-opentype-pdf-unicode-映射)
#### OpenType 脚本和语言标签复编
同一 schema71、十份原始 ACL 文件及既有 BibTeX 产物复编。参考 XDV
+16 -2
View File
@@ -35,7 +35,8 @@ use texrra_tex_core::{
NativeSession, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
SourceProvider, State, WriteDestination,
},
render::DisplayList,
pdf_unicode::XdvGlyphNames,
render::{DisplayItem, DisplayList},
resources::{FileWorld, InputSnapshot, ResourceTrace, ResourceVersion, WorldConfig},
};
@@ -1101,12 +1102,25 @@ impl CompileJob {
&cancellation,
)?;
evidence.phase = AttemptPhase::Export;
let xdv_glyph_names = if request.target == Target::Shipouts
&& request.input_profile == InputProfile::XeTeX
&& pages.iter().any(|page| {
page.items.iter().any(|item| matches!(item, DisplayItem::OpenTypeGlyph { .. }))
})
{
Some(XdvGlyphNames::load(files, &request.input.to_string_lossy())
.map_err(CompileError::Host)?)
} else {
None
};
let (pdf, export_diagnostics) = if pages.is_empty() {
(None, Vec::new())
} else if request.target == Target::Shipouts {
let mut options = e.state.pdf_final_options();
options.xdv_glyph_names = xdv_glyph_names.as_ref();
let document = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
&pages,
e.state.pdf_final_options(),
options,
)?;
(Some(document.bytes), document.diagnostics)
} else {