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
//! A bar that runs on over a system's end.
//!
//! A bar too long for its line (a cadenza, a bar of 12/4, a bar the engraver chose to break) is
//! printed in pieces: the system ends with no barline, inside the bar, and the next system goes
//! on with it (a system in the middle of such a bar has no barline at all). Each system is read
//! by itself, so each piece comes out as a bar of its own, short of its time. Here the pieces
//! are put together again: the text's bars of two pieces become one bar, staff by staff and
//! voice by voice, a tie over the break landing on the voice's next note as it does inside any
//! bar, and the bars after it are numbered on from it. The bar holds what its pieces hold: its
//! time's bar (a plain bar), less (`short`), or more (`free`).
//!
//! Two things are left as they were read (a bar to each system) rather than guessed at: a piece
//! that opens with a key, a time, a tempo or a repeat of its own, and a bar that does not compile
//! once joined. One thing is left unread: a note after the break, with no accidental of its own,
//! on a place the bar altered before the break. The programs that break a bar by splitting it in
//! two (MuseScore, Finale, Sibelius) mean the key's note there; a program that knows the bar as
//! one (Dorico) means the altered one; nothing on the page says which.

use std::collections::{BTreeMap, BTreeSet};

use crate::frac::Q;
use crate::read::{Place, Unread};
use crate::smufl;
use crate::staff::{voices_of, Ev, Rest};
use crate::write::{dur_token, key_alter, plain_lengths};

/// What the reader keeps of the bars that run on, from system to system.
#[derive(Default)]
pub struct RunsOn {
    /// The system before ended inside a bar.
    pub open: bool,
    /// The bars, as numbered when read, that go on with the bar before them.
    pub joins: Vec<i64>,
    /// Each bar as numbered when read: what it holds and what its time's bar holds, in quarters.
    pub lens: BTreeMap<i64, (Q, Q)>,
    /// How many systems had a barline through them, and how many none.
    pub barred: usize,
    pub barless: usize,
    /// The page of the system read last.
    pub page: Option<usize>,
}

/// Why a score with no barline in any system is refused.
pub const NO_BARLINES: &str = "no barlines found through its top staff";

