Parse cmr10 TFM metrics for route-D math

This commit is contained in:
gloamxun committed 2026-10-20 20:44:52 +08:00
1 parent 84e2e9cadb
commit f909e8199c
4 files changed
+314 -37

No files matched your search

+33 -32
View File
@@ -1,12 +1,19 @@
// Computer Modern Roman 10pt character widths, extracted from cmr10.tfm
// with tftopl. Values are scaled points at 10pt design size.
#[derive(Clone, Debug)]
//! Computer Modern Roman 10pt metrics backed by the real `cmr10.tfm`.
use std::sync::OnceLock;
use crate::tfm::TfmMetrics;
/// Metrics for CMR10, parsed from the TFM file embedded in the crate.
#[derive(Clone, Copy, Debug, Default)]
pub struct Cmr10Metrics {}
impl Default for Cmr10Metrics {
fn default() -> Self {
Self::new()
}
static CMR10_TFM: &[u8] = include_bytes!("../assets/cmr10.tfm");
static CMR10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
fn metrics() -> &'static TfmMetrics {
CMR10_METRICS
.get_or_init(|| TfmMetrics::parse(CMR10_TFM).expect("embedded cmr10.tfm must be valid"))
}
impl Cmr10Metrics {
@@ -15,43 +22,35 @@ impl Cmr10Metrics {
}
pub fn width(&self, character: char) -> i64 {
self.widths()
.get(character as usize)
.copied()
.unwrap_or(327_680)
let width = metrics().width(character);
if width > 0 { width } else { 327_680 }
}
pub fn height(&self, character: char) -> i64 {
metrics().height(character)
}
pub fn depth(&self, character: char) -> i64 {
metrics().depth(character)
}
pub fn italic(&self, character: char) -> i64 {
metrics().italic(character)
}
pub fn space(&self) -> i64 {
218_454
metrics().space()
}
pub fn stretch(&self) -> i64 {
109_227
metrics().stretch()
}
pub fn shrink(&self) -> i64 {
72_818
}
fn widths(&self) -> &'static [i64; 128] {
&CMR10_WIDTHS
metrics().shrink()
}
}
const CMR10_WIDTHS: [i64; 128] = [
409601, 546135, 509727, 455112, 436908, 491521, 473317, 509727, 473317, 509727, 473317, 382295,
364090, 364090, 546135, 546135, 182045, 200250, 327681, 327681, 327681, 327681, 327681, 491521,
291272, 327682, 473317, 509727, 327681, 591647, 664464, 509727, 182045, 182045, 327681, 546135,
327681, 546135, 509727, 182045, 254863, 254863, 327681, 509727, 182045, 218454, 182045, 327681,
327681, 327681, 327681, 327681, 327681, 327681, 327681, 327681, 327681, 327681, 182045, 182045,
182045, 509727, 309477, 309477, 509727, 491521, 464215, 473317, 500624, 446010, 427807, 514277,
491521, 236658, 336783, 509727, 409601, 600748, 491521, 509727, 446010, 509727, 482419, 364090,
473317, 491521, 491521, 673567, 491521, 491521, 400499, 182045, 327681, 182045, 327681, 182045,
182045, 327681, 364090, 291272, 364090, 291272, 200250, 327681, 364090, 182045, 200250, 345887,
182045, 546135, 364090, 327681, 364090, 345885, 256684, 258503, 254863, 364090, 345887, 473317,
345887, 345887, 291272, 327681, 655362, 327681, 327681, 327681,
];
#[cfg(test)]
mod tests {
use super::*;
@@ -64,5 +63,7 @@ mod tests {
assert!((font.space() - 218_454).abs() <= 2);
assert!(font.stretch() > 0);
assert!(font.shrink() > 0);
assert!(font.height('A') > 0);
assert!(font.depth('g') > 0);
}
}
+18 -5
View File
@@ -199,11 +199,15 @@ pub fn delimiter_scale(body: &MathBox) -> f64 {
/// Lay out a math atom at the current style size.
pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
match atom {
MathAtom::Symbol(character) => MathBox {
width: font.width(*character),
height: 7 * 65_536,
depth: 2 * 65_536,
},
MathAtom::Symbol(character) => {
let height = font.height(*character);
let depth = font.depth(*character);
MathBox {
width: font.width(*character),
height: if height > 0 { height } else { 7 * 65_536 },
depth: if depth > 0 { depth } else { 2 * 65_536 },
}
}
MathAtom::Space(width) => MathBox {
width: *width,
height: 0,
@@ -1595,6 +1599,15 @@ mod tests {
assert!(underlined.depth > plain.depth);
assert_eq!(underlined.height, plain.height);
}
#[test]
fn glyph_height_comes_from_the_tfm() {
let font = Cmr10Metrics::default();
let box_ = layout_math(&parse_math("A"), &font);
assert_eq!(box_.height, font.height('A'));
let g = layout_math(&parse_math("g"), &font);
assert_eq!(g.depth, font.depth('g'));
}
#[test]
fn math_text_uses_upright_character_widths() {
let font = Cmr10Metrics::default();
+263
View File
@@ -0,0 +1,263 @@
//! 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,
}
#[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>,
}
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],
tag: 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")?;
Ok(Self {
design_size_pt,
bc,
ec,
char_info,
widths,
heights,
depths,
italics,
params,
})
}
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
}
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)
}
}
#[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 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());
}
}