fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Key signatures: each staff's own, at a system's start, changed at a barline inside the system
//! (the old one's naturals, then the new one's sharps or flats) and announced at its end.

use crate::page::{Glyph, Staff};
use crate::smufl;
use crate::staff::Ev;

/// Where the sharps and the flats of a signature stand on a treble staff, in order, in half
/// spaces up from its bottom line (f5 c5 g5 d5 a4 e5 b4; b4 e5 a4 d5 g4 c5 f4).
const SHARPS: [i32; 7] = [8, 5, 9, 6, 3, 7, 4];
const FLATS: [i32; 7] = [4, 7, 3, 6, 2, 5, 1];

/// Where a signature's sharps (or flats) stand on a staff whose bottom line is the place
/// `clef_bottom`: the treble's, a step lower under an alto clef, two under a bass clef; a tenor
/// clef's flats a step higher, and its sharps set their own way.
fn order(sharps: bool, clef_bottom: i32) -> [i32; 7] {
    let shift = match clef_bottom.rem_euclid(7) {
        2 => 0,
        3 => -1,
        4 => -2,
        1 if sharps => return [2, 6, 3, 7, 4, 8, 5],
        1 => 1,
        // (another clef: the treble's letters, a step lower for each step its bottom line is
        // higher; the octave is the engraver's)
        b => 2 - b,
    };
    (if sharps { SHARPS } else { FLATS }).map(|p| p + shift)
}

/// What stands where a key signature may.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Found {
    /// The signature read: `None` where no accidentals stand, or only the notes' own.
    pub fifths: Option<i32>,
    /// How many naturals it starts with (the old key taken away).
    pub naturals: usize,
    /// Accidentals set like a signature that are none, and no note's either.
    pub unclear: bool,
    /// Every accidental of the signature has a notehead at its height just after it: it may be
    /// the notes' own.
    pub beside: bool,
    /// The signature's glyphs.
    pub glyphs: Vec<Glyph>,
}

impl Found {
    fn nothing() -> Found {
        Found {
            fifths: None,
            naturals: 0,
            unclear: false,
            beside: false,
            glyphs: Vec::new(),
        }
    }

    /// Naturals alone (no sharps or flats from here) are a signature where the key `old` has
    /// that many to take away, or where they are no notes' own; sharps or flats are one as
    /// they stand.
    fn holds_after(&self, old: Option<i32>) -> bool {
        match self.fifths {
            None => false,
            Some(0) => {
                old != Some(0)
                    && (!self.beside
                        || old.is_some_and(|o| o.unsigned_abs() as usize == self.naturals))
            }
            Some(_) => true,
        }
    }
}

/// `places` are some in a row of `order`, from its `from`th. Under a clef whose signatures'
/// heights are not known here (`by_letter`: a soprano, mezzo-soprano or baritone clef), each
/// on the same letter as the order's, in whichever octave the engraver set it.
fn in_order(places: &[i32], order: &[i32; 7], from: usize, by_letter: bool) -> bool {
    let same = |a: &i32, b: &i32| a == b || (by_letter && (a - b).rem_euclid(7) == 0);
    from + places.len() <= 7 && places.iter().zip(&order[from..]).all(|(a, b)| same(a, b))
}

/// Whether the clef whose bottom line is the place `clef_bottom` is one whose signatures are
/// told by their letters alone (`in_order`): not the treble, alto, bass or tenor clef.
fn by_letter(clef_bottom: i32) -> bool {
    !matches!(clef_bottom.rem_euclid(7), 1..=4)
}

/// How many of `run`'s accidentals (each its alteration and its place on the staff), from its
/// first, are a key signature: naturals where a signature's sharps or flats stand, in its order
/// (the old key taken away), then sharps or flats from the order's first; its count of naturals
/// and of sharps (flats negative).
fn valid_prefix(run: &[(i32, i32)], clef_bottom: i32) -> (usize, usize, i32) {
    let (sharps, flats) = (order(true, clef_bottom), order(false, clef_bottom));
    let loose = by_letter(clef_bottom);
    let mut best = (0, 0, 0);
    for n in 1..=run.len() {
        let part = &run[..n];
        let nat = part.iter().take_while(|a| a.0 == 0).count();
        let naturals: Vec<i32> = part[..nat].iter().map(|a| a.1).collect();
        let rest: Vec<i32> = part[nat..].iter().map(|a| a.1).collect();
        let naturals_ok = nat == 0
            || (0..7).any(|k| {
                in_order(&naturals, &sharps, k, loose) || in_order(&naturals, &flats, k, loose)
            });
        let alt = part.get(nat).map_or(0, |a| a.0);
        let rest_ok = part[nat..].iter().all(|a| a.0 == alt)
            && match alt {
                1 => in_order(&rest, &sharps, 0, loose),
                -1 => in_order(&rest, &flats, 0, loose),
                _ => rest.is_empty(),
            };
        if naturals_ok && rest_ok {
            best = (n, nat, alt * rest.len() as i32);
        } else {
            break;
        }
    }
    best
}

