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
//! Doubt: what the reader was unsure of when it read a staff's bar, carried to the end. A bar
//! is read from what is printed; where the print leaves two readings open and nothing on the
//! page chose between them (a dot two notes could claim, a sign no note took), the bar is left
//! unread rather than given as read.

use crate::page::Glyph;
use crate::smufl;
use crate::staff::Ev;

/// A dot of the bar that no note or rest took.
pub const DOT_UNCLAIMED: &str = "a dot by its notes that none of them took";
/// The dots beside notes set side by side at one start that fit no choice of them.
pub const DOTS_UNFIT: &str = "dots beside two voices' notes that fit neither";
/// One dot that either of two notes at one start could claim.
pub const DOT_EITHER: &str = "a dot that either of two voices' notes could claim";
/// An accidental by a note that no note took.
pub const SIGN_UNCLAIMED: &str = "an accidental by its notes that none of them took";

/// The doubts the reader acts on: a staff's bar with one of these is left unread. The others
/// are found and counted (`FMV_DOUBT`) but cost more right bars than the wrong ones they catch.
pub const KEPT: &[&str] = &[
    DOT_UNCLAIMED,
    SIGN_UNCLAIMED,
    DOTS_UNFIT,
    PAD_NUMBER,
    PAD_SMALL,
    TIE_FROM_UNREAD_SIGNED,
    SMALL_BY_REST,
    SMALL_PADDED,
    TREMOLO_UNLIKE,
];

