fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
//! A system's marks that are not notes, each put on the note it stands at as the format writes
//! it: hairpins, words over and under the staves (tempo, expression), chord symbols, rehearsal
//! marks, the pedal, ottava lines, glissandos and fingering. Hairpins, the pedal and ottava lines
//! run on from one system into the next.

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

use crate::frac::Q;
use crate::jumps::{ending_numbers, jump_named, phrases};
use crate::page::{Glyph, HLine, Page, Staff};
use crate::smufl;
use crate::staff::{Ev, Rest};
use crate::words::{words_of, Word};

/// What runs on over a system's end.
#[derive(Clone, Debug, Default)]
pub struct Open {
    /// Staves with a hairpin open, each with its number (1; 2 for a second at once on its staff).
    pub hairpins: BTreeSet<(String, u8)>,
    /// Staves whose pedal is down.
    pub pedal: BTreeSet<String>,
    /// Staves under an ottava line.
    pub ottava: BTreeSet<String>,
    /// Staves with a line of dashes (`cresc. - - -`) open.
    pub dashes: BTreeSet<String>,
    /// The words each staff's open line of dashes runs on from.
    pub dashes_words: BTreeMap<String, String>,
    /// Lines of dashes found to have begun at the end of the system before, whose words had no
    /// room for a dash there: the staff and the words (`dashes::open_late`).
    pub dashes_late: Vec<(String, String)>,
    /// The plain words of the system's last bar (staff, text): the next system may show the
    /// line of dashes they had no room for.
    pub words_at_end: Vec<(String, String)>,
}

/// A system as the marks need it.
pub struct Sys<'a> {
    pub pg: &'a Page,
    pub staves: &'a [Staff],
    pub names: &'a [String],
    /// Each bar's left and right edges.
    pub bars: &'a [(f64, f64)],
    pub sp: f64,
    pub right: f64,
    /// The first note or rest of the system (what stands left of it is the system's start).
    pub first_event: f64,
    /// Where the system's band begins above.
    pub ceiling: f64,
    /// The top of the system below on the page, or 0 when this is the page's last.
    pub floor: f64,
    /// Staves with words sung under them: no other words are read there.
    pub sung: &'a BTreeSet<usize>,
}

/// Per bar, per staff: its notes and rests.
pub type Bars = Vec<Vec<Vec<Ev>>>;

impl Sys<'_> {
    fn bar_at(&self, x: f64) -> usize {
        self.bars
            .iter()
            .position(|&(_, r)| x < r)
            .unwrap_or(self.bars.len() - 1)
    }

    /// The staff a mark at height y belongs to: the one over it, or the top one.
    /// The staff a mark between staves is of: the upper one (a piano's marks stand between its
    /// hands), unless the mark stands much nearer the lower one (a singer's stand over the staff).
    fn staff_over(&self, y: f64) -> usize {
        let above = (0..self.staves.len())
            .filter(|&j| self.staves[j].top() < y)
            .max()
            .unwrap_or(0);
        let below = above + 1;
        if below < self.staves.len() && y > self.staves[above].bottom() {
            let up = y - self.staves[above].bottom();
            let down = self.staves[below].top() - y;
            if down < 0.5 * up {
                return below;
            }
        }
        above
    }

    /// The staff a mark at height y is printed under (a pedal's is, however near the staff
    /// below it stands): the lowest staff that begins over it, or the top one.
    fn staff_under_which(&self, y: f64) -> usize {
        (0..self.staves.len())
            .filter(|&j| self.staves[j].top() < y)
            .max()
            .unwrap_or(0)
    }

    /// The staff a mark is nearest (above it or below it), and whether the mark is above it.
    fn nearest_staff(&self, y: f64) -> (usize, bool) {
        let d = |j: usize| {
            let s = &self.staves[j];
            if y < s.top() {
                s.top() - y
            } else if y > s.bottom() {
                y - s.bottom()
            } else {
                0.0
            }
        };
        let j = (0..self.staves.len())
            .min_by(|&a, &b| d(a).total_cmp(&d(b)))
            .unwrap_or(0);
        (j, y < self.staves[j].top() + 2.0 * self.sp)
    }

    pub(crate) fn top(&self) -> f64 {
        self.staves[0].top()
    }

    pub(crate) fn bottom(&self) -> f64 {
        self.staves.last().map_or(0.0, |s| s.bottom())
    }
}

/// Put `tok` on staff `i` at x: before the first note or rest at x or after it in x's bar, else
/// after the bar's last.
pub fn put(bars: &mut Bars, s: &Sys, i: usize, x: f64, tok: String) {
    let b = s.bar_at(x);
    let tol = 0.8 * s.sp;
    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 - tol)
    {
        e.before.push(tok);
    } else if let Some(e) = evs.iter_mut().rev().find(|e| e.grace.is_none()) {
        e.after.push(tok);
    }
}

/// Put `tok` before the first note or rest of staff `i` in the system.
fn put_first(bars: &mut Bars, i: usize, tok: String) {
    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.push(tok);
            return;
        }
    }
}

/// What the marks give besides the notes' own.
#[derive(Debug, Default)]
pub struct Placed {
    /// A bar's tempo (`"Moderately" 2=79`), by the bar's index in the system.
    pub tempos: Vec<(usize, String)>,
    /// The pedal's marks, left to right: written once the bars' voices are read
    /// ([`write_pedals`]).
    pub pedals: Vec<PedalMark>,
}

/// A pedal's mark: its bar in the system, its staff, where it stands, what it is (`\ped`,
/// `\ped^`, `\ped*`).
#[derive(Clone, Debug, PartialEq)]
pub struct PedalMark {
    pub bar: usize,
    pub staff: usize,
    pub x: f64,
    pub tok: &'static str,
}

/// A drawn line neither level nor upright: x0, y0, x1, y1, width.
type Diagonal = (f64, f64, f64, f64, f64);

/// A fingering digit by its note: its distance, the digit, the head it is of.
type Finger = (f64, u8, Option<usize>);

/// Everything, in order.
pub fn place(s: &Sys, bars: &mut Bars, open: &mut Open) -> Placed {
    let mut used: Vec<usize> = Vec::new(); // diagonals taken
    hairpins(s, bars, open, &mut used);
    ottavas(s, bars, open);
    let pedals = pedals(s, open);
    glissandos(s, bars, &used);
    let words = band_words(s);
    let mut taken = vec![false; words.len()];
    fingering(s, bars, &words, &mut taken);
    let mut placed = texts(s, bars, &words, &mut taken, open);
    placed.pedals = pedals;
    placed
}

/// The page's words in the system's band, not in a chord frame.
fn band_words(s: &Sys) -> Vec<Word> {
    let lo = s.top() - 10.0 * s.sp;
    let hi = s.bottom() + 6.0 * s.sp;
    let (l, r) = (s.bars[0].0 - 2.0 * s.sp, s.right + 2.0 * s.sp);
    words_of(s.pg)
        .into_iter()
        .filter(|w| {
            let cx = (w.x0 + w.x1) / 2.0;
            let cy = w.base - 0.35 * w.size;
            w.base > s.ceiling.max(lo)
                && w.base < hi
                && l < cx
                && cx < r
                && !s.pg.in_frame(cx, cy)
                && !s
                    .pg
                    .frames
                    .iter()
                    .any(|f| f.1 - 1.0 < cy && cy < f.3 && f.0 - 3.0 * s.sp < cx && cx < f.2)
        })
        .collect()
}

