use std::collections::BTreeSet;
use crate::marks::{Bars, Open, Sys};
use crate::page::Page;
use crate::staff::Rest;
use crate::words::Word;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Dashed {
pub x0: f64,
pub x1: f64,
pub y: f64,
}
pub fn lines(pg: &Page, sp: f64) -> Vec<Dashed> {
let mut out: Vec<Dashed> = pg
.dashed
.iter()
.filter(|h| h.x1 - h.x0 > 1.5 * sp)
.map(|h| Dashed {
x0: h.x0,
x1: h.x1,
y: h.y,
})
.collect();
let mut pieces: Vec<(f64, f64, f64)> = pg
.hlines
.iter()
.filter(|h| h.x1 - h.x0 > 0.2 * sp && h.x1 - h.x0 < 1.5 * sp)
.filter(|h| !pg.dashed.iter().any(|d| *d == **h))
.map(|h| (h.y, h.x0, h.x1))
.collect();
pieces.sort_by(|a, b| {
((a.0 * 10.0).round())
.total_cmp(&(b.0 * 10.0).round())
.then(a.1.total_cmp(&b.1))
});
let mut run: Vec<(f64, f64, f64)> = Vec::new();
let mut flush = |run: &mut Vec<(f64, f64, f64)>| {
if run.len() >= 3 {
out.push(Dashed {
x0: run[0].1,
x1: run.last().unwrap().2,
y: run[0].0,
});
}
run.clear();
};
for p in pieces {
let follows = run.last().is_some_and(|l| {
let len = l.2 - l.1;
(p.0 - l.0).abs() < 0.15
&& ((p.2 - p.1) - len).abs() < 0.25 * len
&& p.1 > l.2 + 0.2 * len
&& p.1 < l.2 + 2.5 * len
});
if !follows {
flush(&mut run);
}
run.push(p);
}
flush(&mut run);
out
}
fn after(lines: &[Dashed], w: &Word, sp: f64) -> Option<usize> {
(0..lines.len())
.filter(|&k| {
let l = &lines[k];
l.x0 > w.x1 - 0.5 * sp
&& l.x0 < w.x1 + 2.0 * sp
&& l.y < w.base + 0.1 * w.size
&& l.y > w.base - 0.75 * w.size
})
.min_by(|&a, &b| lines[a].x0.total_cmp(&lines[b].x0))
}
pub fn phrases_with_dashes(pg: &Page, sp: f64, words: &[Word]) -> Vec<bool> {
let lines = lines(pg, sp);
if lines.is_empty() {
return vec![false; words.len()];
}
let with: Vec<Word> = crate::jumps::phrases(words.to_vec())
.into_iter()
.filter(|p| after(&lines, p, sp).is_some())
.collect();
words
.iter()
.map(|w| {
with.iter().any(|p| {
(w.base - p.base).abs() < 0.2 * p.size && w.x0 > p.x0 - 0.01 && w.x1 < p.x1 + 0.01
})
})
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Role {
Plain,
Opens,
Continues,
}
#[derive(Debug, Default)]
pub struct Plan {
roles: Vec<Role>,
runs: Vec<(usize, f64, f64, Option<usize>)>,
opened: BTreeSet<usize>,
ended: Vec<usize>,
late: Vec<(usize, String)>,
at_end: Vec<(String, String)>,
texts: Vec<String>,
}
fn in_parentheses(text: &str) -> bool {
let t = text.trim();
t.starts_with('(') && t.ends_with(')')
}
impl Plan {
pub fn new(
s: &Sys,
phrases: &[Word],
staff_of: impl Fn(&Word) -> Option<usize>,
open: &Open,
) -> Plan {
let (open, at_end, words_open) = (&open.dashes, &open.words_at_end, &open.dashes_words);
let sp = s.sp;
let mut plan = Plan {
roles: vec![Role::Plain; phrases.len()],
texts: phrases.iter().map(|p| unparenthesized(&p.text)).collect(),
..Plan::default()
};
let (lo, hi) = (s.top() - 8.0 * sp, s.bottom() + 6.0 * sp);
let (left, right) = (s.bars[0].0 - 3.0 * sp, s.right + sp);
let lines: Vec<Dashed> = lines(s.pg, sp)
.into_iter()
.filter(|l| lo < l.y && l.y < hi && left < l.x0 && l.x1 < right + sp)
.collect();
let open_by = |i: usize| -> usize {
let has = |j: usize| open.contains(&s.names[j]);
match has(i) {
true => i,
false => (i.saturating_sub(1)..(i + 2).min(s.staves.len()))
.find(|&j| has(j))
.unwrap_or(i),
}
};
let mut found: Vec<(usize, f64, f64, Option<usize>, bool)> = Vec::new();
for (k, p) in phrases.iter().enumerate() {
let (Some(i), Some(l)) = (staff_of(p), after(&lines, p, sp)) else {
continue;
};
if (found.iter()).any(|f| {
f.3.is_some_and(|q| after(&lines, &phrases[q], sp) == Some(l))
}) {
continue;
}
let l = &lines[l];
let said = unparenthesized(&p.text).to_lowercase();
let stood = at_end.iter().find(|(_, t)| {
let t = t.to_lowercase();
!t.is_empty() && said.starts_with(&t)
});
let by_open = open_by(i);
let same = words_open.get(&s.names[by_open]).is_some_and(|t| {
let t = t.to_lowercase();
t.starts_with(&said) || said.starts_with(&t)
});
let again = p.x0 < s.first_event + 4.0 * sp
&& (in_parentheses(&p.text)
|| (open.contains(&s.names[by_open]) && same)
|| stood.is_some());
let i = match (again, stood) {
(true, _) if open.contains(&s.names[by_open]) => by_open,
(true, Some((name, _))) => s.names.iter().position(|n| n == name).unwrap_or(i),
_ => i,
};
found.push((i, l.x0, l.x1, Some(k), again));
}
for l in &lines {
let taken = found
.iter()
.any(|f| (f.1 - l.x0).abs() < 0.01 && f.2 == l.x1);
if taken || l.x0 > s.first_event + 2.0 * sp {
continue;
}
let i = open_by(nearest(s, l.y).0);
if open.contains(&s.names[i]) {
found.push((i, l.x0, l.x1, None, true));
}
}
found.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
for i in 0..s.staves.len() {
let mut until: Option<f64> = open.contains(&s.names[i]).then_some(f64::MIN);
let mut first = true;
for &(_, x0, x1, k, again) in found.iter().filter(|f| f.0 == i) {
let carried = first && until == Some(f64::MIN);
let was_first = first;
first = false;
if again {
if carried {
if let Some(k) = k {
plan.roles[k] = Role::Continues;
}
plan.runs.push((i, x0, x1, None));
until = Some(x1);
}
if let (Some(k), true, None) = (k, was_first, until) {
plan.roles[k] = Role::Continues;
plan.runs.push((i, x0, x1, None));
plan.late.push((i, unparenthesized(&phrases[k].text)));
until = Some(x1);
}
continue;
}
if carried {
plan.ended.push(i);
until = None;
}
if until.is_some_and(|u| x0 < u - 0.5 * sp) {
continue; }
if let Some(k) = k {
plan.roles[k] = Role::Opens;
plan.runs.push((i, x0, x1, Some(k)));
until = Some(x1);
}
}
if first && until == Some(f64::MIN) {
plan.ended.push(i);
}
}
plan
}
pub fn role(&mut self, k: usize) -> Role {
let r = self.roles.get(k).copied().unwrap_or(Role::Plain);
if r == Role::Opens {
self.opened.insert(k);
}
r
}
pub fn wrote(&mut self, s: &Sys, i: usize, x: f64, text: &str) {
if s.bars.last().is_some_and(|b| x > b.0) {
self.at_end.push((s.names[i].clone(), text.to_string()));
}
}
pub fn close(&self, s: &Sys, bars: &mut Bars, open: &mut Open) {
for (i, words) in &self.late {
open.dashes.insert(s.names[*i].clone());
open.dashes_late.push((s.names[*i].clone(), words.clone()));
open.dashes_words.insert(s.names[*i].clone(), words.clone());
}
open.words_at_end = self.at_end.clone();
let words = &mut open.dashes_words;
let open = &mut open.dashes;
for &i in &self.ended {
if open.remove(&s.names[i]) {
put_first(bars, i);
}
}
for &(i, _, x1, k) in &self.runs {
match k {
Some(k) if !self.opened.contains(&k) => continue,
None if !open.contains(&s.names[i]) => continue,
_ => {}
}
if x1 > s.right - 2.5 * s.sp {
open.insert(s.names[i].clone());
if let Some(t) = k.and_then(|k| self.texts.get(k)) {
words.insert(s.names[i].clone(), t.clone());
}
} else {
open.remove(&s.names[i]);
put_end(bars, s, i, x1);
}
}
}
}
fn unparenthesized(text: &str) -> String {
let t = text.trim();
t.trim_start_matches('(')
.trim_end_matches(')')
.trim()
.to_string()
}
pub fn open_late(done: &mut String, late: &mut Vec<(String, String)>) {
for (staff, words) in late.drain(..) {
let words = words.to_lowercase();
let from = done
.rmatch_indices("\nbar ")
.nth(1)
.map_or(0, |(k, _)| k + 1);
let mut at: Option<usize> = None;
let mut pos = from;
for line in done[from..].split_inclusive('\n') {
let head = line.split(':').next().unwrap_or("");
let base = head.split('/').next().unwrap_or(head);
if base == staff && !head.contains(' ') {
let mut k = 0;
while let Some(q) = line[k..].find('"') {
let open = k + q;
let Some(len) = line[open + 1..].find('"') else {
break;
};
let close = open + 1 + len;
let inner = line[open + 1..close].to_lowercase();
let marks = line[..open].ends_with(" ^") || line[..open].ends_with(" _");
let plain = !line[close + 1..].starts_with("--");
if marks
&& plain
&& !inner.is_empty()
&& (words.starts_with(&inner) || inner.starts_with(&words))
{
at = Some(pos + close + 1);
}
k = close + 1;
}
}
pos += line.len();
}
if let Some(at) = at {
done.insert_str(at, "--");
}
}
}
fn nearest(s: &Sys, y: f64) -> (usize, f64) {
let d = |j: usize| {
let st = &s.staves[j];
if y < st.top() {
st.top() - y
} else if y > st.bottom() {
y - st.bottom()
} else {
0.0
}
};
(0..s.staves.len())
.map(|j| (j, d(j)))
.min_by(|a, b| a.1.total_cmp(&b.1))
.unwrap_or((0, 0.0))
}
const END: &str = "\\--";
fn put_first(bars: &mut Bars, i: usize) {
for bar in bars.iter_mut() {
if let Some(e) = bar[i]
.iter_mut()
.find(|e| e.rest != Rest::Blank && e.grace.is_none())
{
e.before.insert(0, END.to_string());
return;
}
}
}
fn put_end(bars: &mut Bars, s: &Sys, i: usize, x: f64) {
let b = s
.bars
.iter()
.position(|&(_, r)| x < r + 0.5 * s.sp)
.unwrap_or(s.bars.len() - 1);
let evs = &mut bars[b][i];
if let Some(e) = evs
.iter_mut()
.filter(|e| e.rest != Rest::Blank && e.grace.is_none())
.find(|e| e.x >= x - 1.0 * s.sp)
{
e.before.insert(0, END.to_string());
} else if let Some(e) = evs.iter_mut().rev().find(|e| e.grace.is_none()) {
e.after.push(END.to_string());
}
}
pub fn mend(done: &mut String, text: &mut String, msg: &str) -> Option<String> {
let msg = msg.lines().last().unwrap_or("");
let bar_of = |m: &str| -> Option<String> {
let n: String = m
.strip_prefix("bar ")?
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '-')
.collect();
(!n.is_empty()).then_some(n)
};
if let Some(k) = msg.find(": a line of dashes opens in ") {
let who = msg[k + ": a line of dashes opens in ".len()..]
.split(' ')
.next()?;
let bar = bar_of(msg)?;
return strip(text, &bar, who, false)
.then(|| format!("a line of dashes after words, one being open (bar {bar})"));
}
if let Some(k) = msg.find(" ends no line of dashes in ") {
let who = msg[k + " ends no line of dashes in ".len()..].trim();
let bar = bar_of(msg)?;
return strip(text, &bar, who, true)
.then(|| format!("a line of dashes' end with no start (bar {bar})"));
}
if let Some(rest) = msg.strip_prefix("a line of dashes in ") {
let who = rest.split(' ').next()?;
let bar = bar_of(rest.split(" from ").nth(1)?)?;
return (strip(text, &bar, who, false) || strip(done, &bar, who, false))
.then(|| format!("a line of dashes with no end (bar {bar})"));
}
None
}
fn strip(s: &mut String, bar: &str, who: &str, end: bool) -> bool {
let staff = who.split('/').next().unwrap_or(who);
let (part, n) = staff.rsplit_once('.').unwrap_or((staff, "1"));
let mine = |head: &str| {
let base = head.split('/').next().unwrap_or(head);
base == staff || (n == "1" && base == part)
};
let mut out: Vec<String> = Vec::new();
let mut on = false;
let mut cut: Option<(usize, usize)> = None; for (li, line) in s.lines().enumerate() {
if let Some(n) = line.strip_prefix("bar ") {
on = n.split_whitespace().next() == Some(bar);
}
let head = line.split(':').next().unwrap_or("");
if on && !head.contains(' ') && mine(head) && line.contains(':') {
let mut quoted = false;
for (ti, t) in line.split(' ').enumerate() {
let was = quoted;
if t.matches('"').count() % 2 == 1 {
quoted = !quoted;
}
if end && !was && t == END && cut.is_none() {
cut = Some((li, ti));
}
if !end && !quoted && t.ends_with("\"--") {
cut = Some((li, ti));
}
}
}
out.push(line.to_string());
}
let Some((li, ti)) = cut else { return false };
let toks: Vec<&str> = out[li].split(' ').collect();
let mut kept: Vec<String> = Vec::new();
for (k, t) in toks.iter().enumerate() {
if k != ti {
kept.push(t.to_string());
} else if !end {
kept.push(t[..t.len() - 2].to_string());
}
}
out[li] = kept.join(" ");
let tail = if s.ends_with('\n') { "\n" } else { "" };
*s = out.join("\n") + tail;
true
}
#[cfg(test)]
mod tests {
use super::*;
use crate::page::{Glyph, HLine, Staff};
use crate::staff::Ev;
fn staves() -> [Staff; 2] {
let staff = |top: f64| Staff {
lines: [top, top + 1.0, top + 2.0, top + 3.0, top + 4.0],
left: 0.0,
right: 60.0,
breaks: Vec::new(),
};
[staff(100.0), staff(112.0)]
}
fn notes_at(xs: &[f64], y: f64) -> Vec<Ev> {
xs.iter()
.map(|&x| {
let head = Glyph {
code: 0xE0A4,
x0: x,
x1: x + 1.2,
y,
size: 4.0,
};
Ev::new(vec![head], None, None)
})
.collect()
}
fn word(text: &str, x0: f64, x1: f64, base: f64) -> Word {
Word {
text: text.into(),
x0,
x1,
base,
size: 2.0,
}
}
fn marks_of(evs: &[Ev]) -> String {
evs.iter()
.map(|e| format!("{}|{}", e.before.join(" "), e.after.join(" ")))
.collect::<Vec<_>>()
.join(" , ")
}
#[test]
fn dashes_are_a_dashed_stroke_or_even_short_pieces() {
let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
let pg = Page {
dashed: vec![h(10.0, 30.0, 50.0)],
hlines: vec![
h(10.0, 30.0, 50.0),
h(40.0, 40.5, 60.0),
h(41.0, 41.5, 60.0),
h(42.0, 42.5, 60.0),
h(43.0, 43.5, 60.0),
h(44.0, 44.5, 60.0),
h(50.0, 58.0, 60.0),
h(70.0, 71.0, 61.0),
h(70.0, 71.0, 62.0),
],
..Page::default()
};
let found = lines(&pg, 1.0);
assert_eq!(found.len(), 2);
assert_eq!((found[0].x0, found[0].x1), (10.0, 30.0));
assert_eq!((found[1].x0, found[1].x1), (40.0, 44.5));
}
#[test]
fn words_with_a_line_of_dashes_open_it_and_the_line_s_end_closes_it() {
let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
let st = staves();
let pg = Page {
dashed: vec![h(8.5, 22.0, 106.2), h(49.0, 59.0, 118.4)],
..Page::default()
};
let names = ["P.1".to_string(), "P.2".to_string()];
let none = BTreeSet::new();
let s = Sys {
pg: &pg,
staves: &st,
names: &names,
bars: &[(0.0, 30.0), (30.0, 60.0)],
sp: 1.0,
right: 60.0,
first_event: 4.0,
ceiling: 0.0,
floor: 0.0,
sung: &none,
};
let phrases = [
word("cresc.", 4.0, 8.0, 107.0),
word("dim.", 34.0, 37.0, 107.0),
word("rit.", 44.0, 48.0, 119.0),
];
let staff_of = |w: &Word| Some(if w.base < 110.0 { 0 } else { 1 });
let mut open = Open::default();
let mut plan = Plan::new(&s, &phrases, staff_of, &open);
assert_eq!(
[plan.role(0), plan.role(1), plan.role(2)],
[Role::Opens, Role::Plain, Role::Opens]
);
let mut bars: Bars = vec![
vec![notes_at(&[4.0, 14.0, 24.0], 102.0), notes_at(&[4.0], 114.0)],
vec![
notes_at(&[34.0, 44.0], 102.0),
notes_at(&[34.0, 50.0], 114.0),
],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][0]), "| , | , \\--|");
assert_eq!(marks_of(&bars[1][1]), "| , |");
assert_eq!(open.dashes.iter().collect::<Vec<_>>(), ["P.2"]);
let pg = Page {
dashed: vec![h(9.0, 20.0, 118.4)],
..Page::default()
};
let s = Sys { pg: &pg, ..s };
assert_eq!(open.dashes_words["P.2"], "rit.");
let phrases = [
word("(rit.)", 4.0, 8.5, 119.0),
word("(sempre)", 4.0, 8.5, 107.0),
];
let mut plan = Plan::new(&s, &phrases, staff_of, &open);
assert_eq!([plan.role(0), plan.role(1)], [Role::Continues, Role::Plain]);
let mut bars: Bars = vec![
vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][1]), "| , \\--|");
assert!(open.dashes.is_empty() && open.dashes_late.is_empty());
let mut plan = Plan::new(&s, &phrases, staff_of, &open);
assert_eq!([plan.role(0), plan.role(1)], [Role::Continues, Role::Plain]);
let mut bars: Bars = vec![
vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][1]), "| , \\--|");
assert_eq!(open.dashes_late, [("P.2".to_string(), "rit.".to_string())]);
let mut done = String::from(
"bar 6\nP.2: _\"rit.\" c3/1\nbar 7\nP.1: ^\"rit.\" c5/1\nP.2: c3/2 _\"Rit.\" c3\nbar 8\nP.2/2: c3/2 ^\"dolce\" _\"rit.\"-- c3 \\--\n",
);
open_late(&mut done, &mut open.dashes_late);
assert_eq!(
done,
"bar 6\nP.2: _\"rit.\" c3/1\nbar 7\nP.1: ^\"rit.\" c5/1\nP.2: c3/2 _\"Rit.\"-- c3\nbar 8\nP.2/2: c3/2 ^\"dolce\" _\"rit.\"-- c3 \\--\n"
);
assert!(open.dashes_late.is_empty());
let mut open = Open {
dashes: ["P.2".to_string()].into(),
dashes_words: [("P.2".to_string(), "rit.".to_string())].into(),
..Open::default()
};
let phrases = [word("a tempo", 4.0, 8.5, 119.0)];
let mut plan = Plan::new(&s, &phrases, staff_of, &open);
assert_eq!(plan.role(0), Role::Opens);
let mut bars: Bars = vec![
vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][1]), "\\--| , \\--|");
let mut open = Open {
dashes: ["P.1".to_string()].into(),
..Open::default()
};
let pg = Page::default();
let s = Sys { pg: &pg, ..s };
let plan = Plan::new(&s, &[], staff_of, &open);
let mut bars: Bars = vec![
vec![notes_at(&[4.0], 102.0), notes_at(&[4.0], 114.0)],
vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][0]), "\\--|");
assert!(open.dashes.is_empty());
let pg = Page {
dashed: vec![h(12.0, 20.0, 110.4)],
..Page::default()
};
let s = Sys { pg: &pg, ..s };
let mut plan = Plan::new(&s, &[], staff_of, &open);
plan.wrote(&s, 0, 20.0, "cresc.");
plan.wrote(&s, 0, 50.0, "dim. e");
let mut bars: Bars = vec![vec![notes_at(&[4.0], 102.0), notes_at(&[4.0], 114.0)]; 2];
plan.close(&s, &mut bars, &mut open);
assert_eq!(
open.words_at_end,
[("P.1".to_string(), "dim. e".to_string())]
);
let phrases = [word("dim. e rall.", 4.0, 11.5, 111.0)];
let mut plan = Plan::new(&s, &phrases, |_| Some(1), &open);
assert_eq!(plan.role(0), Role::Continues);
let mut bars: Bars = vec![
vec![notes_at(&[4.0, 22.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
];
plan.close(&s, &mut bars, &mut open);
assert_eq!(marks_of(&bars[0][0]), "| , \\--|");
assert_eq!(
open.dashes_late,
[("P.1".to_string(), "dim. e rall.".to_string())]
);
assert!(open.words_at_end.is_empty());
}
#[test]
fn a_line_of_dashes_the_compiler_will_not_have_is_taken_out() {
let mut done = String::from("bar 1\nP.1: R\n");
let mut text = String::from("bar 2\nP.1: c5/2 \\-- c5\nP.2: \\-- c3/1\n");
let what = mend(
&mut done,
&mut text,
"bar 2: \\-- ends no line of dashes in P.1/1",
);
assert_eq!(
what.as_deref(),
Some("a line of dashes' end with no start (bar 2)")
);
assert_eq!(text, "bar 2\nP.1: c5/2 c5\nP.2: \\-- c3/1\n");
let mut done = String::from("bar 1\nV: _\"poco a poco cresc.\"-- c5/1\n");
let mut text = String::from("bar 2\nV: R\n");
let msg = "a line of dashes in V.1/1 from bar 1 is never closed (\\--)";
assert!(mend(&mut done, &mut text, msg).is_some());
assert_eq!(done, "bar 1\nV: _\"poco a poco cresc.\" c5/1\n");
let mut text = String::from("bar 3\nP.2/2: _\"a\"-- c3/2 _\"b\"-- c3\n");
let msg = "bar 3: a line of dashes opens in P.2/2 while the one from bar 3 is open (close it with \\--)";
assert!(mend(&mut done, &mut text, msg).is_some());
assert_eq!(text, "bar 3\nP.2/2: _\"a\"-- c3/2 _\"b\" c3\n");
assert!(mend(&mut done, &mut text, "bar 3: a tie never lands").is_none());
}
}