383 lines
13 KiB
Rust
Executable File
383 lines
13 KiB
Rust
Executable File
//! Minimal TeX Font Metric (TFM) parser.
|
|
//!
|
|
//! The parser follows the TFM layout used by `cmr10.tfm`:
|
|
//! - 24-byte fixed header followed by `lh` 4-byte header words
|
|
//! - one 4-byte char-info record per character in `bc..=ec`
|
|
//! - width/height/depth/italic arrays of 4-byte fixed values
|
|
//! - lig/kern, kern, extensible and parameter sections
|
|
//!
|
|
//! Metric values are stored as fixed-point values relative to the design
|
|
//! size. They are converted to TeX scaled points (1pt = 65536sp).
|
|
|
|
use std::fs;
|
|
use std::path::Path;
|
|
|
|
#[derive(Clone, Copy, Debug, Default)]
|
|
pub struct CharInfo {
|
|
pub width_index: u8,
|
|
pub height_index: u8,
|
|
pub depth_index: u8,
|
|
pub italic_index: u8,
|
|
pub tag: u8,
|
|
/// Start offset into the lig/kern instruction table (tag 1).
|
|
pub lig_kern_start: usize,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct TfmMetrics {
|
|
design_size_pt: f64,
|
|
bc: u16,
|
|
ec: u16,
|
|
char_info: Vec<CharInfo>,
|
|
widths: Vec<i32>,
|
|
heights: Vec<i32>,
|
|
depths: Vec<i32>,
|
|
italics: Vec<i32>,
|
|
params: Vec<i32>,
|
|
kerns: std::collections::HashMap<(char, char), i64>,
|
|
ligatures: std::collections::HashMap<(char, char), (char, char)>,
|
|
}
|
|
|
|
impl TfmMetrics {
|
|
pub fn parse(bytes: &[u8]) -> Result<Self, String> {
|
|
let word = |offset: usize| -> Result<u16, String> {
|
|
let slice = bytes
|
|
.get(offset..offset + 2)
|
|
.ok_or_else(|| format!("TFM truncated at byte {offset}"))?;
|
|
Ok(u16::from_be_bytes([slice[0], slice[1]]))
|
|
};
|
|
let fixed = |offset: usize| -> Result<i32, String> {
|
|
let slice = bytes
|
|
.get(offset..offset + 4)
|
|
.ok_or_else(|| format!("TFM truncated at byte {offset}"))?;
|
|
Ok(i32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
|
|
};
|
|
let table = |offset: usize, count: u16, label: &str| -> Result<Vec<i32>, String> {
|
|
let count = usize::from(count);
|
|
let end = offset
|
|
.checked_add(count * 4)
|
|
.ok_or_else(|| format!("TFM {label} table overflow"))?;
|
|
if end > bytes.len() {
|
|
return Err(format!("TFM {label} table extends past end of file"));
|
|
}
|
|
(0..count).map(|index| fixed(offset + index * 4)).collect()
|
|
};
|
|
|
|
let lh = usize::from(word(2)?);
|
|
let bc = word(4)?;
|
|
let ec = word(6)?;
|
|
let nw = word(8)?;
|
|
let nh = word(10)?;
|
|
let nd = word(12)?;
|
|
let ni = word(14)?;
|
|
let nl = word(16)?;
|
|
let nk = word(18)?;
|
|
let ne = word(20)?;
|
|
let np = word(22)?;
|
|
if ec < bc {
|
|
return Err("TFM has ec < bc".to_string());
|
|
}
|
|
let design_fixed = fixed(28)?;
|
|
if design_fixed <= 0 {
|
|
return Err("TFM design size is not positive".to_string());
|
|
}
|
|
// TFM design size is a 16.16 fixed value in units of 1/16pt: dividing
|
|
// by 2^20 yields points.
|
|
let design_size_pt = f64::from(design_fixed) / 1_048_576.0;
|
|
|
|
let header_end = 24usize
|
|
.checked_add(lh.checked_mul(4).ok_or("TFM header size overflow")?)
|
|
.ok_or("TFM header overflow")?;
|
|
let char_count = usize::from(ec - bc) + 1;
|
|
let char_end = header_end
|
|
.checked_add(char_count * 4)
|
|
.ok_or("TFM char-info overflow")?;
|
|
if char_end > bytes.len() {
|
|
return Err("TFM char-info table extends past end of file".to_string());
|
|
}
|
|
let mut char_info = Vec::with_capacity(char_count);
|
|
for index in 0..char_count {
|
|
let offset = header_end + index * 4;
|
|
char_info.push(CharInfo {
|
|
width_index: bytes[offset],
|
|
height_index: bytes[offset + 1] >> 4,
|
|
depth_index: bytes[offset + 1] & 0x0f,
|
|
italic_index: bytes[offset + 2] >> 2,
|
|
tag: bytes[offset + 2] & 0x03,
|
|
lig_kern_start: usize::from(bytes[offset + 3]),
|
|
});
|
|
}
|
|
|
|
let width_offset = char_end;
|
|
let height_offset = width_offset
|
|
.checked_add(usize::from(nw) * 4)
|
|
.ok_or("TFM width table overflow")?;
|
|
let depth_offset = height_offset
|
|
.checked_add(usize::from(nh) * 4)
|
|
.ok_or("TFM height table overflow")?;
|
|
let italic_offset = depth_offset
|
|
.checked_add(usize::from(nd) * 4)
|
|
.ok_or("TFM depth table overflow")?;
|
|
let lig_kern_offset = italic_offset
|
|
.checked_add(usize::from(ni) * 4)
|
|
.ok_or("TFM italic table overflow")?;
|
|
let kern_offset = lig_kern_offset
|
|
.checked_add(usize::from(nl) * 4)
|
|
.ok_or("TFM lig/kern table overflow")?;
|
|
let extensible_offset = kern_offset
|
|
.checked_add(usize::from(nk) * 4)
|
|
.ok_or("TFM kern table overflow")?;
|
|
let params_offset = extensible_offset
|
|
.checked_add(usize::from(ne) * 4)
|
|
.ok_or("TFM extensible table overflow")?;
|
|
|
|
let widths = table(width_offset, nw, "width")?;
|
|
let heights = table(height_offset, nh, "height")?;
|
|
let depths = table(depth_offset, nd, "depth")?;
|
|
let italics = table(italic_offset, ni, "italic")?;
|
|
let params = table(params_offset, np, "parameter")?;
|
|
let kern_table = table(kern_offset, nk, "kern")?;
|
|
let (kerns, ligatures) = parse_kerns(
|
|
bytes,
|
|
lig_kern_offset,
|
|
usize::from(nl),
|
|
&kern_table,
|
|
&char_info,
|
|
u32::from(bc),
|
|
design_size_pt,
|
|
);
|
|
|
|
Ok(Self {
|
|
design_size_pt,
|
|
bc,
|
|
ec,
|
|
char_info,
|
|
widths,
|
|
heights,
|
|
depths,
|
|
italics,
|
|
params,
|
|
kerns,
|
|
ligatures,
|
|
})
|
|
}
|
|
|
|
pub fn parse_file(path: &Path) -> Result<Self, String> {
|
|
let bytes = fs::read(path).map_err(|error| format!("read {}: {error}", path.display()))?;
|
|
Self::parse(&bytes)
|
|
}
|
|
|
|
pub fn design_size_pt(&self) -> f64 {
|
|
self.design_size_pt
|
|
}
|
|
|
|
fn fixed_to_scaled(&self, raw: i32) -> i64 {
|
|
(f64::from(raw) * self.design_size_pt / 16.0).round() as i64
|
|
}
|
|
|
|
/// Kerning between two characters, in scaled points.
|
|
pub fn kern(&self, left: char, right: char) -> i64 {
|
|
self.kerns.get(&(left, right)).copied().unwrap_or(0)
|
|
}
|
|
|
|
/// Ligature replacement for a pair, as (Unicode display char, TFM slot char).
|
|
pub fn ligature(&self, left: char, right: char) -> Option<(char, char)> {
|
|
self.ligatures.get(&(left, right)).copied()
|
|
}
|
|
|
|
fn index_for(&self, character: char) -> Option<usize> {
|
|
let code = u32::from(character);
|
|
if code < u32::from(self.bc) || code > u32::from(self.ec) {
|
|
return None;
|
|
}
|
|
Some((code - u32::from(self.bc)) as usize)
|
|
}
|
|
|
|
pub fn char_info(&self, character: char) -> Option<CharInfo> {
|
|
self.index_for(character)
|
|
.and_then(|index| self.char_info.get(index).copied())
|
|
}
|
|
|
|
fn table_value(&self, table: &[i32], index: u8) -> Option<i32> {
|
|
if index == 0 {
|
|
return None;
|
|
}
|
|
table.get(usize::from(index)).copied()
|
|
}
|
|
|
|
pub fn width(&self, character: char) -> i64 {
|
|
self.char_info(character)
|
|
.and_then(|info| self.table_value(&self.widths, info.width_index))
|
|
.map_or(0, |raw| self.fixed_to_scaled(raw))
|
|
}
|
|
|
|
pub fn height(&self, character: char) -> i64 {
|
|
self.char_info(character)
|
|
.and_then(|info| self.table_value(&self.heights, info.height_index))
|
|
.map_or(0, |raw| self.fixed_to_scaled(raw))
|
|
}
|
|
|
|
pub fn depth(&self, character: char) -> i64 {
|
|
self.char_info(character)
|
|
.and_then(|info| self.table_value(&self.depths, info.depth_index))
|
|
.map_or(0, |raw| self.fixed_to_scaled(raw))
|
|
}
|
|
|
|
pub fn italic(&self, character: char) -> i64 {
|
|
self.char_info(character)
|
|
.and_then(|info| self.table_value(&self.italics, info.italic_index))
|
|
.map_or(0, |raw| self.fixed_to_scaled(raw))
|
|
}
|
|
|
|
fn param(&self, index: usize) -> i64 {
|
|
self.params
|
|
.get(index)
|
|
.copied()
|
|
.map_or(0, |raw| self.fixed_to_scaled(raw))
|
|
}
|
|
|
|
pub fn space(&self) -> i64 {
|
|
self.param(1)
|
|
}
|
|
|
|
pub fn stretch(&self) -> i64 {
|
|
self.param(2)
|
|
}
|
|
|
|
pub fn shrink(&self) -> i64 {
|
|
self.param(3)
|
|
}
|
|
|
|
pub fn x_height(&self) -> i64 {
|
|
self.param(4)
|
|
}
|
|
|
|
pub fn quad(&self) -> i64 {
|
|
self.param(5)
|
|
}
|
|
|
|
/// `\fontdimen7`: extra space inserted after punctuation with a space
|
|
/// factor of 2000 or more.
|
|
pub fn extra_space(&self) -> i64 {
|
|
self.param(6)
|
|
}
|
|
}
|
|
|
|
fn parse_kerns(
|
|
bytes: &[u8],
|
|
lig_kern_offset: usize,
|
|
instruction_count: usize,
|
|
kern_table: &[i32],
|
|
char_info: &[CharInfo],
|
|
bc: u32,
|
|
design_size_pt: f64,
|
|
) -> (
|
|
std::collections::HashMap<(char, char), i64>,
|
|
std::collections::HashMap<(char, char), (char, char)>,
|
|
) {
|
|
let mut kerns = std::collections::HashMap::new();
|
|
let mut ligatures = std::collections::HashMap::new();
|
|
for (index, info) in char_info.iter().enumerate() {
|
|
if info.tag != 1 {
|
|
continue;
|
|
}
|
|
let left = char::from_u32(bc + index as u32).unwrap_or('?');
|
|
let mut cursor = info.lig_kern_start;
|
|
while cursor < instruction_count {
|
|
let offset = lig_kern_offset + cursor * 4;
|
|
let Some(entry) = bytes.get(offset..offset + 4) else {
|
|
break;
|
|
};
|
|
let (skip, next, op, remainder) = (entry[0], entry[1], entry[2], entry[3]);
|
|
if op < 128 {
|
|
let slot_char = char::from_u32(bc + u32::from(remainder)).unwrap_or('?');
|
|
let unicode = match remainder {
|
|
11 => Some('\u{FB00}'),
|
|
12 => Some('\u{FB01}'),
|
|
13 => Some('\u{FB02}'),
|
|
14 => Some('\u{FB03}'),
|
|
15 => Some('\u{FB04}'),
|
|
_ => None,
|
|
};
|
|
if let Some(unicode) = unicode {
|
|
let right = char::from_u32(u32::from(next)).unwrap_or('?');
|
|
ligatures
|
|
.entry((left, right))
|
|
.or_insert((unicode, slot_char));
|
|
}
|
|
} else {
|
|
let kern_index = usize::from(op - 128) * 256 + usize::from(remainder);
|
|
if let Some(raw) = kern_table.get(kern_index) {
|
|
let right = char::from_u32(u32::from(next)).unwrap_or('?');
|
|
// Kern values are design-size-relative, like character
|
|
// widths; at the design size they are in 1/16 pt units.
|
|
let value = (f64::from(*raw) * design_size_pt / 16.0).round() as i64;
|
|
// TeX stops at the first instruction that matches the
|
|
// pair, so later instructions must not overwrite it.
|
|
kerns.entry((left, right)).or_insert(value);
|
|
}
|
|
}
|
|
if skip >= 128 {
|
|
break;
|
|
}
|
|
cursor += usize::from(skip) + 1;
|
|
}
|
|
}
|
|
(kerns, ligatures)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn cmr10() -> TfmMetrics {
|
|
TfmMetrics::parse(include_bytes!("../assets/cmr10.tfm")).expect("parse cmr10")
|
|
}
|
|
|
|
#[test]
|
|
fn parses_cmr10_header_and_widths() {
|
|
let font = cmr10();
|
|
assert!((font.design_size_pt() - 10.0).abs() < 0.001);
|
|
assert!((font.width('A') - 491_521).abs() <= 2);
|
|
assert!((font.width('a') - 327_681).abs() <= 2);
|
|
assert!((font.space() - 218_454).abs() <= 2);
|
|
assert!(font.height('A') > 0);
|
|
assert!(font.depth('g') > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn cmr10_kerning_is_design_size_relative() {
|
|
let font = cmr10();
|
|
let kern = font.kern('m', 'b');
|
|
assert!(
|
|
(kern + 18_205).abs() <= 4,
|
|
"m/b kern should be -0.277779pt, got {kern}"
|
|
);
|
|
let apostrophe = font.kern('f', '\'');
|
|
assert!(
|
|
(apostrophe - 50_973).abs() <= 4,
|
|
"f/apostrophe kern should be +0.777779pt, got {apostrophe}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn cmr10_has_an_fi_ligature() {
|
|
let font = cmr10();
|
|
let (unicode, slot) = font.ligature('f', 'i').expect("fi ligature");
|
|
assert_eq!(unicode, '\u{FB01}');
|
|
assert_eq!(slot, char::from_u32(u32::from(font.bc) + 12).unwrap());
|
|
}
|
|
|
|
#[test]
|
|
fn missing_characters_have_zero_metrics() {
|
|
let font = cmr10();
|
|
assert_eq!(font.width('\u{4e2d}'), 0);
|
|
assert_eq!(font.height('\u{4e2d}'), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_truncated_files() {
|
|
assert!(TfmMetrics::parse(&[0_u8; 8]).is_err());
|
|
}
|
|
}
|