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
//! Songs repeat: a staff's bar the reader could not time often stands again elsewhere in the
//! score (another verse, an accompaniment figure that comes back) in a bar it could.
//!
//! Two bars of one staff are *twins* when they print the same thing: the same chords and rests
//! in the same order, each with the same heads on the same places, the same stem, the same
//! length by head, flags, beams and dots, beamed in the same groups, and standing at the same
//! places across the bar in proportion. What the print does not say of such a bar (which voice
//! a note is in, where a hidden rest falls, what a tuplet's hidden member takes) it does not
//! say of its twin either, and the program that set both set them from the same notes.
//!
//! The score is read twice ([`Twins::again`]). The first pass keeps every staff's bar as it
//! stood ([`snap`]) with how it was read ([`Twins::note`]). On the second, a bar that cannot be
//! read takes the reading of its twins ([`as_their_twins`]): each of its own chords and rests
//! gets the voice, the length and the tuplet its twin's has, where every twin that was read was
//! read the same way, and the other staves' columns in its own bar do not gainsay it. Its
//! pitches, accidentals, ties, slurs and marks stay its own.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

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

/// How far a chord may stand from its twin's place, as a share of the way from the bar's first
/// chord or rest to its last (the words under another verse, an accidental, move a column).
const OFF: f64 = 0.12;

/// A chord or a rest as printed: what must be the same in a twin.
#[derive(Clone, Debug, PartialEq)]
struct Shape {
    /// A rest: its glyph and its height on the staff in half spaces (`(0, 0)`: a bar's rest).
    rest: Option<(u32, i32)>,
    /// Its heads low to high: each one's staff place and glyph.
    heads: Vec<(i32, u32)>,
    up: Option<bool>,
    written: Q,
    grace: Option<bool>,
    tuplets: Vec<(u32, u32)>,
    /// The beams it hangs from, numbered as the bar first comes to them.
    beams: Vec<usize>,
    tremolo: Option<Trem>,
    /// Tuplet numbers by it that no notes were given to.
    loose: usize,
    dots: (u8, bool),
}

/// A staff's bar as it stood before its voices were looked for.
#[derive(Clone, Debug, Default)]
pub(crate) struct Snap {
    /// Its chords and rests left to right (of those in one column, the lower first).
    evs: Vec<Ev>,
    shapes: Vec<Shape>,
    len: Q,
    sp: f64,
}

/// A staff's bar as it stands: `top` its staff's top line, `len` its length.
pub(crate) fn snap(evs: &[Ev], sp: f64, top: f64, len: Q) -> Snap {
    let low = |e: &Ev| match &e.rest {
        Rest::Printed(g) => (-2.0 * (g.y - top) / sp).round() as i32,
        _ => e.places.first().copied().unwrap_or(0),
    };
    let mut evs: Vec<Ev> = (evs.iter().filter(|e| e.rest != Rest::Blank))
        .cloned()
        .collect();
    evs.sort_by(|a, b| a.x.total_cmp(&b.x));
    // (those of one column in an order their places give, not the page's)
    let mut from = 0;
    for k in 1..=evs.len() {
        if k == evs.len() || evs[k].x - evs[k - 1].x > 0.25 * sp {
            evs[from..k].sort_by_key(|e| (low(e), e.up, e.heads.len()));
            from = k;
        }
    }
    let mut beams: Vec<usize> = Vec::new();
    let shapes = evs
        .iter()
        .map(|e| {
            let mut heads: Vec<(i32, u32)> = (e.place_of.iter().copied())
                .zip(e.heads.iter().map(|h| h.code))
                .collect();
            heads.sort();
            Shape {
                rest: match &e.rest {
                    Rest::Printed(g) => Some((g.code, low(e))),
                    Rest::Bar => Some((0, 0)),
                    _ => None,
                },
                heads,
                up: e.up,
                written: e.written(),
                grace: e.grace,
                tuplets: e.tuplets.iter().map(|t| (t.0, t.1)).collect(),
                beams: (e.beam_polys.iter())
                    .map(|p| match beams.iter().position(|q| q == p) {
                        Some(k) => k,
                        None => {
                            beams.push(*p);
                            beams.len() - 1
                        }
                    })
                    .collect(),
                tremolo: e.tremolo,
                loose: e.loose.len(),
                dots: (e.dots_shared, e.dots_partial),
            }
        })
        .collect();
    Snap {
        evs,
        shapes,
        len,
        sp,
    }
}

