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
//! A system's jumps and endings: the segno and coda signs (music-font glyphs,
//! often from the font's text companion), the words that say where to go
//! ("To Coda", "D.S. al Coda", "D.C. al Fine", "Fine"), and the endings'
//! brackets with their numbers ("1.", "1, 2"), each placed on its bar.
//!
//! A sign stands at the start of its bar, over the barline before it; the
//! words of a jump stand at the end of theirs, right-aligned to its barline.
//! Only what is printed above the system's top staff is taken: the words
//! under a staff are a song's.

use crate::layout::System;
use crate::page::Page;
use crate::words::{words_of, Word};

/// What a system's bars carry: (bar index, `jump` name) and (bar index,
/// ending numbers as `1` or `1,2`).
#[derive(Debug, Default, PartialEq)]
pub struct Marks {
    pub jumps: Vec<(usize, &'static str)>,
    pub endings: Vec<(usize, String)>,
    /// The ending whose bracket runs on past the system's end (no hook closes it there).
    pub runs_on: Option<String>,
}

const SEGNO: u32 = 0xE047;
const CODA: u32 = 0xE048;

/// Words on one baseline that run on, as phrases ("D.S. al Coda").
pub fn phrases(words: Vec<Word>) -> Vec<Word> {
    let mut ws = words;
    ws.sort_by(|a, b| a.base.total_cmp(&b.base).then(a.x0.total_cmp(&b.x0)));
    let mut out: Vec<Word> = Vec::new();
    for w in ws {
        match out.last_mut() {
            Some(p)
                if (w.base - p.base).abs() < 0.2 * p.size
                    && w.x0 >= p.x1 - 0.1 * p.size
                    && w.x0 - p.x1 < 0.6 * p.size.max(w.size) =>
            {
                p.text.push(' ');
                p.text.push_str(&w.text);
                p.x1 = w.x1;
            }
            _ => out.push(w),
        }
    }
    out
}

/// A phrase as a jump's name, when it is one.
pub fn jump_named(text: &str) -> Option<&'static str> {
    let t: String = text
        .to_lowercase()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let t = t.trim_end_matches(['.', ',', ';', ':', '!']);
    let al = |rest: &str| -> Option<&'static str> {
        let rest = rest.trim();
        if rest.is_empty() {
            Some("")
        } else if rest.starts_with("al coda") {
            Some("-al-coda")
        } else if rest.starts_with("al fine") {
            Some("-al-fine")
        } else {
            None
        }
    };
    for (lead, name) in [
        ("d.s.", "ds"),
        ("dal segno", "ds"),
        ("d.c.", "dc"),
        ("da capo", "dc"),
    ] {
        if let Some(rest) = t.strip_prefix(lead) {
            return match (name, al(rest)?) {
                ("ds", "") => Some("ds"),
                ("ds", "-al-coda") => Some("ds-al-coda"),
                ("ds", _) => Some("ds-al-fine"),
                (_, "") => Some("dc"),
                (_, "-al-coda") => Some("dc-al-coda"),
                _ => Some("dc-al-fine"),
            };
        }
    }
    match t {
        "to coda" => Some("to-coda"),
        "fine" => Some("fine"),
        _ => None,
    }
}

/// An ending's number as printed ("1.", "2", "1, 2."), as `1` or `1,2`.
pub fn ending_numbers(text: &str) -> Option<String> {
    let t = text.trim().trim_end_matches('.');
    let nums: Vec<&str> = t.split(',').map(str::trim).collect();
    if nums.iter().all(|n| {
        !n.is_empty() && n.len() <= 2 && n.chars().all(|c| c.is_ascii_digit()) && *n != "0"
    }) {
        Some(nums.join(","))
    } else {
        None
    }
}

