latexml_core/common/font/
coverage.rs1use std::{cell::RefCell, rc::Rc};
20
21use rustc_hash::{FxHashMap, FxHashSet};
22
23#[derive(Debug)]
25pub struct GlyphCoverage {
26 set: FxHashSet<u32>,
27}
28
29impl GlyphCoverage {
30 pub fn contains(&self, code: u32) -> bool { self.set.contains(&code) }
32
33 pub fn len(&self) -> usize { self.set.len() }
35
36 pub fn is_empty(&self) -> bool { self.set.is_empty() }
38}
39
40thread_local! {
41 static COVERAGE_CACHE: RefCell<FxHashMap<String, Option<Rc<GlyphCoverage>>>> =
42 RefCell::new(FxHashMap::default());
43 static FONT_INDEX: RefCell<Option<Rc<FontIndex>>> = const { RefCell::new(None) };
44}
45
46pub fn coverage_for_file(path: &str) -> Option<Rc<GlyphCoverage>> {
51 if !crate::util::pathname::read_allowed(path) {
52 if crate::util::pathname::refused_exists(path) {
53 crate::util::pathname::probing(|| crate::util::pathname::refuse(path));
54 }
55 return None;
56 }
57 COVERAGE_CACHE.with(|cache| {
58 if let Some(hit) = cache.borrow().get(path) {
59 return hit.clone();
60 }
61 let parsed = std::fs::read(path).ok().and_then(|bytes| {
62 let lower = path.to_ascii_lowercase();
63 if lower.ends_with(".tfm") {
64 parse_tfm(&bytes)
65 } else {
66 parse_sfnt_cmap(&bytes)
67 }
68 });
69 let entry = parsed.map(|set| Rc::new(GlyphCoverage { set }));
70 cache.borrow_mut().insert(path.to_string(), entry.clone());
71 entry
72 })
73}
74
75fn parse_tfm(b: &[u8]) -> Option<FxHashSet<u32>> {
81 if b.len() < 24 {
82 return None;
83 }
84 let hw = |i: usize| u16::from_be_bytes([b[2 * i], b[2 * i + 1]]) as usize;
85 let (lf, lh, bc, ec) = (hw(0), hw(1), hw(2), hw(3));
86 if lf * 4 != b.len() || bc > ec + 1 || ec > 255 {
87 return None; }
89 let mut set = FxHashSet::default();
90 let start = 24 + 4 * lh;
91 if bc <= ec {
92 for c in bc..=ec {
93 let off = start + 4 * (c - bc);
94 if off + 4 > b.len() {
95 break;
96 }
97 if b[off] != 0 {
98 set.insert(c as u32);
99 }
100 }
101 }
102 Some(set)
103}
104
105fn rd16(b: &[u8], o: usize) -> Option<u16> {
110 Some(u16::from_be_bytes([*b.get(o)?, *b.get(o + 1)?]))
111}
112fn rd32(b: &[u8], o: usize) -> Option<u32> {
113 Some(u32::from_be_bytes([
114 *b.get(o)?,
115 *b.get(o + 1)?,
116 *b.get(o + 2)?,
117 *b.get(o + 3)?,
118 ]))
119}
120
121fn sfnt_base(b: &[u8]) -> Option<usize> {
123 if b.get(0..4)? == b"ttcf" {
124 Some(rd32(b, 12)? as usize)
125 } else {
126 Some(0)
127 }
128}
129
130fn sfnt_table(b: &[u8], tag: &[u8; 4]) -> Option<(usize, usize)> {
132 let base = sfnt_base(b)?;
133 let num_tables = rd16(b, base + 4)? as usize;
134 for i in 0..num_tables {
135 let rec = base + 12 + 16 * i;
136 if b.get(rec..rec + 4)? == tag {
137 let off = rd32(b, rec + 8)? as usize;
138 let len = rd32(b, rec + 12)? as usize;
139 return if off.checked_add(len)? <= b.len() {
140 Some((off, len))
141 } else {
142 None
143 };
144 }
145 }
146 None
147}
148
149fn parse_sfnt_cmap(b: &[u8]) -> Option<FxHashSet<u32>> {
150 let (off, len) = sfnt_table(b, b"cmap")?;
151 let c = &b[off..off + len];
152 let n = rd16(c, 2)? as usize;
153 let mut subtables: Vec<(u8, u16, u16, usize)> = Vec::with_capacity(n);
154 for i in 0..n {
155 let rec = 4 + 8 * i;
156 let platform = rd16(c, rec)?;
157 let encoding = rd16(c, rec + 2)?;
158 let sub_off = rd32(c, rec + 4)? as usize;
159 let rank = match (platform, encoding) {
161 (3, 10) => 0,
162 (0, 4) | (0, 6) => 1,
163 (3, 1) => 2,
164 (0, _) => 3,
165 _ => 4,
166 };
167 subtables.push((rank, platform, encoding, sub_off));
168 }
169 subtables.sort_by_key(|s| s.0);
170 for (_, _, _, sub_off) in subtables {
171 if let Some(set) = parse_cmap_subtable(c, sub_off) {
172 return Some(set);
173 }
174 }
175 None
176}
177
178fn parse_cmap_subtable(c: &[u8], off: usize) -> Option<FxHashSet<u32>> {
179 let mut set = FxHashSet::default();
180 match rd16(c, off)? {
181 0 => {
182 for code in 0..256usize {
183 if *c.get(off + 6 + code)? != 0 {
184 set.insert(code as u32);
185 }
186 }
187 },
188 4 => {
189 let seg_x2 = rd16(c, off + 6)? as usize;
190 let segs = seg_x2 / 2;
191 let end_codes = off + 14;
192 let start_codes = end_codes + seg_x2 + 2;
193 let deltas = start_codes + seg_x2;
194 let range_offsets = deltas + seg_x2;
195 for s in 0..segs {
196 let end = rd16(c, end_codes + 2 * s)? as u32;
197 let start = rd16(c, start_codes + 2 * s)? as u32;
198 let delta = rd16(c, deltas + 2 * s)?;
199 let range_offset = rd16(c, range_offsets + 2 * s)? as usize;
200 if start > end || start == 0xFFFF {
201 continue;
202 }
203 for code in start..=end {
204 let glyph = if range_offset == 0 {
205 (code as u16).wrapping_add(delta)
206 } else {
207 let addr = range_offsets + 2 * s + range_offset + 2 * (code - start) as usize;
208 let g = rd16(c, addr)?;
209 if g == 0 { 0 } else { g.wrapping_add(delta) }
210 };
211 if glyph != 0 {
212 set.insert(code);
213 }
214 }
215 }
216 },
217 6 => {
218 let first = rd16(c, off + 6)? as u32;
219 let count = rd16(c, off + 8)? as usize;
220 for i in 0..count {
221 if rd16(c, off + 10 + 2 * i)? != 0 {
222 set.insert(first + i as u32);
223 }
224 }
225 },
226 12 => {
227 let groups = rd32(c, off + 12)? as usize;
228 for g in 0..groups {
229 let rec = off + 16 + 12 * g;
230 let start = rd32(c, rec)?;
231 let end = rd32(c, rec + 4)?;
232 let start_glyph = rd32(c, rec + 8)?;
233 if start > end || end > 0x10FFFF {
234 continue;
235 }
236 for code in start..=end {
237 if start_glyph + (code - start) != 0 {
238 set.insert(code);
239 }
240 }
241 }
242 },
243 _ => return None,
244 }
245 Some(set)
246}
247
248struct FontIndex {
261 files: FxHashMap<String, String>,
263}
264
265fn texmf_trees() -> Vec<String> {
266 let mut trees = Vec::new();
267 for var in ["TEXMFDIST", "TEXMFLOCAL"] {
268 if let Ok(out) = crate::util::pathname::tex_tool_command("kpsewhich")
269 .arg(format!("-var-value={var}"))
270 .output()
271 {
272 let dir = String::from_utf8_lossy(&out.stdout).trim().to_string();
273 let dir = crate::util::pathname::trim_texmf_root(&dir).unwrap_or(dir);
275 if !dir.is_empty() && std::path::Path::new(&format!("{dir}/ls-R")).exists() {
276 trees.push(dir);
277 }
278 }
279 }
280 trees
281}
282
283fn font_index() -> Rc<FontIndex> {
284 FONT_INDEX.with(|slot| {
285 if let Some(idx) = slot.borrow().as_ref() {
286 return Rc::clone(idx);
287 }
288 let mut files = FxHashMap::default();
289 for tree in texmf_trees() {
290 let Ok(text) = std::fs::read_to_string(format!("{tree}/ls-R")) else {
291 continue;
292 };
293 let mut dir = String::new();
294 for line in text.lines() {
295 let l = line.trim();
296 if l.is_empty() || l.starts_with('%') {
297 continue;
298 }
299 if let Some(d) = l.strip_suffix(':') {
300 dir = format!("{tree}/{}", d.trim_start_matches("./"));
301 continue;
302 }
303 let lower = l.to_ascii_lowercase();
304 if lower.ends_with(".otf")
305 || lower.ends_with(".ttf")
306 || lower.ends_with(".ttc")
307 || lower.ends_with(".tfm")
308 {
309 files.entry(lower).or_insert_with(|| format!("{dir}/{l}"));
310 }
311 }
312 }
313 let idx = Rc::new(FontIndex { files });
314 *slot.borrow_mut() = Some(Rc::clone(&idx));
315 idx
316 })
317}
318
319pub fn font_file_path(basename: &str) -> Option<String> {
321 font_index()
322 .files
323 .get(&basename.to_ascii_lowercase())
324 .cloned()
325}
326
327fn squash(s: &str) -> String {
328 s.chars()
329 .filter(|c| c.is_ascii_alphanumeric())
330 .map(|c| c.to_ascii_lowercase())
331 .collect()
332}
333
334pub fn resolve_fontspec_file(spec: &str) -> Option<String> {
337 let name = spec
338 .trim()
339 .trim_start_matches('[')
340 .trim_end_matches(']')
341 .trim();
342 let name = name.split('/').next().unwrap_or(name).trim();
344 if name.is_empty() {
345 return None;
346 }
347 let lower = name.to_ascii_lowercase();
348 if [".otf", ".ttf", ".ttc"].iter().any(|e| lower.ends_with(e)) {
349 return font_file_path(name);
350 }
351 let idx = font_index();
352 let key = squash(name);
354 let mut best: Option<(u8, &String, &String)> = None;
355 for (base, path) in &idx.files {
356 if base.ends_with(".tfm") {
357 continue;
358 }
359 let stem = squash(base.rsplit_once('.').map(|(s, _)| s).unwrap_or(base));
360 let rank = if stem == key {
361 0
362 } else if stem == format!("{key}regular") || stem == format!("{key}r") {
363 1
364 } else if stem == format!("{key}book") || stem == format!("{key}roman") {
365 2
366 } else {
367 continue;
368 };
369 if best.is_none_or(|(r, b, _)| rank < r || (rank == r && base.len() < b.len())) {
370 best = Some((rank, base, path));
371 }
372 }
373 if let Some((_, _, path)) = best {
374 return Some(path.clone());
375 }
376 let families = family_index();
378 let mut best: Option<(u8, &String)> = None;
379 if let Some(entries) = families.get(&key) {
380 for (path, regular) in entries {
381 let rank = if *regular { 0 } else { 1 };
382 if best.is_none_or(|(r, b)| rank < r || (rank == r && path.len() < b.len())) {
383 best = Some((rank, path));
384 }
385 }
386 }
387 best.map(|(_, p)| p.clone())
388}
389
390type FamilyIndex = FxHashMap<String, Vec<(String, bool)>>;
392
393thread_local! {
394 static FAMILY_INDEX: RefCell<Option<Rc<FamilyIndex>>> = const { RefCell::new(None) };
395}
396
397fn family_index() -> Rc<FamilyIndex> {
400 FAMILY_INDEX.with(|slot| {
401 if let Some(idx) = slot.borrow().as_ref() {
402 return Rc::clone(idx);
403 }
404 let mut map: FamilyIndex = FxHashMap::default();
405 for (base, path) in &font_index().files {
406 if base.ends_with(".tfm") {
407 continue;
408 }
409 let Some((families, subfamilies)) = sfnt_names_at(path) else {
410 continue;
411 };
412 let regular = subfamilies.iter().any(|s| {
413 matches!(
414 s.to_ascii_lowercase().as_str(),
415 "regular" | "book" | "roman" | "normal"
416 )
417 });
418 let mut seen: Vec<String> = Vec::new();
419 for f in families {
420 let k = squash(&f);
421 if k.is_empty() || seen.contains(&k) {
422 continue;
423 }
424 seen.push(k.clone());
425 map.entry(k).or_default().push((path.clone(), regular));
426 }
427 }
428 let idx = Rc::new(map);
429 *slot.borrow_mut() = Some(Rc::clone(&idx));
430 idx
431 })
432}
433
434fn sfnt_names_at(path: &str) -> Option<(Vec<String>, Vec<String>)> {
437 use std::io::{Read, Seek, SeekFrom};
438 let mut f = std::fs::File::open(path).ok()?;
439 let mut head = [0u8; 16];
440 f.read_exact(&mut head).ok()?;
441 let base = if &head[0..4] == b"ttcf" {
442 rd32(&head, 12)? as u64
443 } else {
444 0
445 };
446 let mut dir_head = [0u8; 12];
447 f.seek(SeekFrom::Start(base)).ok()?;
448 f.read_exact(&mut dir_head).ok()?;
449 let num_tables = rd16(&dir_head, 4)? as usize;
450 if num_tables == 0 || num_tables > 64 {
451 return None;
452 }
453 let mut dir = vec![0u8; 16 * num_tables];
454 f.read_exact(&mut dir).ok()?;
455 for i in 0..num_tables {
456 let rec = 16 * i;
457 if &dir[rec..rec + 4] == b"name" {
458 let off = rd32(&dir, rec + 8)? as u64;
459 let len = rd32(&dir, rec + 12)? as usize;
460 if len > 1 << 20 {
461 return None;
462 }
463 let mut table = vec![0u8; len];
464 f.seek(SeekFrom::Start(off)).ok()?;
465 f.read_exact(&mut table).ok()?;
466 return parse_name_table(&table);
467 }
468 }
469 None
470}
471
472#[cfg(test)]
474fn sfnt_names(b: &[u8]) -> Option<(Vec<String>, Vec<String>)> {
475 let (off, len) = sfnt_table(b, b"name")?;
476 parse_name_table(&b[off..off + len])
477}
478
479fn parse_name_table(t: &[u8]) -> Option<(Vec<String>, Vec<String>)> {
481 let count = rd16(t, 2)? as usize;
482 let strings = rd16(t, 4)? as usize;
483 let mut families = Vec::new();
484 let mut subfamilies = Vec::new();
485 for i in 0..count {
486 let rec = 6 + 12 * i;
487 let platform = rd16(t, rec)?;
488 let name_id = rd16(t, rec + 6)?;
489 let slen = rd16(t, rec + 8)? as usize;
490 let soff = rd16(t, rec + 10)? as usize;
491 if !matches!(name_id, 1 | 2 | 16 | 17) {
492 continue;
493 }
494 let Some(raw) = t.get(strings + soff..strings + soff + slen) else {
495 continue;
496 };
497 let text = if platform == 1 {
498 raw.iter().map(|&c| c as char).collect::<String>()
499 } else {
500 let units: Vec<u16> = raw
501 .as_chunks::<2>()
502 .0
503 .iter()
504 .map(|p| u16::from_be_bytes(*p))
505 .collect();
506 String::from_utf16_lossy(&units)
507 };
508 if matches!(name_id, 1 | 16) {
509 families.push(text)
510 } else {
511 subfamilies.push(text)
512 }
513 }
514 Some((families, subfamilies))
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520
521 #[test]
522 fn tfm_coverage_of_cmr10_is_the_128_slot_ot1_font() {
523 let Some(path) = font_file_path("cmr10.tfm") else {
524 return;
525 }; let cov = coverage_for_file(&path).expect("cmr10.tfm parses");
527 assert_eq!(cov.len(), 128);
528 assert!(cov.contains(b'A' as u32));
529 assert!(!cov.contains(200));
530 }
531
532 #[test]
533 fn opentype_cmap_bounds_coverage_to_real_glyphs() {
534 let Some(path) = resolve_fontspec_file("Latin Modern Sans") else {
535 return;
536 };
537 let cov = coverage_for_file(&path).expect("otf parses");
538 assert!(cov.contains(b'A' as u32));
539 assert!(!cov.contains(0x0000), "control block is not covered");
540 assert!(!cov.contains(0x0080));
541 assert!(
542 cov.len() > 200 && cov.len() < 2000,
543 "lmsans10-regular has ~800 glyphs: {}",
544 cov.len()
545 );
546 }
547
548 #[test]
549 fn name_table_reader_matches_whole_file_parse() {
550 let Some(path) = font_file_path("lmsans10-regular.otf") else {
551 return;
552 };
553 let whole = std::fs::read(&path)
554 .map(|b| sfnt_names(&b).expect("names"))
555 .expect("read");
556 let partial = sfnt_names_at(&path).expect("partial names");
557 assert_eq!(whole, partial);
558 assert!(
559 partial.0.iter().any(|f| f == "Latin Modern Sans"),
560 "{partial:?}"
561 );
562 }
563
564 #[test]
565 fn fontspec_file_names_and_family_names_resolve() {
566 if font_file_path("NewCMMath-Regular.otf").is_none()
571 || font_file_path("texgyrepagella-regular.otf").is_none()
572 {
573 return;
574 }
575 let direct = resolve_fontspec_file("NewCMMath-Regular.otf");
576 assert!(direct.is_some_and(|p| p.ends_with("NewCMMath-Regular.otf")));
577 let stem = resolve_fontspec_file("TeX Gyre Pagella");
578 assert!(
579 stem
580 .as_deref()
581 .is_some_and(|p| p.to_ascii_lowercase().contains("texgyrepagella-regular")),
582 "{stem:?}"
583 );
584 }
585}