fontoxide-misc 0.1.0

Miscellaneous font utilities; a port of fontTools.misc, agl, afmLib and tfmLib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//! Port of `fontTools.afmLib`: reading and writing AFM (Adobe Font Metrics)
//! files.
//!
//! Like fontTools, this has been designed to read AFM files generated by
//! Fontographer: it does not implement the whole Adobe AFM specification, but
//! it should read most "common" AFM files.
//!
//! ```
//! use fontoxide_misc::afm_lib::{Afm, AttrValue};
//! let mut f = Afm::from_str(
//!     "StartFontMetrics 2.0\nFontName TestFont-Regular\nXHeight 500\n\
//!      C 65 ; WX 668 ; N A ; B 8 -25 660 666 ;\nKPX V A -60\nEndFontMetrics\n",
//! )?;
//! // Accessing a pair gets you the kern value.
//! assert_eq!(f.kerning(("V", "A")), Some(-60));
//! // Accessing a glyph name gets you metrics: (charnum, width, bounding box).
//! assert_eq!(f.char("A"), Some((65, 668, (8, -25, 660, 666))));
//! // Attributes are metadata.
//! assert_eq!(f.attr("FontName"), Some(&AttrValue::Str("TestFont-Regular".into())));
//! assert_eq!(f.attr("XHeight"), Some(&AttrValue::Int(500)));
//! // Attributes and items can also be set.
//! f.set_kerning(("A", "V"), -150);
//! f.set_attr("FontName", AttrValue::Str("TestFont Squished".into()));
//! # Ok::<(), fontoxide_misc::afm_lib::Error>(())
//! ```

use std::path::Path;

use indexmap::IndexMap;
use thiserror::Error;

/// Errors of this module.
#[derive(Debug, Error)]
pub enum Error {
	/// `error`: a syntax error in an AFM file.
	#[error("{0}")]
	Afm(String),
	/// The file could not be read or written.
	#[error(transparent)]
	Io(#[from] std::io::Error),
	/// Other Python exceptions fontTools raises on bad input (`ValueError`,
	/// `UnicodeDecodeError`, `AssertionError`, ...).
	#[error("{0}")]
	Python(String),
}

/// The result type of this module.
pub type Result<T> = std::result::Result<T, Error>;

/// The value of an attribute: an integer if the text is one, the bounding box of
/// `FontBBox`, or the text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttrValue {
	/// An integer (`int(rest)`).
	Int(i128),
	/// Text.
	Str(String),
	/// The four integers of `FontBBox`.
	BBox(i64, i64, i64, i64),
}

impl std::fmt::Display for AttrValue {
	/// `str(value)`; a bounding box as `"l b r t"`.
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			AttrValue::Int(i) => write!(f, "{i}"),
			AttrValue::Str(s) => f.write_str(s),
			AttrValue::BBox(l, b, r, t) => write!(f, "{l} {b} {r} {t}"),
		}
	}
}

/// Character metrics: code (-1 if unencoded), width and bounding box.
pub type CharMetrics = (i64, i64, (i64, i64, i64, i64));

/// A row of the char metrics being written: code, name, width, box.
type CharItem<'a> = (i64, &'a String, i64, (i64, i64, i64, i64));

/// A component of a composite glyph: base glyph name, x and y offsets.
pub type Component = (String, i64, i64);

/// The attributes written first, in this order (`preferredAttributeOrder`).
pub const PREFERRED_ATTRIBUTE_ORDER: [&str; 16] = [
	"FontName",
	"FullName",
	"FamilyName",
	"Weight",
	"ItalicAngle",
	"IsFixedPitch",
	"FontBBox",
	"UnderlinePosition",
	"UnderlineThickness",
	"Version",
	"Notice",
	"EncodingScheme",
	"CapHeight",
	"XHeight",
	"Ascender",
	"Descender",
];

const KEYWORDS: [&str; 10] = [
	"StartFontMetrics",
	"EndFontMetrics",
	"StartCharMetrics",
	"EndCharMetrics",
	"StartKernData",
	"StartKernPairs",
	"EndKernPairs",
	"EndKernData",
	"StartComposites",
	"EndComposites",
];

/// An AFM file (`AFM`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Afm {
	attrs: IndexMap<String, AttrValue>,
	chars: IndexMap<String, CharMetrics>,
	kerning: IndexMap<(String, String), i64>,
	comments: Vec<String>,
	composites: IndexMap<String, Vec<Component>>,
}

