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
//! Tuplets of a line that passes between a part's two staves: a triplet whose first eighth is a
//! rest on the upper staff and whose other two are beamed on the lower, an arpeggio in triplets
//! a hand to each note, a run of eleven under one number that starts in the left hand and ends
//! in the right. Neither staff has the tuplet's notes, so neither shows it alone (`tuplets.rs`
//! reads a staff at a time), and with the lengths printed no line fills the bar (`passing.rs`).
//! Here the groups that may be such tuplets are found over both staves, on evidence (three
//! notes on one beam; a number over a run of as many notes; two on a beam and one note or rest
//! of their value next to them), and the pair is read with some of them taken, each staff
//! alone or with a line passing between the two ([`passing::line_between`]): where one reading
//! alone fills the bar, it is the bar's. A number the reader gave to notes of both staves
//! that it is not over (it stands between the staves, by a beam that crosses) is taken back
//! first where the bar does not read with it.

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

/// A group that may be a tuplet: its notes and rests (staff of the pair, place among the
/// staff's events), whether something printed shows it (a beam of three, a number over it) or
/// only the bar's adding up can, and the number it is under (its middle).
#[derive(Clone, Debug, PartialEq)]
struct Group {
    members: Vec<(usize, usize)>,
    ratio: (u32, u32),
    shown: bool,
    number: Option<f64>,
}

/// A tuplet the reader had made that was taken back: its ratio and where its notes stood.
#[derive(Clone, Copy, Debug)]
struct Was {
    ratio: (u32, u32),
    lo: f64,
    hi: f64,
}

/// More groups than this are not tried one by one.
const MOST: usize = 10;

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

fn beamed(a: &Ev, b: &Ev) -> bool {
    a.is_note() && b.is_note() && !a.beam_polys.is_disjoint(&b.beam_polys)
}

/// Each beam's notes, left to right (a staff's events; a beam between the staves is held by
/// one of them).
fn beams(evs: &[Ev]) -> Vec<Vec<usize>> {
    let mut out: Vec<Vec<usize>> = Vec::new();
    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;
        }
        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);
        out.push(group);
    }
    out
}

/// The numbers of both staves that grouped nothing: each one's ratio and middle.
fn numbers(pair: &[Vec<Ev>; 2], sp: f64) -> Vec<(u32, u32, f64)> {
    let mut out: Vec<(u32, u32, f64)> = Vec::new();
    for n in pair.iter().flatten().flat_map(|e| e.loose.iter()) {
        if !out
            .iter()
            .any(|o| o.0 == n.0 && (o.2 - n.2).abs() < 0.5 * sp)
        {
            out.push((n.0, n.1, n.2));
        }
    }
    out
}

