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
//! A voice of a bar as `.fmn` tokens (docs/transcribing.md).

use std::collections::{BTreeMap, BTreeSet};

use crate::frac::Q;
use crate::smufl::STEPS;
use crate::staff::{Ev, Res, Rest, Untaken};

/// A length as the format writes it: 1 2 4 8 16 32 64 128 256, `0` a double whole note and
/// `00` a long, and its dots after, as many as printed (four at most).
pub fn dur_token(d: Q) -> Res<String> {
    let longer = [(16, "00"), (8, "0"), (4, "1"), (2, "2"), (1, "4")].map(|(n, t)| (Q::int(n), t));
    let shorter = [
        (2, "8"),
        (4, "16"),
        (8, "32"),
        (16, "64"),
        (32, "128"),
        (64, "256"),
    ]
    .map(|(d, t)| (Q::new(1, d), t));
    for (base, name) in longer.into_iter().chain(shorter) {
        let (mut v, mut step) = (base, base / Q::int(2));
        for dots in 0..5 {
            if v == d {
                return Ok(format!("{name}{}", ".".repeat(dots)));
            }
            v += step;
            step = step / Q::int(2);
        }
    }
    Err(Untaken::new("a length the format has no single note for"))
}

/// A length as written lengths, longest first (blank time may need more than one).
pub fn plain_lengths(mut d: Q) -> Res<Vec<Q>> {
    let mut out = Vec::new();
    for base in [
        (4, 1),
        (3, 1),
        (2, 1),
        (3, 2),
        (1, 1),
        (3, 4),
        (1, 2),
        (3, 8),
        (1, 4),
        (1, 8),
        (1, 16),
    ] {
        let b = Q::new(base.0, base.1);
        while d >= b {
            out.push(b);
            d -= b;
        }
    }
    if !d.is_zero() {
        return Err(Untaken::new("a length the format has no single note for"));
    }
    Ok(out)
}

pub fn pitch_name(place: i32, alt: i32) -> String {
    let acc = match alt {
        -2 => "ff",
        -1 => "f",
        1 => "s",
        2 => "ss",
        _ => "",
    };
    format!(
        "{}{acc}{}",
        STEPS[place.rem_euclid(7) as usize],
        place.div_euclid(7)
    )
}

/// What the key signature does to a staff place.
pub fn key_alter(fifths: i32, place: i32) -> i32 {
    let letter = STEPS[place.rem_euclid(7) as usize];
    if fifths > 0 && "fcgdaeb".chars().take(fifths as usize).any(|c| c == letter) {
        return 1;
    }
    if fifths < 0
        && "beadgcf"
            .chars()
            .take((-fifths) as usize)
            .any(|c| c == letter)
    {
        return -1;
    }
    0
}

/// `[` and `]` for the printed beam groups, where they differ from the beat's (the compiler's own
/// grouping): else nothing.
pub fn beam_marks(events: &[Ev], beat: Q) -> Vec<String> {
    let mut printed: Vec<Vec<usize>> = Vec::new();
    let mut cur: Vec<usize> = Vec::new();
    for (i, e) in events.iter().enumerate() {
        let joins = e.is_note()
            && !e.beam_polys.is_empty()
            && cur
                .last()
                .is_some_and(|&k| !events[k].beam_polys.is_disjoint(&e.beam_polys));
        if joins {
            cur.push(i);
        } else {
            if cur.len() > 1 {
                printed.push(std::mem::take(&mut cur));
            }
            cur = if e.is_note() && !e.beam_polys.is_empty() {
                vec![i]
            } else {
                Vec::new()
            };
        }
    }
    if cur.len() > 1 {
        printed.push(cur);
    }
    let mut default: Vec<Vec<usize>> = Vec::new();
    let mut cur: Vec<(usize, i64)> = Vec::new();
    let mut onset = Q::ZERO;
    let eps = Q::new(1, 1000);
    for (i, e) in events.iter().enumerate() {
        let beamable = e.is_note() && e.dur < Q::ONE;
        let unit = onset.floor_div(beat);
        let fits = (onset + e.dur - eps).floor_div(beat) == unit;
        if beamable && fits && cur.last().is_some_and(|&(_, u)| u == unit) {
            cur.push((i, unit));
        } else {
            if cur.len() > 1 {
                default.push(cur.iter().map(|&(k, _)| k).collect());
            }
            cur = if beamable && fits {
                vec![(i, unit)]
            } else {
                Vec::new()
            };
        }
        onset += e.dur;
    }
    if cur.len() > 1 {
        default.push(cur.iter().map(|&(k, _)| k).collect());
    }
    let mut marks = vec![String::new(); events.len()];
    if printed != default {
        for g in &printed {
            marks[g[0]].push('[');
            marks[*g.last().unwrap()].push(']');
        }
    }
    marks
}

