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
//! Which note each tie lands on. A tie is written on the note it leaves (`~`), and the format
//! lands it on its voice's next note or, where that is not of its pitch, on the note of that
//! pitch that starts where the tied note ends in another voice of the part (its staff's or the
//! part's other staff's). Here each tie read from a curve is held against the voices as read:
//! kept where it has such a note to land on, moved to the note of the other voice that shares
//! its head where only that one has, and dropped where neither has: the curve was a slur's,
//! and is written as one, from its note to the note it ends by, unless it ends by its heads as
//! a tie's does.
//! The note a tie lands on is marked (`Ev::landed`): it takes no syllable.
//!
//! A tie that passes over later notes of its own voice (an arpeggio whose notes are each held
//! into the chord that follows) is written `~~`: it lands on the staff's next note at its place,
//! in its bar or the next (`Ev::held`, and `Ev::held_in` on the note it lands on, which takes
//! the pitch it carries).

use std::collections::BTreeSet;

use crate::frac::Q;
use crate::staff::Ev;

/// A bar's voices, staff by staff, or why a staff's could not be timed.
pub type BarVoices = Vec<Result<Vec<Vec<Ev>>, String>>;

/// A note by its bar, staff, voice and index.
type At = (usize, usize, usize, usize);

/// When each of a voice's notes and rests starts, in quarters from the bar's start.
fn onsets(v: &[Ev]) -> Vec<Q> {
    let mut t = Q::ZERO;
    v.iter()
        .map(|e| {
            let at = t;
            t += e.takes();
            at
        })
        .collect()
}

/// Whether a tie on `place` may land on a note: it has the place, with no accidental of its own
/// there (the pitch changes, and the curve is a slur's; one in parentheses only reminds).
fn takes(e: &Ev, place: i32) -> bool {
    e.is_note()
        && e.grace.is_none()
        && e.places.contains(&place)
        && e.accs.get(&place).is_none_or(|a| a.1)
}

