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
//! A voice passing between a part's two staves: a piano's left hand runs up into the right
//! hand's staff, or one line is shared out between the hands, and the program prints no rests
//! where the voice has left a staff. Each staff alone then has time with nothing in it, and its
//! bar does not add up. Read together they do: the line's notes and rests, in the order they
//! stand across both staves, follow one another and fill the bar exactly, and what each staff
//! has besides is voices that fill the bar on their own. The staff the line has left has blank
//! time where it sounds on the other.

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

/// A note stands in a column when no further from it than this, in spaces.
const IN_COLUMN: f64 = 0.7;
/// A tuplet's note, when no further from it than this.
const IN_COLUMN_TUPLET: f64 = 0.4;
/// What starts later stands at least this far right of what starts before it.
const ON: f64 = 0.5;
/// The same for two notes on one beam.
const ON_A_BEAM: f64 = 0.2;
/// The bar's first notes stand no further apart than this.
const FIRST: f64 = 1.8;

/// One bar of a part's two staves, for [`line_between`].
pub struct Pair<'a> {
    /// Each staff's notes and rests, and its voices where it reads alone.
    pub events: [&'a [Ev]; 2],
    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>,
}

struct Item<'a> {
    staff: usize,
    e: &'a Ev,
    x: f64,
    /// When it starts, where its staff reads alone.
    known: Option<Q>,
    /// The note after it on its beam, and whether a note stands before it there: a beam's
    /// notes follow one another in one voice.
    beam_next: Option<usize>,
    beam_first: bool,
}

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

fn same(a: &Ev, b: &Ev) -> bool {
    a.x == b.x && a.dur == b.dur && a.up == b.up && a.places == b.places && a.rest == b.rest
}

/// When each event of a staff's voices starts, and whether its voice has blank time.
fn starts_of(voices: &[Vec<Ev>]) -> Vec<(&Ev, Q, bool)> {
    let mut out = Vec::new();
    for v in voices {
        let blank = v.iter().any(|e| e.rest == Rest::Blank);
        let mut t = Q::ZERO;
        for e in v {
            out.push((e, t, blank));
            t += e.takes();
        }
    }
    out
}

struct Search<'a> {
    items: &'a [Item<'a>],
    others: &'a [Mark],
    sp: f64,
    len: Q,
    chain: Vec<usize>,
    found: Vec<Vec<usize>>,
    nodes: usize,
}

impl Search<'_> {
    fn walk(&mut self, from: usize, t: Q) {
        self.nodes += 1;
        if self.nodes > 60_000 || self.found.len() > 400 {
            return;
        }
        if t == self.len {
            self.found.push(self.chain.clone());
            return;
        }
        let on_beam = self.chain.last().and_then(|&k| self.items[k].beam_next);
        for k in from..self.items.len() {
            let it = &self.items[k];
            if on_beam.map_or(!it.beam_first, |n| n != k) {
                continue;
            }
            // (what starts later stands right of what starts before it: a little, for two
            // notes on one beam passing between the staves, which a program sets close)
            let last = self.chain.last().map(|&k| &self.items[k]);
            let near = |l: &Item| match l.e.beam_polys.is_disjoint(&it.e.beam_polys) {
                true => ON,
                false => ON_A_BEAM,
            };
            if last.is_some_and(|l| it.x - l.x < near(l) * self.sp) || t + it.e.takes() > self.len {
                continue;
            }
            if it.known.is_some_and(|at| at != t) {
                continue;
            }
            // (a note in a column of the other staves starts with it)
            if it.e.is_note() {
                // (a tuplet's note stands close by the plain note it falls just before or
                // after, a triplet's third eighth by a fourth sixteenth: in its column only
                // where nearer)
                let within = match it.e.tuplets.is_empty() {
                    true => IN_COLUMN,
                    false => IN_COLUMN_TUPLET,
                };
                let col = self
                    .others
                    .iter()
                    .filter(|m| (m.x - it.x).abs() <= within * self.sp)
                    .min_by(|a, b| (a.x - it.x).abs().total_cmp(&(b.x - it.x).abs()));
                if col.is_some_and(|m| m.at != t) {
                    continue;
                }
            }
            self.chain.push(k);
            self.walk(k + 1, t + it.e.takes());
            self.chain.pop();
        }
    }
}

