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
//! Words that run on with a line of dashes (`cresc. - - -`): the line drawn from the words' end
//! to where it stops, over a system's end too. The words are written `_"cresc."--` and the line's
//! end `\--` (docs/transcribing.md).
//!
//! A line is the words' own where it starts at their end, at the height of their letters. It
//! runs on into the next system where it reaches this system's last barline and the next system
//! has a dashed line from its start by the same staff (with the words again in parentheses or
//! none); with no such line there it ended with the system.

use std::collections::BTreeSet;

use crate::marks::{Bars, Open, Sys};
use crate::page::Page;
use crate::staff::Rest;
use crate::words::Word;

/// A line of dashes: its ends and its height.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Dashed {
    pub x0: f64,
    pub x1: f64,
    pub y: f64,
}

/// The page's level lines of dashes: those stroked with a dash pattern, and runs of three or
/// more short pieces of one length set evenly at one height.
pub fn lines(pg: &Page, sp: f64) -> Vec<Dashed> {
    let mut out: Vec<Dashed> = pg
        .dashed
        .iter()
        .filter(|h| h.x1 - h.x0 > 1.5 * sp)
        .map(|h| Dashed {
            x0: h.x0,
            x1: h.x1,
            y: h.y,
        })
        .collect();
    // pieces: each under a space and a half long, the next of the same length within two
    // lengths of it
    let mut pieces: Vec<(f64, f64, f64)> = pg
        .hlines
        .iter()
        .filter(|h| h.x1 - h.x0 > 0.2 * sp && h.x1 - h.x0 < 1.5 * sp)
        .filter(|h| !pg.dashed.iter().any(|d| *d == **h))
        .map(|h| (h.y, h.x0, h.x1))
        .collect();
    pieces.sort_by(|a, b| {
        ((a.0 * 10.0).round())
            .total_cmp(&(b.0 * 10.0).round())
            .then(a.1.total_cmp(&b.1))
    });
    let mut run: Vec<(f64, f64, f64)> = Vec::new();
    let mut flush = |run: &mut Vec<(f64, f64, f64)>| {
        if run.len() >= 3 {
            out.push(Dashed {
                x0: run[0].1,
                x1: run.last().unwrap().2,
                y: run[0].0,
            });
        }
        run.clear();
    };
    for p in pieces {
        let follows = run.last().is_some_and(|l| {
            let len = l.2 - l.1;
            (p.0 - l.0).abs() < 0.15
                && ((p.2 - p.1) - len).abs() < 0.25 * len
                && p.1 > l.2 + 0.2 * len
                && p.1 < l.2 + 2.5 * len
        });
        if !follows {
            flush(&mut run);
        }
        run.push(p);
    }
    flush(&mut run);
    out
}

/// The line that runs on from a phrase: it starts at the phrase's end (within two spaces),
/// between the letters' baseline and their height.
fn after(lines: &[Dashed], w: &Word, sp: f64) -> Option<usize> {
    (0..lines.len())
        .filter(|&k| {
            let l = &lines[k];
            l.x0 > w.x1 - 0.5 * sp
                && l.x0 < w.x1 + 2.0 * sp
                && l.y < w.base + 0.1 * w.size
                && l.y > w.base - 0.75 * w.size
        })
        .min_by(|&a, &b| lines[a].x0.total_cmp(&lines[b].x0))
}

/// Per word: whether it is of a phrase that a line of dashes runs on from (such words under a
/// singer's staff are no words of the song).
pub fn phrases_with_dashes(pg: &Page, sp: f64, words: &[Word]) -> Vec<bool> {
    let lines = lines(pg, sp);
    if lines.is_empty() {
        return vec![false; words.len()];
    }
    let with: Vec<Word> = crate::jumps::phrases(words.to_vec())
        .into_iter()
        .filter(|p| after(&lines, p, sp).is_some())
        .collect();
    words
        .iter()
        .map(|w| {
            with.iter().any(|p| {
                (w.base - p.base).abs() < 0.2 * p.size && w.x0 > p.x0 - 0.01 && w.x1 < p.x1 + 0.01
            })
        })
        .collect()
}