/// Every tie of a system's bars settled (`all`: bar -> staff -> its voices; `names`: the staves').
pub fn settle(all: &mut [BarVoices], names: &[String]) {
    let part = |i: usize| names.get(i).map(|n| n.split('.').next().unwrap_or(n));
    let staves = all.first().map_or(0, |b| b.len());
    let voices = |all: &[BarVoices], b: usize, st: usize| -> Option<Vec<Vec<Ev>>> {
        all.get(b)?.get(st)?.as_ref().ok().cloned()
    };
    // where a note that ends at `end` of a bar of length `len` hands over: (bar, onset)
    let after = |b: usize, end: Q, len: Q| match end < len {
        true => (b, end),
        false => (b + 1, Q::ZERO),
    };
    // the notes of the part's voices (but `not`) that start at (bar, onset) and take the place
    let landing = |all: &[BarVoices], st: usize, (b, at): (usize, Q), place: i32, not: At| {
        let mut found: Vec<At> = Vec::new();
        // (its own staff first)
        let order = std::iter::once(st).chain((0..staves).filter(|&j| j != st));
        for j in order.filter(|&j| part(j).is_some() && part(j) == part(st)) {
            let Some(vs) = voices(all, b, j) else {
                continue;
            };
            // (an accidental printed there on the place, on whichever voice's note of a head they
            // share, changes the pitch: no tie lands)
            let mut changed = false;
            for (vi, v) in vs.iter().enumerate() {
                let on = onsets(v);
                for (k, e) in v.iter().enumerate() {
                    let here = on[k] == at && e.is_note() && e.grace.is_none();
                    changed |= here && e.accs.get(&place).is_some_and(|a| !a.1);
                    if here && takes(e, place) && (b, j, vi, k) != not {
                        found.push((b, j, vi, k));
                    }
                }
            }
            if changed {
                found.retain(|f| f.1 != j);
            }
        }
        found.first().copied()
    };
    let mut lands: Vec<(At, i32)> = Vec::new();
    let mut holds: Vec<(At, At, i32)> = Vec::new();
    let mut slurs: Vec<(At, u32)> = Vec::new();
    for b in 0..all.len() {
        for st in 0..staves {
            let Some(vs) = voices(all, b, st) else {
                continue;
            };
            let len = (vs.iter())
                .map(|v| v.iter().map(|e| e.takes()).sum::<Q>())
                .max()
                .unwrap_or(Q::ZERO);
            for (vi, v) in vs.iter().enumerate() {
                let on = onsets(v);
                for (k, e) in v.iter().enumerate() {
                    if !e.is_note() || e.grace.is_some() || e.tied.is_empty() {
                        continue;
                    }
                    let me: At = (b, st, vi, k);
                    // where its note ends, and what its voice has next there: in this bar,
                    // or the first of the next
                    let hands_over = after(b, on[k] + e.takes(), len);
                    // (one that runs off the system's end, or into a bar not read, is kept as
                    // it is: the next system, or the compiler, says)
                    if hands_over.0 >= all.len() || all[hands_over.0][st].is_err() {
                        continue;
                    }
                    let timed = |c: usize, from: usize| -> Vec<(At, bool)> {
                        let v = voices(all, c, st).and_then(|vs| vs.get(vi).cloned());
                        let v = v.unwrap_or_default();
                        (from..v.len())
                            .filter(|&m| v[m].grace.is_none())
                            .map(|m| ((c, st, vi, m), v[m].is_note()))
                            .collect()
                    };
                    let mut ahead = timed(b, k + 1);
                    if b + 1 < all.len() {
                        ahead.extend(timed(b + 1, 0));
                    }
                    // the voice's next note, and whether it follows at once (no rest between)
                    let next = ahead.iter().find(|a| a.1).map(|a| a.0);
                    let direct = ahead.first().is_some_and(|a| a.1);
                    for place in e.tied.clone() {
                        let own = next.filter(|&(c, _, _, m)| {
                            voices(all, c, st).is_some_and(|vs| takes(&vs[vi][m], place))
                        });
                        let to = (own.filter(|_| direct))
                            .or_else(|| landing(all, st, hands_over, place, me));
                        if let Some(to) = to {
                            lands.push((to, place));
                            continue;
                        }
                        // the other voice's note on the same head: the tie is its own, where
                        // that note has one to land on and this has none
                        let sibling = vs.iter().enumerate().find_map(|(wi, w)| {
                            let won = onsets(w);
                            (0..w.len())
                                .find(|&m| {
                                    wi != vi
                                        && won[m] == on[k]
                                        && w[m].is_note()
                                        && w[m].grace.is_none()
                                        && w[m].places.contains(&place)
                                        && !w[m].tied.contains(&place)
                                })
                                .map(|m| (wi, m, after(b, won[m] + w[m].takes(), len)))
                        });
                        let moved = sibling.and_then(|(wi, m, over)| {
                            let to = landing(all, st, over, place, (b, st, wi, m))?;
                            Some(((b, st, wi, m), to))
                        });
                        // (a tie to the voice's next note over a rest stays for the compiler to
                        // refuse: it is then left out, and said)
                        if moved.is_none() && own.is_some() {
                            continue;
                        }
                        // held over the notes that follow, to the staff's next note at its place
                        let ends = (b, on[k] + e.takes());
                        // (only a curve that ends by its heads: a slur over notes that
                        // come back to their first pitch does not)
                        let held = (moved.is_none() && e.tie_close.contains(&place))
                            .then(|| held_landing(all, st, ends, place, me))
                            .flatten();
                        if let Some(to) = held {
                            holds.push((me, to, place));
                            continue;
                        }
                        if moved.is_none() {
                            crate::doubt::tie_dropped(&mut all[hands_over.0][st]);
                            // (the curve was a slur's, unless it ends by its heads as a
                            // tie's does: then a tie whose note was not read)
                            if !e.tie_close.contains(&place) {
                                slurs.extend(e.tie_curves.get(&place).map(|n| (me, *n)));
                            }
                        }
                        if let Ok(now) = &mut all[b][st] {
                            now[vi][k].tied.remove(&place);
                            if let Some(((_, _, wi, m), to)) = moved {
                                now[wi][m].tied.insert(place);
                                lands.push((to, place));
                            }
                        }
                    }
                }
            }
        }
    }
    for ((b, st, vi, k), place) in lands {
        if let Ok(vs) = &mut all[b][st] {
            vs[vi][k].landed.insert(place);
        }
    }
    // a tie that lands on no note was a slur, to the note its curve ends by
    for ((b, st, vi, k), n) in slurs {
        let to = (all.iter_mut().flatten().flatten().flatten().flatten())
            .find(|e| e.curve_ends.contains(&n));
        let Some(to) = to else {
            continue;
        };
        to.slur_close += 1;
        if let Ok(vs) = &mut all[b][st] {
            vs[vi][k].slur_open += 1;
        }
    }
    for (from, to, place) in holds {
        if let Ok(vs) = &mut all[from.0][from.1] {
            vs[from.2][from.3].held.insert(place);
        }
        if let Ok(vs) = &mut all[to.0][to.1] {
            vs[to.2][to.3].landed.insert(place);
            vs[to.2][to.3].held_in.insert(place);
        }
    }
}