/// The blank time of a staff from `from` to `to`, at `x`: one blank; or, where the line's notes
/// on the other staff then (`whole`: the line, each event with its start) are in a tuplet that
/// has notes on this staff too (`here`: those tuplets), the tuplet's time blank note for note,
/// so that what this staff has of the tuplet is written in it (`3:2{ s/8 g8 a8 }`).
fn blank(from: Q, to: Q, x: f64, whole: &[(&Ev, Q)], here: &[usize]) -> Option<Vec<Ev>> {
    let mut out: Vec<Ev> = Vec::new();
    let mut plain = Q::ZERO;
    let mut t = from;
    let flush = |plain: &mut Q, out: &mut Vec<Ev>| {
        if !plain.is_zero() {
            crate::write::plain_lengths(*plain).ok()?;
            out.push(Ev::spacer(*plain, x));
            *plain = Q::ZERO;
        }
        Some(())
    };
    for &(e, at) in whole {
        let shared = e.tuplets.iter().any(|t| here.contains(&t.2));
        if at < t || at >= to || e.grace.is_some() || !shared {
            continue;
        }
        plain += at - t;
        flush(&mut plain, &mut out)?;
        let mut b = Ev::spacer(e.dur, x);
        b.tuplets = e.tuplets.clone();
        // (two of a triplet's eighths blank: a quarter's blank in it)
        match out.last_mut() {
            Some(l)
                if l.tuplets == b.tuplets
                    && l.dur == b.dur
                    && crate::write::plain_lengths(l.written() + b.written())
                        .is_ok_and(|p| p.len() == 1) =>
            {
                l.dur += b.dur
            }
            _ => out.push(b),
        }
        t = at + e.dur;
    }
    if t > to {
        return None;
    }
    plain += to - t;
    flush(&mut plain, &mut out)?;
    Some(out)
}

/// The line's part on one staff as a voice: its notes and rests at their starts, blank time
/// between them (of a tuplet shared between the staves, in the tuplet: `whole` is the line on
/// both staves). `None` where a blank is of a length no rest could be written in.
fn line_voice(part: &[(&Ev, Q)], whole: &[(&Ev, Q)], len: Q) -> Option<Vec<Ev>> {
    let here: Vec<usize> = part
        .iter()
        .flat_map(|(e, _)| e.tuplets.iter().map(|t| t.2))
        .collect();
    let mut v: Vec<Ev> = Vec::new();
    let mut t = Q::ZERO;
    for &(e, at) in part {
        if at > t {
            v.extend(blank(t, at, e.x - 0.01, whole, &here)?);
        }
        v.push(e.clone());
        t = at + e.takes();
    }
    if t < len {
        let x = v.last().map_or(0.0, |e| e.x + 0.01);
        v.extend(blank(t, len, x, whole, &here)?);
    }
    Some(v)
}

/// The line on both staves, in time.
fn both<'a>(parts: &[Vec<(&'a Ev, Q)>; 2]) -> Vec<(&'a Ev, Q)> {
    let mut all: Vec<(&Ev, Q)> = parts.iter().flatten().copied().collect();
    all.sort_by_key(|a| a.1);
    all
}

