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
//! Small notes that are sung: a syllable of a verse stands under one. A grace note carries no
//! syllable of its own, so such a note is another verse's (its rhythm where it differs from the
//! first verse's, printed small) and takes time in its bar.

use std::collections::BTreeSet;

use crate::lyrics;
use crate::marks::Bars;
use crate::page::{Page, Staff};
use crate::words::Word;

/// A syllable's middle: its letters', without the hyphen or extender read after it.
fn middle(w: &Word) -> Option<f64> {
    let text = w.text.trim_end_matches(['-', '_']);
    let letters = text.chars().filter(|c| c.is_alphabetic()).count();
    if letters == 0 || text.starts_with('(') {
        return None;
    }
    // (the mark added after the word widens it by nothing: the word's own extent)
    Some((w.x0 + w.x1) / 2.0)
}

/// The syllables' middles under a sung staff: those of its verse lines (a line of four words
/// or more; a word alone under the staff is a mark). None when the staff has one verse: small
/// notes another verse sings stand only where there is another verse (a lone verse's syllable
/// under a small note is an appoggiatura's, sung on the beat and taking the next note's time).
fn syllables(pg: &Page, staff: &Staff, below: Option<&Staff>, x0: f64, x1: f64) -> Vec<f64> {
    let sp = staff.sp();
    let lines: Vec<Vec<Word>> = lyrics::verse_lines(lyrics::band(pg, staff, below, x0, x1), sp)
        .into_iter()
        .filter(|line| line.len() >= 4)
        .collect();
    if lines.len() < 2 {
        return Vec::new();
    }
    lines
        .iter()
        .flat_map(|line| line.iter().filter_map(middle))
        .collect()
}

/// Mark the small notes of the sung staves that a syllable stands under (`sung_small`): the
/// syllable's middle within 0.8 of a space of the small note's head's, and no full-size note
/// of the staff as near it by a space or more.
pub fn mark_sung(
    pg: &Page,
    staves: &[Staff],
    sung: &BTreeSet<usize>,
    bars: &mut Bars,
    left: f64,
    right: f64,
) {
    for &i in sung {
        let Some(staff) = staves.get(i) else { continue };
        let sp = staff.sp();
        if !bars.iter().any(|b| b[i].iter().any(|e| e.grace.is_some())) {
            continue;
        }
        let syls = syllables(pg, staff, staves.get(i + 1), left, right);
        let mid = |e: &crate::staff::Ev| (e.left() + e.right()) / 2.0;
        let full: Vec<f64> = bars
            .iter()
            .flat_map(|b| b[i].iter())
            .filter(|e| e.is_note() && e.grace.is_none())
            .map(mid)
            .collect();
        for e in bars.iter_mut().flat_map(|b| b[i].iter_mut()) {
            // (a slashed small note is an acciaccatura, never sung for time)
            if e.grace != Some(false) || !e.is_note() {
                continue;
            }
            let x = mid(e);
            e.sung_small = syls.iter().any(|&s| {
                let d = (s - x).abs();
                d < 0.8 * sp && full.iter().all(|&f| (s - f).abs() > d + 1.0 * sp)
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::page::{Glyph, Letter};
    use crate::staff::Ev;

    fn note(x: f64, small: bool) -> Ev {
        let head = Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + if small { 0.8 } else { 1.2 },
            y: 102.0,
            size: if small { 2.6 } else { 4.0 },
        };
        let mut e = Ev::new(vec![head], None, Some(true));
        e.grace = small.then_some(false);
        e
    }

    fn word(text: &str, x: f64, base: f64, run: usize) -> Vec<Letter> {
        text.chars()
            .enumerate()
            .map(|(k, ch)| Letter {
                ch,
                x0: x + k as f64 * 0.5,
                x1: x + k as f64 * 0.5 + 0.5,
                base,
                size: 2.0,
                run,
            })
            .collect()
    }

    /// Which small notes are sung, under one verse line or (with `second`) two.
    fn sung(second: bool) -> Vec<bool> {
        let staff = Staff {
            lines: [100.0, 101.0, 102.0, 103.0, 104.0],
            left: 0.0,
            right: 60.0,
            breaks: Vec::new(),
        };
        // full-size notes at 10, 20, 30, 40; a small note at 16 with "June" under it, and a
        // small note at 38.4 before the note at 40 with nothing of its own under it
        let mut pg = Page::default();
        let first = [
            ("the", 9.8),
            ("June", 15.4),
            ("ro", 20.1),
            ("ses", 29.9),
            ("blow", 39.6),
        ];
        let other = [("a", 9.8), ("b", 20.1), ("c", 29.9), ("d", 39.6)];
        for (k, (t, x)) in first.into_iter().enumerate() {
            pg.letters.extend(word(t, x, 108.0, k));
        }
        if second {
            for (k, (t, x)) in other.into_iter().enumerate() {
                pg.letters.extend(word(t, x, 111.0, 10 + k));
            }
        }
        let evs = vec![
            note(10.0, false),
            note(16.0, true),
            note(20.0, false),
            note(30.0, false),
            note(38.4, true),
            note(40.0, false),
        ];
        let mut bars: Bars = vec![vec![evs]];
        mark_sung(&pg, &[staff], &[0].into(), &mut bars, 0.0, 60.0);
        bars[0][0].iter().map(|e| e.sung_small).collect()
    }

    #[test]
    fn a_small_note_with_a_syllable_under_it_is_sung() {
        assert_eq!(sung(true), [false, true, false, false, false, false]);
    }

    #[test]
    fn under_a_lone_verse_a_small_note_is_an_appoggiatura() {
        assert_eq!(sung(false), [false; 6]);
    }
}