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
//! `cargo run -p fm-vector --example fontdump -- SCORE.pdf [PAGES]`: every font of the first
//! pages and the glyphs it sets, as tab-separated lines (font name, font key, character code,
//! Unicode, count, advance, outline as an SVG path in thousandths of the font size). For finding
//! out what a music font this reader does not know calls its glyphs.

use std::collections::BTreeMap;

use hayro_interpret::font::{Glyph as PdfGlyph, GlyphRun};
use hayro_interpret::hayro_cmap::BfString;
use hayro_interpret::kurbo::{BezPath, Rect};
use hayro_interpret::{
    interpret_page, BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image,
    ImageDrawProps, InterpreterCache, InterpreterSettings, SoftMask,
};

/// A glyph as set: its Unicode, how often, its advance and its outline.
type Seen = (u32, usize, f32, String, u128);

#[derive(Default)]
struct Fonts {
    // by font name, font key and character code
    seen: BTreeMap<(String, u128, u32), Seen>,
}

impl<'a> Device<'a> for Fonts {
    fn draw_path(&mut self, _: &BezPath, _: DrawProps<'a>, _: &DrawMode) {}
    fn draw_rect(&mut self, _: &Rect, _: DrawProps<'a>, _: &DrawMode) {}
    fn push_clip_path(&mut self, _: &ClipPath) {}
    fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
    fn draw_glyph_run(&mut self, run: &GlyphRun<'_, 'a>, props: DrawProps<'a>, _: &DrawMode) {
        for g in run.glyphs() {
            let size = (props.transform * g.transform()).determinant().abs().sqrt() * 1000.0;
            let uni = match g.as_unicode() {
                Some(BfString::Char(c)) => c as u32,
                Some(BfString::String(s)) => s.chars().next().map_or(0, |c| c as u32),
                None => 0,
            };
            let glyph_key = match &**g {
                PdfGlyph::Outline(og) => og.identifier().cache_key(),
                PdfGlyph::Type3(_) => 0,
            };
            let (name, key, adv, path) = match &**g {
                PdfGlyph::Outline(og) => {
                    let (name, key) = match og.font_data() {
                        Some(d) => (d.postscript_name.unwrap_or_default(), d.cache_key),
                        // (no key to be had: by size, as the reader groups them)
                        None => (
                            format!("(type 1 at {:.2})", (size * 4.0).round() / 4.0),
                            (size * 4.0).round() as u128,
                        ),
                    };
                    (
                        name,
                        key,
                        og.advance_width().unwrap_or(0.0),
                        og.outline().to_svg(),
                    )
                }
                PdfGlyph::Type3(t3) => (
                    "(type 3)".to_string(),
                    1,
                    t3.advance_width().unwrap_or(0.0),
                    String::new(),
                ),
            };
            let e = self
                .seen
                .entry((name, key, g.char_code()))
                .or_insert((uni, 0, adv, path, glyph_key));
            e.1 += 1;
        }
    }
    fn draw_image(&mut self, _: Image<'a, '_>, _: ImageDrawProps<'a>) {}
    fn pop_clip(&mut self) {}
    fn pop_transparency_group(&mut self) {}
}

fn main() {
    let a: Vec<String> = std::env::args().collect();
    let bytes = std::fs::read(&a[1]).expect("reading the PDF");
    let pages: usize = a.get(2).and_then(|n| n.parse().ok()).unwrap_or(3);
    let Ok(pdf) = hayro_syntax::Pdf::new(bytes) else {
        eprintln!("not a PDF it can open");
        return;
    };
    let cache = InterpreterCache::new();
    let mut dev = Fonts::default();
    for page in pdf.pages().iter().take(pages) {
        let (w, h) = page.render_dimensions();
        let t = hayro_interpret::kurbo::Affine::new(page.initial_transform(true).as_coeffs());
        let mut ctx = Context::new(
            t,
            Rect::new(0.0, 0.0, w as f64, h as f64),
            &cache,
            pdf.xref(),
            InterpreterSettings::default(),
        );
        interpret_page(page, &mut ctx, &mut dev);
    }
    // (the last column: the font's name and the glyph's, where the PDF's fonts give them)
    let names = fm_vector::names::glyph_names(&pdf, |_| true);
    for ((name, key, code), (uni, n, adv, path, glyph_key)) in dev.seen {
        let named = names
            .get(&glyph_key)
            .map_or(String::new(), |n| format!("{}/{}", n.font, n.glyph));
        println!(
            "{name}\t{:08x}\t{code}\t{uni:04X}\t{n}\t{adv}\t{path}\t{named}",
            key as u32
        );
    }
}