/// The groups of a part's two staves that may be tuplets.
///
/// Of a beam's notes of one value: three (shown by the beam), six or nine in threes, and six
/// as one group of six under a 6; two or five with one more note or rest of their value (not
/// on a beam; on either staff) standing next to them as far as they stand apart, in threes.
/// Under a number that grouped nothing, the run of as many notes of one value over both staves
/// that it stands over. A group is shown where its number stands over it, or the reader had
/// given a number to its notes among others (`was`).
fn groups(pair: &[Vec<Ev>; 2], was: &[Was], sp: f64) -> Vec<Group> {
    let mut out: Vec<Group> = Vec::new();
    let loose = numbers(pair, sp);
    let ev = |m: &(usize, usize)| &pair[m.0][m.1];
    let span = |ms: &[(usize, usize)]| {
        let xs = ms.iter().map(|m| ev(m).x);
        xs.fold((f64::MAX, f64::MIN), |a, x| (a.0.min(x), a.1.max(x)))
    };
    // the number a group of `count` is under, or that it had
    let number_over = |ms: &[(usize, usize)], count: u32| -> (Option<(u32, u32)>, Option<f64>) {
        let (lo, hi) = span(ms);
        let mid = (lo + hi) / 2.0 + 0.6 * sp;
        let n = loose
            .iter()
            .find(|n| n.0 == count && (n.2 - mid).abs() < 1.0 * sp);
        if let Some(n) = n {
            return (Some((n.0, n.1)), Some(n.2));
        }
        let had = was
            .iter()
            .find(|w| w.ratio.0 == count && w.lo - 0.5 * sp <= lo && hi <= w.hi + 0.5 * sp);
        (had.map(|w| w.ratio), None)
    };
    let push = |g: Group, out: &mut Vec<Group>| {
        if !out
            .iter()
            .any(|o| o.members == g.members && o.ratio == g.ratio)
        {
            out.push(g);
        }
    };
    for s in 0..2 {
        let evs = &pair[s];
        // (of a beam some of whose notes are in a tuplet, the others that follow one another)
        let mut runs_of: Vec<(Vec<usize>, bool)> = Vec::new();
        for beam in beams(evs) {
            let whole = beam.iter().all(|&i| free(&evs[i]));
            let mut run: Vec<usize> = Vec::new();
            for &i in &beam {
                match free(&evs[i]) {
                    true => run.push(i),
                    false => runs_of.push((std::mem::take(&mut run), whole)),
                }
            }
            runs_of.push((run, whole));
        }
        for (beam, whole) in runs_of.into_iter().filter(|r| !r.0.is_empty()) {
            let d = evs[beam[0]].dur;
            let n = beam.len();
            if !beam.iter().all(|&i| evs[i].dur == d) || d > Q::new(1, 2) || !(2..=12).contains(&n)
            {
                continue;
            }
            let on_beam: Vec<(usize, usize)> = beam.iter().map(|&i| (s, i)).collect();
            let (a, b) = span(&on_beam);
            let gap = (b - a) / (n - 1) as f64;
            let mut runs: Vec<Vec<(usize, usize)>> = Vec::new();
            if n % 3 == 0 {
                runs.push(on_beam.clone());
            }
            if n % 3 == 2 {
                for t in 0..2 {
                    for (k, e) in pair[t].iter().enumerate() {
                        let alone = !e.is_note() || e.beam_polys.is_empty();
                        if !free(e) || e.dur != d || !alone {
                            continue;
                        }
                        // before the beam's notes, after them, or a rest between two of them
                        let before = e.x < a - 0.4 * sp && e.x > a - 2.5 * gap;
                        let after = e.x > b + 0.4 * sp && e.x < b + 2.5 * gap;
                        let between =
                            n == 2 && !e.is_note() && e.x > a + 0.4 * sp && e.x < b - 0.4 * sp;
                        if before || after || between {
                            let mut run = on_beam.clone();
                            run.push((t, k));
                            run.sort_by(|p, q| ev(p).x.total_cmp(&ev(q).x));
                            runs.push(run);
                        }
                    }
                }
            }
            for run in runs {
                if run.len() == 6 && n == 6 {
                    if let (Some(ratio), number) = number_over(&run, 6) {
                        let g = Group {
                            members: run.clone(),
                            ratio,
                            shown: true,
                            number,
                        };
                        push(g, &mut out);
                    }
                }
                for three in run.chunks(3) {
                    let (ratio, number) = number_over(three, 3);
                    let g = Group {
                        members: three.to_vec(),
                        ratio: ratio.unwrap_or((3, 2)),
                        shown: (n == 3 && whole) || ratio.is_some(),
                        number,
                    };
                    push(g, &mut out);
                }
            }
        }
    }
    // a number over a run that passes between the staves
    let mut all: Vec<(usize, usize)> = (0..2)
        .flat_map(|s| (0..pair[s].len()).map(move |i| (s, i)))
        .filter(|m| free(ev(m)) && ev(m).is_note() && ev(m).dur <= Q::new(1, 2))
        .collect();
    all.sort_by(|p, q| ev(p).x.total_cmp(&ev(q).x));
    for &(a, n, cx) in &loose {
        // (three under a 3 with no beam between the staves are `tuplets::across`'s)
        if a < 5 || a.is_power_of_two() {
            continue;
        }
        let mut best: Option<(f64, Vec<(usize, usize)>)> = None;
        let mut durs: Vec<Q> = all.iter().map(|m| ev(m).dur).collect();
        durs.sort();
        durs.dedup();
        for d in durs {
            let of: Vec<(usize, usize)> = all.iter().copied().filter(|m| ev(m).dur == d).collect();
            for w in of.windows(a as usize) {
                let (lo, hi) = span(w);
                let one = w.windows(2).all(|p| ev(&p[1]).x - ev(&p[0]).x > 0.3 * sp);
                let both = w.iter().any(|m| m.0 != w[0].0);
                let off = ((lo + hi) / 2.0 + 0.6 * sp - cx).abs();
                let under = lo - 0.5 * sp <= cx && cx <= hi + 1.7 * sp;
                if one && both && under && best.as_ref().is_none_or(|b| off < b.0) {
                    best = Some((off, w.to_vec()));
                }
            }
        }
        if let Some((_, members)) = best {
            let g = Group {
                members,
                ratio: (a, n),
                shown: true,
                number: Some(cx),
            };
            push(g, &mut out);
        }
    }
    out
}

/// The pair's events with the groups taken as tuplets (a number so given its notes is no
/// longer one that grouped nothing), and each tuplet's number.
fn taken(pair: &[Vec<Ev>; 2], groups: &[&Group], sp: f64) -> ([Vec<Ev>; 2], Vec<usize>) {
    let mut evs = pair.clone();
    let mut ids = Vec::new();
    for g in groups {
        let id = next_group();
        ids.push(id);
        for &(s, i) in &g.members {
            let e = &mut evs[s][i];
            e.tuplets.push((g.ratio.0, g.ratio.1, id));
            e.dur = e.dur * Q::new(g.ratio.1 as i64, g.ratio.0 as i64);
        }
        if let Some(cx) = g.number {
            for e in evs.iter_mut().flatten() {
                e.loose
                    .retain(|n| n.0 != g.ratio.0 || (n.2 - cx).abs() >= 0.5 * sp);
            }
        }
    }
    (evs, ids)
}