/// The first doubt of a staff's bar that the reader acts on.
pub fn kept(evs: &[Ev], of_bar: &[&'static str]) -> Option<&'static str> {
    evs.iter()
        .flat_map(|e| e.doubts.iter().copied())
        .chain(of_bar.iter().copied())
        .find(|d| KEPT.contains(d))
}

/// A staff's bar as read, or left unread for a doubt the reader acts on.
pub fn sure(
    evs: &[Ev],
    of_bar: &[&'static str],
    voices: Result<Vec<Vec<Ev>>, String>,
) -> Result<Vec<Vec<Ev>>, String> {
    let Ok(vs) = voices else {
        return voices;
    };
    if !tremolos_paired(&vs) {
        return Err(TREMOLO_APART.to_string());
    }
    let all: Vec<Ev> = evs.iter().chain(vs.iter().flatten()).cloned().collect();
    match kept(&all, of_bar) {
        Some(d) if vs.iter().flatten().any(|e| e.is_note()) => Err(d.to_string()),
        _ => Ok(vs),
    }
}

/// Two or more strokes like a tremolo's between two notes not written alike.
pub const TREMOLO_UNLIKE: &str = "a tremolo's strokes between two notes of different lengths";
/// A tremolo between two notes that the voices as read set apart.
pub const TREMOLO_APART: &str =
    "a tremolo between two notes that are not one voice's, one after the other";

/// Whether every tremolo between two notes has both in one voice, the second right after the
/// first (small notes apart): the format writes it on the first and takes the voice's next note
/// for its second, so one whose notes the voices set apart cannot be written.
pub fn tremolos_paired(voices: &[Vec<Ev>]) -> bool {
    use crate::staff::Trem;
    voices.iter().all(|v| {
        let main: Vec<&Ev> = v.iter().filter(|e| e.grace.is_none()).collect();
        (0..main.len()).all(|k| match main[k].tremolo {
            Some(Trem::Start(_)) => main
                .get(k + 1)
                .is_some_and(|n| n.is_note() && n.tremolo == Some(Trem::Stop)),
            Some(Trem::Stop) => k > 0 && matches!(main[k - 1].tremolo, Some(Trem::Start(_))),
            _ => true,
        })
    })
}

/// What the dots beside notes set side by side say of one of those notes.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Dotted {
    /// How many dots it has, where the dots say.
    pub dots: Option<usize>,
    /// The dots it took, each by where it stands.
    pub taken: Vec<(u64, u64)>,
    /// The dots it took by a black head another chord of the group hangs from too and that
    /// chord took as well: the dots of one head with two stems, which may be one voice's only.
    pub shared: Vec<(u64, u64)>,
    pub doubt: Option<&'static str>,
}

/// A choice of dots for the chords of a group that fits: how far off the dots stand in all,
/// how many dots each chord has, and each dot with the chord that takes it and the head it is
/// by.
type Fit = (f64, Vec<usize>, Vec<(usize, (u64, u64), (u64, u64))>);

fn key(g: &Glyph) -> (u64, u64) {
    (g.x0.to_bits(), g.y.to_bits())
}

/// The dots of notes set side by side at one start (two voices' chords a second or a unison
/// apart, one moved past the other): an engraver sets all their dots in one column past the
/// rightmost head, each dot in the space of its note (a note on a line takes the space above
/// or below). A dotted chord dots every head, so the chords that are dotted are those whose
/// heads, taken together, the column's dots match one for one in order of height. Where one
/// choice of chords fits, each note has its dots however far its own head stands from them;
/// where none or more than one does, the notes are in doubt.
pub fn dots_by_column(out: &[Ev], heads: &[Glyph], inside: &[Glyph], sp: f64) -> Vec<Dotted> {
    let mut said = vec![Dotted::default(); out.len()];
    let mut notes: Vec<usize> = (0..out.len())
        .filter(|&i| out[i].is_note() && out[i].grace.is_none() && !out[i].heads.is_empty())
        .collect();
    notes.sort_by(|&a, &b| out[a].left().total_cmp(&out[b].left()));
    let mut groups: Vec<(Vec<usize>, f64)> = Vec::new();
    for i in notes {
        match groups.last_mut() {
            Some((g, right)) if out[i].left() < *right + 0.2 * sp => {
                g.push(i);
                *right = right.max(out[i].right());
            }
            _ => groups.push((vec![i], out[i].right())),
        }
    }
    for (group, right) in groups {
        if group.len() < 2 || group.len() > 5 {
            continue;
        }
        let mine = |h: &Glyph| {
            group
                .iter()
                .any(|&i| out[i].heads.iter().any(|o| key(o) == key(h)))
        };
        let (hi, lo) = group
            .iter()
            .flat_map(|&i| out[i].heads.iter())
            .fold((f64::MAX, f64::MIN), |a, h| (a.0.min(h.y), a.1.max(h.y)));
        // (a dot stands before the next head at its height)
        let next = |y: f64| {
            heads
                .iter()
                .filter(|h| !mine(h) && h.x0 > right - 0.1 * sp && (h.y - y).abs() < 1.0 * sp)
                .map(|h| h.x0)
                .fold(1e18, f64::min)
        };
        // (each chord's dots stand past its own heads at least: a chord far above or below the
        // other, clear of it, keeps its dots by its own heads)
        let nearest = group
            .iter()
            .map(|&i| out[i].right())
            .fold(f64::MAX, f64::min);
        let mut dots: Vec<&Glyph> = inside
            .iter()
            .filter(|g| {
                g.code == smufl::DOT
                    && 0.0 < g.x0 - nearest
                    && g.x0 - right < 2.6 * sp
                    && hi - 0.9 * sp < g.y
                    && g.y < lo + 0.9 * sp
                    && g.x0 < next(g.y)
            })
            .collect();
        let first = dots.iter().map(|g| g.x0).fold(f64::MAX, f64::min);
        // (past the heads, or past a flag: no further)
        let last = dots.iter().map(|g| g.x0).fold(f64::MIN, f64::max);
        if dots.is_empty() || first - right > 1.4 * sp || last < right {
            continue;
        }
        dots.sort_by(|a, b| a.y.total_cmp(&b.y));
        // each choice of how many dots each chord has (none, one or two; a dotted chord dots
        // every head) whose heads the dots then match in order of height: how far off they stand
        let n = group.len();
        let mut fits: Vec<Fit> = Vec::new();
        for choice in 1..3usize.pow(n as u32) {
            let many: Vec<usize> = (0..n).map(|k| choice / 3usize.pow(k as u32) % 3).collect();
            // a chord all of whose black heads are another dotted chord's (one head, two
            // stems) is taken first as dotted as that chord is (the head's dots both notes'),
            // and marked so, for the bar may read only with them one voice's
            if (0..n).any(|k| many[k] == 0 && heads_dotted_by_another(out, &group, &many, k)) {
                continue;
            }
            let mut hs: Vec<(usize, f64, f64, (u64, u64))> = Vec::new();
            for (k, &i) in group.iter().enumerate() {
                // (two voices' heads printed one on the other are one place)
                let mut at: Vec<(u64, u64)> = out[i].heads.iter().map(key).collect();
                at.sort();
                at.dedup();
                // (a head two chords share, dotted alike, has its dots once)
                at.retain(|p| !shared_before(out, &group, &many, k, p));
                for _ in 0..many[k] {
                    hs.extend(
                        at.iter()
                            .map(|p| (k, f64::from_bits(p.1), out[i].right(), *p)),
                    );
                }
            }
            if hs.len() != dots.len() {
                continue;
            }
            hs.sort_by(|a, b| a.1.total_cmp(&b.1));
            let off: Vec<f64> = hs
                .iter()
                .zip(&dots)
                .map(|(h, d)| (h.1 - d.y).abs())
                .collect();
            let past = hs.iter().zip(&dots).all(|(h, d)| d.x0 > h.2);
            // (a note's second dot stands after its first, not over or under it)
            let twice = (0..hs.len()).any(|a| {
                (0..a).any(|b| {
                    (hs[a].0, hs[a].1) == (hs[b].0, hs[b].1)
                        && (dots[a].x0 - dots[b].x0).abs() < 0.3 * sp
                })
            });
            let past = past && !twice;
            if past && off.iter().all(|&o| o < 0.65 * sp) {
                let pairs = hs
                    .iter()
                    .zip(&dots)
                    .map(|(h, d)| (h.0, key(d), h.3))
                    .collect();
                fits.push((off.iter().sum(), many, pairs));
            }
        }
        fits.sort_by(|a, b| a.0.total_cmp(&b.0));
        let doubt = match fits.len() {
            0 => Some(DOTS_UNFIT),
            1 => None,
            _ if fits[1].0 - fits[0].0 > 0.4 * sp => None,
            _ => Some(DOT_EITHER),
        };
        if let Some(d) = doubt {
            for &i in &group {
                said[i].doubt = Some(d);
            }
            continue;
        }
        let (_, many, pairs) = &fits[0];
        for (k, &i) in group.iter().enumerate() {
            said[i].dots = Some(many[k]);
            said[i].taken = pairs.iter().filter(|p| p.0 == k).map(|p| p.1).collect();
        }
        for &(k, d, p) in pairs {
            for (o, &j) in group.iter().enumerate() {
                if o != k && shared_before(out, &group, many, o, &p) {
                    said[group[k]].shared.push(d);
                    said[j].shared.push(d);
                    said[j].taken.push(d);
                }
            }
        }
    }
    said
}

fn has_head(e: &Ev, p: &(u64, u64)) -> bool {
    e.heads.iter().any(|h| key(h) == *p)
}

/// Whether the group's chord `k` has its black head at `p` from a chord before it in the group,
/// dotted alike: one head two stems hang from, whose dots are counted once.
fn shared_before(out: &[Ev], group: &[usize], many: &[usize], k: usize, p: &(u64, u64)) -> bool {
    black(&out[group[k]], p) && (0..k).any(|o| many[o] == many[k] && has_head(&out[group[o]], p))
}

/// Whether every head of the group's chord `k` is a head of another of its chords that `many`
/// dots (the same glyph hanging from two stems).
fn heads_dotted_by_another(out: &[Ev], group: &[usize], many: &[usize], k: usize) -> bool {
    let e = &out[group[k]];
    !e.heads.is_empty()
        && e.heads.iter().all(|h| {
            smufl::head(h.code) == Some(crate::frac::Q::ONE)
                && (0..group.len())
                    .any(|o| o != k && many[o] > 0 && has_head(&out[group[o]], &key(h)))
        })
}

/// Whether the chord's head at `p` is a black one. (A half note's hollow head may be shared
/// with a black note's stem, the dots the half note's alone.)
fn black(e: &Ev, p: &(u64, u64)) -> bool {
    (e.heads.iter()).any(|h| key(h) == *p && smufl::head(h.code) == Some(crate::frac::Q::ONE))
}

/// The bar's dots that nothing took: each is put on the note or rest nearest it as a doubt.
/// (`others`: the heads about that are not this staff's. A dot by one of them is its dot: a
/// note of the staff above, far down on ledger lines, has its dot in this staff's band.)
pub fn unclaimed_dots(
    out: &mut [Ev],
    inside: &[Glyph],
    others: &[Glyph],
    taken: &[(u64, u64)],
    (top, bottom): (f64, f64),
    sp: f64,
) {
    for g in inside.iter().filter(|g| g.code == smufl::DOT) {
        if taken.contains(&key(g)) || g.y < top - 4.0 * sp || g.y > bottom + 4.0 * sp {
            continue;
        }
        let by = |h: &Glyph| {
            g.x0 > h.x1 - 0.2 * sp && g.x0 - h.x1 < 3.0 * sp && (h.y - g.y).abs() < 0.8 * sp
        };
        if others.iter().any(by) {
            continue;
        }
        // (by a note: within three spaces right of a head or a rest, near its height)
        let near = out
            .iter_mut()
            .filter(|e| {
                let (r, y) = match &e.rest {
                    crate::staff::Rest::Printed(r) => (r.x1, r.y),
                    _ => (e.right(), e.y()),
                };
                let ys = e.heads.iter().map(|h| h.y).chain([y]);
                g.x0 > r - 0.2 * sp
                    && g.x0 - r < 3.0 * sp
                    && ys.into_iter().any(|y| (y - g.y).abs() < 1.2 * sp)
            })
            .min_by(|a, b| (g.x0 - a.x).abs().total_cmp(&(g.x0 - b.x).abs()));
        if let Some(e) = near {
            e.doubts.push(DOT_UNCLAIMED);
        }
    }
}

/// The bar's accidentals that no head took, standing just before a head: a doubt of that head's
/// note.
pub fn unclaimed_signs(out: &mut [Ev], left: &[Glyph], sp: f64) {
    for g in left {
        let near = out.iter_mut().find(|e| {
            e.heads.iter().any(|h| {
                h.x0 - g.x1 > -0.2 * sp && h.x0 - g.x1 < 4.0 * sp && (h.y - g.y).abs() < 1.2 * sp
            })
        });
        if let Some(e) = near {
            e.doubts.push(SIGN_UNCLAIMED);
        }
    }
}

/// Blank time put before a note that no column confirms.
pub const PAD_UNCONFIRMED: &str =
    "a note after time the reader filled in, where no other note's column says it starts";
/// The same, the note standing clear of the other voice's note it was said to start with.
pub const PAD_BESIDE: &str =
    "a note after time the reader filled in, set clear of the note it is said to start with";
/// Any blank time at all.
pub const PAD_ANY: &str = "time the reader filled in";
/// Blank time before a voice's last notes only (it ends with the bar), or after them only.
pub const PAD_INNER: &str = "time the reader filled in between a voice's notes";
/// Small notes that take time.
pub const SMALL_TIMED: &str = "small notes read as taking time";
/// Small notes that take none.
pub const SMALL_GRACE: &str =
    "small notes read as grace notes, with stems of their own and no slash";
/// A voice with blank time in two places.
pub const PAD_TWICE: &str = "a voice the reader filled in time for in two places";
/// A small note read as a grace note, far from the note after it.
pub const SMALL_APART: &str =
    "a small note read as a grace note that stands clear of the next note";
/// A small note read as a grace note at the place of a rest of its staff.
pub const SMALL_BY_REST: &str = "a small note read as a grace note, at a rest's place";
/// A voice of small notes alone after the bar's last full-size note, with blank time.
pub const SMALL_PADDED: &str =
    "small notes after the bar's last note, read as taking time the reader filled in before them";
/// Blank time in a bar with a tuplet's number that no notes were given to.
pub const PAD_NUMBER: &str =
    "time the reader filled in, by a tuplet's number no notes were given to";
/// Blank time in two places in a voice, one of them between its notes, in a bar with small
/// notes read as grace notes: they may be notes that take that time (another verse's rhythm).
pub const PAD_SMALL: &str =
    "time the reader filled in between a voice's notes, by small notes read as grace notes";
/// One head two voices' stems share.
pub const SHARED_HEAD: &str = "a head two stems share";
/// A tuplet's number no notes were given to.
pub const NUMBER_LOOSE: &str = "a tuplet's number no notes were given to";
/// More than two voices.
pub const VOICES_MANY: &str = "more than two voices";

// Ink: what is printed in the staff's bar that nothing written uses, the page's other staves'
// notes counted (`staff::read_staff_bar`). Not kept: a read bar with one is asked in the review
// (`review`), not unread. On the working set (gen): 3 of its 96 wrong bars, 60 of 46,944 right.

/// A stem standing where a head's own stem would (up from its right, down from its left, the
/// head at its end), with no head on it: the head was hung from another stem.
pub const INK_STEM_LEFT: &str = "a stem left bare by the head at its end";
/// A stem in the staff's band that no head on the page hangs from.
pub const INK_STEM_BARE: &str = "a stem no head hangs from";
/// A beam across two or more of the staff's notes' stems that no note took.
pub const INK_BEAM: &str = "a beam across the staff's stems that no note took";
/// A flag on no stem of the page, or on a note of the staff's whose length took no flag.
pub const INK_FLAG: &str = "a flag by no note's stem";

/// The doubts of each staff's bar that are told only with the bar's other staves read: `evs`
/// each staff's notes and rests as found, `voices` each staff's reading.
pub fn of_bar(
    evs: &[Vec<Ev>],
    voices: &[Result<Vec<Vec<Ev>>, String>],
    sp: f64,
) -> Vec<Vec<&'static str>> {
    use crate::columns::{column_x, Mark};
    use crate::frac::Q;
    use crate::staff::Rest;
    // each staff's marks, with whether the note comes after blank time in its voice
    let marked: Vec<Vec<(Mark, bool, usize)>> = voices
        .iter()
        .map(|v| {
            let mut out = Vec::new();
            for (vi, voice) in v.iter().flatten().enumerate() {
                let (mut t, mut after) = (Q::ZERO, false);
                for e in voice {
                    after |= e.rest == Rest::Blank;
                    if e.is_note() && e.grace.is_none() {
                        let m = Mark {
                            x: column_x(e),
                            at: t,
                            play: 0.0,
                            wide: false,
                            sign: false,
                        };
                        out.push((m, after, vi));
                    }
                    t += e.takes();
                }
            }
            out
        })
        .collect();
    let mut all = Vec::new();
    for (i, v) in voices.iter().enumerate() {
        let mut ds: Vec<&'static str> = Vec::new();
        let Ok(vs) = v else {
            all.push(ds);
            continue;
        };
        let blank = |v: &Vec<Ev>| v.iter().any(|e| e.rest == Rest::Blank);
        if vs.iter().any(blank) {
            ds.push(PAD_ANY);
        }
        // blank time with notes of its voice both before and after it
        let inner = vs.iter().any(|v| {
            let first = v.iter().position(|e| e.is_note());
            let last = v.iter().rposition(|e| e.is_note());
            match (first, last) {
                (Some(a), Some(b)) => v[a..b].iter().any(|e| e.rest == Rest::Blank),
                _ => false,
            }
        });
        if inner {
            ds.push(PAD_INNER);
        }
        let sure = |x: f64, reach: f64| {
            marked
                .iter()
                .flatten()
                .filter(|(m, after, _)| !after && (m.x - x).abs() <= reach * sp)
                .min_by(|a, b| (a.0.x - x).abs().total_cmp(&(b.0.x - x).abs()))
                .map(|(m, _, _)| m.at)
        };
        for (m, after, vi) in &marked[i] {
            if !after {
                continue;
            }
            if sure(m.x, 0.7) != Some(m.at) {
                ds.push(PAD_UNCONFIRMED);
                // clear of its own staff's other voice's note at its start
                let clear = marked[i]
                    .iter()
                    .any(|(o, oa, ov)| !oa && ov != vi && o.at == m.at && m.x - o.x > 0.7 * sp);
                if clear {
                    ds.push(PAD_BESIDE);
                }
            }
        }
        let small = |e: &Ev| !e.heads.is_empty() && e.heads.iter().all(|h| h.size < 0.8 * 4.0 * sp);
        if evs[i].iter().any(|e| small(e) && e.grace.is_none()) {
            ds.push(SMALL_TIMED);
        }
        if evs[i]
            .iter()
            .any(|e| small(e) && e.grace == Some(false) && e.stem.is_some())
        {
            ds.push(SMALL_GRACE);
        }
        let keys: Vec<Vec<(u64, u64)>> = evs[i]
            .iter()
            .map(|e| e.heads.iter().map(key).collect())
            .collect();
        let shared = (0..keys.len()).any(|a| {
            (0..a).any(|b| {
                evs[i][a].dur != evs[i][b].dur && keys[a].iter().any(|k| keys[b].contains(k))
            })
        });
        if shared {
            ds.push(SHARED_HEAD);
        }
        if evs[i]
            .iter()
            .any(|e| e.loose.iter().any(|l| l.3) && e.tuplets.is_empty())
        {
            ds.push(NUMBER_LOOSE);
        }
        if vs.len() > 2 {
            ds.push(VOICES_MANY);
        }
        // a voice with blank time in two places: where its notes stand between them is spacing
        let runs = |v: &Vec<Ev>| {
            let mut n = 0;
            let mut was = false;
            for e in v {
                let b = e.rest == Rest::Blank;
                if b && !was {
                    n += 1;
                }
                was = b;
            }
            n
        };
        if vs
            .iter()
            .any(|v| runs(v) >= 2 && v.iter().any(|e| e.is_note()))
        {
            ds.push(PAD_TWICE);
        }
        // a small note read as a grace note that stands clear of the note after it (a grace
        // note is set close before its note), or after the bar's last
        let apart = evs[i].iter().any(|e| {
            let next = evs[i]
                .iter()
                .filter(|o| o.is_note() && o.grace.is_none() && o.left() > e.left() + 0.2 * sp)
                .map(|o| o.left())
                .fold(f64::MAX, f64::min);
            small(e) && e.grace == Some(false) && e.stem.is_some() && next - e.right() > 2.0 * sp
        });
        if apart {
            ds.push(SMALL_APART);
        }
        // a small note read as a grace note at the place of a full-size rest of its staff: a
        // note of another verse's rhythm, which sounds where the rest stands
        let lone = |e: &&Ev| small(e) && e.grace == Some(false) && e.stem.is_some();
        let by_rest = |e: &Ev| {
            evs[i].iter().any(|o| match &o.rest {
                Rest::Printed(g) => (g.x0 - e.left()).abs() < 0.7 * sp && g.size > 0.8 * 4.0 * sp,
                _ => false,
            })
        };
        if vs.iter().flatten().filter(lone).any(by_rest) {
            ds.push(SMALL_BY_REST);
        }
        // a voice of small notes alone, read as taking time after the bar's last full-size
        // note, with blank time before them: when they sound is a guess (they may be the note's
        // closing notes, or grace notes leading over the barline)
        let last_full = (evs[i].iter())
            .filter(|e| e.is_note() && !small(e))
            .map(|e| e.left())
            .fold(f64::MIN, f64::max);
        let small_padded = last_full > f64::MIN
            && vs.iter().any(|v| {
                // (with a rest printed for them they are a voice in its own time)
                let mut notes = v.iter().filter(|e| e.is_note() && e.grace.is_none());
                v.iter().any(|e| e.rest == Rest::Blank)
                    && !v.iter().any(|e| matches!(e.rest, Rest::Printed(_)))
                    && v.iter().any(|e| e.is_note())
                    && notes.all(|e| small(e) && e.left() > last_full + 0.6 * sp)
            });
        if small_padded {
            ds.push(SMALL_PADDED);
        }
        if ds.contains(&PAD_ANY) && ds.contains(&NUMBER_LOOSE) {
            ds.push(PAD_NUMBER);
        }
        if ds.contains(&PAD_TWICE) && ds.contains(&PAD_INNER) && ds.contains(&SMALL_GRACE) {
            ds.push(PAD_SMALL);
        }
        ds.sort();
        ds.dedup();
        all.push(ds);
    }
    all
}

/// A tie-like curve into a system's first notes with no tie left open by the system before.
pub const TIE_IN_UNCARRIED: &str = "a tie from the system before whose note was not found";
/// A flat curve between two notes at one height that was not read as a tie.
pub const TIE_FAILED: &str = "a curve between two notes at one height that was not read as a tie";
/// A flat curve ending at a note, with no note found at its start.
pub const TIE_NO_START: &str = "a curve like a tie whose first note was not found";
/// A tie read from a curve with no note found to land on.
pub const TIE_DROPPED: &str = "a tie with no note found to land on";

/// A note a tie (or a curve like one, from the bar before) ends by. No doubt of itself.
pub const TIE_ENDS: &str = "a tie ends by it";
/// A tie into a bar from a bar left unread.
pub const TIE_FROM_UNREAD: &str = "a tie from a bar that was not read";
/// The same, the bar not read having an accidental on the tied note's place.
pub const TIE_FROM_UNREAD_SIGNED: &str =
    "a tie from a bar that was not read, which has an accidental on its place";
/// A curve not read as a tie, from a chord with other notes tied.
pub const TIE_PARTIAL: &str = "a chord some of whose ties were not read";

/// What a flat curve that ends by a note and was not read as a tie leaves in doubt of that note:
/// `incoming`, for one that comes from the system before, says whether a tie was left open on a
/// place; `start`, the note at its left end.
pub fn of_curve(
    incoming: Option<&dyn Fn(i32) -> bool>,
    start: Option<&Ev>,
    end: &Ev,
    cy: f64,
    sp: f64,
) -> Option<&'static str> {
    let k = ends_by(end, cy, sp)?;
    let h = &end.heads[k];
    match (incoming, start) {
        (Some(carried), _) => (!carried(end.place_of[k])).then_some(TIE_IN_UNCARRIED),
        (None, Some(s)) => {
            let same = s.heads.iter().any(|o| (o.y - h.y).abs() < 0.2 * sp);
            (same && s.x < end.x - 0.5 * sp).then_some(TIE_FAILED)
        }
        (None, None) => Some(TIE_NO_START),
    }
}