/// The marks over a system whose bars stand between the given edges (left,
/// right). `ceiling` is where the system's band begins (the system above's
/// last staff, or the page's top); `carried`, the ending whose bracket ran on
/// from the system before.
pub fn marks(
    pg: &Page,
    sys: &System,
    bars: &[(f64, f64)],
    ceiling: f64,
    carried: Option<&str>,
) -> Marks {
    let mut out = Marks::default();
    let (Some(top), Some(&(first_left, _)), Some(&(_, last_right))) =
        (sys.staves.first(), bars.first(), bars.last())
    else {
        return out;
    };
    let sp = top.sp();
    let above = |y: f64| ceiling < y && y < top.top();
    let containing = |x: f64| bars.iter().position(|&(l, r)| l <= x && x < r);
    // a sign stands over its bar's opening barline, or inside it
    let starting = |x: f64| {
        bars.iter()
            .position(|&(l, _)| (l - x).abs() < 1.5 * sp)
            .or_else(|| containing(x))
    };
    // words of a jump end at their bar's closing barline
    let ending_at = |x1: f64| containing((x1 - sp).clamp(first_left, last_right - 0.01));

    let ps: Vec<Word> = phrases(
        words_of(pg)
            .into_iter()
            .filter(|w| above(w.base) && w.x1 > first_left - sp && w.x0 < last_right + 2.0 * sp)
            .collect(),
    );
    let mut to_codas: Vec<&Word> = Vec::new();
    for p in &ps {
        if let Some(name) = jump_named(&p.text) {
            if let Some(b) = ending_at(p.x1) {
                out.jumps.push((b, name));
            }
            if name == "to-coda" {
                to_codas.push(p);
            }
        } else if let Some(nums) = ending_numbers(&p.text) {
            // the bracket: a line over the number, starting by it
            let bracket = pg.hlines.iter().find(|l| {
                l.y < p.base
                    && p.base - l.y < 2.5 * p.size
                    && (l.x0 - p.x0).abs() < 1.5 * p.size
                    && l.x1 - l.x0 > 2.0 * sp
            });
            if let Some(l) = bracket {
                for (b, &(bl, br)) in bars.iter().enumerate() {
                    let mid = (bl + br) / 2.0;
                    if l.x0 - sp <= mid && mid <= l.x1 + sp {
                        out.endings.push((b, nums.clone()));
                    }
                }
                if runs_past(pg, l, last_right, sp) {
                    out.runs_on = Some(nums.clone());
                }
            }
        }
    }
    // an ending's bracket run on from the system before: a line over the first bars with no
    // number at its start
    if let Some(nums) = carried {
        let numbered: Vec<f64> = out.endings.iter().map(|e| bars[e.0].0).collect();
        let line = pg.hlines.iter().find(|l| {
            above(l.y)
                && top.top() - l.y < 8.0 * sp
                && l.x0 < first_left + 2.0 * sp
                && l.x1 - l.x0 > 2.0 * sp
                && !numbered.iter().any(|&x| (x - l.x0).abs() < 2.0 * sp)
        });
        if let Some(l) = line {
            for (b, &(bl, br)) in bars.iter().enumerate() {
                let mid = (bl + br) / 2.0;
                if mid <= l.x1 + sp && !out.endings.iter().any(|e| e.0 == b) {
                    out.endings.push((b, nums.to_string()));
                }
            }
            if runs_past(pg, l, last_right, sp) {
                out.runs_on = Some(nums.to_string());
            }
        }
    }
    out.endings.sort();
    for g in pg
        .glyphs
        .iter()
        .filter(|g| (g.code == SEGNO || g.code == CODA) && above(g.y))
    {
        let x = (g.x0 + g.x1) / 2.0;
        if x < first_left - sp || x > last_right + sp {
            continue;
        }
        // the coda sign printed with "To Coda" is that jump's, not a coda
        if g.code == CODA
            && to_codas.iter().any(|t| {
                g.x0 < t.x1 + 3.0 * t.size
                    && g.x1 > t.x0 - t.size
                    && (g.y - t.base).abs() < 4.0 * t.size
            })
        {
            continue;
        }
        if let Some(b) = starting(x) {
            out.jumps
                .push((b, if g.code == SEGNO { "segno" } else { "coda" }));
        }
    }
    out.jumps.sort();
    out.jumps.dedup();
    out
}

/// Whether an ending's bracket reaches the system's end open (no hook down at its end).
fn runs_past(pg: &Page, l: &crate::page::HLine, last_right: f64, sp: f64) -> bool {
    l.x1 > last_right - sp
        && !pg.vlines.iter().any(|v| {
            (v.x - l.x1).abs() < 0.4 * sp && (v.y0 - l.y).abs() < 0.4 * sp && v.y1 - v.y0 > sp
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_words_of_a_jump_are_known() {
        assert_eq!(jump_named("D.S. al Coda"), Some("ds-al-coda"));
        assert_eq!(jump_named("D.C.  al  Fine"), Some("dc-al-fine"));
        assert_eq!(jump_named("Dal Segno"), Some("ds"));
        assert_eq!(jump_named("To Coda"), Some("to-coda"));
        assert_eq!(jump_named("Fine"), Some("fine"));
        assert_eq!(jump_named("fine day"), None);
        assert_eq!(jump_named("D.S. somewhere"), None);
        assert_eq!(ending_numbers("1, 2"), Some("1,2".into()));
        assert_eq!(ending_numbers("2."), Some("2".into()));
        assert_eq!(ending_numbers("Gm"), None);
    }
}