/// The key signature among a staff's glyphs `gs` from x `lo` to `hi` (the place a signature may
/// stand: before the system's first note, after a barline before the bar's first, after the
/// system's last barline). `clef_bottom`: the place of the staff's bottom line there.
pub(crate) fn signature(gs: &[Glyph], lo: f64, hi: f64, staff: &Staff, clef_bottom: i32) -> Found {
    let sp = staff.sp();
    let mut cand: Vec<&Glyph> = gs
        .iter()
        .filter(|g| {
            smufl::accidental(g.code).is_some()
                && lo <= g.x0
                && g.x0 < hi
                && staff.top() - 0.8 * sp < g.y
                && g.y < staff.bottom() + 0.8 * sp
        })
        .collect();
    cand.sort_by(|a, b| a.x0.total_cmp(&b.x0));
    // set evenly one after another; one after a wider gap is the first note's own
    let mut run: Vec<&Glyph> = Vec::new();
    for g in cand {
        let gap = run.last().map(|p| g.x0 - p.x0);
        let step = (run.len() >= 2).then(|| run[1].x0 - run[0].x0);
        // (the new key's first after the old one's naturals may stand a little apart)
        let turn = run
            .last()
            .is_some_and(|p| smufl::accidental(p.code) != smufl::accidental(g.code));
        let fits = match (gap, step) {
            (None, _) => true,
            (Some(d), _) if d < 0.4 * sp => false,
            (Some(d), _) if turn => d < 2.0 * sp,
            (Some(d), Some(s)) => d < 1.5 * s && d < 2.0 * sp,
            (Some(d), None) => d < 1.6 * sp,
        };
        if !fits {
            break;
        }
        run.push(g);
    }
    let beside_note = |g: &Glyph| beside_note(g, gs, 4.0, sp);
    let placed: Vec<(i32, i32)> = run
        .iter()
        .map(|g| {
            let up = ((staff.bottom() - g.y) / (sp / 2.0)).round() as i32;
            (smufl::accidental(g.code).unwrap(), up)
        })
        .collect();
    let (n, naturals, fifths) = valid_prefix(&placed, clef_bottom);
    Found {
        fifths: (n > 0).then_some(fifths),
        naturals,
        unclear: run[n..]
            .iter()
            .any(|g| !beside_note(g) && !stacked_before(g, gs, sp)),
        beside: n > 0 && run[..n].iter().all(|g| beside_note(g)),
        glyphs: run[..n].iter().map(|g| **g).collect(),
    }
}

/// Whether a head at the accidental `g`'s height stands just after it, within `reach` staff
/// spaces; a wide accidental (as some fonts draw a sharp) may touch its head, or lap over its
/// edge.
pub(crate) fn beside_note(g: &Glyph, gs: &[Glyph], reach: f64, sp: f64) -> bool {
    gs.iter().any(|h| {
        smufl::head(h.code).is_some()
            && -0.5 * sp < h.x0 - g.x1
            && h.x0 - g.x1 < reach * sp
            && (h.y - g.y).abs() < 0.3 * sp
    })
}

/// Whether the accidental `g` is one of a chord's, stacked in columns before its heads: from it
/// to a head at its height, accidentals and heads stand edge to edge, each starting within half
/// a staff space of where the ones before end.
fn stacked_before(g: &Glyph, gs: &[Glyph], sp: f64) -> bool {
    let mut after: Vec<&Glyph> = gs
        .iter()
        .filter(|c| {
            (smufl::accidental(c.code).is_some() || smufl::head(c.code).is_some()) && c.x0 > g.x0
        })
        .collect();
    after.sort_by(|a, b| a.x0.total_cmp(&b.x0));
    let mut reach = g.x1;
    for c in after {
        if c.x0 > reach + 0.5 * sp {
            break;
        }
        if smufl::head(c.code).is_some() && (c.y - g.y).abs() < 0.3 * sp && c.x0 > g.x1 - 0.5 * sp {
            return true;
        }
        reach = reach.max(c.x1);
    }
    false
}