/// One voice of one staff in one bar as tokens. `ties_in`: {place: alteration} of the notes tied
/// over from before (into the bar's first notes); `printed`: the accidentals printed on the staff in the bar, in any of its
/// voices, as (onset, place, alteration): one holds from its note on, whichever voice's note
/// comes after it. Returns the tokens and the {place: alteration} tied on.
// (a voice with no note drawn on another staff; the reader writes with `write_voice_across`)
#[allow(dead_code)]
pub fn write_voice(
    events: &[Ev],
    fifths: i32,
    printed: &[(Q, i32, i32)],
    ties_in: &BTreeMap<i32, i32>,
    beat: Q,
) -> Res<(String, BTreeMap<i32, i32>)> {
    write_voice_across(
        events,
        fifths,
        printed,
        &BTreeMap::new(),
        ties_in,
        beat,
        None,
    )
}

/// A key signature inside a bar, on a staff: when it holds from (in quarters from the bar's
/// start), its key, and whether this voice's line is the one that says it (`\key:N`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KeyChange {
    pub at: Q,
    pub fifths: i32,
    pub say: bool,
}

/// Where a key signature that stands at `x` inside a staff's bar holds from: the start of the
/// first note or rest of the staff's voices that stands after it (the bar's end if none does),
/// and the voice whose line says it: the first with a note or rest starting there.
pub fn key_change_at(voices: &[Vec<Ev>], x: f64) -> (Q, usize) {
    let mut starts: Vec<(Q, usize)> = Vec::new();
    let mut end = Q::ZERO;
    for (vi, v) in voices.iter().enumerate() {
        let mut t = Q::ZERO;
        for e in v {
            if e.grace.is_none() && e.rest != Rest::Blank && e.x > x {
                starts.push((t, vi));
            }
            t += e.takes();
        }
        end = end.max(t);
    }
    starts.into_iter().min().unwrap_or((end, 0))
}

/// [`write_voice`], with a key signature inside the bar (`change`): from where it holds the
/// notes go by its key, and what the bar had altered before it is forgotten.
#[cfg(test)]
pub fn write_voice_in(
    events: &[Ev],
    fifths: i32,
    printed: &[(Q, i32, i32)],
    ties_in: &BTreeMap<i32, i32>,
    beat: Q,
    change: Option<KeyChange>,
) -> Res<(String, BTreeMap<i32, i32>)> {
    write_voice_across(
        events,
        fifths,
        printed,
        &BTreeMap::new(),
        ties_in,
        beat,
        change,
    )
}

/// [`write_voice`] for a voice some of whose notes are drawn on the part's other staves
/// (`Ev::on_staff`): an accidental holds on the staff it is printed on, so such a note goes by
/// the accidentals printed on its own staff, `printed_on` by staff number. And with a key
/// signature inside the bar (`change`, as [`write_voice_in`]).
pub fn write_voice_across(
    events: &[Ev],
    fifths: i32,
    printed: &[(Q, i32, i32)],
    printed_on: &BTreeMap<u8, Vec<(Q, i32, i32)>>,
    ties_in: &BTreeMap<i32, i32>,
    beat: Q,
    change: Option<KeyChange>,
) -> Res<(String, BTreeMap<i32, i32>)> {
    let none = BTreeMap::new();
    let (line, ties, _) = write_voice_held(
        events, fifths, printed, printed_on, ties_in, &none, beat, change,
    )?;
    Ok((line, ties))
}

/// The pitches ties carry on, as {place: alteration}.
pub type Carried = BTreeMap<i32, i32>;

