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
//! Columns: an engraver sets what sounds together one above the other through all the staves
//! of a system, and what starts later further right. Each staff's bar is timed on its own from
//! its notes' lengths; here a bar's staves as read are checked against one another by where
//! their notes stand. A staff whose reading its own columns or the other staves' contradict is
//! misread, and the reader then knows it.

use crate::frac::Q;
use crate::staff::{Ev, Rest};

/// Voices of one staff set side by side at one start (a second or a unison between them, the
/// second voice moved past the first's head) stand no further apart than this, in staff spaces.
const BESIDE: f64 = 2.2;
/// The same past a dotted note's dots, or a note's flag.
const BESIDE_PAST: f64 = 3.3;
/// A note set beside another stands this much further off for its own accidental.
const ACCIDENTAL: f64 = 1.3;
/// The columns of two staves at one start stand no further apart than this (a staff whose only
/// chord there is set a head's width aside).
const APART: f64 = 1.8;
/// What starts later stands at least this far right of what starts before it.
const ON: f64 = 0.3;

/// Why a staff's bar is left unread by this check.
pub const MISREAD: &str = "notes that do not stand where the bar's other notes say they start";

/// A note that starts at a time: where it stands, and when it starts in quarters from the
/// bar's start.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mark {
    pub x: f64,
    pub at: Q,
    /// How far right of `x` its column may be: a stemless chord with a second in it has heads
    /// both sides of the stem it has not, and which side is the column's is not told.
    pub play: f64,
    /// Dotted, or with a flag: another voice's note set beside it stands past the dots or flag.
    pub wide: bool,
    /// With an accidental before it.
    pub sign: bool,
}

/// Where a note's column is: its head's left edge as its stem says (a head set across the stem,
/// a second, does not move it); a rest's or a whole note's, its own left edge.
pub fn column_x(e: &Ev) -> f64 {
    let w = e.heads.iter().map(|h| h.x1 - h.x0).fold(0.0, f64::max);
    match (&e.rest, e.stem, e.up) {
        (Rest::None, Some(s), Some(true)) => s.x - w,
        (Rest::None, Some(s), Some(false)) => s.x,
        _ => e.x,
    }
}

/// The marks of a staff's voices: its notes with their starts. Grace notes take no time; rests
/// are left out, for a rest alone is set in the bar's middle and some programs set others off
/// their columns.
pub fn marks(voices: &[Vec<Ev>]) -> Vec<Mark> {
    let mut out = Vec::new();
    for v in voices {
        let mut t = Q::ZERO;
        for e in v {
            if e.is_note() && e.grace.is_none() {
                let lefts = || e.heads.iter().map(|h| h.x0);
                let play = match e.stem {
                    None => lefts().fold(f64::MIN, f64::max) - lefts().fold(f64::MAX, f64::min),
                    Some(_) => 0.0,
                };
                let written = e.written();
                let flagged = written < Q::ONE && e.beam_polys.is_empty();
                out.push(Mark {
                    x: column_x(e),
                    at: t,
                    play: play.max(0.0),
                    wide: flagged || !written.is_power_of_two(),
                    sign: !e.accs.is_empty(),
                });
            }
            t += e.takes();
        }
    }
    out
}

/// A staff's columns: each start with the leftmost of what starts then, in order of time.
pub fn columns(marks: &[Mark]) -> Vec<Mark> {
    let mut cols: Vec<Mark> = Vec::new();
    for m in marks {
        match cols.iter_mut().find(|c| c.at == m.at) {
            Some(c) if m.x < c.x => *c = *m,
            Some(_) => {}
            None => cols.push(*m),
        }
    }
    cols.sort_by_key(|c| c.at);
    cols
}

/// A staff's marks contradict themselves: two starts whose columns do not stand in order, or
/// something far right of the column it is said to start with.
pub fn contradicts_itself(marks: &[Mark], sp: f64) -> bool {
    let cols = columns(marks);
    cols.windows(2).any(|w| w[1].x - w[0].x < ON * sp)
        || marks
            .iter()
            .any(|m| cols.iter().any(|c| c.at == m.at && !beside(c, m, sp)))
}

/// Whether a mark stands near enough its staff's column of the same start to be another voice's
/// note set beside it.
fn beside(col: &Mark, m: &Mark, sp: f64) -> bool {
    let reach = if col.wide { BESIDE_PAST } else { BESIDE };
    let sign = if m.sign { ACCIDENTAL } else { 0.0 };
    m.x - col.x <= (reach + sign) * sp + col.play
}