/// Hairpins: two straight lines from one point opening apart (a crescendo opens to the right).
fn hairpins(s: &Sys, bars: &mut Bars, open: &mut Open, used: &mut Vec<usize>) {
    let sp = s.sp;
    let ds: Vec<(usize, &Diagonal)> =
        s.pg.diagonals
            .iter()
            .enumerate()
            .filter(|(_, d)| {
                d.2 - d.0 > 1.5 * sp
                    && (d.3 - d.1).abs() < 0.35 * (d.2 - d.0)
                    && d.1 > s.top() - 8.0 * sp
                    && d.1 < s.bottom() + 8.0 * sp
                    && d.0 > s.bars[0].0 - 3.0 * sp
                    && d.2 < s.right + sp
            })
            .collect();
    // the pairs: (crescendo, staff, left, right)
    let mut pins: Vec<(bool, usize, f64, f64)> = Vec::new();
    let mut taken: BTreeSet<usize> = BTreeSet::new();
    for (a, &(ia, da)) in ds.iter().enumerate() {
        for &(ib, db) in &ds[a + 1..] {
            if taken.contains(&ia) || taken.contains(&ib) {
                continue;
            }
            if (da.0 - db.0).abs() > 0.5 * sp || (da.2 - db.2).abs() > 0.5 * sp {
                continue;
            }
            let gl = (da.1 - db.1).abs();
            let gr = (da.3 - db.3).abs();
            // one end closed (or nearly, where a hairpin runs on from the system before), the
            // other open
            if gl.max(gr) < 0.5 * sp || gl.max(gr) > 3.0 * sp || (gl - gr).abs() < 0.3 * sp {
                continue;
            }
            taken.insert(ia);
            taken.insert(ib);
            used.extend([ia, ib]);
            let y = (da.1 + da.3 + db.1 + db.3) / 4.0;
            pins.push((gl < gr, s.staff_over(y), da.0.min(db.0), da.2.max(db.2)));
        }
    }
    pins.sort_by(|a, b| a.2.total_cmp(&b.2));
    let pins: Vec<Pin> = pins
        .into_iter()
        .map(|(cresc, staff, x0, x1)| Pin {
            cresc,
            staff,
            x0,
            x1,
        })
        .collect();
    // a hairpin from the system before runs on in one at this one's start, or ended there
    let mut number: Vec<u8> = vec![0; pins.len()];
    for (name, n) in open.hairpins.clone() {
        let Some(i) = s.names.iter().position(|m| *m == name) else {
            continue;
        };
        let runs_on = (0..pins.len())
            .find(|&k| pins[k].staff == i && pins[k].x0 < s.first_event && number[k] == 0);
        match runs_on {
            Some(k) => number[k] = n,
            None => {
                put_first(bars, i, hairpin_token("\\!", n));
                open.hairpins.remove(&(name, n));
            }
        }
    }
    let continued: BTreeSet<usize> = (0..pins.len()).filter(|&k| number[k] != 0).collect();
    number_hairpins(&pins, &mut number, 0.8 * sp);
    for (k, p) in pins.iter().enumerate() {
        let (i, n) = (p.staff, number[k]);
        let name = &s.names[i];
        if !continued.contains(&k) {
            let tok = if p.cresc { "\\<" } else { "\\>" };
            put(bars, s, i, p.x0, hairpin_token(tok, n));
        }
        if p.x1 > s.right - 0.8 * sp {
            open.hairpins.insert((name.clone(), n));
        } else {
            put(bars, s, i, p.x1, hairpin_token("\\!", n));
            open.hairpins.remove(&(name.clone(), n));
        }
    }
}

/// A hairpin: whether it opens to the right (a crescendo), its staff, its left and right ends.
#[derive(Clone, Copy, Debug)]
struct Pin {
    cresc: bool,
    staff: usize,
    x0: f64,
    x1: f64,
}

/// A hairpin's token with its number: the first on a staff plain (`\<`), a second open at once
/// on the staff `\<2` (closed by `\!2`), and so on.
fn hairpin_token(tok: &str, n: u8) -> String {
    match n {
        0 | 1 => tok.to_string(),
        n => format!("{tok}{n}"),
    }
}

/// Each hairpin's number (those 0 in `number` are given one): the lowest that no hairpin on its
/// staff has that is open while it is. Two that only meet (one ends where the next begins,
/// within `near`) are not open at once.
fn number_hairpins(pins: &[Pin], number: &mut [u8], near: f64) {
    let at_once = |a: &Pin, b: &Pin| a.staff == b.staff && a.x0 < b.x1 - near && b.x0 < a.x1 - near;
    for k in 0..pins.len() {
        if number[k] != 0 {
            continue;
        }
        let busy: Vec<u8> = (0..pins.len())
            .filter(|&j| j != k && number[j] != 0 && at_once(&pins[j], &pins[k]))
            .map(|j| number[j])
            .collect();
        number[k] = (1..=9).find(|n| !busy.contains(n)).unwrap_or(1);
    }
}

/// Glyphs of the music font over the system, of the given codes.
fn glyphs_of<'a>(s: &'a Sys, codes: &'a [u32]) -> impl Iterator<Item = &'a Glyph> + 'a {
    let (lo, hi) = (
        (s.top() - 10.0 * s.sp).max(s.ceiling),
        s.bottom() + 8.0 * s.sp,
    );
    let (l, r) = (s.bars[0].0 - 3.0 * s.sp, s.right + s.sp);
    s.pg.glyphs
        .iter()
        .filter(move |g| codes.contains(&g.code) && lo < g.y && g.y < hi && l < g.x0 && g.x0 < r)
}

/// Where a line drawn in pieces from x (dashes, or a pedal's line broken by its changes) ends:
/// the level pieces at about height y, each starting within `gap` of the one before. Returns
/// the end and the gaps between pieces.
fn line_from(pg: &Page, x: f64, y: f64, tol: f64, gap: f64) -> Option<(f64, Vec<(f64, f64)>)> {
    let mut pieces: Vec<(f64, f64, f64)> = pg
        .hlines
        .iter()
        .filter(|h| (h.y - y).abs() < tol && h.x1 > x)
        .map(|h| (h.x0, h.x1, h.y))
        .collect();
    pieces.sort_by(|a, b| a.0.total_cmp(&b.0));
    let first = pieces.iter().position(|p| p.0 < x + gap)?;
    let line_y = pieces[first].2;
    let mut end = pieces[first].1;
    let mut gaps = Vec::new();
    for p in &pieces[first + 1..] {
        if (p.2 - line_y).abs() > 0.3 {
            continue;
        }
        if p.0 > end + gap {
            break;
        }
        if p.0 > end + 0.3 {
            gaps.push((end, p.0));
        }
        end = end.max(p.1);
    }
    Some((end, gaps))
}

/// Ottava lines: `8va` (or `8vb`, `15ma`, `15mb`) and a dashed line to the last note it covers.
/// The notes are read as printed; the compiler sounds them where the line says.
fn ottavas(s: &Sys, bars: &mut Bars, open: &mut Open) {
    let sp = s.sp;
    let codes = [
        0xE510, 0xE511, 0xE512, 0xE513, 0xE514, 0xE515, 0xE516, 0xE51C, 0xE51D,
    ];
    let mut here: BTreeSet<usize> = BTreeSet::new();
    // (a mark under the low notes of the last staff may stand far under it)
    let (lo, hi) = ((s.top() - 10.0 * sp).max(s.ceiling), s.bottom() + 12.0 * sp);
    let (l, r) = (s.bars[0].0 - 3.0 * sp, s.right + sp);
    let mut gs: Vec<&Glyph> =
        s.pg.glyphs
            .iter()
            .filter(|g| codes.contains(&g.code) && lo < g.y && g.y < hi && l < g.x0 && g.x0 < r)
            .collect();
    gs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
    // one mark a line: an "8" and its "va" are one
    gs.dedup_by(|b, a| (b.x0 - a.x1) < 0.5 * sp && (b.y - a.y).abs() < sp);
    for g in gs {
        let fifteen = matches!(g.code, 0xE514 | 0xE515 | 0xE516 | 0xE51D);
        let line = ottava_line(s, g);
        // below its staff (or marked bassa) it sounds lower
        let bassa = matches!(g.code, 0xE512 | 0xE513 | 0xE516 | 0xE51C | 0xE51D)
            || match line.and_then(|l| l.1) {
                _ if matches!(g.code, 0xE511 | 0xE515) => false,
                Some(low) => low,
                None => {
                    s.staves
                        .iter()
                        .any(|st| g.y > st.bottom() && g.y < st.bottom() + 6.0 * sp)
                        && !s
                            .staves
                            .iter()
                            .any(|st| g.y < st.top() && g.y > st.top() - 6.0 * sp)
                        || g.y > s.bottom()
                }
            };
        // one under the system above's last staff, or over the system below's first, is theirs
        let known_low = line.and_then(|l| l.1) == Some(true);
        if (!bassa && (above_reach(s, g) || g.y > s.bottom()))
            || (bassa && g.y < s.top())
            || (!known_low && g.y > s.bottom() + 8.0 * sp)
        {
            continue;
        }
        let i = if bassa {
            (0..s.staves.len())
                .filter(|&j| s.staves[j].bottom() < g.y)
                .max()
                .unwrap_or(0)
        } else {
            (0..s.staves.len())
                .find(|&j| s.staves[j].top() > g.y)
                .unwrap_or(s.staves.len() - 1)
        };
        let name = &s.names[i];
        let tok = match (fifteen, bassa) {
            (false, false) => "\\8va",
            (false, true) => "\\8vb",
            (true, false) => "\\15ma",
            (true, true) => "\\15mb",
        };
        let end = line.map_or(g.x1, |l| l.0);
        let runs_on = g.x0 < s.first_event && open.ottava.contains(name);
        if !runs_on {
            if open.ottava.contains(name) {
                put(bars, s, i, g.x0, "\\loco".into());
            }
            put_from(bars, s, i, g.x0, tok.into());
        }
        here.insert(i);
        if end > s.right - sp {
            open.ottava.insert(name.clone());
        } else {
            // the line ends over its last note or just past it: the music after it is as
            // printed (a note that starts where the line's hook stands is after it)
            put(bars, s, i, end + 0.4 * sp + 0.01, "\\loco".into());
            open.ottava.remove(name);
        }
    }
    for i in 0..s.names.len() {
        if !here.contains(&i) && open.ottava.remove(&s.names[i]) {
            put_first(bars, i, "\\loco".into());
        }
    }
}