/// What a phrase is to the system's lines of dashes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Role {
    /// No line runs on from it (or its staff has one open already): plain words.
    Plain,
    /// A line runs on from it: `--` after the words.
    Opens,
    /// The words again at a system's start, by a line that runs on from the system before: not
    /// written.
    Continues,
}

/// A system's lines of dashes, each with the staff it is of and the phrase it runs on from.
#[derive(Debug, Default)]
pub struct Plan {
    /// Per phrase: what it is.
    roles: Vec<Role>,
    /// The lines that are some staff's: (staff, start, end, the phrase that opens it).
    runs: Vec<(usize, f64, f64, Option<usize>)>,
    /// Phrases whose `--` was written.
    opened: BTreeSet<usize>,
    /// Staves whose line from the system before ends at this system's start.
    ended: Vec<usize>,
    /// Lines that began with words at the end of the system before, where no dash had room:
    /// the staff, and the words as they are said again here.
    late: Vec<(usize, String)>,
    /// The plain words written in the system's last bar: staff and text.
    at_end: Vec<(String, String)>,
    /// Each phrase's words, without parentheses.
    texts: Vec<String>,
}

/// A phrase in parentheses: the words of a line said again at a system's start.
fn in_parentheses(text: &str) -> bool {
    let t = text.trim();
    t.starts_with('(') && t.ends_with(')')
}

impl Plan {
    /// `staff_of` gives a phrase's staff where it is words of the kind a line may run on from.
    pub fn new(
        s: &Sys,
        phrases: &[Word],
        staff_of: impl Fn(&Word) -> Option<usize>,
        open: &Open,
    ) -> Plan {
        let (open, at_end, words_open) = (&open.dashes, &open.words_at_end, &open.dashes_words);
        let sp = s.sp;
        let mut plan = Plan {
            roles: vec![Role::Plain; phrases.len()],
            texts: phrases.iter().map(|p| unparenthesized(&p.text)).collect(),
            ..Plan::default()
        };
        let (lo, hi) = (s.top() - 8.0 * sp, s.bottom() + 6.0 * sp);
        let (left, right) = (s.bars[0].0 - 3.0 * sp, s.right + sp);
        let lines: Vec<Dashed> = lines(s.pg, sp)
            .into_iter()
            .filter(|l| lo < l.y && l.y < hi && left < l.x0 && l.x1 < right + sp)
            .collect();

        // a staff beside `i` with a line open, where `i` has none (words set under one staff
        // in one system and over the next staff in the next)
        let open_by = |i: usize| -> usize {
            let has = |j: usize| open.contains(&s.names[j]);
            match has(i) {
                true => i,
                false => (i.saturating_sub(1)..(i + 2).min(s.staves.len()))
                    .find(|&j| has(j))
                    .unwrap_or(i),
            }
        };
        // each line's phrase and staff
        let mut found: Vec<(usize, f64, f64, Option<usize>, bool)> = Vec::new();
        for (k, p) in phrases.iter().enumerate() {
            let (Some(i), Some(l)) = (staff_of(p), after(&lines, p, sp)) else {
                continue;
            };
            if (found.iter()).any(|f| {
                f.3.is_some_and(|q| after(&lines, &phrases[q], sp) == Some(l))
            }) {
                continue;
            }
            let l = &lines[l];
            // the words again before the system's first note or just after it: in parentheses,
            // or by a staff whose line is open, or as they stood at the end of the system
            // before (with no room for a dash there)
            let said = unparenthesized(&p.text).to_lowercase();
            let stood = at_end.iter().find(|(_, t)| {
                let t = t.to_lowercase();
                !t.is_empty() && said.starts_with(&t)
            });
            let by_open = open_by(i);
            // (by a staff whose line is open: the open line's own words, or part of them)
            let same = words_open.get(&s.names[by_open]).is_some_and(|t| {
                let t = t.to_lowercase();
                t.starts_with(&said) || said.starts_with(&t)
            });
            let again = p.x0 < s.first_event + 4.0 * sp
                && (in_parentheses(&p.text)
                    || (open.contains(&s.names[by_open]) && same)
                    || stood.is_some());
            let i = match (again, stood) {
                (true, _) if open.contains(&s.names[by_open]) => by_open,
                // (the staff the words were given to there)
                (true, Some((name, _))) => s.names.iter().position(|n| n == name).unwrap_or(i),
                _ => i,
            };
            found.push((i, l.x0, l.x1, Some(k), again));
        }
        // a line from the system's start with no words: the staff's whose line is open
        for l in &lines {
            let taken = found
                .iter()
                .any(|f| (f.1 - l.x0).abs() < 0.01 && f.2 == l.x1);
            if taken || l.x0 > s.first_event + 2.0 * sp {
                continue;
            }
            let i = open_by(nearest(s, l.y).0);
            if open.contains(&s.names[i]) {
                found.push((i, l.x0, l.x1, None, true));
            }
        }
        found.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
        // per staff, left to right: one line at a time
        for i in 0..s.staves.len() {
            let mut until: Option<f64> = open.contains(&s.names[i]).then_some(f64::MIN);
            let mut first = true;
            for &(_, x0, x1, k, again) in found.iter().filter(|f| f.0 == i) {
                let carried = first && until == Some(f64::MIN);
                let was_first = first;
                first = false;
                if again {
                    if carried {
                        // the line from the system before goes on
                        if let Some(k) = k {
                            plan.roles[k] = Role::Continues;
                        }
                        plan.runs.push((i, x0, x1, None));
                        until = Some(x1);
                    }
                    // the words again and their line at the system's start with nothing open:
                    // they stood at the end of the system before, with no room for a dash
                    if let (Some(k), true, None) = (k, was_first, until) {
                        plan.roles[k] = Role::Continues;
                        plan.runs.push((i, x0, x1, None));
                        plan.late.push((i, unparenthesized(&phrases[k].text)));
                        until = Some(x1);
                    }
                    continue;
                }
                if carried {
                    // the line from the system before ended with it
                    plan.ended.push(i);
                    until = None;
                }
                if until.is_some_and(|u| x0 < u - 0.5 * sp) {
                    continue; // one open on the staff: plain words
                }
                if let Some(k) = k {
                    plan.roles[k] = Role::Opens;
                    plan.runs.push((i, x0, x1, Some(k)));
                    until = Some(x1);
                }
            }
            if first && until == Some(f64::MIN) {
                plan.ended.push(i);
            }
        }
        plan
    }