/// The key of a staff whose key the system before could not make out, at a system's start where
/// it prints none: the one known key of the other staves that print none there either (in a
/// score that sets its signatures again at each system, or one where the staves keep theirs
/// unprinted alike); `None` where there is no such key, or more than one.
fn unprinted_like(starts: &[Found], carried: &[Option<i32>], i: usize) -> Option<i32> {
    let mut like = (0..starts.len())
        .filter(|&j| j != i && starts[j].fifths.is_none() && !starts[j].unclear)
        .filter_map(|j| carried[j]);
    let k = like.next()?;
    like.all(|o| o == k).then_some(k)
}

/// Every staff's key through a system.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Keys {
    /// Per staff, per bar: the key in force (sharps; flats negative); `None` where the signature
    /// cannot be made out.
    pub at: Vec<Vec<Option<i32>>>,
    /// Per staff: the key the next system starts in (this one's last, or the one announced after
    /// its last barline).
    pub out: Vec<Option<i32>>,
    /// Where the signatures at the system's start end.
    pub opening_end: f64,
    /// Per staff: the glyphs of the signatures inside the system, which are no note's.
    pub inner: Vec<Vec<Glyph>>,
    /// A staff has a signature at the system's start.
    pub at_start: bool,
    /// Per staff, per bar: a signature inside the bar (not at its barline), as where it stands
    /// and the key from there on. `at` is the key the bar starts in.
    pub mid: Vec<Vec<Option<(f64, i32)>>>,
}

impl Keys {
    /// The system's key at a bar, as the score has one: the key most of its staves are in (the
    /// upper staff's of two as common).
    pub fn common(&self, b: usize) -> Option<i32> {
        let known: Vec<i32> = self.at.iter().filter_map(|s| s[b]).collect();
        let count = |k: i32| known.iter().filter(|o| **o == k).count();
        let most = known.iter().map(|&k| count(k)).max()?;
        known.iter().copied().find(|&k| count(k) == most)
    }
}

/// A staff's bar with notes whose key is not known is not read.
pub(crate) fn known(
    key: Option<i32>,
    voices: Result<Vec<Vec<Ev>>, String>,
) -> Result<Vec<Vec<Ev>>, String> {
    match voices {
        Ok(vs) if key.is_none() && vs.iter().flatten().any(|e| e.is_note()) => {
            Err("a key signature it cannot make out".to_string())
        }
        v => v,
    }
}