/// The pair's events with the tuplets taken back that hold notes or rests of both staves' bars
/// (a number between the staves, given to this staff's quarter and rest and to the notes of a
/// beam that crosses from the other): the lengths as printed again, and what was taken back. `None` where there is none such, or tuplets stand inside tuplets.
fn taken_back(pair: &[Vec<Ev>; 2]) -> Option<([Vec<Ev>; 2], Vec<Was>)> {
    if pair.iter().flatten().any(|e| e.tuplets.len() > 1) {
        return None;
    }
    let mut ids: Vec<usize> = pair
        .iter()
        .flatten()
        .filter_map(|e| e.tuplets.first().map(|t| t.2))
        .collect();
    ids.sort();
    ids.dedup();
    let of = |e: &Ev, id: usize| e.tuplets.first().is_some_and(|t| t.2 == id);
    let mut evs = pair.clone();
    let mut was: Vec<Was> = Vec::new();
    for id in ids {
        let on = |s: usize| pair[s].iter().any(|e| of(e, id));
        if !(on(0) && on(1)) {
            continue;
        }
        let members = pair.iter().flatten().filter(|e| of(e, id));
        let ratio = members.clone().next().map(|e| e.tuplets[0])?;
        let (lo, hi) = members
            .map(|e| e.x)
            .fold((f64::MAX, f64::MIN), |a, x| (a.0.min(x), a.1.max(x)));
        was.push(Was {
            ratio: (ratio.0, ratio.1),
            lo,
            hi,
        });
        for e in evs.iter_mut().flatten().filter(|e| of(e, id)) {
            e.dur = e.written();
            e.tuplets.clear();
        }
    }
    if was.is_empty() {
        return None;
    }
    // the blank time a note left on its own staff, as long as the note is again
    for s in 0..2 {
        let moved: Vec<(f64, Q)> = evs[1 - s]
            .iter()
            .filter(|e| e.is_note() && e.on_staff.is_some())
            .map(|e| (e.x, e.dur))
            .collect();
        for e in evs[s].iter_mut().filter(|e| e.rest == Rest::Blank) {
            if let Some(m) = moved.iter().find(|m| m.0 == e.x) {
                e.dur = m.1;
            }
        }
    }
    Some((evs, was))
}

/// One bar of a part's two staves, for [`read_pair`].
pub struct Two<'a> {
    pub events: [&'a [Ev]; 2],
    /// Each staff's voices where it reads alone.
    pub read: [Option<&'a [Vec<Ev>]>; 2],
    /// The columns of the bar's other staves as read.
    pub others: &'a [Mark],
    pub sp: f64,
    pub len: Q,
    pub right: Option<f64>,
    /// No time may be made up beside the tuplets' line: the bar may be a short one (a
    /// pickup), which only a reading that fills it with what is printed shows to be whole.
    pub strict: bool,
}

/// When each note starts, how long it lasts and where it stands: what tells two readings apart.
fn signature(voices: &[Vec<Vec<Ev>>; 2]) -> Vec<(usize, Q, Q, i32)> {
    let mut sig = Vec::new();
    for (s, vs) in voices.iter().enumerate() {
        for v in vs {
            let mut t = Q::ZERO;
            for e in v {
                if e.is_note() {
                    sig.push((s, t, e.takes(), e.places.first().copied().unwrap_or(0)));
                }
                t += e.takes();
            }
        }
    }
    sig.sort();
    sig
}

/// A pair as read: each staff's events with the tuplets taken, and its voices.
pub type Read = ([Vec<Ev>; 2], [Vec<Vec<Ev>>; 2]);

/// The groups taken for one reading, and the tuplets made of them.
struct Pick<'a> {
    groups: &'a [&'a Group],
    ids: &'a [usize],
}

/// Whether a staff's bar has a note or rest of the tuplets taken, or the blank time one of
/// their notes left on it (a note beamed with the other staff's and held by its bar): its
/// reading before them no longer stands.
fn touched(evs: &[Vec<Ev>; 2], pick: &Pick, s: usize) -> bool {
    let of = |e: &Ev| e.tuplets.iter().any(|t| pick.ids.contains(&t.2));
    evs[s].iter().any(of)
        || evs[1 - s].iter().any(|m| {
            of(m)
                && m.on_staff.is_some()
                && evs[s].iter().any(|e| e.rest == Rest::Blank && e.x == m.x)
        })
}

