Skip to main content

fm_vector/
review.rs

1//! A PDF read for a person to review: the reading, and a question for each doubt it left (a
2//! staff's bar it could not read), with the readings the reader can make of the bar to choose
3//! from, each as the bar's new `.fmn` lines. A system whose part the page does not tell is one
4//! question for all its bars. The read bars the reader had other readings of keep those
5//! (`latent`), for a person who flags the bar. Where every bar and note is on its pages comes
6//! with it, for the app to cut a bar from the page and draw the reading over it.
7//!
8//! Nothing here changes a reading: the review's `.fmn` is [`crate::read_pdf`]'s, but that it is
9//! never refused for its share of unread bars.
10
11use 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
25/// Whether a review is being read (what each staff's bar was seen as is then kept).
26pub(crate) fn on() -> bool {
27    ON.with(Cell::get)
28}
29
30/// A PDF's reading and the questions a person answers to settle what the reader could not.
31#[derive(Clone, Debug)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct Review {
34    /// As [`crate::read_pdf`]'s.
35    pub reading: Reading,
36    /// One a doubt to ask; a system's part question is one question.
37    pub questions: Vec<Question>,
38    /// The read bars the reader had other readings of: shown when a person flags the bar.
39    pub latent: Vec<Question>,
40    /// Where every bar of every system is on its page.
41    pub bars: Vec<BarPlace>,
42    /// Where every note read is, for an overlay.
43    pub marks: Vec<NoteMark>,
44    /// The pages' sizes, in points.
45    pub pages: Vec<[f64; 2]>,
46}
47
48/// A question on one or more bars.
49#[derive(Clone, Debug, PartialEq)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51pub struct Question {
52    /// Stable within this reading.
53    pub id: String,
54    /// The bar's label as in the `.fmn` (the first, where it settles several).
55    pub bar: String,
56    /// Every bar it settles.
57    pub bars: Vec<String>,
58    /// The staves it settles, as the `.fmn` names them.
59    pub staves: Vec<String>,
60    /// `dot`, `tuplet`, `rest-or-longer`, `cross-staff`, `chord-voices`, `part`, `ink` (a read
61    /// bar whose printed stems, beams or flags its reading leaves unused) or `other`.
62    pub kind: String,
63    /// The question in plain words.
64    pub ask: String,
65    /// The reader's own reason.
66    pub why: String,
67    /// The page, from 0.
68    pub page: usize,
69    /// What it is about: boxes `[x0, y0, x1, y1]` in page points from the page's top left.
70    pub spot: Vec<[f64; 4]>,
71    /// The likeliest first. Two to six; none where the reader has no reading that fits, and
72    /// then the person writes the bar, starting from [`Question::draft`].
73    pub choices: Vec<Choice>,
74    /// The notes the reader saw in the bar as it saw them, its lines a voice split by stem, for
75    /// a person to start writing the bar from. They need not add up, nor compile; empty where
76    /// the reader cannot write them.
77    #[cfg_attr(feature = "serde", serde(default))]
78    pub draft: Vec<BarText>,
79}
80
81/// One answer: the bars to replace if it is chosen.
82#[derive(Clone, Debug, PartialEq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct Choice {
85    /// Short plain words.
86    pub label: String,
87    pub rewrite: Vec<BarText>,
88}
89
90/// Where a bar is on its page.
91#[derive(Clone, Debug, PartialEq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93pub struct BarPlace {
94    pub bar: String,
95    /// From 0, as the systems.
96    pub page: usize,
97    pub system: usize,
98    /// `[x0, y0, x1, y1]`: from the bar's left edge to its right, the top staff's top line to
99    /// the bottom staff's bottom line.
100    pub frame: [f64; 4],
101    /// Each staff's top and bottom line: (staff, y0, y1).
102    pub staves: Vec<(String, f64, f64)>,
103}
104
105/// A note read, where its head stands.
106#[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    /// The head's middle, in page points from the top left.
113    pub at: [f64; 2],
114    /// As written in the `.fmn` (`cs5`).
115    pub pitch: String,
116    /// As written in the `.fmn` (`4.`), or `grace`.
117    pub length: String,
118}
119
120/// The notes of a staff's bar as read, where they stand (`read.rs`, during a review).
121pub(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    // (an accidental holds to the bar's end at its place)
133    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
159/// What a doubt is about, from the reader's reason.
160fn 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
196/// The reader's reason without its `bar N, staff: `.
197fn 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
204/// The ottava marks a staff's bar has in `fmn` (an option's lines leave its marks out).
205fn 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
227/// A staff's bar's lines as one [`BarText`], its ottava marks kept.
228fn 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
244/// Whether the reading with `rewrite` made compiles.
245fn 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
271/// The parts the score has: (id, name), from its `part` lines.
272fn 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/// What a staff's bar is asked as.
284#[derive(Clone, Copy, PartialEq, Eq, Debug)]
285enum Ask {
286    /// Unread: its readings, the reader's first among them.
287    Unread,
288    /// Read, with other readings set aside: shown when a person flags the bar.
289    Latent,
290    /// Read, but some of its printed ink (a stem, a beam, a flag) is in no note: asked.
291    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    /// A staff's bar's question from its options: for an unread bar, a read bar's other
317    /// readings (latent), or a read bar whose printed ink its reading leaves unused.
318    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            // (a read bar's slurs go on into the bars beside it: kept where they can be)
343            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            // (a reading the score would not compile with is no answer, asked or offered for a
349            // flagged bar; readings that would engrave alike are one already: `options::of`)
350            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        // (a rest beside one reading, so that it is a choice; with none, the bar is written)
368        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    /// A staff beamed with its part's other staff, both unread: one question, the other staff's
413    /// options each with this one's likeliest.
414    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    /// A system whose part the page does not tell: one question, a choice a part, each putting
462    /// what was read on that part's staves in every bar of it.
463    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        // the parts it may be: as the reason names them, or else any part of the score
471        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        // what was read, by bar and staff (named as the reader took the system)
477        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
548/// What the reader saw in a staff's bar as `.fmn` lines that need not add up: a voice for the
549/// notes with stems up (or none) and one for those with stems down, a rest to the voice that
550/// has no note where it stands. `None` where nothing was seen or it cannot be written.
551fn 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            // (a rest under or over the other voice's note is this one's)
570            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    // (a tuplet the split broke is written without its number, else the notes alone)
580    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
588/// What a read bar's other readings are about, from what the reader was unsure of in it.
589fn 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
599/// The first of a read staff's bar's doubts about ink its reading leaves unused.
600fn 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
607/// Whether a read staff's bar had something the reader settled one way of several.
608fn 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
614/// A PDF read for review: never refused for its share of unread bars (a PDF the reader cannot
615/// read at all still is: no staff lines, an unknown music font).
616pub fn read_pdf_review(pdf: &[u8]) -> Result<Review, Refusal> {
617    Ok(review_of(read_kept(pdf)?, page_sizes(pdf)))
618}
619
620/// The PDF read with what each staff's bar was seen as kept, never refused for its unread bars.
621fn 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
629/// The review of a reading made by [`read_kept`].
630fn 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    // a system's part: one question, by system and reason
642    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        // (the reason names the staff first)
651        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    // the read bars with other readings
692    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        // printed ink the reading leaves unused: asked, not only offered
698        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
737/// Each page's size in points.
738fn 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
750// ---- JSON (the browser's glue passes it on as it is) ----
751
752fn 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
822/// A [`BarText`] as JSON: `{"staff","bar","fmn"}`.
823pub 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
861/// A [`Reading`] as JSON: the `.fmn`, the MusicXML, the counts, the notices and the bars not
862/// read (bar, staff, why, and the place: page from 1, x0, x1, y0, y1).
863pub 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    /// The review as JSON, its fields as named here (`reading` as [`reading_json`]).
896    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        // every head read: the bars' notes and chords' heads
930        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        // (bar 4's lower voice, after its hidden rest)
937        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        // bar 4's upper staff as if left unread, its notes seen
948        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        // the first choice puts the bar back as it was read
981        let back = fm_transcribe::replace_bars(&r.reading.fmn, &q.choices[0].rewrite).unwrap();
982        assert_eq!(back, given);
983        // what was seen, a voice a stem direction, to write the bar from
984        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        // the second puts what was read on Q's staves, in both bars
1022        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            // bar 4's upper staff read with a doubt settled: its other readings are latent
1041            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                // (a score no rewrite of bar 4 compiles: a voice line bar 5 has no room for)
1045                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        // none compiles: the bar has no choice to offer, and is not offered
1067        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}