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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
//! Tuplets whose number is not printed where the reader looks for it: an engraver prints the 3
//! over the first few triplets and then stops, hides it throughout, or prints it bare (no
//! bracket) over notes that no one beam joins. A staff's bar that does not add up as printed is
//! read again here with such groups taken as tuplets, on evidence: a bare number standing over
//! the middle of the group, a beam that joins three notes (or five, six, seven) where two or four
//! would be usual, a group set as a tuplet marked earlier on the staff was, and the other
//! staves' columns (what sounds together stands one above the other, so three notes that span
//! what another staff shows to be one beat are a triplet). A reading is taken only where it is
//! the one such reading that fills the bar and stands in the columns; where two do, or a
//! number printed in the bar is left with no notes, the bar is left as it was.

use crate::columns::{self, Mark};
use crate::frac::Q;
use crate::staff::{next_group, voices_of, Ev, Rest};

/// What says a group of notes is a tuplet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum By {
    /// A number printed over its middle.
    Number,
    /// One beam joining just these notes.
    Beam,
    /// Set as a tuplet marked before on the staff was: the same values, beamed the same.
    Before,
    /// Nothing of its own: the other staves' columns have to show it.
    Columns,
}

#[derive(Clone, Debug)]
struct Cand {
    members: Vec<usize>,
    ratio: (u32, u32),
    by: By,
    /// The number it is under (its place among the bar's loose numbers).
    number: Option<usize>,
    /// How many of its notes make one tuplet (nine sixteenths on a beam, three triplets); 0
    /// where all do.
    each: usize,
}

/// One bar of a system, for [`unnumbered_in_bar`].
pub struct Bar<'a> {
    /// The staves' names (`P.1`, `P.2`: one part's two staves).
    pub names: &'a [String],
    /// Each staff's own time where it is not the bar's.
    pub own_time: &'a [Option<(i64, i64)>],
    /// Each staff's notes read in tuplets before this bar (and in it).
    pub seen: &'a [Vec<Ev>],
    pub sp: f64,
    pub len: Q,
    pub right: Option<f64>,
    pub short: bool,
}

fn timed(e: &Ev) -> bool {
    e.grace.is_none() && matches!(e.rest, Rest::None | Rest::Printed(_))
}

/// A note or printed rest that takes time and is in no tuplet yet.
fn free(e: &Ev) -> bool {
    timed(e) && e.tuplets.is_empty() && e.tremolo.is_none()
}

/// The bar's notes and rests in turn, then each stem's voice alone with the rests.
fn lanes(evs: &[Ev], one: bool) -> Vec<Vec<usize>> {
    let mut out: Vec<Vec<usize>> = Vec::new();
    for lane in [None, Some(true), Some(false)] {
        let l: Vec<usize> = (0..evs.len())
            .filter(|&i| timed(&evs[i]) && (lane.is_none() || evs[i].up != lane.map(|u: bool| !u)))
            .collect();
        if !out.contains(&l) {
            out.push(l);
        }
        if one {
            break;
        }
    }
    out
}

/// The ratio a group of `k` notes of one value has with no number printed: its count in the
/// time of the power of two below it (3 in 2, 5 6 7 in 4, 9 to 15 in 8).
fn ratio_of(k: usize) -> Option<(u32, u32)> {
    let k = k as u32;
    ((3..=15).contains(&k) && !k.is_power_of_two()).then(|| (k, 1 << (31 - k.leading_zeros())))
}

/// The bar's numbers that grouped nothing, each once (a number set in the music font may be
/// read as a word too, and one between two staves by both): the staff's own, and with `far`
/// those that may be another staff's (for a part's two staves read together).
fn loose_numbers(evs: &[Ev], sp: f64, far: bool) -> Vec<(u32, u32, f64, bool)> {
    numbers_over(evs, sp, far, false)
}

/// The staff's own numbers that grouped nothing and stand over a tuplet that has its number:
/// another staff's, set between the two; or the number of another voice's tuplet at the same
/// place (a quarter and an eighth under a bare 3, stems up, over three beamed eighths with
/// their 3 below).
fn spare_numbers(evs: &[Ev], sp: f64) -> Vec<(u32, u32, f64, bool)> {
    numbers_over(evs, sp, false, true)
}

fn numbers_over(evs: &[Ev], sp: f64, far: bool, spare: bool) -> Vec<(u32, u32, f64, bool)> {
    let mut out: Vec<(u32, u32, f64, bool)> = Vec::new();
    // (nor one over a tuplet that has its number: another staff's, set between the two)
    let over_one = |cx: f64| {
        evs.iter().flat_map(|e| e.tuplets.iter()).any(|t| {
            let xs = evs
                .iter()
                .filter(|e| e.tuplets.iter().any(|u| u.2 == t.2))
                .map(|e| e.x);
            let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |a, x| (a.0.min(x), a.1.max(x)));
            lo - 0.5 * sp <= cx && cx <= hi + 1.7 * sp
        })
    };
    for own in [true, false] {
        for n in evs.iter().flat_map(|e| e.loose.iter().copied()) {
            if n.3 == own
                && (own || far)
                && !out
                    .iter()
                    .any(|o| o.0 == n.0 && (o.2 - n.2).abs() < 0.5 * sp)
                && over_one(n.2) == spare
            {
                out.push(n);
            }
        }
    }
    out
}

/// The groups a bare number may be over: runs of one lane's notes and rests that the number
/// divides, the number over their middle. The best centred of them, one that keeps every beam
/// whole before one that does not, and one of as many notes as the number says before another.
fn by_number(evs: &[Ev], sp: f64, one: bool, out: &mut Vec<Cand>) {
    let loose = loose_numbers(evs, sp, one).into_iter().map(|n| (n, false));
    let spare = spare_numbers(evs, sp).into_iter().map(|n| (n, true));
    let spare = spare.filter(|_| !one);
    for (k, ((a, n, cx, own), spare)) in loose.chain(spare).enumerate() {
        let mut best: Option<((bool, bool, f64), Vec<usize>)> = None;
        for lane in lanes(evs, one) {
            for s in 0..lane.len() {
                let mut shown = Q::ZERO;
                for e in s..lane.len() {
                    let ev = &evs[lane[e]];
                    // one note with strokes across its stem, a number at it: the strokes'
                    // notes written short (a dotted quarter for a triplet of eighths)
                    let stroked = matches!(ev.tremolo, Some(crate::staff::Trem::Single(_)))
                        && timed(ev)
                        && ev.tuplets.is_empty();
                    if !free(ev) && !(e == s && stroked) {
                        break;
                    }
                    shown += ev.dur;
                    let unit = shown / Q::int(a as i64);
                    // (a tuplet's notes are no longer than twice the note its number counts)
                    if (e == s && !stroked)
                        || !unit.is_power_of_two()
                        || (!stroked && (s..=e).any(|k| evs[lane[k]].dur > unit * Q::int(2)))
                    {
                        continue;
                    }
                    let mid = (evs[lane[s]].x + evs[lane[e]].x) / 2.0 + 0.6 * sp;
                    let off = (mid - cx).abs();
                    let run = &lane[s..=e];
                    let splits = run.iter().any(|&m| {
                        (0..evs.len()).any(|o| !run.contains(&o) && beamed(&evs[m], &evs[o]))
                    });
                    // (three notes under a 3 before six)
                    let key = (splits, run.len() != a as usize, off);
                    if off < 1.0 * sp && best.as_ref().is_none_or(|b| key < b.0) {
                        best = Some((key, run.to_vec()));
                    }
                }
            }
        }
        if let Some((_, members)) = best {
            out.push(Cand {
                members,
                ratio: (a, n),
                by: By::Number,
                // (a spare number is one no reading has to give notes to)
                number: (own && !spare).then_some(k),
                each: 0,
            });
        }
    }
}