fn syntax_error(s: &str) -> Error {
	Error::Afm(format!(
		"syntax error in AFM file: {}",
		crate::py::str_repr(s)
	))
}

/// `\s` of Python `str` patterns, for the ASCII text of AFM files.
fn is_space(c: u8) -> bool {
	matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C | 0x1C..=0x1F)
}

/// A cursor for the regular expressions of fontTools, which match from the
/// start of the text.
struct Cursor<'a> {
	s: &'a str,
	pos: usize,
}

impl<'a> Cursor<'a> {
	fn new(s: &'a str) -> Self {
		Cursor { s, pos: 0 }
	}

	fn bytes(&self) -> &'a [u8] {
		self.s.as_bytes()
	}

	/// `\s*`, or `\s+` if `one`.
	fn space(&mut self, one: bool) -> Option<()> {
		let start = self.pos;
		while self.bytes().get(self.pos).is_some_and(|&c| is_space(c)) {
			self.pos += 1;
		}
		(!one || self.pos > start).then_some(())
	}

	fn lit(&mut self, lit: &str) -> Option<()> {
		if self.s[self.pos..].starts_with(lit) {
			self.pos += lit.len();
			Some(())
		} else {
			None
		}
	}

	fn take_while(&mut self, f: impl Fn(u8) -> bool) -> Option<&'a str> {
		let start = self.pos;
		while self.bytes().get(self.pos).is_some_and(|&c| f(c)) {
			self.pos += 1;
		}
		(self.pos > start).then(|| &self.s[start..self.pos])
	}

	/// `[.A-Za-z0-9_]+`.
	fn name(&mut self) -> Option<&'a str> {
		self.take_while(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'_')
	}

	/// `\d+`.
	fn digits(&mut self) -> Option<&'a str> {
		self.take_while(|c| c.is_ascii_digit())
	}

	/// `-?\d+`.
	fn int(&mut self) -> Option<&'a str> {
		let start = self.pos;
		if self.bytes().get(self.pos) == Some(&b'-') {
			self.pos += 1;
		}
		match self.digits() {
			Some(_) => Some(&self.s[start..self.pos]),
			None => {
				self.pos = start;
				None
			}
		}
	}

	/// `\s*;\s*`.
	fn semicolon(&mut self) -> Option<()> {
		self.space(false)?;
		self.lit(";")?;
		self.space(false)
	}
}

fn int(s: &str) -> Result<i64> {
	s.parse()
		.map_err(|_| Error::Python(format!("ValueError: invalid literal for int(): {s}")))
}

/// `str.splitlines()` of text read in universal newlines mode.
fn splitlines(data: &str) -> Vec<&str> {
	let mut lines = Vec::new();
	let bytes = data.as_bytes();
	let mut start = 0;
	let mut i = 0;
	while i < bytes.len() {
		match bytes[i] {
			b'\r' => {
				lines.push(&data[start..i]);
				if bytes.get(i + 1) == Some(&b'\n') {
					i += 1;
				}
				start = i + 1;
			}
			b'\n' | 0x0B | 0x0C | 0x1C..=0x1E => {
				lines.push(&data[start..i]);
				start = i + 1;
			}
			_ => {}
		}
		i += 1;
	}
	if start < bytes.len() {
		lines.push(&data[start..]);
	}
	lines
}

/// `str.strip()` for ASCII text.
fn strip(s: &str) -> &str {
	s.trim_matches(|c: char| c.is_ascii() && is_space(c as u8))
}

impl Afm {
	/// An empty AFM (`AFM()`).
	pub fn new() -> Self {
		Self::default()
	}

	/// Opens, reads and parses a file (`AFM(path)`).
	pub fn open(path: impl AsRef<Path>) -> Result<Self> {
		let mut afm = Self::new();
		afm.read(path)?;
		Ok(afm)
	}

	/// Parses the text of an AFM file.
	#[allow(clippy::should_implement_trait)]
	pub fn from_str(text: &str) -> Result<Self> {
		let mut afm = Self::new();
		afm.parse(text)?;
		Ok(afm)
	}

