use std::path::Path;
use indexmap::IndexMap;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("{0}")]
Afm(String),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("{0}")]
Python(String),
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttrValue {
Int(i128),
Str(String),
BBox(i64, i64, i64, i64),
}
impl std::fmt::Display for AttrValue {
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}"),
}
}
}
pub type CharMetrics = (i64, i64, (i64, i64, i64, i64));
type CharItem<'a> = (i64, &'a String, i64, (i64, i64, i64, i64));
pub type Component = (String, i64, i64);
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",
];
#[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)
))
}
fn is_space(c: u8) -> bool {
matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C | 0x1C..=0x1F)
}
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()
}
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])
}
fn name(&mut self) -> Option<&'a str> {
self.take_while(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'_')
}
fn digits(&mut self) -> Option<&'a str> {
self.take_while(|c| c.is_ascii_digit())
}
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
}
}
}
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}")))
}
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
}
fn strip(s: &str) -> &str {
s.trim_matches(|c: char| c.is_ascii() && is_space(c as u8))
}
impl Afm {
pub fn new() -> Self {
Self::default()
}
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let mut afm = Self::new();
afm.read(path)?;
Ok(afm)
}
#[allow(clippy::should_implement_trait)]
pub fn from_str(text: &str) -> Result<Self> {
let mut afm = Self::new();
afm.parse(text)?;
Ok(afm)
}
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)
}
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 {
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(())
}
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}"),
];
for comment in &self.comments {
lines.push(format!("Comment {comment}"));
}
for attr in PREFERRED_ATTRIBUTE_ORDER {
if let Some(value) = self.attrs.get(attr) {
lines.push(format!("{attr} {value}"));
}
}
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}"));
}
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();
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());
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
}
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, ×tamp);
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(())
}
pub fn has_kernpair(&self, pair: (&str, &str)) -> bool {
self.kerning(pair).is_some()
}
pub fn kernpairs(&self) -> Vec<(String, String)> {
self.kerning.keys().cloned().collect()
}
pub fn kerning(&self, (left, right): (&str, &str)) -> Option<i64> {
self.kerning
.get(&(left.to_owned(), right.to_owned()))
.copied()
}
pub fn set_kerning(&mut self, (left, right): (&str, &str), value: i64) {
self.kerning
.insert((left.to_owned(), right.to_owned()), value);
}
pub fn remove_kerning(&mut self, (left, right): (&str, &str)) -> Option<i64> {
self.kerning
.shift_remove(&(left.to_owned(), right.to_owned()))
}
pub fn has_char(&self, name: &str) -> bool {
self.chars.contains_key(name)
}
pub fn chars(&self) -> Vec<String> {
self.chars.keys().cloned().collect()
}
pub fn char(&self, name: &str) -> Option<CharMetrics> {
self.chars.get(name).copied()
}
pub fn set_char(&mut self, name: &str, metrics: CharMetrics) {
self.chars.insert(name.to_owned(), metrics);
}
pub fn remove_char(&mut self, name: &str) -> Option<CharMetrics> {
self.chars.shift_remove(name)
}
pub fn comments(&self) -> &[String] {
&self.comments
}
pub fn add_comment(&mut self, comment: &str) {
self.comments.push(comment.to_owned());
}
pub fn composites(&self) -> &IndexMap<String, Vec<Component>> {
&self.composites
}
pub fn add_composite(&mut self, glyph_name: &str, components: Vec<Component>) {
self.composites.insert(glyph_name.to_owned(), components);
}
pub fn attr(&self, name: &str) -> Option<&AttrValue> {
self.attrs.get(name)
}
pub fn attrs(&self) -> &IndexMap<String, AttrValue> {
&self.attrs
}
pub fn set_attr(&mut self, name: &str, value: AttrValue) {
self.attrs.insert(name.to_owned(), value);
}
pub fn remove_attr(&mut self, name: &str) -> Option<AttrValue> {
self.attrs.shift_remove(name)
}
}