/// What a staff has besides the line where that does not fill the bar: one voice whose rests
/// the program hid, timed by the columns of the line and of the other staves, every note of
/// it in a column. Only where the passing is sure (`sure`): a beam joins the two staves, or
/// the line does not turn on one note that a missed dot would explain as well.
fn beside_the_line(
    rest: &[Ev],
    parts: &[Vec<(&Ev, Q)>; 2],
    p: &Pair,
    sure: bool,
) -> Option<Vec<Ev>> {
    let sp = p.sp;
    let mut run: Vec<Ev> = rest.to_vec();
    run.sort_by(|a, b| a.x.total_cmp(&b.x));
    let one = run
        .windows(2)
        .all(|w| w[1].x - w[0].x > 0.6 * sp || w[0].grace.is_some());
    if !sure || !one {
        return None;
    }
    let mut fixed: Vec<Mark> = p.others.to_vec();
    for (s, part) in parts.iter().enumerate() {
        fixed.extend(columns::marks(&[
            line_voice(part, &[], p.len).or_else(|| line_voice(part, &both(parts), p.len))?
        ]));
        if let Some(vs) = p.read[s] {
            fixed.extend(columns::marks(vs));
        }
    }
    let in_column = |e: &Ev| {
        let x = columns::column_x(e);
        fixed.iter().any(|m| (m.x - x).abs() <= IN_COLUMN * sp)
    };
    if !run
        .iter()
        .filter(|e| e.is_note() && e.grace.is_none())
        .all(in_column)
    {
        return None;
    }
    let v = columns::retimed(&[run], &fixed, p.len, sp)?.pop()?;
    (v.iter().map(|e| e.takes()).sum::<Q>() == p.len).then_some(v)
}