impl Snap {
    fn has_notes(&self) -> bool {
        self.evs.iter().any(|e| e.is_note())
    }

    /// Where each of its chords and rests stands, from the first (0) to the last (1).
    fn across(&self) -> Vec<f64> {
        let lo = self.evs.iter().map(|e| e.x).fold(f64::MAX, f64::min);
        let hi = self.evs.iter().map(|e| e.x).fold(f64::MIN, f64::max);
        let span = (hi - lo).max(1e-6);
        self.evs.iter().map(|e| (e.x - lo) / span).collect()
    }

    /// Whether the two bars print the same thing.
    fn twin_of(&self, o: &Snap) -> bool {
        self.len == o.len
            && self.shapes == o.shapes
            && (self.across().iter().zip(o.across())).all(|(a, b)| (a - b).abs() <= OFF)
    }
}

/// What a reading gave one chord or rest of a bar, or the blank time it put in a voice.
#[derive(Clone, Debug, PartialEq)]
struct Slot {
    /// Which of the bar's chords and rests ([`Snap::evs`]); `None`: time with nothing printed.
    of: Option<usize>,
    dur: Q,
    tuplets: Vec<(u32, u32, usize)>,
}

/// A reading's tuplets with their groups numbered as the bar first comes to them (from 1): a
/// group's number is the page's, and another bar's reading has others for the same thing.
fn groups_of(voices: &[Vec<Ev>]) -> impl Fn(&Ev) -> Vec<(u32, u32, usize)> {
    let mut ids: Vec<usize> = Vec::new();
    for t in voices.iter().flatten().flat_map(|e| e.tuplets.iter()) {
        if !ids.contains(&t.2) {
            ids.push(t.2);
        }
    }
    move |e: &Ev| {
        let number = |t: &(u32, u32, usize)| ids.iter().position(|i| *i == t.2).unwrap_or(0) + 1;
        e.tuplets.iter().map(|t| (t.0, t.1, number(t))).collect()
    }
}

/// How a bar was read: its voices, each a row of what the bar holds. `None` where the voices
/// do not hold the bar's own chords and rests, each once and whole (a note that went to the
/// part's other staff or came from it, a chord parted between two voices), or do not each fill
/// the bar.
fn reading_of(snap: &Snap, voices: &[Vec<Ev>]) -> Option<Vec<Vec<Slot>>> {
    let mut used = vec![false; snap.evs.len()];
    let groups = groups_of(voices);
    let mut out = Vec::new();
    for v in voices {
        let mut row = Vec::new();
        for e in v {
            let of = match e.rest {
                Rest::Blank => None,
                _ => {
                    let same = |s: &Ev| {
                        s.rest == e.rest
                            && s.heads == e.heads
                            && (s.up, s.grace, s.grace_after) == (e.up, e.grace, e.grace_after)
                            && s.tremolo == e.tremolo
                    };
                    let k = (0..used.len()).find(|&k| !used[k] && same(&snap.evs[k]))?;
                    used[k] = true;
                    Some(k)
                }
            };
            row.push(Slot {
                of,
                dur: e.dur,
                tuplets: groups(e),
            });
        }
        if v.iter().map(|e| e.takes()).sum::<Q>() != snap.len {
            return None;
        }
        out.push(row);
    }
    used.iter().all(|u| *u).then_some(out)
}

/// A bar's own chords and rests in the voices of a reading of its twin.
fn read_as(snap: &Snap, reading: &[Vec<Slot>]) -> Vec<Vec<Ev>> {
    reading
        .iter()
        .map(|row| {
            let mut voice: Vec<Ev> = Vec::new();
            for (k, slot) in row.iter().enumerate() {
                let mut e = match slot.of {
                    Some(of) => snap.evs[of].clone(),
                    // (blank time stands just before the voice's next note, or after its last)
                    None => {
                        let next = row[k + 1..].iter().find_map(|s| s.of);
                        let x = match (next, voice.last()) {
                            (Some(of), _) => snap.evs[of].x - 0.01,
                            (None, Some(last)) => last.x + 0.01,
                            (None, None) => 0.0,
                        };
                        Ev::spacer(slot.dur, x)
                    }
                };
                e.dur = slot.dur;
                e.tuplets = slot.tuplets.clone();
                voice.push(e);
            }
            voice
        })
        .collect()
}