/// Whether two staves' columns of one start stand one above the other.
fn above(p: &Mark, q: &Mark, sp: f64) -> bool {
    let (l, r) = if p.x <= q.x { (p, q) } else { (q, p) };
    r.x - l.x <= APART * sp + l.play
}

/// Two staves' columns contradict each other: one start at two places, or a later start not
/// right of an earlier one.
pub fn contradict(a: &[Mark], b: &[Mark], sp: f64) -> bool {
    a.iter().any(|p| {
        b.iter().any(|q| match p.at.cmp(&q.at) {
            std::cmp::Ordering::Equal => !above(p, q, sp),
            std::cmp::Ordering::Less => q.x - p.x < ON * sp,
            std::cmp::Ordering::Greater => p.x - q.x < ON * sp,
        })
    })
}

/// How far a staff's reading is from sure, for choosing between staves that contradict each
/// other with none left to say: one whose voices do not all last the bar, then one with blank
/// time (a guess at hidden rests), then the one of more voices.
fn doubt(voices: &[Vec<Ev>], held: Q) -> (bool, bool, usize) {
    let total = |v: &Vec<Ev>| v.iter().map(|e| e.takes()).sum::<Q>();
    (
        voices
            .iter()
            .any(|v| v.iter().any(|e| e.is_note()) && total(v) != held),
        voices.iter().flatten().any(|e| e.rest == Rest::Blank),
        voices.len(),
    )
}

/// The staves of one bar that are misread by their columns: each staff's voices as read (`None`
/// for a staff not read), and for each whether its reading stands contradicted. A staff that
/// contradicts itself is; then, while staves contradict each other, the one most others
/// contradict (of several as much contradicted, the least sure; all of them where none is
/// surer).
#[allow(dead_code)]
pub fn misread(staves: &[Option<&[Vec<Ev>]>], sp: f64) -> Vec<bool> {
    misread_in(staves, sp, &[])
}

/// A staff's marks with their starts in the top staff's time: `scale` is how much longer the
/// top staff's bar is than this staff's (staves printed in different times agree in proportion,
/// a beat of one against a beat of the other).
fn scaled(mut marks: Vec<Mark>, scale: Option<&Q>) -> Vec<Mark> {
    if let Some(&k) = scale.filter(|k| **k != Q::ONE) {
        for m in marks.iter_mut() {
            m.at = m.at * k;
        }
    }
    marks
}

/// [`misread`], each staff in its own time (`scales`: `times::scales`; none, every staff in one).
pub fn misread_in(staves: &[Option<&[Vec<Ev>]>], sp: f64, scales: &[Q]) -> Vec<bool> {
    let all: Vec<Vec<Mark>> = staves
        .iter()
        .enumerate()
        .map(|(i, s)| scaled(s.map(marks).unwrap_or_default(), scales.get(i)))
        .collect();
    let mut bad: Vec<bool> = all.iter().map(|m| contradicts_itself(m, sp)).collect();
    let cols: Vec<Vec<Mark>> = all.iter().map(|m| columns(m)).collect();
    let scale = |i: usize| scales.get(i).copied().unwrap_or(Q::ONE);
    let held = staves
        .iter()
        .enumerate()
        .filter_map(|(i, s)| s.map(|vs| (i, vs)))
        .flat_map(|(i, vs)| vs.iter().map(move |v| (i, v)))
        .filter(|(_, v)| v.iter().any(|e| e.is_note()))
        .map(|(i, v)| v.iter().map(|e| e.takes()).sum::<Q>() * scale(i))
        .max()
        .unwrap_or(Q::ZERO);
    loop {
        let live: Vec<usize> = (0..staves.len()).filter(|&i| !bad[i]).collect();
        let against = |i: usize| {
            live.iter()
                .filter(|&&j| j != i && contradict(&cols[i], &cols[j], sp))
                .count()
        };
        let counts: Vec<(usize, usize)> = live.iter().map(|&i| (i, against(i))).collect();
        let most = counts.iter().map(|c| c.1).max().unwrap_or(0);
        if most == 0 {
            return bad;
        }
        let worst: Vec<usize> = counts.iter().filter(|c| c.1 == most).map(|c| c.0).collect();
        let doubt_of = |i: usize| staves[i].map(|vs| doubt(vs, held / scale(i)));
        let top = worst.iter().map(|&i| doubt_of(i)).max().flatten();
        for i in worst {
            if doubt_of(i) == top {
                bad[i] = true;
            }
        }
    }
}