/// Each staff read alone with the tuplets taken, every one of them a staff's own: voices that
/// fill the bar with what is printed and stand in the columns. No time is made up in a voice
/// with one of the tuplets; nor in any, where nothing printed shows one of them.
fn each_alone(two: &Two, evs: &[Vec<Ev>; 2], pick: &Pick) -> Option<[Vec<Vec<Ev>>; 2]> {
    let sp = two.sp;
    let across = |g: &&Group| g.members.iter().any(|m| m.0 != g.members[0].0);
    if pick.groups.iter().any(across) {
        return None;
    }
    let unshown = two.strict || pick.groups.iter().any(|g| !g.shown);
    let blank = |e: &Ev| e.rest == Rest::Blank;
    let made_up = |v: &Vec<Ev>| {
        v.iter().any(blank)
            && (unshown || (v.iter()).any(|e| e.tuplets.iter().any(|t| pick.ids.contains(&t.2))))
    };
    let mut out: [Vec<Vec<Ev>>; 2] = [Vec::new(), Vec::new()];
    for s in 0..2 {
        let touched = touched(evs, pick, s);
        out[s] = match (two.read[s], touched) {
            (Some(r), false) => r.to_vec(),
            _ => {
                // (the blank time a note beamed with the other staff's left is not this
                // staff's voices')
                let own: Vec<Ev> = evs[s].iter().filter(|e| !blank(e)).cloned().collect();
                voices_of(own, sp, two.len, two.right, false)
                    .ok()
                    .filter(|vs| !vs.iter().any(made_up))?
            }
        };
    }
    let marks: [Vec<Mark>; 2] = [0, 1].map(|s| columns::marks(&out[s]));
    let cols: [Vec<Mark>; 2] = [0, 1].map(|s| columns::columns(&marks[s]));
    let against = marks.iter().any(|m| columns::contradicts_itself(m, sp))
        || columns::contradict(&cols[0], &cols[1], sp)
        || cols.iter().any(|c| columns::contradict(c, two.others, sp));
    (!against).then_some(out)
}

/// The two staves with a line passing between them, the tuplets taken
/// ([`passing::line_between`]; a staff that read alone and has a tuplet now is read with the
/// line). With a tuplet nothing printed shows, only where no time is made up but for the
/// line's on the staff it has left: a voice with blank time is nothing but tuplets and blank.
fn with_a_line(two: &Two, evs: &[Vec<Ev>; 2], pick: &Pick) -> Option<[Vec<Vec<Ev>>; 2]> {
    let again: [Option<Vec<Vec<Ev>>>; 2] = [0, 1].map(|s| {
        let touched = touched(evs, pick, s);
        two.read[s].filter(|_| !touched).map(|r| r.to_vec())
    });
    if again.iter().all(|r| r.is_some()) {
        return None;
    }
    let p = Pair {
        events: [&evs[0], &evs[1]],
        read: [again[0].as_deref(), again[1].as_deref()],
        others: two.others,
        sp: two.sp,
        len: two.len,
        right: two.right,
    };
    let [a, b] = passing::line_between(&p)?;
    let [ra, rb] = again;
    let voices = [a.or(ra)?, b.or(rb)?];
    let unshown = two.strict || pick.groups.iter().any(|g| !g.shown);
    let made_up = |v: &Vec<Ev>| {
        v.iter().any(|e| e.rest == Rest::Blank)
            && (v.iter().any(|e| timed(e) && e.tuplets.is_empty()) || !v.iter().any(timed))
    };
    (!unshown || !voices.iter().flatten().any(made_up)).then_some(voices)
}

/// One reading of the pair with some of its groups taken: each staff alone with tuplets of its
/// own, or with a line passing between them. First with the groups that something printed
/// shows, then with those only the bar's adding up shows; and each staff alone before a line
/// between them; a number that stands over one of the groups is given its notes in every
/// reading. `None` where two readings differ.
fn one_reading(two: &Two, was: &[Was]) -> Option<Read> {
    let sp = two.sp;
    let pair: [Vec<Ev>; 2] = [two.events[0].to_vec(), two.events[1].to_vec()];
    let all = groups(&pair, was, sp);
    // (not with a tuplet of one note: a number given to a note it is not over)
    let lone = |e: &Ev| {
        e.tuplets.iter().any(|t| {
            let of = |o: &&Ev| o.tuplets.iter().any(|u| u.2 == t.2);
            pair.iter().flatten().filter(of).count() < 2
        })
    };
    if all.is_empty() || pair.iter().flatten().any(lone) {
        return None;
    }
    for (with_unshown, alone) in [(false, true), (false, false), (true, true), (true, false)] {
        let cands: Vec<&Group> = all.iter().filter(|g| g.shown || with_unshown).collect();
        if cands.is_empty() || cands.len() > 24 || (with_unshown && all.iter().all(|g| g.shown)) {
            continue;
        }
        let sets = if cands.len() <= MOST {
            1u32..(1 << cands.len())
        } else {
            (1 << cands.len()) - 1..(1 << cands.len())
        };
        type Found = (Vec<(usize, Q, Q, i32)>, [Vec<Ev>; 2], [Vec<Vec<Ev>>; 2]);
        let mut found: Vec<Found> = Vec::new();
        for set in sets {
            let pick: Vec<&Group> = (0..cands.len())
                .filter(|&k| set & (1 << k) != 0)
                .map(|k| cands[k])
                .collect();
            if with_unshown && pick.iter().all(|g| g.shown) {
                continue;
            }
            let overlap = pick.iter().enumerate().any(|(a, c)| {
                pick[..a].iter().any(|d| {
                    c.members.iter().any(|m| d.members.contains(m))
                        || (c.number.is_some() && c.number == d.number)
                })
            });
            // (a number that stands over a group is given its notes)
            let unused = all
                .iter()
                .filter_map(|g| g.number)
                .any(|n| !pick.iter().any(|g| g.number == Some(n)));
            if overlap || unused {
                continue;
            }
            let (evs, ids) = taken(&pair, &pick, sp);
            let pick = Pick {
                groups: &pick,
                ids: &ids,
            };
            let voices = match alone {
                true => each_alone(two, &evs, &pick),
                false => with_a_line(two, &evs, &pick),
            };
            let Some(voices) = voices else {
                continue;
            };
            let sig = signature(&voices);
            if !found.iter().any(|f| f.0 == sig) {
                found.push((sig, evs, voices));
            }
        }
        match found.len() {
            0 => continue,
            1 => return found.pop().map(|f| (f.1, f.2)),
            _ => return None,
        }
    }
    None
}