    /// What phrase `k` is; one that opens a line is taken as written with its `--`.
    pub fn role(&mut self, k: usize) -> Role {
        let r = self.roles.get(k).copied().unwrap_or(Role::Plain);
        if r == Role::Opens {
            self.opened.insert(k);
        }
        r
    }

    /// Plain words written on staff `i` at x: kept where they stand in the system's last bar
    /// (the next system may show their line of dashes).
    pub fn wrote(&mut self, s: &Sys, i: usize, x: f64, text: &str) {
        if s.bars.last().is_some_and(|b| x > b.0) {
            self.at_end.push((s.names[i].clone(), text.to_string()));
        }
    }

    /// The lines' ends, each `\--` on the note the line stops before; a line that reaches the
    /// system's last barline is left open for the next system.
    pub fn close(&self, s: &Sys, bars: &mut Bars, open: &mut Open) {
        for (i, words) in &self.late {
            open.dashes.insert(s.names[*i].clone());
            open.dashes_late.push((s.names[*i].clone(), words.clone()));
            open.dashes_words.insert(s.names[*i].clone(), words.clone());
        }
        // the plain words of the system's last bar, for the next system's lines
        open.words_at_end = self.at_end.clone();
        let words = &mut open.dashes_words;
        let open = &mut open.dashes;
        for &i in &self.ended {
            if open.remove(&s.names[i]) {
                put_first(bars, i);
            }
        }
        for &(i, _, x1, k) in &self.runs {
            match k {
                Some(k) if !self.opened.contains(&k) => continue,
                None if !open.contains(&s.names[i]) => continue,
                _ => {}
            }
            if x1 > s.right - 2.5 * s.sp {
                open.insert(s.names[i].clone());
                if let Some(t) = k.and_then(|k| self.texts.get(k)) {
                    words.insert(s.names[i].clone(), t.clone());
                }
            } else {
                open.remove(&s.names[i]);
                put_end(bars, s, i, x1);
            }
        }
    }
}

fn unparenthesized(text: &str) -> String {
    let t = text.trim();
    t.trim_start_matches('(')
        .trim_end_matches(')')
        .trim()
        .to_string()
}

