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>,