/// Where a tie that passes over the notes after it lands: the staff's next note at its place
/// (in whichever voice; the tied note's own first) that starts where the tied note ends or
/// later, in its bar or anywhere in the next. None where the first note there has an accidental
/// of its own (another pitch: the curve was a slur's), or there is none.
fn held_landing(
    all: &[BarVoices],
    st: usize,
    (b, end): (usize, Q),
    place: i32,
    not: At,
) -> Option<At> {
    for c in [b, b + 1] {
        let Some(Ok(vs)) = all.get(c).and_then(|bar| bar.get(st)) else {
            return None;
        };
        // the notes at the place from there on: (onset, another voice's, where)
        let mut at: Vec<(Q, bool, At)> = Vec::new();
        for (vi, v) in vs.iter().enumerate() {
            for (k, (e, on)) in v.iter().zip(onsets(v)).enumerate() {
                let here = e.is_note() && e.grace.is_none() && e.places.contains(&place);
                if here && (c > b || on >= end) && (c, st, vi, k) != not {
                    at.push((on, vi != not.2, (c, st, vi, k)));
                }
            }
        }
        let Some(first) = at.iter().map(|a| a.0).min() else {
            continue;
        };
        at.retain(|a| a.0 == first);
        at.sort_by_key(|a| a.1);
        let takes_it = |a: &(Q, bool, At)| takes(&vs[a.2 .2][a.2 .3], place);
        return at.iter().all(takes_it).then(|| at[0].2);
    }
    None
}

/// Which head of a chord each of the curves that end at it is by (`cys`: the curves' heights;
/// `ys`: the heads'): the curves in order of height take heads in order of height, no two the
/// same one, each within `reach` of its head, with the least distance in all. A chord's ties
/// lie between its heads' own, so one alone may stand nearer its neighbour's head than its own;
/// together they do not. None for a curve where no such choice takes them all (then each takes
/// the head nearest it, if within reach).
pub fn heads_in_order(cys: &[f64], ys: &[f64], reach: f64) -> Vec<Option<usize>> {
    let mut curves: Vec<usize> = (0..cys.len()).collect();
    curves.sort_by(|&a, &b| cys[a].total_cmp(&cys[b]));
    let mut heads: Vec<usize> = (0..ys.len()).collect();
    heads.sort_by(|&a, &b| ys[a].total_cmp(&ys[b]));
    // best[i][j]: the least distance for the first i curves among the first j heads
    let (n, m) = (curves.len(), heads.len());
    let far = f64::MAX / 4.0;
    let off = |i: usize, j: usize| {
        let d = (cys[curves[i]] - ys[heads[j]]).abs();
        if d <= reach {
            d
        } else {
            far
        }
    };
    let mut best = vec![vec![far; m + 1]; n + 1];
    best[0] = vec![0.0; m + 1];
    for i in 1..=n {
        for j in i..=m {
            best[i][j] = best[i][j - 1].min(best[i - 1][j - 1] + off(i - 1, j - 1));
        }
    }
    let mut out = vec![None; n];
    if n <= m && best[n][m] < far {
        let (mut i, mut j) = (n, m);
        while i > 0 {
            if best[i][j] == best[i][j - 1] {
                j -= 1;
            } else {
                out[curves[i - 1]] = Some(heads[j - 1]);
                i -= 1;
                j -= 1;
            }
        }
        return out;
    }
    for (c, o) in out.iter_mut().enumerate() {
        *o = (0..m)
            .min_by(|&a, &b| (ys[a] - cys[c]).abs().total_cmp(&(ys[b] - cys[c]).abs()))
            .filter(|&k| (ys[k] - cys[c]).abs() <= reach);
    }
    out
}

