fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
//! A PDF read for a person to review: the reading, and a question for each doubt it left (a
//! staff's bar it could not read), with the readings the reader can make of the bar to choose
//! from, each as the bar's new `.fmn` lines. A system whose part the page does not tell is one
//! question for all its bars. The read bars the reader had other readings of keep those
//! (`latent`), for a person who flags the bar. Where every bar and note is on its pages comes
//! with it, for the app to cut a bar from the page and draw the reading over it.
//!
//! Nothing here changes a reading: the review's `.fmn` is [`crate::read_pdf`]'s, but that it is
//! never refused for its share of unread bars.

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) };
}

/// Whether a review is being read (what each staff's bar was seen as is then kept).
pub(crate) fn on() -> bool {
    ON.with(Cell::get)
}

/// A PDF's reading and the questions a person answers to settle what the reader could not.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Review {
    /// As [`crate::read_pdf`]'s.
    pub reading: Reading,
    /// One a doubt to ask; a system's part question is one question.
    pub questions: Vec<Question>,
    /// The read bars the reader had other readings of: shown when a person flags the bar.
    pub latent: Vec<Question>,
    /// Where every bar of every system is on its page.
    pub bars: Vec<BarPlace>,
    /// Where every note read is, for an overlay.
    pub marks: Vec<NoteMark>,
    /// The pages' sizes, in points.
    pub pages: Vec<[f64; 2]>,
}

/// A question on one or more bars.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Question {
    /// Stable within this reading.
    pub id: String,
    /// The bar's label as in the `.fmn` (the first, where it settles several).
    pub bar: String,
    /// Every bar it settles.
    pub bars: Vec<String>,
    /// The staves it settles, as the `.fmn` names them.
    pub staves: Vec<String>,
    /// `dot`, `tuplet`, `rest-or-longer`, `cross-staff`, `chord-voices`, `part`, `ink` (a read
    /// bar whose printed stems, beams or flags its reading leaves unused) or `other`.
    pub kind: String,
    /// The question in plain words.
    pub ask: String,
    /// The reader's own reason.
    pub why: String,
    /// The page, from 0.
    pub page: usize,
    /// What it is about: boxes `[x0, y0, x1, y1]` in page points from the page's top left.
    pub spot: Vec<[f64; 4]>,
    /// The likeliest first. Two to six; none where the reader has no reading that fits, and
    /// then the person writes the bar, starting from [`Question::draft`].
    pub choices: Vec<Choice>,
    /// The notes the reader saw in the bar as it saw them, its lines a voice split by stem, for
    /// a person to start writing the bar from. They need not add up, nor compile; empty where
    /// the reader cannot write them.
    #[cfg_attr(feature = "serde", serde(default))]
    pub draft: Vec<BarText>,
}

/// One answer: the bars to replace if it is chosen.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Choice {
    /// Short plain words.
    pub label: String,
    pub rewrite: Vec<BarText>,
}

/// Where a bar is on its page.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BarPlace {
    pub bar: String,
    /// From 0, as the systems.
    pub page: usize,
    pub system: usize,
    /// `[x0, y0, x1, y1]`: from the bar's left edge to its right, the top staff's top line to
    /// the bottom staff's bottom line.
    pub frame: [f64; 4],
    /// Each staff's top and bottom line: (staff, y0, y1).
    pub staves: Vec<(String, f64, f64)>,
}

/// A note read, where its head stands.
#[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,
    /// The head's middle, in page points from the top left.
    pub at: [f64; 2],
    /// As written in the `.fmn` (`cs5`).
    pub pitch: String,
    /// As written in the `.fmn` (`4.`), or `grace`.
    pub length: String,
}

/// The notes of a staff's bar as read, where they stand (`read.rs`, during a review).
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));
    // (an accidental holds to the bar's end at its place)
    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
}

/// What a doubt is about, from the reader's reason.
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?",
    }
}

/// The reader's reason without its `bar N, staff: `.
fn reason(why: &str) -> &str {
    match why.strip_prefix("bar ") {
        Some(r) => r.split_once(": ").map_or(why, |(_, w)| w),
        None => why,
    }
}

/// The ottava marks a staff's bar has in `fmn` (an option's lines leave its marks out).
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()
}

/// A staff's bar's lines as one [`BarText`], its ottava marks kept.
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"),
    }
}

/// Whether the reading with `rewrite` made compiles.
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]
}

