Skip to main content

fontoxide_misc/
afm_lib.rs

1//! Port of `fontTools.afmLib`: reading and writing AFM (Adobe Font Metrics)
2//! files.
3//!
4//! Like fontTools, this has been designed to read AFM files generated by
5//! Fontographer: it does not implement the whole Adobe AFM specification, but
6//! it should read most "common" AFM files.
7//!
8//! ```
9//! use fontoxide_misc::afm_lib::{Afm, AttrValue};
10//! let mut f = Afm::from_str(
11//!     "StartFontMetrics 2.0\nFontName TestFont-Regular\nXHeight 500\n\
12//!      C 65 ; WX 668 ; N A ; B 8 -25 660 666 ;\nKPX V A -60\nEndFontMetrics\n",
13//! )?;
14//! // Accessing a pair gets you the kern value.
15//! assert_eq!(f.kerning(("V", "A")), Some(-60));
16//! // Accessing a glyph name gets you metrics: (charnum, width, bounding box).
17//! assert_eq!(f.char("A"), Some((65, 668, (8, -25, 660, 666))));
18//! // Attributes are metadata.
19//! assert_eq!(f.attr("FontName"), Some(&AttrValue::Str("TestFont-Regular".into())));
20//! assert_eq!(f.attr("XHeight"), Some(&AttrValue::Int(500)));
21//! // Attributes and items can also be set.
22//! f.set_kerning(("A", "V"), -150);
23//! f.set_attr("FontName", AttrValue::Str("TestFont Squished".into()));
24//! # Ok::<(), fontoxide_misc::afm_lib::Error>(())
25//! ```
26
27use std::path::Path;
28
29use indexmap::IndexMap;
30use thiserror::Error;
31
32/// Errors of this module.
33#[derive(Debug, Error)]
34pub enum Error {
35	/// `error`: a syntax error in an AFM file.
36	#[error("{0}")]
37	Afm(String),
38	/// The file could not be read or written.
39	#[error(transparent)]
40	Io(#[from] std::io::Error),
41	/// Other Python exceptions fontTools raises on bad input (`ValueError`,
42	/// `UnicodeDecodeError`, `AssertionError`, ...).
43	#[error("{0}")]
44	Python(String),
45}
46
47/// The result type of this module.
48pub type Result<T> = std::result::Result<T, Error>;
49
50/// The value of an attribute: an integer if the text is one, the bounding box of
51/// `FontBBox`, or the text.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum AttrValue {
54	/// An integer (`int(rest)`).
55	Int(i128),
56	/// Text.
57	Str(String),
58	/// The four integers of `FontBBox`.
59	BBox(i64, i64, i64, i64),
60}
61
62impl std::fmt::Display for AttrValue {
63	/// `str(value)`; a bounding box as `"l b r t"`.
64	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65		match self {
66			AttrValue::Int(i) => write!(f, "{i}"),
67			AttrValue::Str(s) => f.write_str(s),
68			AttrValue::BBox(l, b, r, t) => write!(f, "{l} {b} {r} {t}"),
69		}
70	}
71}
72
73/// Character metrics: code (-1 if unencoded), width and bounding box.
74pub type CharMetrics = (i64, i64, (i64, i64, i64, i64));
75
76/// A row of the char metrics being written: code, name, width, box.
77type CharItem<'a> = (i64, &'a String, i64, (i64, i64, i64, i64));
78
79/// A component of a composite glyph: base glyph name, x and y offsets.
80pub type Component = (String, i64, i64);
81
82/// The attributes written first, in this order (`preferredAttributeOrder`).
83pub const PREFERRED_ATTRIBUTE_ORDER: [&str; 16] = [
84	"FontName",
85	"FullName",
86	"FamilyName",
87	"Weight",
88	"ItalicAngle",
89	"IsFixedPitch",
90	"FontBBox",
91	"UnderlinePosition",
92	"UnderlineThickness",
93	"Version",
94	"Notice",
95	"EncodingScheme",
96	"CapHeight",
97	"XHeight",
98	"Ascender",
99	"Descender",
100];
101
102const KEYWORDS: [&str; 10] = [
103	"StartFontMetrics",
104	"EndFontMetrics",
105	"StartCharMetrics",
106	"EndCharMetrics",
107	"StartKernData",
108	"StartKernPairs",
109	"EndKernPairs",
110	"EndKernData",
111	"StartComposites",
112	"EndComposites",
113];
114
115/// An AFM file (`AFM`).
116#[derive(Debug, Clone, Default, PartialEq)]
117pub struct Afm {
118	attrs: IndexMap<String, AttrValue>,
119	chars: IndexMap<String, CharMetrics>,
120	kerning: IndexMap<(String, String), i64>,
121	comments: Vec<String>,
122	composites: IndexMap<String, Vec<Component>>,
123}
124
125fn syntax_error(s: &str) -> Error {
126	Error::Afm(format!(
127		"syntax error in AFM file: {}",
128		crate::py::str_repr(s)
129	))
130}
131
132/// `\s` of Python `str` patterns, for the ASCII text of AFM files.
133fn is_space(c: u8) -> bool {
134	matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C | 0x1C..=0x1F)
135}
136
137/// A cursor for the regular expressions of fontTools, which match from the
138/// start of the text.
139struct Cursor<'a> {
140	s: &'a str,
141	pos: usize,
142}
143
144impl<'a> Cursor<'a> {
145	fn new(s: &'a str) -> Self {
146		Cursor { s, pos: 0 }
147	}
148
149	fn bytes(&self) -> &'a [u8] {
150		self.s.as_bytes()
151	}
152
153	/// `\s*`, or `\s+` if `one`.
154	fn space(&mut self, one: bool) -> Option<()> {
155		let start = self.pos;
156		while self.bytes().get(self.pos).is_some_and(|&c| is_space(c)) {
157			self.pos += 1;
158		}
159		(!one || self.pos > start).then_some(())
160	}
161
162	fn lit(&mut self, lit: &str) -> Option<()> {
163		if self.s[self.pos..].starts_with(lit) {
164			self.pos += lit.len();
165			Some(())
166		} else {
167			None
168		}
169	}
170
171	fn take_while(&mut self, f: impl Fn(u8) -> bool) -> Option<&'a str> {
172		let start = self.pos;
173		while self.bytes().get(self.pos).is_some_and(|&c| f(c)) {
174			self.pos += 1;
175		}
176		(self.pos > start).then(|| &self.s[start..self.pos])
177	}
178
179	/// `[.A-Za-z0-9_]+`.
180	fn name(&mut self) -> Option<&'a str> {
181		self.take_while(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'_')
182	}
183
184	/// `\d+`.
185	fn digits(&mut self) -> Option<&'a str> {
186		self.take_while(|c| c.is_ascii_digit())
187	}
188
189	/// `-?\d+`.
190	fn int(&mut self) -> Option<&'a str> {
191		let start = self.pos;
192		if self.bytes().get(self.pos) == Some(&b'-') {
193			self.pos += 1;
194		}
195		match self.digits() {
196			Some(_) => Some(&self.s[start..self.pos]),
197			None => {
198				self.pos = start;
199				None
200			}
201		}
202	}
203
204	/// `\s*;\s*`.
205	fn semicolon(&mut self) -> Option<()> {
206		self.space(false)?;
207		self.lit(";")?;
208		self.space(false)
209	}
210}
211
212fn int(s: &str) -> Result<i64> {
213	s.parse()
214		.map_err(|_| Error::Python(format!("ValueError: invalid literal for int(): {s}")))
215}
216
217/// `str.splitlines()` of text read in universal newlines mode.
218fn splitlines(data: &str) -> Vec<&str> {
219	let mut lines = Vec::new();
220	let bytes = data.as_bytes();
221	let mut start = 0;
222	let mut i = 0;
223	while i < bytes.len() {
224		match bytes[i] {
225			b'\r' => {
226				lines.push(&data[start..i]);
227				if bytes.get(i + 1) == Some(&b'\n') {
228					i += 1;
229				}
230				start = i + 1;
231			}
232			b'\n' | 0x0B | 0x0C | 0x1C..=0x1E => {
233				lines.push(&data[start..i]);
234				start = i + 1;
235			}
236			_ => {}
237		}
238		i += 1;
239	}
240	if start < bytes.len() {
241		lines.push(&data[start..]);
242	}
243	lines
244}
245
246/// `str.strip()` for ASCII text.
247fn strip(s: &str) -> &str {
248	s.trim_matches(|c: char| c.is_ascii() && is_space(c as u8))
249}
250
251impl Afm {
252	/// An empty AFM (`AFM()`).
253	pub fn new() -> Self {
254		Self::default()
255	}
256
257	/// Opens, reads and parses a file (`AFM(path)`).
258	pub fn open(path: impl AsRef<Path>) -> Result<Self> {
259		let mut afm = Self::new();
260		afm.read(path)?;
261		Ok(afm)
262	}
263
264	/// Parses the text of an AFM file.
265	#[allow(clippy::should_implement_trait)]
266	pub fn from_str(text: &str) -> Result<Self> {
267		let mut afm = Self::new();
268		afm.parse(text)?;
269		Ok(afm)
270	}
271
272	/// Opens, reads and parses a file into this AFM (`read`).
273	pub fn read(&mut self, path: impl AsRef<Path>) -> Result<()> {
274		let data = std::fs::read(path)?;
275		if let Some(i) = data.iter().position(|&b| b >= 0x80) {
276			return Err(Error::Python(format!(
277				"UnicodeDecodeError: 'ascii' codec can't decode byte 0x{:02x} in position {i}: ordinal not in range(128)",
278				data[i]
279			)));
280		}
281		let text = String::from_utf8(data).map_err(|e| Error::Python(e.to_string()))?;
282		self.parse(&text)
283	}
284
285	/// Parses the text of an AFM file into this AFM.
286	pub fn parse(&mut self, text: &str) -> Result<()> {
287		for line in splitlines(text) {
288			if strip(line).is_empty() {
289				continue;
290			}
291			let pos = line
292				.bytes()
293				.position(|c| !c.is_ascii_alphabetic())
294				.unwrap_or(line.len());
295			if pos == 0 {
296				return Err(syntax_error(line));
297			}
298			let word = &line[..pos];
299			let rest = strip(&line[pos..]);
300			if KEYWORDS.contains(&word) {
301				continue;
302			}
303			match word {
304				"C" => self.parsechar(rest)?,
305				"KPX" => self.parsekernpair(rest)?,
306				"CC" => self.parsecomposite(rest)?,
307				_ => self.parseattr(word, rest)?,
308			}
309		}
310		Ok(())
311	}
312
313	fn parsechar(&mut self, rest: &str) -> Result<()> {
314		let mut c = Cursor::new(rest);
315		let mut parse = || -> Option<[&str; 7]> {
316			let charnum = c.int()?;
317			c.semicolon()?;
318			c.lit("WX")?;
319			c.space(true)?;
320			let width = c.int()?;
321			c.semicolon()?;
322			c.lit("N")?;
323			c.space(true)?;
324			let name = c.name()?;
325			c.semicolon()?;
326			c.lit("B")?;
327			c.space(true)?;
328			let l = c.int()?;
329			c.space(true)?;
330			let b = c.int()?;
331			c.space(true)?;
332			let r = c.int()?;
333			c.space(true)?;
334			let t = c.int()?;
335			c.semicolon()?;
336			Some([charnum, width, name, l, b, r, t])
337		};
338		let [charnum, width, name, l, b, r, t] = parse().ok_or_else(|| syntax_error(rest))?;
339		self.chars.insert(
340			name.to_owned(),
341			(
342				int(charnum)?,
343				int(width)?,
344				(int(l)?, int(b)?, int(r)?, int(t)?),
345			),
346		);
347		Ok(())
348	}
349
350	fn parsekernpair(&mut self, rest: &str) -> Result<()> {
351		let mut c = Cursor::new(rest);
352		let mut parse = || -> Option<[&str; 3]> {
353			let left = c.name()?;
354			c.space(true)?;
355			let right = c.name()?;
356			c.space(true)?;
357			let value = c.int()?;
358			Some([left, right, value])
359		};
360		let [left, right, value] = parse().ok_or_else(|| syntax_error(rest))?;
361		self.kerning
362			.insert((left.to_owned(), right.to_owned()), int(value)?);
363		Ok(())
364	}
365
366	fn parseattr(&mut self, word: &str, rest: &str) -> Result<()> {
367		if word == "FontBBox" {
368			let v: Vec<i64> = rest
369				.split_ascii_whitespace()
370				.map(|t| {
371					crate::py::parse_int(t)
372						.and_then(|i| i64::try_from(i).ok())
373						.ok_or_else(|| {
374							Error::Python(format!(
375								"ValueError: invalid literal for int() with base 10: {}",
376								crate::py::str_repr(t)
377							))
378						})
379				})
380				.collect::<Result<_>>()?;
381			let [l, b, r, t] = v[..] else {
382				return Err(Error::Python(format!(
383					"ValueError: expected 4 values to unpack, got {}",
384					v.len()
385				)));
386			};
387			self.attrs
388				.insert(word.to_owned(), AttrValue::BBox(l, b, r, t));
389		} else if word == "Comment" {
390			self.comments.push(rest.to_owned());
391		} else {
392			// LENIENT(L47): integers beyond 128 bits (Python's are unbounded) stay
393			// text.
394			let value = match crate::py::parse_int(rest) {
395				Some(i) => AttrValue::Int(i),
396				None => AttrValue::Str(rest.to_owned()),
397			};
398			self.attrs.insert(word.to_owned(), value);
399		}
400		Ok(())
401	}
402
403	fn parsecomposite(&mut self, rest: &str) -> Result<()> {
404		let mut c = Cursor::new(rest);
405		let mut head = || -> Option<(&str, &str)> {
406			let name = c.name()?;
407			c.space(true)?;
408			let n = c.digits()?;
409			c.semicolon()?;
410			Some((name, n))
411		};
412		let (charname, ncomponents) = head().ok_or_else(|| syntax_error(rest))?;
413		let ncomponents = int(ncomponents)?;
414		let mut rest = &rest[c.pos..];
415		let mut components = Vec::new();
416		loop {
417			let mut c = Cursor::new(rest);
418			let mut component = || -> Option<(&str, &str, &str)> {
419				c.lit("PCC")?;
420				c.space(true)?;
421				let base = c.name()?;
422				c.space(true)?;
423				let x = c.int()?;
424				c.space(true)?;
425				let y = c.int()?;
426				c.semicolon()?;
427				Some((base, x, y))
428			};
429			let (base, x, y) = component().ok_or_else(|| syntax_error(rest))?;
430			components.push((base.to_owned(), int(x)?, int(y)?));
431			rest = &rest[c.pos..];
432			if rest.is_empty() {
433				break;
434			}
435		}
436		if components.len() as i64 != ncomponents {
437			return Err(Error::Python(
438				"AssertionError: len(components) == ncomponents".into(),
439			));
440		}
441		self.composites.insert(charname.to_owned(), components);
442		Ok(())
443	}
444
445	/// The text of the file, with lines separated by `sep`; `timestamp` is the
446	/// time in the "Generated by afmLib" comment, `%m/%d/%Y %H:%M:%S`.
447	pub fn to_text(&self, sep: &str, timestamp: &str) -> String {
448		let mut lines = vec![
449			"StartFontMetrics 2.0".to_owned(),
450			format!("Comment Generated by afmLib; at {timestamp}"),
451		];
452		// write comments, assuming (possibly wrongly!) they should all appear
453		// at the top
454		for comment in &self.comments {
455			lines.push(format!("Comment {comment}"));
456		}
457		// write attributes, first the ones we know about, in a preferred order
458		for attr in PREFERRED_ATTRIBUTE_ORDER {
459			if let Some(value) = self.attrs.get(attr) {
460				lines.push(format!("{attr} {value}"));
461			}
462		}
463		// then write the attributes we don't know about, in alphabetical order
464		let mut items: Vec<(&String, &AttrValue)> = self.attrs.iter().collect();
465		items.sort_by(|a, b| a.0.cmp(b.0));
466		for (attr, value) in items {
467			if PREFERRED_ATTRIBUTE_ORDER.contains(&attr.as_str()) {
468				continue;
469			}
470			lines.push(format!("{attr} {value}"));
471		}
472
473		// write char metrics
474		lines.push(format!("StartCharMetrics {}", self.chars.len()));
475		let mut items: Vec<CharItem<'_>> = self
476			.chars
477			.iter()
478			.map(|(name, &(num, width, bbox))| (num, name, width, bbox))
479			.collect();
480		// Unencoded chars (-1) go to the end.
481		items.sort_by(|a, b| {
482			let key =
483				|x: &CharItem<'_>| (if x.0 == -1 { 0xFFFF } else { x.0 }, x.1.clone(), x.2, x.3);
484			key(a).cmp(&key(b))
485		});
486		for (num, name, width, (l, b, r, t)) in items {
487			lines.push(format!(
488				"C {num} ; WX {width} ; N {name} ; B {l} {b} {r} {t} ;"
489			));
490		}
491		lines.push("EndCharMetrics".into());
492
493		// write kerning info
494		lines.push("StartKernData".into());
495		lines.push(format!("StartKernPairs {}", self.kerning.len()));
496		let mut items: Vec<(&(String, String), &i64)> = self.kerning.iter().collect();
497		items.sort();
498		for ((left, right), value) in items {
499			lines.push(format!("KPX {left} {right} {value}"));
500		}
501		lines.push("EndKernPairs".into());
502		lines.push("EndKernData".into());
503
504		if !self.composites.is_empty() {
505			let mut composites: Vec<(&String, &Vec<Component>)> = self.composites.iter().collect();
506			composites.sort();
507			lines.push(format!("StartComposites {}", self.composites.len()));
508			for (name, components) in composites {
509				let mut line = format!("CC {name} {} ;", components.len());
510				for (base, x, y) in components {
511					line.push_str(&format!(" PCC {base} {x} {y} ;"));
512				}
513				lines.push(line);
514			}
515			lines.push("EndComposites".into());
516		}
517
518		lines.push("EndFontMetrics".into());
519		let mut text = lines.join(sep);
520		text.push_str(sep);
521		text
522	}
523
524	/// Writes the AFM to a file (`write`), with lines separated by `sep`
525	/// (fontTools' default is `"\r"`).
526	///
527	/// LENIENT(L47): the "Generated by afmLib" comment has the time in UTC (from the
528	/// clock of [`crate::time_tools`], which honors `SOURCE_DATE_EPOCH`);
529	/// fontTools uses the local time, which needs the time zone database of the
530	/// system. Use [`Afm::to_text`] for another time.
531	pub fn write(&self, path: impl AsRef<Path>, sep: &str) -> Result<()> {
532		use crate::time_tools::{EPOCH_DIFF, gmtime, timestamp_now};
533		let now = timestamp_now().map_or(0, |t| t + EPOCH_DIFF);
534		let t = gmtime(now);
535		let timestamp = format!(
536			"{:02}/{:02}/{:04} {:02}:{:02}:{:02}",
537			t.month, t.day, t.year, t.hour, t.minute, t.second
538		);
539		let text = self.to_text(sep, &timestamp);
540		if let Some(i) = text.chars().position(|c| !c.is_ascii()) {
541			return Err(Error::Python(format!(
542				"UnicodeEncodeError: 'ascii' codec can't encode character in position {i}"
543			)));
544		}
545		std::fs::write(path, text)?;
546		Ok(())
547	}
548
549	/// Whether the kerning pair exists (`has_kernpair`).
550	pub fn has_kernpair(&self, pair: (&str, &str)) -> bool {
551		self.kerning(pair).is_some()
552	}
553
554	/// The kerning pairs (`kernpairs`).
555	pub fn kernpairs(&self) -> Vec<(String, String)> {
556		self.kerning.keys().cloned().collect()
557	}
558
559	/// The kerning value of a pair (`afm[(left, right)]`).
560	pub fn kerning(&self, (left, right): (&str, &str)) -> Option<i64> {
561		self.kerning
562			.get(&(left.to_owned(), right.to_owned()))
563			.copied()
564	}
565
566	/// Sets the kerning value of a pair (`afm[(left, right)] = value`).
567	pub fn set_kerning(&mut self, (left, right): (&str, &str), value: i64) {
568		self.kerning
569			.insert((left.to_owned(), right.to_owned()), value);
570	}
571
572	/// Removes a kerning pair (`del afm[(left, right)]`).
573	pub fn remove_kerning(&mut self, (left, right): (&str, &str)) -> Option<i64> {
574		self.kerning
575			.shift_remove(&(left.to_owned(), right.to_owned()))
576	}
577
578	/// Whether the glyph exists (`has_char`).
579	pub fn has_char(&self, name: &str) -> bool {
580		self.chars.contains_key(name)
581	}
582
583	/// The glyph names (`chars`).
584	pub fn chars(&self) -> Vec<String> {
585		self.chars.keys().cloned().collect()
586	}
587
588	/// The metrics of a glyph (`afm[name]`).
589	pub fn char(&self, name: &str) -> Option<CharMetrics> {
590		self.chars.get(name).copied()
591	}
592
593	/// Sets the metrics of a glyph (`afm[name] = metrics`).
594	pub fn set_char(&mut self, name: &str, metrics: CharMetrics) {
595		self.chars.insert(name.to_owned(), metrics);
596	}
597
598	/// Removes a glyph (`del afm[name]`).
599	pub fn remove_char(&mut self, name: &str) -> Option<CharMetrics> {
600		self.chars.shift_remove(name)
601	}
602
603	/// The comments (`comments`).
604	pub fn comments(&self) -> &[String] {
605		&self.comments
606	}
607
608	/// Adds a comment (`addComment`).
609	pub fn add_comment(&mut self, comment: &str) {
610		self.comments.push(comment.to_owned());
611	}
612
613	/// The composite glyphs and their components.
614	pub fn composites(&self) -> &IndexMap<String, Vec<Component>> {
615		&self.composites
616	}
617
618	/// Specifies the components of a composite glyph (`addComposite`).
619	pub fn add_composite(&mut self, glyph_name: &str, components: Vec<Component>) {
620		self.composites.insert(glyph_name.to_owned(), components);
621	}
622
623	/// An attribute (`afm.FontName` and the like).
624	pub fn attr(&self, name: &str) -> Option<&AttrValue> {
625		self.attrs.get(name)
626	}
627
628	/// The attributes, in the order they were read.
629	pub fn attrs(&self) -> &IndexMap<String, AttrValue> {
630		&self.attrs
631	}
632
633	/// Sets an attribute.
634	pub fn set_attr(&mut self, name: &str, value: AttrValue) {
635		self.attrs.insert(name.to_owned(), value);
636	}
637
638	/// Removes an attribute.
639	pub fn remove_attr(&mut self, name: &str) -> Option<AttrValue> {
640		self.attrs.shift_remove(name)
641	}
642}