/// Whether a system with no barline through it is one piece of a bar that runs on (its start,
/// with the next system going on, or its middle): it has notes or rests, and it is the score's
/// first system or stands on the page of the system before it or the next page (`page`: its
/// page's index). A bar runs on from a system to the next one on the page or to the next page's
/// first, so a barless system pages away from the system before (a book of prose with music
/// examples) has nothing to say it is a bar's piece: the score is refused there, as it was
/// before bars that run on were read, rather than read on through pages that are not a score.
/// Counted either way: a score with no barline in any of its systems is one whose barlines were
/// not found.
pub fn all_one_piece(
    runs: &mut RunsOn,
    barlines: usize,
    page: usize,
    staff_glyphs: &[Vec<crate::page::Glyph>],
) -> bool {
    match barlines {
        0 => runs.barless += 1,
        _ => runs.barred += 1,
    }
    let near = runs.page.is_none_or(|before| page <= before + 1);
    runs.page = Some(page);
    near && staff_glyphs
        .iter()
        .flatten()
        .any(|g| smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
}

/// The bars of a system that are pieces of a bar that runs on over a system's end: its first
/// where the system before ended inside a bar, its last where this one does.
pub fn pieces(continues: bool, ends_open: bool, bars: usize) -> BTreeSet<usize> {
    let first = continues.then_some(0);
    let last = ends_open.then(|| bars.saturating_sub(1));
    first
        .into_iter()
        .chain(last)
        .filter(|b| *b < bars)
        .collect()
}

/// What each voice of a staff holds, as a share of the staff's time's bar: the voices with
/// something in them (not a bar's rest alone, not blank time alone).
fn shares(voices: &[Vec<Ev>], len: Q) -> Vec<Q> {
    voices
        .iter()
        .filter(|v| {
            v.iter()
                .any(|e| e.rest != Rest::Bar && e.rest != Rest::Blank)
        })
        .map(|v| v.iter().map(|e| e.takes()).sum::<Q>() / len)
        .collect()
}

/// Why a piece's staves are not read where they do not agree.
pub const DISAGREE: &str = "a piece of a bar that runs on over a system's end: its staves do not agree how long the piece is";

/// A piece of a bar that runs on over a system's end, read by what its staves hold. A piece is
/// as long as the engraver made it, shorter than its time's bar or longer (a cadenza over three
/// systems), so its time does not say whether a staff was read rightly: the other staves do.
/// `voices`: each staff as read against its time's bar (`lens`). Where every staff was read and
/// all their voices hold the same, they stand. Else each staff is read again with no length to
/// fill (`evs`: its notes and rests), and that reading is taken where every voice of every staff
/// holds the same, one staff at least has notes, each staff's voices start together, and, with
/// only one staff to say how long the piece is, none of its time was filled in. Failing that,
/// the staves read as a whole bar of their time stand (the time vouches for them) and every
/// other staff is left unread.
pub fn as_its_staves_agree(
    voices: &mut [Result<Vec<Vec<Ev>>, String>],
    evs: &[Vec<Ev>],
    sp: f64,
    lens: &[Q],
    right: f64,
) {
    let read: Vec<Vec<Q>> = (voices.iter().zip(lens))
        .map(|(v, &len)| v.as_ref().map_or(Vec::new(), |vs| shares(vs, len)))
        .collect();
    let all: Vec<Q> = read.iter().flatten().copied().collect();
    if voices.iter().all(|v| v.is_ok()) && all.iter().all(|s| *s == all[0]) {
        return;
    }
    if let Some(again) = with_no_length_to_fill(evs, sp, lens, right) {
        for (v, new) in voices.iter_mut().zip(again) {
            *v = Ok(new);
        }
        return;
    }
    for (v, shares) in voices.iter_mut().zip(read) {
        if v.is_ok() && shares.iter().any(|s| *s != Q::ONE) {
            *v = Err(DISAGREE.to_string());
        }
    }
}

fn with_no_length_to_fill(
    evs: &[Vec<Ev>],
    sp: f64,
    lens: &[Q],
    right: f64,
) -> Option<Vec<Vec<Vec<Ev>>>> {
    // (a length no piece reaches: the voices are then only asked to agree)
    let room = Q::int(64);
    let mut read = Vec::new();
    let mut held: Option<Q> = None;
    let mut saying = 0;
    for (staff, &len) in evs.iter().zip(lens) {
        let voices = voices_of(staff.clone(), sp, len * room, Some(right), true).ok()?;
        let timed: Vec<&Vec<Ev>> = voices
            .iter()
            .filter(|v| v.iter().any(|e| e.rest != Rest::Bar))
            .collect();
        for v in &timed {
            let share = v.iter().map(|e| e.takes()).sum::<Q>() / len;
            if share.is_zero() || share >= room / Q::int(2) || held.is_some_and(|h| h != share) {
                return None;
            }
            held = Some(share);
        }
        saying += usize::from(!timed.is_empty());
        let starts: Vec<f64> = timed
            .iter()
            .filter_map(|v| v.first().map(|e| e.x))
            .collect();
        let lo = starts.iter().copied().fold(f64::MAX, f64::min);
        if starts.iter().any(|&x| x - lo >= 2.0 * sp) {
            return None;
        }
        read.push(voices);
    }
    let noted = read.iter().flatten().flatten().any(|e| e.is_note());
    let filled = read
        .iter()
        .flatten()
        .flatten()
        .any(|e| e.rest == Rest::Blank);
    (noted && held.is_some() && (saying >= 2 || !filled)).then_some(read)
}

/// Why a staff's piece is not read.
pub const CARRIED: &str = "a bar that runs on from the system before: a note with no accidental of its own on a place the bar altered before the break (the altered note, or the key's: the page does not say)";

/// A staff's piece that goes on with the bar before the break, as read, or left unread where a
/// note of it could be read two ways: it stands on a place whose alteration in force at the
/// break (`altered`: place -> alteration) is not the key's, with no accidental printed on that
/// place since the break and no tie into it (`tied`: the places tied over the break).
pub fn sure(
    evs: &[Ev],
    altered: Option<&BTreeMap<i32, i32>>,
    tied: &BTreeSet<i32>,
    fifths: i32,
    voices: Result<Vec<Vec<Ev>>, String>,
) -> Result<Vec<Vec<Ev>>, String> {
    let (Ok(_), Some(altered)) = (&voices, altered) else {
        return voices;
    };
    let mut open: BTreeSet<i32> = altered
        .iter()
        .filter(|(p, a)| key_alter(fifths, **p) != **a)
        .map(|(p, _)| *p)
        .collect();
    let mut tied = tied.clone();
    let mut evs: Vec<&Ev> = evs.iter().filter(|e| e.is_note()).collect();
    evs.sort_by(|a, b| a.x.total_cmp(&b.x));
    for e in evs {
        for p in &e.places {
            if e.accs.contains_key(p) {
                open.remove(p);
            } else if open.contains(p) && !tied.remove(p) {
                return Err(CARRIED.to_string());
            }
        }
    }
    voices
}

/// The words that start the lines saying something of the bar, not a voice's notes or words.
const SAYS: [&str; 9] = [
    "key", "time", "tempo", "barline", "jump", "ending", "clef", "drum", "staff",
];

/// A bar's block of the text, taken apart.
#[derive(Debug, Default, PartialEq)]
struct Block {
    number: i64,
    /// After `bar N`: `pickup`, `short`, `free`, `system`.
    flags: Vec<String>,
    /// The lines that say something of the bar (`key 1 major`, `barline final`).
    says: Vec<String>,
    /// Its voices' lines in order: (staff, voice, tokens).
    voices: Vec<(String, usize, String)>,
    /// Their words: (whose: `V` or `V/2`, the label: `lyrics`, `lyrics2 lang=en`, tokens).
    words: Vec<(String, String, String)>,
}

fn parse_block(lines: &[&str]) -> Option<Block> {
    let mut head = lines.first()?.split_whitespace();
    if head.next() != Some("bar") {
        return None;
    }
    let mut block = Block {
        number: head.next()?.parse().ok()?,
        flags: head.map(str::to_string).collect(),
        ..Block::default()
    };
    for l in &lines[1..] {
        let first = l.split_whitespace().next().unwrap_or("");
        if SAYS.contains(&first) {
            block.says.push(l.to_string());
            continue;
        }
        let (who, toks) = match l.split_once(": ") {
            Some(x) => x,
            None => (l.strip_suffix(':')?, ""),
        };
        if let Some((whose, label)) = who.split_once(" lyrics") {
            let label = format!("lyrics{label}");
            block
                .words
                .push((whose.to_string(), label, toks.to_string()));
        } else if who.contains(' ') {
            return None;
        } else {
            let (staff, voice) = match who.split_once('/') {
                Some((s, v)) => (s, v.parse().ok()?),
                None => (who, 1),
            };
            block
                .voices
                .push((staff.to_string(), voice, toks.to_string()));
        }
    }
    Some(block)
}

/// A line's tokens, split at the spaces outside its quoted words (`^"con moto"`) and not taken
/// by a backslash (`to\ the`).
fn tokens(line: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let (mut start, mut quoted, mut escaped) = (None, false, false);
    for (k, c) in line.char_indices() {
        if c.is_whitespace() && !quoted && !escaped {
            if let Some(s) = start.take() {
                out.push(&line[s..k]);
            }
        } else if start.is_none() {
            start = Some(k);
        }
        quoted ^= c == '"' && !escaped;
        escaped = c == '\\' && !escaped;
    }
    if let Some(s) = start {
        out.push(&line[s..]);
    }
    out
}

/// How many of a voice's notes are sung: its notes and chords, but for grace notes and a note a
/// tie lands on.
fn sung_notes(line: &str, tied_in: bool) -> usize {
    let (mut n, mut tied, mut chord) = (0, tied_in, false);
    for t in tokens(line) {
        let is_note = {
            let mut cs = t.chars();
            matches!(cs.next(), Some('a'..='g'))
                && cs
                    .find(|c| !matches!(c, 's' | 'f' | 'n'))
                    .is_some_and(|c| c.is_ascii_digit())
        };
        if chord || t.starts_with('<') {
            chord = !t.contains('>');
        } else if !is_note {
            continue;
        }
        if chord {
            continue;
        }
        if !tied {
            n += 1;
        }
        tied = ties_on(t);
    }
    n
}

/// Whether a note's token ends with a tie to the voice's next note (`c5/4~`, not `c5/4~~`).
fn ties_on(token: &str) -> bool {
    let after = token.rsplit('/').next().unwrap_or("");
    after.contains('~') && !after.contains("~~")
}

/// A voice's line with no tie out of its last note or chord: the bar after it rests.
fn untied(line: &str) -> String {
    let Some((who, toks)) = line.split_once(": ") else {
        return line.to_string();
    };
    let mut last = None;
    let mut chord = false;
    for t in tokens(toks) {
        let at = t.as_ptr() as usize - toks.as_ptr() as usize;
        let note = {
            let mut cs = t.chars();
            matches!(cs.next(), Some('a'..='g'))
                && cs
                    .find(|c| !matches!(c, 's' | 'f' | 'n'))
                    .is_some_and(|c| c.is_ascii_digit())
        };
        if !chord && (note || t.starts_with('<')) {
            last = Some(at);
        }
        if chord || t.starts_with('<') {
            chord = !t.contains('>');
        }
    }
    match last {
        Some(at) => format!("{who}: {}{}", &toks[..at], toks[at..].replace('~', "")),
        None => line.to_string(),
    }
}

/// Time with nothing in it (`s`) or rests (`r`), `len` quarters long.
fn filler(len: Q, what: &str) -> Option<String> {
    let lens = plain_lengths(len).ok()?;
    let toks: Option<Vec<String>> = lens
        .into_iter()
        .map(|l| dur_token(l).ok().map(|d| format!("{what}/{d}")))
        .collect();
    Some(toks?.join(" "))
}

/// One piece's tokens for a voice of the joined bar: its own; rests for its bar's rest (`R`)
/// where the other piece has notes; blank time where it has no such voice.
fn piece_tokens(own: Option<&str>, len: Q, other_rests: bool) -> Option<String> {
    // (blank time alone was filled in as long as the time's bar, not the piece)
    let blank = |toks: &str| tokens(toks).iter().all(|t| t.starts_with("s/"));
    match own {
        None => filler(len, "s"),
        Some(toks) if blank(toks) => filler(len, "s"),
        Some(toks) if tokens(toks).contains(&"R") => {
            if other_rests {
                return Some(toks.to_string());
            }
            let rests = filler(len, "r")?;
            let out: Vec<&str> = tokens(toks)
                .into_iter()
                .map(|t| if t == "R" { rests.as_str() } else { t })
                .collect();
            Some(out.join(" "))
        }
        Some(toks) => Some(toks.to_string()),
    }
}

/// Two pieces of one bar as one block: `a` before the system's end and `b` after it, each
/// holding `lens` quarters, in a time whose bar holds `whole`; `unread`: the staves either was
/// not read on, which rest the joined bar. None where `b` opens with something of its own.
fn joined(
    a: &Block,
    b: &Block,
    lens: (Q, Q),
    whole: Q,
    unread: &BTreeSet<String>,
    with_words: bool,
) -> Option<Vec<String>> {
    let mut says = a.says.clone();
    let mut clefs: BTreeMap<String, String> = BTreeMap::new();
    for l in &b.says {
        let ws: Vec<&str> = l.split_whitespace().collect();
        match ws[..] {
            ["barline", end] if end != "repeat-start" => says.push(l.clone()),
            ["jump", ..] if !l.contains("segno") && !l.contains(" coda") => says.push(l.clone()),
            ["ending", ..] if says.contains(l) => {}
            ["ending", ..] => says.push(l.clone()),
            // (a clef at the system's start that is not the one the staff was in: a change in
            // the bar, before the piece's first note)
            ["clef", staff, clef] => {
                clefs.insert(staff.to_string(), clef.to_string());
            }
            _ => return None,
        }
    }
    let total = lens.0 + lens.1;
    // (a score that opens inside a bar that runs on: a pickup if the whole of it is short, else
    // the score's first bar)
    let pickup = a.flags.iter().any(|f| f == "pickup");
    let mut head = match pickup && total >= whole {
        true => format!("bar {}", b.number),
        false => format!("bar {}", a.number),
    };
    if pickup && total < whole {
        head.push_str(" pickup");
    } else if total < whole {
        head.push_str(" short");
    } else if total > whole {
        head.push_str(" free");
    }
    if a.flags.iter().any(|f| f == "system") {
        head.push_str(" system");
    }
    let mut out = vec![head];
    out.append(&mut says);
    let mut staves: Vec<&str> = Vec::new();
    for (s, _, _) in a.voices.iter().chain(&b.voices) {
        if !staves.contains(&s.as_str()) {
            staves.push(s);
        }
    }
    for staff in staves {
        if unread.contains(staff) {
            out.push(format!("{staff}: R"));
            continue;
        }
        let of = |bl: &'_ Block, v: usize| -> Option<String> {
            (bl.voices.iter())
                .find(|(s, n, _)| s == staff && *n == v)
                .map(|(_, _, t)| t.clone())
        };
        let numbers: BTreeSet<usize> = (a.voices.iter().chain(&b.voices))
            .filter(|(s, _, _)| s == staff)
            .map(|(_, v, _)| *v)
            .collect();
        for v in numbers {
            let (ta, tb) = (of(a, v), of(b, v));
            let rests = |t: &Option<String>| t.as_deref().is_some_and(|t| tokens(t).contains(&"R"));
            let both_rest = rests(&ta) && rests(&tb);
            let who = match v {
                1 => staff.to_string(),
                _ => format!("{staff}/{v}"),
            };
            let line = if both_rest {
                ta.clone()?
            } else {
                let first = piece_tokens(ta.as_deref(), lens.0, false)?;
                let mut second = piece_tokens(tb.as_deref(), lens.1, false)?;
                if let Some(c) = clefs.get(staff).filter(|_| v == 1) {
                    second = format!("\\clef:{c} {second}");
                }
                format!("{first} {second}")
            };
            out.push(format!("{who}: {line}"));
            if !with_words {
                continue;
            }
            // its words, verse by verse: where only one piece has a verse, the other's sung
            // notes have nothing under them
            let verse = |label: &str| label.split_whitespace().next().unwrap_or("").to_string();
            let mut verses: Vec<(String, String)> = Vec::new();
            for (whose, label, _) in a.words.iter().chain(&b.words) {
                if *whose == who && !verses.iter().any(|(v, _)| *v == verse(label)) {
                    verses.push((verse(label), label.clone()));
                }
            }
            for (key, label) in verses {
                let side = |bl: &Block, toks: &Option<String>, tied_in: bool| -> String {
                    let found = (bl.words.iter())
                        .find(|(whose, label, _)| *whose == who && verse(label) == key);
                    match found {
                        Some((_, _, t)) => t.clone(),
                        None => {
                            // as many as another verse of it has, else as its notes are
                            let other = bl.words.iter().find(|(whose, _, _)| *whose == who);
                            let n = match other {
                                Some((_, _, t)) => tokens(t).len(),
                                None => toks.as_deref().map_or(0, |t| sung_notes(t, tied_in)),
                            };
                            vec!["*"; n].join(" ")
                        }
                    }
                };
                // (a tie over the break lands on the second piece's first note)
                let tied =
                    (ta.as_deref()).is_some_and(|t| tokens(t).last().is_some_and(|l| ties_on(l)));
                let words = format!("{} {}", side(a, &ta, false), side(b, &tb, tied));
                out.push(format!("{who} {label}: {}", words.trim()));
            }
        }
    }
    Some(out)
}