/// An ottava mark's own line: the level pieces (dashes) that start just after the mark, and
/// never a staff's line or a ledger line that only passes near it. Its end, and whether it is
/// one under the notes (the line level with the mark's foot) or over them (level with its top),
/// when it is clearly either.
fn ottava_line(s: &Sys, g: &Glyph) -> Option<(f64, Option<bool>)> {
    let (pg, sp) = (s.pg, s.sp);
    let run = |lo: f64, hi: f64, sure: bool| {
        pg.hlines
            .iter()
            .filter(|h| {
                g.x1 - 0.3 * sp < h.x0
                    && h.x0 < g.x1 + 2.0 * sp
                    && lo * sp < g.y - h.y
                    && g.y - h.y < hi * sp
                    && h.w < 0.2 * sp
                    // (a line that starts with a hook is a tuplet's bracket set by the mark)
                    && !hooked(pg, h.x0, h.y, sp)
            })
            .filter_map(|h| {
                let (end, gaps) = line_from(pg, h.x0 - 0.01, h.y, 0.3, 2.0 * sp)?;
                // an ottava's line: dashes, a hook at its end, or on into the next system
                let its_own = gaps.len() >= 2 || end > s.right - sp || hooked(pg, end, h.y, sp);
                (its_own || (!sure && !is_ledger(s, h))).then_some((h.x0, end))
            })
            .min_by(|a, b| a.0.total_cmp(&b.0))
            .map(|l| l.1)
    };
    // at the mark's top, at its foot, or (a font that sets it otherwise) anywhere beside it
    match (run(1.25, 1.85, true), run(-0.25, 0.35, true)) {
        (Some(end), None) => Some((end, Some(false))),
        (None, Some(end)) => Some((end, Some(true))),
        _ => Some((run(-0.8, 1.6, false)?, None)),
    }
}

/// Whether a level line ending at (x, y) ends in a hook: a short upright stroke from its end.
fn hooked(pg: &Page, x: f64, y: f64, sp: f64) -> bool {
    pg.vlines.iter().any(|v| {
        (v.x - x).abs() < 0.15 * sp
            && v.y1 - v.y0 < 2.0 * sp
            && ((v.y0 - y).abs() < 0.2 * sp || (v.y1 - y).abs() < 0.2 * sp)
    })
}

/// Whether a short level line is a ledger line: where a line of one of the system's staves
/// would be were there more of them, with a notehead within its ends.
fn is_ledger(s: &Sys, h: &HLine) -> bool {
    let sp = s.sp;
    let on_a_line = s.staves.iter().any(|st| {
        let k = (h.y - st.top()) / st.sp();
        (k - k.round()).abs() < 0.06 && (k < -0.5 || k > 4.5) && -8.5 < k && k < 12.5
    });
    on_a_line
        && h.x1 - h.x0 < 3.5 * sp
        && s.pg.glyphs.iter().any(|g| {
            smufl::head(g.code).is_some()
                && h.x0 - 0.05 * sp < g.x0
                && g.x1 < h.x1 + 0.05 * sp
                && (g.y - h.y).abs() < 8.0 * sp
        })
}

/// Put an ottava's start on staff `i`: before the first note or rest in x's bar that reaches
/// past x (a chord's head set left of its stem, beside the others, starts before the mark set
/// over it), else after the bar's last.
fn put_from(bars: &mut Bars, s: &Sys, i: usize, x: f64, tok: String) {
    let b = s.bar_at(x);
    let reach = |e: &Ev| {
        if e.heads.is_empty() {
            e.x + 1.2 * s.sp
        } else {
            e.right()
        }
    };
    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| reach(e) > x + 0.3 * s.sp)
    {
        e.before.push(tok);
    } else if let Some(e) = evs.iter_mut().rev().find(|e| e.grace.is_none()) {
        e.after.push(tok);
    }
}

/// An ottava mark far over the system's first staff: the system above's, under its last staff
/// (an 8 marking a line below it), not this one's.
fn above_reach(s: &Sys, g: &Glyph) -> bool {
    s.staves
        .first()
        .is_some_and(|st| g.y < st.top() - 7.0 * s.sp)
}

/// Whether a pedal sign stands in the pedal's own parentheses (U+E676, U+E677).
fn in_parens(pg: &Page, g: &Glyph, sp: f64) -> bool {
    pg.glyphs
        .iter()
        .any(|p| p.code == 0xE676 && (p.y - g.y).abs() < 0.5 * sp && (g.x0 - p.x1).abs() < sp)
}

/// The pedal: `Ped.` where it goes down and `*` where it comes up, or a line under the notes
/// from `Ped.` to a hook, notched where it changes.
fn pedals(s: &Sys, open: &mut Open) -> Vec<PedalMark> {
    let sp = s.sp;
    let mut marks: Vec<PedalMark> = Vec::new();
    let mut mark = |at: f64, x: f64, staff: usize, tok: &'static str| {
        marks.push(PedalMark {
            bar: s.bar_at(at),
            staff,
            x,
            tok,
        })
    };
    let mut lined: BTreeSet<usize> = BTreeSet::new();
    let mut runs_off: BTreeSet<usize> = BTreeSet::new();
    let mut starts: Vec<(f64, f64, usize)> = Vec::new(); // where a line may start: x, y, staff

    // a pedal is printed under its staff, however far under (the row stands clear of the
    // lowest note's ledger lines): every sign from the system's top staff down to the system
    // below is this system's, and one over the top staff is the system above's
    let (l, r) = (s.bars[0].0 - 3.0 * sp, s.right + sp);
    // (a sign at the size of words is set in a line of them, `senza Ped.`: no mark)
    let signs = s.pg.glyphs.iter().filter(|g| {
        matches!(g.code, 0xE650 | 0xE651 | 0xE655 | 0xE656)
            && g.size > 0.6 * s.pg.size
            && l < g.x0
            && g.x0 < r
            && s.top() < g.y
            && (s.floor <= 0.0 || g.y < s.floor)
    });
    for g in signs {
        let i = s.staff_under_which(g.y);
        // `(Ped.)` at a system's start is the pedal still down from the system before, shown
        // again, and no second press
        if matches!(g.code, 0xE650 | 0xE651) && in_parens(s.pg, g, sp) {
            continue;
        }
        match g.code {
            0xE650 | 0xE651 => {
                mark(g.x0, g.x0, i, "\\ped");
                starts.push((g.x1, g.y, i));
            }
            // (the star ends where the pedal comes up: it stands before that note, and may
            // reach back under the last note held; its bar is the one it starts in)
            0xE655 => mark(g.x0, g.x1, i, "\\ped*"),
            _ => mark(g.x0, g.x0, i, "\\ped^"),
        }
    }
    // a line that runs on from the system before
    for (i, name) in s.names.iter().enumerate() {
        if open.pedal.contains(name) {
            let st = &s.staves[i];
            if let Some(h) = s.pg.hlines.iter().find(|h| {
                h.x0 < s.first_event
                    && h.x1 > s.first_event
                    && h.y > st.bottom() + sp
                    && (s.floor <= 0.0 || h.y < s.floor)
                    && h.x1 - h.x0 > 2.0 * sp
                    && s.staff_under_which(h.y) == i
            }) {
                starts.push((h.x0, h.y, i));
            }
        }
    }
    for (x, y, i) in starts {
        let Some((end, gaps)) = line_from(s.pg, x, y, 1.5 * sp, 2.5 * sp) else {
            continue;
        };
        if end - x < 1.0 * sp {
            continue;
        }
        lined.insert(i);
        for (a, b) in gaps {
            mark((a + b) / 2.0, (a + b) / 2.0, i, "\\ped^");
        }
        if end > s.right - sp {
            runs_off.insert(i);
        } else {
            mark(end, end, i, "\\ped*");
        }
    }
    marks.sort_by(|a, b| a.x.total_cmp(&b.x));
    for m in &marks {
        let name = &s.names[m.staff];
        match m.tok {
            "\\ped" => {
                open.pedal.insert(name.clone());
            }
            "\\ped*" => {
                open.pedal.remove(name);
            }
            _ => {}
        }
    }
    // a line that goes on into the next system leaves the pedal down
    for i in lined {
        if runs_off.contains(&i) {
            open.pedal.insert(s.names[i].clone());
        }
    }
    marks
}