	/// Opens, reads and parses a file into this AFM (`read`).
	pub fn read(&mut self, path: impl AsRef<Path>) -> Result<()> {
		let data = std::fs::read(path)?;
		if let Some(i) = data.iter().position(|&b| b >= 0x80) {
			return Err(Error::Python(format!(
				"UnicodeDecodeError: 'ascii' codec can't decode byte 0x{:02x} in position {i}: ordinal not in range(128)",
				data[i]
			)));
		}
		let text = String::from_utf8(data).map_err(|e| Error::Python(e.to_string()))?;
		self.parse(&text)
	}

	/// Parses the text of an AFM file into this AFM.
	pub fn parse(&mut self, text: &str) -> Result<()> {
		for line in splitlines(text) {
			if strip(line).is_empty() {
				continue;
			}
			let pos = line
				.bytes()
				.position(|c| !c.is_ascii_alphabetic())
				.unwrap_or(line.len());
			if pos == 0 {
				return Err(syntax_error(line));
			}
			let word = &line[..pos];
			let rest = strip(&line[pos..]);
			if KEYWORDS.contains(&word) {
				continue;
			}
			match word {
				"C" => self.parsechar(rest)?,
				"KPX" => self.parsekernpair(rest)?,
				"CC" => self.parsecomposite(rest)?,
				_ => self.parseattr(word, rest)?,
			}
		}
		Ok(())
	}

	fn parsechar(&mut self, rest: &str) -> Result<()> {
		let mut c = Cursor::new(rest);
		let mut parse = || -> Option<[&str; 7]> {
			let charnum = c.int()?;
			c.semicolon()?;
			c.lit("WX")?;
			c.space(true)?;
			let width = c.int()?;
			c.semicolon()?;
			c.lit("N")?;
			c.space(true)?;
			let name = c.name()?;
			c.semicolon()?;
			c.lit("B")?;
			c.space(true)?;
			let l = c.int()?;
			c.space(true)?;
			let b = c.int()?;
			c.space(true)?;
			let r = c.int()?;
			c.space(true)?;
			let t = c.int()?;
			c.semicolon()?;
			Some([charnum, width, name, l, b, r, t])
		};
		let [charnum, width, name, l, b, r, t] = parse().ok_or_else(|| syntax_error(rest))?;
		self.chars.insert(
			name.to_owned(),
			(
				int(charnum)?,
				int(width)?,
				(int(l)?, int(b)?, int(r)?, int(t)?),
			),
		);
		Ok(())
	}

	fn parsekernpair(&mut self, rest: &str) -> Result<()> {
		let mut c = Cursor::new(rest);
		let mut parse = || -> Option<[&str; 3]> {
			let left = c.name()?;
			c.space(true)?;
			let right = c.name()?;
			c.space(true)?;
			let value = c.int()?;
			Some([left, right, value])
		};
		let [left, right, value] = parse().ok_or_else(|| syntax_error(rest))?;
		self.kerning
			.insert((left.to_owned(), right.to_owned()), int(value)?);
		Ok(())
	}

	fn parseattr(&mut self, word: &str, rest: &str) -> Result<()> {
		if word == "FontBBox" {
			let v: Vec<i64> = rest
				.split_ascii_whitespace()
				.map(|t| {
					crate::py::parse_int(t)
						.and_then(|i| i64::try_from(i).ok())
						.ok_or_else(|| {
							Error::Python(format!(
								"ValueError: invalid literal for int() with base 10: {}",
								crate::py::str_repr(t)
							))
						})
				})
				.collect::<Result<_>>()?;
			let [l, b, r, t] = v[..] else {
				return Err(Error::Python(format!(
					"ValueError: expected 4 values to unpack, got {}",
					v.len()
				)));
			};
			self.attrs
				.insert(word.to_owned(), AttrValue::BBox(l, b, r, t));
		} else if word == "Comment" {
			self.comments.push(rest.to_owned());
		} else {
			// LENIENT(L47): integers beyond 128 bits (Python's are unbounded) stay
			// text.
			let value = match crate::py::parse_int(rest) {
				Some(i) => AttrValue::Int(i),
				None => AttrValue::Str(rest.to_owned()),
			};
			self.attrs.insert(word.to_owned(), value);
		}
		Ok(())
	}