/// [`write_voice_across`], with the ties held over the notes that follow them (`~~`, `Ev::held`):
/// `held_in` is the pitch each carries from the bar before, by place, for the note it lands on
/// (`Ev::held_in`); the third thing given back is what this voice's carry on.
#[allow(clippy::too_many_arguments)]
pub fn write_voice_held(
    events: &[Ev],
    fifths: i32,
    printed: &[(Q, i32, i32)],
    printed_on: &BTreeMap<u8, Vec<(Q, i32, i32)>>,
    ties_in: &BTreeMap<i32, i32>,
    held_in: &BTreeMap<i32, i32>,
    beat: Q,
    change: Option<KeyChange>,
) -> Res<(String, Carried, Carried)> {
    let mut said = change.is_none_or(|c| !c.say);
    let mut toks: Vec<String> = Vec::new();
    let mut out_ties = BTreeMap::new();
    let mut held_out = BTreeMap::new();
    // the beams by the notes that take time; a grace note's are its own
    let timed: Vec<usize> = (0..events.len())
        .filter(|&i| events[i].grace.is_none())
        .collect();
    let timed_evs: Vec<Ev> = timed.iter().map(|&i| events[i].clone()).collect();
    let mut marks = vec![String::new(); events.len()];
    for (k, m) in timed.iter().zip(beam_marks(&timed_evs, beat)) {
        marks[*k] = m;
    }
    let mut open: Vec<usize> = Vec::new(); // the tuplet groups open, outermost first
    let mut next_onset = Q::ZERO;
    for (e, bm) in events.iter().zip(marks) {
        let now = next_onset;
        next_onset += e.takes();
        // a tie from the bar before lands on the bar's first note: a later note at its place
        // goes by the key and the bar's accidentals again
        let takes_ties = now.is_zero() && e.grace.is_none();
        // tuplets: close the groups this note is not in, open the ones it starts
        let ids: Vec<usize> = e.tuplets.iter().map(|t| t.2).collect();
        let keep = open.iter().zip(&ids).take_while(|(a, b)| a == b).count();
        for _ in keep..open.len() {
            toks.push("}".into());
        }
        open.truncate(keep);
        for &(a, n, id) in &e.tuplets[keep..] {
            toks.push(format!("{a}:{n}{{"));
            open.push(id);
        }
        let changed = change.filter(|c| now >= c.at);
        if let Some(c) = changed.filter(|_| !said) {
            toks.push(format!("\\key:{}", c.fifths));
            said = true;
        }
        toks.extend(e.before.iter().cloned());
        let mut t = e
            .dynamic
            .as_ref()
            .map(|d| format!("\\{d} "))
            .unwrap_or_default();
        match (e.grace, e.grace_after) {
            (Some(true), false) => t.push_str("gs:"),
            (Some(false), false) => t.push_str("g:"),
            (Some(true), true) => t.push_str("gsa:"),
            (Some(false), true) => t.push_str("ga:"),
            (None, _) => {}
        }
        match &e.rest {
            Rest::Bar => t.push('R'),
            Rest::Blank => {
                // (blank time in a tuplet is written as the tuplet's notes are: `3:2{ s/8 g8 a8 }`)
                let parts: Res<Vec<String>> = plain_lengths(e.written())?
                    .into_iter()
                    .map(|d| dur_token(d).map(|s| format!("s/{s}")))
                    .collect();
                t.push_str(&parts?.join(" "));
            }
            Rest::Printed(_) => t.push_str(&format!("r/{}", dur_token(e.written())?)),
            Rest::None => {
                // the bar's accidental on a place so far: the last printed before this note on the
                // staff, in any voice (this voice's own included), else the key's
                // `with`: a head both voices share at this onset takes the other's accidental
                let printed = e
                    .on_staff
                    .and_then(|n| printed_on.get(&n))
                    .map_or(printed, |v| &v[..]);
                let so_far = |place: i32, with: bool| -> i32 {
                    printed
                        .iter()
                        .rfind(|&&(o, p, _)| {
                            p == place
                                && (o < now || (with && o == now))
                                && changed.is_none_or(|c| o >= c.at)
                        })
                        .map_or_else(
                            || key_alter(changed.map_or(fifths, |c| c.fifths), place),
                            |t| t.2,
                        )
                };
                let mut names = Vec::new();
                let mut alts = BTreeMap::new();
                let places: BTreeSet<i32> = e.places.iter().copied().collect();
                for &place in &e.places {
                    let (alt, mark) = if let Some(&(alt, cautious)) = e.accs.get(&place) {
                        let redundant = so_far(place, false) == alt;
                        (
                            alt,
                            if cautious {
                                "?"
                            } else if redundant {
                                "!"
                            } else {
                                ""
                            },
                        )
                    } else if let Some(&alt) = ties_in.get(&place).filter(|_| takes_ties) {
                        (alt, "")
                    } else if let Some(&alt) = out_ties.get(&place) {
                        // tied from the voice's note before: its pitch
                        (alt, "")
                    } else if let Some(&alt) =
                        held_in.get(&place).filter(|_| e.held_in.contains(&place))
                    {
                        // a tie held over from the bar before lands here: its pitch
                        (alt, "")
                    } else {
                        (so_far(place, true), "")
                    };
                    alts.insert(place, alt);
                    let mut nm = pitch_name(place, alt) + mark;
                    // (a chord's ties a pitch at a time where they are not all alike)
                    if e.places.len() > 1 && e.tied.contains(&place) && !tied_alike(e) {
                        nm.push_str(if e.held.contains(&place) { "~~" } else { "~" });
                    }
                    names.push(nm);
                }
                if names.len() == 1 {
                    t.push_str(&names[0]);
                } else {
                    t.push_str(&format!("<{}>", names.join(" ")));
                }
                t.push('/');
                t.push_str(&dur_token(e.written())?);
                if !e.tied.is_empty() && e.tied.is_superset(&places) && tied_alike(e) {
                    t.push_str(if e.held.is_empty() { "~" } else { "~~" });
                }
                if let Some(st) = e.on_staff {
                    t.push_str(&format!("@{st}"));
                }
                // fingering: every note of the chord's, or the one note's
                let fs: Vec<u8> = e
                    .places
                    .iter()
                    .filter_map(|p| e.fingers.get(p).copied())
                    .collect();
                if !fs.is_empty() && fs.len() == e.places.len() {
                    t.push_str("-f");
                    for f in fs {
                        t.push(char::from(b'0' + f));
                    }
                }
                if e.gliss {
                    t.push_str("-gliss");
                }
                match e.tremolo {
                    Some(crate::staff::Trem::Single(k)) => t.push_str(&format!("-trem{k}")),
                    Some(crate::staff::Trem::Start(k)) => t.push_str(&format!("-trem{k}=")),
                    _ => {}
                }
                // a small note read as taking its time (a second verse's other rhythm)
                if e.sung_small {
                    t.push_str("-cue");
                }
                // a shape every head of it has (x heads)
                let shape = e
                    .heads
                    .first()
                    .and_then(|h| crate::smufl::head_shape(h.code));
                if let Some(sh) = shape {
                    if e.heads
                        .iter()
                        .all(|h| crate::smufl::head_shape(h.code) == shape)
                    {
                        t.push_str(&format!("-head:{sh}"));
                    }
                }
                // (a tie held over what follows is not the next note's: `held_out`)
                let plain = e.tied.iter().filter(|p| !e.held.contains(p));
                out_ties = plain.map(|p| (*p, alts[p])).collect();
                held_out.extend(e.held.iter().map(|p| (*p, alts[p])));
            }
        }
        for m in &e.marks {
            t.push_str(m);
        }
        t.push_str(&")".repeat(e.slur_close as usize));
        t.push_str(&"(".repeat(e.slur_open as usize));
        t.push_str(&bm);
        toks.push(t);
        toks.extend(e.after.iter().cloned());
    }
    for _ in 0..open.len() {
        toks.push("}".into());
    }
    if let Some(c) = change.filter(|_| !said) {
        toks.push(format!("\\key:{}", c.fifths));
    }
    Ok((toks.join(" "), out_ties, held_out))
}