/// The parts the score has: (id, name), from its `part` lines.
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()
}

/// What a staff's bar is asked as.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Ask {
    /// Unread: its readings, the reader's first among them.
    Unread,
    /// Read, with other readings set aside: shown when a person flags the bar.
    Latent,
    /// Read, but some of its printed ink (a stem, a beam, a flag) is in no note: asked.
    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)
    }

    /// A staff's bar's question from its options: for an unread bar, a read bar's other
    /// readings (latent), or a read bar whose printed ink its reading leaves unused.
    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() {
            // (a read bar's slurs go on into the bars beside it: kept where they can be)
            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));
            // (a reading the score would not compile with is no answer, asked or offered for a
            // flagged bar; readings that would engrave alike are one already: `options::of`)
            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()];
        // (a rest beside one reading, so that it is a choice; with none, the bar is written)
        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,
        })
    }

    /// A staff beamed with its part's other staff, both unread: one question, the other staff's
    /// options each with this one's likeliest.
    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,
        })
    }

    /// A system whose part the page does not tell: one question, a choice a part, each putting
    /// what was read on that part's staves in every bar of it.
    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()
        };
        // the parts it may be: as the reason names them, or else any part of the score
        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();
        // what was read, by bar and staff (named as the reader took the system)
        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(),
        }
    }
}

/// What the reader saw in a staff's bar as `.fmn` lines that need not add up: a voice for the
/// notes with stems up (or none) and one for those with stems down, a rest to the voice that
/// has no note where it stands. `None` where nothing was seen or it cannot be written.
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 {
            // (a rest under or over the other voice's note is this one's)
            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());
    // (a tuplet the split broke is written without its number, else the notes alone)
    options::lines_of(&voices, staff, s).or_else(|| {
        for v in voices.iter_mut().flatten() {
            v.tuplets.clear();
        }
        options::lines_of(&voices, staff, s)
    })
}

/// What a read bar's other readings are about, from what the reader was unsure of in it.
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"
    }
}

/// The first of a read staff's bar's doubts about ink its reading leaves unused.
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))
}

/// Whether a read staff's bar had something the reader settled one way of several.
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())
}

/// A PDF read for review: never refused for its share of unread bars (a PDF the reader cannot
/// read at all still is: no staff lines, an unknown music font).
pub fn read_pdf_review(pdf: &[u8]) -> Result<Review, Refusal> {
    Ok(review_of(read_kept(pdf)?, page_sizes(pdf)))
}

/// The PDF read with what each staff's bar was seen as kept, never refused for its unread bars.
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
}

/// The review of a reading made by [`read_kept`].
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();
    // a system's part: one question, by system and reason
    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);
        // (the reason names the staff first)
        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);
        }
    }
    // the read bars with other readings
    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;
        }
        // printed ink the reading leaves unused: asked, not only offered
        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,
    }
}

/// Each page's size in points.
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()
}

// ---- JSON (the browser's glue passes it on as it is) ----

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)
        )
    }
}

/// A [`BarText`] as JSON: `{"staff","bar","fmn"}`.
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)
        )
    }
}

/// A [`Reading`] as JSON: the `.fmn`, the MusicXML, the counts, the notices and the bars not
/// read (bar, staff, why, and the place: page from 1, x0, x1, y0, y1).
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 {
    /// The review as JSON, its fields as named here (`reading` as [`reading_json`]).
    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]);
        }
        // every head read: the bars' notes and chords' heads
        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]);
        // (bar 4's lower voice, after its hidden rest)
        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();
        // bar 4's upper staff as if left unread, its notes seen
        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());
        // the first choice puts the bar back as it was read
        let back = fm_transcribe::replace_bars(&r.reading.fmn, &q.choices[0].rewrite).unwrap();
        assert_eq!(back, given);
        // what was seen, a voice a stem direction, to write the bar from
        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)"]);
        // the second puts what was read on Q's staves, in both bars
        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();
            // bar 4's upper staff read with a doubt settled: its other readings are latent
            let s = reading.seen.get_mut(&(4, "P.1".to_string())).unwrap();
            s.events[0].doubts.push("a doubt settled");
            if break_it {
                // (a score no rewrite of bar 4 compiles: a voice line bar 5 has no room for)
                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);
        }
        // none compiles: the bar has no choice to offer, and is not offered
        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>();
    }
}