/// Whether two notes are on one beam.
fn beamed(a: &Ev, b: &Ev) -> bool {
    a.is_note() && b.is_note() && a.beam_polys.iter().any(|p| b.beam_polys.contains(p))
}

/// The groups one beam joins that may be tuplets: three notes of one value (or five, six,
/// seven, nine and so on), or notes that make three of one value (a dotted eighth, a sixteenth
/// and an eighth).
fn by_beam(evs: &[Ev], out: &mut Vec<Cand>) {
    let mut done: Vec<usize> = Vec::new();
    for i in 0..evs.len() {
        if done.contains(&i) || !evs[i].is_note() || evs[i].beam_polys.is_empty() {
            continue;
        }
        // the notes beamed with it, through any beam
        let mut group = vec![i];
        let mut grew = true;
        while grew {
            grew = false;
            for j in 0..evs.len() {
                if !group.contains(&j) && group.iter().any(|&g| beamed(&evs[g], &evs[j])) {
                    group.push(j);
                    grew = true;
                }
            }
        }
        group.sort_by(|&a, &b| evs[a].x.total_cmp(&evs[b].x));
        done.extend(&group);
        if !group.iter().all(|&g| free(&evs[g])) {
            continue;
        }
        let shown: Q = group.iter().map(|&g| evs[g].dur).sum();
        let even = group.iter().all(|&g| evs[g].dur == evs[group[0]].dur);
        let ratio = if even {
            ratio_of(group.len())
        } else if group.len() >= 3 && (shown / Q::int(3)).is_power_of_two() {
            Some((3, 2))
        } else {
            None
        };
        if let Some(ratio) = ratio {
            if !out.iter().any(|c| c.members == group) {
                // (nine or twelve of one value: so many in the time of eight, or triplets)
                if even && group.len() > 6 && group.len() % 3 == 0 {
                    out.push(Cand {
                        members: group.clone(),
                        ratio: (3, 2),
                        by: By::Beam,
                        number: None,
                        each: 3,
                    });
                }
                out.push(Cand {
                    members: group,
                    ratio,
                    by: By::Beam,
                    number: None,
                    each: 0,
                });
            }
        }
    }
}

/// A tuplet as it was set: its ratio, its members' values as shown and whether each is a note,
/// and whether each is beamed to the next.
type Shape = (u32, u32, Vec<(Q, bool)>, Vec<bool>);

fn shapes(seen: &[Ev]) -> Vec<Shape> {
    let mut ids: Vec<usize> = Vec::new();
    for e in seen {
        if let [(_, _, id)] = e.tuplets[..] {
            if !ids.contains(&id) {
                ids.push(id);
            }
        }
    }
    let mut out: Vec<Shape> = Vec::new();
    for id in ids {
        let members: Vec<&Ev> = seen
            .iter()
            .filter(|e| e.grace.is_none() && e.tuplets.iter().any(|t| t.2 == id))
            .collect();
        if members.len() < 2 || members.iter().any(|e| e.rest == Rest::Blank) {
            continue;
        }
        let (a, n, _) = members[0].tuplets[0];
        // (one shared with the part's other staff has only some of its notes here: no shape)
        let shown: Q = members.iter().map(|e| e.written()).sum();
        if !(shown / Q::int(a as i64)).is_power_of_two() {
            continue;
        }
        let shape = (
            a,
            n,
            members.iter().map(|e| (e.written(), e.is_note())).collect(),
            members.windows(2).map(|w| beamed(w[0], w[1])).collect(),
        );
        if !out.contains(&shape) {
            out.push(shape);
        }
    }
    out
}

/// Runs set as a tuplet marked before on the staff was.
fn by_shape(evs: &[Ev], seen: &[Ev], one: bool, out: &mut Vec<Cand>) {
    let shapes = shapes(seen);
    for lane in lanes(evs, one) {
        for s in &shapes {
            for w in lane.windows(s.2.len()) {
                let same = w.iter().zip(&s.2).all(|(&i, &(d, note))| {
                    free(&evs[i]) && evs[i].dur == d && evs[i].is_note() == note
                }) && w
                    .windows(2)
                    .zip(&s.3)
                    .all(|(p, &j)| beamed(&evs[p[0]], &evs[p[1]]) == j);
                if same && !out.iter().any(|c| c.members == w) {
                    out.push(Cand {
                        members: w.to_vec(),
                        ratio: (s.0, s.1),
                        by: By::Before,
                        number: None,
                        each: 0,
                    });
                }
            }
        }
    }
}

/// Runs of three notes or rests of one value, one lane's, that nothing of their own marks.
fn by_run(evs: &[Ev], one: bool, out: &mut Vec<Cand>) {
    for lane in lanes(evs, one) {
        for w in lane.windows(3) {
            let d = evs[w[0]].dur;
            if w.iter().all(|&i| free(&evs[i]) && evs[i].dur == d)
                && w.iter().any(|&i| evs[i].is_note())
                && d <= Q::ONE
                && d.is_power_of_two()
                && !out.iter().any(|c| c.members == w)
            {
                out.push(Cand {
                    members: w.to_vec(),
                    ratio: (3, 2),
                    by: By::Columns,
                    number: None,
                    each: 0,
                });
            }
        }
    }
}