	fn parsecomposite(&mut self, rest: &str) -> Result<()> {
		let mut c = Cursor::new(rest);
		let mut head = || -> Option<(&str, &str)> {
			let name = c.name()?;
			c.space(true)?;
			let n = c.digits()?;
			c.semicolon()?;
			Some((name, n))
		};
		let (charname, ncomponents) = head().ok_or_else(|| syntax_error(rest))?;
		let ncomponents = int(ncomponents)?;
		let mut rest = &rest[c.pos..];
		let mut components = Vec::new();
		loop {
			let mut c = Cursor::new(rest);
			let mut component = || -> Option<(&str, &str, &str)> {
				c.lit("PCC")?;
				c.space(true)?;
				let base = c.name()?;
				c.space(true)?;
				let x = c.int()?;
				c.space(true)?;
				let y = c.int()?;
				c.semicolon()?;
				Some((base, x, y))
			};
			let (base, x, y) = component().ok_or_else(|| syntax_error(rest))?;
			components.push((base.to_owned(), int(x)?, int(y)?));
			rest = &rest[c.pos..];
			if rest.is_empty() {
				break;
			}
		}
		if components.len() as i64 != ncomponents {
			return Err(Error::Python(
				"AssertionError: len(components) == ncomponents".into(),
			));
		}
		self.composites.insert(charname.to_owned(), components);
		Ok(())
	}

	/// The text of the file, with lines separated by `sep`; `timestamp` is the
	/// time in the "Generated by afmLib" comment, `%m/%d/%Y %H:%M:%S`.
	pub fn to_text(&self, sep: &str, timestamp: &str) -> String {
		let mut lines = vec![
			"StartFontMetrics 2.0".to_owned(),
			format!("Comment Generated by afmLib; at {timestamp}"),
		];
		// write comments, assuming (possibly wrongly!) they should all appear
		// at the top
		for comment in &self.comments {
			lines.push(format!("Comment {comment}"));
		}
		// write attributes, first the ones we know about, in a preferred order
		for attr in PREFERRED_ATTRIBUTE_ORDER {
			if let Some(value) = self.attrs.get(attr) {
				lines.push(format!("{attr} {value}"));
			}
		}
		// then write the attributes we don't know about, in alphabetical order
		let mut items: Vec<(&String, &AttrValue)> = self.attrs.iter().collect();
		items.sort_by(|a, b| a.0.cmp(b.0));
		for (attr, value) in items {
			if PREFERRED_ATTRIBUTE_ORDER.contains(&attr.as_str()) {
				continue;
			}
			lines.push(format!("{attr} {value}"));
		}

		// write char metrics
		lines.push(format!("StartCharMetrics {}", self.chars.len()));
		let mut items: Vec<CharItem<'_>> = self
			.chars
			.iter()
			.map(|(name, &(num, width, bbox))| (num, name, width, bbox))
			.collect();
		// Unencoded chars (-1) go to the end.
		items.sort_by(|a, b| {
			let key =
				|x: &CharItem<'_>| (if x.0 == -1 { 0xFFFF } else { x.0 }, x.1.clone(), x.2, x.3);
			key(a).cmp(&key(b))
		});
		for (num, name, width, (l, b, r, t)) in items {
			lines.push(format!(
				"C {num} ; WX {width} ; N {name} ; B {l} {b} {r} {t} ;"
			));
		}
		lines.push("EndCharMetrics".into());

		// write kerning info
		lines.push("StartKernData".into());
		lines.push(format!("StartKernPairs {}", self.kerning.len()));
		let mut items: Vec<(&(String, String), &i64)> = self.kerning.iter().collect();
		items.sort();
		for ((left, right), value) in items {
			lines.push(format!("KPX {left} {right} {value}"));
		}
		lines.push("EndKernPairs".into());
		lines.push("EndKernData".into());

		if !self.composites.is_empty() {
			let mut composites: Vec<(&String, &Vec<Component>)> = self.composites.iter().collect();
			composites.sort();
			lines.push(format!("StartComposites {}", self.composites.len()));
			for (name, components) in composites {
				let mut line = format!("CC {name} {} ;", components.len());
				for (base, x, y) in components {
					line.push_str(&format!(" PCC {base} {x} {y} ;"));
				}
				lines.push(line);
			}
			lines.push("EndComposites".into());
		}

		lines.push("EndFontMetrics".into());
		let mut text = lines.join(sep);
		text.push_str(sep);
		text
	}

