fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
//! The names a PDF's simple fonts give their glyphs. LilyPond's music font (Emmentaler, feta) has
//! no code points to go by: each PDF numbers the glyphs it uses as it meets them, and says which
//! is which only by name (`noteheads.s2`, `clefs.G`) in the font's encoding. A Type 1 font also
//! comes to the reader with no name of its own. So the fonts are looked up in the PDF itself: for
//! every font whose name is wanted, each code's glyph is found as the interpreter will find it,
//! and kept under the key the interpreter's glyph has (`OutlineGlyph::identifier`), with the
//! font's name and the glyph's.

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;

/// A glyph's font (its name without a subset's tag) and its own name there.
#[derive(Clone, Debug, PartialEq)]
pub struct Named {
    pub font: String,
    pub glyph: String,
}

/// A font's name without the tag of a subset (`ABCDEF+`).
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,
    }
}

/// The name a code has where the font's encoding gives it none of its own: the standard
/// encodings' names for the digits, the letters and the few signs a music font's numbers and
/// dynamics are set with.
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,
    })
}

/// The names an encoding's `Differences` give the codes.
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
}

/// The fonts the pages name in their resources, and the forms drawn on them in theirs (to three
/// deep), each once.
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
}

/// Every glyph of the PDF's simple fonts whose name `wanted` says yes to, by the interpreter's
/// key for it.
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);
    }
}