/// Write a bar's pedal marks into its staves' voices as read (`voices`: per staff, its voices).
/// A mark is its staff's, at the time of the first note or rest that stands at it or right of
/// it on any staff of the system: the hand may be on the other staff there, or its notes read
/// in the other staff's line. On its own staff it goes before what starts at that time; into
/// blank time, which is split there; else before the staff's next note or rest, or after its
/// last. `skip`: the staves whose bar is not read. `tol`: how far left of a mark its note may
/// stand.
pub fn write_pedals(
    voices: &mut [Vec<Vec<Ev>>],
    marks: &[&PedalMark],
    skip: &dyn Fn(usize) -> bool,
    tol: f64,
) {
    if marks.is_empty() {
        return;
    }
    let timed = |e: &Ev| e.grace.is_none() && e.rest != Rest::Blank;
    // every staff's notes and rests: where each stands and when it starts (a rest alone in
    // its bar stands in the middle of it)
    let mut columns: Vec<(f64, Q)> = Vec::new();
    for (i, vs) in voices.iter().enumerate() {
        for v in vs.iter().filter(|_| !skip(i)) {
            let mut t = Q::ZERO;
            for e in v {
                if timed(e) && (e.is_note() || v.iter().filter(|e| timed(e)).count() > 1) {
                    columns.push((e.x, t));
                }
                t += e.takes();
            }
        }
    }
    for m in marks {
        let Some(vs) = voices.get_mut(m.staff).filter(|_| !skip(m.staff)) else {
            continue;
        };
        // (a star's end is known to stand before its note; a sign begins a little left of its)
        let tol = if m.tok == "\\ped*" { 0.3 * tol } else { tol };
        let at = (columns.iter())
            .filter(|c| c.0 >= m.x - tol)
            .map(|c| c.1)
            .min();
        write_pedal(vs, at, m, &timed);
    }
}

/// One mark into its staff's voices, at time `at` (None: after everything).
fn write_pedal(vs: &mut [Vec<Ev>], at: Option<Q>, m: &PedalMark, timed: &dyn Fn(&Ev) -> bool) {
    let tok = m.tok.to_string();
    // each event's start: (voice, place in it, start)
    let starts: Vec<(usize, usize, Q)> = (vs.iter().enumerate())
        .flat_map(|(vi, v)| {
            let mut t = Q::ZERO;
            (v.iter().enumerate())
                .map(|(k, e)| {
                    let s = t;
                    t += e.takes();
                    (vi, k, s)
                })
                .collect::<Vec<_>>()
        })
        .collect();
    if let Some(at) = at {
        // what starts then
        let on = |&&(vi, k, s): &&(usize, usize, Q)| s == at && timed(&vs[vi][k]);
        if let Some(&(vi, k, _)) = starts.iter().find(on) {
            vs[vi][k].before.push(tok);
            return;
        }
        // blank time over it: the mark stands in it
        let blank = |&&(vi, k, s): &&(usize, usize, Q)| {
            let e = &vs[vi][k];
            e.rest == Rest::Blank && e.grace.is_none() && s <= at && at < s + e.dur
        };
        if let Some(&(vi, k, s)) = starts.iter().find(blank) {
            let (head, tail) = (at - s, s + vs[vi][k].dur - at);
            let plain = |d: Q| crate::write::plain_lengths(d).is_ok();
            if head.is_zero() {
                vs[vi][k].before.push(tok);
                return;
            }
            if vs[vi][k].tuplets.is_empty() && plain(head) && plain(tail) {
                let mut rest = vs[vi][k].clone();
                rest.dur = tail;
                rest.x = m.x;
                rest.before = vec![tok];
                vs[vi][k].dur = head;
                vs[vi][k].after.clear();
                vs[vi].insert(k + 1, rest);
                return;
            }
        }
        // the staff's next note or rest
        let next = (starts.iter())
            .filter(|&&(vi, k, s)| s >= at && timed(&vs[vi][k]))
            .min_by_key(|&&(vi, _, s)| (s, vi));
        if let Some(&(vi, k, _)) = next {
            vs[vi][k].before.push(tok);
            return;
        }
    }
    // after its last (blank time, where it has nothing else)
    let last = (starts.iter())
        .filter(|&&(vi, k, _)| timed(&vs[vi][k]))
        .max_by_key(|&&(vi, _, s)| (s, std::cmp::Reverse(vi)))
        .or_else(|| {
            starts
                .iter()
                .rfind(|&&(vi, k, _)| vi == 0 && vs[vi][k].grace.is_none())
        });
    if let Some(&(vi, k, _)) = last {
        vs[vi][k].after.push(tok);
    }
}

/// Glissandos: a straight line from a note's head to a later head, not level.
fn glissandos(s: &Sys, bars: &mut Bars, used: &[usize]) {
    let sp = s.sp;
    for (k, d) in s.pg.diagonals.iter().enumerate() {
        if used.contains(&k) || d.2 - d.0 < 1.5 * sp || (d.3 - d.1).abs() < 0.3 * sp {
            continue;
        }
        if !(s.top() - 4.0 * sp < d.1 && d.1 < s.bottom() + 4.0 * sp) {
            continue;
        }
        // the note it leaves and the one it reaches
        let mut from: Option<(usize, usize, usize)> = None;
        let mut to = false;
        for (b, bar) in bars.iter().enumerate() {
            for (i, evs) in bar.iter().enumerate() {
                for (n, e) in evs.iter().enumerate() {
                    if !e.is_note() {
                        continue;
                    }
                    let near = |x: f64, y: f64, right: bool| {
                        e.heads.iter().any(|h| {
                            let dx = if right { x - h.x1 } else { h.x0 - x };
                            -0.3 * sp < dx && dx < 1.5 * sp && (h.y - y).abs() < 1.2 * sp
                        })
                    };
                    if near(d.0, d.1, true) {
                        from = Some((b, i, n));
                    }
                    if near(d.2, d.3, false) {
                        to = true;
                    }
                }
            }
        }
        if let (Some((b, i, n)), true) = (from, to) {
            bars[b][i][n].gliss = true;
        }
    }
}

/// Fingering: a digit 1 to 5 by a note's heads, set as text or in the music font.
fn fingering(s: &Sys, bars: &mut Bars, words: &[Word], taken: &mut [bool]) {
    let sp = s.sp;
    let mut digits: Vec<(f64, f64, u8, Option<usize>)> = Vec::new(); // x, y, finger, word
    for (k, w) in words.iter().enumerate() {
        if w.text.len() == 1 && w.size < 3.0 * sp {
            if let Some(f) = w.text.chars().next().and_then(|c| c.to_digit(10)) {
                if (1..=5).contains(&f) {
                    digits.push((
                        (w.x0 + w.x1) / 2.0,
                        w.base - 0.35 * w.size,
                        f as u8,
                        Some(k),
                    ));
                }
            }
        }
    }
    for g in glyphs_of(s, &[0xED11, 0xED12, 0xED13, 0xED14, 0xED15]) {
        digits.push((
            (g.x0 + g.x1) / 2.0,
            g.y - 0.4 * sp,
            (g.code - 0xED10) as u8,
            None,
        ));
    }
    // a tuplet's number set as text is no finger's
    let numbers = tuplet_numbers(bars, &digits, sp);
    // per note: the digits by it
    let mut by_note: BTreeMap<(usize, usize, usize), Vec<Finger>> = BTreeMap::new();
    for (n, (x, y, f, k)) in digits.into_iter().enumerate() {
        if numbers.contains(&n) {
            continue;
        }
        if x < s.first_event - 0.5 * sp {
            continue; // a bar's number
        }
        let mut best: Option<((usize, usize, usize), f64)> = None;
        for (b, bar) in bars.iter().enumerate() {
            for (i, evs) in bar.iter().enumerate() {
                for (n, e) in evs.iter().enumerate() {
                    if !e.is_note() || x < e.left() - 0.6 * sp || x > e.right() + 0.6 * sp {
                        continue;
                    }
                    let dy = e
                        .heads
                        .iter()
                        .map(|h| (h.y - y).abs())
                        .fold(f64::MAX, f64::min);
                    if dy < 3.0 * sp && best.is_none_or(|(_, d)| dy < d) {
                        best = Some(((b, i, n), dy));
                    }
                }
            }
        }
        if let Some((at, _)) = best {
            by_note.entry(at).or_default().push((y, f, k));
        }
    }
    for ((b, i, n), mut ds) in by_note {
        let e = &mut bars[b][i][n];
        ds.sort_by(|a, b| a.0.total_cmp(&b.0));
        // the heads top to bottom, by place
        let mut heads: Vec<(f64, i32)> = e
            .heads
            .iter()
            .zip(&e.place_of)
            .map(|(h, &p)| (h.y, p))
            .collect();
        heads.sort_by(|a, b| a.0.total_cmp(&b.0));
        heads.dedup_by_key(|h| h.1);
        if ds.len() == heads.len() {
            for ((_, f, _), (_, p)) in ds.iter().zip(&heads) {
                e.fingers.insert(*p, *f);
            }
        } else {
            for (y, f, _) in &ds {
                let p = heads
                    .iter()
                    .min_by(|a, b| (a.0 - y).abs().total_cmp(&(b.0 - y).abs()))
                    .map(|h| h.1);
                if let Some(p) = p {
                    e.fingers.insert(p, *f);
                }
            }
        }
        for (_, _, k) in ds {
            if let Some(k) = k {
                taken[k] = true;
            }
        }
    }
}