/// Whether a note is reached by ties alone: every one of its places has a tie landing on it
/// (`carried`: the places tied over from the system before, for a system's first note).
pub fn tied_into(e: &Ev, carried: &BTreeSet<i32>) -> bool {
    // (a note a held tie lands on is a new note of its voice's line, and takes its token)
    let landed = |p: &i32| e.landed.contains(p) && !e.held_in.contains(p);
    !e.places.is_empty() && (e.places.iter()).all(|p| landed(p) || carried.contains(p))
}

/// The places tied over a bar's end: those of each voice's last note, where a note ends it.
pub fn over_the_end(voices: &[Vec<Ev>]) -> BTreeSet<i32> {
    (voices.iter())
        .filter_map(|v| v.iter().rev().find(|e| e.grace.is_none()))
        .filter(|e| e.is_note())
        .flat_map(|e| e.tied.iter().copied())
        .collect()
}

/// The places of each voice's last note in a bar (hidden time after it passed over), where the
/// bar has notes at all: what a tie out of it can start from. `None` for a bar of rests only or
/// one not read.
pub fn last_places(voices: &[Vec<Ev>]) -> Option<BTreeSet<i32>> {
    if !voices.iter().flatten().any(|e| e.is_note()) {
        return None;
    }
    let ends = (voices.iter()).filter_map(|v| {
        v.iter()
            .rev()
            .find(|e| e.grace.is_none() && e.rest != crate::staff::Rest::Blank)
    });
    Some(
        ends.filter(|e| e.is_note())
            .flat_map(|e| e.places.iter().copied())
            .collect(),
    )
}