/// The events with the groups taken as tuplets, and each tuplet made: its number, how many
/// notes it has, and whether the columns have to show it.
fn taken(events: &[Ev], cands: &[&Cand]) -> (Vec<Ev>, Vec<(usize, usize, bool)>) {
    let mut evs = events.to_vec();
    let mut made = Vec::new();
    for c in cands {
        let each = if c.each == 0 { c.members.len() } else { c.each };
        for part in c.members.chunks(each) {
            let id = next_group();
            made.push((id, part.len(), c.by == By::Columns));
            for &i in part {
                evs[i].tuplets.push((c.ratio.0, c.ratio.1, id));
                evs[i].dur = evs[i].dur * Q::new(c.ratio.1 as i64, c.ratio.0 as i64);
            }
        }
    }
    (evs, made)
}

/// A note stands in another staff's column when no further from it than this, in spaces.
const IN_COLUMN: f64 = 0.7;

/// Whether the other staves' columns show a group to last what its tuplet says: a column of
/// theirs where it starts, at its start, and one where the voice's next note stands, at that
/// note's start (or, for a group that ends the bar, a later column of theirs under it).
fn shown_by_columns(voices: &[Vec<Ev>], group: usize, others: &[Mark], len: Q, sp: f64) -> bool {
    let of = |e: &Ev| e.tuplets.iter().any(|t| t.2 == group);
    for v in voices {
        let Some(first) = v.iter().position(of) else {
            continue;
        };
        let last = v.iter().rposition(of).unwrap_or(first);
        let before = |k: usize| -> Q { v[..k].iter().map(|e| e.takes()).sum() };
        let at = |x: f64, t: Q| {
            others
                .iter()
                .any(|m| m.at == t && (m.x - x).abs() <= IN_COLUMN * sp + m.play)
        };
        let starts = v[first].is_note() && at(columns::column_x(&v[first]), before(first));
        let next = (last + 1..v.len()).find(|&k| v[k].is_note() && v[k].grace.is_none());
        let ends = match next {
            Some(k) => at(columns::column_x(&v[k]), before(k)),
            None => before(last + 1) == len && others.iter().any(|m| m.at > before(first)),
        };
        return starts && ends;
    }
    false
}