/// The words at the end of the text so far (its last two bars) that a line of dashes found in
/// the next system runs on from: `--` is written after them. The words are the last on the
/// staff's lines that begin as the words said again do (or that those begin with: words cut
/// short at the page's edge).
pub fn open_late(done: &mut String, late: &mut Vec<(String, String)>) {
    for (staff, words) in late.drain(..) {
        let words = words.to_lowercase();
        let from = done
            .rmatch_indices("\nbar ")
            .nth(1)
            .map_or(0, |(k, _)| k + 1);
        let mut at: Option<usize> = None;
        let mut pos = from;
        for line in done[from..].split_inclusive('\n') {
            let head = line.split(':').next().unwrap_or("");
            let base = head.split('/').next().unwrap_or(head);
            if base == staff && !head.contains(' ') {
                // the quoted words of the line: `^"..."` or `_"..."`, a token's start
                let mut k = 0;
                while let Some(q) = line[k..].find('"') {
                    let open = k + q;
                    let Some(len) = line[open + 1..].find('"') else {
                        break;
                    };
                    let close = open + 1 + len;
                    let inner = line[open + 1..close].to_lowercase();
                    let marks = line[..open].ends_with(" ^") || line[..open].ends_with(" _");
                    let plain = !line[close + 1..].starts_with("--");
                    if marks
                        && plain
                        && !inner.is_empty()
                        && (words.starts_with(&inner) || inner.starts_with(&words))
                    {
                        at = Some(pos + close + 1);
                    }
                    k = close + 1;
                }
            }
            pos += line.len();
        }
        if let Some(at) = at {
            done.insert_str(at, "--");
        }
    }
}

/// The staff a line at height y is nearest, as a phrase's is found.
fn nearest(s: &Sys, y: f64) -> (usize, f64) {
    let d = |j: usize| {
        let st = &s.staves[j];
        if y < st.top() {
            st.top() - y
        } else if y > st.bottom() {
            y - st.bottom()
        } else {
            0.0
        }
    };
    (0..s.staves.len())
        .map(|j| (j, d(j)))
        .min_by(|a, b| a.1.total_cmp(&b.1))
        .unwrap_or((0, 0.0))
}

const END: &str = "\\--";

/// `\--` before the staff's first note or rest of the system.
fn put_first(bars: &mut Bars, i: usize) {
    for bar in bars.iter_mut() {
        if let Some(e) = bar[i]
            .iter_mut()
            .find(|e| e.rest != Rest::Blank && e.grace.is_none())
        {
            e.before.insert(0, END.to_string());
            return;
        }
    }
}

/// `\--` where a line ends at x: before the first note or rest that stands at its end or past
/// it in that bar (the line stops short of the note it runs to), else after the bar's last.
fn put_end(bars: &mut Bars, s: &Sys, i: usize, x: f64) {
    let b = s
        .bars
        .iter()
        .position(|&(_, r)| x < r + 0.5 * s.sp)
        .unwrap_or(s.bars.len() - 1);
    let evs = &mut bars[b][i];
    if let Some(e) = evs
        .iter_mut()
        .filter(|e| e.rest != Rest::Blank && e.grace.is_none())
        .find(|e| e.x >= x - 1.0 * s.sp)
    {
        e.before.insert(0, END.to_string());
    } else if let Some(e) = evs.iter_mut().rev().find(|e| e.grace.is_none()) {
        e.after.push(END.to_string());
    }
}

/// A line of dashes the compiler will not have (one that opens in a voice with one open, an
/// end with no line, a line never closed: a bar left as a rest took its other end), taken out
/// of the text: the opener keeps its words. What was taken out, for the notice.
pub fn mend(done: &mut String, text: &mut String, msg: &str) -> Option<String> {
    let msg = msg.lines().last().unwrap_or("");
    let bar_of = |m: &str| -> Option<String> {
        let n: String = m
            .strip_prefix("bar ")?
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '-')
            .collect();
        (!n.is_empty()).then_some(n)
    };
    if let Some(k) = msg.find(": a line of dashes opens in ") {
        let who = msg[k + ": a line of dashes opens in ".len()..]
            .split(' ')
            .next()?;
        let bar = bar_of(msg)?;
        return strip(text, &bar, who, false)
            .then(|| format!("a line of dashes after words, one being open (bar {bar})"));
    }
    if let Some(k) = msg.find(" ends no line of dashes in ") {
        let who = msg[k + " ends no line of dashes in ".len()..].trim();
        let bar = bar_of(msg)?;
        return strip(text, &bar, who, true)
            .then(|| format!("a line of dashes' end with no start (bar {bar})"));
    }
    if let Some(rest) = msg.strip_prefix("a line of dashes in ") {
        let who = rest.split(' ').next()?;
        let bar = bar_of(rest.split(" from ").nth(1)?)?;
        return (strip(text, &bar, who, false) || strip(done, &bar, who, false))
            .then(|| format!("a line of dashes with no end (bar {bar})"));
    }
    None
}