/// The text with each bar that runs on over a system's end made one bar of its pieces, and the
/// bars after numbered on from it; the unread staves' bars and the bars' places renumbered with
/// them. A join the compiler will not have is tried without the bar's words, then left as it
/// was read. `check`: whether a text compiles. Returns how many bars were joined.
pub fn join(
    text: &mut String,
    runs: &mut RunsOn,
    unread: &mut Vec<Unread>,
    places: &mut BTreeMap<(i64, String), Place>,
    check: impl Fn(&str) -> bool,
) -> usize {
    let mut joins = std::mem::take(&mut runs.joins);
    joins.sort();
    joins.dedup();
    let mut done = 0;
    // (from the last: the pieces before keep their numbers until their turn)
    for &second in joins.iter().rev() {
        let first = second - 1;
        let (Some(&(la, whole)), Some(&(lb, _))) = (runs.lens.get(&first), runs.lens.get(&second))
        else {
            continue;
        };
        let lines: Vec<&str> = text.lines().collect();
        let starts = |n: i64| {
            let head = format!("bar {n}");
            lines
                .iter()
                .position(|l| *l == head || l.starts_with(&format!("{head} ")))
        };
        let (Some(at_a), Some(at_b)) = (starts(first), starts(second)) else {
            continue;
        };
        let end_of = |from: usize| {
            (from + 1..lines.len())
                .find(|&k| lines[k].is_empty() || lines[k].starts_with("bar "))
                .unwrap_or(lines.len())
        };
        let (end_a, end_b) = (end_of(at_a), end_of(at_b));
        // (the two blocks one after the other, a blank line between)
        if at_b < end_a || lines[end_a..at_b].iter().any(|l| !l.is_empty()) {
            continue;
        }
        let (Some(a), Some(b)) = (
            parse_block(&lines[at_a..end_a]),
            parse_block(&lines[at_b..end_b]),
        ) else {
            continue;
        };
        let lost: BTreeSet<String> = unread
            .iter()
            .filter(|u| u.bar == first || u.bar == second)
            .map(|u| u.staff.clone())
            .collect();
        // (the bar before the joined one: a tie out of it into a staff that now rests goes)
        let before = (0..at_a).rev().find(|&k| lines[k].starts_with("bar "));
        let renumbered = |block: Vec<String>, keeps_first: bool| -> String {
            let mut out: Vec<String> = lines[..at_a].iter().map(|l| l.to_string()).collect();
            for l in out.iter_mut().skip(before.unwrap_or(at_a)) {
                let staff = l.split([':', '/', ' ']).next().unwrap_or("");
                if lost.contains(staff) && !l.contains(" lyrics") {
                    *l = untied(l);
                }
            }
            out.extend(block);
            for l in &lines[end_b..] {
                let n = l
                    .strip_prefix("bar ")
                    .and_then(|r| r.split_whitespace().next())
                    .and_then(|n| n.parse::<i64>().ok());
                match n {
                    Some(n) if n > second && keeps_first => {
                        let rest = &l[4 + n.to_string().len()..];
                        out.push(format!("bar {}{rest}", n - 1));
                    }
                    _ => out.push(l.to_string()),
                }
            }
            out.join("\n") + "\n"
        };
        // (a pickup that grew to a whole bar takes the second piece's number, and the bars after
        // keep theirs)
        let keeps_first = !(a.flags.iter().any(|f| f == "pickup") && la + lb >= whole);
        let tried = [true, false].into_iter().find_map(|with_words| {
            let block = joined(&a, &b, (la, lb), whole, &lost, with_words)?;
            Some(renumbered(block, keeps_first)).filter(|t| check(t))
        });
        let Some(new) = tried else {
            continue;
        };
        *text = new;
        done += 1;
        if !keeps_first {
            runs.lens.remove(&first);
            runs.lens.insert(second, (la + lb, whole));
            for u in unread.iter_mut().filter(|u| u.bar == first) {
                if let Some(rest) = u.why.strip_prefix(&format!("bar {first},")) {
                    u.why = format!("bar {second},{rest}");
                }
                u.bar = second;
            }
            let mut seen: BTreeSet<(i64, String)> = BTreeSet::new();
            unread.retain(|u| seen.insert((u.bar, u.staff.clone())));
            let old = std::mem::take(places);
            for ((bar, staff), place) in old {
                places.entry((bar.max(second), staff)).or_insert(place);
            }
            continue;
        }
        // the joined bar holds both pieces; what came after it is numbered one less
        let later: Vec<(i64, (Q, Q))> = runs
            .lens
            .range(second + 1..)
            .map(|(k, v)| (*k, *v))
            .collect();
        runs.lens.retain(|k, _| *k < second);
        runs.lens.insert(first, (la + lb, whole));
        runs.lens.extend(later.into_iter().map(|(k, v)| (k - 1, v)));
        let moved = |bar: i64| if bar >= second { bar - 1 } else { bar };
        for u in unread.iter_mut() {
            let now = moved(u.bar);
            if now != u.bar {
                if let Some(rest) = u.why.strip_prefix(&format!("bar {},", u.bar)) {
                    u.why = format!("bar {now},{rest}");
                }
                u.bar = now;
            }
        }
        // (a staff unread in either piece is unread once, in the joined bar)
        let mut seen: BTreeSet<(i64, String)> = BTreeSet::new();
        unread.retain(|u| seen.insert((u.bar, u.staff.clone())));
        let old = std::mem::take(places);
        for ((bar, staff), place) in old {
            // (the joined bar's place: its first piece's)
            places.entry((moved(bar), staff)).or_insert(place);
        }
    }
    done
}