/// A tie was dropped for want of a note to land on: a doubt of the bar it would have landed in.
pub fn tie_dropped(bar: &mut Result<Vec<Vec<Ev>>, String>) {
    let first = bar
        .iter_mut()
        .flatten()
        .flatten()
        .find(|e| e.is_note() && e.grace.is_none());
    if let Some(e) = first {
        e.doubts.push(TIE_DROPPED);
    }
}

/// The head of a note that a curve at height `cy` ends by: the one nearest its height, close
/// by, with no accidental of its own (a tie does not change the pitch).
pub fn ends_by(end: &Ev, cy: f64, sp: f64) -> Option<usize> {
    let (k, h) = end
        .heads
        .iter()
        .enumerate()
        .min_by(|a, b| (a.1.y - cy).abs().total_cmp(&(b.1.y - cy).abs()))?;
    ((h.y - cy).abs() <= 1.5 * sp && !end.accs.contains_key(end.place_of.get(k)?)).then_some(k)
}

/// The alteration in force on each place at a bar's end: the last accidental printed on it in
/// the bar (`printed`: onset, place, alteration, in order), else the one tied into the bar.
pub fn in_force(
    printed: &[(crate::frac::Q, i32, i32)],
    tied_in: &std::collections::BTreeMap<i32, i32>,
) -> std::collections::BTreeMap<i32, i32> {
    let mut left = tied_in.clone();
    left.extend(printed.iter().map(|&(_, p, a)| (p, a)));
    left
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frac::Q;
    use crate::staff::Rest;

    const SP: f64 = 10.0;

    fn glyph(code: u32, x: f64, y: f64) -> Glyph {
        Glyph {
            code,
            x0: x,
            x1: x + if code == smufl::DOT { 4.0 } else { 12.0 },
            y,
            size: 40.0,
        }
    }

    fn head(x: f64, y: f64) -> Glyph {
        glyph(0xE0A4, x, y)
    }

    fn dot(x: f64, y: f64) -> Glyph {
        glyph(smufl::DOT, x, y)
    }

    fn chord(x: f64, ys: &[f64], up: bool) -> Ev {
        let mut e = Ev::new(ys.iter().map(|&y| head(x, y)).collect(), None, Some(up));
        e.dur = Q::ONE;
        e.place_of = ys.iter().map(|y| 40 - (*y / 5.0) as i32).collect();
        e.places = e.place_of.clone();
        e
    }

    fn said(out: &[Ev], dots: &[Glyph]) -> Vec<Dotted> {
        let heads: Vec<Glyph> = out.iter().flat_map(|e| e.heads.clone()).collect();
        dots_by_column(out, &heads, dots, SP)
    }

    #[test]
    fn a_dot_past_another_voice_s_head_is_its_note_s() {
        // a chord of two half notes stemmed down, and a second up from its top note another
        // voice's note set past it: four dots in one column past that note, two of them the
        // chord's though they stand a head further from it than a dot does
        let out = [
            chord(100.0, &[20.0, 40.0], false),
            chord(113.0, &[15.0, 50.0], true),
        ];
        let dots = [
            dot(130.0, 15.0),
            dot(130.0, 20.0),
            dot(130.0, 40.0),
            dot(130.0, 45.0),
        ];
        let s = said(&out, &dots);
        assert_eq!((s[0].dots, s[1].dots), (Some(1), Some(1)));
        assert_eq!(s[0].taken.len(), 2);
        // one dot, in the space of the second voice's note: the chord has none
        let out = [chord(100.0, &[25.0], false), chord(113.0, &[20.0], true)];
        let s = said(&out, &[dot(130.0, 20.0)]);
        assert_eq!((s[0].dots, s[1].dots), (Some(0), Some(1)));
    }

    #[test]
    fn dots_one_after_the_other_are_one_note_s_and_one_over_the_other_two_notes() {
        // two voices' notes at one height side by side: two dots in a column are one each
        let out = [chord(100.0, &[20.0], false), chord(113.0, &[20.0], true)];
        let s = said(&out, &[dot(130.0, 20.0), dot(130.0, 25.0)]);
        assert_eq!((s[0].dots, s[1].dots), (Some(1), Some(1)));
        // one dot may be either's: nothing is said, and both notes are in doubt
        let s = said(&out, &[dot(130.0, 20.0)]);
        assert_eq!((s[0].dots, s[0].doubt), (None, Some(DOT_EITHER)));
        // three dots by two single notes fit no reading
        let s = said(
            &out,
            &[dot(130.0, 15.0), dot(130.0, 20.0), dot(130.0, 25.0)],
        );
        assert_eq!(s[1].doubt, Some(DOTS_UNFIT));
    }

    #[test]
    fn a_black_head_two_stems_share_has_its_dot_for_both_notes() {
        // a dotted chord stemmed down whose top head another voice's note stemmed up hangs
        // from too: two dots, one by each head; the shared one is both notes'
        let down = chord(100.0, &[20.0, 30.0], false);
        let up = chord(100.0, &[20.0], true);
        let dots = [dot(116.0, 20.0), dot(116.0, 30.0)];
        let s = said(&[down.clone(), up.clone()], &dots);
        assert_eq!((s[0].dots, s[1].dots), (Some(1), Some(1)));
        assert_eq!((s[0].shared.len(), s[1].shared.len()), (1, 1));
        assert_eq!(s[0].shared, s[1].shared);
        // a hollow head shared with a black note's stem: the dots the half note's alone
        let hollow = |mut e: Ev| {
            e.heads.iter_mut().for_each(|h| h.code = 0xE0A3);
            e
        };
        let s = said(&[hollow(down), hollow(up)], &dots);
        assert_eq!((s[0].dots, s[1].dots), (Some(1), Some(0)));
        assert!(s[0].shared.is_empty());
    }

    #[test]
    fn a_chord_clear_of_the_other_voice_s_keeps_its_dots_by_its_own_heads() {
        // a low note with its dot by its head, under a wide chord (a second in it) whose dots
        // stand past its further head
        let mut wide = chord(100.0, &[10.0, 15.0], true);
        wide.heads[1].x0 = 112.0;
        wide.heads[1].x1 = 124.0;
        let out = [chord(100.0, &[60.0], false), wide];
        let s = said(
            &out,
            &[dot(116.0, 60.0), dot(128.0, 10.0), dot(128.0, 20.0)],
        );
        assert_eq!((s[0].dots, s[1].dots), (Some(1), Some(1)));
    }

    #[test]
    fn a_dot_or_an_accidental_that_no_note_took_is_a_doubt_of_the_note_by_it() {
        let mut out = vec![chord(100.0, &[20.0], true), chord(200.0, &[20.0], true)];
        let dots = [dot(118.0, 20.0)];
        unclaimed_dots(&mut out, &dots, &[], &[], (0.0, 40.0), SP);
        assert_eq!(out[0].doubts, vec![DOT_UNCLAIMED]);
        assert!(out[1].doubts.is_empty());
        let mut out = vec![chord(100.0, &[20.0], true)];
        unclaimed_dots(&mut out, &dots, &[], &[key(&dots[0])], (0.0, 40.0), SP);
        // (nor is a dot by another staff's head)
        unclaimed_dots(&mut out, &dots, &[head(104.0, 22.0)], &[], (0.0, 40.0), SP);
        assert!(out[0].doubts.is_empty());
        unclaimed_signs(&mut out, &[glyph(0xE262, 80.0, 25.0)], SP);
        assert_eq!(out[0].doubts, vec![SIGN_UNCLAIMED]);
        assert_eq!(kept(&out, &[]), Some(SIGN_UNCLAIMED));
        assert!(sure(&out, &[], Ok(vec![out.clone()])).is_err());
        // (a bar of rests has nothing to doubt)
        assert!(sure(&out, &[], Ok(vec![vec![Ev::spacer(Q::int(4), 0.0)]])).is_ok());
    }

    #[test]
    fn blank_time_by_a_tuplet_s_number_no_notes_took_is_a_doubt() {
        let mut a = chord(100.0, &[20.0], true);
        a.loose.push((3, 2, 100.0, true));
        let evs = vec![vec![a.clone()]];
        let padded = vec![Ok(vec![vec![a.clone(), Ev::spacer(Q::int(3), 150.0)]])];
        assert!(of_bar(&evs, &padded, SP)[0].contains(&PAD_NUMBER));
        let full = vec![Ok(vec![vec![a.clone()]])];
        assert!(!of_bar(&evs, &full, SP)[0].contains(&PAD_NUMBER));
        // a small note read as a grace note, in a voice with blank time between its notes and
        // after them: it may be a note that takes that time
        let mut small = chord(120.0, &[20.0], true);
        small.heads[0].size = 26.0;
        small.grace = Some(false);
        small.stem = Some(crate::page::VLine {
            x: 132.0,
            y0: -10.0,
            y1: 20.0,
            w: 1.0,
        });
        let b = chord(160.0, &[20.0], true);
        let blank = || Ev::spacer(Q::ONE, 140.0);
        let evs = vec![vec![a.clone(), small.clone(), b.clone()]];
        let read = vec![Ok(vec![vec![
            a.clone(),
            small.clone(),
            blank(),
            b.clone(),
            blank(),
        ]])];
        assert!(of_bar(&evs, &read, SP)[0].contains(&PAD_SMALL));
        let once = vec![Ok(vec![vec![a.clone(), small.clone(), b.clone(), blank()]])];
        assert!(!of_bar(&evs, &once, SP)[0].contains(&PAD_SMALL));
        // a small note read as a grace note under a full-size rest: it sounds where the rest is
        let mut rest = Ev::new(Vec::new(), None, None);
        rest.rest = Rest::Printed(glyph(0xE4E6, 122.0, 10.0));
        let evs = vec![vec![a.clone(), rest.clone(), small.clone(), b.clone()]];
        let read = vec![Ok(vec![vec![a.clone(), rest, small.clone(), b.clone()]])];
        assert!(of_bar(&evs, &read, SP)[0].contains(&SMALL_BY_REST));
        assert!(KEPT.contains(&SMALL_BY_REST));
        // (not one read as taking time, nor with no rest there)
        let mut timed = small.clone();
        timed.grace = None;
        let read = vec![Ok(vec![vec![a.clone(), timed, b.clone()]])];
        assert!(!of_bar(&evs, &read, SP)[0].contains(&SMALL_BY_REST));
        let evs = vec![vec![a.clone(), small.clone(), b.clone()]];
        let read = vec![Ok(vec![vec![a.clone(), small.clone(), b.clone()]])];
        assert!(!of_bar(&evs, &read, SP)[0].contains(&SMALL_BY_REST));
        // a small note after the bar's last full-size note, read as a voice of its own that
        // takes time after blank time: a guess (it may lead over the barline)
        let mut last = small.clone();
        last.grace = None;
        last.heads[0].x0 += 80.0;
        last.heads[0].x1 += 80.0;
        let evs = vec![vec![a.clone(), b.clone(), last.clone()]];
        let read = vec![Ok(vec![
            vec![a.clone(), b.clone()],
            vec![blank(), last.clone()],
        ])];
        assert!(of_bar(&evs, &read, SP)[0].contains(&SMALL_PADDED));
        assert!(KEPT.contains(&SMALL_PADDED));
        // (not one in a full-size note's column, nor a voice with nothing filled in)
        let mut under = last.clone();
        under.heads[0].x0 = b.heads[0].x0;
        under.heads[0].x1 = b.heads[0].x1;
        let evs_under = vec![vec![a.clone(), b.clone(), under.clone()]];
        let read = vec![Ok(vec![vec![a.clone(), b.clone()], vec![blank(), under]])];
        assert!(!of_bar(&evs_under, &read, SP)[0].contains(&SMALL_PADDED));
        let read = vec![Ok(vec![vec![a, b], vec![last]])];
        assert!(!of_bar(&evs, &read, SP)[0].contains(&SMALL_PADDED));
        assert_eq!(Ev::spacer(Q::ONE, 0.0).rest, Rest::Blank);
    }

    #[test]
    fn a_tie_s_end_is_by_a_head_with_no_accidental_and_takes_the_bar_before_s_alteration() {
        let mut e = chord(100.0, &[20.0, 40.0], true);
        assert_eq!(ends_by(&e, 42.0, SP), Some(1));
        assert_eq!(ends_by(&e, 70.0, SP), None);
        e.accs.insert(e.place_of[1], (1, false));
        assert_eq!(ends_by(&e, 42.0, SP), None);
        // the last accidental printed on a place holds at the bar's end, else the one tied in
        let printed = [(Q::ZERO, 30, 1), (Q::ONE, 30, 0), (Q::ONE, 32, -1)];
        let tied = [(28, 1), (32, 1)].into_iter().collect();
        let left = in_force(&printed, &tied);
        assert_eq!((left[&30], left[&32], left[&28]), (0, -1, 1));
        // a flat curve from the system before to a place no tie was left open on
        let e = chord(100.0, &[20.0], true);
        let none = |_: i32| false;
        assert_eq!(
            of_curve(Some(&none), None, &e, 21.0, SP),
            Some(TIE_IN_UNCARRIED)
        );
        let earlier = chord(40.0, &[20.0], true);
        assert_eq!(
            of_curve(None, Some(&earlier), &e, 21.0, SP),
            Some(TIE_FAILED)
        );
        let mut bar = Ok(vec![vec![e]]);
        tie_dropped(&mut bar);
        assert_eq!(bar.unwrap()[0][0].doubts, vec![TIE_DROPPED]);
    }

    #[test]
    fn a_tremolo_between_notes_the_voices_set_apart_leaves_the_bar_unread() {
        use crate::staff::Trem;
        let mut a = chord(100.0, &[20.0], true);
        a.tremolo = Some(Trem::Start(3));
        let mut b = chord(160.0, &[30.0], true);
        b.tremolo = Some(Trem::Stop);
        let mut rest = chord(160.0, &[30.0], true);
        rest.rest = Rest::Blank;
        assert!(tremolos_paired(&[vec![a.clone(), b.clone()]]));
        assert!(!tremolos_paired(&[vec![a.clone()], vec![b.clone()]]));
        assert!(!tremolos_paired(&[vec![
            a.clone(),
            rest.clone(),
            b.clone()
        ]]));
        let said = sure(&[], &[], Ok(vec![vec![a, rest]]));
        assert_eq!(said.err(), Some(TREMOLO_APART.to_string()));
    }
}