//! Validated TFM data and TeX's integer font-loading arithmetic. //! Slots and lig/kern bytecode are retained independently of glyph encodings. use std::{fs, path::Path}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum FontSize { Design, At(i64), Scaled(i32), } impl FontSize { /// Validate the syntax-level request before opening a font file. A scaled /// request additionally needs its actual design size checked when loaded. pub fn validate(self) -> Result<(), String> { match self { Self::At(n) if n <= 0 || n >= 1 << 27 => { Err("font size must be positive and less than 2048pt".into()) } Self::Scaled(n) if !(1..=32768).contains(&n) => { Err("font scaled ratio must be in 1..32768".into()) } _ => Ok(()), } } } #[derive( Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, )] pub struct CharInfo { pub width_index: u8, pub height_index: u8, pub depth_index: u8, pub italic_index: u8, pub tag: u8, pub remainder: u8, pub lig_kern_start: usize, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct LigKernInstruction { pub skip: u8, pub next: u8, pub operation: u8, pub remainder: u8, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum LigKernCommand { Kern(i64), Ligature { operation: u8, replacement: u8 }, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct ExtensibleRecipe { pub top: u8, pub middle: u8, pub bottom: u8, pub repeat: u8, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct TfmMetrics { checksum: u32, design_size: i64, size: i64, bc: u16, ec: u16, char_info: Vec, widths: Vec, heights: Vec, depths: Vec, italics: Vec, params: Vec, extensibles: Vec, kern_values: Vec, lig_kern: Vec, boundary_char: Option, boundary_label: Option, } impl TfmMetrics { pub fn parse(bytes: &[u8]) -> Result { Self::parse_at(bytes, FontSize::Design) } pub fn parse_at(bytes: &[u8], requested: FontSize) -> Result { let mut fields = [0usize; 12]; for (i, n) in fields.iter_mut().enumerate() { let b = bytes .get(2 * i..2 * i + 2) .ok_or("truncated TFM size fields")?; *n = usize::from(u16::from_be_bytes([b[0], b[1]])); if *n > 32767 { return Err("TFM size field exceeds 32767".into()); } } let [lf, lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np] = fields; if lh < 2 || ec > 255 || bc > ec + 1 || nw == 0 || nh == 0 || nd == 0 || ni == 0 { return Err("invalid TFM header or table size".into()); } let nc = ec + 1 - bc; if lf != 6 + lh + nc + nw + nh + nd + ni + nl + nk + ne + np { return Err("inconsistent TFM length fields".into()); } if bytes.len() < lf * 4 { return Err("truncated TFM data".into()); } let fixed = |i: usize| i32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()); let design_fixed = fixed(28); if design_fixed < 1 << 20 { return Err("TFM design size must be at least 1pt".into()); } let design_size = i64::from(design_fixed) / 16; let size = Self::resolve_size(design_size, requested)?; let mut at = (6 + lh) * 4; let mut char_info = Vec::with_capacity(nc); for _ in 0..nc { let b = &bytes[at..at + 4]; at += 4; let c = CharInfo { width_index: b[0], height_index: b[1] >> 4, depth_index: b[1] & 15, italic_index: b[2] >> 2, tag: b[2] & 3, remainder: b[3], lig_kern_start: usize::from(b[3]), }; if usize::from(c.width_index) >= nw || usize::from(c.height_index) >= nh || usize::from(c.depth_index) >= nd || usize::from(c.italic_index) >= ni { return Err("TFM character metric index outside its table".into()); } if c.tag == 1 && usize::from(c.remainder) >= nl || c.tag == 3 && usize::from(c.remainder) >= ne { return Err("TFM character program/recipe index outside its table".into()); } char_info.push(c); } let mut table = |n: usize| { let v = (0..n).map(|j| fixed(at + 4 * j)).collect::>(); at += n * 4; v }; let widths = table(nw); let heights = table(nh); let depths = table(nd); let italics = table(ni); // At this point all table offsets are guaranteed by lf and the sizes. let lig_at = at; at += 4 * nl; let kern_values = (0..nk).map(|j| fixed(at + 4 * j)).collect(); at += 4 * nk; let extensibles = (0..ne) .map(|j| { let b = &bytes[at + 4 * j..at + 4 * j + 4]; ExtensibleRecipe { top: b[0], middle: b[1], bottom: b[2], repeat: b[3], } }) .collect(); at += 4 * ne; let params = (0..np).map(|j| fixed(at + 4 * j)).collect(); let lig_kern = (0..nl) .map(|j| { let b = &bytes[lig_at + 4 * j..lig_at + 4 * j + 4]; LigKernInstruction { skip: b[0], next: b[1], operation: b[2], remainder: b[3], } }) .collect::>(); let boundary_char = lig_kern.first().filter(|i| i.skip == 255).map(|i| i.next); let boundary_label = lig_kern .last() .filter(|i| i.skip == 255) .map(|i| usize::from(i.operation) * 256 + usize::from(i.remainder)) .filter(|n| *n < nl); let font = Self { checksum: u32::from_be_bytes(bytes[24..28].try_into().unwrap()), design_size, size, bc: bc as u16, ec: ec as u16, char_info, widths, heights, depths, italics, params, kern_values, extensibles, lig_kern, boundary_char, boundary_label, }; font.validate()?; Ok(font) } fn resolve_size(design: i64, requested: FontSize) -> Result { requested.validate()?; let size = match requested { FontSize::Design => design, FontSize::At(n) => n, FontSize::Scaled(n) => design * i64::from(n) / 1000, }; if size <= 0 || size >= 1 << 27 { return Err("font size must be positive and less than 2048pt".into()); } Ok(size) } /// Resolve a load request against this font's original design size, without /// revalidating its tables at another size. Used to look up loaded fonts: /// TeX reuses their current state before attempting any new file read. pub fn requested_size(&self, requested: FontSize) -> Result { Self::resolve_size(self.design_size, requested) } fn validate(&self) -> Result<(), String> { for table in [ &self.widths, &self.heights, &self.depths, &self.italics, &self.kern_values, ] { for raw in table { self.scaled(*raw)?; } } for raw in self.params.iter().skip(1) { self.scaled(*raw)?; } for table in [&self.widths, &self.heights, &self.depths, &self.italics] { if self.scaled(table[0])? != 0 { return Err("TFM metric zero entry must scale to zero".into()); } } for (i, c) in self.char_info.iter().enumerate() { if c.tag != 2 { continue; } let mut next = c.remainder; // TeX rejects cycles, including links through zero-width records. for _ in 0..=self.char_info.len() { let Some(info) = self.char_info(char::from(next)) else { return Err("TFM next-larger character outside range".into()); }; if usize::from(next) == usize::from(self.bc) + i { return Err("TFM next-larger cycle".into()); } if info.tag != 2 { break; } next = info.remainder; } } for (i, ins) in self.lig_kern.iter().enumerate() { if ins.skip > 128 { if usize::from(ins.operation) * 256 + usize::from(ins.remainder) >= self.lig_kern.len() { return Err("TFM lig/kern restart outside program".into()); } } else { if Some(ins.next) != self.boundary_char && !self.has_slot(ins.next) { return Err("TFM lig/kern next character does not exist".into()); } if ins.operation < 128 { if !self.has_slot(ins.remainder) { return Err("TFM ligature replacement does not exist".into()); } } else if usize::from(ins.operation - 128) * 256 + usize::from(ins.remainder) >= self.kern_values.len() { return Err("TFM kern index outside table".into()); } if ins.skip < 128 && i + usize::from(ins.skip) + 1 >= self.lig_kern.len() { return Err("TFM lig/kern skip outside program".into()); } } } for r in &self.extensibles { for c in [r.top, r.middle, r.bottom] .into_iter() .filter(|c| *c != 0) .chain([r.repeat]) { if !self.has_slot(c) { return Err("TFM extensible component does not exist".into()); } } } Ok(()) } /// TeX store_scaled: reduce z before multiplying, preserving its deliberate /// quantization above 128pt instead of computing a floating-point ratio. fn scaled(&self, raw: i32) -> Result { Self::scale_fix_word(raw, self.size) } pub(crate) fn scale_fix_word(raw: i32, size: i64) -> Result { let [a, b, c, d] = raw.to_be_bytes(); if a != 0 && a != 255 { return Err("TFM metric must be between -16 and 16".into()); } let (mut z, mut alpha) = (size, 16i64); while z >= 1 << 23 { z /= 2; alpha *= 2; } let beta = 256 / alpha; let alpha = alpha * z; let n = ((i64::from(d) * z / 256 + i64::from(c) * z) / 256 + i64::from(b) * z) / beta; Ok(if a == 0 { n } else { n - alpha }) } pub fn at_size(&self, requested: FontSize) -> Result { let mut font = self.clone(); font.size = Self::resolve_size(self.design_size, requested)?; font.validate()?; Ok(font) } pub fn parse_file(path: &Path) -> Result { Self::parse(&fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?) } pub fn checksum(&self) -> u32 { self.checksum } pub fn design_size_sp(&self) -> i64 { self.design_size } pub fn size_sp(&self) -> i64 { self.size } pub fn design_size_pt(&self) -> f64 { self.design_size as f64 / 65536.0 } pub fn char_info(&self, c: char) -> Option { let c = c as u32; if c < u32::from(self.bc) || c > u32::from(self.ec) { return None; } self.char_info .get((c - u32::from(self.bc)) as usize) .copied() } pub fn has_slot(&self, slot: u8) -> bool { self.char_info(char::from(slot)) .is_some_and(|c| c.width_index != 0) } fn dimension(&self, c: char, table: &[i32], index: impl FnOnce(CharInfo) -> u8) -> i64 { self.char_info(c).map_or(0, |info| { self.scaled(table[usize::from(index(info))]) .expect("validated TFM metric") }) } pub fn width(&self, c: char) -> i64 { self.dimension(c, &self.widths, |i| i.width_index) } pub fn height(&self, c: char) -> i64 { self.dimension(c, &self.heights, |i| i.height_index) } pub fn depth(&self, c: char) -> i64 { self.dimension(c, &self.depths, |i| i.depth_index) } pub fn italic(&self, c: char) -> i64 { self.dimension(c, &self.italics, |i| i.italic_index) } pub fn parameter_count(&self) -> usize { self.params.len().max(7) } /// Zero-based fontdimen. Slant is 16.16 and independent of the font size. pub fn param(&self, index: usize) -> i64 { self.params.get(index).map_or(0, |raw| { if index == 0 { i64::from(*raw).div_euclid(16) } else { self.scaled(*raw).expect("validated TFM parameter") } }) } pub fn lig_kern_program(&self) -> &[LigKernInstruction] { &self.lig_kern } pub fn boundary_char(&self) -> Option { self.boundary_char } pub fn false_boundary_char(&self) -> Option { self.boundary_char.filter(|c| !self.has_slot(*c)) } pub fn boundary_label(&self) -> Option { self.boundary_label } pub fn lig_kern(&self, left: Option, right: u8) -> Option { let mut at = if let Some(c) = left { let info = self.char_info(char::from(c))?; if info.width_index == 0 || info.tag != 1 { return None; } info.lig_kern_start } else { self.boundary_label? }; let first = self.lig_kern.get(at)?; // Character labels may start with a restart. The left-boundary // label enters the program directly, as TeX's main_lig_loop+1 does. if left.is_some() && first.skip > 128 { at = usize::from(first.operation) * 256 + usize::from(first.remainder); } loop { let ins = self.lig_kern.get(at)?; if ins.skip <= 128 && ins.next == right { return Some(if ins.operation < 128 { LigKernCommand::Ligature { operation: ins.operation, replacement: ins.remainder, } } else { LigKernCommand::Kern( self.scaled( self.kern_values[usize::from(ins.operation - 128) * 256 + usize::from(ins.remainder)], ) .expect("validated kern"), ) }); } if ins.skip >= 128 { return None; } at += usize::from(ins.skip) + 1; } } pub fn kern(&self, left: char, right: char) -> i64 { let (Ok(l), Ok(r)) = (u8::try_from(left as u32), u8::try_from(right as u32)) else { return 0; }; match self.lig_kern(Some(l), r) { Some(LigKernCommand::Kern(k)) => k, _ => 0, } } /// A simple replace-both operation. Full consumers must use lig_kern, /// whose operation byte retains keep/pass semantics and arbitrary slots. pub fn ligature_slot(&self, left: char, right: char) -> Option { let (Ok(l), Ok(r)) = (u8::try_from(left as u32), u8::try_from(right as u32)) else { return None; }; match self.lig_kern(Some(l), r) { Some(LigKernCommand::Ligature { operation: 0, replacement, }) => Some(replacement), _ => None, } } pub fn next_larger(&self, c: char) -> Option { let info = self.char_info(c)?; (info.tag == 2 && self.has_slot(info.remainder)).then_some(info.remainder) } pub fn extensible_recipe(&self, c: char) -> Option { let info = self.char_info(c)?; if info.tag != 3 { return None; } self.extensibles.get(usize::from(info.remainder)).copied() } 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) } pub fn extra_space(&self) -> i64 { self.param(6) } } #[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(); assert_eq!(font.ligature_slot('f', 'i'), Some(12)); } #[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()); } #[test] fn fontdimens_use_tex_truncation_before_mu_conversion() { let font = cmr10(); assert_eq!(font.param(5), 655_361); assert_eq!(font.param(5) / 18, 36_408); assert_eq!(font.param(100), 0); let symbol = TfmMetrics::parse(include_bytes!("../assets/cmsy10.tfm")).unwrap(); assert_eq!(symbol.param(7), 443_356); // fontdimen8 = num1 assert_eq!(symbol.param(21), 163_840); // fontdimen22 = axis height } #[test] fn cmex_retains_next_larger_and_extensible_recipes() { let font = TfmMetrics::parse(include_bytes!("../assets/cmex10.tfm")).unwrap(); assert_eq!(font.next_larger(char::from(80)), Some(88)); // display sum assert_eq!(font.next_larger(char::from(88)), None); assert_eq!(font.char_info(char::from(80)).unwrap().remainder, 88); assert_eq!( font.extensible_recipe(char::from(48)), Some(ExtensibleRecipe { top: 48, middle: 0, bottom: 64, repeat: 66, }) ); assert_eq!(font.extensible_recipe(char::from(80)), None); let mut slot = 0; for expected in [16, 18, 32, 48] { slot = font.next_larger(char::from(slot)).unwrap(); assert_eq!(slot, expected); } assert!(font.extensible_recipe(char::from(slot)).is_some()); } }