1use std::fmt::Write as _;
11use std::path::Path;
12
13use crate::py;
14use indexmap::IndexMap;
15use thiserror::Error;
16
17#[derive(Debug, Error)]
19pub enum Error {
20 #[error("{0}")]
22 Tfm(String),
23 #[error(transparent)]
25 Io(#[from] std::io::Error),
26 #[error("{0}")]
29 Python(String),
30}
31
32pub type Result<T> = std::result::Result<T, Error>;
34
35pub const VANILLA: u8 = 0;
37pub const MATHSY: u8 = 1;
39pub const MATHEX: u8 = 2;
41
42const BASE_PARAMS: [&str; 7] = [
43 "SLANT",
44 "SPACE",
45 "STRETCH",
46 "SHRINK",
47 "XHEIGHT",
48 "QUAD",
49 "EXTRASPACE",
50];
51
52const MATHSY_PARAMS: [&str; 15] = [
53 "NUM1",
54 "NUM2",
55 "NUM3",
56 "DENOM1",
57 "DENOM2",
58 "SUP1",
59 "SUP2",
60 "SUP3",
61 "SUB1",
62 "SUB2",
63 "SUPDROP",
64 "SUBDROP",
65 "DELIM1",
66 "DELIM2",
67 "AXISHEIGHT",
68];
69
70const MATHEX_PARAMS: [&str; 6] = [
71 "DEFAULTRULETHICKNESS",
72 "BIGOPSPACING1",
73 "BIGOPSPACING2",
74 "BIGOPSPACING3",
75 "BIGOPSPACING4",
76 "BIGOPSPACING5",
77];
78
79const NO_TAG: u8 = 0;
80const LIG_TAG: u8 = 1;
81const LIST_TAG: u8 = 2;
82const EXT_TAG: u8 = 3;
83
84const STOP_FLAG: u8 = 128;
85const KERN_FLAG: u8 = 128;
86
87#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum HeaderString {
91 Str(String),
93 Bytes(Vec<u8>),
95}
96
97impl std::fmt::Display for HeaderString {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 match self {
101 HeaderString::Str(s) => f.write_str(s),
102 HeaderString::Bytes(b) => f.write_str(&py::bytes_repr(b)),
103 }
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum Face {
111 Int(u8),
113 Str(String),
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum LigOp {
121 Str(String),
123 Code(u8),
125}
126
127#[derive(Debug, Clone, PartialEq, Default)]
129pub struct CharInfo {
130 pub width: f64,
132 pub height: Option<f64>,
134 pub depth: Option<f64>,
136 pub italic: Option<f64>,
138 pub nextlarger: Option<u8>,
140 pub varchar: Option<IndexMap<&'static str, i64>>,
143}
144
145impl CharInfo {
146 pub fn repr(&self) -> String {
148 let mut items = vec![format!("'width': {}", py::float_repr(self.width))];
149 for (name, v) in [
150 ("height", self.height),
151 ("depth", self.depth),
152 ("italic", self.italic),
153 ] {
154 if let Some(v) = v {
155 items.push(format!("'{name}': {}", py::float_repr(v)));
156 }
157 }
158 if let Some(n) = self.nextlarger {
159 items.push(format!("'nextlarger': {n}"));
160 }
161 if let Some(v) = &self.varchar {
162 let inner: Vec<String> = v.iter().map(|(k, v)| format!("'{k}': {v}")).collect();
163 items.push(format!("'varchar': {{{}}}", inner.join(", ")));
164 }
165 format!("{{{}}}", items.join(", "))
166 }
167}
168
169#[derive(Debug, Clone, PartialEq)]
171pub struct Tfm {
172 pub checksum: u32,
174 pub designsize: f64,
176 pub codingscheme: String,
178 pub family: HeaderString,
180 pub seven_bit_safe_flag: bool,
182 pub face: Face,
184 pub extraheader: IndexMap<String, i32>,
187 pub fonttype: u8,
189 pub fontdimens: IndexMap<String, f64>,
191 pub right_boundary_char: Option<u8>,
193 pub left_boundary_char: Option<u16>,
195 pub chars: IndexMap<u16, CharInfo>,
197 pub kerning: IndexMap<u16, IndexMap<u8, f64>>,
200 pub ligatures: IndexMap<u16, IndexMap<u8, (LigOp, u8)>>,
203}
204
205fn tfm_err(msg: impl Into<String>) -> Error {
206 Error::Tfm(msg.into())
207}
208
209fn struct_error(n: usize) -> Error {
210 Error::Python(format!(
211 "struct.error: unpack requires a buffer of {n} bytes"
212 ))
213}
214
215fn index_error() -> Error {
216 Error::Python("IndexError: index out of range".into())
217}
218
219struct Data<'a>(&'a [u8]);
221
222impl Data<'_> {
223 fn byte(&self, i: i64) -> Result<u8> {
224 usize::try_from(i)
225 .ok()
226 .and_then(|i| self.0.get(i).copied())
227 .ok_or_else(index_error)
228 }
229
230 fn bytes(&self, i: i64, n: usize) -> Result<&[u8]> {
231 usize::try_from(i)
232 .ok()
233 .and_then(|i| self.0.get(i..i.checked_add(n)?))
234 .ok_or_else(|| struct_error(n))
235 }
236
237 fn fixed(&self, i: i64) -> Result<f64> {
239 let b = self.bytes(i, 4)?;
240 Ok(i32::from_be_bytes([b[0], b[1], b[2], b[3]]) as f64 / (1 << 20) as f64)
241 }
242
243 fn lig_kern_command(&self, i: i64) -> Result<[u8; 4]> {
245 let b = self.bytes(i, 4)?;
246 Ok([b[0], b[1], b[2], b[3]])
247 }
248}
249
250fn pascal(b: &[u8]) -> HeaderString {
252 let n = (b[0] as usize).min(b.len() - 1);
253 let s = &b[1..1 + n];
254 if s.is_ascii() {
255 HeaderString::Str(String::from_utf8_lossy(s).into_owned())
256 } else {
257 HeaderString::Bytes(s.to_vec())
258 }
259}
260
261const SIZE_NAMES: [&str; 12] = [
262 "lf", "lh", "bc", "ec", "nw", "nh", "nd", "ni", "nl", "nk", "ne", "np",
263];
264
265impl Tfm {
266 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
268 Self::from_bytes(&std::fs::read(path)?)
269 }
270
271 pub fn from_bytes(data: &[u8]) -> Result<Self> {
273 if data.len() < 24 {
274 return Err(tfm_err("Too short input file"));
275 }
276 let mut sizes = [0i64; 12];
277 for (i, s) in sizes.iter_mut().enumerate() {
278 *s = i16::from_be_bytes([data[2 * i], data[2 * i + 1]]) as i64;
279 }
280 let [lf, lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np] = sizes;
281
282 if lf < 0 {
287 return Err(tfm_err("The file claims to have negative or zero length!"));
288 }
289 if (data.len() as i64) < lf * 4 {
290 return Err(tfm_err("The file has fewer bytes than it claims!"));
291 }
292 for (_name, length) in SIZE_NAMES.iter().zip(sizes) {
293 if length < 0 {
294 return Err(tfm_err("The subfile size: '{name}' is negative!"));
297 }
298 }
299 if lh < 2 {
300 return Err(tfm_err(format!("The header length is only {lh}!")));
301 }
302 if bc > ec + 1 || ec > 255 {
303 return Err(tfm_err(format!(
304 "The character code range {bc}..{ec} is illegal!"
305 )));
306 }
307 if nw == 0 || nh == 0 || nd == 0 || ni == 0 {
308 return Err(tfm_err("Incomplete subfiles for character dimensions!"));
309 }
310 if ne > 256 {
311 return Err(Error::Python("NameError: name 'ne' is not defined".into()));
313 }
314 if lf != 6 + lh + (ec - bc + 1) + nw + nh + nd + ni + nl + nk + ne + np {
315 return Err(tfm_err(
316 "Subfile sizes don\u{2019}t add up to the stated total",
317 ));
318 }
319
320 let char_base = 6 + lh - bc;
322 let width_base = char_base + ec + 1;
323 let height_base = width_base + nw;
324 let depth_base = height_base + nh;
325 let italic_base = depth_base + nd;
326 let lig_kern_base = italic_base + ni;
327 let kern_base = lig_kern_base + nl;
328 let exten_base = kern_base + nk;
329 let param_base = exten_base + ne;
330
331 let d = Data(data);
332 let char_info = |c: i64| 4 * (char_base + c);
333 let width_index = |c: i64| d.byte(char_info(c));
334 let noneexistent =
335 |c: i64| -> Result<bool> { Ok(c < bc || c > ec || width_index(c)? == 0) };
336 let height_index = |c: i64| -> Result<u8> { Ok(d.byte(char_info(c) + 1)? / 16) };
337 let depth_index = |c: i64| -> Result<u8> { Ok(d.byte(char_info(c) + 1)? % 16) };
338 let italic_index = |c: i64| -> Result<u8> { Ok(d.byte(char_info(c) + 2)? / 4) };
339 let tag = |c: i64| -> Result<u8> { Ok(d.byte(char_info(c) + 2)? % 4) };
340 let remainder = |c: i64| d.byte(char_info(c) + 3);
341 let lig_step = |i: i64| 4 * (lig_kern_base + i);
342
343 let mut tfm = Tfm {
345 checksum: 0,
346 designsize: 0.0,
347 codingscheme: String::new(),
348 family: HeaderString::Str(String::new()),
349 seven_bit_safe_flag: false,
350 face: Face::Int(0),
351 extraheader: IndexMap::new(),
352 fonttype: VANILLA,
353 fontdimens: IndexMap::new(),
354 right_boundary_char: None,
355 left_boundary_char: None,
356 chars: IndexMap::new(),
357 kerning: IndexMap::new(),
358 ligatures: IndexMap::new(),
359 };
360
361 let offset = 24;
362 let length = lh * 4;
363 let mut codingscheme = HeaderString::Str(String::new());
364 if length >= 8 {
365 let h = d.bytes(
366 offset,
367 if length >= 72 {
368 72
369 } else if length >= 68 {
370 68
371 } else if length >= 48 {
372 48
373 } else {
374 8
375 },
376 )?;
377 tfm.checksum = u32::from_be_bytes([h[0], h[1], h[2], h[3]]);
378 tfm.designsize = i32::from_be_bytes([h[4], h[5], h[6], h[7]]) as f64 / (1 << 20) as f64;
379 if length >= 48 {
380 codingscheme = pascal(&h[8..48]);
381 }
382 if length >= 68 {
383 tfm.family = pascal(&h[48..68]);
384 }
385 if length >= 72 {
386 tfm.seven_bit_safe_flag = h[68] != 0;
387 let face = h[71];
388 tfm.face = if face < 18 {
389 let s = (face % 2) as usize;
390 let b = (face / 2) as usize;
391 Face::Str(
392 [
393 "MBL".as_bytes()[b % 3] as char,
394 "RI".as_bytes()[s] as char,
395 "RCE".as_bytes()[b / 3] as char,
396 ]
397 .iter()
398 .collect(),
399 )
400 } else {
401 Face::Int(face)
402 };
403 for i in 0..(lh - 18).max(0) {
404 let b = d.bytes(offset + 72 + 4 * i, 4)?;
405 tfm.extraheader.insert(
406 format!("HEADER{}", i + 18),
407 i32::from_be_bytes([b[0], b[1], b[2], b[3]]),
408 );
409 }
410 }
411 }
412 tfm.codingscheme = match codingscheme {
413 HeaderString::Str(s) => s,
414 HeaderString::Bytes(_) => {
416 return Err(Error::Python(
417 "TypeError: startswith first arg must be bytes or a tuple of bytes, not str"
418 .into(),
419 ));
420 }
421 };
422
423 let scheme = tfm.codingscheme.to_uppercase();
424 if scheme.starts_with("TEX MATH SY") {
425 tfm.fonttype = MATHSY;
426 } else if scheme.starts_with("TEX MATH EX") {
427 tfm.fonttype = MATHEX;
428 }
429
430 for i in 0..np {
431 let name = if i <= 6 {
432 BASE_PARAMS[i as usize].to_owned()
433 } else if tfm.fonttype == MATHSY && i <= 21 {
434 MATHSY_PARAMS[i as usize - 7].to_owned()
435 } else if tfm.fonttype == MATHEX && i <= 12 {
436 MATHEX_PARAMS[i as usize - 7].to_owned()
437 } else {
438 format!("PARAMETER{}", i + 1)
439 };
440 let v = d.fixed(4 * (param_base + i))?;
441 tfm.fontdimens.insert(name, v);
442 }
443
444 let mut lig_kern_map: IndexMap<i64, i64> = IndexMap::new();
445 if nl > 0 {
446 let cmd = d.lig_kern_command(lig_step(0))?;
447 if cmd[0] == 255 {
448 tfm.right_boundary_char = Some(cmd[1]);
449 }
450 let cmd = d.lig_kern_command(lig_step(nl - 1))?;
451 if cmd[0] == 255 {
452 tfm.left_boundary_char = Some(256);
453 lig_kern_map.insert(256, 256 * cmd[2] as i64 + cmd[3] as i64);
454 }
455 }
456
457 for c in bc..=ec {
458 if width_index(c)? == 0 {
459 continue;
460 }
461 let mut info = CharInfo {
462 width: d.fixed(4 * (width_base + width_index(c)? as i64))?,
463 ..CharInfo::default()
464 };
465 if height_index(c)? > 0 {
466 info.height = Some(d.fixed(4 * (height_base + height_index(c)? as i64))?);
467 }
468 if depth_index(c)? > 0 {
469 info.depth = Some(d.fixed(4 * (depth_base + depth_index(c)? as i64))?);
470 }
471 if italic_index(c)? > 0 {
472 info.italic = Some(d.fixed(4 * (italic_base + italic_index(c)? as i64))?);
473 }
474 match tag(c)? {
475 NO_TAG => {}
476 LIG_TAG => {
477 lig_kern_map.insert(c, remainder(c)? as i64);
478 }
479 LIST_TAG => info.nextlarger = Some(remainder(c)?),
480 EXT_TAG => {
481 let mut varchar = IndexMap::new();
482 let exten = 4 * (exten_base + remainder(c)? as i64);
483 for i in 0..4 {
484 let part = d.byte(exten + i)?;
485 if i == 3 || part > 0 {
486 let name = match i {
487 0 => "top",
488 1 => "mid",
489 2 => "bot",
490 _ => "rep",
491 };
492 let v = if noneexistent(part as i64)? {
493 c
494 } else {
495 part as i64
496 };
497 varchar.insert(name, v);
498 }
499 }
500 info.varchar = Some(varchar);
501 }
502 _ => {}
503 }
504 tfm.chars.insert(c as u16, info);
506 }
507
508 let mut items: Vec<(i64, i64)> = lig_kern_map.into_iter().collect();
509 items.sort();
510 for (c, mut i) in items {
511 let cmd = d.lig_kern_command(lig_step(i))?;
512 if cmd[0] > STOP_FLAG {
513 i = 256 * cmd[2] as i64 + cmd[3] as i64;
514 }
515 while i < nl {
516 let [skip_byte, next_char, op_byte, rem] = d.lig_kern_command(lig_step(i))?;
517 if skip_byte <= STOP_FLAG {
518 if op_byte >= KERN_FLAG {
519 let r = 256 * (op_byte - KERN_FLAG) as i64 + rem as i64;
520 let kern = d.fixed(4 * (kern_base + r))?;
521 tfm.kerning
522 .entry(c as u16)
523 .or_default()
524 .insert(next_char, kern);
525 } else {
526 let mut r = op_byte;
527 let lig = if r == 4 || (r > 7 && r != 11) {
528 LigOp::Code(r)
531 } else {
532 let mut lig = String::new();
533 if r % 4 > 1 {
534 lig.push('/');
535 }
536 lig.push_str("LIG");
537 if r % 2 != 0 {
538 lig.push('/');
539 }
540 while r > 3 {
541 lig.push('>');
542 r -= 4;
543 }
544 LigOp::Str(lig)
545 };
546 tfm.ligatures
547 .entry(c as u16)
548 .or_default()
549 .insert(next_char, (lig, rem));
550 }
551 }
552 if skip_byte >= STOP_FLAG {
553 break;
554 }
555 i += skip_byte as i64 + 1;
556 }
557 }
558 Ok(tfm)
559 }
560
561 pub fn repr(&self) -> String {
563 format!(
564 "<TFM for {} in {} at {}pt>",
565 self.family,
566 self.codingscheme,
567 py::format_g_lower(self.designsize, 6)
568 )
569 }
570}
571
572pub fn repr_kerning(d: &IndexMap<u8, f64>) -> String {
574 let mut s = String::from("{");
575 for (i, (k, v)) in d.iter().enumerate() {
576 if i > 0 {
577 s.push_str(", ");
578 }
579 let _ = write!(s, "{k}: {}", py::float_repr(*v));
580 }
581 s.push('}');
582 s
583}
584
585pub fn repr_ligatures(d: &IndexMap<u8, (LigOp, u8)>) -> String {
587 let mut s = String::from("{");
588 for (i, (k, (op, r))) in d.iter().enumerate() {
589 if i > 0 {
590 s.push_str(", ");
591 }
592 let op = match op {
593 LigOp::Str(o) => py::str_repr(o),
594 LigOp::Code(c) => c.to_string(),
595 };
596 let _ = write!(s, "{k}: ({op}, {r})");
597 }
598 s.push('}');
599 s
600}
601
602pub fn repr_fontdimens(d: &IndexMap<String, f64>) -> String {
604 let items: Vec<String> = d
605 .iter()
606 .map(|(k, v)| format!("{}: {}", py::str_repr(k), py::float_repr(*v)))
607 .collect();
608 format!("{{{}}}", items.join(", "))
609}