/// Each staff's key in each bar of a system. `edges`: the bars' edges (the system's left, then
/// each barline); `clef_bottoms(i, x)`: the place of staff `i`'s bottom line at x; `carried`:
/// each staff's key from the system before (`None`: not known); `reprints`: the score prints its
/// signature at every system's start, so a start without one is in no sharps or flats;
/// `first`: the score's first system.
#[allow(clippy::too_many_arguments)]
pub(crate) fn keys(
    staff_glyphs: &[Vec<Glyph>],
    staves: &[Staff],
    first_event: f64,
    edges: &[f64],
    clef_bottoms: &dyn Fn(usize, f64) -> i32,
    carried: &[Option<i32>],
    reprints: bool,
    first: bool,
) -> Keys {
    let n = staves.len();
    let nb = edges.len() - 1;
    let sp = staves[0].sp();
    let left = edges[0];
    let right = staves.iter().map(|s| s.right).fold(f64::MIN, f64::max);
    let mut keys = Keys {
        at: vec![Vec::new(); n],
        out: vec![None; n],
        opening_end: f64::MIN,
        inner: vec![Vec::new(); n],
        at_start: false,
        mid: vec![Vec::new(); n],
    };
    // at the system's start
    let starts: Vec<Found> = (0..n)
        .map(|i| {
            let lo = left - 2.0 * sp;
            signature(
                &staff_glyphs[i],
                lo,
                first_event,
                &staves[i],
                clef_bottoms(i, lo),
            )
        })
        .collect();
    let mut now: Vec<Option<i32>> = Vec::new();
    for (i, f) in starts.iter().enumerate() {
        // accidentals that have each a note beside them at their height are the notes' own,
        // unless the staff was in that key already or another staff has the same signature at
        // the same place (one that is plainly no notes' own, or both of two or more)
        let aligned = || {
            starts.iter().enumerate().any(|(j, o)| {
                j != i
                    && o.holds_after(carried[j])
                    && o.fifths == f.fifths
                    && (!o.beside || (o.glyphs.len() >= 2 && f.glyphs.len() >= 2))
                    && (o.glyphs[0].x0 - f.glyphs[0].x0).abs() < 0.3 * sp
            })
        };
        let own = f.beside && !(f.fifths == carried[i] && f.fifths != Some(0)) && !aligned();
        let key = if f.unclear {
            None
        } else if f.holds_after(carried[i]) && !own {
            keys.at_start |= f.fifths != Some(0);
            keys.opening_end = f
                .glyphs
                .iter()
                .map(|g| g.x1 + 0.1)
                .fold(keys.opening_end, f64::max);
            f.fifths
        } else if first || reprints {
            Some(0)
        } else if carried[i].is_none() && f.fifths.is_none() {
            unprinted_like(&starts, carried, i)
        } else {
            carried[i]
        };
        now.push(key);
    }
    for (i, k) in now.iter().enumerate() {
        keys.at[i].push(*k);
    }
    let seen = (staff_glyphs, staves, clef_bottoms);
    inside(seen, (first_event, edges[1]), &mut now, &mut keys);
    // at each barline inside it: before the bar's first note or rest on any staff
    for b in 1..nb {
        let first_in = staff_glyphs
            .iter()
            .flatten()
            .filter(|g| smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
            .map(|g| g.x0)
            .filter(|&x| edges[b] < x && x < edges[b + 1])
            .fold(edges[b + 1], f64::min);
        let found: Vec<Found> = (0..n)
            .map(|i| {
                let at = clef_bottoms(i, edges[b]);
                let f = signature(&staff_glyphs[i], edges[b], first_in, &staves[i], at);
                // (a signature stands at the barline, or after a break in the staff's lines and the
                // clef there; and naturals alone take a key away)
                let from = staves[i]
                    .breaks
                    .iter()
                    .filter(|k| edges[b] - sp < k.0 && k.1 < first_in)
                    .map(|k| k.1 + 4.0 * sp)
                    .fold(edges[b], f64::max);
                match f.glyphs.first() {
                    Some(g) if g.x0 - from < 4.0 * sp && f.holds_after(now[i]) => f,
                    _ => Found::nothing(),
                }
            })
            .collect();
        // a change shows on the staves together: on two at least, one's accidentals plainly no
        // notes' own; where some may be their notes', all go to one key. Two accidentals or more
        // that are no notes' own are a signature on one staff alone.
        let signed: Vec<&Found> = found.iter().filter(|f| f.fifths.is_some()).collect();
        let together = signed.len() >= n.min(2)
            && signed.iter().any(|f| !f.beside)
            && (signed.iter().all(|f| !f.beside)
                || signed.iter().all(|f| f.fifths == signed[0].fifths));
        for (i, f) in found.into_iter().enumerate() {
            if f.fifths.is_some() && (together || (!f.beside && f.glyphs.len() >= 2)) {
                now[i] = if f.unclear { None } else { f.fifths };
                keys.inner[i].extend(f.glyphs);
            }
            keys.at[i].push(now[i]);
        }
        inside(seen, (edges[b], edges[b + 1]), &mut now, &mut keys);
    }
    // after the last barline: the next system's key, announced
    for i in 0..n {
        let f = signature(
            &staff_glyphs[i],
            edges[nb],
            right + sp,
            &staves[i],
            clef_bottoms(i, edges[nb]),
        );
        keys.out[i] = match f.fifths {
            Some(_) if f.unclear => None,
            Some(k) => Some(k),
            None => now[i],
        };
    }
    keys
}

/// A system as the signatures are read from it: each staff's glyphs, the staves, and the place of
/// a staff's bottom line at an x.
type Seen<'a> = (&'a [Vec<Glyph>], &'a [Staff], &'a dyn Fn(usize, f64) -> i32);