/// When each note starts and how long it lasts: what tells two readings apart.
fn starts(voices: &[Vec<Ev>]) -> Vec<(Q, Q)> {
    let mut out: Vec<(Q, Q)> = Vec::new();
    for v in voices {
        let mut t = Q::ZERO;
        for e in v {
            if e.is_note() {
                out.push((t, e.takes()));
            }
            t += e.takes();
        }
    }
    out.sort_by(|a, b| {
        (a.0.to_f64(), a.1.to_f64())
            .partial_cmp(&(b.0.to_f64(), b.1.to_f64()))
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    out
}

/// The bar's other staves, for a staff (or a part's two) being read again: every staff as read
/// (`None`: unread, or the one being read), where the new reading goes, and the columns of the
/// staves the columns do not speak against.
struct Beside {
    staves: Vec<Option<Vec<Vec<Ev>>>>,
    home: usize,
    marks: Vec<Mark>,
}

impl Beside {
    fn new(voices: &[Result<Vec<Vec<Ev>>, String>], out: &[usize], home: usize, sp: f64) -> Beside {
        let staves: Vec<Option<Vec<Vec<Ev>>>> = (0..voices.len())
            .map(|j| {
                voices[j]
                    .as_ref()
                    .ok()
                    .filter(|_| !out.contains(&j))
                    .cloned()
            })
            .collect();
        let bad = misread(&staves, sp);
        let marks = (0..staves.len())
            .filter(|&j| !bad[j])
            .filter_map(|j| staves[j].as_ref())
            .flat_map(|vs| columns::columns(&columns::marks(vs)))
            .collect();
        Beside {
            staves,
            home,
            marks,
        }
    }

    /// Whether the columns speak against a reading of the staff: its own, or those of the
    /// staves that stand unquestioned.
    fn against(&self, voices: &[Vec<Ev>], sp: f64) -> bool {
        let mine = columns::marks(voices);
        columns::contradicts_itself(&mine, sp)
            || columns::contradict(&columns::columns(&mine), &self.marks, sp)
    }

    /// Whether the part's other staff is read (so that no voice passes between the two unseen).
    fn mate_read(&self, names: &[String]) -> bool {
        let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
        (0..names.len())
            .filter(|&j| j != self.home && part(&names[j]) == part(&names[self.home]))
            .all(|j| self.staves[j].is_some())
    }
}

fn misread(staves: &[Option<Vec<Vec<Ev>>>], sp: f64) -> Vec<bool> {
    let views: Vec<Option<&[Vec<Ev>]>> = staves.iter().map(|s| s.as_deref()).collect();
    columns::misread(&views, sp)
}

/// One voice whose rests the program hid, timed by the columns: its notes and rests one after
/// another in tuplets as taken fall short of the bar, and each note (or tuplet's rest) that
/// stands in a column of the other staves starts with it, the time before it blank. Blank
/// time after the last only where another staff goes on past it. Only where the columns show
/// each tuplet to be one.
fn blank_by_columns(evs: &[Ev], beside: &[Mark], bar: &Bar) -> Option<Vec<Vec<Ev>>> {
    let sp = bar.sp;
    let one_voice = evs.iter().all(timed)
        && evs.windows(2).all(|w| w[1].x - w[0].x > 0.5 * sp)
        && evs.iter().any(|e| !e.tuplets.is_empty());
    if !one_voice || beside.is_empty() {
        return None;
    }
    let mut out: Vec<Ev> = Vec::new();
    let mut t = Q::ZERO;
    let mut blanks = 0;
    for e in evs {
        // (a rest alone is set where it has room; one in a tuplet stands at its time)
        let x = match e.is_note() {
            true => Some(columns::column_x(e)),
            false => (!e.tuplets.is_empty()).then_some(e.x),
        };
        let at = x.and_then(|x| {
            beside
                .iter()
                .filter(|m| (m.x - x).abs() <= IN_COLUMN * sp)
                .min_by(|a, b| (a.x - x).abs().total_cmp(&(b.x - x).abs()))
                .map(|m| m.at)
        });
        match at {
            Some(c) if c < t => return None,
            Some(c) if c > t => {
                // (not inside a tuplet)
                let inside = out.last().is_some_and(|p| {
                    p.tuplets
                        .last()
                        .is_some_and(|a| e.tuplets.last().is_some_and(|b| a.2 == b.2))
                });
                if inside {
                    return None;
                }
                crate::write::plain_lengths(c - t).ok()?;
                out.push(Ev::spacer(c - t, e.x - 0.01));
                blanks += 1;
                t = c;
            }
            _ => {}
        }
        out.push(e.clone());
        t += e.takes();
    }
    if t > bar.len {
        return None;
    }
    if t < bar.len {
        let last = evs.last()?.x;
        if !beside.iter().any(|m| m.at >= t && m.x > last + 1.0 * sp) {
            return None;
        }
        crate::write::plain_lengths(bar.len - t).ok()?;
        out.push(Ev::spacer(bar.len - t, last + 0.01));
        blanks += 1;
    }
    // each tuplet is one by the columns: another staff's note right of its last note starts
    // before notes of the lengths printed would end, or the bar ends before they would (so a
    // bar that only lacks notes, read elsewhere, is not made up with tuplets and blank time)
    let mut ids: Vec<usize> = out
        .iter()
        .filter_map(|e| e.tuplets.last().map(|t| t.2))
        .collect();
    ids.dedup();
    let told = ids.iter().all(|&id| {
        let of = |e: &Ev| e.tuplets.last().is_some_and(|t| t.2 == id);
        let first = out.iter().position(of).unwrap_or(0);
        let last = out.iter().rposition(of).unwrap_or(first);
        let t0: Q = out[..first].iter().map(|e| e.takes()).sum();
        let printed: Q = out[first..=last].iter().map(|e| e.written()).sum();
        t0 + printed > bar.len
            || beside
                .iter()
                .any(|m| m.x > out[last].x + 0.3 * sp && m.at < t0 + printed)
    });
    (blanks > 0 && told).then(|| vec![out])
}

/// The readings of `events` with some of `cands` taken that `voiced` makes voices of (told
/// whether every group taken is shown by a number, a beam or an earlier tuplet), that the
/// columns do not speak against, and that give every loose number its notes: the one there is,
/// if there is one. First with the groups a number, a beam or an earlier tuplet shows, then
/// with runs the columns have to show; and with every beam kept whole before with one split.
/// `some_runs`: a run or two may be taken among plain notes; `some_tuplets`: tuplets may be
/// taken among plain notes at all (else the bar is nothing but tuplets).
fn one_reading(
    events: &[Ev],
    cands: &[Cand],
    numbers: usize,
    beside: &Beside,
    bar: &Bar,
    (some_runs, some_tuplets): (bool, bool),
    voiced: &dyn Fn(Vec<Ev>, bool) -> Option<Vec<Vec<Ev>>>,
) -> Option<(Vec<Ev>, Vec<Vec<Ev>>)> {
    // a tuplet that takes some of a beam's notes and leaves others
    let splits = |c: &Cand| {
        c.members.iter().any(|&m| {
            (0..events.len()).any(|o| !c.members.contains(&o) && beamed(&events[m], &events[o]))
        })
    };
    // (where the groups to try are many, those the columns have to show are left out, then
    // those that split a beam; of more groups than can be tried one by one, all together)
    let fewer: Vec<Cand>;
    let cands = if cands.len() <= 14 {
        cands
    } else {
        let shown: Vec<Cand> = cands
            .iter()
            .filter(|c| c.by != By::Columns)
            .cloned()
            .collect();
        fewer = match shown.len() {
            0..=12 => shown,
            _ => shown.into_iter().filter(|c| !splits(c)).collect(),
        };
        &fewer[..]
    };
    if cands.is_empty() || cands.len() > 30 {
        return None;
    }
    let sets = if cands.len() <= 14 {
        1u32..(1 << cands.len())
    } else {
        (1 << cands.len()) - 1..(1 << cands.len())
    };
    let sp = bar.sp;
    // set as an earlier tuplet was with no beam to show it (a quarter and an eighth): what
    // any quarter before an eighth looks like
    let unbeamed = |c: &Cand| {
        c.by == By::Before && !(c.members.windows(2)).any(|w| beamed(&events[w[0]], &events[w[1]]))
    };
    let levels = [(false, false), (false, true), (true, false), (true, true)];
    // (what does not change from level to level is worked out once: which groups each set
    // takes, and whether it passes the tests a level does not bear on)
    let cand_splits: Vec<bool> = cands.iter().map(splits).collect();
    let cand_unbeamed: Vec<bool> = cands.iter().map(unbeamed).collect();
    struct Set {
        runs: usize,
        splits: bool,
        unbeamed: bool,
        pick: Vec<usize>,
    }
    let all_sets: Vec<Set> = sets
        .clone()
        .filter_map(|set| {
            let pick: Vec<usize> = (0..cands.len()).filter(|&k| set & (1 << k) != 0).collect();
            let runs = pick.iter().filter(|&&k| cands[k].by == By::Columns).count();
            let used = pick.iter().filter(|&&k| cands[k].number.is_some()).count();
            // (more than two runs only where the bar is nothing but tuplets: twelve eighths in
            // 4/4)
            let covered = |i: usize| pick.iter().any(|&k| cands[k].members.contains(&i));
            let all = (0..events.len())
                .all(|i| !timed(&events[i]) || !events[i].tuplets.is_empty() || covered(i));
            if (pick.len() > 8 && sets.len() > 1)
                || (runs > if some_runs { 2 } else { 0 } && !all)
                || (!all && !some_tuplets)
                || used != numbers
            {
                return None;
            }
            let overlap = pick.iter().enumerate().any(|(a, &c)| {
                pick[..a].iter().any(|&d| {
                    cands[c]
                        .members
                        .iter()
                        .any(|i| cands[d].members.contains(i))
                        || (cands[c].number.is_some() && cands[c].number == cands[d].number)
                })
            });
            if overlap {
                return None;
            }
            Some(Set {
                runs,
                splits: pick.iter().any(|&k| cand_splits[k]),
                unbeamed: pick.iter().any(|&k| cand_unbeamed[k]),
                pick,
            })
        })
        .collect();
    // what a set reads as, if it reads: the same at every level it comes up in
    type Reading = Option<(Vec<Ev>, Vec<Vec<Ev>>, Vec<(Q, Q)>)>;
    let mut read_as: Vec<Option<Reading>> = vec![None; all_sets.len()];
    // (at each step, first without the groups set as an unbeamed tuplet was)
    for ((with_runs, split), sure) in levels.into_iter().flat_map(|l| [(l, true), (l, false)]) {
        let mut found: Vec<(Vec<Ev>, Vec<Vec<Ev>>)> = Vec::new();
        let mut seen: Vec<Vec<(Q, Q)>> = Vec::new();
        for (n, set) in all_sets.iter().enumerate() {
            if (sure && set.unbeamed) || set.splits != split || (set.runs > 0) != with_runs {
                continue;
            }
            let reading = read_as[n].get_or_insert_with(|| {
                let pick: Vec<&Cand> = set.pick.iter().map(|&k| &cands[k]).collect();
                let runs = set.runs;
                let (evs, made) = taken(events, &pick);
                let voices = voiced(evs.clone(), runs == 0)?;
                // every tuplet whole in one voice, its notes one after another
                let whole = made.iter().all(|&(id, len, _)| {
                    voices.iter().any(|v| {
                        let at: Vec<usize> = (0..v.len())
                            .filter(|&k| v[k].tuplets.last().map(|t| t.2) == Some(id))
                            .collect();
                        at.len() == len && at.windows(2).all(|w| w[1] == w[0] + 1)
                    })
                });
                if !whole || beside.against(&voices, sp) {
                    return None;
                }
                // the columns show every run; or one of them, where the bar is nothing but
                // tuplets
                let shown = made
                    .iter()
                    .filter(|m| m.2 && shown_by_columns(&voices, m.0, &beside.marks, bar.len, sp))
                    .count();
                // (or most of its tuplets are shown by a number, a beam or an earlier tuplet)
                let most = pick.len() >= 2 * runs;
                let covered = |i: usize| pick.iter().any(|c| c.members.contains(&i));
                let all = (0..events.len())
                    .all(|i| !timed(&events[i]) || !events[i].tuplets.is_empty() || covered(i));
                if (all && runs > 0 && shown == 0 && !most) || (!all && shown < runs) {
                    return None;
                }
                let s = starts(&voices);
                Some((evs, voices, s))
            });
            let Some((evs, voices, s)) = reading else {
                continue;
            };
            if !seen.contains(s) {
                seen.push(s.clone());
                found.push((evs.clone(), voices.clone()));
            }
        }
        match found.len() {
            0 => continue,
            1 => return found.pop(),
            _ => return None,
        }
    }
    None
}

/// A tuplet of one note: a number given to a note it is not over. A bar with one is not read
/// again here.
fn lone_tuplet(events: &[Ev]) -> bool {
    events.iter().any(|e| {
        e.tuplets.iter().any(|t| {
            let of = |o: &&Ev| o.tuplets.iter().any(|u| u.2 == t.2);
            events.iter().filter(of).count() < 2
        })
    })
}

/// One staff's bar that does not add up (or whose reading the columns speak against), read
/// with tuplets its numbers, beams, the tuplets before it (`seen`) or the other staves' columns
/// show: the events so marked and their voices, where one reading alone fills the bar and
/// the columns do not speak against it. Where the tuplets a number, a beam or an earlier
/// tuplet shows leave one voice short of the bar, the columns say where its hidden rests are.
fn unnumbered(
    events: &[Ev],
    seen: &[Ev],
    beside: &Beside,
    bar: &Bar,
) -> Option<(Vec<Ev>, Vec<Vec<Ev>>)> {
    if lone_tuplet(events) {
        return None;
    }
    let mut cands: Vec<Cand> = Vec::new();
    by_number(events, bar.sp, false, &mut cands);
    by_beam(events, &mut cands);
    by_shape(events, seen, false, &mut cands);
    by_run(events, false, &mut cands);
    let numbers = loose_numbers(events, bar.sp, false).len();
    let mate = beside.mate_read(bar.names);
    let voiced = |evs: Vec<Ev>, shown: bool| {
        voices_of(evs.clone(), bar.sp, bar.len, bar.right, bar.short)
            .ok()
            .or_else(|| blank_by_columns(&evs, &beside.marks, bar).filter(|_| shown && mate))
    };
    one_reading(events, &cands, numbers, beside, bar, (true, true), &voiced)
}

/// One voice passing between a part's two staves with nothing beamed across (an arpeggio in
/// triplets, a hand to each beat): neither staff's bar adds up alone, and their notes taken
/// together, in the order they stand, are one voice that fills the bar with its tuplets
/// taken. The voice so read: its events, each with whether it is the second staff's. Its
/// tuplets are those a number, a beam or an earlier tuplet shows, or the bar is nothing but
/// triplets; and nothing but tuplets where one of the staves adds up alone (`whole`).
fn across(
    a: &[Ev],
    b: &[Ev],
    seen: &[Ev],
    beside: &Beside,
    bar: &Bar,
    whole: bool,
) -> Option<Vec<(Ev, bool)>> {
    let sp = bar.sp;
    if lone_tuplet(a) || lone_tuplet(b) || a.iter().chain(b).any(|e| e.grace.is_some()) {
        return None;
    }
    let mut all: Vec<(Ev, bool)> = a
        .iter()
        .map(|e| (e.clone(), false))
        .chain(b.iter().map(|e| (e.clone(), true)))
        .filter(|(e, _)| timed(e))
        .collect();
    all.sort_by(|p, q| p.0.x.total_cmp(&q.0.x));
    // one voice: each note well right of the one before; and both staves have notes in it
    let apart = all
        .windows(2)
        .all(|w| columns::column_x(&w[1].0) - columns::column_x(&w[0].0) > 1.0 * sp);
    let both = [false, true]
        .iter()
        .all(|&s| all.iter().any(|(e, second)| *second == s && e.is_note()));
    if !apart || !both {
        return None;
    }
    let events: Vec<Ev> = all.iter().map(|(e, _)| e.clone()).collect();
    let mut cands: Vec<Cand> = Vec::new();
    by_number(&events, sp, true, &mut cands);
    by_beam(&events, &mut cands);
    by_shape(&events, seen, true, &mut cands);
    by_run(&events, true, &mut cands);
    let numbers = loose_numbers(&events, sp, false).len();
    let voiced = |evs: Vec<Ev>, _: bool| {
        let total: Q = evs.iter().map(|e| e.takes()).sum();
        (total == bar.len).then(|| vec![evs])
    };
    let (evs, _) = one_reading(
        &events,
        &cands,
        numbers,
        beside,
        bar,
        (false, !whole),
        &voiced,
    )?;
    Some(evs.into_iter().zip(all.iter().map(|p| p.1)).collect())
}

/// One bar's staves: each that does not add up is read again with its tuplets found against
/// the columns of the staves that are read, a staff so read then standing for the next; then
/// each that adds up but stands against the columns (six eighths in 3/4 that are two triplets
/// and hidden rests); then a part's two staves that still do not, as one voice passing between
/// them.
pub fn unnumbered_in_bar(
    events: &mut [Vec<Ev>],
    voices: &mut [Result<Vec<Vec<Ev>>, String>],
    bar: &Bar,
) {
    let sp = bar.sp;
    // (a staff in a time of its own has another bar's length: no tuplets make it up)
    let open = |voices: &[Result<Vec<Vec<Ev>>, String>], i: usize| {
        voices[i].is_err() && bar.own_time[i].is_none()
    };
    loop {
        let mut read = false;
        for i in 0..voices.len() {
            if !open(voices, i) {
                continue;
            }
            let beside = Beside::new(voices, &[i], i, sp);
            if let Some((evs, vs)) = unnumbered(&events[i], &bar.seen[i], &beside, bar) {
                events[i] = evs;
                voices[i] = Ok(vs);
                read = true;
            }
        }
        if !read {
            break;
        }
    }
    let all: Vec<Option<Vec<Vec<Ev>>>> = voices.iter().map(|v| v.as_ref().ok().cloned()).collect();
    let against = misread(&all, sp);
    for i in 0..voices.len() {
        if !against[i] || voices[i].is_err() || bar.own_time[i].is_some() {
            continue;
        }
        let beside = Beside::new(voices, &[i], i, sp);
        if let Some((evs, vs)) = unnumbered(&events[i], &bar.seen[i], &beside, bar) {
            events[i] = evs;
            voices[i] = Ok(vs);
        }
    }
    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
    let number = |n: &str| n.split('.').nth(1).and_then(|k| k.parse::<u8>().ok());
    for i in 0..voices.len().saturating_sub(1) {
        let j = i + 1;
        if part(&bar.names[i]) != part(&bar.names[j])
            || bar.own_time[i].or(bar.own_time[j]).is_some()
        {
            continue;
        }
        let (Some(ni), Some(nj)) = (number(&bar.names[i]), number(&bar.names[j])) else {
            continue;
        };
        // its home is the staff with more of its notes (the upper where they have as many)
        let notes = |k: usize| events[k].iter().filter(|e| timed(e) && e.is_note()).count();
        let (home, away, away_no) = if notes(i) >= notes(j) {
            (i, j, nj)
        } else {
            (j, i, ni)
        };
        let seen: Vec<Ev> = bar.seen[i].iter().chain(&bar.seen[j]).cloned().collect();
        let beside = Beside::new(voices, &[i, j], home, sp);
        // neither adds up alone; or one does not, and the other as read does not stand in the
        // columns of the staves outside the part (its eighths, read plain, are the triplets'
        // other notes)
        let misread = |k: usize| {
            voices[k].as_ref().is_ok_and(|vs| {
                columns::contradict(&columns::columns(&columns::marks(vs)), &beside.marks, sp)
            })
        };
        let unread = [i, j].iter().filter(|&&k| voices[k].is_err()).count();
        if unread == 0 || ![i, j].iter().all(|&k| voices[k].is_err() || misread(k)) {
            continue;
        }
        let Some(voice) = across(&events[i], &events[j], &seen, &beside, bar, unread < 2) else {
            continue;
        };
        let voice: Vec<Ev> = voice
            .into_iter()
            .map(|(mut e, second)| {
                if second == (away == j) && e.is_note() {
                    e.on_staff = Some(away_no);
                }
                e
            })
            .collect();
        let blank = Ev::spacer(bar.len, voice[0].x);
        events[home] = voice.clone();
        events[away] = vec![blank.clone()];
        voices[home] = Ok(vec![voice]);
        voices[away] = Ok(vec![vec![blank]]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::page::{Glyph, VLine};

    /// A note at `x` (staff spaces of 1), stemmed up or down, its head on the staff at 20.
    fn note(x: f64, dur: Q, up: bool) -> Ev {
        let g = Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y: 22.0,
            size: 1.0,
        };
        let stem = VLine {
            x: if up { x + 1.2 } else { x },
            y0: if up { 18.5 } else { 22.0 },
            y1: if up { 22.0 } else { 25.5 },
            w: 0.1,
        };
        let mut e = Ev::new(vec![g], Some(stem), Some(up));
        e.dur = dur;
        e
    }

    fn rest(x: f64, dur: Q) -> Ev {
        let g = Glyph {
            code: 0xE4E6,
            x0: x,
            x1: x + 1.0,
            y: 22.0,
            size: 1.0,
        };
        let mut e = Ev::new(Vec::new(), None, None);
        e.rest = Rest::Printed(g);
        e.dur = dur;
        e.x = x;
        e
    }

    fn beamed_at(xs: &[f64], dur: Q, beam: usize) -> Vec<Ev> {
        xs.iter()
            .map(|&x| {
                let mut e = note(x, dur, true);
                e.beam_polys.insert(beam);
                e
            })
            .collect()
    }

    #[test]
    fn some_of_a_tuplet_shared_with_the_other_staff_is_no_shape() {
        let (e, third) = (Q::new(1, 2), Q::new(1, 3));
        // two beamed eighths of a triplet whose third note is on the part's other staff
        let mut two = beamed_at(&[0.0, 3.0], third, 1);
        for n in two.iter_mut() {
            n.tuplets = vec![(3, 2, 5)];
        }
        assert!(shapes(&two).is_empty());
        // all three here: a shape
        let mut three = beamed_at(&[0.0, 3.0, 6.0], third, 1);
        for n in three.iter_mut() {
            n.tuplets = vec![(3, 2, 5)];
        }
        assert_eq!(shapes(&three).len(), 1);
        assert_eq!(shapes(&three)[0].2[0], (e, true));
    }

    #[test]
    fn a_number_over_another_voice_s_tuplet_may_be_this_voice_s() {
        let third = Q::new(1, 3);
        // three beamed eighths, stems down, in the triplet their own 3 made; over them a
        // quarter and an eighth, stems up, under a bare 3 of their own
        let mut evs = vec![note(10.0, Q::ONE, true), note(16.0, half(), true)];
        for x in [10.0, 13.0, 16.0] {
            let mut e = note(x, third, false);
            e.tuplets = vec![(3, 2, 77)];
            e.beam_polys.insert(1);
            evs.push(e);
        }
        evs[0].loose.push((3, 2, 13.6, true));
        // it grouped nothing and stands over a tuplet that has its number: no reading has to
        // give it notes, but the quarter and the eighth may be its
        assert!(loose_numbers(&evs, 1.0, false).is_empty());
        assert_eq!(spare_numbers(&evs, 1.0).len(), 1);
        let mut cands = Vec::new();
        by_number(&evs, 1.0, false, &mut cands);
        assert_eq!(cands.len(), 1);
        assert_eq!(cands[0].members, vec![0, 1]);
        assert_eq!((cands[0].ratio, cands[0].number), ((3, 2), None));
        // (not for a part's two staves read as one voice)
        let mut cands = Vec::new();
        by_number(&evs, 1.0, true, &mut cands);
        assert!(cands.is_empty());
    }

    #[test]
    fn a_beam_s_tuplet_is_taken_before_one_set_as_an_unbeamed_tuplet_was() {
        let third = Q::new(1, 3);
        // earlier on the staff: a quarter and an eighth under a 3, no beam
        let mut before = vec![note(1.0, Q::new(2, 3), true), note(5.0, third, true)];
        for e in before.iter_mut() {
            e.tuplets = vec![(3, 2, 50)];
        }
        // a bar of two and a half quarters: three beamed eighths, a quarter and an eighth.
        // Either the beam's three are a triplet or the quarter and the eighth are, as before:
        // the beam shows its own
        let mut evs = beamed_at(&[1.0, 4.0, 7.0], half(), 0);
        evs.extend([note(10.0, Q::ONE, true), note(14.0, half(), true)]);
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        let mut b = bar(&n, &seen, 2);
        b.len = Q::new(5, 2);
        let (read, _) = unnumbered(&evs, &before, &alone(3), &b).unwrap();
        assert!(read[..3].iter().all(|e| e.dur == third));
        assert!(read[3..].iter().all(|e| e.tuplets.is_empty()));
        // with no beam on the three, the bar's two readings stand alike: none is taken
        let mut loose = evs.clone();
        for e in loose.iter_mut() {
            e.beam_polys.clear();
        }
        let mut two = vec![note(1.0, Q::new(2, 3), true), note(5.0, third, true)];
        two.extend([10.0, 13.0, 16.0].map(|x| note(x, third, true)));
        for (k, e) in two.iter_mut().enumerate() {
            e.tuplets = vec![(3, 2, if k < 2 { 50 } else { 51 })];
        }
        assert!(unnumbered(&loose, &two, &alone(3), &b).is_none());
    }

    fn names() -> Vec<String> {
        ["V", "P.1", "P.2"].iter().map(|s| s.to_string()).collect()
    }

    /// A bar of `len` quarters ending at x 30, of a voice and a piano.
    fn bar<'a>(names: &'a [String], seen: &'a [Vec<Ev>], len: i64) -> Bar<'a> {
        Bar {
            names,
            own_time: &[None, None, None],
            seen,
            sp: 1.0,
            len: Q::int(len),
            right: Some(30.0),
            short: false,
        }
    }

    fn alone(voices: usize) -> Beside {
        Beside {
            staves: vec![None; voices],
            home: 0,
            marks: Vec::new(),
        }
    }

    /// Another staff's notes: (x, start) of each.
    fn beside(marks: &[(f64, Q)]) -> Beside {
        Beside {
            staves: vec![None; 3],
            home: 0,
            marks: marks
                .iter()
                .map(|&(x, at)| Mark {
                    x,
                    at,
                    play: 0.0,
                    wide: false,
                    sign: false,
                })
                .collect(),
        }
    }

    fn half() -> Q {
        Q::new(1, 2)
    }

    #[test]
    fn three_eighths_on_one_beam_that_fill_the_bar_as_a_triplet_are_one() {
        // 2/4: a quarter, then three eighths under one beam
        let mut evs = vec![note(1.0, Q::ONE, true)];
        evs.extend(beamed_at(&[10.0, 13.0, 16.0], half(), 0));
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        let (read, voices) = unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 2)).unwrap();
        assert_eq!(voices.len(), 1);
        assert_eq!(read[0].dur, Q::ONE);
        assert!(read[1..].iter().all(|e| e.dur == Q::new(1, 3)));
        assert!(read[1..]
            .iter()
            .all(|e| e.tuplets.len() == 1 && e.tuplets[0].0 == 3));
        // two such beams, of which the bar needs only one: it is not told which
        let mut two = beamed_at(&[1.0, 4.0, 7.0], half(), 0);
        two.push(note(10.0, half(), true));
        two.extend(beamed_at(&[14.0, 17.0, 20.0], half(), 1));
        assert!(unnumbered(&two, &[], &alone(3), &bar(&n, &seen, 3)).is_none());
    }

    #[test]
    fn a_bare_number_takes_the_notes_it_stands_over_the_middle_of() {
        // 3/4: a quarter, then an eighth rest and two beamed eighths with a 3 over the first of
        // the two (no bracket), then a quarter
        let mut evs = vec![note(1.0, Q::ONE, true), rest(8.0, half())];
        evs.extend(beamed_at(&[11.0, 14.0], half(), 0));
        evs.push(note(20.0, Q::ONE, true));
        evs[2].loose.push((3, 2, 11.6, true));
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        let (read, _) = unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 3)).unwrap();
        assert!(read[1..4].iter().all(|e| e.dur == Q::new(1, 3)));
        assert_eq!(read[1].tuplets[0].2, read[3].tuplets[0].2);
        // a number in the bar that finds no notes: nothing is read
        let mut stray = evs.clone();
        stray[4].loose.push((3, 2, 25.0, true));
        assert!(unnumbered(&stray, &[], &alone(3), &bar(&n, &seen, 3)).is_none());
    }

    #[test]
    fn a_number_at_one_note_with_strokes_across_its_stem_is_its_tuplet() {
        // 2/4: two dotted quarters, each with a stroke across its stem and a 3 at it: triplets
        // of eighths written short, a quarter each
        let dotted = Q::new(3, 2);
        let mut evs = vec![note(1.0, dotted, false), note(12.0, dotted, false)];
        for e in &mut evs {
            e.tremolo = Some(crate::staff::Trem::Single(1));
            e.loose.push((3, 2, e.x + 0.6, true));
        }
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        let (read, voices) = unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 2)).unwrap();
        assert_eq!(voices.len(), 1);
        assert!(read.iter().all(|e| e.dur == Q::ONE && e.tuplets.len() == 1));
        assert_ne!(read[0].tuplets[0].2, read[1].tuplets[0].2);
        // a number at a plain note groups nothing
        let mut plain = evs.clone();
        plain[0].tremolo = None;
        assert!(unnumbered(&plain, &[], &alone(3), &bar(&n, &seen, 2)).is_none());
    }

    #[test]
    fn a_run_set_as_a_tuplet_marked_before_is_one_again() {
        // a triplet marked before: a flagged eighth and two beamed; in 2/4 the same again,
        // unmarked, after a quarter ("simile")
        let mut marked = vec![note(0.0, half(), true)];
        marked.extend(beamed_at(&[3.0, 6.0], half(), 7));
        for e in &mut marked {
            e.tuplets.push((3, 2, 9999));
            e.dur = Q::new(1, 3);
        }
        let mut evs = vec![note(1.0, Q::ONE, true), note(10.0, half(), true)];
        evs.extend(beamed_at(&[13.0, 16.0], half(), 0));
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        assert!(unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 2)).is_none());
        let (read, _) = unnumbered(&evs, &marked, &alone(3), &bar(&n, &seen, 2)).unwrap();
        assert!(read[1..].iter().all(|e| e.dur == Q::new(1, 3)));
    }

    #[test]
    fn flagged_eighths_are_a_triplet_where_another_staff_shows_their_beat() {
        // 3/4, a voice's eight flagged eighths... seven: three of them are a triplet; which, the
        // piano's quarters say (its second stands under the fourth eighth)
        let evs: Vec<Ev> = [1.0, 4.0, 7.0, 10.0, 15.0, 20.0, 25.0]
            .iter()
            .map(|&x| note(x, half(), false))
            .collect();
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        // with nothing beside it, nothing says which three
        assert!(unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 3)).is_none());
        let piano = beside(&[(1.0, Q::ZERO), (10.0, Q::ONE), (20.0, Q::int(2))]);
        let (read, _) = unnumbered(&evs, &[], &piano, &bar(&n, &seen, 3)).unwrap();
        assert!(read[..3].iter().all(|e| e.dur == Q::new(1, 3)));
        assert!(read[3..].iter().all(|e| e.dur == half()));
    }

    #[test]
    fn nine_sixteenths_on_a_beam_are_three_triplets_where_the_bar_says_so() {
        // 3/4: an eighth rest, six sixteenths on a beam and nine on another: fifteen triplet
        // sixteenths (nine in the time of eight would overfill the bar)
        let q = Q::new(1, 4);
        let mut evs = vec![rest(1.0, half())];
        evs.extend(beamed_at(&[3.0, 4.0, 5.0, 6.0, 7.0, 8.0], q, 0));
        let xs: Vec<f64> = (0..9).map(|k| 10.0 + k as f64).collect();
        evs.extend(beamed_at(&xs, q, 1));
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        let (read, voices) = unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 3)).unwrap();
        assert_eq!(voices.len(), 1);
        assert!(read[1..].iter().all(|e| e.dur == Q::new(1, 6)));
        let groups: std::collections::BTreeSet<usize> =
            read[7..].iter().map(|e| e.tuplets[0].2).collect();
        assert_eq!(groups.len(), 3);
    }

    #[test]
    fn a_tuplet_and_hidden_rests_are_read_only_where_the_columns_show_both() {
        // 3/4: an eighth rest and two beamed eighths under a bare 3, twice, the second at the
        // third beat: two triplets with a beat between them that the program hid. As printed
        // the six eighths fill the bar, and the other staves stand against that reading.
        let mut evs = vec![rest(1.0, half())];
        evs.extend(beamed_at(&[3.5, 6.0], half(), 0));
        evs.push(rest(17.0, half()));
        evs.extend(beamed_at(&[19.5, 22.0], half(), 1));
        evs[1].loose.push((3, 2, 4.1, true));
        evs[4].loose.push((3, 2, 20.1, true));
        let (n, seen) = (names(), vec![Vec::new(); 3]);
        assert!(unnumbered(&evs, &[], &alone(3), &bar(&n, &seen, 3)).is_none());
        // another staff's quarters at 1, 9 and 17
        let mut other = beside(&[(1.0, Q::ZERO), (9.0, Q::ONE), (17.0, Q::int(2))]);
        other.staves[2] = Some(Vec::new());
        other.home = 1;
        let (_, voices) = unnumbered(&evs, &[], &other, &bar(&n, &seen, 3)).unwrap();
        let lasts: Vec<Q> = voices[0].iter().map(|e| e.takes()).collect();
        let t = Q::new(1, 3);
        assert_eq!(lasts, [t, t, t, Q::ONE, t, t, t]);
        assert_eq!(voices[0][3].rest, Rest::Blank);
        // the part's other staff unread: a voice may pass between the two, and nothing is read
        other.staves[2] = None;
        assert!(unnumbered(&evs, &[], &other, &bar(&n, &seen, 3)).is_none());
    }

    #[test]
    fn a_voice_passing_between_a_part_s_staves_in_triplets_is_one_voice() {
        // 2/4, a piano: each staff has three eighths (a beamed pair and one flagged) that do not
        // fill its bar; together, in the order they stand, they are two triplets, each with its
        // bare 3
        let mut upper = vec![note(9.0, half(), true)];
        upper.extend(beamed_at(&[15.0, 19.0], half(), 0));
        let mut lower = beamed_at(&[1.0, 5.0], half(), 1);
        lower.push(note(23.0, half(), false));
        lower[1].loose.push((3, 2, 5.6, false));
        upper[1].loose.push((3, 2, 19.6, true));
        let n = names();
        let seen = vec![Vec::new(); 3];
        let b = bar(&n, &seen, 2);
        let mut events = vec![vec![rest(12.0, Q::int(2))], upper, lower];
        events[0][0].rest = Rest::Bar;
        let mut voices: Vec<Result<Vec<Vec<Ev>>, String>> = vec![
            Ok(vec![events[0].clone()]),
            Err("a bar whose notes do not add up to the time".into()),
            Err("a bar whose notes do not add up to the time".into()),
        ];
        unnumbered_in_bar(&mut events, &mut voices, &b);
        let home = voices[1].as_ref().unwrap();
        assert_eq!(home.len(), 1);
        assert_eq!(home[0].len(), 6);
        assert!(home[0].iter().all(|e| e.dur == Q::new(1, 3)));
        // the lower staff's notes are drawn there, and its own bar is blank
        let drawn: Vec<Option<u8>> = home[0].iter().map(|e| e.on_staff).collect();
        assert_eq!(drawn, [Some(2), Some(2), None, None, None, Some(2)]);
        let away = voices[2].as_ref().unwrap();
        assert_eq!(away[0].len(), 1);
        assert_eq!(away[0][0].rest, Rest::Blank);
        assert_eq!(away[0][0].dur, Q::int(2));
    }

    #[test]
    fn a_staff_in_a_time_of_its_own_is_given_no_tuplets() {
        // six beamed eighths in a bar of 2/4: a piano in 6/8 under a voice in 2/4, not triplets
        let mut six = beamed_at(&[1.0, 4.0, 7.0], half(), 0);
        six.extend(beamed_at(&[10.0, 13.0, 16.0], half(), 1));
        let n = names();
        let seen = vec![Vec::new(); 3];
        let mut b = bar(&n, &seen, 2);
        let mut events = vec![Vec::new(), six, Vec::new()];
        let unread = || Err("a bar whose notes do not add up to the time".to_string());
        let mut voices = vec![Ok(Vec::new()), unread(), Ok(Vec::new())];
        let own = [None, Some((6, 8)), Some((6, 8))];
        b.own_time = &own;
        unnumbered_in_bar(&mut events, &mut voices, &b);
        assert!(voices[1].is_err());
        b.own_time = &[None, None, None];
        unnumbered_in_bar(&mut events, &mut voices, &b);
        assert!(voices[1].is_ok());
    }
}