/// The two staves' voices with a line passing between them, where there is one such reading:
/// a chain of notes and rests of both staves, each standing right of the one before and
/// starting where it ends, that fills the bar; what a staff has besides fills the bar in voices
/// of its own, or is one voice the columns time ([`beside_the_line`]). Of a staff that reads
/// alone already, the line's part is a whole voice of it that was read with blank time, its
/// notes starting as read. A beam's notes follow one another in the line. Only the staves that
/// do not read alone are given; nothing where two chains make readings that differ, where a
/// dot is in doubt, or in a run of small notes.
pub fn line_between(p: &Pair) -> Option<[Option<Vec<Vec<Ev>>>; 2]> {
    let sp = p.sp;
    if p.read.iter().all(|r| r.is_some()) {
        return None;
    }
    let unsure = |e: &Ev| e.rest == Rest::Bar || e.dots_shared > 0 || e.dots_partial;
    if p.events.iter().any(|evs| evs.iter().any(unsure)) {
        return None;
    }
    // (nor with one note read twice, or a run of small notes in time of their own: a cadenza)
    let twice = |evs: &[Ev]| {
        (0..evs.len()).any(|i| evs[i].is_note() && (0..i).any(|j| same(&evs[i], &evs[j])))
    };
    let small = |evs: &[Ev]| evs.iter().filter(|e| e.grace.is_some()).count() > 4;
    if p.events.iter().any(|evs| twice(evs) || small(evs)) {
        return None;
    }
    let known: [Vec<(&Ev, Q, bool)>; 2] =
        [0, 1].map(|s| p.read[s].map(starts_of).unwrap_or_default());
    let mut items: Vec<Item> = Vec::new();
    for s in 0..2 {
        for e in p.events[s].iter().filter(|e| timed(e)) {
            let found = known[s].iter().find(|(f, _, _)| same(f, e));
            // (of a staff that reads alone, only a voice with blank time may be the line's)
            if found.is_some_and(|f| !f.2) {
                continue;
            }
            let at = found.map(|f| f.1);
            if p.read[s].is_some() && at.is_none() {
                return None;
            }
            items.push(Item {
                staff: s,
                e,
                x: match e.is_note() {
                    true => columns::column_x(e),
                    false => e.x,
                },
                known: at,
                beam_next: None,
                beam_first: true,
            });
        }
    }
    items.sort_by(|a, b| a.x.total_cmp(&b.x));
    // (the line has notes on one staff at least, and on the other notes or the rests it is
    // printed with there: a hand's line written on the other staff, its rests left at home)
    if items.len() > 48
        || !(0..2).all(|s| items.iter().any(|i| i.staff == s))
        || !items.iter().any(|i| i.e.is_note())
    {
        return None;
    }
    for k in 0..items.len() {
        let on = |j: usize| {
            j != k
                && items[j].e.is_note()
                && items[k].e.is_note()
                && !items[j].e.beam_polys.is_disjoint(&items[k].e.beam_polys)
        };
        let next = (k + 1..items.len()).find(|&j| on(j) && items[j].x > items[k].x);
        let first = !(0..k).any(|j| on(j) && items[j].x < items[k].x);
        (items[k].beam_next, items[k].beam_first) = (next, first);
    }
    let first_x = items.first()?.x;
    let mut search = Search {
        items: &items,
        others: p.others,
        sp,
        len: p.len,
        chain: Vec::new(),
        found: Vec::new(),
        nodes: 0,
    };
    // (the line starts with the bar: at its first column)
    for k in 0..items.len() {
        let it = &items[k];
        if it.x - first_x > FIRST * sp {
            break;
        }
        if it.known.is_some_and(|at| !at.is_zero()) || !it.beam_first {
            continue;
        }
        search.chain.push(k);
        search.walk(k + 1, it.e.takes());
        search.chain.pop();
    }
    if search.nodes > 60_000 || search.found.len() > 400 {
        return None;
    }
    let crossed = p
        .events
        .iter()
        .any(|evs| evs.iter().any(|e| e.on_staff.is_some()));
    type Reading = (Vec<(usize, Q, Q, i32)>, [Option<Vec<Vec<Ev>>>; 2], usize);
    let mut readings: Vec<Reading> = Vec::new();
    'chains: for chain in &search.found {
        let on = |s: usize| chain.iter().any(|&k| items[k].staff == s);
        if !(on(0) && on(1)) || !chain.iter().any(|&k| items[k].e.is_note()) {
            continue;
        }
        // a tuplet's notes are one voice's: all in the line or none
        let split = chain.iter().any(|&k| {
            (0..items.len()).any(|o| {
                !chain.contains(&o)
                    && items[o]
                        .e
                        .tuplets
                        .iter()
                        .any(|t| items[k].e.tuplets.iter().any(|u| u.2 == t.2))
            })
        });
        if split {
            continue;
        }
        let mut t = Q::ZERO;
        let mut parts: [Vec<(&Ev, Q)>; 2] = [Vec::new(), Vec::new()];
        for &k in chain {
            parts[items[k].staff].push((items[k].e, t));
            t += items[k].e.takes();
        }
        // one note of the other staff between two of a staff's, as long as a dot on the note
        // before it would be: that note's dot may have been missed, and nothing passes
        let dot = chain.windows(3).any(|w| {
            let (a, x, b) = (&items[w[0]], &items[w[1]], &items[w[2]]);
            let half = a.e.written() / Q::int(2);
            a.staff == b.staff
                && x.staff != a.staff
                && a.e.is_note()
                && (x.e.takes() == half || x.e.takes() == half + half / Q::int(2))
        });
        let sure = crossed || !dot;
        let mut out: [Option<Vec<Vec<Ev>>>; 2] = [None, None];
        let mut all: [Vec<Vec<Ev>>; 2] = [Vec::new(), Vec::new()];
        for s in 0..2 {
            if let Some(vs) = p.read[s] {
                // of a staff that reads alone, the line's part is whole voices of it that do
                // not fill the bar with what is printed (their rests hidden)
                let of_line = |e: &Ev| parts[s].iter().any(|(f, _)| same(f, e));
                let whole = vs.iter().all(|v| {
                    let n = v.iter().filter(|e| timed(e) && of_line(e)).count();
                    n == 0
                        || (n == v.iter().filter(|e| timed(e)).count()
                            && v.iter().any(|e| e.rest == Rest::Blank))
                });
                if !whole {
                    continue 'chains;
                }
                all[s] = vs.to_vec();
                continue;
            }
            // what the staff has besides the line: voices that fill the bar as printed
            let in_line = |e: &Ev| parts[s].iter().any(|(f, _)| std::ptr::eq(*f, e));
            let mut rest: Vec<Ev> = Vec::new();
            let mut line: Vec<(&Ev, Q)> = Vec::new();
            let evs = p.events[s];
            for (i, e) in evs.iter().enumerate() {
                if e.rest == Rest::Blank {
                    continue;
                }
                // (a grace note goes with the note it leads to)
                let with_line = match e.grace {
                    None => in_line(e),
                    Some(_) => evs[i + 1..]
                        .iter()
                        .filter(|n| timed(n) && n.x > e.x)
                        .min_by(|a, b| a.x.total_cmp(&b.x))
                        .is_some_and(in_line),
                };
                match with_line {
                    true => {
                        let at = parts[s].iter().find(|(f, _)| f.x >= e.x).map(|&(_, t)| t);
                        line.push((e, at.unwrap_or(p.len)));
                    }
                    false => rest.push(e.clone()),
                }
            }
            let mut vs = match rest.iter().any(timed) {
                false if rest.is_empty() => Vec::new(),
                false => continue 'chains,
                true => match voices_of(rest.clone(), sp, p.len, p.right, false) {
                    Ok(vs) if !vs.iter().flatten().any(|e| e.rest == Rest::Blank) => vs,
                    _ => match beside_the_line(&rest, &parts, p, sure) {
                        Some(v) => vec![v],
                        None => continue 'chains,
                    },
                },
            };
            line.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.x.total_cmp(&b.0.x)));
            let Some(v) = line_voice(&line, &both(&parts), p.len) else {
                continue 'chains;
            };
            vs.push(v);
            if vs.len() > 4 {
                continue 'chains;
            }
            let height = |v: &Vec<Ev>| {
                let ys: Vec<f64> = v.iter().filter(|e| e.is_note()).map(|e| e.y()).collect();
                ys.iter().sum::<f64>() / ys.len().max(1) as f64
            };
            vs.sort_by(|a, b| height(a).total_cmp(&height(b)));
            all[s] = vs.clone();
            out[s] = Some(vs);
        }
        // the columns do not speak against it
        let marks: [Vec<Mark>; 2] = [0, 1].map(|s| columns::marks(&all[s]));
        let cols: [Vec<Mark>; 2] = [0, 1].map(|s| columns::columns(&marks[s]));
        if marks.iter().any(|m| columns::contradicts_itself(m, sp))
            || columns::contradict(&cols[0], &cols[1], sp)
            || cols.iter().any(|c| columns::contradict(c, p.others, sp))
        {
            continue;
        }
        let mut sig: Vec<(usize, Q, Q, i32)> = Vec::new();
        for s in 0..2 {
            for (e, at, _) in starts_of(&all[s]) {
                if e.is_note() {
                    sig.push((s, at, e.takes(), e.places.first().copied().unwrap_or(0)));
                }
            }
        }
        sig.sort();
        // (of chains that give the notes the same starts, the one whose voices are each in
        // tuplets or plain throughout: a tuplet's rest is not the plain voice's)
        let mixed = all
            .iter()
            .flatten()
            .filter(|v| {
                v.iter().any(|e| timed(e) && e.tuplets.is_empty())
                    && v.iter().any(|e| timed(e) && !e.tuplets.is_empty())
            })
            .count();
        if let Some(r) = readings.iter_mut().find(|r| r.0 == sig) {
            if mixed < r.2 {
                *r = (sig, out, mixed);
            }
        } else {
            readings.push((sig, out, mixed));
        }
    }
    match readings.len() {
        1 => readings.pop().map(|r| r.1),
        _ => None,
    }
}