/// The first contradiction a staff's marks are in, in words: with itself, or with one of the
/// other staves' marks.
fn first_contradiction(mine: &[Mark], others: &[&[Mark]], sp: f64) -> String {
    let cols = columns(mine);
    let said = |p: &Mark, q: &Mark| {
        format!(
            "the start at {} stands {:.1} spaces from the start at {}",
            p.at,
            (p.x - q.x) / sp,
            q.at
        )
    };
    if let Some(w) = cols.windows(2).find(|w| w[1].x - w[0].x < ON * sp) {
        return said(&w[1], &w[0]);
    }
    for m in mine {
        if let Some(c) = cols.iter().find(|c| c.at == m.at && !beside(c, m, sp)) {
            return said(m, c);
        }
    }
    for o in others {
        for p in &cols {
            for q in columns(o) {
                if contradict(&[*p], &[q], sp) {
                    return format!("{} on another staff", said(p, &q));
                }
            }
        }
    }
    String::new()
}

/// A note stands in a column of another staff when no further from it than this.
const IN_COLUMN: f64 = 0.7;

/// The start a column gives a note at `x`: that of the nearest column it stands in, of the
/// other staves' and of its own staff's other voices'. (A note set beside another voice's is in
/// no column: a note a sixteenth later stands as near.)
fn start_at(x: f64, others: &[Mark], own: &[Mark], sp: f64) -> Option<Q> {
    others
        .iter()
        .chain(own)
        .filter(|m| (m.x - x).abs() <= IN_COLUMN * sp)
        .min_by(|a, b| (a.x - x).abs().total_cmp(&(b.x - x).abs()))
        .map(|m| m.at)
}

/// Whether a note at `x` may start at `t` by where the columns stand: after those left of it
/// and before those right of it, or with one of them if it does not stand clear of it.
fn in_order(x: f64, t: Q, others: &[Mark], own: &[Mark], sp: f64) -> bool {
    let ok = |m: &Mark, clear: f64| {
        let dx = x - m.x;
        if dx > IN_COLUMN * sp {
            t > m.at || (t == m.at && dx <= clear * sp)
        } else if dx < -IN_COLUMN * sp {
            t < m.at || (t == m.at && -dx <= clear * sp)
        } else {
            true
        }
    };
    others.iter().all(|m| ok(m, APART)) && own.iter().all(|m| ok(m, BESIDE_PAST + ACCIDENTAL))
}