/// Whether a note's ties are written once after its length: every place of it tied, and all of
/// them plain (`~`) or all held over what follows (`~~`).
fn tied_alike(e: &Ev) -> bool {
    let all = |s: &BTreeSet<i32>| e.places.iter().all(|p| s.contains(p));
    all(&e.tied) && (all(&e.held) || !e.places.iter().any(|p| e.held.contains(p)))
}

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

    #[test]
    fn a_key_signature_inside_the_bar_holds_from_its_note_on() {
        // in two flats: b4 (flat by the key), then one sharp from the second note on: b4 is
        // natural and f5 sharp; a flat printed on the first note is forgotten after it
        let note = |x: f64, place: i32| {
            let mut e = Ev::new(Vec::new(), None, Some(true));
            e.x = x;
            e.dur = Q::ONE;
            e.places = vec![place];
            e.place_of = vec![place];
            e
        };
        let mut first = note(0.0, 34);
        first.accs.insert(34, (-1, false));
        let voice = vec![first, note(10.0, 34), note(20.0, 38)];
        let printed = [(Q::ZERO, 34, -1)];
        let (at, voice_no) = key_change_at(std::slice::from_ref(&voice), 5.0);
        assert_eq!((at, voice_no), (Q::ONE, 0));
        let change = KeyChange {
            at,
            fifths: 1,
            say: true,
        };
        let none = BTreeMap::new();
        let (line, _) = write_voice_in(&voice, -2, &printed, &none, Q::ONE, Some(change)).unwrap();
        assert_eq!(line, "bf4!/4 \\key:1 b4/4 fs5/4");
        // the staff's other voice goes by it too, and does not say it again
        let other = vec![note(0.0, 31), note(10.0, 31), note(20.0, 31)];
        let quiet = KeyChange {
            say: false,
            ..change
        };
        let (line, _) = write_voice_in(&other, -2, &printed, &none, Q::ONE, Some(quiet)).unwrap();
        assert_eq!(line, "f4/4 fs4/4 fs4/4");
    }

    #[test]
    fn lengths_and_names() {
        assert_eq!(dur_token(Q::new(3, 2)).unwrap(), "4.");
        assert_eq!(dur_token(Q::new(1, 4)).unwrap(), "16");
        assert_eq!(dur_token(Q::new(7, 2)).unwrap(), "2..");
        // a double whole note, a long, a note of three dots, a 128th
        assert_eq!(dur_token(Q::int(8)).unwrap(), "0");
        assert_eq!(dur_token(Q::int(12)).unwrap(), "0.");
        assert_eq!(dur_token(Q::int(16)).unwrap(), "00");
        assert_eq!(dur_token(Q::new(15, 8)).unwrap(), "4...");
        assert_eq!(dur_token(Q::new(1, 32)).unwrap(), "128");
        let text = "part V \"V\" voice\ntime 4/2\nbar 1\nV: c5/0\nbar 2\nV: c5/4... d5/32 e5/1.\n";
        fm_transcribe::compile(text).unwrap();
        assert!(dur_token(Q::new(5, 4)).is_err());
        assert_eq!(
            plain_lengths(Q::new(5, 4)).unwrap(),
            vec![Q::ONE, Q::new(1, 4)]
        );
        assert_eq!(pitch_name(4 * 7 + 6, -1), "bf4");
        assert_eq!(pitch_name(4 * 7, 1), "cs4");
        assert_eq!(key_alter(-2, 4 * 7 + 6), -1);
        assert_eq!(key_alter(-2, 4 * 7 + 5), 0);
        assert_eq!(key_alter(3, 4 * 7 + 4), 1);
    }

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

    #[test]
    fn a_voice_with_its_marks_as_tokens() {
        let c4 = 4 * 7;
        let third = Q::new(1, 3);
        let mut grace = ev(c4 + 1, Q::new(1, 2));
        grace.grace = Some(true);
        let mut t: Vec<Ev> = (0..3)
            .map(|k| {
                let mut e = ev(c4 + k, third);
                e.tuplets = vec![(3, 2, 7)];
                e
            })
            .collect();
        t[0].fingers.insert(c4, 1);
        t[0].before.push(r"\clef:bass".into());
        let mut low = ev(c4 - 7, Q::ONE);
        low.on_staff = Some(2);
        low.gliss = true;
        low.after.push(r"\!".into());
        let mut events = vec![grace];
        events.extend(t);
        events.push(low);
        let (line, _) = write_voice(&events, 0, &[], &BTreeMap::new(), Q::ONE).unwrap();
        assert!(
            line.starts_with(r"gs:d4/8 3:2{ \clef:bass c4/8-f1"),
            "{line}"
        );
        assert!(line.contains("e4/8"), "{line}");
        assert!(line.contains(r"} c3/4@2-gliss \!"), "{line}");
    }

    #[test]
    fn an_accidental_holds_across_the_staff_s_voices_from_its_note_on() {
        let a4 = 4 * 7 + 5;
        // voice 2: a, then a sharp at beat 2; voice 1: a at beats 1 and 3
        let printed = vec![(Q::ONE, a4, 1)];
        let v1: Vec<Ev> = (0..4).map(|_| ev(a4, Q::ONE)).collect();
        let (line, _) = write_voice(&v1, 1, &printed, &BTreeMap::new(), Q::ONE).unwrap();
        // before the sharp: natural; at its onset (a head both voices share) and after: sharp
        assert_eq!(line, "a4/4 as4/4 as4/4 as4/4", "{line}");
        // a voice's own accidental the other voice printed already is shown, marked
        let mut own = ev(a4, Q::ONE);
        own.accs.insert(a4, (1, false));
        let v2 = vec![ev(a4, Q::ONE), ev(a4, Q::ONE), own];
        let printed = vec![(Q::ONE, a4, 1), (Q::int(2), a4, 1)];
        let (line, _) = write_voice(&v2, 1, &printed, &BTreeMap::new(), Q::ONE).unwrap();
        assert_eq!(line, "a4/4 as4/4 as4!/4", "{line}");
    }

    #[test]
    fn a_tie_from_the_bar_before_lands_on_the_first_note_only() {
        let c5 = 5 * 7;
        // c sharp tied in; the bar's c, c, c: the first is the tied one, the others the key's
        let ties_in: BTreeMap<i32, i32> = [(c5, 1)].into_iter().collect();
        let v: Vec<Ev> = (0..3).map(|_| ev(c5, Q::ONE)).collect();
        let (line, _) = write_voice(&v, 0, &[], &ties_in, Q::ONE).unwrap();
        assert_eq!(line, "cs5/4 c5/4 c5/4", "{line}");
        // tied on within the bar, the pitch goes with the tie; the tie out says what it carries
        let mut v = v;
        v[0].tied.insert(c5);
        v[1].tied.insert(c5);
        let (line, out) = write_voice(&v[..2], 0, &[], &ties_in, Q::ONE).unwrap();
        assert_eq!(line, "cs5/4~ cs5/4~", "{line}");
        assert_eq!(out.get(&c5), Some(&1));
        // a voice that starts later takes no tie
        let mut rest = ev(c5, Q::ONE);
        rest.rest = Rest::Blank;
        let late = vec![rest, ev(c5, Q::ONE)];
        let (line, _) = write_voice(&late, 0, &[], &ties_in, Q::ONE).unwrap();
        assert_eq!(line, "s/4 c5/4", "{line}");
    }

    #[test]
    fn blank_time_in_a_tuplet_is_written_in_it() {
        // a triplet whose first eighth is on the part's other staff: blank here, then two notes
        let c5 = 5 * 7;
        let third = Q::new(1, 3);
        let mut v = vec![Ev::spacer(third, 0.0), ev(c5, third), ev(c5, third)];
        for e in v.iter_mut() {
            e.tuplets = vec![(3, 2, 7)];
        }
        v.push(ev(c5, Q::ONE));
        let (line, _) = write_voice(&v, 0, &[], &BTreeMap::new(), Q::ONE).unwrap();
        assert_eq!(line, "3:2{ s/8 c5/8 c5/8 } c5/4", "{line}");
        // two thirds of it blank: a quarter's blank in the tuplet
        v[1] = Ev::spacer(third * Q::int(2), 0.0);
        v[1].tuplets = vec![(3, 2, 7)];
        v[0] = ev(c5, third);
        v[0].tuplets = vec![(3, 2, 7)];
        v.remove(2);
        let (line, _) = write_voice(&v, 0, &[], &BTreeMap::new(), Q::ONE).unwrap();
        assert_eq!(line, "3:2{ c5/8 s/4 } c5/4", "{line}");
    }

    #[test]
    fn a_note_drawn_on_the_other_staff_goes_by_that_staff_s_accidentals() {
        let c4 = 4 * 7;
        let mut across = ev(c4, Q::ONE);
        across.on_staff = Some(2);
        let v = vec![across, ev(c4, Q::ONE)];
        // a sharp printed on the lower staff's c, a flat on this staff's
        let own = [(Q::ZERO, c4, -1)];
        let mut printed_on = BTreeMap::new();
        printed_on.insert(2u8, vec![(Q::ZERO, c4, 1)]);
        let (line, _) =
            write_voice_across(&v, 0, &own, &printed_on, &BTreeMap::new(), Q::ONE, None).unwrap();
        assert_eq!(line, "cs4/4@2 cf4/4", "{line}");
    }
}