	/// Writes the AFM to a file (`write`), with lines separated by `sep`
	/// (fontTools' default is `"\r"`).
	///
	/// LENIENT(L47): the "Generated by afmLib" comment has the time in UTC (from the
	/// clock of [`crate::time_tools`], which honors `SOURCE_DATE_EPOCH`);
	/// fontTools uses the local time, which needs the time zone database of the
	/// system. Use [`Afm::to_text`] for another time.
	pub fn write(&self, path: impl AsRef<Path>, sep: &str) -> Result<()> {
		use crate::time_tools::{EPOCH_DIFF, gmtime, timestamp_now};
		let now = timestamp_now().map_or(0, |t| t + EPOCH_DIFF);
		let t = gmtime(now);
		let timestamp = format!(
			"{:02}/{:02}/{:04} {:02}:{:02}:{:02}",
			t.month, t.day, t.year, t.hour, t.minute, t.second
		);
		let text = self.to_text(sep, &timestamp);
		if let Some(i) = text.chars().position(|c| !c.is_ascii()) {
			return Err(Error::Python(format!(
				"UnicodeEncodeError: 'ascii' codec can't encode character in position {i}"
			)));
		}
		std::fs::write(path, text)?;
		Ok(())
	}

	/// Whether the kerning pair exists (`has_kernpair`).
	pub fn has_kernpair(&self, pair: (&str, &str)) -> bool {
		self.kerning(pair).is_some()
	}

	/// The kerning pairs (`kernpairs`).
	pub fn kernpairs(&self) -> Vec<(String, String)> {
		self.kerning.keys().cloned().collect()
	}

	/// The kerning value of a pair (`afm[(left, right)]`).
	pub fn kerning(&self, (left, right): (&str, &str)) -> Option<i64> {
		self.kerning
			.get(&(left.to_owned(), right.to_owned()))
			.copied()
	}

	/// Sets the kerning value of a pair (`afm[(left, right)] = value`).
	pub fn set_kerning(&mut self, (left, right): (&str, &str), value: i64) {
		self.kerning
			.insert((left.to_owned(), right.to_owned()), value);
	}

	/// Removes a kerning pair (`del afm[(left, right)]`).
	pub fn remove_kerning(&mut self, (left, right): (&str, &str)) -> Option<i64> {
		self.kerning
			.shift_remove(&(left.to_owned(), right.to_owned()))
	}

	/// Whether the glyph exists (`has_char`).
	pub fn has_char(&self, name: &str) -> bool {
		self.chars.contains_key(name)
	}

	/// The glyph names (`chars`).
	pub fn chars(&self) -> Vec<String> {
		self.chars.keys().cloned().collect()
	}

	/// The metrics of a glyph (`afm[name]`).
	pub fn char(&self, name: &str) -> Option<CharMetrics> {
		self.chars.get(name).copied()
	}

	/// Sets the metrics of a glyph (`afm[name] = metrics`).
	pub fn set_char(&mut self, name: &str, metrics: CharMetrics) {
		self.chars.insert(name.to_owned(), metrics);
	}

	/// Removes a glyph (`del afm[name]`).
	pub fn remove_char(&mut self, name: &str) -> Option<CharMetrics> {
		self.chars.shift_remove(name)
	}

	/// The comments (`comments`).
	pub fn comments(&self) -> &[String] {
		&self.comments
	}

	/// Adds a comment (`addComment`).
	pub fn add_comment(&mut self, comment: &str) {
		self.comments.push(comment.to_owned());
	}

	/// The composite glyphs and their components.
	pub fn composites(&self) -> &IndexMap<String, Vec<Component>> {
		&self.composites
	}

	/// Specifies the components of a composite glyph (`addComposite`).
	pub fn add_composite(&mut self, glyph_name: &str, components: Vec<Component>) {
		self.composites.insert(glyph_name.to_owned(), components);
	}

	/// An attribute (`afm.FontName` and the like).
	pub fn attr(&self, name: &str) -> Option<&AttrValue> {
		self.attrs.get(name)
	}

	/// The attributes, in the order they were read.
	pub fn attrs(&self) -> &IndexMap<String, AttrValue> {
		&self.attrs
	}

	/// Sets an attribute.
	pub fn set_attr(&mut self, name: &str, value: AttrValue) {
		self.attrs.insert(name.to_owned(), value);
	}

	/// Removes an attribute.
	pub fn remove_attr(&mut self, name: &str) -> Option<AttrValue> {
		self.attrs.shift_remove(name)
	}
}