#[cfg(test)]
mod tests {
    use super::*;

    fn q(n: i64) -> Q {
        Q::int(n)
    }

    fn block(text: &str) -> Block {
        parse_block(&text.lines().collect::<Vec<_>>()).unwrap()
    }

    #[test]
    fn two_pieces_of_a_bar_are_one_bar_voice_by_voice() {
        let a = block("bar 7 short\nV: c5/4 d5/4~\nV lyrics: one two\nP.1: <c4 e4>/2\nP.1/2: c4/4 r/4\nP.2: c3/2");
        let b = block("bar 8 short system\nbarline double\nV: d5/2\nP.1: e4/4 f4/4\nP.2: R");
        let out = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(
            out,
            [
                "bar 7",
                "barline double",
                "V: c5/4 d5/4~ d5/2",
                "V lyrics: one two",
                "P.1: <c4 e4>/2 e4/4 f4/4",
                // a voice only the first piece has is blank through the second
                "P.1/2: c4/4 r/4 s/2",
                // a piece's bar rest is rests as long as the piece
                "P.2: c3/2 r/2",
            ]
        );
    }

    #[test]
    fn a_bar_longer_than_its_time_is_free_and_a_shorter_one_short() {
        let a = block("bar 3 short system\nP.1: c5/2.");
        let b = block("bar 4 short system\nP.1: d5/2");
        let out = joined(&a, &b, (q(3), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(out, ["bar 3 free system", "P.1: c5/2. d5/2"]);
        let out = joined(&a, &b, (q(3), q(2)), q(6), &BTreeSet::new(), true).unwrap();
        assert_eq!(out[0], "bar 3 short system");
    }

    #[test]
    fn a_staff_unread_in_either_piece_rests_the_joined_bar() {
        let a = block("bar 3 short\nV: c5/2\nV lyrics: la\nP.1: R");
        let b = block("bar 4 short system\nV: d5/2\nV lyrics: la\nP.1: e4/2");
        let lost = BTreeSet::from(["P.1".to_string()]);
        let out = joined(&a, &b, (q(2), q(2)), q(4), &lost, true).unwrap();
        assert_eq!(out, ["bar 3", "V: c5/2 d5/2", "V lyrics: la la", "P.1: R"]);
    }

    #[test]
    fn a_piece_that_opens_with_a_key_or_a_time_of_its_own_is_left_a_bar() {
        let a = block("bar 3 short\nV: c5/2");
        for says in [
            "key 2 major",
            "time 3/4",
            "barline repeat-start",
            "jump segno",
        ] {
            let b = block(&format!("bar 4 short system\n{says}\nV: d5/2"));
            assert_eq!(
                joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true),
                None
            );
        }
    }

    #[test]
    fn a_score_that_opens_inside_a_bar_that_runs_on_has_no_pickup_unless_the_whole_is_short() {
        let a = block("bar 0 pickup system\nV: c5/2");
        let b = block("bar 1 short system\nV: d5/2");
        let out = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(out, ["bar 1 system", "V: c5/2 d5/2"]);
        let out = joined(&a, &b, (q(2), q(2)), q(6), &BTreeSet::new(), true).unwrap();
        assert_eq!(out[0], "bar 0 pickup system");
        // the bars after keep their numbers where the pickup became bar 1
        let mut text =
            "bar 0 pickup system\nV: c5/2\n\nbar 1 short system\nV: d5/2\n\nbar 2\nV: R\n"
                .to_string();
        let mut runs = RunsOn {
            joins: vec![1],
            lens: BTreeMap::from([(0, (q(2), q(4))), (1, (q(2), q(4))), (2, (q(4), q(4)))]),
            ..RunsOn::default()
        };
        let mut lost = vec![unread(0, "V"), unread(2, "V")];
        join(
            &mut text,
            &mut runs,
            &mut lost,
            &mut BTreeMap::new(),
            |_| true,
        );
        assert_eq!(text, "bar 1 system\nV: R\n\nbar 2\nV: R\n");
        assert_eq!((lost[0].bar, lost[1].bar), (1, 2));
    }

    #[test]
    fn a_new_clef_after_the_break_is_a_change_in_the_bar() {
        let a = block("bar 3 short\nP.2: c3/2");
        let b = block("bar 4 short system\nclef P.2 treble\nP.2: d5/2");
        let out = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(out, ["bar 3", "P.2: c3/2 \\clef:treble d5/2"]);
    }

    #[test]
    fn a_verse_only_one_piece_has_leaves_the_others_notes_bare() {
        // (the note the tie lands on and the grace note take no word)
        let a = block("bar 3 short\nV: c5/4~ c5/8 g:e5/16 d5/8 <c5 e5>/4");
        let b = block("bar 4 short system\nV: d5/2\nV lyrics: la\nV lyrics2 lang=en: lo");
        let out = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(out[2], "V lyrics: * * * la");
        assert_eq!(out[3], "V lyrics2 lang=en: * * * lo");
        let bare = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), false).unwrap();
        assert_eq!(bare.len(), 2);
        // (and a tie over the break lands on a note with no word)
        let a = block(
            "bar 3 short
V: c5/2~
V lyrics: la",
        );
        let b = block(
            "bar 4 short system
V: c5/4 d5/4",
        );
        let out = joined(&a, &b, (q(2), q(2)), q(4), &BTreeSet::new(), true).unwrap();
        assert_eq!(out[2], "V lyrics: la *");
    }

    #[test]
    fn a_tie_into_a_staff_the_joined_bar_rests_is_taken_out() {
        assert_eq!(
            untied("P.1: c4/4~ <e4~ g4>/2~ \\!"),
            "P.1: c4/4~ <e4 g4>/2 \\!"
        );
        assert_eq!(untied("P.1: c4/4~ r/4"), "P.1: c4/4 r/4");
        let mut text =
            "bar 1 system\nV: c5/1~\nP.1: c4/1~\n\nbar 2 short\nV: c5/2\nP.1: c4/2\n\nbar 3 short system\nV: R\nP.1: d4/2\n".to_string();
        let mut runs = RunsOn {
            joins: vec![3],
            lens: BTreeMap::from([(2, (q(2), q(4))), (3, (q(2), q(4)))]),
            ..RunsOn::default()
        };
        let mut lost = vec![unread(3, "V")];
        join(
            &mut text,
            &mut runs,
            &mut lost,
            &mut BTreeMap::new(),
            |_| true,
        );
        assert_eq!(
            text,
            "bar 1 system\nV: c5/1\nP.1: c4/1~\n\nbar 2\nV: R\nP.1: c4/2 d4/2\n"
        );
        assert_eq!((lost.len(), lost[0].bar), (1, 2));
    }

    #[test]
    fn tokens_keep_quoted_words_whole() {
        assert_eq!(
            tokens("^\"con R moto\" R to\\ the x"),
            ["^\"con R moto\"", "R", "to\\ the", "x"]
        );
    }

    fn unread(bar: i64, staff: &str) -> Unread {
        Unread {
            bar,
            staff: staff.into(),
            why: format!("bar {bar}, {staff}: a bar whose notes do not add up to the time"),
            place: None,
            beside: Vec::new(),
        }
    }

    #[test]
    fn the_text_s_pieces_are_joined_and_the_bars_after_numbered_on() {
        let mut text = "title: x\n\nbar 1 system\nV: c5/1\n\nbar 2 short\nV: c5/2\n\nbar 3 short system\nV: d5/4\n\nbar 4 short system\nV: e5/4\n\nbar 5\nV: R\n".to_string();
        let mut runs = RunsOn {
            open: false,
            joins: vec![3, 4],
            lens: (1..=5)
                .map(|n| (n, (q([4, 2, 1, 1, 4][n as usize - 1]), q(4))))
                .collect(),
            ..RunsOn::default()
        };
        let mut lost = vec![unread(5, "V")];
        let mut places = BTreeMap::new();
        let n = join(&mut text, &mut runs, &mut lost, &mut places, |_| true);
        assert_eq!(n, 2);
        assert_eq!(
            text,
            "title: x\n\nbar 1 system\nV: c5/1\n\nbar 2\nV: c5/2 d5/4 e5/4\n\nbar 3\nV: R\n"
        );
        assert_eq!(lost[0].bar, 3);
        assert!(lost[0].why.starts_with("bar 3, V:"));
        assert_eq!(runs.lens[&2], (q(4), q(4)));
    }

    #[test]
    fn a_join_the_compiler_will_not_have_is_left_as_read() {
        let before = "bar 1 short system\nV: c5/2\n\nbar 2 short system\nV: d5/2\n".to_string();
        let mut text = before.clone();
        let mut runs = RunsOn {
            open: false,
            joins: vec![2],
            lens: BTreeMap::from([(1, (q(2), q(4))), (2, (q(2), q(4)))]),
            ..RunsOn::default()
        };
        let n = join(
            &mut text,
            &mut runs,
            &mut Vec::new(),
            &mut BTreeMap::new(),
            |_| false,
        );
        assert_eq!((n, text), (0, before));
    }

    fn timed(x: f64, quarters: i64) -> Ev {
        let mut e = note(x, 3, None);
        e.dur = q(quarters);
        e.up = None;
        e
    }

    #[test]
    fn a_piece_is_as_long_as_its_staves_agree_it_is() {
        let lens = [q(4), q(4)];
        let ok = |evs: &[Ev]| Ok::<_, String>(vec![evs.to_vec()]);
        let err =
            || Err::<Vec<Vec<Ev>>, String>("a bar whose notes do not add up to the time".into());
        // two staves of six quarters in 4/4: neither fills its time's bar, both agree
        let six = vec![timed(10.0, 4), timed(60.0, 2)];
        let evs = vec![six.clone(), six.clone()];
        let mut voices = vec![err(), err()];
        as_its_staves_agree(&mut voices, &evs, 1.0, &lens, 100.0);
        let held = |v: &Result<Vec<Vec<Ev>>, String>| shares(v.as_ref().unwrap(), q(4));
        assert_eq!(
            (held(&voices[0]), held(&voices[1])),
            (vec![Q::new(3, 2)], vec![Q::new(3, 2)])
        );
        // one of six quarters and one of five: neither is read
        let evs = vec![six.clone(), vec![timed(10.0, 4), timed(60.0, 1)]];
        let mut voices = vec![ok(&six), err()];
        as_its_staves_agree(&mut voices, &evs, 1.0, &lens, 100.0);
        assert_eq!(voices[0].clone().unwrap_err(), DISAGREE);
        assert!(voices[1].is_err());
        // a staff that fills its time's bar stands beside one that could not be read
        let four = vec![timed(10.0, 4)];
        let evs = vec![four.clone(), vec![timed(10.0, 4), timed(60.0, 1)]];
        let mut voices = vec![ok(&four), err()];
        as_its_staves_agree(&mut voices, &evs, 1.0, &lens, 100.0);
        assert!(voices[0].is_ok() && voices[1].is_err());
        // staves read and agreeing are left as they were read
        let mut voices = vec![ok(&six), ok(&six)];
        as_its_staves_agree(&mut voices, &[Vec::new(), Vec::new()], 1.0, &lens, 100.0);
        assert!(voices.iter().all(|v| v.is_ok()));
    }

    #[test]
    fn a_barless_system_is_a_piece_only_next_to_the_system_before() {
        let head = crate::page::Glyph {
            code: 0xE0A4,
            x0: 10.0,
            x1: 11.2,
            y: 10.0,
            size: 4.0,
        };
        let noted = vec![vec![head]];
        let runs = &mut RunsOn::default();
        // a score's first system, then one on its page, then the next page's
        assert!(all_one_piece(runs, 0, 4, &noted));
        assert!(all_one_piece(runs, 0, 4, &noted));
        assert!(all_one_piece(runs, 0, 5, &noted));
        // pages away from the system before (a book's music example): not a bar's piece
        assert!(!all_one_piece(runs, 0, 20, &noted));
        // nor a system with nothing in it
        assert!(!all_one_piece(runs, 0, 20, &[Vec::new()]));
        assert_eq!((runs.barred, runs.barless), (0, 5));
        all_one_piece(runs, 3, 21, &noted);
        assert_eq!(runs.barred, 1);
    }

    #[test]
    fn the_pieces_of_a_system_are_its_first_and_last_bars() {
        assert_eq!(pieces(true, true, 3), BTreeSet::from([0, 2]));
        assert_eq!(pieces(false, true, 1), BTreeSet::from([0]));
        assert_eq!(pieces(true, false, 4), BTreeSet::from([0]));
        assert!(pieces(false, false, 4).is_empty());
    }

    fn note(x: f64, place: i32, acc: Option<i32>) -> Ev {
        let mut e = Ev::new(Vec::new(), None, Some(true));
        e.x = x;
        e.dur = Q::ONE;
        e.places = vec![place];
        e.place_of = vec![place];
        if let Some(a) = acc {
            e.accs.insert(place, (a, false));
        }
        e
    }

    #[test]
    fn a_bare_note_where_the_bar_was_altered_before_the_break_is_not_read() {
        let altered = BTreeMap::from([(3, 1)]);
        let none = BTreeSet::new();
        let read = |evs: &[Ev], tied: &BTreeSet<i32>| {
            sure(evs, Some(&altered), tied, 0, Ok(vec![evs.to_vec()]))
        };
        // on another place, or with its own accidental: read
        assert!(read(&[note(1.0, 4, None)], &none).is_ok());
        assert!(read(&[note(1.0, 3, Some(0)), note(2.0, 3, None)], &none).is_ok());
        // bare on the altered place: either reading may be meant
        assert_eq!(read(&[note(1.0, 3, None)], &none).unwrap_err(), CARRIED);
        // tied over the break it is the altered note; the next one bare is in doubt again
        let tied = BTreeSet::from([3]);
        assert!(read(&[note(1.0, 3, None)], &tied).is_ok());
        assert!(read(&[note(1.0, 3, None), note(2.0, 3, None)], &tied).is_err());
        // an alteration that is the key's own leaves nothing in doubt (F sharp in G)
        let fs = (0..12).find(|p| key_alter(1, *p) == 1).unwrap();
        let altered = BTreeMap::from([(fs, 1)]);
        assert!(sure(
            &[note(1.0, fs, None)],
            Some(&altered),
            &none,
            1,
            Ok(Vec::new())
        )
        .is_ok());
        // a system that goes on with no bar has nothing carried
        assert!(sure(&[note(1.0, 3, None)], None, &none, 0, Ok(Vec::new())).is_ok());
    }
}