/// A staff's voices timed again by the columns: each voice's notes and rests run on one after
/// another as printed, and every note that stands in a column (the other staves' as read,
/// `others`, and those of its own staff's voices already timed) starts with it. Where that is
/// later than the voice has run to, the time between is blank (a program hides a voice's rests:
/// where it enters late, ends early, or rests between its notes). The blank time goes where
/// the columns leave it one place: before the voice's first note or after its last if it may,
/// else before the one note where the notes after it then stand in order among the columns. It
/// does not follow a rest, nor a note that a dot would lengthen by as much: then a dot may have
/// been missed, which is not told. Where no place or more than one is left there is no such
/// reading, nor for a voice with blank time as read and no note in any column.
pub fn retimed(voices: &[Vec<Ev>], others: &[Mark], bar_len: Q, sp: f64) -> Option<Vec<Vec<Ev>>> {
    let blank = |v: &Vec<Ev>| v.iter().any(|e| e.rest == Rest::Blank);
    // the voices read without blank time first: the others may stand in their columns
    let mut order: Vec<usize> = (0..voices.len()).collect();
    order.sort_by_key(|&i| blank(&voices[i]));
    let mut own: Vec<Mark> = Vec::new();
    let mut out: Vec<Vec<Ev>> = vec![Vec::new(); voices.len()];
    for i in order {
        let run: Vec<Ev> = voices[i]
            .iter()
            .filter(|e| e.rest != Rest::Blank)
            .cloned()
            .collect();
        let n = run.len();
        // what the voice has run to before each of its notes and rests, and at its end
        let mut before = vec![Q::ZERO; n + 1];
        for k in 0..n {
            before[k + 1] = before[k] + run[k].takes();
        }
        let timed = |k: usize| run[k].is_note() && run[k].grace.is_none();
        // the notes that stand in a column, each with how much later it starts than run to
        let fixed: Vec<(usize, Q)> = (0..n)
            .filter(|&k| timed(k))
            .filter_map(|k| {
                start_at(column_x(&run[k]), others, &own, sp).map(|at| (k, at - before[k]))
            })
            .collect();
        if fixed.is_empty() {
            if blank(&voices[i]) {
                return None;
            }
            own.extend(marks(std::slice::from_ref(&run)));
            out[i] = run;
            continue;
        }
        // the stretches between them, with the bar's start and end: (from, to, blank so far,
        // blank to place)
        let mut spans: Vec<(usize, usize, Q, Q)> = Vec::new();
        let (mut from, mut shift) = (0, Q::ZERO);
        for &(k, s) in &fixed {
            spans.push((from, k, shift, s - shift));
            (from, shift) = (k + 1, s);
        }
        spans.push((from, n, shift, bar_len - before[n] - shift));
        let mut gaps: Vec<(usize, Q)> = Vec::new();
        for (si, &(from, to, shift, gap)) in spans.iter().enumerate() {
            if gap < Q::ZERO {
                return None;
            }
            if gap.is_zero() {
                continue;
            }
            crate::write::plain_lengths(gap).ok()?;
            let (first, last) = (si == 0, si + 1 == spans.len());
            // blank before the note or rest `j` of the stretch (or after its last)
            let may = |j: usize| {
                let follows = run[..j].iter().rev().find(|e| e.grace.is_none());
                let after_ok = match follows {
                    _ if j > 0 && run[j - 1].grace.is_some() => false,
                    None => true,
                    Some(_) if last && j == n => true,
                    Some(p) => {
                        let dot = p.written() / Q::int(2);
                        p.is_note() && gap != dot && gap != dot + dot / Q::int(2)
                    }
                };
                after_ok
                    && (from..to.min(n)).filter(|&m| timed(m)).all(|m| {
                        let t = before[m] + shift + if m >= j { gap } else { Q::ZERO };
                        in_order(column_x(&run[m]), t, others, &own, sp)
                    })
            };
            let lo = if first { 0 } else { from.max(1) };
            let places: Vec<usize> = (lo..=to).filter(|&j| may(j)).collect();
            let at = match places[..] {
                _ if first && places.contains(&0) => 0,
                _ if last && places.contains(&n) => n,
                [j] => j,
                _ => return None,
            };
            gaps.push((at, gap));
        }
        let mut v = Vec::new();
        for (k, e) in run.iter().enumerate() {
            if let Some(g) = gaps.iter().find(|g| g.0 == k) {
                v.push(Ev::spacer(g.1, e.x - 0.01));
            }
            v.push(e.clone());
        }
        if let Some(g) = gaps.iter().find(|g| g.0 == n) {
            v.push(Ev::spacer(g.1, run.last().map_or(0.0, |e| e.x) + 0.01));
        }
        own.extend(marks(std::slice::from_ref(&v)));
        out[i] = v;
    }
    Some(out)
}

/// One bar's staves as read: one misread by its columns is timed again by the columns of the
/// staves that are not, if that makes a reading nothing contradicts in which one voice at least
/// fills the bar with what is printed; else it is left unread.
#[allow(dead_code)]
pub fn unread_misread(staves: &mut [Result<Vec<Vec<Ev>>, String>], sp: f64) {
    unread_misread_in(staves, sp, &[])
}