/// The text digits (x, y, digit, word) that are tuplets' numbers: for each group of notes read
/// as a tuplet, the digit of its number standing nearest the middle of the group, within its
/// width.
fn tuplet_numbers(
    bars: &Bars,
    digits: &[(f64, f64, u8, Option<usize>)],
    sp: f64,
) -> BTreeSet<usize> {
    let mut out = BTreeSet::new();
    for evs in bars.iter().flatten() {
        // each group: its number, its notes' left and right ends
        let mut groups: BTreeMap<usize, (u32, f64, f64)> = BTreeMap::new();
        for e in evs {
            for &(actual, _, id) in &e.tuplets {
                let g = groups.entry(id).or_insert((actual, f64::MAX, f64::MIN));
                g.1 = g.1.min(e.x);
                g.2 = g.2.max(e.x + 1.2 * sp);
            }
        }
        for (actual, l, r) in groups.into_values() {
            let mid = (l + r) / 2.0;
            let number = (0..digits.len())
                .filter(|n| !out.contains(n))
                .filter(|&n| {
                    let (x, _, f, word) = digits[n];
                    word.is_some() && f as u32 == actual && l - 0.5 * sp < x && x < r + 0.5 * sp
                })
                .min_by(|&a, &b| {
                    (digits[a].0 - mid)
                        .abs()
                        .total_cmp(&(digits[b].0 - mid).abs())
                });
            out.extend(number);
        }
    }
    out
}

/// Whether a word is boxed (a rehearsal mark): level lines over it and under it.
fn boxed(pg: &Page, w: &Word) -> bool {
    let spans = |lo: f64, hi: f64| {
        pg.hlines.iter().any(|h| {
            lo < h.y && h.y < hi && h.x0 <= w.x0 + 0.1 * w.size && h.x1 >= w.x1 - 0.1 * w.size
        })
    };
    spans(w.base - 1.8 * w.size, w.base - 0.6 * w.size)
        && spans(w.base - 0.1 * w.size, w.base + 0.8 * w.size)
}

/// A chord symbol's pieces run together (a raised extension, a flat set apart).
fn chord_runs(ws: &[Word]) -> Vec<(Word, Vec<usize>)> {
    let mut idx: Vec<usize> = (0..ws.len()).collect();
    idx.sort_by(|&a, &b| ws[a].x0.total_cmp(&ws[b].x0));
    let mut out: Vec<(Word, Vec<usize>)> = Vec::new();
    let mut used = vec![false; ws.len()];
    for &a in &idx {
        if used[a] {
            continue;
        }
        used[a] = true;
        let mut w = ws[a].clone();
        let mut ks = vec![a];
        for &b in &idx {
            let v = &ws[b];
            if used[b] {
                continue;
            }
            if v.x0 >= w.x1 - 0.05 * w.size
                && v.x0 - w.x1 < 0.15 * w.size
                && (v.base - w.base).abs() < 0.6 * w.size
                && v.size <= w.size * 1.05
            {
                used[b] = true;
                w.text.push_str(&v.text);
                w.x1 = v.x1;
                ks.push(b);
            }
        }
        out.push((w, ks));
    }
    out
}

/// A tempo mark inside a bar as a token: its words (if any) and its number.
fn tempo_inside(words: &str, number: &str) -> String {
    match words.is_empty() {
        true => format!("\\tempo:{number}"),
        false => format!("\\tempo:\"{words}\":{number}"),
    }
}

