Render and embed TrueType fonts selected by pdfTeX maps

This commit is contained in:
gloamxun committed 2026-11-28 02:30:30 +08:00
1 parent aa780a800b
commit 46ef76f890
9 files changed
+570 -36

No files matched your search

@@ -38,6 +38,21 @@ impl MapEntry {
self.file.is_some() || self.postscript_name
}
pub(super) fn true_type_file(&self) -> Option<&str> {
self.file.as_deref().filter(|file| {
Path::new(file)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
extension.eq_ignore_ascii_case("ttf") || extension.eq_ignore_ascii_case("ttc")
})
})
}
pub(super) fn postscript_name(&self) -> Option<&str> {
self.ps_name.as_deref()
}
pub(super) fn type1_file(&self, name: &str) -> Result<&str, String> {
let file = self.file.as_deref().ok_or_else(|| {
format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support")
@@ -0,0 +1,320 @@
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
use super::{NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
use crate::{execution::SourceProvider, resources::ResourceKind};
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
use subsetter::GlyphRemapper;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct TrueTypeProgram {
pub(crate) name: String,
data: Arc<[u8]>,
glyphs: Vec<u16>,
pub(crate) reencoded: bool,
}
impl TrueTypeProgram {
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
Face::parse(&self.data, 0)
.map_err(|error| format!("invalid TrueType font {}: {error}", self.name))
}
pub(crate) fn embed(
&self,
slots: impl Iterator<Item = u8>,
subset: bool,
) -> Result<Vec<u8>, String> {
if !subset {
// A collection stores offsets into the entire file. Rebuild its
// first face as a standalone font for the PDF stream.
if self.data.starts_with(b"ttcf") {
let face = self.face()?;
return build_sfnt(tables(face.raw_face())?);
}
return Ok(self.data.to_vec());
}
let mut remapper = GlyphRemapper::new();
remapper.remap(1);
let mut mapping = [0u16; 256];
for slot in slots {
let index = usize::from(slot);
mapping[index] = remapper.remap(self.glyphs[index]);
}
let data = subsetter::subset(&self.data, 0, &remapper)
.map_err(|error| format!("failed to subset TrueType font {}: {error}", self.name))?;
let face = RawFace::parse(&data, 0).map_err(|error| error.to_string())?;
let mut tables = tables(&face)?;
let original = self.face()?;
let glyph_count = Face::parse(&data, 0)
.map_err(|error| error.to_string())?
.number_of_glyphs();
tables.insert(tag(b"cmap"), slot_cmap(&mapping, glyph_count));
if let Some(os2) = original.raw_face().table(tag(b"OS/2")) {
tables.insert(tag(b"OS/2"), symbol_os2(os2)?);
}
if let Some(pclt) = original.raw_face().table(tag(b"PCLT")) {
tables.insert(tag(b"PCLT"), pclt.to_vec());
}
build_sfnt(tables)
}
}
pub(super) fn resolve(
files: &mut impl SourceProvider,
outline: &MapEntry,
file: &str,
font: &NativeFont,
slots: BTreeSet<u8>,
) -> Result<NativeFontPaint, String> {
let from = outline.from.to_string_lossy();
let resource = super::actual_resource(files, ResourceKind::TrueType, file, &from)?;
let face = Face::parse(&resource.data, 0)
.map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
return Err(format!("invalid TrueType outline tables in {file}"));
}
let mut resources: Vec<_> = outline.version.iter().cloned().collect();
let program_index = Some(resources.len());
resources.push(resource.version);
let encoding = if let Some(name) = &outline.encoding {
let enc = super::actual_resource(files, ResourceKind::Encoding, name, &from)?;
let encoding = super::encoding_vector(&enc.data)?;
resources.push(enc.version);
Some(encoding)
} else {
None
};
if outline.subset && encoding.is_none() {
return Err(format!(
"subset TrueType font {} needs a reencoding",
font.name
));
}
let reencoded = encoding.is_some();
let glyphs = if outline.subset {
let encoding = encoding.as_ref().unwrap();
encoding
.iter()
.map(|name| face.glyph_index_by_name(name).unwrap_or(GlyphId(0)).0)
.collect()
} else {
(0..=255)
.map(|slot| builtin_glyph(&face, slot).0)
.collect::<Vec<_>>()
};
let encoding = encoding.unwrap_or_else(|| {
glyphs
.iter()
.enumerate()
.map(|(slot, &glyph)| {
if let Some(name) = face.glyph_name(GlyphId(glyph)) {
return name.to_owned();
}
let character = win_ansi(slot as u8);
if glyph != 0 && face.glyph_index(character) == Some(GlyphId(glyph)) {
format!("uni{:04X}", u32::from(character))
} else {
".notdef".to_owned()
}
})
.collect()
});
let units = f64::from(face.units_per_em());
let scale = 1000. / units;
let glyph_paths = slots
.into_iter()
.map(|slot| {
let path = crate::opentype::outline(
&face,
glyphs[usize::from(slot)],
Some([scale, 0., scale]),
);
(slot, path)
})
.collect();
let name = face
.names()
.into_iter()
.filter(|name| name.name_id == name_id::POST_SCRIPT_NAME)
.find_map(|name| name.to_string())
.unwrap_or_else(|| outline.postscript_name().unwrap_or(&font.name).to_owned());
let bbox = face.global_bounding_box();
let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max]
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
let program = TrueTypeProgram {
name,
data: resource.data.into(),
glyphs,
reencoded,
};
Ok(NativeFontPaint {
program: NativeFontProgram::TrueType(program),
encoding,
glyph_paths,
bbox,
stem_v: 0,
subset: outline.subset,
descriptor_flags: outline.descriptor_flags,
xdv_descriptor: None,
resources,
program_index,
})
}
fn builtin_glyph(face: &Face<'_>, slot: u8) -> GlyphId {
let code = u32::from(slot);
if let Some(cmap) = face.tables().cmap {
for table in cmap.subtables {
if table.platform_id == PlatformId::Windows && table.encoding_id == 0 {
return table
.glyph_index(0xf000 | code)
.or_else(|| table.glyph_index(code))
.unwrap_or(GlyphId(0));
}
}
}
face.glyph_index(win_ansi(slot))
.or_else(|| {
face.tables()
.cmap?
.subtables
.into_iter()
.find(|table| table.platform_id == PlatformId::Macintosh && table.encoding_id == 0)?
.glyph_index(code)
})
.unwrap_or(GlyphId(0))
}
fn win_ansi(slot: u8) -> char {
// WinAnsi assigns the printable Windows characters and fills the
// unused 0x80–0x9f entries with bullet.
const HIGH: [char; 32] = [
'€', '•', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '•', 'Ž', '•', '•', '‘',
'’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '•', 'ž', 'Ÿ',
];
match slot {
0x80..=0x9f => HIGH[usize::from(slot - 0x80)],
0x7f => '•',
0xa0 => ' ',
0xad => '-',
_ => char::from(slot),
}
}
fn tag(bytes: &[u8; 4]) -> Tag {
Tag::from_bytes(bytes)
}
fn tables(face: &RawFace<'_>) -> Result<BTreeMap<Tag, Vec<u8>>, String> {
face.table_records
.into_iter()
.map(|entry| {
let bytes = face
.table(entry.tag)
.ok_or("invalid TrueType table range")?;
Ok((entry.tag, bytes.to_vec()))
})
.collect()
}
fn symbol_os2(original: &[u8]) -> Result<Vec<u8>, String> {
let mut data = original
.get(..78)
.ok_or("invalid TrueType OS/2 table")?
.to_vec();
data[0..2].copy_from_slice(&1u16.to_be_bytes());
data[42..58].fill(0);
data[45] = 3;
data[46] = 0x10;
data[64..68].copy_from_slice(&[0, 0, 0xf0, 0xff]);
data.extend_from_slice(&[0x80, 0, 0, 0, 0, 0, 0, 0]);
Ok(data)
}
fn slot_cmap(mapping: &[u16; 256], glyph_count: u16) -> Vec<u8> {
let mut mac = Vec::new();
if glyph_count < 256 {
push_words(&mut mac, &[0, 262, 0]);
mac.extend(mapping.iter().map(|&gid| gid as u8));
} else {
push_words(&mut mac, &[6, 522, 0, 0, 256]);
push_words(&mut mac, mapping);
}
let mut out = Vec::new();
// A Mac byte cmap and a Windows symbol cmap address the same TeX slots.
push_words(
&mut out,
&[0, 2, 1, 0, 0, 20, 3, 0, 0, 20 + mac.len() as u16],
);
out.extend(mac);
push_words(
&mut out,
&[
4, 544, 0, 4, 4, 1, 0, 0xf0ff, 0xffff, 0, 0xf000, 0xffff, 0, 1, 4, 0,
],
);
push_words(&mut out, mapping);
out
}
fn push_words(out: &mut Vec<u8>, words: &[u16]) {
for word in words {
out.extend_from_slice(&word.to_be_bytes());
}
}
fn checksum(bytes: &[u8]) -> u32 {
bytes.chunks(4).fold(0u32, |sum, chunk| {
let mut word = [0; 4];
word[..chunk.len()].copy_from_slice(chunk);
sum.wrapping_add(u32::from_be_bytes(word))
})
}
fn build_sfnt(mut tables: BTreeMap<Tag, Vec<u8>>) -> Result<Vec<u8>, String> {
let head = tables
.get_mut(&tag(b"head"))
.ok_or("missing TrueType head table")?;
head.get_mut(8..12)
.ok_or("invalid TrueType head table")?
.fill(0);
let count = u16::try_from(tables.len()).map_err(|_| "too many TrueType tables")?;
let search = count.ilog2() as u16;
let range = (1u16 << search)
.checked_mul(16)
.ok_or("too many TrueType tables")?;
let directory_bytes = count.checked_mul(16).ok_or("too many TrueType tables")?;
let mut out = Vec::new();
push_words(
&mut out,
&[1, 0, count, range, search, directory_bytes - range],
);
out.resize(12 + usize::from(directory_bytes), 0);
let mut adjustment = None;
for (index, (tag, bytes)) in tables.into_iter().enumerate() {
let offset = out.len();
let start = 12 + index * 16;
let length = u32::try_from(bytes.len()).map_err(|_| "TrueType table too large")?;
let address = u32::try_from(offset).map_err(|_| "TrueType font too large")?;
out[start..start + 4].copy_from_slice(&tag.to_bytes());
out[start + 4..start + 8].copy_from_slice(&checksum(&bytes).to_be_bytes());
out[start + 8..start + 12].copy_from_slice(&address.to_be_bytes());
out[start + 12..start + 16].copy_from_slice(&length.to_be_bytes());
if tag == Tag::from_bytes(b"head") {
adjustment = Some(offset + 8);
}
out.extend(bytes);
out.resize(out.len().next_multiple_of(4), 0);
}
let address = adjustment.ok_or("missing TrueType checksum adjustment")?;
let value = 0xb1b0_afbau32.wrapping_sub(checksum(&out));
out[address..address + 4].copy_from_slice(&value.to_be_bytes());
Ok(out)
}