/// A chord, a rest or blank time of a voice as it was read, by what it is and not where it
/// stands: what a bar of the same notes printed another way can be held against.
#[derive(Clone, Debug, PartialEq)]
struct Item {
    /// A chord's staff places, low to high; `Some(vec![])`: a printed rest; `None`: blank time.
    places: Option<Vec<i32>>,
    dur: Q,
    written: Q,
    tuplets: Vec<(u32, u32, usize)>,
    grace: bool,
}

/// A bar's voices as read, by what they hold ([`Item`]). None where a voice does not fill the
/// bar, or the bar holds something that is no plain chord or rest (a tremolo between two
/// notes, a note drawn on the part's other staff).
fn sounded(voices: &[Vec<Ev>], len: Q) -> Option<Vec<Vec<Item>>> {
    let plain = |e: &Ev| e.tremolo.is_none() && e.on_staff.is_none() && !e.grace_after;
    if !voices.iter().flatten().all(plain) {
        return None;
    }
    let filled = |v: &Vec<Ev>| v.iter().map(|e| e.takes()).sum::<Q>() == len;
    let groups = groups_of(voices);
    let item = |e: &Ev| Item {
        places: match e.rest {
            Rest::None => Some(e.places.clone()),
            Rest::Blank => None,
            _ => Some(Vec::new()),
        },
        dur: e.dur,
        written: e.written(),
        tuplets: groups(e),
        grace: e.grace.is_some(),
    };
    (voices.iter().all(filled)).then(|| {
        voices
            .iter()
            .map(|v| v.iter().map(item).collect())
            .collect()
    })
}

/// A bar read as another of the same notes was (`items`: [`sounded`]), where it can be: each
/// of its chords is one of the other's, of the same places and printed length, taken in the
/// order they start as it stands left to right; each of its printed rests one of the other's
/// (a rest the other prints and it does not is time it hides); and its chords then stand as
/// their starts say: those of one start in one column, a later start further right.
fn read_like(snap: &Snap, items: &[Vec<Item>]) -> Option<Vec<Vec<Slot>>> {
    let n = snap.evs.len();
    let plain = |e: &Ev| e.tremolo.is_none() && e.on_staff.is_none() && !e.grace_after;
    if !snap.evs.iter().all(plain) {
        return None;
    }
    // the other's chords and rests in the order they start: (start, voice, index)
    let mut order: Vec<(Q, usize, usize)> = Vec::new();
    for (vi, v) in items.iter().enumerate() {
        let mut t = Q::ZERO;
        for (ki, it) in v.iter().enumerate() {
            order.push((t, vi, ki));
            if !it.grace {
                t += it.dur;
            }
        }
    }
    order.sort_by_key(|o| o.0);
    let mut slots: Vec<Vec<Slot>> = items
        .iter()
        .map(|v| {
            let slot = |it: &Item| Slot {
                of: None,
                dur: it.dur,
                tuplets: it.tuplets.clone(),
            };
            v.iter().map(slot).collect()
        })
        .collect();
    let mut starts: Vec<Option<Q>> = vec![None; n];
    for (t, vi, ki) in order {
        let it = &items[vi][ki];
        let Some(places) = &it.places else {
            continue;
        };
        let fits = |e: &Ev| {
            e.written() == it.written
                && e.grace.is_some() == it.grace
                && match e.rest {
                    Rest::None => !places.is_empty() && e.places == *places,
                    _ => places.is_empty(),
                }
        };
        match (0..n).find(|&k| starts[k].is_none() && fits(&snap.evs[k])) {
            Some(k) => {
                starts[k] = Some(t);
                slots[vi][ki].of = Some(k);
            }
            // (a chord of the other's that is not here: another bar)
            None if !places.is_empty() => return None,
            None => {}
        }
    }
    if starts.iter().any(|t| t.is_none()) {
        return None;
    }
    // where its chords stand against when they start
    let stood: Vec<(f64, Q)> = (0..n)
        .filter(|&k| snap.evs[k].is_note() && snap.evs[k].grace.is_none())
        .filter_map(|k| Some((crate::columns::column_x(&snap.evs[k]), starts[k]?)))
        .collect();
    for (a, &(xa, ta)) in stood.iter().enumerate() {
        for &(xb, tb) in &stood[a + 1..] {
            let ((x0, t0), (x1, t1)) = if xa <= xb {
                ((xa, ta), (xb, tb))
            } else {
                ((xb, tb), (xa, ta))
            };
            let apart = (x1 - x0) / snap.sp;
            if t1 < t0 || (t1 > t0 && apart < 0.3) || (t1 == t0 && apart > 2.2) {
                return None;
            }
        }
    }
    // (a voice of the other's with nothing of this bar's in it is no voice here)
    slots.retain(|v| v.iter().any(|s| s.of.is_some()));
    Some(slots)
}

