use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use hayro_font::{CMapResolverFn, FontCache, FontGlyph, FontResolverFn, GlyphId};
use hayro_syntax::object::{Array, Dict, Name, Object, Stream};
use hayro_syntax::Pdf;
#[derive(Clone, Debug, PartialEq)]
pub struct Named {
pub font: String,
pub glyph: String,
}
pub fn untagged(name: &str) -> &str {
match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest,
_ => name,
}
}
fn standard_name(code: u8) -> Option<String> {
const DIGITS: [&str; 10] = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
Some(match code {
b'0'..=b'9' => DIGITS[(code - b'0') as usize].to_string(),
b'a'..=b'z' | b'A'..=b'Z' => (code as char).to_string(),
b'+' => "plus".to_string(),
b'-' => "hyphen".to_string(),
b',' => "comma".to_string(),
b'.' => "period".to_string(),
b' ' => "space".to_string(),
_ => return None,
})
}
fn differences(font: &Dict<'_>) -> HashMap<u8, String> {
let mut out = HashMap::new();
let Some(diffs) = font
.get::<Dict<'_>>("Encoding")
.and_then(|e| e.get::<Array<'_>>("Differences"))
else {
return out;
};
let mut code = 0_i64;
for obj in diffs.iter::<Object<'_>>() {
match obj {
Object::Number(n) => code = n.as_i64(),
Object::Name(name) => {
if let Ok(c) = u8::try_from(code) {
out.insert(c, name.as_str().to_string());
}
code += 1;
}
_ => {}
}
}
out
}
fn font_dicts(pdf: &Pdf) -> Vec<Dict<'_>> {
fn gather<'a>(
fonts: &Dict<'a>,
forms: &Dict<'a>,
depth: usize,
seen: &mut HashSet<(usize, usize)>,
out: &mut Vec<Dict<'a>>,
) {
for key in fonts.keys() {
if let Some(d) = fonts.get::<Dict<'a>>(&*key) {
if seen.insert((d.data().as_ptr() as usize, d.data().len())) {
out.push(d);
}
}
}
if depth == 3 {
return;
}
for key in forms.keys() {
let Some(form) = forms.get::<Stream<'a>>(&*key) else {
continue;
};
let d = form.dict();
if !seen.insert((d.data().as_ptr() as usize, d.data().len())) {
continue;
}
if let Some(res) = d.get::<Dict<'a>>("Resources") {
let fonts = res.get::<Dict<'a>>("Font").unwrap_or_default();
let forms = res.get::<Dict<'a>>("XObject").unwrap_or_default();
gather(&fonts, &forms, depth + 1, seen, out);
}
}
}
let (mut seen, mut out) = (HashSet::new(), Vec::new());
for page in pdf.pages().iter() {
let res = page.resources();
gather(&res.fonts, &res.x_objects, 0, &mut seen, &mut out);
}
out
}
pub fn glyph_names(pdf: &Pdf, wanted: fn(&str) -> bool) -> HashMap<u128, Named> {
let mut out = HashMap::new();
let no_font: FontResolverFn = Arc::new(|_| None);
let no_cmap: CMapResolverFn = Arc::new(|_| None);
let cache = FontCache::new();
for dict in font_dicts(pdf) {
let simple = dict
.get::<Name<'_>>("Subtype")
.is_some_and(|s| matches!(s.as_str(), "Type1" | "MMType1" | "TrueType"));
let Some(base) = dict.get::<Name<'_>>("BaseFont") else {
continue;
};
let name = untagged(base.as_str()).to_string();
if !simple || !wanted(&name) {
continue;
}
let Some(font) = cache.font(&dict, &no_font, &no_cmap) else {
continue;
};
let diffs = differences(&dict);
for code in 0..=255u8 {
let Some(glyph) = diffs.get(&code).cloned().or_else(|| standard_name(code)) else {
continue;
};
let gid = font.map_code(code as u32);
if gid == GlyphId::NOTDEF {
continue;
}
if let FontGlyph::Outline(og) = font.glyph(gid, code as u32) {
out.entry(og.identifier().cache_key()).or_insert(Named {
font: name.clone(),
glyph,
});
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_subset_s_tag_is_not_the_font_s_name() {
assert_eq!(untagged("PERCCM+Emmentaler-20"), "Emmentaler-20");
assert_eq!(untagged("Emmentaler-20"), "Emmentaler-20");
assert_eq!(untagged("A+B"), "A+B");
}
#[test]
fn a_code_with_no_name_of_its_own_has_the_standard_one() {
assert_eq!(standard_name(b'4').as_deref(), Some("four"));
assert_eq!(standard_name(b'f').as_deref(), Some("f"));
assert_eq!(standard_name(0xCF), None);
}
}