1use std::cell::Cell;
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt::Write as _;
14
15pub use fm_transcribe::BarText;
16
17use crate::options::{self, Seen};
18use crate::read::{Reading, Refusal};
19use crate::staff::{Ev, Rest};
20
21thread_local! {
22 static ON: Cell<bool> = const { Cell::new(false) };
23}
24
25pub(crate) fn on() -> bool {
27 ON.with(Cell::get)
28}
29
30#[derive(Clone, Debug)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct Review {
34 pub reading: Reading,
36 pub questions: Vec<Question>,
38 pub latent: Vec<Question>,
40 pub bars: Vec<BarPlace>,
42 pub marks: Vec<NoteMark>,
44 pub pages: Vec<[f64; 2]>,
46}
47
48#[derive(Clone, Debug, PartialEq)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51pub struct Question {
52 pub id: String,
54 pub bar: String,
56 pub bars: Vec<String>,
58 pub staves: Vec<String>,
60 pub kind: String,
63 pub ask: String,
65 pub why: String,
67 pub page: usize,
69 pub spot: Vec<[f64; 4]>,
71 pub choices: Vec<Choice>,
74 #[cfg_attr(feature = "serde", serde(default))]
78 pub draft: Vec<BarText>,
79}
80
81#[derive(Clone, Debug, PartialEq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct Choice {
85 pub label: String,
87 pub rewrite: Vec<BarText>,
88}
89
90#[derive(Clone, Debug, PartialEq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93pub struct BarPlace {
94 pub bar: String,
95 pub page: usize,
97 pub system: usize,
98 pub frame: [f64; 4],
101 pub staves: Vec<(String, f64, f64)>,
103}
104
105#[derive(Clone, Debug, Default, PartialEq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub struct NoteMark {
109 pub bar: String,
110 pub staff: String,
111 pub page: usize,
112 pub at: [f64; 2],
114 pub pitch: String,
116 pub length: String,
118}
119
120pub(crate) fn marks_of(
122 vs: &[Vec<Ev>],
123 bar: i64,
124 staff: &str,
125 page: usize,
126 fifths: i32,
127) -> Vec<NoteMark> {
128 let mut evs: Vec<&Ev> = (vs.iter().flatten())
129 .filter(|e| e.rest == Rest::None && !e.heads.is_empty())
130 .collect();
131 evs.sort_by(|a, b| a.x.total_cmp(&b.x));
132 let mut force: BTreeMap<i32, i32> = BTreeMap::new();
134 let mut out = Vec::new();
135 for e in evs {
136 for (&p, &(a, _)) in &e.accs {
137 force.insert(p, a);
138 }
139 let length = match e.grace {
140 Some(_) => "grace".to_string(),
141 None => crate::write::dur_token(e.dur).unwrap_or_default(),
142 };
143 for (h, &p) in e.heads.iter().zip(&e.place_of) {
144 let alt =
145 (force.get(&p).copied()).unwrap_or_else(|| crate::write::key_alter(fifths, p));
146 out.push(NoteMark {
147 bar: bar.to_string(),
148 staff: staff.to_string(),
149 page,
150 at: [(h.x0 + h.x1) / 2.0, h.y],
151 pitch: crate::write::pitch_name(p, alt),
152 length: length.clone(),
153 });
154 }
155 }
156 out
157}
158
159fn kind_of(why: &str) -> &'static str {
161 let table: [(&str, &str); 12] = [
162 ("leaves staves out", "part"),
163 ("beamed with the part's other staff", "cross-staff"),
164 ("tuplet's number", "tuplet"),
165 ("two voices' notes", "chord-voices"),
166 ("one head", "chord-voices"),
167 ("dot", "dot"),
168 ("two voices that do not each fill", "rest-or-longer"),
169 ("do not stand where", "rest-or-longer"),
170 ("do not add up to the time", "other"),
171 ("lasts ", "other"),
172 ("grace note", "other"),
173 ("small notes", "other"),
174 ];
175 (table.iter())
176 .find(|(k, _)| why.contains(k))
177 .map_or("other", |(_, v)| v)
178}
179
180fn ask_of(kind: &str) -> &'static str {
181 match kind {
182 "dot" => "Which note does the circled dot belong to?",
183 "tuplet" => "Which notes does the circled tuplet number group?",
184 "rest-or-longer" => {
185 "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?"
186 }
187 "cross-staff" => {
188 "These notes are beamed with the other staff's. Which reading of the two staves is right?"
189 }
190 "chord-voices" => "Which notes of the circled chords belong to which voice?",
191 "part" => "This system leaves staves out. Which part does it show?",
192 _ => "As read, this bar does not add up. Which reading of the circled notes is right?",
193 }
194}
195
196fn reason(why: &str) -> &str {
198 match why.strip_prefix("bar ") {
199 Some(r) => r.split_once(": ").map_or(why, |(_, w)| w),
200 None => why,
201 }
202}
203
204fn ottavas(fmn: &str, bar: &str, staff: &str) -> Vec<String> {
206 let mut lines = fmn.lines();
207 let head = |l: &str| {
208 l.strip_prefix("bar ")
209 .and_then(|r| r.strip_prefix(bar))
210 .is_some_and(|r| r.is_empty() || r.starts_with(' '))
211 };
212 if !lines.any(head) {
213 return Vec::new();
214 }
215 let own = |l: &str| {
216 l.strip_prefix(staff)
217 .is_some_and(|r| r.starts_with(':') || (r.starts_with('/') && r.contains(':')))
218 };
219 (lines.take_while(|l| !l.starts_with("bar ")))
220 .filter(|l| own(l))
221 .flat_map(|l| l.split_whitespace())
222 .filter(|t| ["\\8va", "\\8vb", "\\15ma", "\\15mb", "\\loco"].contains(t))
223 .map(str::to_string)
224 .collect()
225}
226
227fn bar_text(fmn: &str, bar: i64, staff: &str, lines: &[String]) -> BarText {
229 let bar = bar.to_string();
230 let marks = ottavas(fmn, &bar, staff);
231 let mut lines = lines.to_vec();
232 if let (false, Some(first)) = (marks.is_empty(), lines.first_mut()) {
233 if let Some((name, rest)) = first.split_once(':') {
234 *first = format!("{name}: {}{rest}", marks.join(" "));
235 }
236 }
237 BarText {
238 staff: staff.to_string(),
239 bar,
240 fmn: lines.join("\n"),
241 }
242}
243
244fn compiles(fmn: &str, rewrite: &[BarText]) -> bool {
246 fm_transcribe::replace_bars(fmn, rewrite)
247 .and_then(|t| fm_transcribe::compile(&t))
248 .is_ok()
249}
250
251fn leave_as_rest(staves: &[String], bars: &[String]) -> Choice {
252 let rewrite = (bars.iter())
253 .flat_map(|b| {
254 staves.iter().map(move |s| BarText {
255 staff: s.clone(),
256 bar: b.clone(),
257 fmn: format!("{s}: R"),
258 })
259 })
260 .collect();
261 Choice {
262 label: "Leave it as a rest".into(),
263 rewrite,
264 }
265}
266
267fn spot_of(s: (f64, f64, f64, f64)) -> [f64; 4] {
268 [s.0, s.1, s.2, s.3]
269}
270
271fn parts_of(fmn: &str) -> Vec<(String, String)> {
273 (fmn.lines())
274 .filter_map(|l| l.strip_prefix("part "))
275 .filter_map(|r| {
276 let (id, rest) = r.split_once(' ')?;
277 let name = rest.split('"').nth(1).unwrap_or(id);
278 Some((id.to_string(), name.to_string()))
279 })
280 .collect()
281}
282
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
285enum Ask {
286 Unread,
288 Latent,
290 Ink,
292}
293
294struct Build<'a> {
295 r: &'a Reading,
296 seen: &'a BTreeMap<(i64, String), Seen>,
297}
298
299impl Build<'_> {
300 fn page_and_spot(
301 &self,
302 bar: i64,
303 staff: &str,
304 spot: Option<(f64, f64, f64, f64)>,
305 ) -> (usize, Vec<[f64; 4]>) {
306 let place = self.r.places.get(&(bar, staff.to_string()));
307 let page = place.map_or(0, |p| p.page.saturating_sub(1));
308 let spot = match (spot, place) {
309 (Some(s), _) => vec![spot_of(s)],
310 (None, Some(p)) => vec![[p.x0, p.y0, p.x1, p.y1]],
311 (None, None) => Vec::new(),
312 };
313 (page, spot)
314 }
315
316 fn one(&self, bar: i64, staff: &str, why: &str, ask: Ask) -> Option<Question> {
319 let latent = ask != Ask::Unread;
320 let s = self.seen.get(&(bar, staff.to_string()));
321 let mut opts = match s {
322 Some(s) => {
323 let given = match latent {
324 true => (s.read.as_ref().ok()).and_then(|vs| options::lines_of(vs, staff, s)),
325 false => None,
326 };
327 options::of(s, staff, given.as_deref())
328 }
329 None => options::Options {
330 choices: Vec::new(),
331 spot: None,
332 readings: Vec::new(),
333 },
334 };
335 if ask == Ask::Latent {
336 opts.without("as read");
337 }
338 let labels = s.map_or_else(Vec::new, |s| options::labels(s, &opts));
339 let fmn = &self.r.fmn;
340 let mut choices: Vec<Choice> = Vec::new();
341 for (k, ((lines, from), label)) in opts.choices.iter().zip(labels).enumerate() {
342 let slurred = match (latent, s, opts.readings.get(k)) {
344 (true, Some(s), Some(vs)) => options::lines_slurred(vs, staff, s),
345 _ => None,
346 };
347 let ways = slurred.iter().chain(std::iter::once(lines));
348 let Some(rewrite) = ways
351 .map(|ls| vec![bar_text(fmn, bar, staff, ls)])
352 .find(|rw| compiles(fmn, rw))
353 else {
354 continue;
355 };
356 let label = match (*from, latent) {
357 ("as read", _) => format!("As read: {label}"),
358 _ => label,
359 };
360 choices.push(Choice { label, rewrite });
361 }
362 if ask == Ask::Latent && choices.is_empty() {
363 return None;
364 }
365 let staves = vec![staff.to_string()];
366 let bars = vec![bar.to_string()];
367 if !latent && choices.len() == 1 {
369 choices.push(leave_as_rest(&staves, &bars));
370 }
371 let draft = match (ask, s) {
372 (Ask::Unread | Ask::Ink, Some(s)) => draft_of(s, staff)
373 .map(|ls| vec![bar_text(fmn, bar, staff, &ls)])
374 .unwrap_or_default(),
375 _ => Vec::new(),
376 };
377 let kind = match ask {
378 Ask::Latent => s.map_or("other", |s| latent_kind(&s.events)),
379 Ask::Ink => "ink",
380 Ask::Unread => kind_of(why),
381 };
382 let (page, spot) = self.page_and_spot(bar, staff, opts.spot);
383 Some(Question {
384 id: format!(
385 "{}{bar}-{staff}",
386 match ask {
387 Ask::Unread => "q",
388 Ask::Latent => "latent-",
389 Ask::Ink => "ink-",
390 }
391 ),
392 bar: bar.to_string(),
393 bars,
394 staves,
395 kind: kind.into(),
396 ask: match ask {
397 Ask::Latent => "Which reading of this bar is right?",
398 Ask::Ink => {
399 "Something printed in this bar is not in its reading. Which reading is right?"
400 }
401 Ask::Unread => ask_of(kind),
402 }
403 .into(),
404 why: reason(why).to_string(),
405 page,
406 spot,
407 choices,
408 draft,
409 })
410 }
411
412 fn joint(&self, bar: i64, staff: &str, mate: &str, why: &str) -> Option<Question> {
415 let mine = self.seen.get(&(bar, staff.to_string()))?;
416 let theirs = self.seen.get(&(bar, mate.to_string()))?;
417 let my = options::of(mine, staff, None);
418 let first = my.choices.first()?;
419 let opts = options::of(theirs, mate, None);
420 let labels = options::labels(theirs, &opts);
421 let fmn = &self.r.fmn;
422 let mut choices = Vec::new();
423 for ((lines, _), label) in opts.choices.iter().zip(labels) {
424 let rewrite = vec![
425 bar_text(fmn, bar, mate, lines),
426 bar_text(fmn, bar, staff, &first.0),
427 ];
428 if compiles(fmn, &rewrite) {
429 choices.push(Choice { label, rewrite });
430 }
431 }
432 if choices.is_empty() {
433 return None;
434 }
435 let staves = vec![mate.to_string(), staff.to_string()];
436 let bars = vec![bar.to_string()];
437 if choices.len() < 2 {
438 choices.push(leave_as_rest(&staves, &bars));
439 }
440 let draft = [(mate, theirs), (staff, mine)]
441 .iter()
442 .filter_map(|(st, s)| draft_of(s, st).map(|ls| bar_text(fmn, bar, st, &ls)))
443 .collect();
444 let (page, mut spot) = self.page_and_spot(bar, mate, opts.spot);
445 spot.extend(self.page_and_spot(bar, staff, my.spot).1);
446 Some(Question {
447 id: format!("q{bar}-{mate}+{staff}"),
448 bar: bar.to_string(),
449 bars,
450 staves,
451 kind: "cross-staff".into(),
452 ask: ask_of("cross-staff").into(),
453 why: reason(why).to_string(),
454 page,
455 spot,
456 choices,
457 draft,
458 })
459 }
460
461 fn part(&self, system: usize, group: &[(i64, String)], why: &str) -> Question {
464 let parts = parts_of(&self.r.fmn);
465 let staves: BTreeSet<&String> = group.iter().map(|(_, s)| s).collect();
466 let bars: Vec<i64> = {
467 let b: BTreeSet<i64> = group.iter().map(|g| g.0).collect();
468 b.into_iter().collect()
469 };
470 let named: Vec<String> = (reason(why).split_once("which of "))
472 .and_then(|(_, r)| r.split_once(" it shows"))
473 .map(|(ids, _)| ids.split(", ").map(str::to_string).collect())
474 .unwrap_or_else(|| parts.iter().map(|p| p.0.clone()).collect());
475 let part_of = |s: &str| s.split('.').next().unwrap_or(s).to_string();
476 let read: Vec<(i64, &String, &Seen, &Vec<Vec<Ev>>)> = (bars.iter())
478 .flat_map(|&b| staves.iter().map(move |s| (b, *s)))
479 .filter_map(|(b, s)| {
480 let seen = self.seen.get(&(b, s.clone()))?;
481 Some((b, s, seen, seen.read.as_ref().ok()?))
482 })
483 .collect();
484 let taken: Vec<String> = {
485 let t: BTreeSet<String> = read.iter().map(|r| part_of(r.1)).collect();
486 t.into_iter().collect()
487 };
488 let mut order: Vec<String> = taken
489 .iter()
490 .filter(|p| named.contains(p))
491 .cloned()
492 .collect();
493 order.extend(named.iter().filter(|p| !taken.contains(p)).cloned());
494 let fmn = &self.r.fmn;
495 let mut choices = Vec::new();
496 for p in order.iter().take(options::MOST) {
497 let mut rewrite = Vec::new();
498 for (b, s, seen, vs) in &read {
499 let target = format!("{p}{}", &s[part_of(s).len()..]);
500 if !staves.contains(&target) {
501 continue;
502 }
503 if let Some(lines) = options::lines_of(vs, &target, seen) {
504 rewrite.push(bar_text(fmn, *b, &target, &lines));
505 }
506 }
507 if rewrite.is_empty() {
508 continue;
509 }
510 let name = parts
511 .iter()
512 .find(|q| q.0 == *p)
513 .map_or(p.as_str(), |q| q.1.as_str());
514 choices.push(Choice {
515 label: format!("\"{name}\" ({p})"),
516 rewrite,
517 });
518 }
519 let staves: Vec<String> = staves.into_iter().cloned().collect();
520 let labels: Vec<String> = bars.iter().map(i64::to_string).collect();
521 if choices.len() < 2 {
522 choices.push(leave_as_rest(&staves, &labels));
523 }
524 let mut spot = Vec::new();
525 let mut page = None;
526 for (b, s, _, _) in &read {
527 if let Some(pl) = self.r.places.get(&(*b, (*s).clone())) {
528 page.get_or_insert(pl.page.saturating_sub(1));
529 spot.push([pl.x0, pl.y0, pl.x1, pl.y1]);
530 }
531 }
532 Question {
533 id: format!("part-{system}-{}", bars[0]),
534 bar: bars[0].to_string(),
535 bars: labels,
536 staves,
537 kind: "part".into(),
538 ask: ask_of("part").into(),
539 why: reason(why).to_string(),
540 page: page.unwrap_or(0),
541 spot,
542 choices,
543 draft: Vec::new(),
544 }
545 }
546}
547
548fn draft_of(s: &Seen, staff: &str) -> Option<Vec<String>> {
552 let mut seen: Vec<Ev> = (s.events.iter())
553 .filter(|e| e.rest != Rest::Blank)
554 .cloned()
555 .collect();
556 if seen.is_empty() {
557 return None;
558 }
559 seen.sort_by(|a, b| a.x.total_cmp(&b.x));
560 let near = s.sp * 0.8;
561 let down = |e: &Ev| e.rest == Rest::None && e.up == Some(false);
562 let up = |e: &Ev| e.rest == Rest::None && e.up != Some(false);
563 let two = seen.iter().any(down) && seen.iter().any(up);
564 let mut voices: Vec<Vec<Ev>> = vec![Vec::new(), Vec::new()];
565 for e in &seen {
566 let v = if e.rest == Rest::None {
567 usize::from(two && down(e))
568 } else if two {
569 let by_up = seen.iter().any(|o| up(o) && (o.x - e.x).abs() < near);
571 let by_down = seen.iter().any(|o| down(o) && (o.x - e.x).abs() < near);
572 usize::from(by_up && !by_down)
573 } else {
574 0
575 };
576 voices[v].push(e.clone());
577 }
578 voices.retain(|v| !v.is_empty());
579 options::lines_of(&voices, staff, s).or_else(|| {
581 for v in voices.iter_mut().flatten() {
582 v.tuplets.clear();
583 }
584 options::lines_of(&voices, staff, s)
585 })
586}
587
588fn latent_kind(events: &[Ev]) -> &'static str {
590 if events.iter().any(|e| e.dots_shared > 0 || e.dots_partial) {
591 "dot"
592 } else if events.iter().any(|e| !e.loose.is_empty()) {
593 "tuplet"
594 } else {
595 "other"
596 }
597}
598
599fn ink_of(events: &[Ev]) -> Option<&'static str> {
601 use crate::doubt::{INK_BEAM, INK_FLAG, INK_STEM_BARE, INK_STEM_LEFT};
602 (events.iter())
603 .flat_map(|e| e.doubts.iter().copied())
604 .find(|d| [INK_STEM_LEFT, INK_STEM_BARE, INK_BEAM, INK_FLAG].contains(d))
605}
606
607fn had_doubts(events: &[Ev]) -> bool {
609 events
610 .iter()
611 .any(|e| !e.doubts.is_empty() || e.dots_shared > 0 || e.dots_partial || !e.loose.is_empty())
612}
613
614pub fn read_pdf_review(pdf: &[u8]) -> Result<Review, Refusal> {
617 Ok(review_of(read_kept(pdf)?, page_sizes(pdf)))
618}
619
620fn read_kept(pdf: &[u8]) -> Result<Reading, Refusal> {
622 let pages = crate::page::read_pages(pdf).map_err(|why| Refusal { system: None, why })?;
623 ON.with(|c| c.set(true));
624 let read = crate::read::read(&pages, 1.0);
625 ON.with(|c| c.set(false));
626 read
627}
628
629fn review_of(mut reading: Reading, sizes: Vec<[f64; 2]>) -> Review {
631 let seen = std::mem::take(&mut reading.seen);
632 let b = Build {
633 r: &reading,
634 seen: &seen,
635 };
636 let mut questions = Vec::new();
637 let unread: BTreeSet<(i64, String)> = (reading.unread.iter())
638 .map(|u| (u.bar, u.staff.clone()))
639 .collect();
640 let mut asked: BTreeSet<(i64, String)> = BTreeSet::new();
641 let mut by_system: BTreeMap<(usize, String), Vec<(i64, String)>> = BTreeMap::new();
643 for u in reading.unread.iter().filter(|u| kind_of(&u.why) == "part") {
644 let system = reading
645 .bar_systems
646 .get(&u.bar)
647 .copied()
648 .unwrap_or(usize::MAX);
649 let why = reason(&u.why);
650 let why = why.split_once(": ").map_or(why, |w| w.1).to_string();
652 by_system
653 .entry((system, why))
654 .or_default()
655 .push((u.bar, u.staff.clone()));
656 }
657 for ((system, _), group) in &by_system {
658 let why = (reading.unread.iter())
659 .find(|u| (u.bar, u.staff.clone()) == group[0])
660 .map_or(String::new(), |u| u.why.clone());
661 questions.push(b.part(*system, group, &why));
662 asked.extend(group.iter().cloned());
663 }
664 let part = |s: &str| s.split('.').next().unwrap_or(s).to_string();
665 for u in &reading.unread {
666 if asked.contains(&(u.bar, u.staff.clone())) {
667 continue;
668 }
669 if kind_of(&u.why) == "cross-staff" {
670 let mate = (reading.unread.iter()).find(|m| {
671 m.bar == u.bar
672 && m.staff != u.staff
673 && part(&m.staff) == part(&u.staff)
674 && kind_of(&m.why) != "cross-staff"
675 && !asked.contains(&(m.bar, m.staff.clone()))
676 });
677 if let Some(m) = mate {
678 if let Some(q) = b.joint(u.bar, &u.staff, &m.staff, &u.why) {
679 asked.insert((u.bar, u.staff.clone()));
680 asked.insert((m.bar, m.staff.clone()));
681 questions.push(q);
682 continue;
683 }
684 }
685 }
686 if let Some(q) = b.one(u.bar, &u.staff, &u.why, Ask::Unread) {
687 asked.insert((u.bar, u.staff.clone()));
688 questions.push(q);
689 }
690 }
691 let mut latent = Vec::new();
693 for ((bar, staff), s) in &seen {
694 if unread.contains(&(*bar, staff.clone())) || s.read.is_err() || !had_doubts(&s.events) {
695 continue;
696 }
697 if let Some(why) = ink_of(&s.events) {
699 questions.extend(b.one(*bar, staff, why, Ask::Ink));
700 continue;
701 }
702 let why = "read, with other readings set aside";
703 latent.extend(b.one(*bar, staff, why, Ask::Latent));
704 }
705 let mut bars: BTreeMap<i64, BarPlace> = BTreeMap::new();
706 for ((bar, staff), p) in &reading.places {
707 let e = bars.entry(*bar).or_insert_with(|| BarPlace {
708 bar: bar.to_string(),
709 page: p.page.saturating_sub(1),
710 system: reading.bar_systems.get(bar).copied().unwrap_or(0),
711 frame: [p.x0, p.y0, p.x1, p.y1],
712 staves: Vec::new(),
713 });
714 e.frame = [
715 e.frame[0].min(p.x0),
716 e.frame[1].min(p.y0),
717 e.frame[2].max(p.x1),
718 e.frame[3].max(p.y1),
719 ];
720 e.staves.push((staff.clone(), p.y0, p.y1));
721 }
722 let mut bars: Vec<BarPlace> = bars.into_values().collect();
723 for b in &mut bars {
724 b.staves.sort_by(|x, y| x.1.total_cmp(&y.1));
725 }
726 let marks = std::mem::take(&mut reading.marks);
727 Review {
728 reading,
729 questions,
730 latent,
731 bars,
732 marks,
733 pages: sizes,
734 }
735}
736
737fn page_sizes(pdf: &[u8]) -> Vec<[f64; 2]> {
739 let Ok(doc) = hayro_syntax::Pdf::new(pdf.to_vec()) else {
740 return Vec::new();
741 };
742 (doc.pages().iter())
743 .map(|p| {
744 let (w, h) = p.render_dimensions();
745 [w as f64, h as f64]
746 })
747 .collect()
748}
749
750fn js(s: &str) -> String {
753 let mut out = String::from("\"");
754 for c in s.chars() {
755 match c {
756 '"' => out.push_str("\\\""),
757 '\\' => out.push_str("\\\\"),
758 '\n' => out.push_str("\\n"),
759 '\r' => out.push_str("\\r"),
760 '\t' => out.push_str("\\t"),
761 c if (c as u32) < 0x20 => {
762 let _ = write!(out, "\\u{:04x}", c as u32);
763 }
764 c => out.push(c),
765 }
766 }
767 out.push('"');
768 out
769}
770
771fn num(x: f64) -> String {
772 match x.is_finite() {
773 true => format!("{}", (x * 100.0).round() / 100.0),
774 false => "null".into(),
775 }
776}
777
778fn list<T>(xs: &[T], f: impl Fn(&T) -> String) -> String {
779 format!("[{}]", xs.iter().map(f).collect::<Vec<_>>().join(","))
780}
781
782fn strs(xs: &[String]) -> String {
783 list(xs, |s| js(s))
784}
785
786fn nums(xs: &[f64]) -> String {
787 list(xs, |&x| num(x))
788}
789
790impl BarPlace {
791 pub fn to_json(&self) -> String {
792 format!(
793 "{{\"bar\":{},\"page\":{},\"system\":{},\"frame\":{},\"staves\":{}}}",
794 js(&self.bar),
795 self.page,
796 self.system,
797 nums(&self.frame),
798 list(&self.staves, |(s, a, b)| format!(
799 "[{},{},{}]",
800 js(s),
801 num(*a),
802 num(*b)
803 ))
804 )
805 }
806}
807
808impl NoteMark {
809 pub fn to_json(&self) -> String {
810 format!(
811 "{{\"bar\":{},\"staff\":{},\"page\":{},\"at\":{},\"pitch\":{},\"length\":{}}}",
812 js(&self.bar),
813 js(&self.staff),
814 self.page,
815 nums(&self.at),
816 js(&self.pitch),
817 js(&self.length)
818 )
819 }
820}
821
822pub fn bar_text_json(b: &BarText) -> String {
824 format!(
825 "{{\"staff\":{},\"bar\":{},\"fmn\":{}}}",
826 js(&b.staff),
827 js(&b.bar),
828 js(&b.fmn)
829 )
830}
831
832impl Choice {
833 pub fn to_json(&self) -> String {
834 format!(
835 "{{\"label\":{},\"rewrite\":{}}}",
836 js(&self.label),
837 list(&self.rewrite, bar_text_json)
838 )
839 }
840}
841
842impl Question {
843 pub fn to_json(&self) -> String {
844 format!(
845 "{{\"id\":{},\"bar\":{},\"bars\":{},\"staves\":{},\"kind\":{},\"ask\":{},\"why\":{},\"page\":{},\"spot\":{},\"choices\":{},\"draft\":{}}}",
846 js(&self.id),
847 js(&self.bar),
848 strs(&self.bars),
849 strs(&self.staves),
850 js(&self.kind),
851 js(&self.ask),
852 js(&self.why),
853 self.page,
854 list(&self.spot, |s| nums(s)),
855 list(&self.choices, Choice::to_json),
856 list(&self.draft, bar_text_json)
857 )
858 }
859}
860
861pub fn reading_json(r: &Reading) -> String {
864 let unread = list(&r.unread, |u| {
865 let place = u.place.as_ref().map_or("null".to_string(), |p| {
866 format!(
867 "{{\"page\":{},\"x0\":{},\"x1\":{},\"y0\":{},\"y1\":{}}}",
868 p.page,
869 num(p.x0),
870 num(p.x1),
871 num(p.y0),
872 num(p.y1)
873 )
874 });
875 format!(
876 "{{\"bar\":{},\"staff\":{},\"why\":{},\"place\":{place}}}",
877 u.bar,
878 js(&u.staff),
879 js(&u.why)
880 )
881 });
882 format!(
883 "{{\"fmn\":{},\"musicxml\":{},\"systems\":{},\"bars\":{},\"notes\":{},\"syllables\":{},\"notices\":{},\"unread\":{unread}}}",
884 js(&r.fmn),
885 js(&r.musicxml),
886 r.systems,
887 r.bars,
888 r.notes,
889 r.syllables,
890 strs(&r.notices)
891 )
892}
893
894impl Review {
895 pub fn to_json(&self) -> String {
897 format!(
898 "{{\"reading\":{},\"questions\":{},\"latent\":{},\"bars\":{},\"marks\":{},\"pages\":{}}}",
899 reading_json(&self.reading),
900 list(&self.questions, Question::to_json),
901 list(&self.latent, Question::to_json),
902 list(&self.bars, BarPlace::to_json),
903 list(&self.marks, NoteMark::to_json),
904 list(&self.pages, |p| nums(p))
905 )
906 }
907}
908
909#[cfg(test)]
910mod tests {
911 use super::*;
912 use crate::read::Unread;
913
914 const PDF: &[u8] = include_bytes!("../tests/fixtures/small.pdf");
915
916 #[test]
917 fn a_pdf_read_whole_asks_nothing_and_says_where_its_bars_and_notes_are() {
918 let r = read_pdf_review(PDF).unwrap();
919 assert!(r.questions.is_empty());
920 assert_eq!(r.reading.fmn, crate::read_pdf(PDF).unwrap().fmn);
921 assert_eq!(r.pages.len(), 1);
922 assert!(r.pages[0][0] > 500.0 && r.pages[0][1] > 700.0);
923 let bars: Vec<&str> = r.bars.iter().map(|b| b.bar.as_str()).collect();
924 assert_eq!(bars, ["1", "2", "3", "4", "5"]);
925 for b in &r.bars {
926 assert_eq!(b.staves.len(), 2);
927 assert!(b.frame[0] < b.frame[2] && b.frame[1] < b.frame[3]);
928 }
929 assert_eq!(r.marks.len(), 23);
931 let first = &r.marks[0];
932 assert_eq!((first.bar.as_str(), first.staff.as_str()), ("1", "P.1"));
933 assert_eq!((first.pitch.as_str(), first.length.as_str()), ("g4", "4"));
934 let b1 = &r.bars[0];
935 assert!(b1.frame[0] < first.at[0] && first.at[0] < b1.frame[2]);
936 assert!(r.marks.iter().any(|m| m.pitch == "e4" && m.bar == "4"));
938 let json = r.to_json();
939 assert!(json.starts_with("{\"reading\":{\"fmn\":"));
940 assert!(json.contains("\"marks\":[{\"bar\":\"1\""));
941 }
942
943 #[test]
944 fn an_unread_bar_is_asked_with_the_reading_the_reader_had_first() {
945 let mut reading = read_kept(PDF).unwrap();
946 let given = reading.fmn.clone();
947 reading.fmn = given.replace(
949 "bar 4
950P.1: d5/2 c5/2
951P.1/2: s/4 e4/4 s/2
952",
953 "bar 4
954P.1: R
955",
956 );
957 assert_ne!(reading.fmn, given);
958 reading.unread.push(Unread {
959 bar: 4,
960 staff: "P.1".into(),
961 why: "bar 4, P.1: two voices that do not each fill the bar (a voice entering later, or an unseen rest)".into(),
962 place: None,
963 beside: Vec::new(),
964 });
965 let r = review_of(reading, Vec::new());
966 assert_eq!(r.questions.len(), 1);
967 let q = &r.questions[0];
968 assert_eq!(q.kind, "rest-or-longer");
969 assert_eq!(
970 (q.bar.as_str(), q.staves.as_slice()),
971 ("4", &["P.1".to_string()][..])
972 );
973 assert!((2..=6).contains(&q.choices.len()));
974 assert!(
975 q.choices[0].label.starts_with("As read"),
976 "{:?}",
977 q.choices[0]
978 );
979 assert!(!q.spot.is_empty());
980 let back = fm_transcribe::replace_bars(&r.reading.fmn, &q.choices[0].rewrite).unwrap();
982 assert_eq!(back, given);
983 assert_eq!(q.draft.len(), 1);
985 let draft = &q.draft[0].fmn;
986 let (upper, lower) = draft.split_once('\n').expect(draft);
987 assert!(
988 upper.starts_with("P.1: ") && upper.contains("d5"),
989 "{draft}"
990 );
991 assert!(
992 lower.starts_with("P.1/2: ") && lower.contains("e4"),
993 "{draft}"
994 );
995 }
996
997 #[test]
998 fn a_systems_part_is_one_question_for_all_its_bars() {
999 let mut reading = read_kept(PDF).unwrap();
1000 let why = |bar: i64, staff: &str| {
1001 format!("bar {bar}, {staff}: its system leaves staves out, and nothing on the page says which of P, Q it shows")
1002 };
1003 for bar in [1, 2] {
1004 for staff in ["P.1", "P.2", "Q.1", "Q.2"] {
1005 reading.unread.push(Unread {
1006 bar,
1007 staff: staff.into(),
1008 why: why(bar, staff),
1009 place: None,
1010 beside: Vec::new(),
1011 });
1012 }
1013 }
1014 let r = review_of(reading, Vec::new());
1015 assert_eq!(r.questions.len(), 1);
1016 let q = &r.questions[0];
1017 assert_eq!(q.kind, "part");
1018 assert_eq!(q.bars, ["1", "2"]);
1019 let labels: Vec<&str> = q.choices.iter().map(|c| c.label.as_str()).collect();
1020 assert_eq!(labels, ["\"Piano\" (P)", "\"Q\" (Q)"]);
1021 let to: Vec<(&str, &str)> = (q.choices[1].rewrite.iter())
1023 .map(|b| (b.bar.as_str(), b.staff.as_str()))
1024 .collect();
1025 assert_eq!(to, [("1", "Q.1"), ("1", "Q.2"), ("2", "Q.1"), ("2", "Q.2")]);
1026 assert!(q.choices[1].rewrite[0].fmn.starts_with("Q.1: g4/4 a4/4"));
1027 }
1028
1029 #[test]
1030 fn plain_words_for_lengths_and_pitches() {
1031 use crate::frac::Q;
1032 assert_eq!(options::length_words(Q::new(3, 2)), "dotted quarter");
1033 assert_eq!(options::length_words(Q::new(1, 3)), "eighth (in a tuplet)");
1034 assert_eq!(options::pitch_words(31, 1), "F#4");
1035 }
1036 #[test]
1037 fn a_flagged_bars_choices_are_only_those_that_compile() {
1038 let latent_of = |break_it: bool| {
1039 let mut reading = read_kept(PDF).unwrap();
1040 let s = reading.seen.get_mut(&(4, "P.1".to_string())).unwrap();
1042 s.events[0].doubts.push("a doubt settled");
1043 if break_it {
1044 reading.fmn = reading.fmn.replace(
1046 "bar 5
1047",
1048 "bar 5
1049P.2/2: c3/1 c3/1
1050",
1051 );
1052 }
1053 review_of(reading, Vec::new()).latent
1054 };
1055 let latent = latent_of(false);
1056 assert_eq!(latent.len(), 1, "{latent:?}");
1057 let q = &latent[0];
1058 assert_eq!((q.bar.as_str(), q.staves[0].as_str()), ("4", "P.1"));
1059 assert!(!q.choices.is_empty() && q.choices.len() <= options::MOST);
1060 let fmn = read_kept(PDF).unwrap().fmn;
1061 for c in &q.choices {
1062 let text = fm_transcribe::replace_bars(&fmn, &c.rewrite).unwrap();
1063 assert!(fm_transcribe::compile(&text).is_ok(), "{c:?}");
1064 assert_ne!(text, fmn);
1065 }
1066 assert!(latent_of(true).is_empty());
1068 }
1069
1070 #[test]
1071 fn a_read_bar_with_ink_unused_is_asked_by_its_ink() {
1072 let mut e = Ev::new(Vec::new(), None, None);
1073 assert_eq!(ink_of(std::slice::from_ref(&e)), None);
1074 e.doubts.push(crate::doubt::DOT_UNCLAIMED);
1075 e.doubts.push(crate::doubt::INK_FLAG);
1076 assert_eq!(ink_of(&[e]), Some(crate::doubt::INK_FLAG));
1077 }
1078
1079 #[cfg(feature = "serde")]
1080 #[test]
1081 fn the_reviews_types_go_both_ways_as_data() {
1082 fn both<T: serde::Serialize + serde::de::DeserializeOwned>() {}
1083 both::<Review>();
1084 both::<Question>();
1085 both::<Choice>();
1086 both::<BarText>();
1087 both::<BarPlace>();
1088 both::<NoteMark>();
1089 both::<Reading>();
1090 both::<Refusal>();
1091 }
1092}