use std::collections::BTreeMap;
use crate::frac::Q;
use crate::page::{Glyph, Staff};
use crate::read::{on_staff_for_time, time_of};
use crate::smufl;
use crate::staff::Res;
pub type Time = (i64, i64);
pub struct Seen<'a> {
pub staff_glyphs: &'a [Vec<Glyph>],
pub staves: &'a [Staff],
pub names: &'a [String],
pub first_event: f64,
pub edges: &'a [f64],
pub ev_x: &'a [f64],
pub sp: f64,
pub size: f64,
}
pub type Sign = Option<&'static str>;
pub fn said(t: Time, sign: Sign) -> String {
match sign {
Some(name) => name.to_string(),
None => format!("{}/{}", t.0, t.1),
}
}
pub struct Before<'a> {
pub score: Time,
pub staves: &'a BTreeMap<String, Time>,
pub signs: &'a BTreeMap<String, &'static str>,
pub every: bool,
pub top: &'a str,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Times {
pub at: Vec<Vec<Time>>,
pub score: Vec<Time>,
pub before: Vec<Time>,
pub every: bool,
pub signs: Vec<Vec<Sign>>,
pub score_signs: Vec<Sign>,
}
fn printed(s: &Seen, i: usize, lo: f64, hi: f64) -> Option<Res<(Time, Sign)>> {
let (top, bottom) = (s.staves[i].top(), s.staves[i].bottom());
let ts: Vec<&Glyph> = s.staff_glyphs[i]
.iter()
.filter(|g| smufl::is_time(g.code) && lo <= g.x0 && g.x0 < hi)
.filter(|g| on_staff_for_time(g, top, bottom, s.sp, s.size))
.collect();
let sign = (ts
.iter()
.find(|g| g.code == smufl::COMMON)
.map(|_| "common"))
.or_else(|| ts.iter().find(|g| g.code == smufl::CUT).map(|_| "cut"));
(!ts.is_empty()).then(|| time_of(&ts).map(|t| (t, sign)))
}
pub fn read(s: &Seen, was: &Before) -> Res<Times> {
let n = s.names.len();
let bars = s.edges.len().saturating_sub(1);
let before: Vec<Time> = (s.names.iter())
.map(|name| was.staves.get(name).copied().unwrap_or(was.score))
.collect();
let mut now: Vec<(Time, Sign)> = (s.names.iter().zip(&before))
.map(|(name, t)| {
let whose = match was.staves.contains_key(name) {
true => name.as_str(),
false => "",
};
(*t, was.signs.get(whose).copied())
})
.collect();
let mut score = (was.score, was.signs.get("").copied());
let mut every = was.every;
let mut out = Times {
at: vec![Vec::new(); n],
score: Vec::new(),
before,
every,
signs: vec![Vec::new(); n],
score_signs: Vec::new(),
};
for b in 0..bars {
let (lo, hi) = if b == 0 {
(f64::MIN, s.first_event)
} else {
let within = |a: f64, z: f64| s.ev_x.iter().copied().filter(move |&x| a < x && x < z);
(
within(s.edges[b - 1], s.edges[b]).fold(s.edges[b - 1], f64::max),
within(s.edges[b], s.edges[b + 1]).fold(s.edges[b + 1], f64::min),
)
};
let mut found: Vec<Option<(Time, Sign)>> = Vec::new();
for i in 0..n {
found.push(match printed(s, i, lo, hi) {
Some(t) if i == 0 => Some(t?),
Some(t) => t.ok().or(found[0]),
None => None,
});
}
every |= n > 1 && found.iter().all(|f| f.is_some());
if !every {
if let Some(t) = found[0] {
now.fill(t);
score = t;
}
} else {
for (i, f) in found.iter().enumerate() {
now[i] = f.unwrap_or(now[i]);
}
let alike =
(found.iter()).all(|f| f.is_some() && f.map(|t| t.0) == found[0].map(|t| t.0));
if s.names[0] == was.top {
score = now[0];
} else if alike {
score = now[0];
}
}
for (i, t) in now.iter().enumerate() {
out.at[i].push(t.0);
out.signs[i].push(t.1);
}
out.score.push(score.0);
out.score_signs.push(score.1);
}
out.every = every;
Ok(out)
}
pub fn bar_len(t: Time) -> Q {
Q::new(4 * t.0, t.1)
}
pub fn own_lines(
names: &[String],
(now, signs): (&[Time], &[Sign]),
before: &[Time],
score: Time,
said: bool,
) -> Vec<String> {
let sign = |i: usize| signs.get(i).copied().flatten();
let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
let needs = |i: usize| match said {
true => now[i] != score,
false => now[i] != before[i],
};
let mut lines = Vec::new();
let mut i = 0;
while i < names.len() {
let p = part(&names[i]);
let end = (i..names.len())
.find(|&j| part(&names[j]) != p)
.unwrap_or(names.len());
if (i..end).any(needs) {
if (i..end).all(|j| now[j] == now[i]) {
lines.push(format!("time {p} {}", self::said(now[i], sign(i))));
} else {
for j in (i..end).filter(|&j| needs(j)) {
lines.push(format!("time {} {}", names[j], self::said(now[j], sign(j))));
}
}
}
i = end;
}
lines
}
pub fn lines_for<T: Copy + PartialEq>(
names: &[String],
want: &[T],
common: T,
(score, own): (&mut T, &mut [Option<T>]),
say: &dyn Fn(Option<&str>, T) -> String,
) -> Vec<String> {
let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
let has = |i: usize, score: T, own: &[Option<T>]| own[i].unwrap_or(score);
let mut lines = Vec::new();
if (0..names.len()).all(|i| has(i, *score, own) == want[i]) {
return lines;
}
let all_change = (0..names.len()).all(|i| want[i] == common && has(i, *score, own) != common);
if common != *score || all_change {
lines.push(say(None, common));
*score = common;
own.fill(None);
}
let mut i = 0;
while i < names.len() {
let p = part(&names[i]);
let end = (i..names.len())
.find(|&j| part(&names[j]) != p)
.unwrap_or(names.len());
if (i..end).any(|j| has(j, *score, own) != want[j]) {
if (i..end).all(|j| want[j] == want[i]) {
lines.push(say(Some(&p), want[i]));
own[i..end].fill(Some(want[i]));
} else {
for j in i..end {
if has(j, *score, own) != want[j] {
lines.push(say(Some(&names[j]), want[j]));
own[j] = Some(want[j]);
}
}
}
}
i = end;
}
lines
}
pub fn scales(times: &[Time]) -> Vec<Q> {
(times.iter())
.map(|t| bar_len(times[0]) / bar_len(*t))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn staff(top: f64) -> Staff {
Staff {
lines: [0.0, 10.0, 20.0, 30.0, 40.0].map(|y| top + y),
left: 0.0,
right: 400.0,
breaks: Vec::new(),
}
}
fn digit(d: u32, x: f64, y: f64) -> Glyph {
Glyph {
code: 0xE080 + d,
x0: x,
x1: x + 8.0,
y,
size: 10.0,
}
}
fn sig(n: u32, d: u32, x: f64, top: f64) -> Vec<Glyph> {
vec![digit(n, x, top + 10.0), digit(d, x, top + 30.0)]
}
fn seen<'a>(
glyphs: &'a [Vec<Glyph>],
staves: &'a [Staff],
names: &'a [String],
edges: &'a [f64],
) -> Seen<'a> {
Seen {
staff_glyphs: glyphs,
staves,
names,
first_event: 60.0,
edges,
ev_x: &[100.0, 250.0],
sp: 10.0,
size: 10.0,
}
}
#[test]
fn a_staff_with_no_signature_where_another_changes_keeps_its_time() {
let staves = [staff(0.0), staff(100.0), staff(200.0)];
let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
let mut glyphs: Vec<Vec<Glyph>> =
(0..3).map(|i| sig(6, 8, 30.0, 100.0 * i as f64)).collect();
glyphs[0].extend(sig(2, 4, 210.0, 0.0));
let edges = [0.0, 200.0, 400.0];
let none = BTreeMap::new();
let was = Before {
score: (4, 4),
staves: &none,
signs: &BTreeMap::new(),
every: false,
top: "V",
};
let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
assert!(t.every);
assert_eq!(t.score, vec![(6, 8), (2, 4)]);
assert_eq!(t.at[0], vec![(6, 8), (2, 4)]);
assert_eq!(t.at[1], vec![(6, 8), (6, 8)]);
assert_eq!(t.at[2], vec![(6, 8), (6, 8)]);
assert_eq!(
own_lines(
&names,
(&[(2, 4), (6, 8), (6, 8)], &[]),
&[(6, 8); 3],
(2, 4),
true
),
vec!["time P 6/8"]
);
let held = [(2, 4), (6, 8), (6, 8)];
assert!(own_lines(&names, (&held, &[]), &held, (2, 4), false).is_empty());
assert_eq!(scales(&held), vec![Q::ONE, Q::new(2, 3), Q::new(2, 3)]);
}
#[test]
fn a_signature_printed_once_is_every_staffs() {
let staves = [staff(0.0), staff(100.0)];
let names: Vec<String> = ["P.1", "P.2"].map(String::from).to_vec();
let glyphs = vec![sig(3, 4, 30.0, 0.0), Vec::new()];
let edges = [0.0, 400.0];
let none = BTreeMap::new();
let was = Before {
score: (4, 4),
staves: &none,
signs: &BTreeMap::new(),
every: false,
top: "P.1",
};
let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
assert!(!t.every);
assert_eq!(t.at, vec![vec![(3, 4)], vec![(3, 4)]]);
}
#[test]
fn a_staff_in_its_own_key_says_so_once() {
let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
let say = |who: Option<&str>, k: i32| match who {
Some(n) => format!("key {n} {k} major"),
None => format!("key {k} major"),
};
let (mut score, mut own) = (-3, vec![None; 3]);
let want = [-3, -3, 0];
let lines = lines_for(&names, &want, -3, (&mut score, &mut own), &say);
assert_eq!(lines, vec!["key P.2 0 major"]);
assert!(lines_for(&names, &want, -3, (&mut score, &mut own), &say).is_empty());
let want = [2, 2, 0];
let lines = lines_for(&names, &want, 2, (&mut score, &mut own), &say);
assert_eq!(lines, vec!["key 2 major", "key P.2 0 major"]);
assert_eq!((score, own.clone()), (2, vec![None, None, Some(0)]));
own.fill(Some(1));
assert!(lines_for(&names, &[1, 1, 1], 1, (&mut score, &mut own), &say).is_empty());
let lines = lines_for(&names, &[2, 2, 2], 2, (&mut score, &mut own), &say);
assert_eq!(lines, vec!["key 2 major"]);
assert_eq!(own, vec![None; 3]);
own[0] = Some(0);
let lines = lines_for(&names, &[2, 2, 2], 2, (&mut score, &mut own), &say);
assert_eq!(lines, vec!["key V 2 major"]);
let names: Vec<String> = ["Cl", "P.1", "P.2"].map(String::from).to_vec();
let (mut score, mut own) = (0, vec![None; 3]);
let lines = lines_for(&names, &[2, 0, 0], 0, (&mut score, &mut own), &say);
assert_eq!(lines, vec!["key Cl 2 major"]);
}
#[test]
fn a_time_printed_as_a_sign_is_said_by_its_name() {
let staves = [staff(0.0), staff(100.0)];
let names: Vec<String> = ["P.1", "P.2"].map(String::from).to_vec();
let sign = |code: u32, x: f64, top: f64| Glyph {
code,
x0: x,
x1: x + 8.0,
y: top + 20.0,
size: 10.0,
};
let glyphs: Vec<Vec<Glyph>> = [0.0, 100.0]
.iter()
.map(|&top| vec![sign(smufl::COMMON, 30.0, top), sign(smufl::CUT, 210.0, top)])
.collect();
let edges = [0.0, 200.0, 400.0];
let none = BTreeMap::new();
let was = Before {
score: (4, 4),
staves: &none,
signs: &BTreeMap::new(),
every: false,
top: "P.1",
};
let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
assert_eq!(t.score, vec![(4, 4), (2, 2)]);
assert_eq!(t.score_signs, vec![Some("common"), Some("cut")]);
assert_eq!(said(t.score[0], t.score_signs[0]), "common");
assert_eq!(said(t.score[1], t.score_signs[1]), "cut");
assert_eq!(said((3, 4), None), "3/4");
let signs: BTreeMap<String, &'static str> = [(String::new(), "cut")].into_iter().collect();
let was = Before {
score: (2, 2),
staves: &none,
signs: &signs,
every: true,
top: "P.1",
};
let t = read(
&seen(&[Vec::new(), Vec::new()], &staves, &names, &edges),
&was,
)
.unwrap();
assert_eq!(t.score_signs, vec![Some("cut"), Some("cut")]);
assert_eq!(t.signs[1], vec![Some("cut"), Some("cut")]);
}
#[test]
fn one_staff_of_a_part_in_its_own_time_says_so_alone() {
let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
assert_eq!(
own_lines(
&names,
(&[(2, 4), (2, 4), (6, 8)], &[]),
&[(2, 4); 3],
(2, 4),
false
),
vec!["time P.2 6/8"]
);
}
}