/// A key signature inside a bar (from `lo` to `hi`): between two of the bar's notes or rests,
/// not at its barline. As at a barline, it shows on the staves together, at one place: on two at
/// least, one's accidentals plainly no notes' own (or, where some may be their notes', all to
/// one key); on one staff alone, two accidentals or more that are no notes' own. Each staff's
/// key goes on from it (`now`), its bar's `mid` says where, and its glyphs are no note's.
fn inside(
    (staff_glyphs, staves, clef_bottoms): Seen,
    (lo, hi): (f64, f64),
    now: &mut [Option<i32>],
    keys: &mut Keys,
) {
    let n = staves.len();
    let sp = staves[0].sp();
    for m in keys.mid.iter_mut() {
        m.push(None);
    }
    // where the bar's notes and rests stand, on any staff
    let mut xs: Vec<f64> = staff_glyphs
        .iter()
        .flatten()
        .filter(|g| smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
        .map(|g| g.x0)
        .filter(|&x| lo <= x && x < hi)
        .collect();
    xs.sort_by(f64::total_cmp);
    xs.dedup_by(|b, a| *b - *a < 0.5 * sp);
    for w in xs.windows(2) {
        // (accidentals in the gap at all, on a staff: most gaps have none)
        let any = staff_glyphs
            .iter()
            .flatten()
            .any(|g| smufl::accidental(g.code).is_some() && w[0] + 0.5 * sp <= g.x0 && g.x0 < w[1]);
        if !any {
            continue;
        }
        let found: Vec<Found> = (0..n)
            .map(|i| {
                let from = w[0] + 0.5 * sp;
                let at = clef_bottoms(i, from);
                let f = signature(&staff_glyphs[i], from, w[1], &staves[i], at);
                match f.holds_after(now[i]) && !f.unclear && f.fifths != now[i] {
                    true => f,
                    false => Found::nothing(),
                }
            })
            .collect();
        let signed: Vec<&Found> = found.iter().filter(|f| f.fifths.is_some()).collect();
        let Some(first) = signed.first() else {
            continue;
        };
        let x = first.glyphs[0].x0;
        let aligned = signed.iter().all(|f| (f.glyphs[0].x0 - x).abs() < sp);
        let together = signed.len() >= n.min(2)
            && signed.iter().any(|f| !f.beside)
            && (signed.iter().all(|f| !f.beside)
                || signed.iter().all(|f| f.fifths == signed[0].fifths));
        let mut taken = false;
        for (i, f) in found.into_iter().enumerate() {
            let alone = !f.beside && f.glyphs.len() >= 2;
            if f.fifths.is_some() && aligned && (together || alone) {
                now[i] = f.fifths;
                let b = keys.mid[i].len() - 1;
                keys.mid[i][b] = f.fifths.map(|k| (f.glyphs[0].x0, k));
                keys.inner[i].extend(f.glyphs);
                taken = true;
            }
        }
        if taken {
            return;
        }
    }
}

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

    #[test]
    fn a_signature_between_a_bars_notes_changes_the_key_from_there() {
        // two staves in two flats; in the first bar, after a half note and before the last
        // quarter (a d4, no f), a sharp on each staff's f line, one over the other
        let staves = [staff(0.0), staff(10.0)];
        let flats = |top: f64| {
            vec![
                glyph(FLAT, 3.0, top + 2.0),
                glyph(FLAT, 4.0, top + 0.5),
                glyph(HEAD, 10.0, top + 3.0),
                glyph(SHARP, 20.0, top),
                glyph(HEAD, 24.0, top + 4.5),
                glyph(HEAD, 40.0, top + 3.0),
            ]
        };
        let glyphs = vec![flats(0.0), flats(10.0)];
        let edges = [0.0, 30.0, 60.0];
        let k = keys(
            &glyphs,
            &staves,
            10.0,
            &edges,
            &|_, _| TREBLE,
            &[Some(0), Some(0)],
            false,
            true,
        );
        assert_eq!(k.at[0], vec![Some(-2), Some(1)]);
        assert_eq!(k.mid[0], vec![Some((20.0, 1)), None]);
        assert_eq!(k.mid[1], vec![Some((20.0, 1)), None]);
        assert_eq!(k.inner[0].len(), 1);
        assert_eq!(k.out, vec![Some(1), Some(1)]);
        // a sharp before an f on one staff alone is that note's own
        let mut one = flats(0.0);
        one[4].y = 0.0;
        let glyphs = vec![
            one,
            flats(10.0)
                .into_iter()
                .filter(|g| g.code != SHARP)
                .collect(),
        ];
        let k = keys(
            &glyphs,
            &staves,
            10.0,
            &edges,
            &|_, _| TREBLE,
            &[Some(0), Some(0)],
            false,
            true,
        );
        assert_eq!(k.at[0], vec![Some(-2), Some(-2)]);
        assert_eq!(k.mid[0], vec![None, None]);
    }

    fn glyph(code: u32, x0: f64, y: f64) -> Glyph {
        Glyph {
            code,
            x0,
            x1: x0 + 0.9,
            y,
            size: 1.0,
        }
    }

    fn staff(top: f64) -> Staff {
        Staff {
            lines: [top, top + 1.0, top + 2.0, top + 3.0, top + 4.0],
            left: 0.0,
            right: 100.0,
            breaks: Vec::new(),
        }
    }

    const FLAT: u32 = 0xE260;
    const NATURAL: u32 = 0xE261;
    const SHARP: u32 = 0xE262;
    const HEAD: u32 = 0xE0A4;
    const TREBLE: i32 = 4 * 7 + 2;

    /// A treble staff's glyph on a letter's place counted from the bottom line (e4 = 0).
    fn on(code: u32, x0: f64, up: i32) -> Glyph {
        glyph(code, x0, 4.0 - up as f64 / 2.0)
    }

    #[test]
    fn a_signature_is_sharps_or_flats_on_their_letters_in_order() {
        let st = staff(0.0);
        // three flats: b4, e5, a4
        let gs = vec![on(FLAT, 5.0, 4), on(FLAT, 6.0, 7), on(FLAT, 7.0, 3)];
        let f = signature(&gs, 0.0, 20.0, &st, TREBLE);
        assert_eq!((f.fifths, f.unclear, f.glyphs.len()), (Some(-3), false, 3));
        // two sharps: f5, c5
        let gs = vec![on(SHARP, 5.0, 8), on(SHARP, 6.0, 5)];
        assert_eq!(signature(&gs, 0.0, 20.0, &st, TREBLE).fifths, Some(2));
        // the same two read in the bass clef stand on other letters: no signature, and no note's
        let f = signature(&gs, 0.0, 20.0, &st, 2 * 7 + 4);
        assert_eq!((f.fifths, f.unclear), (None, true));
    }

    #[test]
    fn naturals_take_the_old_key_away() {
        let st = staff(0.0);
        // three naturals on b e a: no sharps or flats
        let mut gs = vec![
            on(NATURAL, 5.0, 4),
            on(NATURAL, 6.0, 7),
            on(NATURAL, 7.0, 3),
        ];
        assert_eq!(signature(&gs, 0.0, 20.0, &st, TREBLE).fifths, Some(0));
        // then a sharp on f: one sharp
        gs.push(on(SHARP, 8.2, 8));
        let f = signature(&gs, 0.0, 20.0, &st, TREBLE);
        assert_eq!((f.fifths, f.glyphs.len()), (Some(1), 4));
    }

    #[test]
    fn a_notes_own_accidental_is_no_signature() {
        let st = staff(0.0);
        // a sharp on g4 with its note: nothing of a signature, nothing unclear
        let gs = vec![on(SHARP, 5.0, 2), on(HEAD, 6.1, 2)];
        let f = signature(&gs, 0.0, 6.1, &st, TREBLE);
        assert_eq!((f.fifths, f.unclear), (None, false));
        // one flat on b4 with a note on b4 after it: a signature that may be the note's
        let gs = vec![on(FLAT, 5.0, 4), on(HEAD, 7.5, 4)];
        let f = signature(&gs, 0.0, 7.5, &st, TREBLE);
        assert_eq!((f.fifths, f.beside), (Some(-1), true));
        // two flats, then the first note's own after a wider gap
        let gs = vec![
            on(FLAT, 5.0, 4),
            on(FLAT, 6.0, 7),
            on(FLAT, 9.0, 3),
            on(HEAD, 10.0, 3),
        ];
        let f = signature(&gs, 0.0, 10.0, &st, TREBLE);
        assert_eq!((f.fifths, f.unclear), (Some(-2), false));
    }

    fn treble(_: usize, _: f64) -> i32 {
        TREBLE
    }

    #[test]
    fn each_staff_has_its_own_key() {
        // the upper staff without a signature, the lower in three flats
        let staves = [staff(0.0), staff(10.0)];
        let lower: Vec<Glyph> = [(5.0, 4), (6.0, 7), (7.0, 3)]
            .iter()
            .map(|&(x, up)| glyph(FLAT, x, 14.0 - up as f64 / 2.0))
            .collect();
        let gs = vec![vec![on(HEAD, 12.0, 2)], lower];
        let k = keys(
            &gs,
            &staves,
            12.0,
            &[0.0, 50.0, 100.0],
            &treble,
            &[Some(0), Some(-3)],
            true,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0), Some(0)], vec![Some(-3), Some(-3)]]);
        assert_eq!(k.common(0), Some(0));
        assert!(k.at_start && k.opening_end > 7.0);
    }

    #[test]
    fn a_key_changes_at_a_barline_and_is_announced_at_the_end() {
        let st = [staff(0.0)];
        let mut gs = vec![on(FLAT, 5.0, 4), on(HEAD, 12.0, 2)];
        // after the barline at 50: the flat's natural, then two sharps; a note
        gs.extend([on(NATURAL, 50.5, 4), on(SHARP, 51.6, 8), on(SHARP, 52.6, 5)]);
        gs.push(on(HEAD, 56.0, 2));
        // after the last barline at 90: two naturals (f, c)
        gs.extend([on(NATURAL, 90.5, 8), on(NATURAL, 91.5, 5)]);
        let k = keys(
            &[gs.clone()],
            &st,
            12.0,
            &[0.0, 50.0, 90.0],
            &treble,
            &[Some(-1)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(-1), Some(2)]]);
        assert_eq!(k.out, vec![Some(0)]);
        assert_eq!(k.inner[0].len(), 3);
        // a start with no signature: the key carried, or none where the score prints one at
        // every system
        let plain = [vec![on(HEAD, 12.0, 2)]];
        let k = keys(
            &plain,
            &st,
            12.0,
            &[0.0, 90.0],
            &treble,
            &[Some(2)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(2)]]);
        let k = keys(
            &plain,
            &st,
            12.0,
            &[0.0, 90.0],
            &treble,
            &[Some(2)],
            true,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0)]]);
    }

    #[test]
    fn a_first_notes_accidental_after_a_barline_changes_no_key() {
        let st = [staff(0.0)];
        // a sharp on f5 with its note right after the barline
        let gs = vec![on(HEAD, 12.0, 2), on(SHARP, 50.6, 8), on(HEAD, 51.7, 8)];
        let k = keys(
            &[gs],
            &st,
            12.0,
            &[0.0, 50.0, 90.0],
            &treble,
            &[Some(0)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0), Some(0)]]);
        assert!(k.inner[0].is_empty());
    }

    #[test]
    fn a_change_shows_on_the_staves_together_or_plainly_on_one() {
        let staves = [staff(0.0), staff(10.0)];
        let low = |code: u32, x0: f64, up: i32| glyph(code, x0, 14.0 - up as f64 / 2.0);
        let at = |gs: &[Vec<Glyph>]| {
            let k = keys(
                gs,
                &staves,
                12.0,
                &[0.0, 50.0, 90.0],
                &treble,
                &[Some(0), Some(0)],
                false,
                false,
            );
            (k.at[0][1], k.at[1][1])
        };
        // one sharp on f5 after the barline on the upper staff alone, no note at its height:
        // one staff's lone accidental changes no key
        let upper = vec![on(HEAD, 12.0, 2), on(SHARP, 50.6, 8), on(HEAD, 53.0, 2)];
        let lower = vec![low(HEAD, 12.0, 2), low(HEAD, 53.0, 2)];
        assert_eq!(at(&[upper.clone(), lower.clone()]), (Some(0), Some(0)));
        // the same on both staves: one sharp
        let mut both = lower.clone();
        both.push(low(SHARP, 50.6, 8));
        assert_eq!(at(&[upper.clone(), both]), (Some(1), Some(1)));
        // a sharp on the upper staff and a flat on the lower, each with its note: no change
        let mut sharp = upper.clone();
        sharp.push(on(HEAD, 51.7, 8));
        let mut flat = lower.clone();
        flat.extend([low(FLAT, 50.6, 4), low(HEAD, 51.7, 4)]);
        assert_eq!(at(&[sharp, flat]), (Some(0), Some(0)));
        // two sharps in their order on the upper staff alone, no notes': its key, not the lower's
        let mut two = upper;
        two.push(on(SHARP, 51.6, 5));
        assert_eq!(at(&[two, lower]), (Some(2), Some(0)));
    }

    #[test]
    fn a_signature_stands_after_a_break_in_the_lines() {
        // the lines stop at 50 and start again at 60 with a clef, then two flats from 66
        let mut st = staff(0.0);
        st.breaks = vec![(50.0, 60.0)];
        let gs = vec![
            on(HEAD, 12.0, 2),
            on(FLAT, 66.0, 4),
            on(FLAT, 67.0, 7),
            on(HEAD, 72.0, 2),
        ];
        let k = keys(
            &[gs],
            &[st],
            12.0,
            &[0.0, 49.0, 90.0],
            &treble,
            &[Some(0)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0), Some(-2)]]);
    }

    #[test]
    fn naturals_alone_take_away_the_key_there_is() {
        let st = [staff(0.0)];
        // in one flat, a natural on b4 with its note at the system's start is the note's; with
        // no note at its height it takes the flat away
        let own = vec![on(NATURAL, 5.0, 4), on(HEAD, 6.2, 4)];
        let k = keys(
            &[own],
            &st,
            6.2,
            &[0.0, 90.0],
            &treble,
            &[Some(-2)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(-2)]]);
        let away = vec![on(NATURAL, 5.0, 4), on(HEAD, 12.0, 2)];
        let k = keys(
            &[away],
            &st,
            12.0,
            &[0.0, 90.0],
            &treble,
            &[Some(-1)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0)]]);
    }

    #[test]
    fn a_signature_under_a_soprano_clef_is_told_by_its_letters() {
        // the bottom line is c4: a sharp on f (the second space, or an octave up) is one sharp,
        // then one on c; a sharp on g first is no signature
        let c4 = crate::smufl::clef_bottom("soprano");
        assert_eq!(valid_prefix(&[(1, 3)], c4), (1, 0, 1));
        assert_eq!(valid_prefix(&[(1, 10), (1, 7)], c4), (2, 0, 2));
        assert_eq!(valid_prefix(&[(1, 4)], c4), (0, 0, 0));
        assert_eq!(valid_prefix(&[(-1, 6), (-1, 2)], c4), (2, 0, -2));
        // (a treble clef's are told by their places: f5, not f4)
        let e4 = crate::smufl::clef_bottom("treble");
        assert_eq!(valid_prefix(&[(1, 8)], e4), (1, 0, 1));
        assert_eq!(valid_prefix(&[(1, 1)], e4), (0, 0, 0));
    }

    #[test]
    fn a_bar_in_an_unknown_key_is_not_read() {
        let g = glyph(HEAD, 0.0, 0.0);
        let note = Ev::new(vec![g], None, Some(true));
        assert!(known(None, Ok(vec![vec![note.clone()]])).is_err());
        assert!(known(Some(0), Ok(vec![vec![note]])).is_ok());
        assert!(known(None, Ok(vec![vec![]])).is_ok());
    }

    #[test]
    fn a_wide_sharp_touching_its_head_is_beside_it() {
        // a sharp whose right edge laps a little over the head's left (as Petaluma sets it)
        let sharp = Glyph {
            x1: 1.6,
            ..on(SHARP, 0.0, 1)
        };
        let gs = [sharp, on(HEAD, 1.5, 1)];
        assert!(beside_note(&sharp, &gs, 3.0, 1.0));
        // (not a head at another height, nor one far on)
        assert!(!beside_note(&sharp, &[on(HEAD, 1.5, 3)], 3.0, 1.0));
        assert!(!beside_note(&sharp, &[on(HEAD, 5.0, 1)], 3.0, 1.0));
    }

    #[test]
    fn a_chords_accidentals_stacked_after_the_clef_are_its_own() {
        let st = [staff(0.0)];
        // four sharps edge to edge, the first more than four spaces before the chord's heads,
        // on d4 f4 a4 c5: no signature's order, and each at a head's height
        let ups = [-1, 1, 3, 5];
        let mut gs: Vec<Glyph> = (ups.iter().enumerate())
            .map(|(k, &u)| on(SHARP, 2.0 + 1.3 * k as f64, u))
            .collect();
        gs.extend(ups.iter().map(|&u| on(HEAD, 7.2, u)));
        let f = signature(&gs, -2.0, 7.2, &st[0], TREBLE);
        assert_eq!((f.fifths, f.unclear), (None, false));
        let k = keys(
            &[gs],
            &st,
            7.2,
            &[0.0, 90.0],
            &treble,
            &[Some(0)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0)]]);
        // (with no heads at their heights they are still accidentals it cannot make out)
        let lone: Vec<Glyph> = (ups.iter().enumerate())
            .map(|(k, &u)| on(SHARP, 2.0 + 1.3 * k as f64, u))
            .chain([on(HEAD, 7.2, 0)])
            .collect();
        assert!(signature(&lone, -2.0, 7.2, &st[0], TREBLE).unclear);
    }

    #[test]
    fn a_key_not_made_out_is_the_others_where_a_later_system_prints_none() {
        let st = [staff(0.0), staff(10.0)];
        let gs = vec![vec![on(HEAD, 8.0, 0)], vec![glyph(HEAD, 8.0, 14.0)]];
        let k = keys(
            &gs,
            &st,
            8.0,
            &[0.0, 90.0],
            &treble,
            &[None, Some(0)],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![Some(0)], vec![Some(0)]]);
        // (where no other staff's key is known either, it stays unknown)
        let k = keys(
            &gs,
            &st,
            8.0,
            &[0.0, 90.0],
            &treble,
            &[None, None],
            false,
            false,
        );
        assert_eq!(k.at, vec![vec![None], vec![None]]);
        // (and a later system that prints one is in it)
        let signed = vec![
            vec![on(SHARP, 3.0, 8), on(HEAD, 8.0, 0)],
            vec![glyph(HEAD, 8.0, 14.0)],
        ];
        let k = keys(
            &signed,
            &st,
            8.0,
            &[0.0, 90.0],
            &treble,
            &[None, Some(0)],
            false,
            false,
        );
        assert_eq!(k.at[0], vec![Some(1)]);
    }

    #[test]
    fn accidentals_like_a_signature_that_are_none_leave_the_key_unknown() {
        let st = [staff(0.0)];
        // two flats on b4 and d5 at the start, no notes at their heights
        let gs = vec![on(FLAT, 5.0, 4), on(FLAT, 6.0, 6), on(HEAD, 12.0, 0)];
        let k = keys(
            &[gs],
            &st,
            12.0,
            &[0.0, 90.0],
            &treble,
            &[Some(0)],
            false,
            true,
        );
        assert_eq!(k.at, vec![vec![None]]);
    }
}