/// One bar's staves: each part's two staves of which one at least does not read alone are read
/// with a line passing between them ([`line_between`]).
pub fn between_staves(
    events: &[Vec<Ev>],
    voices: &mut [Result<Vec<Vec<Ev>>, String>],
    names: &[String],
    sp: f64,
    lens: &[Q],
    right: Option<f64>,
) {
    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])
            || (voices[i].is_ok() && voices[j].is_ok())
            || lens[i] != lens[j]
        {
            continue;
        }
        // (the columns of the staves in the same time)
        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 pair = Pair {
            events: [&events[i], &events[j]],
            read: [voices[i].as_deref().ok(), voices[j].as_deref().ok()],
            others: &others,
            sp,
            len,
            right,
        };
        if let Some([a, b]) = line_between(&pair) {
            if let Some(a) = a {
                voices[i] = Ok(a);
            }
            if let Some(b) = b {
                voices[j] = Ok(b);
            }
        }
    }
}

/// A staff's one voice whose rests the program hid (its line gone to the part's other staff, a
/// hand that enters late or stops early): the bar does not add up, no two of its notes sound at
/// once, and every note stands in a column of the other staves as read, so starts with it; the
/// time between is blank (`columns::retimed` says where, or that it is not told). The caller
/// has seen that nothing printed in the staff's bar was passed over.
pub fn hidden_rests(events: &[Ev], others: &[Mark], sp: f64, len: Q) -> Option<Vec<Vec<Ev>>> {
    let unsure = |e: &Ev| e.rest == Rest::Bar || e.dots_shared > 0 || e.dots_partial;
    // (a full-size note on a beam with small ones: its length is not sure)
    let with_small = |e: &Ev| {
        e.grace.is_none()
            && events
                .iter()
                .any(|g| g.grace.is_some() && !g.beam_polys.is_disjoint(&e.beam_polys))
    };
    if events.iter().any(|e| unsure(e) || with_small(e)) {
        return None;
    }
    let mut run: Vec<Ev> = events
        .iter()
        .filter(|e| e.rest != Rest::Blank)
        .cloned()
        .collect();
    run.sort_by(|a, b| a.x.total_cmp(&b.x));
    let one = run
        .windows(2)
        .all(|w| w[1].x - w[0].x > 0.6 * sp || w[0].grace.is_some());
    let in_column = |e: &Ev| {
        let x = columns::column_x(e);
        others.iter().any(|m| (m.x - x).abs() <= IN_COLUMN * sp)
    };
    let mut notes = run.iter().filter(|e| e.is_note() && e.grace.is_none());
    if notes.clone().count() == 0 {
        return rests_alone(&run, others, sp, len);
    }
    if !one || !notes.all(in_column) {
        return None;
    }
    let v = columns::retimed(&[run], others, len, sp)?.pop()?;
    let blank = v.iter().any(|e| e.rest == Rest::Blank);
    (blank && v.iter().map(|e| e.takes()).sum::<Q>() == len).then(|| vec![v])
}