/// The two staves' events and voices with tuplets taken that neither staff shows alone, where
/// there is one such reading ([`one_reading`]): as the staves were read; else with the tuplets
/// taken back that the reader had made of both staves' notes ([`taken_back`]), the staves that
/// had them read anew.
pub fn read_pair(two: &Two) -> Option<Read> {
    if two.read.iter().all(|r| r.is_some()) {
        return None;
    }
    if let Some(read) = one_reading(two, &[]) {
        return Some(read);
    }
    let pair: [Vec<Ev>; 2] = [two.events[0].to_vec(), two.events[1].to_vec()];
    let (evs, was) = taken_back(&pair)?;
    let same = |s: usize| {
        evs[s].len() == pair[s].len()
            && evs[s]
                .iter()
                .zip(&pair[s])
                .all(|(a, b)| a.dur == b.dur && a.tuplets == b.tuplets)
    };
    let back = Two {
        events: [&evs[0], &evs[1]],
        read: [0, 1].map(|s| two.read[s].filter(|_| same(s))),
        others: two.others,
        sp: two.sp,
        len: two.len,
        right: two.right,
        strict: two.strict,
    };
    one_reading(&back, &was)
}

/// One bar's staves: each part's two staves of which one at least does not read are read with
/// the tuplets shared between them ([`read_pair`]); `strict` in a bar that may be short.
pub fn tuplets_between(
    events: &mut [Vec<Ev>],
    voices: &mut [Result<Vec<Vec<Ev>>, String>],
    names: &[String],
    sp: f64,
    lens: &[Q],
    (right, strict): (Option<f64>, bool),
) {
    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
    for i in 0..voices.len().saturating_sub(1) {
        let j = i + 1;
        if part(&names[i]) != part(&names[j]) || lens[i] != lens[j] {
            continue;
        }
        // both read, one of them as nothing but one printed rest shorter than the bar (held to
        // be its bar's rest, or filled out with blank time): the rest may be a tuplet's whose
        // other notes are on the other staff
        let alone = |k: usize| -> Vec<f64> {
            let printed: Vec<&Ev> = events[k].iter().filter(|e| timed(e)).collect();
            let resting = voices[k].as_ref().is_ok_and(|vs| {
                !vs.iter().flatten().any(|e| e.is_note())
                    && vs.iter().all(|v| {
                        v.iter().any(|e| e.rest == Rest::Blank)
                            || v.iter().map(|e| e.takes()).sum::<Q>() < lens[k]
                    })
            });
            match printed[..] {
                [e] if resting && !e.is_note() && e.dur < lens[k] => vec![e.x],
                _ => Vec::new(),
            }
        };
        let both = voices[i].is_ok() && voices[j].is_ok();
        let lone = [alone(i), alone(j)];
        if both && lone.iter().all(|l| l.is_empty()) {
            continue;
        }
        let len = lens[i];
        let others: Vec<Mark> = (0..voices.len())
            .filter(|&k| k != i && k != j && lens[k] == len)
            .filter_map(|k| voices[k].as_ref().ok())
            .flat_map(|vs| columns::columns(&columns::marks(vs)))
            .collect();
        let two = Two {
            events: [&events[i], &events[j]],
            read: match both {
                true => [None, None],
                false => [voices[i].as_deref().ok(), voices[j].as_deref().ok()],
            },
            others: &others,
            sp,
            len,
            right,
            strict,
        };
        let read = read_pair(&two).filter(|(evs, _)| {
            // (read again only for the rest: it is in a tuplet now)
            !both
                || (0..2).all(|s| {
                    lone[s].iter().all(|&x| {
                        evs[s]
                            .iter()
                            .any(|e| e.x == x && !e.is_note() && !e.tuplets.is_empty())
                    })
                })
        });
        if let Some(([a, b], [va, vb])) = read {
            events[i] = a;
            events[j] = b;
            voices[i] = Ok(va);
            voices[j] = Ok(vb);
        }
    }
}

