1use std::path::Path;
28
29use indexmap::IndexMap;
30use thiserror::Error;
31
32#[derive(Debug, Error)]
34pub enum Error {
35 #[error("{0}")]
37 Afm(String),
38 #[error(transparent)]
40 Io(#[from] std::io::Error),
41 #[error("{0}")]
44 Python(String),
45}
46
47pub type Result<T> = std::result::Result<T, Error>;
49
50#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum AttrValue {
54 Int(i128),
56 Str(String),
58 BBox(i64, i64, i64, i64),
60}
61
62impl std::fmt::Display for AttrValue {
63 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
73pub type CharMetrics = (i64, i64, (i64, i64, i64, i64));
75
76type CharItem<'a> = (i64, &'a String, i64, (i64, i64, i64, i64));
78
79pub type Component = (String, i64, i64);
81
82pub 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#[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
132fn is_space(c: u8) -> bool {
134 matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C | 0x1C..=0x1F)
135}
136
137struct 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 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 fn name(&mut self) -> Option<&'a str> {
181 self.take_while(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'_')
182 }
183
184 fn digits(&mut self) -> Option<&'a str> {
186 self.take_while(|c| c.is_ascii_digit())
187 }
188
189 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 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
217fn 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
246fn strip(s: &str) -> &str {
248 s.trim_matches(|c: char| c.is_ascii() && is_space(c as u8))
249}
250
251impl Afm {
252 pub fn new() -> Self {
254 Self::default()
255 }
256
257 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 #[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 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 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 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 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 for comment in &self.comments {
455 lines.push(format!("Comment {comment}"));
456 }
457 for attr in PREFERRED_ATTRIBUTE_ORDER {
459 if let Some(value) = self.attrs.get(attr) {
460 lines.push(format!("{attr} {value}"));
461 }
462 }
463 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 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 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 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 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, ×tamp);
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 pub fn has_kernpair(&self, pair: (&str, &str)) -> bool {
551 self.kerning(pair).is_some()
552 }
553
554 pub fn kernpairs(&self) -> Vec<(String, String)> {
556 self.kerning.keys().cloned().collect()
557 }
558
559 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 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 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 pub fn has_char(&self, name: &str) -> bool {
580 self.chars.contains_key(name)
581 }
582
583 pub fn chars(&self) -> Vec<String> {
585 self.chars.keys().cloned().collect()
586 }
587
588 pub fn char(&self, name: &str) -> Option<CharMetrics> {
590 self.chars.get(name).copied()
591 }
592
593 pub fn set_char(&mut self, name: &str, metrics: CharMetrics) {
595 self.chars.insert(name.to_owned(), metrics);
596 }
597
598 pub fn remove_char(&mut self, name: &str) -> Option<CharMetrics> {
600 self.chars.shift_remove(name)
601 }
602
603 pub fn comments(&self) -> &[String] {
605 &self.comments
606 }
607
608 pub fn add_comment(&mut self, comment: &str) {
610 self.comments.push(comment.to_owned());
611 }
612
613 pub fn composites(&self) -> &IndexMap<String, Vec<Component>> {
615 &self.composites
616 }
617
618 pub fn add_composite(&mut self, glyph_name: &str, components: Vec<Component>) {
620 self.composites.insert(glyph_name.to_owned(), components);
621 }
622
623 pub fn attr(&self, name: &str) -> Option<&AttrValue> {
625 self.attrs.get(name)
626 }
627
628 pub fn attrs(&self) -> &IndexMap<String, AttrValue> {
630 &self.attrs
631 }
632
633 pub fn set_attr(&mut self, name: &str, value: AttrValue) {
635 self.attrs.insert(name.to_owned(), value);
636 }
637
638 pub fn remove_attr(&mut self, name: &str) -> Option<AttrValue> {
640 self.attrs.shift_remove(name)
641 }
642}