/// A staff's bar of printed rests that do not fill it (a voice that rests where the other
/// staves play, the rest of its time hidden): each rest stands in a column of the other staves
/// and starts with it, the time between blank.
fn rests_alone(run: &[Ev], others: &[Mark], sp: f64, len: Q) -> Option<Vec<Vec<Ev>>> {
    if run.is_empty() || !run.iter().all(|e| matches!(e.rest, Rest::Printed(_))) {
        return None;
    }
    let mut part: Vec<(&Ev, Q)> = Vec::new();
    let mut t = Q::ZERO;
    for e in run {
        let at = others
            .iter()
            .filter(|m| (m.x - e.x).abs() <= IN_COLUMN * sp)
            .min_by(|a, b| (a.x - e.x).abs().total_cmp(&(b.x - e.x).abs()))?
            .at;
        if at < t || at + e.takes() > len {
            return None;
        }
        part.push((e, at));
        t = at + e.takes();
    }
    let v = line_voice(&part, &[], len)?;
    v.iter().any(|e| e.rest == Rest::Blank).then(|| vec![v])
}

#[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 mark(x: f64, at: Q) -> Mark {
        Mark {
            x,
            at,
            play: 0.0,
            wide: false,
            sign: false,
        }
    }

    fn shape(v: &[Ev]) -> Vec<(Q, bool)> {
        v.iter().map(|e| (e.dur, e.rest == Rest::Blank)).collect()
    }

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

    #[test]
    fn a_line_passing_to_the_other_staff_beside_its_melody_leaves_blank_time() {
        let (q, s) = (Q::ONE, Q::new(1, 4));
        // 2/4: the upper staff has two quarters, stems up, and under the second the line's
        // four sixteenths, stems down; the lower staff has the line's first four
        let mut upper = vec![note(0.0, 10.0, q, true), note(12.0, 10.0, q, true)];
        upper.extend([12.0, 15.0, 18.0, 21.0].map(|x| note(x, 14.0, s, false)));
        let lower: Vec<Ev> = [0.0, 3.0, 6.0, 9.0]
            .iter()
            .map(|&x| note(x, 40.0, s, true))
            .collect();
        let [a, b] = line_between(&pair(&upper, &lower, &[], 2)).unwrap();
        let (a, b) = (a.unwrap(), b.unwrap());
        // the upper staff: its melody, and the line from the second beat; the lower: the line,
        // then a quarter's blank time
        assert_eq!(a.len(), 2);
        assert!(a.iter().any(|v| shape(v)[0] == (q, true)));
        assert_eq!(b.len(), 1);
        assert_eq!(shape(&b[0]).last(), Some(&(q, true)));
        // a bar the line does not fill: notes are missing, and nothing is read
        assert!(line_between(&pair(&upper, &lower, &[], 3)).is_none());
    }

    #[test]
    fn a_tuplet_shared_between_the_staves_is_written_on_both() {
        let (h, third) = (Q::int(2), Q::new(1, 3));
        // 2/4: an eighth rest on the upper staff and two eighths on the lower are one triplet,
        // three more on the lower another; under them the lower staff's half note
        let mut r = rest(0.0, 10.0, third);
        r.tuplets = vec![(3, 2, 7)];
        let upper = vec![r];
        let mut lower = vec![note(0.0, 46.0, h, false)];
        for (k, x) in [3.0, 6.0, 9.0, 12.0, 15.0].into_iter().enumerate() {
            let mut e = note(x, 40.0, third, true);
            e.tuplets = vec![(3, 2, if k < 2 { 7 } else { 8 })];
            lower.push(e);
        }
        let [a, b] = line_between(&pair(&upper, &lower, &[], 2)).unwrap();
        let (a, b) = (a.unwrap(), b.unwrap());
        // the upper staff: the rest, the triplet's other two thirds blank in it, a quarter blank
        assert_eq!(a.len(), 1);
        assert_eq!(
            shape(&a[0]),
            vec![(third, false), (third * Q::int(2), true), (Q::ONE, true)]
        );
        assert_eq!(a[0][1].tuplets, vec![(3, 2, 7)]);
        assert!(a[0][2].tuplets.is_empty());
        // the lower: its half note, and the line after a third's blank in the triplet
        assert_eq!(b.len(), 2);
        let line = b.iter().find(|v| v.len() > 1).unwrap();
        assert_eq!(shape(line)[0], (third, true));
        assert_eq!(line[0].tuplets, vec![(3, 2, 7)]);
        assert_eq!(line.len(), 6);
        // another staff's sixteenth at 1 3/4, close by the triplet's last eighth (at 1 2/3):
        // the eighth is not in its column
        let others = [mark(15.6, Q::new(7, 4))];
        assert!(line_between(&pair(&upper, &lower, &others, 2)).is_some());
        // nearer, it is, and would start with it
        let others = [mark(15.3, Q::new(7, 4))];
        assert!(line_between(&pair(&upper, &lower, &others, 2)).is_none());
    }

    #[test]
    fn a_line_written_on_the_other_staff_leaves_only_its_rests_at_home() {
        let (q, e) = (Q::ONE, Q::new(1, 2));
        // 3/4: the upper staff has two eighth rests, at the first and the third beat; the
        // lower a half and a quarter, stems down, and the upper hand's eighths, stems up, after
        // each rest
        let upper = vec![rest(0.0, 10.0, e), rest(12.0, 10.0, e)];
        let mut lower = vec![
            note(0.0, 40.0, Q::int(2), false),
            note(12.0, 40.0, q, false),
        ];
        lower.extend([3.0, 6.0, 9.0, 15.0].map(|x| note(x, 34.0, e, true)));
        let [a, b] = line_between(&pair(&upper, &lower, &[], 3)).unwrap();
        let (a, b) = (a.unwrap(), b.unwrap());
        // the upper staff: its rests, blank time where the line sounds below; the lower: its
        // own voice whole, and the line with blank time where the upper staff rests
        assert_eq!(a.len(), 1);
        assert_eq!(shape(&a[0])[..2], [(e, false), (q + e, true)]);
        assert_eq!(b.len(), 2);
        assert!(b
            .iter()
            .any(|v| shape(v) == [(Q::int(2), false), (q, false)]));
        assert!(b.iter().any(|v| shape(v)[0] == (e, true) && v.len() == 6));
        // rests on both staves and no note: nothing passes
        assert!(line_between(&pair(&upper, &upper, &[], 3)).is_none());
    }

    #[test]
    fn a_staff_that_reads_alone_gives_the_line_only_a_voice_with_blank_time() {
        let (q, e) = (Q::ONE, Q::new(1, 2));
        // the upper staff reads alone: two quarters, and a voice of two eighths after a
        // quarter's blank time; the lower staff has two eighths and nothing after them
        let melody = vec![note(0.0, 10.0, q, true), note(12.0, 10.0, q, true)];
        let part = vec![
            Ev::spacer(q, 11.9),
            note(12.0, 14.0, e, false),
            note(18.0, 14.0, e, false),
        ];
        let upper: Vec<Ev> = melody.iter().chain(&part[1..]).cloned().collect();
        let lower = vec![note(0.0, 40.0, e, true), note(6.0, 40.0, e, true)];
        let read = vec![melody.clone(), part];
        let mut p = pair(&upper, &lower, &[], 2);
        p.read = [Some(&read), None];
        let [a, b] = line_between(&p).unwrap();
        assert!(a.is_none());
        assert_eq!(
            shape(&b.unwrap()[0]),
            vec![(e, false), (e, false), (q, true)]
        );
        // read as one full voice, the upper staff has nothing of a line: the lower staff's
        // quarter of nothing is not explained
        let full = vec![melody];
        let mut p = pair(&upper[..2], &lower, &[], 2);
        p.read = [Some(&full), None];
        assert!(line_between(&p).is_none());
    }

    #[test]
    fn a_voice_with_hidden_rests_is_timed_by_the_other_staves_columns() {
        let q = Q::ONE;
        // 4/4: quarters at the second and fourth beats, another staff's quarters on every beat
        let others: Vec<Mark> = (0..4).map(|k| mark(10.0 * k as f64, Q::int(k))).collect();
        let evs = vec![note(10.0, 20.0, q, false), note(30.0, 20.0, q, false)];
        let v = hidden_rests(&evs, &others, 1.0, Q::int(4)).unwrap();
        assert_eq!(
            shape(&v[0]),
            vec![(q, true), (q, false), (q, true), (q, false)]
        );
        // a note in no column: its start is not told
        let off = vec![note(10.0, 20.0, q, false), note(25.0, 20.0, q, false)];
        assert!(hidden_rests(&off, &others, 1.0, Q::int(4)).is_none());
        // two notes at once are no one voice
        let two = vec![note(10.0, 20.0, q, false), note(10.0, 24.0, q, false)];
        assert!(hidden_rests(&two, &others, 1.0, Q::int(4)).is_none());
    }

    #[test]
    fn printed_rests_alone_stand_at_their_columns_with_blank_time_between() {
        let (q, e) = (Q::ONE, Q::new(1, 2));
        let others: Vec<Mark> = (0..4).map(|k| mark(10.0 * k as f64, Q::int(k))).collect();
        // an eighth rest on the first beat and one on the third, nothing else printed
        let evs = vec![rest(0.0, 20.0, e), rest(20.0, 20.0, e)];
        let v = hidden_rests(&evs, &others, 1.0, Q::int(4)).unwrap();
        assert_eq!(
            shape(&v[0]),
            vec![(e, false), (q + e, true), (e, false), (q + e, true)]
        );
        // a rest in no column is left
        let off = vec![rest(0.0, 20.0, e), rest(25.0, 20.0, e)];
        assert!(hidden_rests(&off, &others, 1.0, Q::int(4)).is_none());
    }
}