use crate::page::{Page, Staff};
use crate::words::{words_of, Word};
const DASHES: &[char] = &['-', '‐', '‑', '‒', '–', '—', '−', '~'];
const PUNCT: &[char] = &[',', '.', ';', ':', '!', '?', '"', '“', '”'];
const APOS: &[char] = &['\'', '’', 'ʼ', '‘', '`'];
fn apostrophe(c: char) -> char {
match c {
'’' | 'ʼ' => c,
_ => '\'',
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Syl {
pub text: String,
pub x: f64,
pub left: f64,
pub cont: bool,
pub ext: bool,
}
fn is_mark(t: &str, open: bool) -> bool {
is_dynamic(t) && !((open && !t.ends_with('.')) || t == "dim")
}
fn is_dynamic(t: &str) -> bool {
let l = t.to_lowercase();
let l = l.trim_end_matches('.');
matches!(
l,
"p" | "pp"
| "ppp"
| "mp"
| "mf"
| "f"
| "ff"
| "fff"
| "sf"
| "sfz"
| "fp"
| "cresc"
| "dim"
| "rit"
| "rall"
| "8va"
)
}
pub fn band(pg: &Page, staff: &Staff, below: Option<&Staff>, x0: f64, x1: f64) -> Vec<Word> {
let sp = staff.sp();
let lo = staff.bottom() + 0.6 * sp;
let hi = below
.map(|b| b.top() - 0.3 * sp)
.unwrap_or(staff.bottom() + 12.0 * sp);
let mut words: Vec<Word> = words_of(pg)
.into_iter()
.filter(|w| {
let cx = (w.x0 + w.x1) / 2.0;
x0 - sp <= cx && cx <= x1 + sp && lo <= w.base && w.base <= hi
})
.collect();
let mut segs: Vec<(f64, f64, f64)> = pg.hlines.iter().map(|l| (l.x0, l.x1, l.y)).collect();
for p in &pg.polys {
for k in 0..p.len() {
let (a, b) = (p[k], p[(k + 1) % p.len()]);
if (a.1 - b.1).abs() < 0.1 * sp {
segs.push((a.0.min(b.0), a.0.max(b.0), a.1));
}
}
}
for (xa, xb, y) in segs {
if xb - xa < 0.15 * sp || !(x0 - sp <= xa && xa <= x1 + sp && lo - sp <= y && y <= hi) {
continue;
}
let near = words
.iter_mut()
.filter(|w| {
-0.5 * w.size <= y - w.base
&& y - w.base <= 0.15 * w.size
&& -0.1 * sp <= xa - w.x1
&& xa - w.x1 < 4.0 * w.size
})
.min_by(|a, b| (xa - a.x1).total_cmp(&(xa - b.x1)));
if let Some(w) = near {
let rel = (y - w.base) / w.size;
let mark = if rel < -0.15 {
Some('-')
} else if rel > -0.12 {
Some('_')
} else {
None
};
if let Some(m) = mark {
if !w.text.ends_with(m) {
w.text = w.text.trim_end_matches(['-', '_']).to_string();
w.text.push(m);
}
}
}
}
words
}
pub fn verse_lines(words: Vec<Word>, sp: f64) -> Vec<Vec<Word>> {
let mut ws = words;
ws.sort_by(|a, b| a.base.total_cmp(&b.base));
let mut lines: Vec<Vec<Word>> = Vec::new();
for w in ws {
match lines.last_mut() {
Some(l)
if (w.base - l.iter().map(|v| v.base).sum::<f64>() / l.len() as f64).abs()
< 0.9 * sp =>
{
l.push(w)
}
_ => lines.push(vec![w]),
}
}
for l in lines.iter_mut() {
l.sort_by(|a, b| a.x0.total_cmp(&b.x0));
}
lines
}
fn tidy(line: &[Word], sp: f64) -> Vec<Word> {
let (mut syl, mut open) = (false, false);
let mut ws: Vec<Word> = Vec::new();
for w in line {
let w = Word {
text: w.text.trim().to_string(),
..w.clone()
};
let t = w.text.as_str();
if t.is_empty() {
continue;
}
if is_mark(t, open)
|| t.chars()
.all(|c| c.is_ascii_digit() || c == '(' || c == ')')
{
(syl, open) = (false, false);
continue;
}
if t.chars().all(|c| DASHES.contains(&c)) {
open = syl;
} else if !t.chars().all(|c| PUNCT.contains(&c) || APOS.contains(&c)) {
syl = true;
open = t.trim_end_matches(PUNCT).ends_with(DASHES);
}
ws.push(w);
}
let mut out: Vec<Word> = Vec::new();
let mut i = 0;
while i < ws.len() {
let t = ws[i].text.clone();
if t.chars().all(|c| PUNCT.contains(&c)) {
if let Some(p) = out.last_mut() {
p.text.push_str(&t);
}
i += 1;
continue;
}
if t.chars().all(|c| APOS.contains(&c)) {
let a = t.chars().next().map_or('\'', apostrophe);
let gl = out.last().map(|p| ws[i].x0 - p.x1).unwrap_or(1e18);
let gr = ws.get(i + 1).map(|n| n.x0 - ws[i].x1).unwrap_or(1e18);
let prev_dash = out.last().is_some_and(|p| p.text.ends_with(DASHES));
if !out.is_empty() && i + 1 < ws.len() && gl < 0.6 * sp && gr < 0.6 * sp && !prev_dash {
let n = ws[i + 1].clone();
let p = out.last_mut().unwrap();
p.text.push(a);
p.text.push_str(&n.text);
p.x1 = n.x1;
i += 2;
continue;
}
if i + 1 < ws.len() && gr < 0.6 * sp {
let x0 = ws[i].x0;
ws[i + 1].text.insert(0, a);
ws[i + 1].x0 = x0;
} else if let Some(p) = out.last_mut() {
p.text.push(a);
}
i += 1;
continue;
}
out.push(ws[i].clone());
i += 1;
}
out
}
pub fn syllables(line: &[Word], sp: f64) -> Vec<Syl> {
let mut out: Vec<Syl> = Vec::new();
for w in tidy(line, sp) {
let t = w.text.as_str();
if t.chars().all(|c| DASHES.contains(&c) || c == '_') {
if let Some(p) = out.last_mut() {
if t.contains('_') {
p.ext = true;
} else {
p.cont = true;
}
}
continue;
}
let ext = t.trim_end_matches(PUNCT).ends_with('_');
let t: String = t.chars().filter(|&c| c != '_').collect();
let t = t.as_str();
let chars: Vec<char> = t.chars().collect();
let n = chars.len().max(1) as f64;
let mut segs: Vec<Syl> = Vec::new();
let mut pos = 0usize;
let mut k = 0;
while k < chars.len() {
let dash = DASHES.contains(&chars[k]);
let mut e = k;
while e < chars.len() && DASHES.contains(&chars[e]) == dash {
e += 1;
}
if dash {
if let Some(s) = segs.last_mut() {
s.cont = true;
}
} else {
let a = w.x0 + (w.x1 - w.x0) * pos as f64 / n;
let b = w.x0 + (w.x1 - w.x0) * (pos + e - k) as f64 / n;
segs.push(Syl {
text: chars[k..e].iter().collect(),
x: (a + b) / 2.0,
left: a,
cont: false,
ext: false,
});
}
pos += e - k;
k = e;
}
if segs.is_empty() {
continue;
}
if chars.first().is_some_and(|c| DASHES.contains(c)) {
if let Some(p) = out.last_mut() {
p.cont = true;
}
}
if ext {
segs.last_mut().unwrap().ext = true;
}
out.extend(segs);
}
out
}
pub fn align(syls: &[Syl], notes_x: &[f64], sp: f64) -> Vec<Option<usize>> {
let (m, n) = (syls.len(), notes_x.len());
let (skip_note, skip_syl) = (1.5, 25.0);
let mut d = vec![vec![1e18f64; n + 1]; m + 1];
let mut back = vec![vec![0u8; n + 1]; m + 1];
for j in 0..=n {
d[0][j] = j as f64 * skip_note;
}
for i in 1..=m {
d[i][0] = i as f64 * skip_syl;
back[i][0] = 2;
for j in 1..=n {
let (s, x) = (&syls[i - 1], notes_x[j - 1]);
let off = (s.x - x).abs().min((s.left + 0.6 * sp - x).abs());
let c = [
d[i - 1][j - 1] + off / sp,
d[i][j - 1] + skip_note,
d[i - 1][j] + skip_syl,
];
let (k, v) = c
.iter()
.enumerate()
.fold((0, f64::MAX), |b, (k, &v)| if v < b.1 { (k, v) } else { b });
d[i][j] = v;
back[i][j] = k as u8;
}
}
let (mut i, mut j) = (m, n);
let mut res = vec![None; m];
while i > 0 {
if j == 0 || back[i][j] == 2 {
i -= 1;
} else if back[i][j] == 0 {
res[i - 1] = Some(j - 1);
i -= 1;
j -= 1;
} else {
j -= 1;
}
}
res
}
pub fn clean(t: &str) -> String {
let mut s = String::new();
for c in t.trim().chars() {
match c {
'‘' => s.push('\''),
c if c.is_whitespace() => s.push_str("\\ "),
'*' | '_' | '#' | '\\' => s.extend(['\\', c]),
c => s.push(c),
}
}
if s.is_empty() {
"?".into()
} else {
s
}
}
#[cfg(test)]
mod tests {
use super::*;
fn w(text: &str, x0: f64) -> Word {
Word {
text: text.into(),
x0,
x1: x0 + 6.0 * text.chars().count() as f64,
base: 100.0,
size: 10.0,
}
}
#[test]
fn a_syllable_keeps_the_marks_the_format_reads_after_a_backslash() {
assert_eq!(clean("to the"), "to\\ the");
assert_eq!(clean(" *"), "\\*");
assert_eq!(clean("a_b#"), "a\\_b\\#");
assert_eq!(clean("l’a"), "l’a");
assert_eq!(clean("lʼa"), "lʼa");
assert_eq!(clean("l'a"), "l'a");
assert_eq!(clean("‘ta"), "'ta");
assert_eq!(clean(" "), "?");
let fmn = "part V \"V\" voice\nkey 0 major\ntime 2/4\nbar 1\nV: c5/4 d5\nV lyrics: ";
let line = format!("{fmn}{} {}\n", clean("to the"), clean("a_b#"));
let xml = fm_transcribe::compile(&line).unwrap().musicxml;
assert!(xml.contains("<text>to the</text>") && xml.contains("<text>a_b#</text>"));
let line = format!("{fmn}{} {}\n", clean("l’a"), clean("tʼa"));
let xml = fm_transcribe::compile(&line).unwrap().musicxml;
assert!(xml.contains("<text>l’a</text>") && xml.contains("<text>tʼa</text>"));
}
#[test]
fn an_apostrophe_set_apart_joins_its_word_as_printed() {
let texts = |ws: &[Word]| -> Vec<String> {
syllables(ws, 5.0).into_iter().map(|s| s.text).collect()
};
assert_eq!(texts(&[w("l", 0.0), w("’", 6.5), w("a", 13.0)]), ["l’a"]);
assert_eq!(texts(&[w("l", 0.0), w("ʼ", 6.5), w("a", 13.0)]), ["lʼa"]);
assert_eq!(texts(&[w("l", 0.0), w("'", 6.5), w("a", 13.0)]), ["l'a"]);
assert_eq!(texts(&[w("l", 0.0), w("‘", 6.5), w("a", 13.0)]), ["l'a"]);
assert_eq!(texts(&[w("’", 0.0), w("ta", 6.5)]), ["’ta"]);
assert_eq!(texts(&[w("ta", 0.0), w("’", 40.0)]), ["ta’"]);
}
#[test]
fn syllables_keep_their_hyphens_and_holds() {
let s = syllables(
&[w("lo-", 0.0), w("ra", 40.0), w("mi_", 80.0), w(",", 98.0)],
5.0,
);
let t: Vec<(&str, bool, bool)> =
s.iter().map(|s| (s.text.as_str(), s.cont, s.ext)).collect();
assert_eq!(
t,
[
("lo", true, false),
("ra", false, false),
("mi,", false, true)
]
);
}
#[test]
fn a_word_after_a_hyphen_or_before_one_is_a_syllable_not_a_mark() {
let texts = |ws: &[Word]| -> Vec<(String, bool, bool)> {
syllables(ws, 5.0)
.into_iter()
.map(|s| (s.text, s.cont, s.ext))
.collect()
};
let s = |t: &str, cont: bool, ext: bool| (t.to_string(), cont, ext);
assert_eq!(
texts(&[w("me-", 0.0), w("rit", 40.0)]),
[s("me", true, false), s("rit", false, false)]
);
assert_eq!(
texts(&[w("ca", 0.0), w("-", 20.0), w("dim", 40.0)]),
[s("ca", true, false), s("dim", false, false)]
);
assert_eq!(
texts(&[w("so-", 0.0), w("f", 40.0), w("ter", 60.0)]),
[
s("so", true, false),
s("f", false, false),
s("ter", false, false)
]
);
assert_eq!(
texts(&[w("rit-", 0.0), w("ual", 40.0)]),
[s("rit", true, false), s("ual", false, false)]
);
assert_eq!(texts(&[w("dim_", 0.0)]), [s("dim", false, true)]);
assert_eq!(
texts(&[w("la", 0.0), w("rit.", 40.0), w("lo", 80.0)]),
[s("la", false, false), s("lo", false, false)]
);
assert_eq!(
texts(&[w("molto-", 0.0), w("cresc.", 60.0), w("lo", 90.0)]),
[s("molto", true, false), s("lo", false, false)]
);
assert_eq!(
texts(&[w("la", 0.0), w("mf", 40.0)]),
[s("la", false, false)]
);
assert_eq!(
texts(&[
w("the", 0.0),
w("dim", 30.0),
w("Dim.", 60.0),
w("dim.", 90.0)
]),
[s("the", false, false), s("dim", false, false)]
);
assert_eq!(
texts(&[
w("cresc.", 0.0),
w("-", 40.0),
w("dim.", 60.0),
w("lo", 90.0)
]),
[s("lo", false, false)]
);
}
#[test]
fn a_syllable_finds_its_note_and_a_stray_one_none() {
let syl = |x: f64| Syl {
text: "x".into(),
x,
left: x - 3.0,
cont: false,
ext: false,
};
let at = align(&[syl(10.0), syl(30.0), syl(31.0)], &[10.0, 30.0], 5.0);
assert_eq!(at, [Some(0), Some(1), None]);
}
}