use crate::layout::System;
use crate::page::Page;
use crate::words::{words_of, Word};
#[derive(Debug, Default, PartialEq)]
pub struct Marks {
pub jumps: Vec<(usize, &'static str)>,
pub endings: Vec<(usize, String)>,
pub runs_on: Option<String>,
}
const SEGNO: u32 = 0xE047;
const CODA: u32 = 0xE048;
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
}
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,
}
}
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
}
}
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);
let starting = |x: f64| {
bars.iter()
.position(|&(l, _)| (l - x).abs() < 1.5 * sp)
.or_else(|| containing(x))
};
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) {
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());
}
}
}
}
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;
}
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
}
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);
}
}