use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::Path;
#[derive(Debug, Clone, PartialEq)]
pub struct Glyph {
pub name: String,
pub width: f64,
pub left_side_bearing: f64,
pub charstring: Vec<u8>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Type1 {
parts: (Vec<u8>, Vec<u8>, Vec<u8>),
pub font_name: String,
pub font_matrix: [f64; 6],
pub font_bbox: [f64; 4],
pub encoding: BTreeMap<u8, String>,
pub uses_standard_encoding: bool,
pub italic_angle: f64,
pub stem_v: Option<f64>,
pub subroutines: usize,
pub afm_metrics: Option<AfmMetrics>,
glyphs: BTreeMap<String, Glyph>,
private: Vec<u8>,
len_iv: usize,
charstring_tokens: (String, String),
charstrings: (usize, usize),
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct AfmMetrics {
pub ascender: f64,
pub descender: f64,
pub cap_height: f64,
pub x_height: f64,
}
impl AfmMetrics {
pub fn parse(text: &str) -> AfmMetrics {
let mut out = AfmMetrics::default();
for line in text.lines() {
if line.starts_with("StartCharMetrics") {
break;
}
let Some((key, value)) = line.split_once(char::is_whitespace) else {
continue;
};
let Ok(value) = value.trim().parse::<f64>() else {
continue;
};
match key {
"Ascender" => out.ascender = value,
"Descender" => out.descender = value,
"CapHeight" => out.cap_height = value,
"XHeight" => out.x_height = value,
_ => {}
}
}
out
}
}
const EEXEC_KEY: u16 = 55665;
const CHARSTRING_KEY: u16 = 4330;
fn decrypt(bytes: &[u8], key: u16, skip: usize) -> Vec<u8> {
let mut r = key;
let mut out = Vec::with_capacity(bytes.len().saturating_sub(skip));
for (i, &c) in bytes.iter().enumerate() {
let plain = c ^ (r >> 8) as u8;
r = (c as u16)
.wrapping_add(r)
.wrapping_mul(52845)
.wrapping_add(22719);
if i >= skip {
out.push(plain);
}
}
out
}
fn encrypt(plain: &[u8], key: u16, pad: usize) -> Vec<u8> {
let mut r = key;
let mut out = Vec::with_capacity(plain.len() + pad);
for &byte in std::iter::repeat_n(&0x58u8, pad).chain(plain) {
let cipher = byte ^ (r >> 8) as u8;
r = (cipher as u16)
.wrapping_add(r)
.wrapping_mul(52845)
.wrapping_add(22719);
out.push(cipher);
}
out
}
fn afm_beside(path: &Path) -> Option<AfmMetrics> {
let read = |at: &Path| {
std::fs::read_to_string(at)
.ok()
.map(|t| AfmMetrics::parse(&t))
};
if let Some(found) = read(&path.with_extension("afm")) {
return Some(found);
}
let name = format!("{}.afm", path.file_stem()?.to_string_lossy());
read(&crate::kpse::locate(&name)?)
}
fn find(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
(from..=haystack.len() - needle.len()).find(|&at| &haystack[at..at + needle.len()] == needle)
}
fn word_at(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
let mut at = from;
loop {
let found = find(haystack, needle, at)?;
let before = found
.checked_sub(1)
.map(|i| haystack[i].is_ascii_whitespace());
let after = haystack
.get(found + needle.len())
.map(|c| c.is_ascii_whitespace());
if before.unwrap_or(true) && after.unwrap_or(true) {
return Some(found);
}
at = found + 1;
}
}
fn replace_after(bytes: &[u8], key: &[u8], replacement: &str, until: &[u8]) -> Option<Vec<u8>> {
let at = find(bytes, key, 0)? + key.len();
let end = word_at(bytes, until, at)? + until.len();
let mut out = bytes[..at].to_vec();
out.extend(replacement.as_bytes());
out.extend(&bytes[end..]);
Some(out)
}
pub fn installed(file: &str) -> Option<std::path::PathBuf> {
static SEEN: std::sync::OnceLock<
std::sync::Mutex<BTreeMap<String, Option<std::path::PathBuf>>>,
> = std::sync::OnceLock::new();
let seen = SEEN.get_or_init(Default::default);
if let Some(hit) = seen.lock().ok().and_then(|m| m.get(file).cloned()) {
return hit;
}
let found = crate::kpse::locate(file);
if let Ok(mut m) = seen.lock() {
m.insert(file.to_string(), found.clone());
}
found
}
impl Type1 {
pub fn open(path: impl AsRef<Path>) -> Result<Type1, String> {
let path = path.as_ref();
let bytes =
std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let mut font = Type1::parse(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
font.afm_metrics = afm_beside(path);
Ok(font)
}
pub fn parse(bytes: &[u8]) -> Result<Type1, String> {
let joined = match bytes.first() {
Some(0x80) => {
let mut out = Vec::with_capacity(bytes.len());
let mut at = 0usize;
while at + 2 <= bytes.len() && bytes[at] == 0x80 {
let kind = bytes[at + 1];
if kind == 3 {
break;
}
let length = bytes
.get(at + 2..at + 6)
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
.ok_or("a segment header past the end of the font")?;
let start = at + 6;
let end = start
.checked_add(length)
.filter(|&end| end <= bytes.len())
.ok_or("a segment longer than the font")?;
out.extend_from_slice(&bytes[start..end]);
at = end;
}
out
}
Some(b'%') => bytes.to_vec(),
_ => return Err("does not begin with %! or a PFB segment".into()),
};
let eexec = find(&joined, b"eexec", 0).ok_or("the font has no eexec")?;
let clear = &joined[..eexec];
let mut start = eexec + 5;
while joined.get(start).is_some_and(|c| c.is_ascii_whitespace()) {
start += 1;
}
let body = &joined[start..];
let is_hex = body.iter().take(4).all(|c| c.is_ascii_hexdigit());
let binary: Vec<u8> = match is_hex {
false => body.to_vec(),
true => {
let digits: Vec<u8> = body
.iter()
.copied()
.filter(|c| c.is_ascii_hexdigit())
.collect();
digits
.chunks(2)
.filter(|pair| pair.len() == 2)
.map(|pair| {
let value = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
value(pair[0]) << 4 | value(pair[1])
})
.collect()
}
};
let private = decrypt(&binary, EEXEC_KEY, 4);
let (body, trailer) = split_trailer(&joined, start);
let mut font = Type1 {
font_name: text_after(clear, b"/FontName").unwrap_or_default(),
parts: (joined[..start].to_vec(), body.to_vec(), trailer.to_vec()),
..Type1::default()
};
font.font_matrix = numbers_after(clear, b"/FontMatrix")
.try_into()
.unwrap_or([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]);
font.font_bbox = numbers_after(clear, b"/FontBBox")
.try_into()
.unwrap_or_default();
font.italic_angle = numbers_after(clear, b"/ItalicAngle")
.first()
.copied()
.unwrap_or(0.0);
font.stem_v = numbers_after(&private, b"/StdVW").first().copied();
font.read_encoding(clear);
let len_iv = find(&private, b"/lenIV", 0)
.and_then(|at| numbers_after(&private[at..], b"/lenIV").first().copied())
.unwrap_or(4.0) as usize;
font.subroutines = find(&private, b"/Subrs", 0)
.and_then(|at| numbers_after(&private[at..], b"/Subrs").first().copied())
.unwrap_or(0.0) as usize;
font.len_iv = len_iv;
font.read_charstrings(&private, len_iv)?;
font.private = private;
Ok(font)
}
fn read_encoding(&mut self, clear: &[u8]) {
let Some(at) = find(clear, b"/Encoding", 0) else {
return;
};
let rest = &clear[at..];
if find(rest, b"StandardEncoding", 0).is_some_and(|found| found < 40) {
self.uses_standard_encoding = true;
return;
}
let end = find(rest, b"readonly def", 0)
.or_else(|| find(rest, b" def", 0))
.unwrap_or(rest.len());
let mut from = 0usize;
while let Some(found) = find(&rest[..end], b"dup ", from) {
let after = &rest[found + 4..end];
let text: String = after.iter().take(64).map(|&b| b as char).collect();
let mut words = text.split_whitespace();
let code = words.next().and_then(|w| w.parse::<i64>().ok());
let name = words.next().and_then(|w| w.strip_prefix('/'));
if let (Some(code), Some(name)) = (code, name) {
if (0..=255).contains(&code) {
self.encoding.insert(code as u8, name.to_string());
}
}
from = found + 4;
}
}
fn read_charstrings(&mut self, private: &[u8], len_iv: usize) -> Result<(), String> {
let at = find(private, b"/CharStrings", 0)
.ok_or("the decrypted body holds no /CharStrings, so the key was wrong")?;
let mut from = at;
while let Some(slash) = find(private, b"/", from + 1) {
let mut cursor = slash + 1;
let mut name = String::new();
while let Some(&c) = private.get(cursor) {
if c.is_ascii_whitespace() || c == b'(' || c == b'/' || c == b'{' {
break;
}
name.push(c as char);
cursor += 1;
}
let text: String = private
.get(cursor..cursor + 32)
.unwrap_or_default()
.iter()
.map(|&b| b as char)
.collect();
let mut words = text.split_whitespace();
let Some(length) = words.next().and_then(|w| w.parse::<usize>().ok()) else {
from = slash;
continue;
};
let Some(token) = words.next() else {
from = slash;
continue;
};
let Some(token_at) = find(private, token.as_bytes(), cursor) else {
from = slash;
continue;
};
let start = token_at + token.len() + 1;
let Some(bytes) = private.get(start..start + length) else {
from = slash;
continue;
};
let charstring = decrypt(bytes, CHARSTRING_KEY, len_iv);
let (left_side_bearing, width) = width_of(&charstring);
self.glyphs.insert(
name.clone(),
Glyph {
name,
width,
left_side_bearing,
charstring,
},
);
let closing: String = private
.get(start + length..start + length + 16)
.unwrap_or_default()
.iter()
.map(|&b| b as char)
.collect();
self.charstring_tokens = (
token.to_string(),
closing
.split_whitespace()
.next()
.unwrap_or("ND")
.to_string(),
);
from = start + length;
self.charstrings = (at, from);
}
match self.glyphs.is_empty() {
true => Err("the font's /CharStrings holds no glyphs".into()),
false => Ok(()),
}
}
pub fn embeddable(&self) -> (Vec<u8>, usize, usize, usize) {
let (clear, body, trailer) = &self.parts;
let mut bytes = clear.clone();
bytes.extend(body);
bytes.extend(trailer);
(bytes, clear.len(), body.len(), trailer.len())
}
pub fn subset(&self, keep: &std::collections::BTreeSet<String>, tag: &str) -> Option<Type1> {
let kept: Vec<&Glyph> = keep
.iter()
.filter_map(|name| self.glyphs.get(name))
.collect();
if kept.is_empty() || self.private.is_empty() {
return None;
}
let name = format!("{tag}+{}", self.font_name);
let clear = replace_after(
&self.parts.0,
b"/FontName",
&format!(" /{name} def"),
b"def",
)?;
let mut array = String::from(" 256 array\n0 1 255 {1 index exch /.notdef put} for\n");
for (code, glyph) in &self.encoding {
if keep.contains(glyph) {
let _ = writeln!(array, "dup {code} /{glyph} put");
}
}
array.push_str("readonly def");
let clear = replace_after(&clear, b"/Encoding", &array, b"def")?;
let (from, after_last) = self.charstrings;
let tail = word_at(&self.private, b"end", after_last)?;
let (rd, nd) = &self.charstring_tokens;
let mut body = self.private[..from].to_vec();
body.extend(format!("/CharStrings {} dict dup begin\n", kept.len()).into_bytes());
for glyph in &kept {
let bytes = encrypt(&glyph.charstring, CHARSTRING_KEY, self.len_iv);
body.extend(format!("/{} {} {rd} ", glyph.name, bytes.len()).into_bytes());
body.extend(bytes);
body.extend(format!(" {nd}\n").into_bytes());
}
body.extend(self.private[tail..].to_vec());
let mut cut = self.clone();
cut.font_name = name;
cut.glyphs = kept
.iter()
.map(|glyph| (glyph.name.clone(), (*glyph).clone()))
.collect();
cut.encoding.retain(|_, glyph| keep.contains(glyph));
cut.parts = (clear, encrypt(&body, EEXEC_KEY, 4), Vec::new());
cut.private = body;
Some(cut)
}
pub fn glyph(&self, name: &str) -> Option<&Glyph> {
self.glyphs.get(name)
}
pub fn glyph_names(&self) -> Vec<&str> {
self.glyphs.keys().map(String::as_str).collect()
}
pub fn encoded(&self, code: u8) -> Option<&Glyph> {
let name = match self.uses_standard_encoding {
true => crate::sfnt::MAC_GLYPH_NAMES
.get(code as usize)
.copied()
.unwrap_or_default(),
false => self.encoding.get(&code)?.as_str(),
};
self.glyph(name)
}
pub fn summary(&self) -> String {
let mut out = String::new();
out.push_str(&format!("font name {}\n", self.font_name));
out.push_str(&format!(
"matrix {}\n",
self.font_matrix
.iter()
.map(|n| format!("{n}"))
.collect::<Vec<_>>()
.join(" ")
));
out.push_str(&format!(
"bounding box {}\n",
self.font_bbox
.iter()
.map(|n| format!("{n}"))
.collect::<Vec<_>>()
.join(" ")
));
out.push_str(&format!("glyphs {}\n", self.glyphs.len()));
out.push_str(&format!("subroutines {}\n", self.subroutines));
out.push_str(&format!(
"encoding {}\n",
match self.uses_standard_encoding {
true => "StandardEncoding".to_string(),
false => format!("{} characters, the font's own", self.encoding.len()),
}
));
out
}
pub fn describe(&self, code: u8) -> String {
let name = match self.uses_standard_encoding {
true => crate::sfnt::MAC_GLYPH_NAMES
.get(code as usize)
.copied()
.unwrap_or("")
.to_string(),
false => self.encoding.get(&code).cloned().unwrap_or_default(),
};
let shown = match (code as char).is_ascii_graphic() {
true => format!("'{}'", code as char),
false => format!("0o{code:o}"),
};
let Some(glyph) = self.glyph(&name) else {
return format!("{shown}: the font's encoding gives no glyph for it\n");
};
format!(
"{shown} {} width {} side bearing {} charstring {} bytes\n",
glyph.name,
glyph.width,
glyph.left_side_bearing,
glyph.charstring.len()
)
}
}
fn split_trailer(joined: &[u8], start: usize) -> (&[u8], &[u8]) {
let body = &joined[start..];
let Some(last) = body.iter().rposition(|&b| b == b'0') else {
return (body, &body[body.len()..]);
};
let mut at = last + 1;
let mut zeros = 0usize;
while at > 0 {
match body[at - 1] {
b'0' => zeros += 1,
c if c.is_ascii_whitespace() => {}
_ => break,
}
at -= 1;
}
match zeros >= 512 {
true => (&body[..at], &body[at..]),
false => (body, &body[body.len()..]),
}
}
fn text_after(bytes: &[u8], key: &[u8]) -> Option<String> {
let at = find(bytes, key, 0)? + key.len();
let text: String = bytes
.get(at..)?
.iter()
.take(128)
.map(|&b| b as char)
.collect();
let word = text.split_whitespace().next()?;
Some(word.trim_start_matches('/').to_string())
}
fn numbers_after(bytes: &[u8], key: &[u8]) -> Vec<f64> {
let Some(at) = find(bytes, key, 0) else {
return Vec::new();
};
let text: String = bytes[at + key.len()..]
.iter()
.take(128)
.map(|&b| b as char)
.collect();
let text = text.replace(['[', ']', '{', '}'], " ");
let mut out = Vec::new();
for word in text.split_whitespace() {
match word.parse::<f64>() {
Ok(value) => out.push(value),
Err(_) if !out.is_empty() => break,
Err(_) => {}
}
}
out
}
fn width_of(charstring: &[u8]) -> (f64, f64) {
let mut stack: Vec<f64> = Vec::new();
let mut at = 0usize;
while at < charstring.len() {
let byte = charstring[at];
at += 1;
match byte {
32..=246 => stack.push(byte as f64 - 139.0),
247..=250 => {
let Some(&low) = charstring.get(at) else {
break;
};
at += 1;
stack.push((byte as f64 - 247.0) * 256.0 + low as f64 + 108.0);
}
251..=254 => {
let Some(&low) = charstring.get(at) else {
break;
};
at += 1;
stack.push(-(byte as f64 - 251.0) * 256.0 - low as f64 - 108.0);
}
255 => {
let Some(bytes) = charstring.get(at..at + 4) else {
break;
};
at += 4;
stack.push(i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f64);
}
13 => {
return match stack.len() >= 2 {
true => (stack[stack.len() - 2], stack[stack.len() - 1]),
false => (0.0, 0.0),
}
}
12 => {
let Some(&second) = charstring.get(at) else {
break;
};
at += 1;
if second == 7 {
return match stack.len() >= 4 {
true => (stack[stack.len() - 4], stack[stack.len() - 2]),
false => (0.0, 0.0),
};
}
stack.clear();
}
_ => break,
}
}
(0.0, 0.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn installed(name: &str) -> Option<Vec<u8>> {
let found = std::process::Command::new("kpsewhich")
.arg(name)
.output()
.ok()?;
let path = String::from_utf8_lossy(&found.stdout).trim().to_string();
std::fs::read(path).ok()
}
#[test]
fn a_type1_font_gives_up_its_names_and_widths() {
let Some(bytes) = installed("cmr10.pfb") else {
return;
};
let font = Type1::parse(&bytes).expect("cmr10 reads");
assert_eq!(font.font_name, "CMR10");
assert_eq!(font.font_matrix, [0.001, 0.0, 0.0, 0.001, 0.0, 0.0]);
assert_eq!(font.font_bbox, [-40.0, -250.0, 1009.0, 750.0]);
assert!(
font.subroutines > 0,
"a Computer Modern font has subroutines"
);
assert!(
font.glyph_names().len() > 100,
"{}",
font.glyph_names().len()
);
assert!(font.glyph("A").is_some() && font.glyph("space").is_some());
assert!(
font.glyph_names()
.iter()
.all(|name| name.chars().all(|c| c.is_ascii_alphanumeric() || c == '.')),
"a name with rubbish in it means the key was wrong"
);
let a = font.glyph("A").expect("an A");
assert_eq!(a.width, 750.0);
assert_eq!(a.left_side_bearing, 32.0);
assert!(!a.charstring.is_empty());
assert!(!font.uses_standard_encoding);
assert_eq!(font.encoding.get(&65).map(String::as_str), Some("A"));
assert_eq!(font.encoding.get(&11).map(String::as_str), Some("ff"));
assert_eq!(font.encoded(65).map(|g| g.name.as_str()), Some("A"));
}
#[test]
fn the_font_comes_apart_into_the_lengths_a_pdf_wants() {
let Some(bytes) = installed("cmr10.pfb") else {
return;
};
let font = Type1::parse(&bytes).expect("cmr10 reads");
let (embedded, clear, binary, trailer) = font.embeddable();
assert_eq!(embedded.len(), clear + binary + trailer);
assert!(embedded[..clear].starts_with(b"%!"));
assert!(embedded[..clear].ends_with(b"eexec\r") || embedded[..clear].ends_with(b"eexec\n"));
assert!(
embedded[clear..clear + binary]
.iter()
.any(|&b| b > 127 || b == 0),
"the encrypted body reads as text, so the split is wrong"
);
assert!(trailer >= 512, "{trailer}");
assert_eq!(
embedded[clear + binary..]
.iter()
.filter(|&&b| b == b'0')
.count(),
512
);
assert!(bytes.windows(64).any(|w| w == &embedded[..64]));
}
#[test]
fn what_is_not_a_type1_font_is_refused() {
assert!(Type1::parse(b"").is_err());
assert!(Type1::parse(b"not a font").is_err());
assert!(Type1::parse(b"%!PS-AdobeFont-1.0\n/FontName /X def\n")
.unwrap_err()
.contains("eexec"));
let mut wrong = b"%!PS-AdobeFont-1.0\n/FontName /X def\neexec ".to_vec();
wrong.extend([0u8; 64]);
let e = Type1::parse(&wrong).unwrap_err();
assert!(e.contains("/CharStrings"), "{e}");
}
}