/// A note beamed with the part's other staff's is held by that staff's bar, and its own
/// staff's bar holds blank time of its length where it stood. Where the note has since been
/// found to be in a tuplet, the blank time is as long as the note is now, and the staff is
/// read again (blank time of the lengths printed would be given to a voice as time it has not):
/// without the blank time where what else it has fills the bar (the notes are a voice of the
/// other staff's, that has all of it), else with it.
pub fn blanks_as_their_notes(
    events: &mut [Vec<Ev>],
    voices: &mut [Result<Vec<Vec<Ev>>, String>],
    names: &[String],
    sp: f64,
    lens: &[Q],
    right: Option<f64>,
    short: bool,
) {
    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 away in 0..events.len() {
        let mut changed = false;
        let mut left: Vec<f64> = Vec::new();
        for home in 0..events.len() {
            if home == away || part(&names[home]) != part(&names[away]) {
                continue;
            }
            let Some(no) = number(&names[away]) else {
                continue;
            };
            let moved: Vec<(f64, Q, bool)> = events[home]
                .iter()
                .filter(|e| e.is_note() && e.on_staff == Some(no))
                .map(|e| (e.x, e.dur, !e.tuplets.is_empty()))
                .collect();
            for e in events[away].iter_mut().filter(|e| e.rest == Rest::Blank) {
                if let Some(m) = moved.iter().find(|m| m.0 == e.x) {
                    left.push(e.x);
                    if m.2 && m.1 != e.dur {
                        e.dur = m.1;
                        changed = true;
                    }
                }
            }
        }
        if !changed {
            continue;
        }
        let own: Vec<Ev> = events[away]
            .iter()
            .filter(|e| e.rest != Rest::Blank || !left.contains(&e.x))
            .cloned()
            .collect();
        let alone = voices_of(own, sp, lens[away], right, short)
            .ok()
            .filter(|vs| !vs.iter().flatten().any(|e| e.rest == Rest::Blank));
        voices[away] = match alone {
            Some(vs) => Ok(vs),
            None => voices_of(events[away].clone(), sp, lens[away], right, short).map_err(|e| e.0),
        };
    }
}

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

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

    fn rest(x: f64, y: f64, dur: Q) -> Ev {
        let g = Glyph {
            code: 0xE4E6,
            x0: x,
            x1: x + 1.0,
            y,
            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 on_beam(mut evs: Vec<Ev>, beam: usize) -> Vec<Ev> {
        for e in evs.iter_mut() {
            e.beam_polys.insert(beam);
        }
        evs
    }

    fn two<'a>(a: &'a [Ev], b: &'a [Ev], len: i64) -> Two<'a> {
        Two {
            events: [a, b],
            read: [None, None],
            others: &[],
            sp: 1.0,
            len: Q::int(len),
            right: Some(40.0),
            strict: false,
        }
    }

    fn starts(v: &[Ev]) -> Vec<(Q, bool)> {
        let mut t = Q::ZERO;
        let mut out = Vec::new();
        for e in v {
            if e.rest != Rest::Blank {
                out.push((t, e.is_note()));
            }
            t += e.takes();
        }
        out
    }

    /// 2/4: an eighth rest on the upper staff; on the lower a half note, two beamed eighths
    /// and three beamed eighths.
    fn rest_above() -> (Vec<Ev>, Vec<Ev>) {
        let e = Q::new(1, 2);
        let upper = vec![rest(0.0, 10.0, e)];
        let mut lower = vec![note(0.0, 46.0, Q::int(2), false)];
        lower.extend(on_beam(
            vec![note(3.0, 40.0, e, true), note(6.0, 40.0, e, true)],
            1,
        ));
        let three = [9.0, 12.0, 15.0].map(|x| note(x, 40.0, e, true));
        lower.extend(on_beam(three.to_vec(), 2));
        (upper, lower)
    }

    #[test]
    fn a_rest_on_one_staff_and_two_beamed_notes_on_the_other_are_a_triplet() {
        let (upper, lower) = rest_above();
        let third = Q::new(1, 3);
        let pair = [upper.clone(), lower.clone()];
        let found = groups(&pair, &[], 1.0);
        // the beam of three is shown; the rest with the two is not
        assert_eq!(found.len(), 2);
        assert_eq!(found.iter().filter(|g| g.shown).count(), 1);
        assert!(found
            .iter()
            .any(|g| !g.shown && g.members == vec![(0, 0), (1, 1), (1, 2)]));
        let (evs, voices) = read_pair(&two(&upper, &lower, 2)).unwrap();
        assert!(evs[0][0].tuplets.len() == 1 && evs[0][0].dur == third);
        // the upper staff: the rest and blank time; the lower: the half note, and the line
        // from the bar's second third
        assert_eq!(starts(&voices[0][0]), vec![(Q::ZERO, false)]);
        let line = voices[1].iter().find(|v| v.len() > 1).unwrap();
        assert_eq!(starts(line)[0], (third, true));
        assert_eq!(starts(line).len(), 5);
        assert!(line.iter().all(|e| !e.tuplets.is_empty()));
        // with a plain quarter after the rest's triplet in place of the beam of three, the
        // triplet would be a guess beside plain notes: nothing is read
        let mut plain = lower[..3].to_vec();
        plain.push(note(9.0, 40.0, Q::ONE, true));
        assert!(read_pair(&two(&upper, &plain, 2)).is_none());
    }

    #[test]
    fn a_rest_read_as_its_bar_s_rest_is_the_triplet_s_where_the_other_staff_has_its_notes() {
        let (upper, lower) = rest_above();
        let (e, third) = (Q::new(1, 2), Q::new(1, 3));
        let names: Vec<String> = ["P.1", "P.2"].iter().map(|s| s.to_string()).collect();
        // both staves read: the upper as its bar's rest (one printed rest, shorter than the
        // bar), the lower with the two eighths plain and the beam of three a triplet
        let mut held = Ev::spacer(e, 0.0);
        held.rest = Rest::Bar;
        let mut as_read = lower.clone();
        for n in as_read[3..].iter_mut() {
            n.tuplets = vec![(3, 2, 99)];
            n.dur = third;
        }
        let was = vec![vec![as_read[0].clone()], as_read[1..].to_vec()];
        let mut events = vec![upper.clone(), as_read.clone()];
        let mut voices = vec![Ok(vec![vec![held.clone()]]), Ok(was.clone())];
        let lens = [Q::int(2), Q::int(2)];
        let how = (Some(40.0), false);
        tuplets_between(&mut events, &mut voices, &names, 1.0, &lens, how);
        // the rest and the two eighths are a triplet now, the line starting on the upper staff
        assert_eq!(events[0][0].dur, third);
        assert!(events[1][1..].iter().all(|n| n.dur == third));
        let line = voices[1].as_ref().unwrap();
        let line = line.iter().find(|v| v.len() > 1).unwrap();
        assert_eq!(starts(line)[0], (third, true));
        // (in a bar that may be short too: nothing is made up to fill it)
        let mut events = vec![upper.clone(), as_read.clone()];
        let mut voices = vec![Ok(vec![vec![held.clone()]]), Ok(was.clone())];
        tuplets_between(
            &mut events,
            &mut voices,
            &names,
            1.0,
            &lens,
            (Some(40.0), true),
        );
        assert_eq!(events[0][0].dur, third);
        // with notes of its own, the upper staff's reading stands: nothing is read again
        let mut busy = upper.clone();
        busy.push(note(9.0, 12.0, Q::ONE, true));
        let mut events = vec![busy.clone(), as_read.clone()];
        let mut voices = vec![Ok(vec![busy.clone()]), Ok(was)];
        tuplets_between(&mut events, &mut voices, &names, 1.0, &lens, how);
        assert_eq!(events[0][0].dur, e);
    }

    #[test]
    fn of_a_beam_partly_in_a_tuplet_the_other_notes_may_be_one_with_a_rest() {
        let (e, third) = (Q::new(1, 2), Q::new(1, 3));
        // one beam of five eighths, the last three in a tuplet already; an eighth rest before
        let (upper, mut lower) = rest_above();
        for n in lower[1..].iter_mut() {
            n.beam_polys.clear();
            n.beam_polys.insert(5);
        }
        for n in lower[3..].iter_mut() {
            n.tuplets = vec![(3, 2, 99)];
            n.dur = third;
        }
        let found = groups(&[upper, lower.clone()], &[], 1.0);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].members, vec![(0, 0), (1, 1), (1, 2)]);
        assert!(!found[0].shown);
        // three free notes of a beam with others in a tuplet are not shown by the beam
        let mut six = lower[1..].to_vec();
        six.push(note(18.0, 40.0, e, true));
        six[5].beam_polys.insert(5);
        for n in six[..3].iter_mut() {
            n.tuplets.clear();
            n.dur = e;
        }
        six[3].tuplets = vec![(3, 2, 99)];
        six[3].dur = third;
        let found = groups(&[Vec::new(), six], &[], 1.0);
        assert!(found.iter().all(|g| !g.shown));
    }

    #[test]
    fn a_rest_and_two_beamed_notes_of_one_staff_fill_its_bar_as_a_triplet() {
        let (e, q) = (Q::new(1, 2), Q::ONE);
        // 2/4, the lower staff: a quarter, an eighth rest and two beamed eighths; the upper
        // reads alone
        let upper = vec![note(0.0, 10.0, Q::int(2), true)];
        let read = vec![upper.clone()];
        let mut lower = vec![note(0.0, 40.0, q, true), rest(6.0, 40.0, e)];
        lower.extend(on_beam(
            vec![note(8.0, 40.0, e, true), note(10.0, 40.0, e, true)],
            1,
        ));
        let mut t = two(&upper, &lower, 2);
        t.read = [Some(&read), None];
        let (evs, voices) = read_pair(&t).unwrap();
        assert_eq!(voices[1].len(), 1);
        assert_eq!(
            starts(&voices[1][0]),
            vec![
                (Q::ZERO, true),
                (q, false),
                (Q::new(4, 3), true),
                (Q::new(5, 3), true)
            ]
        );
        assert!(evs[1][1..].iter().all(|e| e.tuplets.len() == 1));
    }

    #[test]
    fn a_number_over_a_run_that_passes_between_the_staves_takes_its_notes() {
        let s = Q::new(1, 4);
        // a bar of one quarter: five sixteenths under a 5, two on the lower staff and three
        // on the upper, each on a beam of its own
        let mut lower = on_beam(vec![note(0.0, 40.0, s, true), note(2.0, 39.0, s, true)], 1);
        let upper = on_beam(
            vec![
                note(4.0, 14.0, s, false),
                note(6.0, 13.0, s, false),
                note(8.0, 12.0, s, false),
            ],
            2,
        );
        lower[1].loose.push((5, 4, 4.6, false));
        let pair = [upper.clone(), lower.clone()];
        let found = groups(&pair, &[], 1.0);
        let five = found.iter().find(|g| g.ratio == (5, 4)).unwrap();
        assert!(five.shown && five.members.len() == 5);
        let (evs, voices) = read_pair(&two(&upper, &lower, 1)).unwrap();
        let fifth = Q::new(1, 5);
        assert!(evs.iter().flatten().all(|e| e.dur == fifth));
        assert!(evs.iter().flatten().all(|e| e.loose.is_empty()));
        let line = &voices[0][0];
        assert_eq!(starts(line)[0], (fifth * Q::int(2), true));
    }

    #[test]
    fn a_number_given_to_both_staves_notes_is_taken_back() {
        let (e, q, third) = (Q::new(1, 2), Q::ONE, Q::new(1, 3));
        // a 3 between the staves, given to the lower staff's quarter and to an eighth the
        // upper holds for its beam (drawn on the lower)
        let mut held = note(4.0, 30.0, third, false);
        held.on_staff = Some(2);
        held.tuplets = vec![(3, 2, 9)];
        let mut quarter = note(0.0, 40.0, q * Q::new(2, 3), true);
        quarter.tuplets = vec![(3, 2, 9)];
        let upper = vec![note(0.0, 12.0, e, false), note(2.0, 13.0, e, false), held];
        let lower = vec![quarter, Ev::spacer(third, 4.0)];
        let (evs, was) = taken_back(&[upper, lower]).unwrap();
        assert_eq!(was.len(), 1);
        assert_eq!((was[0].ratio, was[0].lo, was[0].hi), ((3, 2), 0.0, 4.0));
        assert!(evs.iter().flatten().all(|e| e.tuplets.is_empty()));
        assert_eq!(evs[0][2].dur, e);
        assert_eq!(evs[1][0].dur, q);
        // (the blank time the eighth left on the lower staff is an eighth's again)
        assert_eq!(evs[1][1].dur, e);
        // a tuplet all of one staff's bar stays
        let mut own = note(0.0, 40.0, third, true);
        own.tuplets = vec![(3, 2, 9)];
        assert!(taken_back(&[vec![note(0.0, 12.0, e, false)], vec![own]]).is_none());
    }

    #[test]
    fn blank_time_left_by_a_note_found_in_a_tuplet_is_as_long_as_the_note() {
        let (e, q, third) = (Q::new(1, 2), Q::ONE, Q::new(1, 3));
        // the upper staff holds a triplet whose last note is drawn on the lower; the lower has
        // a quarter and the blank time the note left, an eighth long as it was printed
        let mut upper: Vec<Ev> = [0.0, 3.0, 6.0]
            .iter()
            .map(|&x| note(x, 12.0, third, false))
            .collect();
        for n in upper.iter_mut() {
            n.tuplets = vec![(3, 2, 4)];
        }
        upper[2].on_staff = Some(2);
        let lower = vec![note(0.0, 40.0, q, true), Ev::spacer(e, 6.0)];
        let names: Vec<String> = ["P.1", "P.2"].iter().map(|s| s.to_string()).collect();
        let mut events = vec![upper, lower];
        let mut voices: Vec<Result<Vec<Vec<Ev>>, String>> = vec![Ok(Vec::new()), Err("?".into())];
        let lens = [q, q];
        blanks_as_their_notes(
            &mut events,
            &mut voices,
            &names,
            1.0,
            &lens,
            Some(20.0),
            false,
        );
        assert_eq!(events[1][1].dur, third);
        // the lower staff's quarter fills its bar: the note is the upper staff's voice's
        let read = voices[1].as_ref().unwrap();
        assert_eq!(read.len(), 1);
        assert_eq!(read[0].len(), 1);
    }
}