struct Known {
    number: i64,
    snap: Snap,
    /// How it was read, in its own chords and rests ([`reading_of`]) and by what its voices
    /// hold ([`sounded`]); and whether it was left unread.
    read: Option<Vec<Vec<Slot>>>,
    sounded: Option<Vec<Vec<Item>>>,
    unread: bool,
}

#[derive(Default)]
struct Store {
    /// staff -> its bars with notes, as the first pass found and read them.
    known: BTreeMap<String, Vec<Known>>,
    /// The first pass came to the score's end.
    whole: bool,
    /// The second pass is on: bars are read as their twins, and none is noted.
    second: bool,
    said: Vec<String>,
}

/// Every staff's bars of a score, as they stood and as they were read, over its two passes.
#[derive(Clone, Default)]
pub(crate) struct Twins(Rc<RefCell<Store>>);

impl Twins {
    /// First pass: a staff's bar and the voices it was read in (a bar left as a rest too: it is
    /// struck off at [`Twins::close`]).
    pub(crate) fn note(&self, staff: &str, number: i64, snap: &Snap, voices: &[Vec<Ev>]) {
        let mut s = self.0.borrow_mut();
        if s.second || !snap.has_notes() {
            return;
        }
        let read = reading_of(snap, voices);
        let sounded = sounded(voices, snap.len);
        s.known.entry(staff.to_string()).or_default().push(Known {
            number,
            snap: snap.clone(),
            read,
            sounded,
            unread: false,
        });
    }

    /// The first pass's end: the bars left unread after they were noted are no reading.
    pub(crate) fn close(&self, unread: impl Fn(i64, &str) -> bool) {
        let mut s = self.0.borrow_mut();
        if s.second {
            return;
        }
        for (staff, bars) in s.known.iter_mut() {
            for k in bars.iter_mut().filter(|k| unread(k.number, staff)) {
                (k.read, k.sounded, k.unread) = (None, None, true);
            }
        }
        s.whole = true;
        if std::env::var("FMV_TWINS").is_ok() {
            for (bar, staff, kind) in disagreeing(&s.known) {
                eprintln!("TWINDOUBT\t{bar}\t{staff}\t{kind}");
            }
        }
    }

    /// Whether a second pass has something to read: a bar left unread that a bar that was
    /// read gives a reading. From here on the second pass is on.
    pub(crate) fn again(&self) -> bool {
        let mut s = self.0.borrow_mut();
        let any = s.whole
            && s.known.values().any(|bars| {
                (bars.iter().filter(|u| u.unread)).any(|u| reading_among(bars, &u.snap).is_some())
            });
        s.second = any;
        any
    }

    /// Second pass: the reading the staff's bars that were read give a bar, in its own chords
    /// and rests, and the number of the bar it is read as ([`reading_among`]).
    fn reading_for(&self, staff: &str, snap: &Snap) -> Option<(Vec<Vec<Ev>>, i64)> {
        let s = self.0.borrow();
        if !s.second || !snap.has_notes() {
            return None;
        }
        let (reading, twin) = reading_among(s.known.get(staff)?, snap)?;
        Some((read_as(snap, &reading), twin))
    }