/// Of the notes a flat curve may start by (`starts`, the rightmost first in the reader's
/// choice), one further left whose head stands at the curve's height and whose pitch the note
/// the curve ends by has at that height, where none of the rightmost has: a tie from a chord
/// that reaches past another voice's notes set just after it (two voices' notes beside the
/// chord's tie are not where it starts). Its place across the staff, to choose by.
/// `curve`: its left and right ends, its height and how high it rises.
pub fn start_of_a_tie<'a>(
    starts: &[(usize, usize)],
    notes: &[(usize, usize)],
    ev: impl Fn((usize, usize)) -> &'a Ev,
    curve: (f64, f64, f64, f64),
    sp: f64,
) -> Option<f64> {
    let (x0, x1, cy, rise) = curve;
    if rise >= 1.5 * sp {
        return None;
    }
    // the heads of the notes it ends by (one with a head at its end, at its height)
    let ends: Vec<f64> = (notes.iter())
        .filter(|&&t| {
            (ev(t).heads.iter())
                .any(|h| (h.x0 - x1).abs() < 1.5 * sp && (h.y - cy).abs() < 1.0 * sp)
        })
        .flat_map(|&t| ev(t).heads.iter().map(|h| h.y))
        .collect();
    let ties = |t: (usize, usize)| {
        (ev(t).heads.iter()).any(|h| {
            (h.y - cy).abs() < 1.0 * sp
                && h.x1 < x1 - sp
                && ends.iter().any(|y| (y - h.y).abs() < 0.2 * sp)
        })
    };
    // (none of the rightmost has the pitch the curve lands on at all)
    let lands = |t: (usize, usize)| {
        (ev(t).heads.iter()).any(|h| ends.iter().any(|y| (y - h.y).abs() < 0.2 * sp))
    };
    let right = starts.iter().map(|&t| ev(t).x).fold(f64::MIN, f64::max);
    if starts.iter().any(|&t| ev(t).x > right - sp && lands(t)) {
        return None;
    }
    // (a tie starts just past its own note's heads)
    let past = |t: (usize, usize)| (x0 - ev(t).right()).abs() < 0.6 * sp;
    let tied: Vec<(usize, usize)> = (starts.iter().copied())
        .filter(|&t| ties(t) && past(t))
        .collect();
    let [t] = tied.as_slice() else {
        return None;
    };
    // (the notes it passes are another voice's, stemmed the other way: not grace notes a slur
    // goes to, nor the tied note's own voice going on)
    let other = |u: (usize, usize)| {
        let (a, b) = (ev(*t), ev(u));
        b.grace.is_none() && matches!((a.up, b.up), (Some(p), Some(q)) if p != q)
    };
    // (and stand further from the curve's height than the tied note's head: a head as near
    // it may be where the curve starts)
    let dy = |u: (usize, usize)| {
        (ev(u).heads.iter())
            .map(|h| (h.y - cy).abs())
            .fold(f64::MAX, f64::min)
    };
    (starts.iter().copied())
        .filter(|&u| ev(u).x > right - sp)
        .all(|u| other(u) && dy(u) > dy(*t) + 0.4 * sp)
        .then(|| ev(*t).x)
}

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

    #[test]
    fn a_tie_out_of_a_bar_starts_from_a_voice_s_last_note() {
        let blank = Ev::spacer(Q::ONE, 9.0);
        let v = vec![
            vec![note(0.0, 30, Q::ONE), note(4.0, 32, Q::ONE), blank],
            vec![note(0.0, 20, Q::int(2))],
        ];
        assert_eq!(last_places(&v), Some(BTreeSet::from([20, 32])));
        // a voice that ends on a rest ends on no note
        let mut rest = Ev::spacer(Q::ONE, 9.0);
        rest.rest = crate::staff::Rest::Bar;
        let v = vec![vec![note(0.0, 30, Q::ONE), rest]];
        assert_eq!(last_places(&v), Some(BTreeSet::new()));
        // a bar of rests (or one left unread, written as a rest) says nothing
        assert_eq!(last_places(&[vec![Ev::spacer(Q::int(4), 0.0)]]), None);
    }

    #[test]
    fn a_chord_s_tie_reaches_past_another_voice_s_note_set_after_it() {
        let head = |x: f64, y: f64| Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y,
            size: 4.0,
        };
        // a second stemmed up (heads side by side), the other voice's note a space under it
        // just after, and the same second in the next bar: a flat curve from past the chord
        // to the second is the chord's tie, though the other note stands nearer its start
        let bar = vec![
            vec![
                Ev::new(vec![head(0.0, 10.0), head(1.2, 9.5)], None, Some(true)),
                Ev::new(vec![head(3.0, 11.0)], None, Some(false)),
            ],
            vec![Ev::new(
                vec![head(10.0, 10.0), head(11.2, 9.5)],
                None,
                Some(true),
            )],
        ];
        let ev = |t: (usize, usize)| &bar[t.0][t.1];
        let notes = [(0, 0), (0, 1), (1, 0)];
        let curve = (2.6, 10.0, 9.0, 0.5);
        let from = start_of_a_tie(&notes[..2], &notes, ev, curve, 1.0);
        assert_eq!(from, Some(0.0));
        // the note after the chord has the pitch the curve lands on: it may start there
        let mut bar2 = bar.clone();
        bar2[0][1] = Ev::new(vec![head(3.0, 10.0)], None, Some(false));
        let ev = |t: (usize, usize)| &bar2[t.0][t.1];
        assert_eq!(start_of_a_tie(&notes[..2], &notes, ev, curve, 1.0), None);
    }

    fn note(x: f64, place: i32, dur: Q) -> Ev {
        let g = Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y: 0.0,
            size: 4.0,
        };
        let mut e = Ev::new(vec![g], None, Some(true));
        e.dur = dur;
        e.places = vec![place];
        e.place_of = vec![place];
        e
    }

    fn tied(mut e: Ev) -> Ev {
        e.tied = e.places.iter().copied().collect();
        e.tie_close = e.tied.clone();
        e
    }

    fn names() -> Vec<String> {
        vec!["P.1".to_string(), "P.2".to_string()]
    }

    #[test]
    fn the_ties_into_a_close_chord_take_its_heads_in_order() {
        // three heads 5 apart; the middle tie stands nearer the top head than its own
        let ys = [20.0, 15.0, 27.5];
        assert_eq!(
            heads_in_order(&[32.0, 10.0, 15.2], &ys, 15.0),
            vec![Some(2), Some(1), Some(0)]
        );
        // one curve alone takes the nearest head, and none too far off
        assert_eq!(heads_in_order(&[15.2], &ys, 15.0), vec![Some(1)]);
        assert_eq!(heads_in_order(&[60.0], &ys, 15.0), vec![None]);
        // more curves than heads: each its nearest
        assert_eq!(
            heads_in_order(&[14.0, 16.0], &[15.0], 15.0),
            vec![Some(0); 2]
        );
    }

    #[test]
    fn a_tie_over_the_barline_lands_in_another_voice() {
        // one voice, its last note (d5) tied; the next bar's upper voice starts on a4 and its
        // lower on d5: the tie lands on the lower voice's d5, which takes no syllable
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![vec![
                note(0.0, 30, Q::ONE),
                tied(note(10.0, 36, Q::ONE)),
            ]])],
            vec![Ok(vec![
                vec![note(20.0, 33, Q::int(2))],
                vec![note(20.0, 36, Q::int(2))],
            ])],
        ];
        settle(&mut all, &names()[..1]);
        assert!(all[0][0].as_ref().unwrap()[0][1].tied.contains(&36));
        let to = &all[1][0].as_ref().unwrap()[1][0];
        assert!(tied_into(to, &BTreeSet::new()));
        assert!(!tied_into(
            &all[1][0].as_ref().unwrap()[0][0],
            &BTreeSet::new()
        ));
        // where the lower voice's d5 has an accidental of its own, the curve was no tie
        let mut own = note(20.0, 36, Q::int(2));
        own.accs.insert(36, (1, false));
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![vec![tied(note(10.0, 36, Q::int(2)))]])],
            vec![Ok(vec![vec![note(20.0, 33, Q::int(2))], vec![own]])],
        ];
        settle(&mut all, &names()[..1]);
        assert!(all[0][0].as_ref().unwrap()[0][0].tied.is_empty());
    }

    #[test]
    fn a_tie_held_over_the_notes_that_follow_lands_on_the_next_note_at_its_place() {
        // an arpeggio a2 e3 g3 c4 g3 e3, its last three notes each tied into the next bar's
        // chord: the last note's tie is a plain one, the two before it are held over
        let eighth = Q::new(1, 2);
        let arp = |places: [i32; 6], tied_from: usize| -> Vec<Ev> {
            let note = |(i, p): (usize, &i32)| {
                let e = note(10.0 * i as f64, *p, eighth);
                if i >= tied_from {
                    tied(e)
                } else {
                    e
                }
            };
            places.iter().enumerate().map(note).collect()
        };
        let chord = |accidental: bool| {
            let mut e = note(70.0, 23, Q::int(3));
            e.places = vec![23, 25, 28];
            e.place_of = vec![23, 25, 28];
            if accidental {
                e.accs.insert(28, (0, false));
            }
            e
        };
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![arp([19, 23, 25, 28, 25, 23], 3)])],
            vec![Ok(vec![vec![chord(false)]])],
        ];
        settle(&mut all, &names()[..1]);
        let v = &all[0][0].as_ref().unwrap()[0];
        let held = |k: usize| v[k].held.iter().copied().collect::<Vec<i32>>();
        assert_eq!((held(3), held(4), held(5)), (vec![28], vec![25], vec![]));
        assert!(v[5].tied.contains(&23) && v[2].tied.is_empty());
        let to = &all[1][0].as_ref().unwrap()[0][0];
        assert_eq!(to.held_in, [25, 28].into_iter().collect());
        // (for the words it is a note like any other: it takes a token)
        assert!(to.landed.contains(&23) && !tied_into(to, &BTreeSet::new()));
        // where the chord's note has an accidental of its own, that curve was no tie
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![arp([19, 23, 25, 28, 25, 23], 3)])],
            vec![Ok(vec![vec![chord(true)]])],
        ];
        settle(&mut all, &names()[..1]);
        let v = &all[0][0].as_ref().unwrap()[0];
        assert!(v[3].tied.is_empty() && v[3].held.is_empty());
        assert_eq!(v[4].held, [25].into_iter().collect());
        // it lands on the first note at its place and no later one: a note of the place
        // between, with another tie's or none, is where it stops
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![arp([28, 23, 25, 28, 25, 23], 0)])],
            vec![Ok(vec![vec![chord(false)]])],
        ];
        settle(&mut all, &names()[..1]);
        let v = &all[0][0].as_ref().unwrap()[0];
        assert!(v[0].held.contains(&28) && v[3].landed.contains(&28));
        assert!(v[3].held.contains(&28));
    }

    #[test]
    fn no_tie_lands_on_a_head_two_voices_share_under_an_accidental() {
        // the next bar's two voices share a head with a natural, read on the upper voice's note
        let mut upper = note(20.0, 28, Q::ONE);
        upper.accs.insert(28, (0, false));
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![vec![tied(note(10.0, 28, Q::int(2)))]])],
            vec![Ok(vec![
                vec![upper, note(30.0, 30, Q::ONE)],
                vec![note(20.0, 28, Q::int(2))],
            ])],
        ];
        settle(&mut all, &names()[..1]);
        assert!(all[0][0].as_ref().unwrap()[0][0].tied.is_empty());
        assert!(all[1][0].as_ref().unwrap()[1][0].landed.is_empty());
    }

    #[test]
    fn only_a_voices_last_note_is_tied_over_the_bars_end() {
        // the upper voice ends tied; the lower's tied note is followed by a rest
        let mut rest = Ev::spacer(Q::ONE, 5.0);
        rest.rest = crate::staff::Rest::Blank;
        let voices = vec![
            vec![note(0.0, 30, Q::ONE), tied(note(10.0, 33, Q::ONE))],
            vec![tied(note(0.0, 28, Q::ONE)), rest],
        ];
        assert_eq!(over_the_end(&voices), [33].into_iter().collect());
    }

    #[test]
    fn a_tie_inside_a_bar_lands_where_its_note_ends() {
        // the lower voice's c4 quarter is tied; its own next note is e4, and the upper voice has
        // a c4 on the second quarter: the tie lands there. To a c4 half a quarter later it is
        // held over (`~~`)
        let upper = |x: f64, rest: Q| {
            let mut blank = Ev::spacer(rest, 0.0);
            blank.rest = crate::staff::Rest::Blank;
            vec![blank, note(x, 28, Q::int(2) - rest)]
        };
        let lower = vec![tied(note(0.0, 28, Q::ONE)), note(10.0, 30, Q::ONE)];
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![upper(10.0, Q::ONE), lower.clone()])],
            vec![Ok(vec![vec![note(30.0, 30, Q::int(2))]])],
        ];
        settle(&mut all, &names()[..1]);
        let vs = all[0][0].as_ref().unwrap();
        assert!(vs[1][0].tied.contains(&28) && vs[0][1].landed.contains(&28));
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![upper(15.0, Q::new(3, 2)), lower])],
            vec![Ok(vec![vec![note(30.0, 30, Q::int(2))]])],
        ];
        settle(&mut all, &names()[..1]);
        let vs = all[0][0].as_ref().unwrap();
        assert!(vs[1][0].held.contains(&28) && vs[0][1].held_in.contains(&28));
    }

    #[test]
    fn a_tie_lands_on_the_parts_other_staff() {
        // the right hand's c4 is tied into the next bar, where the left hand has it
        let mut all: Vec<BarVoices> = vec![
            vec![
                Ok(vec![vec![tied(note(0.0, 28, Q::int(2)))]]),
                Ok(vec![vec![note(0.0, 14, Q::int(2))]]),
            ],
            vec![
                Ok(vec![vec![note(20.0, 35, Q::int(2))]]),
                Ok(vec![vec![note(20.0, 28, Q::int(2))]]),
            ],
        ];
        settle(&mut all, &names());
        assert!(all[0][0].as_ref().unwrap()[0][0].tied.contains(&28));
        assert!(all[1][1].as_ref().unwrap()[0][0].landed.contains(&28));
    }

    #[test]
    fn a_tie_given_to_the_wrong_one_of_two_voices_on_a_head_is_the_others() {
        // two voices share a head: the upper's quarter, then a rest; the lower's half, then the
        // same note again. The curve was given to the upper's note, which has nothing to land on
        let mut rest = Ev::spacer(Q::ONE, 5.0);
        rest.rest = crate::staff::Rest::Printed(note(5.0, 0, Q::ONE).heads[0]);
        let mut all: Vec<BarVoices> = vec![
            vec![Ok(vec![
                vec![tied(note(0.0, 30, Q::ONE)), rest],
                vec![note(0.0, 30, Q::int(2))],
            ])],
            vec![Ok(vec![
                vec![note(20.0, 33, Q::int(2))],
                vec![note(20.0, 30, Q::int(2))],
            ])],
        ];
        settle(&mut all, &names()[..1]);
        let vs = all[0][0].as_ref().unwrap();
        assert!(vs[0][0].tied.is_empty() && vs[1][0].tied.contains(&30));
        assert!(all[1][0].as_ref().unwrap()[1][0].landed.contains(&30));
    }

    // one bar of three quarter notes at the given places
    fn three(places: [i32; 3]) -> Vec<BarVoices> {
        let v = (places.iter().enumerate())
            .map(|(i, &p)| note(4.0 * i as f64, p, Q::ONE))
            .collect();
        vec![vec![Ok(vec![v])]]
    }

    #[test]
    fn a_tie_that_lands_on_no_note_is_the_slur_its_curve_was() {
        let mut all = three([30, 32, 30]);
        {
            let vs = all[0][0].as_mut().unwrap();
            vs[0][0].tied.insert(30);
            vs[0][0].tie_curves.insert(30, 7);
            vs[0][2].curve_ends = vec![7];
        }
        settle(&mut all, &["V".to_string()]);
        let v = &all[0][0].as_ref().unwrap()[0];
        // no tie any more, a slur from the tied note to the note the curve ends by
        assert!(v[0].tied.is_empty());
        assert_eq!((v[0].slur_open, v[0].slur_close), (1, 0));
        assert_eq!((v[2].slur_open, v[2].slur_close), (0, 1));
        // the note between is as it was
        assert!(v[1].tied.is_empty() && v[1].landed.is_empty());
        assert_eq!((v[1].slur_open, v[1].slur_close), (0, 0));
    }

    #[test]
    fn a_tie_whose_curve_ends_by_its_heads_is_no_slur() {
        let mut all = three([30, 32, 30]);
        {
            let vs = all[0][0].as_mut().unwrap();
            vs[0][0].tied.insert(30);
            vs[0][0].tie_close.insert(30);
            vs[0][0].tie_curves.insert(30, 7);
            vs[0][2].curve_ends = vec![7];
        }
        settle(&mut all, &["V".to_string()]);
        let v = &all[0][0].as_ref().unwrap()[0];
        assert_eq!((v[0].slur_open, v[0].slur_close), (0, 0));
        assert_eq!((v[2].slur_open, v[2].slur_close), (0, 0));
        // (what it became: a tie held over the note between, to the third note at its place)
        assert!(v[0].held.contains(&30));
        assert!(v[2].landed.contains(&30) && v[2].held_in.contains(&30));
    }

    #[test]
    fn a_tie_that_lands_makes_no_slur() {
        let mut v = vec![note(0.0, 30, Q::ONE), note(4.0, 30, Q::ONE)];
        v[0].tied.insert(30);
        v[0].tie_curves.insert(30, 3);
        v[1].curve_ends = vec![3];
        let mut all: Vec<BarVoices> = vec![vec![Ok(vec![v])]];
        settle(&mut all, &["V".to_string()]);
        let v = &all[0][0].as_ref().unwrap()[0];
        assert!(v[0].tied.contains(&30));
        assert!(v[1].landed.contains(&30));
        assert!(v.iter().all(|e| e.slur_open == 0 && e.slur_close == 0));
    }

    #[test]
    fn a_tie_to_a_note_with_its_own_accidental_is_a_slur() {
        let mut v = vec![note(0.0, 30, Q::ONE), note(4.0, 30, Q::ONE)];
        v[0].tied.insert(30);
        v[0].tie_curves.insert(30, 1);
        v[1].curve_ends = vec![1];
        v[1].accs.insert(30, (1, false));
        let mut all: Vec<BarVoices> = vec![vec![Ok(vec![v])]];
        settle(&mut all, &["V".to_string()]);
        let v = &all[0][0].as_ref().unwrap()[0];
        assert!(v[0].tied.is_empty());
        assert_eq!(v[0].slur_open, 1);
        assert_eq!(v[1].slur_close, 1);
    }
}