/// Take a line of dashes' end (`\--`), or the `--` of words, out of bar `bar` on the lines of
/// the staff of `who` (`P.1/2`: part P, staff 1): the first end, or the last `--`.
fn strip(s: &mut String, bar: &str, who: &str, end: bool) -> bool {
    let staff = who.split('/').next().unwrap_or(who);
    let (part, n) = staff.rsplit_once('.').unwrap_or((staff, "1"));
    let mine = |head: &str| {
        let base = head.split('/').next().unwrap_or(head);
        base == staff || (n == "1" && base == part)
    };
    let mut out: Vec<String> = Vec::new();
    let mut on = false;
    let mut cut: Option<(usize, usize)> = None; // line, token
    for (li, line) in s.lines().enumerate() {
        if let Some(n) = line.strip_prefix("bar ") {
            on = n.split_whitespace().next() == Some(bar);
        }
        let head = line.split(':').next().unwrap_or("");
        if on && !head.contains(' ') && mine(head) && line.contains(':') {
            let mut quoted = false;
            for (ti, t) in line.split(' ').enumerate() {
                let was = quoted;
                if t.matches('"').count() % 2 == 1 {
                    quoted = !quoted;
                }
                if end && !was && t == END && cut.is_none() {
                    cut = Some((li, ti));
                }
                // (the words' last piece: `molto"--`)
                if !end && !quoted && t.ends_with("\"--") {
                    cut = Some((li, ti));
                }
            }
        }
        out.push(line.to_string());
    }
    let Some((li, ti)) = cut else { return false };
    let toks: Vec<&str> = out[li].split(' ').collect();
    let mut kept: Vec<String> = Vec::new();
    for (k, t) in toks.iter().enumerate() {
        if k != ti {
            kept.push(t.to_string());
        } else if !end {
            kept.push(t[..t.len() - 2].to_string());
        }
    }
    out[li] = kept.join(" ");
    let tail = if s.ends_with('\n') { "\n" } else { "" };
    *s = out.join("\n") + tail;
    true
}

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

    fn staves() -> [Staff; 2] {
        let staff = |top: f64| Staff {
            lines: [top, top + 1.0, top + 2.0, top + 3.0, top + 4.0],
            left: 0.0,
            right: 60.0,
            breaks: Vec::new(),
        };
        [staff(100.0), staff(112.0)]
    }

    fn notes_at(xs: &[f64], y: f64) -> Vec<Ev> {
        xs.iter()
            .map(|&x| {
                let head = Glyph {
                    code: 0xE0A4,
                    x0: x,
                    x1: x + 1.2,
                    y,
                    size: 4.0,
                };
                Ev::new(vec![head], None, None)
            })
            .collect()
    }

    fn word(text: &str, x0: f64, x1: f64, base: f64) -> Word {
        Word {
            text: text.into(),
            x0,
            x1,
            base,
            size: 2.0,
        }
    }

    fn marks_of(evs: &[Ev]) -> String {
        evs.iter()
            .map(|e| format!("{}|{}", e.before.join(" "), e.after.join(" ")))
            .collect::<Vec<_>>()
            .join(" , ")
    }

    #[test]
    fn dashes_are_a_dashed_stroke_or_even_short_pieces() {
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let pg = Page {
            dashed: vec![h(10.0, 30.0, 50.0)],
            hlines: vec![
                h(10.0, 30.0, 50.0),
                // five even pieces, then a longer line, and two ledger lines one over the other
                h(40.0, 40.5, 60.0),
                h(41.0, 41.5, 60.0),
                h(42.0, 42.5, 60.0),
                h(43.0, 43.5, 60.0),
                h(44.0, 44.5, 60.0),
                h(50.0, 58.0, 60.0),
                h(70.0, 71.0, 61.0),
                h(70.0, 71.0, 62.0),
            ],
            ..Page::default()
        };
        let found = lines(&pg, 1.0);
        assert_eq!(found.len(), 2);
        assert_eq!((found[0].x0, found[0].x1), (10.0, 30.0));
        assert_eq!((found[1].x0, found[1].x1), (40.0, 44.5));
    }

    #[test]
    fn words_with_a_line_of_dashes_open_it_and_the_line_s_end_closes_it() {
        // under the upper staff: "cresc." to x 8, its dashes from 8.5 to 22 (a note at 24),
        // "dim." with no line, and over the lower staff's end a line that reaches the last
        // barline at 60
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let st = staves();
        let pg = Page {
            dashed: vec![h(8.5, 22.0, 106.2), h(49.0, 59.0, 118.4)],
            ..Page::default()
        };
        let names = ["P.1".to_string(), "P.2".to_string()];
        let none = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &st,
            names: &names,
            bars: &[(0.0, 30.0), (30.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 4.0,
            ceiling: 0.0,
            floor: 0.0,
            sung: &none,
        };
        let phrases = [
            word("cresc.", 4.0, 8.0, 107.0),
            word("dim.", 34.0, 37.0, 107.0),
            word("rit.", 44.0, 48.0, 119.0),
        ];
        let staff_of = |w: &Word| Some(if w.base < 110.0 { 0 } else { 1 });
        let mut open = Open::default();
        let mut plan = Plan::new(&s, &phrases, staff_of, &open);
        assert_eq!(
            [plan.role(0), plan.role(1), plan.role(2)],
            [Role::Opens, Role::Plain, Role::Opens]
        );
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0, 14.0, 24.0], 102.0), notes_at(&[4.0], 114.0)],
            vec![
                notes_at(&[34.0, 44.0], 102.0),
                notes_at(&[34.0, 50.0], 114.0),
            ],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][0]), "| , | , \\--|");
        // the lower staff's line runs on over the system's end
        assert_eq!(marks_of(&bars[1][1]), "| , |");
        assert_eq!(open.dashes.iter().collect::<Vec<_>>(), ["P.2"]);

        // the next system: "(rit.)" and the line again by the lower staff to 20; the upper
        // staff's "(sempre)" with no line after it is plain words
        let pg = Page {
            dashed: vec![h(9.0, 20.0, 118.4)],
            ..Page::default()
        };
        let s = Sys { pg: &pg, ..s };
        assert_eq!(open.dashes_words["P.2"], "rit.");
        let phrases = [
            word("(rit.)", 4.0, 8.5, 119.0),
            word("(sempre)", 4.0, 8.5, 107.0),
        ];
        let mut plan = Plan::new(&s, &phrases, staff_of, &open);
        assert_eq!([plan.role(0), plan.role(1)], [Role::Continues, Role::Plain]);
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
            vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][1]), "| , \\--|");
        assert!(open.dashes.is_empty() && open.dashes_late.is_empty());

        // the same with no line open: the words stood at the end of the system before
        let mut plan = Plan::new(&s, &phrases, staff_of, &open);
        assert_eq!([plan.role(0), plan.role(1)], [Role::Continues, Role::Plain]);
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
            vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][1]), "| , \\--|");
        assert_eq!(open.dashes_late, [("P.2".to_string(), "rit.".to_string())]);
        let mut done = String::from(
            "bar 6\nP.2: _\"rit.\" c3/1\nbar 7\nP.1: ^\"rit.\" c5/1\nP.2: c3/2 _\"Rit.\" c3\nbar 8\nP.2/2: c3/2 ^\"dolce\" _\"rit.\"-- c3 \\--\n",
        );
        open_late(&mut done, &mut open.dashes_late);
        assert_eq!(
            done,
            "bar 6\nP.2: _\"rit.\" c3/1\nbar 7\nP.1: ^\"rit.\" c5/1\nP.2: c3/2 _\"Rit.\"-- c3\nbar 8\nP.2/2: c3/2 ^\"dolce\" _\"rit.\"-- c3 \\--\n"
        );
        assert!(open.dashes_late.is_empty());

        // a line open over a system's end, and other words with a line of their own at the
        // next system's start: the first ended with its system
        let mut open = Open {
            dashes: ["P.2".to_string()].into(),
            dashes_words: [("P.2".to_string(), "rit.".to_string())].into(),
            ..Open::default()
        };
        let phrases = [word("a tempo", 4.0, 8.5, 119.0)];
        let mut plan = Plan::new(&s, &phrases, staff_of, &open);
        assert_eq!(plan.role(0), Role::Opens);
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
            vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][1]), "\\--| , \\--|");

        // a line open over a system's end with none in the next system ended there
        let mut open = Open {
            dashes: ["P.1".to_string()].into(),
            ..Open::default()
        };
        let pg = Page::default();
        let s = Sys { pg: &pg, ..s };
        let plan = Plan::new(&s, &[], staff_of, &open);
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0], 102.0), notes_at(&[4.0], 114.0)],
            vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][0]), "\\--|");
        assert!(open.dashes.is_empty());

        // "dim. e rall." in a system's last bar with no room for a dash, said again whole
        // with its line at the next system's start (over the other staff there): one line,
        // the first words'
        let pg = Page {
            dashed: vec![h(12.0, 20.0, 110.4)],
            ..Page::default()
        };
        let s = Sys { pg: &pg, ..s };
        let mut plan = Plan::new(&s, &[], staff_of, &open);
        plan.wrote(&s, 0, 20.0, "cresc.");
        plan.wrote(&s, 0, 50.0, "dim. e");
        let mut bars: Bars = vec![vec![notes_at(&[4.0], 102.0), notes_at(&[4.0], 114.0)]; 2];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(
            open.words_at_end,
            [("P.1".to_string(), "dim. e".to_string())]
        );
        let phrases = [word("dim. e rall.", 4.0, 11.5, 111.0)];
        let mut plan = Plan::new(&s, &phrases, |_| Some(1), &open);
        assert_eq!(plan.role(0), Role::Continues);
        let mut bars: Bars = vec![
            vec![notes_at(&[4.0, 22.0], 102.0), notes_at(&[4.0, 22.0], 114.0)],
            vec![notes_at(&[34.0], 102.0), notes_at(&[34.0], 114.0)],
        ];
        plan.close(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][0]), "| , \\--|");
        assert_eq!(
            open.dashes_late,
            [("P.1".to_string(), "dim. e rall.".to_string())]
        );
        assert!(open.words_at_end.is_empty());
    }

    #[test]
    fn a_line_of_dashes_the_compiler_will_not_have_is_taken_out() {
        // an end whose start went with a bar left as a rest
        let mut done = String::from("bar 1\nP.1: R\n");
        let mut text = String::from("bar 2\nP.1: c5/2 \\-- c5\nP.2: \\-- c3/1\n");
        let what = mend(
            &mut done,
            &mut text,
            "bar 2: \\-- ends no line of dashes in P.1/1",
        );
        assert_eq!(
            what.as_deref(),
            Some("a line of dashes' end with no start (bar 2)")
        );
        assert_eq!(text, "bar 2\nP.1: c5/2 c5\nP.2: \\-- c3/1\n");
        // a line never closed: its words stay, in the text before too
        let mut done = String::from("bar 1\nV: _\"poco a poco cresc.\"-- c5/1\n");
        let mut text = String::from("bar 2\nV: R\n");
        let msg = "a line of dashes in V.1/1 from bar 1 is never closed (\\--)";
        assert!(mend(&mut done, &mut text, msg).is_some());
        assert_eq!(done, "bar 1\nV: _\"poco a poco cresc.\" c5/1\n");
        // one opened over another in its voice
        let mut text = String::from("bar 3\nP.2/2: _\"a\"-- c3/2 _\"b\"-- c3\n");
        let msg = "bar 3: a line of dashes opens in P.2/2 while the one from bar 3 is open (close it with \\--)";
        assert!(mend(&mut done, &mut text, msg).is_some());
        assert_eq!(text, "bar 3\nP.2/2: _\"a\"-- c3/2 _\"b\" c3\n");
        assert!(mend(&mut done, &mut text, "bar 3: a tie never lands").is_none());
    }
}