    /// Says, for the person, that a bar was read as another.
    pub(crate) fn say(&self, what: String) {
        self.0.borrow_mut().said.push(what);
    }

    pub(crate) fn said(&self) -> Vec<String> {
        self.0.borrow().said.clone()
    }
}

/// The bars read otherwise than bars that print the same thing (`FMV_TWINS`, for measuring a
/// doubt): (bar, staff, how). `twins-minority`: its twins were read more often another way;
/// `twins-split`: its twins were read as many ways with none the most; `like-minority`: more of
/// the bars of the same notes it can be read as ([`read_like`]) give it another timing than its
/// own; `like-other`: one does at least.
fn disagreeing(known: &BTreeMap<String, Vec<Known>>) -> Vec<(i64, String, &'static str)> {
    let mut out = Vec::new();
    // its chords' and rests' starts and lengths
    let timed = |r: &Vec<Vec<Slot>>| {
        let mut out: Vec<(usize, Q, Q)> = Vec::new();
        for v in r {
            let mut t = Q::ZERO;
            for sl in v {
                if let Some(k) = sl.of {
                    out.push((k, t, sl.dur));
                }
                t += sl.dur;
            }
        }
        out.sort_by_key(|o| o.0);
        out
    };
    for (staff, bars) in known {
        let mut done = vec![false; bars.len()];
        for a in 0..bars.len() {
            if done[a] || bars[a].read.is_none() {
                continue;
            }
            let group: Vec<usize> = (a..bars.len())
                .filter(|&k| !done[k] && bars[k].read.is_some())
                .filter(|&k| bars[k].snap.twin_of(&bars[a].snap))
                .collect();
            let mut ways: Vec<(&Known, Vec<i64>)> = Vec::new();
            for &k in &group {
                done[k] = true;
                match ways.iter_mut().find(|w| w.0.read == bars[k].read) {
                    Some(w) => w.1.push(bars[k].number),
                    None => ways.push((&bars[k], vec![bars[k].number])),
                }
            }
            if ways.len() < 2 {
                continue;
            }
            let most = ways.iter().map(|w| w.1.len()).max().unwrap_or(0);
            let one_most = ways.iter().filter(|w| w.1.len() == most).count() == 1;
            for w in &ways {
                let kind = match (one_most, w.1.len() == most) {
                    (true, true) => continue,
                    (true, false) => "twins-minority",
                    _ => "twins-split",
                };
                out.extend(w.1.iter().map(|n| (*n, staff.clone(), kind)));
            }
        }
        let plain = |k: &Known| k.snap.evs.iter().all(|e| e.grace.is_none());
        for a in bars.iter().filter(|a| a.read.is_some() && plain(a)) {
            let Some(mine) = a.read.as_ref().map(timed) else {
                continue;
            };
            let (mut same, mut other) = (0, 0);
            for b in bars
                .iter()
                .filter(|b| b.number != a.number && b.snap.len == a.snap.len)
            {
                if let Some(r) = b.sounded.as_ref().and_then(|it| read_like(&a.snap, it)) {
                    if timed(&r) == mine {
                        same += 1;
                    } else {
                        other += 1;
                    }
                }
            }
            if other > same {
                out.push((a.number, staff.clone(), "like-minority"));
            } else if other > 0 {
                out.push((a.number, staff.clone(), "like-other"));
            }
        }
    }
    out
}

/// The one reading a staff's bars that were read give a bar of it, and the first such bar's
/// number: that of its twins, the bars that print the same thing ([`Snap::twin_of`]); with no
/// twin read, that of the bars of the same notes printed another way that it can be read as
/// ([`read_like`]: a bar that prints the rests this one hides, or stems its voices apart). None
/// where there is no such bar, or they give more readings than one.
fn reading_among(bars: &[Known], snap: &Snap) -> Option<(Vec<Vec<Slot>>, i64)> {
    let mut twins = (bars.iter()).filter(|k| k.read.is_some() && k.snap.twin_of(snap));
    if let Some(first) = twins.next() {
        let one = twins.all(|k| k.read == first.read);
        return one
            .then(|| first.read.clone())
            .flatten()
            .map(|r| (r, first.number));
    }
    let mut like = (bars.iter().filter(|k| k.snap.len == snap.len))
        .filter_map(|k| Some((read_like(snap, k.sounded.as_ref()?)?, k.number)));
    let first = like.next()?;
    like.all(|l| l.0 == first.0).then_some(first)
}

