use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
pub use fm_transcribe::BarText;
use crate::options::{self, Seen};
use crate::read::{Reading, Refusal};
use crate::staff::{Ev, Rest};
thread_local! {
static ON: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn on() -> bool {
ON.with(Cell::get)
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Review {
pub reading: Reading,
pub questions: Vec<Question>,
pub latent: Vec<Question>,
pub bars: Vec<BarPlace>,
pub marks: Vec<NoteMark>,
pub pages: Vec<[f64; 2]>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Question {
pub id: String,
pub bar: String,
pub bars: Vec<String>,
pub staves: Vec<String>,
pub kind: String,
pub ask: String,
pub why: String,
pub page: usize,
pub spot: Vec<[f64; 4]>,
pub choices: Vec<Choice>,
#[cfg_attr(feature = "serde", serde(default))]
pub draft: Vec<BarText>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Choice {
pub label: String,
pub rewrite: Vec<BarText>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BarPlace {
pub bar: String,
pub page: usize,
pub system: usize,
pub frame: [f64; 4],
pub staves: Vec<(String, f64, f64)>,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NoteMark {
pub bar: String,
pub staff: String,
pub page: usize,
pub at: [f64; 2],
pub pitch: String,
pub length: String,
}
pub(crate) fn marks_of(
vs: &[Vec<Ev>],
bar: i64,
staff: &str,
page: usize,
fifths: i32,
) -> Vec<NoteMark> {
let mut evs: Vec<&Ev> = (vs.iter().flatten())
.filter(|e| e.rest == Rest::None && !e.heads.is_empty())
.collect();
evs.sort_by(|a, b| a.x.total_cmp(&b.x));
let mut force: BTreeMap<i32, i32> = BTreeMap::new();
let mut out = Vec::new();
for e in evs {
for (&p, &(a, _)) in &e.accs {
force.insert(p, a);
}
let length = match e.grace {
Some(_) => "grace".to_string(),
None => crate::write::dur_token(e.dur).unwrap_or_default(),
};
for (h, &p) in e.heads.iter().zip(&e.place_of) {
let alt =
(force.get(&p).copied()).unwrap_or_else(|| crate::write::key_alter(fifths, p));
out.push(NoteMark {
bar: bar.to_string(),
staff: staff.to_string(),
page,
at: [(h.x0 + h.x1) / 2.0, h.y],
pitch: crate::write::pitch_name(p, alt),
length: length.clone(),
});
}
}
out
}
fn kind_of(why: &str) -> &'static str {
let table: [(&str, &str); 12] = [
("leaves staves out", "part"),
("beamed with the part's other staff", "cross-staff"),
("tuplet's number", "tuplet"),
("two voices' notes", "chord-voices"),
("one head", "chord-voices"),
("dot", "dot"),
("two voices that do not each fill", "rest-or-longer"),
("do not stand where", "rest-or-longer"),
("do not add up to the time", "other"),
("lasts ", "other"),
("grace note", "other"),
("small notes", "other"),
];
(table.iter())
.find(|(k, _)| why.contains(k))
.map_or("other", |(_, v)| v)
}
fn ask_of(kind: &str) -> &'static str {
match kind {
"dot" => "Which note does the circled dot belong to?",
"tuplet" => "Which notes does the circled tuplet number group?",
"rest-or-longer" => {
"The circled notes do not fill the bar as printed. Which reading times them right: a voice resting, entering later, or holding a longer note?"
}
"cross-staff" => {
"These notes are beamed with the other staff's. Which reading of the two staves is right?"
}
"chord-voices" => "Which notes of the circled chords belong to which voice?",
"part" => "This system leaves staves out. Which part does it show?",
_ => "As read, this bar does not add up. Which reading of the circled notes is right?",
}
}
fn reason(why: &str) -> &str {
match why.strip_prefix("bar ") {
Some(r) => r.split_once(": ").map_or(why, |(_, w)| w),
None => why,
}
}
fn ottavas(fmn: &str, bar: &str, staff: &str) -> Vec<String> {
let mut lines = fmn.lines();
let head = |l: &str| {
l.strip_prefix("bar ")
.and_then(|r| r.strip_prefix(bar))
.is_some_and(|r| r.is_empty() || r.starts_with(' '))
};
if !lines.any(head) {
return Vec::new();
}
let own = |l: &str| {
l.strip_prefix(staff)
.is_some_and(|r| r.starts_with(':') || (r.starts_with('/') && r.contains(':')))
};
(lines.take_while(|l| !l.starts_with("bar ")))
.filter(|l| own(l))
.flat_map(|l| l.split_whitespace())
.filter(|t| ["\\8va", "\\8vb", "\\15ma", "\\15mb", "\\loco"].contains(t))
.map(str::to_string)
.collect()
}
fn bar_text(fmn: &str, bar: i64, staff: &str, lines: &[String]) -> BarText {
let bar = bar.to_string();
let marks = ottavas(fmn, &bar, staff);
let mut lines = lines.to_vec();
if let (false, Some(first)) = (marks.is_empty(), lines.first_mut()) {
if let Some((name, rest)) = first.split_once(':') {
*first = format!("{name}: {}{rest}", marks.join(" "));
}
}
BarText {
staff: staff.to_string(),
bar,
fmn: lines.join("\n"),
}
}
fn compiles(fmn: &str, rewrite: &[BarText]) -> bool {
fm_transcribe::replace_bars(fmn, rewrite)
.and_then(|t| fm_transcribe::compile(&t))
.is_ok()
}
fn leave_as_rest(staves: &[String], bars: &[String]) -> Choice {
let rewrite = (bars.iter())
.flat_map(|b| {
staves.iter().map(move |s| BarText {
staff: s.clone(),
bar: b.clone(),
fmn: format!("{s}: R"),
})
})
.collect();
Choice {
label: "Leave it as a rest".into(),
rewrite,
}
}
fn spot_of(s: (f64, f64, f64, f64)) -> [f64; 4] {
[s.0, s.1, s.2, s.3]
}
fn parts_of(fmn: &str) -> Vec<(String, String)> {
(fmn.lines())
.filter_map(|l| l.strip_prefix("part "))
.filter_map(|r| {
let (id, rest) = r.split_once(' ')?;
let name = rest.split('"').nth(1).unwrap_or(id);
Some((id.to_string(), name.to_string()))
})
.collect()
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Ask {
Unread,
Latent,
Ink,
}
struct Build<'a> {
r: &'a Reading,
seen: &'a BTreeMap<(i64, String), Seen>,
}
impl Build<'_> {
fn page_and_spot(
&self,
bar: i64,
staff: &str,
spot: Option<(f64, f64, f64, f64)>,
) -> (usize, Vec<[f64; 4]>) {
let place = self.r.places.get(&(bar, staff.to_string()));
let page = place.map_or(0, |p| p.page.saturating_sub(1));
let spot = match (spot, place) {
(Some(s), _) => vec![spot_of(s)],
(None, Some(p)) => vec![[p.x0, p.y0, p.x1, p.y1]],
(None, None) => Vec::new(),
};
(page, spot)
}
fn one(&self, bar: i64, staff: &str, why: &str, ask: Ask) -> Option<Question> {
let latent = ask != Ask::Unread;
let s = self.seen.get(&(bar, staff.to_string()));
let mut opts = match s {
Some(s) => {
let given = match latent {
true => (s.read.as_ref().ok()).and_then(|vs| options::lines_of(vs, staff, s)),
false => None,
};
options::of(s, staff, given.as_deref())
}
None => options::Options {
choices: Vec::new(),
spot: None,
readings: Vec::new(),
},
};
if ask == Ask::Latent {
opts.without("as read");
}
let labels = s.map_or_else(Vec::new, |s| options::labels(s, &opts));
let fmn = &self.r.fmn;
let mut choices: Vec<Choice> = Vec::new();
for (k, ((lines, from), label)) in opts.choices.iter().zip(labels).enumerate() {
let slurred = match (latent, s, opts.readings.get(k)) {
(true, Some(s), Some(vs)) => options::lines_slurred(vs, staff, s),
_ => None,
};
let ways = slurred.iter().chain(std::iter::once(lines));
let Some(rewrite) = ways
.map(|ls| vec![bar_text(fmn, bar, staff, ls)])
.find(|rw| compiles(fmn, rw))
else {
continue;
};
let label = match (*from, latent) {
("as read", _) => format!("As read: {label}"),
_ => label,
};
choices.push(Choice { label, rewrite });
}
if ask == Ask::Latent && choices.is_empty() {
return None;
}
let staves = vec![staff.to_string()];
let bars = vec![bar.to_string()];
if !latent && choices.len() == 1 {
choices.push(leave_as_rest(&staves, &bars));
}
let draft = match (ask, s) {
(Ask::Unread | Ask::Ink, Some(s)) => draft_of(s, staff)
.map(|ls| vec![bar_text(fmn, bar, staff, &ls)])
.unwrap_or_default(),
_ => Vec::new(),
};
let kind = match ask {
Ask::Latent => s.map_or("other", |s| latent_kind(&s.events)),
Ask::Ink => "ink",
Ask::Unread => kind_of(why),
};
let (page, spot) = self.page_and_spot(bar, staff, opts.spot);
Some(Question {
id: format!(
"{}{bar}-{staff}",
match ask {
Ask::Unread => "q",
Ask::Latent => "latent-",
Ask::Ink => "ink-",
}
),
bar: bar.to_string(),
bars,
staves,
kind: kind.into(),
ask: match ask {
Ask::Latent => "Which reading of this bar is right?",
Ask::Ink => {
"Something printed in this bar is not in its reading. Which reading is right?"
}
Ask::Unread => ask_of(kind),
}
.into(),
why: reason(why).to_string(),
page,
spot,
choices,
draft,
})
}
fn joint(&self, bar: i64, staff: &str, mate: &str, why: &str) -> Option<Question> {
let mine = self.seen.get(&(bar, staff.to_string()))?;
let theirs = self.seen.get(&(bar, mate.to_string()))?;
let my = options::of(mine, staff, None);
let first = my.choices.first()?;
let opts = options::of(theirs, mate, None);
let labels = options::labels(theirs, &opts);
let fmn = &self.r.fmn;
let mut choices = Vec::new();
for ((lines, _), label) in opts.choices.iter().zip(labels) {
let rewrite = vec![
bar_text(fmn, bar, mate, lines),
bar_text(fmn, bar, staff, &first.0),
];
if compiles(fmn, &rewrite) {
choices.push(Choice { label, rewrite });
}
}
if choices.is_empty() {
return None;
}
let staves = vec![mate.to_string(), staff.to_string()];
let bars = vec![bar.to_string()];
if choices.len() < 2 {
choices.push(leave_as_rest(&staves, &bars));
}
let draft = [(mate, theirs), (staff, mine)]
.iter()
.filter_map(|(st, s)| draft_of(s, st).map(|ls| bar_text(fmn, bar, st, &ls)))
.collect();
let (page, mut spot) = self.page_and_spot(bar, mate, opts.spot);
spot.extend(self.page_and_spot(bar, staff, my.spot).1);
Some(Question {
id: format!("q{bar}-{mate}+{staff}"),
bar: bar.to_string(),
bars,
staves,
kind: "cross-staff".into(),
ask: ask_of("cross-staff").into(),
why: reason(why).to_string(),
page,
spot,
choices,
draft,
})
}
fn part(&self, system: usize, group: &[(i64, String)], why: &str) -> Question {
let parts = parts_of(&self.r.fmn);
let staves: BTreeSet<&String> = group.iter().map(|(_, s)| s).collect();
let bars: Vec<i64> = {
let b: BTreeSet<i64> = group.iter().map(|g| g.0).collect();
b.into_iter().collect()
};
let named: Vec<String> = (reason(why).split_once("which of "))
.and_then(|(_, r)| r.split_once(" it shows"))
.map(|(ids, _)| ids.split(", ").map(str::to_string).collect())
.unwrap_or_else(|| parts.iter().map(|p| p.0.clone()).collect());
let part_of = |s: &str| s.split('.').next().unwrap_or(s).to_string();
let read: Vec<(i64, &String, &Seen, &Vec<Vec<Ev>>)> = (bars.iter())
.flat_map(|&b| staves.iter().map(move |s| (b, *s)))
.filter_map(|(b, s)| {
let seen = self.seen.get(&(b, s.clone()))?;
Some((b, s, seen, seen.read.as_ref().ok()?))
})
.collect();
let taken: Vec<String> = {
let t: BTreeSet<String> = read.iter().map(|r| part_of(r.1)).collect();
t.into_iter().collect()
};
let mut order: Vec<String> = taken
.iter()
.filter(|p| named.contains(p))
.cloned()
.collect();
order.extend(named.iter().filter(|p| !taken.contains(p)).cloned());
let fmn = &self.r.fmn;
let mut choices = Vec::new();
for p in order.iter().take(options::MOST) {
let mut rewrite = Vec::new();
for (b, s, seen, vs) in &read {
let target = format!("{p}{}", &s[part_of(s).len()..]);
if !staves.contains(&target) {
continue;
}
if let Some(lines) = options::lines_of(vs, &target, seen) {
rewrite.push(bar_text(fmn, *b, &target, &lines));
}
}
if rewrite.is_empty() {
continue;
}
let name = parts
.iter()
.find(|q| q.0 == *p)
.map_or(p.as_str(), |q| q.1.as_str());
choices.push(Choice {
label: format!("\"{name}\" ({p})"),
rewrite,
});
}
let staves: Vec<String> = staves.into_iter().cloned().collect();
let labels: Vec<String> = bars.iter().map(i64::to_string).collect();
if choices.len() < 2 {
choices.push(leave_as_rest(&staves, &labels));
}
let mut spot = Vec::new();
let mut page = None;
for (b, s, _, _) in &read {
if let Some(pl) = self.r.places.get(&(*b, (*s).clone())) {
page.get_or_insert(pl.page.saturating_sub(1));
spot.push([pl.x0, pl.y0, pl.x1, pl.y1]);
}
}
Question {
id: format!("part-{system}-{}", bars[0]),
bar: bars[0].to_string(),
bars: labels,
staves,
kind: "part".into(),
ask: ask_of("part").into(),
why: reason(why).to_string(),
page: page.unwrap_or(0),
spot,
choices,
draft: Vec::new(),
}
}
}
fn draft_of(s: &Seen, staff: &str) -> Option<Vec<String>> {
let mut seen: Vec<Ev> = (s.events.iter())
.filter(|e| e.rest != Rest::Blank)
.cloned()
.collect();
if seen.is_empty() {
return None;
}
seen.sort_by(|a, b| a.x.total_cmp(&b.x));
let near = s.sp * 0.8;
let down = |e: &Ev| e.rest == Rest::None && e.up == Some(false);
let up = |e: &Ev| e.rest == Rest::None && e.up != Some(false);
let two = seen.iter().any(down) && seen.iter().any(up);
let mut voices: Vec<Vec<Ev>> = vec![Vec::new(), Vec::new()];
for e in &seen {
let v = if e.rest == Rest::None {
usize::from(two && down(e))
} else if two {
let by_up = seen.iter().any(|o| up(o) && (o.x - e.x).abs() < near);
let by_down = seen.iter().any(|o| down(o) && (o.x - e.x).abs() < near);
usize::from(by_up && !by_down)
} else {
0
};
voices[v].push(e.clone());
}
voices.retain(|v| !v.is_empty());
options::lines_of(&voices, staff, s).or_else(|| {
for v in voices.iter_mut().flatten() {
v.tuplets.clear();
}
options::lines_of(&voices, staff, s)
})
}
fn latent_kind(events: &[Ev]) -> &'static str {
if events.iter().any(|e| e.dots_shared > 0 || e.dots_partial) {
"dot"
} else if events.iter().any(|e| !e.loose.is_empty()) {
"tuplet"
} else {
"other"
}
}
fn ink_of(events: &[Ev]) -> Option<&'static str> {
use crate::doubt::{INK_BEAM, INK_FLAG, INK_STEM_BARE, INK_STEM_LEFT};
(events.iter())
.flat_map(|e| e.doubts.iter().copied())
.find(|d| [INK_STEM_LEFT, INK_STEM_BARE, INK_BEAM, INK_FLAG].contains(d))
}
fn had_doubts(events: &[Ev]) -> bool {
events
.iter()
.any(|e| !e.doubts.is_empty() || e.dots_shared > 0 || e.dots_partial || !e.loose.is_empty())
}
pub fn read_pdf_review(pdf: &[u8]) -> Result<Review, Refusal> {
Ok(review_of(read_kept(pdf)?, page_sizes(pdf)))
}
fn read_kept(pdf: &[u8]) -> Result<Reading, Refusal> {
let pages = crate::page::read_pages(pdf).map_err(|why| Refusal { system: None, why })?;
ON.with(|c| c.set(true));
let read = crate::read::read(&pages, 1.0);
ON.with(|c| c.set(false));
read
}
fn review_of(mut reading: Reading, sizes: Vec<[f64; 2]>) -> Review {
let seen = std::mem::take(&mut reading.seen);
let b = Build {
r: &reading,
seen: &seen,
};
let mut questions = Vec::new();
let unread: BTreeSet<(i64, String)> = (reading.unread.iter())
.map(|u| (u.bar, u.staff.clone()))
.collect();
let mut asked: BTreeSet<(i64, String)> = BTreeSet::new();
let mut by_system: BTreeMap<(usize, String), Vec<(i64, String)>> = BTreeMap::new();
for u in reading.unread.iter().filter(|u| kind_of(&u.why) == "part") {
let system = reading
.bar_systems
.get(&u.bar)
.copied()
.unwrap_or(usize::MAX);
let why = reason(&u.why);
let why = why.split_once(": ").map_or(why, |w| w.1).to_string();
by_system
.entry((system, why))
.or_default()
.push((u.bar, u.staff.clone()));
}
for ((system, _), group) in &by_system {
let why = (reading.unread.iter())
.find(|u| (u.bar, u.staff.clone()) == group[0])
.map_or(String::new(), |u| u.why.clone());
questions.push(b.part(*system, group, &why));
asked.extend(group.iter().cloned());
}
let part = |s: &str| s.split('.').next().unwrap_or(s).to_string();
for u in &reading.unread {
if asked.contains(&(u.bar, u.staff.clone())) {
continue;
}
if kind_of(&u.why) == "cross-staff" {
let mate = (reading.unread.iter()).find(|m| {
m.bar == u.bar
&& m.staff != u.staff
&& part(&m.staff) == part(&u.staff)
&& kind_of(&m.why) != "cross-staff"
&& !asked.contains(&(m.bar, m.staff.clone()))
});
if let Some(m) = mate {
if let Some(q) = b.joint(u.bar, &u.staff, &m.staff, &u.why) {
asked.insert((u.bar, u.staff.clone()));
asked.insert((m.bar, m.staff.clone()));
questions.push(q);
continue;
}
}
}
if let Some(q) = b.one(u.bar, &u.staff, &u.why, Ask::Unread) {
asked.insert((u.bar, u.staff.clone()));
questions.push(q);
}
}
let mut latent = Vec::new();
for ((bar, staff), s) in &seen {
if unread.contains(&(*bar, staff.clone())) || s.read.is_err() || !had_doubts(&s.events) {
continue;
}
if let Some(why) = ink_of(&s.events) {
questions.extend(b.one(*bar, staff, why, Ask::Ink));
continue;
}
let why = "read, with other readings set aside";
latent.extend(b.one(*bar, staff, why, Ask::Latent));
}
let mut bars: BTreeMap<i64, BarPlace> = BTreeMap::new();
for ((bar, staff), p) in &reading.places {
let e = bars.entry(*bar).or_insert_with(|| BarPlace {
bar: bar.to_string(),
page: p.page.saturating_sub(1),
system: reading.bar_systems.get(bar).copied().unwrap_or(0),
frame: [p.x0, p.y0, p.x1, p.y1],
staves: Vec::new(),
});
e.frame = [
e.frame[0].min(p.x0),
e.frame[1].min(p.y0),
e.frame[2].max(p.x1),
e.frame[3].max(p.y1),
];
e.staves.push((staff.clone(), p.y0, p.y1));
}
let mut bars: Vec<BarPlace> = bars.into_values().collect();
for b in &mut bars {
b.staves.sort_by(|x, y| x.1.total_cmp(&y.1));
}
let marks = std::mem::take(&mut reading.marks);
Review {
reading,
questions,
latent,
bars,
marks,
pages: sizes,
}
}
fn page_sizes(pdf: &[u8]) -> Vec<[f64; 2]> {
let Ok(doc) = hayro_syntax::Pdf::new(pdf.to_vec()) else {
return Vec::new();
};
(doc.pages().iter())
.map(|p| {
let (w, h) = p.render_dimensions();
[w as f64, h as f64]
})
.collect()
}
fn js(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn num(x: f64) -> String {
match x.is_finite() {
true => format!("{}", (x * 100.0).round() / 100.0),
false => "null".into(),
}
}
fn list<T>(xs: &[T], f: impl Fn(&T) -> String) -> String {
format!("[{}]", xs.iter().map(f).collect::<Vec<_>>().join(","))
}
fn strs(xs: &[String]) -> String {
list(xs, |s| js(s))
}
fn nums(xs: &[f64]) -> String {
list(xs, |&x| num(x))
}
impl BarPlace {
pub fn to_json(&self) -> String {
format!(
"{{\"bar\":{},\"page\":{},\"system\":{},\"frame\":{},\"staves\":{}}}",
js(&self.bar),
self.page,
self.system,
nums(&self.frame),
list(&self.staves, |(s, a, b)| format!(
"[{},{},{}]",
js(s),
num(*a),
num(*b)
))
)
}
}
impl NoteMark {
pub fn to_json(&self) -> String {
format!(
"{{\"bar\":{},\"staff\":{},\"page\":{},\"at\":{},\"pitch\":{},\"length\":{}}}",
js(&self.bar),
js(&self.staff),
self.page,
nums(&self.at),
js(&self.pitch),
js(&self.length)
)
}
}
pub fn bar_text_json(b: &BarText) -> String {
format!(
"{{\"staff\":{},\"bar\":{},\"fmn\":{}}}",
js(&b.staff),
js(&b.bar),
js(&b.fmn)
)
}
impl Choice {
pub fn to_json(&self) -> String {
format!(
"{{\"label\":{},\"rewrite\":{}}}",
js(&self.label),
list(&self.rewrite, bar_text_json)
)
}
}
impl Question {
pub fn to_json(&self) -> String {
format!(
"{{\"id\":{},\"bar\":{},\"bars\":{},\"staves\":{},\"kind\":{},\"ask\":{},\"why\":{},\"page\":{},\"spot\":{},\"choices\":{},\"draft\":{}}}",
js(&self.id),
js(&self.bar),
strs(&self.bars),
strs(&self.staves),
js(&self.kind),
js(&self.ask),
js(&self.why),
self.page,
list(&self.spot, |s| nums(s)),
list(&self.choices, Choice::to_json),
list(&self.draft, bar_text_json)
)
}
}
pub fn reading_json(r: &Reading) -> String {
let unread = list(&r.unread, |u| {
let place = u.place.as_ref().map_or("null".to_string(), |p| {
format!(
"{{\"page\":{},\"x0\":{},\"x1\":{},\"y0\":{},\"y1\":{}}}",
p.page,
num(p.x0),
num(p.x1),
num(p.y0),
num(p.y1)
)
});
format!(
"{{\"bar\":{},\"staff\":{},\"why\":{},\"place\":{place}}}",
u.bar,
js(&u.staff),
js(&u.why)
)
});
format!(
"{{\"fmn\":{},\"musicxml\":{},\"systems\":{},\"bars\":{},\"notes\":{},\"syllables\":{},\"notices\":{},\"unread\":{unread}}}",
js(&r.fmn),
js(&r.musicxml),
r.systems,
r.bars,
r.notes,
r.syllables,
strs(&r.notices)
)
}
impl Review {
pub fn to_json(&self) -> String {
format!(
"{{\"reading\":{},\"questions\":{},\"latent\":{},\"bars\":{},\"marks\":{},\"pages\":{}}}",
reading_json(&self.reading),
list(&self.questions, Question::to_json),
list(&self.latent, Question::to_json),
list(&self.bars, BarPlace::to_json),
list(&self.marks, NoteMark::to_json),
list(&self.pages, |p| nums(p))
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::read::Unread;
const PDF: &[u8] = include_bytes!("../tests/fixtures/small.pdf");
#[test]
fn a_pdf_read_whole_asks_nothing_and_says_where_its_bars_and_notes_are() {
let r = read_pdf_review(PDF).unwrap();
assert!(r.questions.is_empty());
assert_eq!(r.reading.fmn, crate::read_pdf(PDF).unwrap().fmn);
assert_eq!(r.pages.len(), 1);
assert!(r.pages[0][0] > 500.0 && r.pages[0][1] > 700.0);
let bars: Vec<&str> = r.bars.iter().map(|b| b.bar.as_str()).collect();
assert_eq!(bars, ["1", "2", "3", "4", "5"]);
for b in &r.bars {
assert_eq!(b.staves.len(), 2);
assert!(b.frame[0] < b.frame[2] && b.frame[1] < b.frame[3]);
}
assert_eq!(r.marks.len(), 23);
let first = &r.marks[0];
assert_eq!((first.bar.as_str(), first.staff.as_str()), ("1", "P.1"));
assert_eq!((first.pitch.as_str(), first.length.as_str()), ("g4", "4"));
let b1 = &r.bars[0];
assert!(b1.frame[0] < first.at[0] && first.at[0] < b1.frame[2]);
assert!(r.marks.iter().any(|m| m.pitch == "e4" && m.bar == "4"));
let json = r.to_json();
assert!(json.starts_with("{\"reading\":{\"fmn\":"));
assert!(json.contains("\"marks\":[{\"bar\":\"1\""));
}
#[test]
fn an_unread_bar_is_asked_with_the_reading_the_reader_had_first() {
let mut reading = read_kept(PDF).unwrap();
let given = reading.fmn.clone();
reading.fmn = given.replace(
"bar 4
P.1: d5/2 c5/2
P.1/2: s/4 e4/4 s/2
",
"bar 4
P.1: R
",
);
assert_ne!(reading.fmn, given);
reading.unread.push(Unread {
bar: 4,
staff: "P.1".into(),
why: "bar 4, P.1: two voices that do not each fill the bar (a voice entering later, or an unseen rest)".into(),
place: None,
beside: Vec::new(),
});
let r = review_of(reading, Vec::new());
assert_eq!(r.questions.len(), 1);
let q = &r.questions[0];
assert_eq!(q.kind, "rest-or-longer");
assert_eq!(
(q.bar.as_str(), q.staves.as_slice()),
("4", &["P.1".to_string()][..])
);
assert!((2..=6).contains(&q.choices.len()));
assert!(
q.choices[0].label.starts_with("As read"),
"{:?}",
q.choices[0]
);
assert!(!q.spot.is_empty());
let back = fm_transcribe::replace_bars(&r.reading.fmn, &q.choices[0].rewrite).unwrap();
assert_eq!(back, given);
assert_eq!(q.draft.len(), 1);
let draft = &q.draft[0].fmn;
let (upper, lower) = draft.split_once('\n').expect(draft);
assert!(
upper.starts_with("P.1: ") && upper.contains("d5"),
"{draft}"
);
assert!(
lower.starts_with("P.1/2: ") && lower.contains("e4"),
"{draft}"
);
}
#[test]
fn a_systems_part_is_one_question_for_all_its_bars() {
let mut reading = read_kept(PDF).unwrap();
let why = |bar: i64, staff: &str| {
format!("bar {bar}, {staff}: its system leaves staves out, and nothing on the page says which of P, Q it shows")
};
for bar in [1, 2] {
for staff in ["P.1", "P.2", "Q.1", "Q.2"] {
reading.unread.push(Unread {
bar,
staff: staff.into(),
why: why(bar, staff),
place: None,
beside: Vec::new(),
});
}
}
let r = review_of(reading, Vec::new());
assert_eq!(r.questions.len(), 1);
let q = &r.questions[0];
assert_eq!(q.kind, "part");
assert_eq!(q.bars, ["1", "2"]);
let labels: Vec<&str> = q.choices.iter().map(|c| c.label.as_str()).collect();
assert_eq!(labels, ["\"Piano\" (P)", "\"Q\" (Q)"]);
let to: Vec<(&str, &str)> = (q.choices[1].rewrite.iter())
.map(|b| (b.bar.as_str(), b.staff.as_str()))
.collect();
assert_eq!(to, [("1", "Q.1"), ("1", "Q.2"), ("2", "Q.1"), ("2", "Q.2")]);
assert!(q.choices[1].rewrite[0].fmn.starts_with("Q.1: g4/4 a4/4"));
}
#[test]
fn plain_words_for_lengths_and_pitches() {
use crate::frac::Q;
assert_eq!(options::length_words(Q::new(3, 2)), "dotted quarter");
assert_eq!(options::length_words(Q::new(1, 3)), "eighth (in a tuplet)");
assert_eq!(options::pitch_words(31, 1), "F#4");
}
#[test]
fn a_flagged_bars_choices_are_only_those_that_compile() {
let latent_of = |break_it: bool| {
let mut reading = read_kept(PDF).unwrap();
let s = reading.seen.get_mut(&(4, "P.1".to_string())).unwrap();
s.events[0].doubts.push("a doubt settled");
if break_it {
reading.fmn = reading.fmn.replace(
"bar 5
",
"bar 5
P.2/2: c3/1 c3/1
",
);
}
review_of(reading, Vec::new()).latent
};
let latent = latent_of(false);
assert_eq!(latent.len(), 1, "{latent:?}");
let q = &latent[0];
assert_eq!((q.bar.as_str(), q.staves[0].as_str()), ("4", "P.1"));
assert!(!q.choices.is_empty() && q.choices.len() <= options::MOST);
let fmn = read_kept(PDF).unwrap().fmn;
for c in &q.choices {
let text = fm_transcribe::replace_bars(&fmn, &c.rewrite).unwrap();
assert!(fm_transcribe::compile(&text).is_ok(), "{c:?}");
assert_ne!(text, fmn);
}
assert!(latent_of(true).is_empty());
}
#[test]
fn a_read_bar_with_ink_unused_is_asked_by_its_ink() {
let mut e = Ev::new(Vec::new(), None, None);
assert_eq!(ink_of(std::slice::from_ref(&e)), None);
e.doubts.push(crate::doubt::DOT_UNCLAIMED);
e.doubts.push(crate::doubt::INK_FLAG);
assert_eq!(ink_of(&[e]), Some(crate::doubt::INK_FLAG));
}
#[cfg(feature = "serde")]
#[test]
fn the_reviews_types_go_both_ways_as_data() {
fn both<T: serde::Serialize + serde::de::DeserializeOwned>() {}
both::<Review>();
both::<Question>();
both::<Choice>();
both::<BarText>();
both::<BarPlace>();
both::<NoteMark>();
both::<Reading>();
both::<Refusal>();
}
}