/// [`unread_misread`], each staff in its own time (`scales`: `times::scales`; none, every staff
/// in one): the starts are held against each other in the top staff's time, and a staff is timed
/// again by the others' columns as they fall in its own.
pub fn unread_misread_in(staves: &mut [Result<Vec<Vec<Ev>>, String>], sp: f64, scales: &[Q]) {
    let scales = match scales.iter().all(|k| *k == Q::ONE) {
        true => &[],
        false => scales,
    };
    // (a program may instead set staves in different times quarter for quarter, the shorter
    // bar ending early: MuseScore does. The columns say which: the way fewer staves are
    // contradicted, in proportion where they say nothing. Set so, a staff is not timed again by
    // the others: what they hold of the bar is not what it holds)
    let own_times = !scales.is_empty();
    let scales = {
        let v: Vec<Option<&[Vec<Ev>]>> = staves.iter().map(|s| s.as_deref().ok()).collect();
        let bad = |k: &[Q]| misread_in(&v, sp, k).iter().filter(|b| **b).count();
        match scales.is_empty() || bad(scales) <= bad(&[]) {
            true => scales,
            false => &[],
        }
    };
    let by_quarters = own_times && scales.is_empty();
    let scale = |i: usize| scales.get(i).copied().unwrap_or(Q::ONE);
    let views = |r: &[Option<Vec<Vec<Ev>>>]| -> Vec<bool> {
        let v: Vec<Option<&[Vec<Ev>]>> = r.iter().map(|s| s.as_deref()).collect();
        misread_in(&v, sp, scales)
    };
    let mut now: Vec<Option<Vec<Vec<Ev>>>> =
        staves.iter().map(|s| s.as_ref().ok().cloned()).collect();
    let bad = views(&now);
    if !bad.iter().any(|&b| b) {
        return;
    }
    let all: Vec<Vec<Mark>> = now
        .iter()
        .enumerate()
        .map(|(i, s)| scaled(s.as_deref().map(marks).unwrap_or_default(), scales.get(i)))
        .collect();
    // what the staves not misread hold of the bar, and their columns
    let held = (0..now.len())
        .filter(|&j| !bad[j])
        .filter_map(|j| now[j].as_ref().map(|vs| (j, vs)))
        .flat_map(|(j, vs)| vs.iter().map(move |v| (j, v)))
        .filter(|(_, v)| v.iter().any(|e| e.is_note()))
        .map(|(j, v)| v.iter().map(|e| e.takes()).sum::<Q>() * scale(j))
        .max();
    let mut others: Vec<Mark> = (0..now.len())
        .filter(|&j| !bad[j])
        .flat_map(|j| columns(&all[j]))
        .collect();
    for i in 0..staves.len() {
        if !bad[i] {
            continue;
        }
        // (the others' columns as they fall in this staff's own time)
        let theirs = scaled(others.clone(), Some(&(Q::ONE / scale(i))));
        let again = held
            .filter(|_| !by_quarters)
            .zip(now[i].as_ref())
            .and_then(|(held, vs)| retimed(vs, &theirs, held / scale(i), sp))
            // a program hides the rests of a second voice, not of a staff's only one: where
            // no voice fills the bar with what is printed, notes are missing
            .filter(|vs| vs.iter().any(|v| !v.iter().any(|e| e.rest == Rest::Blank)));
        if let Some(vs) = again {
            let mut tried = now.clone();
            tried[i] = Some(vs.clone());
            let still = views(&tried);
            if (0..still.len()).all(|j| !still[j] || (bad[j] && j != i)) {
                others.extend(columns(&scaled(marks(&vs), scales.get(i))));
                now = tried;
                staves[i] = Ok(vs);
                continue;
            }
        }
        let rest: Vec<&[Mark]> = (0..all.len())
            .filter(|&j| j != i)
            .map(|j| &all[j][..])
            .collect();
        let how = first_contradiction(&all[i], &rest, sp);
        staves[i] = Err(format!("{MISREAD} ({how})"));
    }
}

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

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

    fn quarters(xs: &[f64]) -> Vec<Ev> {
        xs.iter().map(|&x| note(x, Q::ONE)).collect()
    }

    #[test]
    fn staves_in_different_times_agree_in_proportion_or_quarter_for_quarter() {
        // a voice in 2/4 (two quarters) over a staff in 6/8 (two dotted quarters)
        let two = |x1: f64| vec![vec![note(0.0, Q::ONE), note(x1, Q::ONE)]];
        let six = vec![vec![note(0.0, Q::new(3, 2)), note(6.0, Q::new(3, 2))]];
        let scales = [Q::ONE, Q::new(2, 3)];
        // a beat of one over a beat of the other: in proportion
        let mut staves = vec![Ok(two(6.0)), Ok(six.clone())];
        unread_misread_in(&mut staves, 1.0, &scales);
        assert!(staves.iter().all(|s| s.is_ok()));
        // taken quarter for quarter they would contradict each other
        let mut staves = vec![Ok(two(6.0)), Ok(six.clone())];
        unread_misread_in(&mut staves, 1.0, &[]);
        assert!(staves.iter().any(|s| s.is_err()));
        // a program that sets them quarter for quarter: the voice's second quarter stands two
        // thirds of the way to the other staff's second beat, and both are read
        let mut staves = vec![Ok(two(4.0)), Ok(six.clone())];
        unread_misread_in(&mut staves, 1.0, &scales);
        assert!(staves.iter().all(|s| s.is_ok()));
        // neither way: the voice's second quarter stands past the other staff's second beat
        let mut staves = vec![Ok(two(9.0)), Ok(six)];
        unread_misread_in(&mut staves, 1.0, &scales);
        assert!(staves.iter().any(|s| s.is_err()));
    }

    #[test]
    fn staves_in_step_are_not_misread() {
        // four quarters over two halves, and a voice a head's width aside of its column
        let a = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let b = vec![vec![note(0.1, Q::int(2)), note(8.1, Q::int(2))]];
        let c = vec![
            vec![note(0.0, Q::int(4))],
            vec![note(1.3, Q::int(2)), note(8.0, Q::int(2))],
        ];
        assert_eq!(
            misread(&[Some(&a), Some(&b), Some(&c), None], 1.0),
            vec![false; 4]
        );
    }

    #[test]
    fn a_voice_read_as_starting_with_the_bar_far_right_of_its_start_is_misread() {
        // a whole note, and a voice of eighths that enters at the second beat's column read as
        // starting with the bar
        let late = vec![
            vec![note(0.0, Q::int(4))],
            vec![
                note(4.0, Q::new(1, 2)),
                note(6.0, Q::new(1, 2)),
                Ev::spacer(Q::int(3), 6.1),
            ],
        ];
        assert_eq!(misread(&[Some(&late)], 1.0), vec![true]);
    }

    #[test]
    fn the_staff_the_others_contradict_is_the_one_misread() {
        // two staves agree where the beats stand; the third has its second note, in the third
        // beat's column, a beat early
        let a = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let b = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let c = vec![vec![
            note(0.0, Q::ONE),
            note(8.0, Q::ONE),
            Ev::spacer(Q::int(2), 8.1),
        ]];
        assert_eq!(
            misread(&[Some(&a), Some(&b), Some(&c)], 1.0),
            vec![false, false, true]
        );
    }

    #[test]
    fn of_two_staves_the_one_with_blank_time_is_the_one_misread() {
        let a = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let c = vec![vec![
            note(0.0, Q::ONE),
            note(8.0, Q::ONE),
            Ev::spacer(Q::int(2), 8.1),
        ]];
        assert_eq!(misread(&[Some(&a), Some(&c)], 1.0), vec![false, true]);
        assert_eq!(misread(&[Some(&c), Some(&a)], 1.0), vec![true, false]);
    }

    #[test]
    fn a_voice_entering_late_is_timed_by_the_columns_it_stands_in() {
        // a whole note with eighths entering at the second beat's column, read as starting
        // with the bar; another staff has quarters
        let late = vec![
            vec![note(0.0, Q::int(4))],
            vec![
                note(4.0, Q::new(1, 2)),
                note(6.0, Q::new(1, 2)),
                Ev::spacer(Q::int(3), 6.1),
            ],
        ];
        let beats = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let mut bar = vec![Ok(beats.clone()), Ok(late.clone())];
        unread_misread(&mut bar, 1.0);
        let v = bar[1].as_ref().unwrap();
        assert_eq!(v[0].len(), 1);
        let lens: Vec<(Q, bool)> = v[1].iter().map(|e| (e.dur, e.is_note())).collect();
        assert_eq!(
            lens,
            vec![
                (Q::ONE, false),
                (Q::new(1, 2), true),
                (Q::new(1, 2), true),
                (Q::int(2), false)
            ]
        );
        // with no column to say where it enters, it is left unread
        let mut alone = vec![Err("unread".to_string()), Ok(late)];
        unread_misread(&mut alone, 1.0);
        assert!(alone[1].as_ref().is_err_and(|e| e.starts_with(MISREAD)));
    }

    #[test]
    fn a_voice_whose_notes_stand_in_columns_it_cannot_run_through_is_left_unread() {
        // a quarter and a note in the column of beat 2.5: read on one after the other, a
        // dot was missed or a rest hidden between them, and which is not told
        let gap = vec![vec![
            note(0.0, Q::ONE),
            note(6.0, Q::new(3, 2)),
            Ev::spacer(Q::new(3, 2), 6.1),
        ]];
        let beats = vec![vec![
            note(0.0, Q::new(3, 2)),
            note(6.0, Q::new(3, 2)),
            note(12.0, Q::ONE),
        ]];
        let mut bar = vec![Ok(beats.clone()), Ok(gap)];
        unread_misread(&mut bar, 1.0);
        assert!(bar[0].is_ok());
        assert!(bar[1].is_err());
        // an eighth and a note in that column, under a whole note: no dot would hold so long,
        // a rest is hidden
        let hidden = vec![
            vec![note(0.0, Q::int(4))],
            vec![
                note(0.0, Q::new(1, 2)),
                note(6.0, Q::new(3, 2)),
                Ev::spacer(Q::int(2), 6.1),
            ],
        ];
        let mut bar = vec![Ok(beats), Ok(hidden)];
        unread_misread(&mut bar, 1.0);
        let v = &bar[1].as_ref().unwrap()[1];
        let lens: Vec<(Q, bool)> = v.iter().map(|e| (e.dur, e.is_note())).collect();
        assert_eq!(
            lens,
            vec![
                (Q::new(1, 2), true),
                (Q::ONE, false),
                (Q::new(3, 2), true),
                (Q::ONE, false)
            ]
        );
    }

    #[test]
    fn a_staff_whose_only_voice_would_have_blank_time_is_left_unread() {
        // two quarters in the second and third beats' columns, read as starting with the bar,
        // and nothing else on the staff: timed by the columns its one voice would enter late
        // with no rest printed, which a program does not do; notes are missing
        let late = vec![vec![
            note(4.0, Q::ONE),
            note(8.0, Q::ONE),
            Ev::spacer(Q::int(2), 8.1),
        ]];
        let beats = vec![quarters(&[0.0, 4.0, 8.0, 12.0])];
        let others = columns(&marks(&beats));
        assert!(retimed(&late, &others, Q::int(4), 1.0).is_some());
        let mut bar = vec![Ok(beats), Ok(late)];
        unread_misread(&mut bar, 1.0);
        assert!(bar[0].is_ok());
        assert!(bar[1].as_ref().is_err_and(|e| e.starts_with(MISREAD)));
    }

    #[test]
    fn rests_and_grace_notes_are_no_marks() {
        let mut rest = Ev::new(Vec::new(), None, None);
        rest.rest = Rest::Printed(Glyph {
            code: 0xE4E3,
            x0: 7.0,
            x1: 8.0,
            y: 10.0,
            size: 4.0,
        });
        rest.x = 7.0;
        rest.dur = Q::int(4);
        let mut grace = note(2.5, Q::new(1, 2));
        grace.grace = Some(true);
        let a = vec![vec![rest]];
        let b = vec![vec![note(0.0, Q::int(2)), grace, note(4.0, Q::int(2))]];
        assert!(marks(&a).is_empty());
        assert_eq!(marks(&b).len(), 2);
        // a rest set off its column says nothing
        let mut off = a[0][0].clone();
        off.dur = Q::int(2);
        let c = vec![vec![note(0.0, Q::int(2)), off]];
        assert_eq!(misread(&[Some(&b), Some(&c)], 1.0), vec![false, false]);
        assert_eq!(misread(&[Some(&a), Some(&b)], 1.0), vec![false, false]);
    }

    #[test]
    fn a_stemmed_note_has_its_column_on_its_stems_side() {
        use crate::page::VLine;
        let stem = VLine {
            x: 11.2,
            y0: 3.0,
            y1: 10.0,
            w: 0.1,
        };
        // a second: the lower head left of an up stem, the upper set across it
        let mut up = note(10.0, Q::ONE);
        up.heads.push(Glyph {
            code: 0xE0A4,
            x0: 11.2,
            x1: 12.4,
            y: 9.5,
            size: 4.0,
        });
        up.stem = Some(stem);
        assert!((column_x(&up) - 10.0).abs() < 1e-9);
        // stem down: the head set across stands left of the stem, the column is the stem's
        let mut down = up.clone();
        down.up = Some(false);
        down.x = 8.8;
        assert!((column_x(&down) - 11.2).abs() < 1e-9);
    }
}