/// One bar's staves held against each other's columns (`columns::unread_misread_in`), and on
/// the second pass with their twins' readings: a staff that could not be read, or that the
/// columns leave unread, takes its twins' reading ([`Twins::reading_for`]) where the bar's
/// staves, the others as they were first read, then stand in the columns their starts say with
/// nothing gainsaid. `snaps`: the bar's staves as they stood. Gives the staves so read, each
/// with its twin's bar number.
pub(crate) fn held_by_columns(
    twins: &Twins,
    names: &[String],
    snaps: &[Snap],
    voices: &mut BarVoices,
    sp: f64,
    scales: &[Q],
) -> Vec<(usize, i64)> {
    let before = voices.clone();
    crate::columns::unread_misread_in(voices, sp, scales);
    // the staves to read as their twins: (staff, the reading, the twin's bar)
    let wanting = |i: usize| before[i].is_err() || voices[i].is_err();
    let found: Vec<(usize, Vec<Vec<Ev>>, i64)> = (0..before.len().min(snaps.len()))
        .filter(|&i| wanting(i))
        .filter_map(|i| {
            let (read, twin) = twins.reading_for(&names[i], &snaps[i])?;
            Some((i, read, twin))
        })
        .collect();
    let lengths = |v: &Result<Vec<Vec<Ev>>, String>| -> Option<Vec<Vec<Q>>> {
        let vs = v.as_ref().ok()?;
        Some(
            vs.iter()
                .map(|v| v.iter().map(|e| e.dur).collect())
                .collect(),
        )
    };
    // all of them at once, else the first that stands alone
    let all: Vec<usize> = (0..found.len()).collect();
    let tries = std::iter::once(all).chain((0..found.len()).map(|k| vec![k]));
    for taken in tries.take(if found.len() > 1 {
        found.len() + 1
    } else {
        found.len()
    }) {
        let mut with = before.clone();
        for &k in &taken {
            with[found[k].0] = Ok(found[k].1.clone());
        }
        let mut held = with.clone();
        crate::columns::unread_misread_in(&mut held, sp, scales);
        if (0..with.len()).all(|j| lengths(&held[j]) == lengths(&with[j])) {
            *voices = with;
            return taken.iter().map(|&k| (found[k].0, found[k].2)).collect();
        }
    }
    Vec::new()
}

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

    const TOP: f64 = 100.0;

    /// A quarter or an eighth (`beam`) at `x`, its head on `place`, stemmed up or down.
    fn note(x: f64, place: i32, up: bool, beam: Option<usize>) -> Ev {
        let head = Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y: TOP + 4.0 - place as f64 / 2.0,
            size: 4.0,
        };
        let stem = VLine {
            x: if up { x + 1.2 } else { x },
            y0: head.y - 3.5,
            y1: head.y,
            w: 0.1,
        };
        let mut e = Ev::new(vec![head], Some(stem), Some(up));
        e.place_of = vec![place];
        e.places = vec![place];
        e.dur = if beam.is_some() { Q::new(1, 2) } else { Q::ONE };
        e.beam_polys.extend(beam);
        e
    }

    /// A bar of 3/4 from `x0`, `wide` a beat: a dotted-quarter-long figure of three beamed
    /// eighths stemmed up, over a quarter stemmed down that enters on the second beat.
    fn bar(x0: f64, wide: f64, beam: usize, shift: i32) -> Vec<Ev> {
        vec![
            note(x0, 30 + shift, true, Some(beam)),
            note(x0 + wide / 2.0, 31 + shift, true, Some(beam)),
            note(x0 + wide, 32 + shift, true, Some(beam)),
            note(x0 + wide, 26 + shift, false, None),
            note(x0 + 2.0 * wide, 30 + shift, true, None),
        ]
    }

    /// The bar's reading: the upper voice an eighth short (a hidden eighth rest after the
    /// beam), the lower entering on the second beat and held.
    fn read(evs: &[Ev]) -> Vec<Vec<Ev>> {
        let mut low = evs[3].clone();
        low.dur = Q::int(2);
        vec![
            vec![
                evs[0].clone(),
                evs[1].clone(),
                evs[2].clone(),
                Ev::spacer(Q::new(1, 2), evs[4].x - 0.01),
                evs[4].clone(),
            ],
            vec![Ev::spacer(Q::ONE, low.x - 0.01), low],
        ]
    }

    fn snap_of(evs: &[Ev]) -> Snap {
        snap(evs, 1.0, TOP, Q::int(3))
    }

    /// A bar of a first pass: its number, its chords and rests, and its voices as read.
    type Passed<'a> = (i64, &'a [Ev], Option<Vec<Vec<Ev>>>);

    /// The store after a first pass over these bars of staff `P.1`: (number, bar, as read).
    fn passed(bars: &[Passed]) -> Twins {
        let twins = Twins::default();
        for (n, evs, read) in bars {
            let rest = vec![vec![Ev::spacer(Q::int(3), 0.0)]];
            twins.note("P.1", *n, &snap_of(evs), read.as_ref().unwrap_or(&rest));
        }
        twins.close(|n, _| bars.iter().any(|b| b.0 == n && b.2.is_none()));
        twins
    }

    #[test]
    fn a_bar_set_again_wider_is_its_twin_and_one_with_another_note_is_not() {
        let a = snap_of(&bar(10.0, 6.0, 3, 0));
        // (another system: wider, its beam another shape of the page)
        assert!(a.twin_of(&snap_of(&bar(200.0, 7.5, 9, 0))));
        // one note a step higher; a stem turned; a note moved a third of a beat
        assert!(!a.twin_of(&snap_of(&bar(10.0, 6.0, 3, 1))));
        let mut turned = bar(10.0, 6.0, 3, 0);
        turned[4].up = Some(false);
        assert!(!a.twin_of(&snap_of(&turned)));
        let mut moved = bar(10.0, 6.0, 3, 0);
        moved[1].x += 2.0;
        assert!(!a.twin_of(&snap_of(&moved)));
        // an eighth beamed apart from the other two
        let mut apart = bar(10.0, 6.0, 3, 0);
        apart[2].beam_polys = [4].into();
        assert!(!a.twin_of(&snap_of(&apart)));
        assert!(!a.twin_of(&snap(&bar(10.0, 6.0, 3, 0), 1.0, TOP, Q::int(4))));
    }

    #[test]
    fn an_unread_bar_takes_its_twins_voices_and_lengths_in_its_own_notes() {
        let (one, two) = (bar(10.0, 6.0, 3, 0), bar(200.0, 7.0, 9, 0));
        let twins = passed(&[(4, &one, Some(read(&one))), (12, &two, None)]);
        assert!(twins.again());
        let mut voices: BarVoices = vec![Err("two voices that do not each fill the bar".into())];
        let names = ["P.1".to_string()];
        let got = held_by_columns(&twins, &names, &[snap_of(&two)], &mut voices, 1.0, &[]);
        assert_eq!(got, vec![(0, 4)]);
        let vs = voices[0].as_ref().unwrap();
        // its own heads, where they stand
        assert_eq!(vs[0][0].heads, two[0].heads);
        assert_eq!(vs[1][1].heads, two[3].heads);
        let lens = |v: &[Ev]| {
            v.iter()
                .map(|e| (e.rest == Rest::Blank, e.dur))
                .collect::<Vec<_>>()
        };
        let half = Q::new(1, 2);
        assert_eq!(
            lens(&vs[0]),
            [
                (false, half),
                (false, half),
                (false, half),
                (true, half),
                (false, Q::ONE)
            ]
        );
        assert_eq!(lens(&vs[1]), [(true, Q::ONE), (false, Q::int(2))]);
        // (the blank time stands just before the note it leads to)
        assert!(vs[1][0].x < two[3].x && vs[1][0].x > two[2].x - 1.0);
    }

    #[test]
    fn a_bar_of_the_same_notes_spaced_otherwise_is_read_as_the_other_where_its_columns_agree() {
        let one = bar(10.0, 6.0, 3, 0);
        // (the second eighth drawn nearer the first, by words under it: no twin, the same notes)
        let mut two = bar(200.0, 6.0, 9, 0);
        two[1].x -= 2.0;
        assert!(!snap_of(&one).twin_of(&snap_of(&two)));
        // (its lower voice a quarter as printed, between blank time)
        let mut held = read(&one);
        held[1] = vec![
            Ev::spacer(Q::ONE, one[3].x - 0.01),
            one[3].clone(),
            Ev::spacer(Q::ONE, one[3].x + 0.01),
        ];
        let twins = passed(&[(4, &one, Some(held.clone())), (12, &two, None)]);
        assert!(twins.again());
        let mut voices: BarVoices = vec![Err("unread".into())];
        let names = ["P.1".to_string()];
        let got = held_by_columns(&twins, &names, &[snap_of(&two)], &mut voices, 1.0, &[]);
        assert_eq!(got, vec![(0, 4)]);
        let vs = voices[0].as_ref().unwrap();
        let lens = |v: &[Ev]| {
            v.iter()
                .map(|e| (e.rest == Rest::Blank, e.dur))
                .collect::<Vec<_>>()
        };
        assert_eq!(
            lens(&vs[1]),
            [(true, Q::ONE), (false, Q::ONE), (true, Q::ONE)]
        );
        assert_eq!(vs[1][1].heads, two[3].heads);
        // but not where its notes stand against their starts: the lower voice's quarter left of
        // the eighth that starts before it
        let mut three = bar(300.0, 6.0, 5, 0);
        three[3] = note(302.0, 26, false, None);
        let twins = passed(&[(4, &one, Some(held)), (12, &three, None)]);
        assert!(!twins.again());
    }

    #[test]
    fn twins_read_two_ways_give_no_reading() {
        let (one, two, three) = (
            bar(10.0, 6.0, 3, 0),
            bar(200.0, 7.0, 9, 0),
            bar(90.0, 6.5, 1, 0),
        );
        let mut other = read(&three);
        // (the lower voice's quarter first, then blank)
        other[1] = vec![three[3].clone(), Ev::spacer(Q::int(2), three[3].x + 0.01)];
        let twins = passed(&[
            (4, &one, Some(read(&one))),
            (8, &three, Some(other)),
            (12, &two, None),
        ]);
        assert!(!twins.again());
        let mut voices: BarVoices = vec![Err("unread".into())];
        let names = ["P.1".to_string()];
        let got = held_by_columns(&twins, &names, &[snap_of(&two)], &mut voices, 1.0, &[]);
        assert!(got.is_empty() && voices[0].is_err());
    }

    #[test]
    fn a_score_with_no_unread_bar_that_has_a_read_twin_is_read_once() {
        let (one, two) = (bar(10.0, 6.0, 3, 0), bar(200.0, 7.0, 9, 2));
        // every bar read; then one unread whose only likeness is a step off
        assert!(!passed(&[(4, &one, Some(read(&one)))]).again());
        assert!(!passed(&[(4, &one, Some(read(&one))), (12, &two, None)]).again());
        // and a twin that was not read is no reading
        let same = bar(200.0, 7.0, 9, 0);
        assert!(!passed(&[(4, &one, None), (12, &same, None)]).again());
    }

    #[test]
    fn a_reading_that_holds_another_staffs_note_is_no_reading_to_give() {
        let one = bar(10.0, 6.0, 3, 0);
        let mut vs = read(&one);
        // (a note that is not the bar's own in its lower voice)
        vs[1][1] = note(16.0, 20, false, None);
        vs[1][1].dur = Q::int(2);
        assert!(reading_of(&snap_of(&one), &vs).is_none());
        // (a voice that does not fill the bar)
        let mut short = read(&one);
        short[1].remove(0);
        assert!(reading_of(&snap_of(&one), &short).is_none());
        assert!(reading_of(&snap_of(&one), &read(&one)).is_some());
    }
}