Skip to main content

latexml_core/common/font/
tfm.rs

1//! TeX font metric files: the character dimensions of a `.tfm`, scaled as TeX scales them.
2//!
3//! A character of a font loaded with `\font` (preload.ltx's `\tenln`, a document's
4//! `\font\x=lcircle10`) whose family has no standard metric is measured from its own TFM:
5//! the Unicode character a fontmap decodes it to belongs to some other font (line10's
6//! slot 45 is an arrowhead 10pt wide; the arrow it maps to is cmmi's 5pt `\vec`).
7//! Witness 2605.02221 (diagrams.sty arrows). Guard
8//! `perfect_kernel_batch58::line_font_char_has_its_tfm_width`. The size is the font's size; TeX
9//! scales by the design size when `\font` has no `at` (tex.web §568; SYNC_STATUS 58f residual).
10use std::{cell::RefCell, rc::Rc};
11
12use rustc_hash::FxHashMap;
13
14use crate::util::pathname;
15
16/// The dimension tables of one TFM (tftopl.web / tex.web §539-545).
17pub struct Tfm {
18  /// The design size in points (header word 1, a fix_word in points; tex.web §568); `None` when
19  /// the header has no such word or it is below 1pt, which TeX rejects as a bad TFM.
20  pub design_size: Option<f64>,
21  bc:              usize,
22  char_info:       Vec<[u8; 4]>,
23  widths:          Vec<[u8; 4]>,
24  heights:         Vec<[u8; 4]>,
25  depths:          Vec<[u8; 4]>,
26}
27
28thread_local! {
29  static TFM_CACHE: RefCell<FxHashMap<String, Option<Rc<Tfm>>>> =
30    RefCell::new(FxHashMap::default());
31}
32
33/// Forgets the TFMs read so far, misses included: a document may ship its own `.tfm`, so the
34/// next document must not be sized from it (`reset_conversion_state`, at `initialize_report`, per paper in a
35/// persistent worker; `reset_thread_engine`).
36pub fn reset_tfm_cache() { TFM_CACHE.with(|cache| cache.borrow_mut().clear()); }
37
38/// The TFM of the font named `name` (`line10`), found through kpathsea; `None` when there is
39/// no such file or it is no TFM. Cached per name.
40pub fn tfm_for(name: &str) -> Option<Rc<Tfm>> {
41  TFM_CACHE.with(|cache| {
42    if let Some(hit) = cache.borrow().get(name) {
43      return hit.clone();
44    }
45    let file = format!("{name}.tfm");
46    let parsed = pathname::kpsewhich(&[file.as_str()])
47      .and_then(|path| std::fs::read(path).ok())
48      .and_then(|bytes| Tfm::parse(&bytes))
49      .map(Rc::new);
50    cache.borrow_mut().insert(name.to_string(), parsed.clone());
51    parsed
52  })
53}
54
55impl Tfm {
56  /// tex.web §540: twelve halfwords `lf lh bc ec nw nh nd ni nl nk ne np`, then the `lh`-word
57  /// header, the char_info words for `bc..=ec`, and the width, height and depth tables.
58  fn parse(b: &[u8]) -> Option<Tfm> {
59    if b.len() < 24 {
60      return None;
61    }
62    let hw = |i: usize| u16::from_be_bytes([b[2 * i], b[2 * i + 1]]) as usize;
63    let (lf, lh, bc, ec, nw, nh, nd) = (hw(0), hw(1), hw(2), hw(3), hw(4), hw(5), hw(6));
64    if lf * 4 != b.len() || bc > ec + 1 || ec > 255 {
65      return None; // JFM/OFM headers differ
66    }
67    let words = |start: usize, n: usize| -> Option<Vec<[u8; 4]>> {
68      (0..n)
69        .map(|i| {
70          let o = start + 4 * i;
71          b.get(o..o + 4).map(|w| [w[0], w[1], w[2], w[3]])
72        })
73        .collect()
74    };
75    let char_start = 24 + 4 * lh;
76    let nc = (ec + 1).saturating_sub(bc);
77    let width_start = char_start + 4 * nc;
78    let height_start = width_start + 4 * nw;
79    let depth_start = height_start + 4 * nh;
80    let design = (lh >= 2)
81      .then(|| {
82        b.get(28..32)
83          .map(|w| i32::from_be_bytes([w[0], w[1], w[2], w[3]]))
84      })
85      .flatten()
86      .filter(|&fix| fix >= 1 << 20);
87    Some(Tfm {
88      design_size: design.map(|fix| f64::from(fix) / f64::from(1 << 20)),
89      bc,
90      char_info: words(char_start, nc)?,
91      widths: words(width_start, nw)?,
92      heights: words(height_start, nh)?,
93      depths: words(depth_start, nd)?,
94    })
95  }
96
97  /// Width, height and depth in scaled points of character `code` at size `at` (sp), or `None`
98  /// when the font has no such character (a zero width index, tex.web §554).
99  pub fn char_dims(&self, code: u32, at: i64) -> Option<(i64, i64, i64)> {
100    let info = self.char_info.get((code as usize).checked_sub(self.bc)?)?;
101    let (wi, hi, di) = (
102      info[0] as usize,
103      (info[1] >> 4) as usize,
104      (info[1] & 0xF) as usize,
105    );
106    if wi == 0 {
107      return None;
108    }
109    let scaled = |table: &[[u8; 4]], i: usize| table.get(i).map_or(0, |fix| store_scaled(*fix, at));
110    Some((
111      scaled(&self.widths, wi),
112      scaled(&self.heights, hi),
113      scaled(&self.depths, di),
114    ))
115  }
116}
117
118/// tex.web §571-572 `store_scaled`: a fix_word times the size `z`, computed exactly as TeX does
119/// (so line10's 10pt arrowhead is 10.0pt, not 10.00002pt).
120fn store_scaled(fix: [u8; 4], size: i64) -> i64 {
121  let (mut z, mut alpha) = (size, 16_i64);
122  while z >= 0o40000000 {
123    z /= 2;
124    alpha += alpha;
125  }
126  let beta = 256 / alpha;
127  alpha *= z;
128  let [a, b, c, d] = fix.map(i64::from);
129  let sw = (((d * z) / 0o400 + c * z) / 0o400 + b * z) / beta;
130  match a {
131    0 => sw,
132    255 => sw - alpha,
133    _ => 0, // not a valid fix_word (tex.web aborts the load)
134  }
135}
136
137#[cfg(test)]
138mod tests {
139  use super::*;
140
141  #[test]
142  fn store_scaled_is_exact_for_the_design_size() {
143    // 1.0 as a fix_word is 0x00100000; at 10pt it is exactly 655360sp.
144    assert_eq!(store_scaled([0, 0x10, 0, 0], 655360), 655360);
145    // -0.5 is 0xFFF80000.
146    assert_eq!(store_scaled([255, 0xF8, 0, 0], 655360), -327680);
147  }
148}