/// The words: chord symbols, rehearsal marks, tempo and expression words.
fn texts(s: &Sys, bars: &mut Bars, words: &[Word], taken: &mut [bool], open: &mut Open) -> Placed {
    let sp = s.sp;
    let mut placed = Placed::default();
    // words under a sung staff are its song's
    let sung_band = |w: &Word| {
        s.sung.iter().any(|&i| {
            let st = &s.staves[i];
            let next = s
                .staves
                .get(i + 1)
                .map_or(st.bottom() + 12.0 * sp, |n| n.top());
            w.base > st.bottom() && w.base < next
        })
    };
    // (but not words a line of dashes runs on from: `cresc. - - -` under a singer's staff)
    let with_dashes = crate::dashes::phrases_with_dashes(s.pg, sp, words);
    let free: Vec<Word> = words
        .iter()
        .enumerate()
        .filter(|(k, w)| !taken[*k] && (!sung_band(w) || with_dashes[*k]))
        .map(|(_, w)| w.clone())
        .collect();
    // chord symbols first, from the pieces they are set in
    let mut chord_used = vec![false; free.len()];
    for (w, ks) in chord_runs(&free) {
        let text = w.text.replace(['(', ')'], "");
        let above = s.staves.iter().position(|st| w.base < st.top());
        let Some(i) = above else { continue };
        if w.base < s.staves[i].top() - 10.0 * sp
            || !fm_transcribe::is_chord_symbol(&w.text)
            || jump_named(&text).is_some()
        {
            continue;
        }
        // a lone capital in a box is a rehearsal mark
        if boxed(s.pg, &w) {
            continue;
        }
        // a word of a phrase ("Verse A") is no chord
        let in_phrase = free.iter().enumerate().any(|(k, v)| {
            !ks.contains(&k)
                && (v.base - w.base).abs() < 0.2 * w.size
                && (v.x0 - w.x1).max(w.x0 - v.x1) < 0.6 * w.size
                && !fm_transcribe::is_chord_symbol(&v.text)
        });
        if in_phrase {
            continue;
        }
        // over the staff below it, not one of a part lower down: the nearest staff under it
        if i > 0 && w.base < s.staves[i - 1].bottom() + sp {
            continue;
        }
        for k in ks {
            chord_used[k] = true;
        }
        put(bars, s, i, w.x0, format!("\\chord:{}", w.text));
    }
    let rest: Vec<Word> = free
        .into_iter()
        .zip(chord_used)
        .filter(|(_, u)| !u)
        .map(|(w, _)| w)
        .collect();
    let mut ps = phrases(rest);
    // a metronome mark: a note of the music font between its words ("Moderately (" and "= 79)")
    let mut gone = vec![false; ps.len()];
    // the notes of SMuFL's metronome marks, in its first range and its newer one
    let notes = [
        0xE1D2, 0xE1D3, 0xE1D4, 0xE1D5, 0xE1D6, 0xE1D7, 0xE1D8, 0xE1D9, 0xECA2, 0xECA3, 0xECA4,
        0xECA5, 0xECA6, 0xECA7, 0xECA8, 0xECA9, 0xECAA,
    ];
    for g in glyphs_of(s, &notes).filter(|g| g.y < s.top()) {
        let unit = match g.code {
            0xE1D2 | 0xECA2 => 1,
            0xE1D3 | 0xE1D4 | 0xECA3 | 0xECA4 => 2,
            0xE1D5 | 0xE1D6 | 0xECA5 | 0xECA6 => 4,
            0xE1D7 | 0xE1D8 | 0xECA7 | 0xECA8 => 8,
            _ => 16,
        };
        let dotted = s.pg.glyphs.iter().any(|d| {
            (d.code == crate::smufl::DOT || d.code == 0xECB7)
                && d.x0 > g.x0
                && d.x0 - g.x1 < 1.0 * sp
                && (d.y - g.y).abs() < 1.0 * sp
        });
        let line = |p: &Word| (p.base - g.y).abs() < 1.0 * sp;
        let right = ps.iter().position(|p| {
            line(p) && p.x0 > g.x0 && p.x0 - g.x1 < 2.0 * sp && p.text.trim_start().starts_with('=')
        });
        let Some(r) = right else { continue };
        let digits: String = ps[r]
            .text
            .trim_start()
            .trim_start_matches('=')
            .trim()
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        let Ok(bpm) = digits.parse::<f64>() else {
            continue;
        };
        let left = ps
            .iter()
            .position(|p| line(p) && p.x1 <= g.x0 + 0.2 * sp && g.x0 - p.x1 < 2.0 * sp);
        let words = left
            .map(|l| {
                ps[l]
                    .text
                    .trim()
                    .trim_end_matches('(')
                    .trim()
                    .replace('"', "'")
            })
            .unwrap_or_default();
        gone[r] = true;
        if let Some(l) = left {
            gone[l] = true;
        }
        let x = left.map_or(g.x0, |l| ps[l].x0);
        let b = s.bar_at(x.max(s.bars[0].0));
        // (the number is printed: `!`)
        let number = format!("{unit}{}={bpm}!", if dotted { "." } else { "" });
        // one that stands past its bar's first note holds from the note it stands at
        let first = (bars[b].iter().flatten())
            .filter(|e| e.rest != Rest::Blank)
            .map(|e| e.x)
            .fold(f64::MAX, f64::min);
        if x > first + 2.0 * sp {
            put(bars, s, 0, x, tempo_inside(&words, &number));
        } else {
            placed.tempos.push((b, format!("\"{words}\" {number}")));
        }
    }
    let mut k = 0;
    ps.retain(|_| {
        k += 1;
        !gone[k - 1]
    });
    // a line of several words under a staff is its lyrics (a staff read as not sung), not marks
    let lyric_line = |p: &Word| {
        let (i, above) = s.nearest_staff(p.base - 0.35 * p.size);
        !above
            && ps
                .iter()
                .filter(|q| {
                    (q.base - p.base).abs() < 0.3 * sp
                        && s.nearest_staff(q.base - 0.35 * q.size) == (i, false)
                })
                .count()
                >= 4
    };
    let lyrics: Vec<bool> = ps.iter().map(lyric_line).collect();
    // the lines of dashes that run on from words (`cresc. - - -`)
    let mut dashes = crate::dashes::Plan::new(
        s,
        &ps,
        |p| Some(s.nearest_staff(p.base - 0.35 * p.size).0),
        open,
    );
    for (k, (p, _)) in ps
        .iter()
        .zip(&lyrics)
        .enumerate()
        .filter(|(_, (_, l))| !**l)
    {
        let t = p.text.trim();
        if t.is_empty()
            || jump_named(t).is_some()
            || ending_numbers(t).is_some()
            || t.chars()
                .all(|c| c.is_ascii_digit() || c == ':' || c == '.')
        {
            continue;
        }
        let lower = t.to_lowercase();
        if [
            "ped.", "ped", "*", "gliss.", "gliss", "8va", "8vb", "15ma", "loco",
        ]
        .contains(&lower.as_str())
            || lower.starts_with('©')
            || lower.contains("copyright")
        {
            continue;
        }
        let quoted = t.replace('"', "'");
        if boxed(s.pg, p) && p.base < s.top() {
            put(bars, s, 0, p.x0, format!("\\mark:\"{quoted}\""));
            continue;
        }
        let (i, above) = s.nearest_staff(p.base - 0.35 * p.size);
        // over the top staff, only near it: what stands higher is the page's head
        if p.base < s.top() - 6.0 * sp {
            continue;
        }
        let mut tok = format!("{}\"{quoted}\"", if above { '^' } else { '_' });
        match dashes.role(k) {
            crate::dashes::Role::Continues => continue,
            crate::dashes::Role::Opens => tok.push_str("--"),
            crate::dashes::Role::Plain => dashes.wrote(s, i, p.x0, &quoted),
        }
        put(bars, s, i, p.x0, tok);
    }
    dashes.close(s, bars, open);
    placed
}

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

    #[test]
    fn a_tuplet_s_number_set_as_text_is_no_fingering() {
        // three notes read as a triplet (group 7) at 10, 14, 18; a 3 over their middle is
        // the triplet's number, a second 3 by the first note a finger, and a 2 a finger
        let mut evs = notes_at(&[10.0, 14.0, 18.0, 30.0], 102.0);
        for e in evs.iter_mut().take(3) {
            e.tuplets.push((3, 2, 7));
        }
        let bars: Bars = vec![vec![evs]];
        let digits = [
            (10.5, 99.0, 3, Some(0)),
            (14.6, 98.0, 3, Some(1)),
            (18.5, 99.0, 2, Some(2)),
            (30.5, 99.0, 3, Some(3)),
        ];
        let numbers = tuplet_numbers(&bars, &digits, 1.0);
        assert_eq!(numbers.into_iter().collect::<Vec<_>>(), [1]);
        // a digit of the music font's fingering is a finger wherever it stands
        let digits = [(14.6, 98.0, 3, None)];
        assert!(tuplet_numbers(&bars, &digits, 1.0).is_empty());
    }

    #[test]
    fn a_printed_metronome_mark_inside_a_bar_is_a_token_the_format_takes() {
        assert_eq!(tempo_inside("", "4=96!"), "\\tempo:4=96!");
        assert_eq!(
            tempo_inside("Più mosso", "4.=60!"),
            "\\tempo:\"Più mosso\":4.=60!"
        );
        let text = format!(
            "part V \"V\" voice\ntime 6/8\ntempo \"Andante\" 4.=52!\nbar 1\nV: c5/4. {} c5/4.\n",
            tempo_inside("Più mosso", "4.=60!")
        );
        let x = fm_transcribe::compile(&text).unwrap().musicxml;
        assert_eq!(x.matches("<metronome").count(), 2);
    }

    #[test]
    fn a_hairpin_open_while_another_is_on_its_staff_is_numbered() {
        let pin = |staff: usize, x0: f64, x1: f64| Pin {
            cresc: true,
            staff,
            x0,
            x1,
        };
        // on one staff: one over the bar, a second inside it, a third that begins where the
        // first ends; and one on another staff at the same place
        let pins = [
            pin(0, 0.0, 50.0),
            pin(0, 20.0, 40.0),
            pin(0, 50.0, 80.0),
            pin(1, 0.0, 50.0),
        ];
        let mut number = vec![0; 4];
        number_hairpins(&pins, &mut number, 1.0);
        assert_eq!(number, vec![1, 2, 1, 1]);
        assert_eq!(hairpin_token("\\<", 1), "\\<");
        assert_eq!(hairpin_token("\\!", 2), "\\!2");
        // one that runs on from the system before as the second keeps its number, and a new
        // one beside it is the first
        let mut number = vec![2, 0, 0, 0];
        number_hairpins(&pins, &mut number, 1.0);
        assert_eq!(number, vec![2, 1, 1, 1]);
        // and the compiler takes them
        let text = "part P \"Piano\" piano\n\nkey 0 major\ntime 4/4\n\nbar 1\n\
                    P.1: \\< c5/4 \\<2 d5 \\!2 e5 \\! f5\nP.2: R\n";
        fm_transcribe::compile(text).unwrap();
    }

    #[test]
    fn an_ottava_far_over_the_system_is_the_system_above_s() {
        // an 8 nine spaces over the first staff (under the last staff of the system above) is
        // not this system's; one two spaces over it is
        let staves = [Staff {
            lines: [100.0, 101.0, 102.0, 103.0, 104.0],
            left: 0.0,
            right: 50.0,
            breaks: Vec::new(),
        }];
        let pg = Page::default();
        let names = ["V".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 50.0)],
            sp: 1.0,
            right: 50.0,
            first_event: 5.0,
            ceiling: 0.0,
            floor: 0.0,
            sung: &sung,
        };
        let eight = |y: f64| Glyph {
            code: 0xE510,
            x0: 10.0,
            x1: 11.0,
            y,
            size: 4.0,
        };
        assert!(above_reach(&s, &eight(91.0)));
        assert!(!above_reach(&s, &eight(98.0)));
    }

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

    #[test]
    fn a_pedal_is_one_mark_under_its_staff_not_the_system_above_s_too() {
        // the system above's pedal is drawn under its bottom staff, which is over this
        // system's top staff; this system's own is under its bottom staff
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let ped = |x0: f64, y: f64| Glyph {
            code: 0xE650,
            x0,
            x1: x0 + 2.0,
            y,
            size: 4.0,
        };
        let staves = piano_staves();
        let pg = Page {
            glyphs: vec![ped(30.0, 95.0), ped(10.0, 122.0)],
            hlines: vec![h(32.5, 45.0, 95.0), h(12.5, 25.0, 122.0)],
            ..Page::default()
        };
        let names = ["P.1".to_string(), "P.2".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 30.0), (30.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 90.0,
            floor: 0.0,
            sung: &sung,
        };
        let mut open = Open::default();
        let marks = pedals(&s, &mut open);
        // one pedal, under the bottom staff (staff 1) in the first bar: down at its sign, up
        // where its line ends; the sign over the top staff is the system above's
        let got: Vec<_> = marks.iter().map(|m| (m.bar, m.staff, m.tok)).collect();
        assert_eq!(got, [(0, 1, "\\ped"), (0, 1, "\\ped*")]);
        assert!(open.pedal.is_empty());
    }

    #[test]
    fn an_ottava_s_line_is_its_dashes_to_the_hook_not_the_staff_s_line_near_it() {
        // an 8 a space over the top staff, its line level with its top, hooked down at 20.6;
        // the staff's own top line passes two spaces under it, and a ledger line beside it
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let v = |x: f64, y0: f64, y1: f64| crate::page::VLine { x, y0, y1, w: 0.1 };
        let eight = Glyph {
            code: 0xE510,
            x0: 10.0,
            x1: 11.2,
            y: 98.0,
            size: 4.0,
        };
        let staves = piano_staves();
        let pg = Page {
            glyphs: vec![eight],
            hlines: vec![
                h(0.0, 60.0, 100.0),
                h(11.7, 13.0, 96.45),
                h(14.0, 15.3, 96.45),
                h(16.3, 17.6, 96.45),
                h(18.6, 20.6, 96.45),
                h(11.4, 13.4, 99.0),
            ],
            vlines: vec![v(20.6, 96.45, 97.5)],
            ..Page::default()
        };
        let names = ["P.1".to_string(), "P.2".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 30.0), (30.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 0.0,
            floor: 0.0,
            sung: &sung,
        };
        assert_eq!(ottava_line(&s, &eight), Some((20.6, Some(false))));
        // its notes: the first is set left of the mark (a chord's head beside the others), the
        // third starts where the hook stands and is after the line
        let mut bars: Bars = vec![
            vec![
                notes_at(&[8.8, 15.0, 20.5, 25.0], 99.0),
                notes_at(&[9.0], 114.0),
            ],
            vec![notes_at(&[35.0], 101.0), notes_at(&[35.0], 114.0)],
        ];
        let beside = bars[0][0][0].heads[0];
        bars[0][0][0].heads.push(Glyph {
            x0: 10.0,
            x1: 11.2,
            ..beside
        });
        let mut open = Open::default();
        ottavas(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][0]), ["\\8va|", "|", "\\loco|", "|"]);
        assert_eq!(marks_of(&bars[0][1]), ["|"]);
        assert!(open.ottava.is_empty());
    }

    #[test]
    fn a_tuplet_s_bracket_by_an_ottava_mark_is_not_its_line() {
        // an 8 over the staff, its line (one dashed stroke) level with its top and hooked down
        // at 26; under the line a triplet's bracket, level with the mark's foot, starts just
        // past the mark with a hook of its own and ends with one at 17
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let v = |x: f64, y0: f64, y1: f64| crate::page::VLine { x, y0, y1, w: 0.1 };
        let eight = Glyph {
            code: 0xE510,
            x0: 10.0,
            x1: 11.2,
            y: 98.0,
            size: 4.0,
        };
        let staves = piano_staves();
        let pg = Page {
            glyphs: vec![eight],
            hlines: vec![
                h(0.0, 60.0, 100.0),
                h(11.5, 26.0, 96.4),
                h(11.5, 13.5, 98.1),
                h(15.0, 17.0, 98.1),
            ],
            vlines: vec![
                v(26.0, 96.4, 97.4),
                v(11.5, 98.1, 98.9),
                v(17.0, 98.1, 98.9),
            ],
            ..Page::default()
        };
        let names = ["P.1".to_string(), "P.2".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 30.0), (30.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 0.0,
            floor: 0.0,
            sung: &sung,
        };
        assert_eq!(ottava_line(&s, &eight), Some((26.0, Some(false))));
    }

    #[test]
    fn an_ottava_s_line_level_with_its_foot_is_one_under_the_notes() {
        // an 8 nine spaces under the last staff (its notes on ledger lines), its line at its
        // foot running to the system's end: the staff's, an octave down, and on into the next
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.1 };
        let eight = Glyph {
            code: 0xE510,
            x0: 10.0,
            x1: 11.2,
            y: 125.0,
            size: 4.0,
        };
        let staves = piano_staves();
        let mut hlines = vec![h(0.0, 60.0, 116.0)];
        let mut x = 11.7;
        while x < 60.0 {
            hlines.push(h(x, (x + 1.3).min(60.0), 124.95));
            x += 2.3;
        }
        let pg = Page {
            glyphs: vec![eight],
            hlines,
            ..Page::default()
        };
        let names = ["P.1".to_string(), "P.2".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg: &pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 0.0,
            floor: 0.0,
            sung: &sung,
        };
        let (end, low) = ottava_line(&s, &eight).unwrap();
        assert!(end > 59.0);
        assert_eq!(low, Some(true));
        let mut bars: Bars = vec![vec![
            notes_at(&[10.0, 30.0], 101.0),
            notes_at(&[10.0, 30.0], 120.0),
        ]];
        let mut open = Open::default();
        ottavas(&s, &mut bars, &mut open);
        assert_eq!(marks_of(&bars[0][0]), ["|", "|"]);
        assert_eq!(marks_of(&bars[0][1]), ["\\8vb|", "|"]);
        assert!(open.ottava.contains("P.2"));
        // the same mark over the system below's first staff is not that system's
        let below = [Staff {
            lines: [130.0, 131.0, 132.0, 133.0, 134.0],
            left: 0.0,
            right: 60.0,
            breaks: Vec::new(),
        }];
        let names = ["V".to_string()];
        let s = Sys {
            pg: &pg,
            staves: &below,
            names: &names,
            bars: &[(0.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 116.0,
            floor: 0.0,
            sung: &sung,
        };
        let mut bars: Bars = vec![vec![notes_at(&[10.0, 30.0], 131.0)]];
        ottavas(&s, &mut bars, &mut Open::default());
        assert_eq!(marks_of(&bars[0][0]), ["|", "|"]);
    }

    fn sign(code: u32, x0: f64, x1: f64, y: f64) -> Glyph {
        Glyph {
            code,
            x0,
            x1,
            y,
            size: 4.0,
        }
    }

    /// The pedal marks of a page read as the piano's system of two bars (0..30, 30..60).
    fn pedals_in(pg: &Page, floor: f64, open: &mut Open) -> Vec<PedalMark> {
        let staves = piano_staves();
        let names = ["P.1".to_string(), "P.2".to_string()];
        let sung = BTreeSet::new();
        let s = Sys {
            pg,
            staves: &staves,
            names: &names,
            bars: &[(0.0, 30.0), (30.0, 60.0)],
            sp: 1.0,
            right: 60.0,
            first_event: 5.0,
            ceiling: 90.0,
            floor,
            sung: &sung,
        };
        pedals(&s, open)
    }

    fn page_of(glyphs: Vec<Glyph>) -> Page {
        Page {
            glyphs,
            ..Page::default()
        }
    }

    #[test]
    fn a_pedal_sign_far_under_the_bottom_staff_is_read_on_it() {
        // the last system on the page has nothing under it to be mistaken for
        let pg = page_of(vec![sign(0xE650, 10.0, 12.0, 130.0)]);
        let marks = pedals_in(&pg, 0.0, &mut Open::default());
        let got: Vec<_> = marks.iter().map(|m| (m.bar, m.staff, m.x, m.tok)).collect();
        assert_eq!(got, [(0, 1, 10.0, "\\ped")]);
    }

    #[test]
    fn a_pedal_sign_at_the_size_of_words_is_no_mark() {
        // `senza Ped.` set as words: the sign is half the music's size, in the line of text
        let mut pg = page_of(vec![
            sign(0xE650, 10.0, 12.0, 125.0),
            Glyph {
                size: 2.0,
                ..sign(0xE650, 40.0, 41.0, 125.0)
            },
        ]);
        pg.size = 4.0;
        let marks = pedals_in(&pg, 0.0, &mut Open::default());
        let got: Vec<_> = marks.iter().map(|m| m.x).collect();
        assert_eq!(got, [10.0]);
    }

    #[test]
    fn a_pedal_sign_under_the_next_system_s_top_is_not_read() {
        let pg = page_of(vec![
            sign(0xE650, 10.0, 12.0, 139.0),
            sign(0xE650, 40.0, 42.0, 145.0),
        ]);
        let marks = pedals_in(&pg, 140.0, &mut Open::default());
        let got: Vec<_> = marks.iter().map(|m| (m.staff, m.x)).collect();
        assert_eq!(got, [(1, 10.0)]);
    }

    #[test]
    fn a_pedal_sign_between_a_piano_s_staves_is_the_upper_staff_s_even_nearer_the_lower() {
        // a pedal is printed under its staff: 2 over the lower staff's top is 6 under the
        // upper's bottom, and still the upper's
        let pg = page_of(vec![sign(0xE650, 10.0, 12.0, 110.0)]);
        let marks = pedals_in(&pg, 0.0, &mut Open::default());
        let got: Vec<_> = marks.iter().map(|m| m.staff).collect();
        assert_eq!(got, [0]);
    }

    #[test]
    fn a_pedal_sign_in_parentheses_is_no_mark_and_leaves_the_pedal_as_it_was() {
        // `(Ped.)` at a system's start shows the pedal still down, and is no second press
        let mut open = Open::default();
        open.pedal.insert("P.2".to_string());
        let pg = page_of(vec![
            sign(0xE676, 8.0, 10.0, 122.0),
            sign(0xE650, 10.0, 12.0, 122.0),
        ]);
        assert!(pedals_in(&pg, 0.0, &mut open).is_empty());
        assert!(open.pedal.contains("P.2"));
        // the same sign with no parenthesis is a press
        let pg = page_of(vec![sign(0xE650, 10.0, 12.0, 122.0)]);
        let marks = pedals_in(&pg, 0.0, &mut Open::default());
        let got: Vec<_> = marks.iter().map(|m| (m.staff, m.tok)).collect();
        assert_eq!(got, [(1, "\\ped")]);
    }

    #[test]
    fn a_pedal_star_stands_at_its_right_edge_in_the_bar_its_left_edge_is_in() {
        // the star ends where the pedal comes up, but it begins in the earlier bar
        let pg = page_of(vec![sign(0xE655, 29.5, 31.0, 122.0)]);
        let marks = pedals_in(&pg, 0.0, &mut Open::default());
        assert_eq!(
            marks,
            [PedalMark {
                bar: 0,
                staff: 1,
                x: 31.0,
                tok: "\\ped*"
            }]
        );
    }

    fn timed_note(x: f64, dur: Q) -> Ev {
        let mut e = notes_at(&[x], 101.0).remove(0);
        e.dur = dur;
        e
    }

    fn printed_rest_at(x: f64, dur: Q) -> Ev {
        let mut e = Ev::new(Vec::new(), None, None);
        e.rest = Rest::Printed(sign(0xE4E4, x, x + 1.0, 102.0));
        e.dur = dur;
        e.x = x;
        e
    }

    fn quarters(xs: &[f64]) -> Vec<Ev> {
        xs.iter().map(|&x| timed_note(x, Q::ONE)).collect()
    }

    fn pedal_mark(staff: usize, x: f64, tok: &'static str) -> PedalMark {
        PedalMark {
            bar: 0,
            staff,
            x,
            tok,
        }
    }

    fn length(v: &[Ev]) -> Q {
        v.iter().fold(Q::ZERO, |t, e| t + e.takes())
    }

    #[test]
    fn a_pedal_mark_at_a_note_of_its_own_staff_goes_before_that_note() {
        let mut voices = vec![
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
        ];
        let m = pedal_mark(1, 20.0, "\\ped");
        write_pedals(&mut voices, &[&m], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[1][0]), ["|", "\\ped|", "|", "|"]);
        assert_eq!(marks_of(&voices[0][0]), ["|", "|", "|", "|"]);
    }

    #[test]
    fn a_pedal_mark_in_a_staff_s_blank_time_splits_it_at_the_other_staff_s_note() {
        // the lower staff has a note and then nothing printed; the upper's note at 30 is where
        // the mark stands
        let q = Q::ONE;
        let mut voices = vec![
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
            vec![vec![timed_note(10.0, q), Ev::spacer(Q::int(3), 20.0)]],
        ];
        let m = pedal_mark(1, 29.5, "\\ped");
        write_pedals(&mut voices, &[&m], &|_| false, 0.8);
        let low = &voices[1][0];
        assert_eq!(low.len(), 3);
        assert_eq!(low[0].dur, q);
        assert!(low[1].rest == Rest::Blank && low[1].dur == q);
        assert!(low[2].rest == Rest::Blank && low[2].dur == Q::int(2));
        assert_eq!(marks_of(low), ["|", "|", "\\ped|"]);
        assert_eq!(length(low), Q::int(4));
    }

    #[test]
    fn a_pedal_mark_a_held_note_cannot_stand_in_goes_after_it_or_before_the_next_note() {
        // a whole note on the lower staff covers the time of the upper's note at 30: the mark
        // is after it, there being nothing later on its staff
        let mut voices = vec![
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
            vec![vec![timed_note(10.0, Q::int(4))]],
        ];
        let m = pedal_mark(1, 29.5, "\\ped");
        write_pedals(&mut voices, &[&m], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[1][0]), ["|\\ped"]);
        // with a note later on the staff (in another voice) it goes before that
        let mut voices = vec![
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
            vec![
                vec![timed_note(10.0, Q::int(3)), timed_note(40.0, Q::ONE)],
                vec![timed_note(10.0, Q::int(4))],
            ],
        ];
        write_pedals(&mut voices, &[&m], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[1][0]), ["|", "\\ped|"]);
        assert_eq!(marks_of(&voices[1][1]), ["|"]);
    }

    #[test]
    fn a_pedal_star_reaches_back_a_third_as_far_as_a_sign() {
        // a note 0.5 left of the mark: a sign (0.8) stands at it, a star (0.24) is after it
        let m_sign = pedal_mark(0, 20.5, "\\ped");
        let m_star = pedal_mark(0, 20.5, "\\ped*");
        let mut voices = vec![vec![quarters(&[10.0, 20.0])]];
        write_pedals(&mut voices, &[&m_sign], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[0][0]), ["|", "\\ped|"]);
        let mut voices = vec![vec![quarters(&[10.0, 20.0])]];
        write_pedals(&mut voices, &[&m_star], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[0][0]), ["|", "|\\ped*"]);
        // and before the next note, where there is one
        let mut voices = vec![vec![quarters(&[10.0, 20.0, 30.0])]];
        write_pedals(&mut voices, &[&m_star], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[0][0]), ["|", "|", "\\ped*|"]);
    }

    #[test]
    fn a_skipped_staff_gets_no_pedal_mark_and_its_notes_are_no_columns() {
        let mut voices = vec![
            vec![vec![
                timed_note(10.0, Q::ONE),
                Ev::spacer(Q::int(2), 20.0),
                timed_note(40.0, Q::ONE),
            ]],
            vec![quarters(&[10.0, 20.0, 30.0, 40.0])],
        ];
        let (a, b) = (pedal_mark(0, 29.5, "\\ped"), pedal_mark(1, 10.0, "\\ped"));
        write_pedals(&mut voices, &[&a, &b], &|i| i == 1, 0.8);
        // the skipped staff's note at 30 is no place for the mark: it goes before the 40
        assert_eq!(marks_of(&voices[0][0]), ["|", "|", "\\ped|"]);
        assert_eq!(marks_of(&voices[1][0]), ["|", "|", "|", "|"]);
    }

    #[test]
    fn a_rest_alone_in_its_voice_is_no_column_for_a_pedal_mark() {
        // the upper staff's printed bar rest stands mid-bar at 30, but is no time-0 note
        let mut voices = vec![
            vec![vec![printed_rest_at(30.0, Q::int(4))]],
            vec![vec![
                timed_note(10.0, Q::int(2)),
                timed_note(40.0, Q::int(2)),
            ]],
        ];
        let m = pedal_mark(1, 25.0, "\\ped");
        write_pedals(&mut voices, &[&m], &|_| false, 0.8);
        assert_eq!(marks_of(&voices[1][0]), ["|", "\\ped|"]);
    }
}