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
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
//! One PDF page as the reader sees it: the music font's glyphs at their places, the text's letters,
//! and the drawn lines, beams and curves. Coordinates are the page's, y growing downwards.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::rc::Rc;

use hayro_interpret::font::{Glyph as PdfGlyph, GlyphRun};
use hayro_interpret::hayro_cmap::BfString;
use hayro_interpret::kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape};
use hayro_interpret::{
    interpret_page, BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image, ImageData,
    ImageDrawProps, InterpreterCache, InterpreterSettings, SoftMask,
};

use crate::legacy::{self, Decoding, Family, Role};
use crate::lilypond;
use crate::mscore;
use crate::shapes;
use crate::smufl;

/// A music font's glyph: its code point, left edge, right edge, origin height (a notehead's
/// origin is its exact staff place) and size (only ever compared with other glyphs' sizes).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glyph {
    pub code: u32,
    pub x0: f64,
    pub x1: f64,
    pub y: f64,
    pub size: f64,
}

/// A letter of the page's text: its left edge, its advance's end, its baseline and its font size.
/// `run` numbers the text-showing operation it came in (a word never spans two).
#[derive(Clone, Debug)]
pub struct Letter {
    pub ch: char,
    pub x0: f64,
    pub x1: f64,
    pub base: f64,
    pub size: f64,
    pub run: usize,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HLine {
    pub x0: f64,
    pub x1: f64,
    pub y: f64,
    pub w: f64,
}

/// A vertical line: x, top, bottom, width.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VLine {
    pub x: f64,
    pub y0: f64,
    pub y1: f64,
    pub w: f64,
}

/// A five-line staff: the heights of its lines, top to bottom, and its left and right ends.
#[derive(Clone, Debug, PartialEq)]
pub struct Staff {
    pub lines: [f64; 5],
    pub left: f64,
    pub right: f64,
    /// Where its lines stop and start again within it (a coda set apart on the line).
    pub breaks: Vec<(f64, f64)>,
}

impl Staff {
    pub fn top(&self) -> f64 {
        self.lines[0]
    }
    pub fn bottom(&self) -> f64 {
        self.lines[4]
    }
    /// The staff space: the distance between two lines.
    pub fn sp(&self) -> f64 {
        (self.lines[4] - self.lines[0]) / 4.0
    }
}

/// A filled shape with curved edges (a tie, a slur): its bounding box, and how high its two
/// ends stand (`ya` its left end's, `yb` its right end's: the leftmost and the rightmost of the
/// points its outline is drawn through).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Curve {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
    pub ya: f64,
    pub yb: f64,
}

impl Curve {
    pub(crate) fn of(p: &BezPath) -> Curve {
        let b = p.bounding_box();
        let (mut a, mut z) = (Point::new(f64::MAX, 0.0), Point::new(f64::MIN, 0.0));
        for el in p.elements() {
            let q = match *el {
                PathEl::MoveTo(q) | PathEl::LineTo(q) => q,
                PathEl::QuadTo(_, q) | PathEl::CurveTo(_, _, q) => q,
                PathEl::ClosePath => continue,
            };
            if q.x < a.x {
                a = q;
            }
            if q.x > z.x {
                z = q;
            }
        }
        Curve {
            x0: b.x0,
            y0: b.y0,
            x1: b.x1,
            y1: b.y1,
            ya: a.y,
            yb: z.y,
        }
    }

    /// Whether it arches upwards (a slur over its notes): its ends stand lower than its middle.
    pub fn over(&self) -> bool {
        (self.ya + self.yb) / 2.0 > (self.y0 + self.y1) / 2.0
    }

    /// Whether its two ends stand at one height (within a tenth of a staff space), as a tie's
    /// do: a slur between notes of two pitches slants, and so does the half of a slur that
    /// runs off a system's end.
    pub fn level(&self, sp: f64) -> bool {
        (self.ya - self.yb).abs() < 0.1 * sp
    }
}

#[derive(Clone, Debug, Default)]
pub struct Page {
    pub width: f64,
    pub glyphs: Vec<Glyph>,
    pub letters: Vec<Letter>,
    pub hlines: Vec<HLine>,
    pub vlines: Vec<VLine>,
    /// Filled shapes of straight edges only (beams), as their outline's points.
    pub polys: Vec<Vec<(f64, f64)>>,
    /// Filled shapes with curved edges (ties and slurs).
    pub curves: Vec<Curve>,
    /// Stroked lines neither level nor upright (hairpins, glissandos, a pedal's change), as
    /// (x0, y0, x1, y1, width) with x0 <= x1.
    pub diagonals: Vec<(f64, f64, f64, f64, f64)>,
    /// Guitar chord frames (a grid of strings and frets over the staff), as (x0, y0, x1, y1): their
    /// lines are no stems, their dots no ties, their numbers no fingering.
    pub frames: Vec<(f64, f64, f64, f64)>,
    /// The letter pairs the document shows kerned (`words::kerned_pairs`): None for a page
    /// read alone.
    pub kerned: Option<std::sync::Arc<std::collections::BTreeSet<crate::words::Kern>>>,
    /// The level lines stroked with a dash pattern (they are among `hlines` too): the line
    /// after `cresc.`, an ottava's.
    pub dashed: Vec<HLine>,
    /// The most common notehead size: a smaller head is a grace note. 0 when the page has no
    /// SMuFL noteheads (no music, or a music font this reader does not know).
    pub size: f64,
    /// The images drawn on the page, as the ink they leave: a program that prints its music
    /// font's glyphs as pictures (Musicnotes, Windows' Print to PDF) draws each glyph so.
    pub pictures: Vec<Picture>,
}

/// An image as drawn: its box on the page and where it leaves ink.
#[derive(Clone, Debug, PartialEq)]
pub struct Picture {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
    /// Its pixels across and down.
    pub w: usize,
    pub h: usize,
    /// Row by row from the top, left to right: whether the pixel is inked.
    pub ink: Vec<bool>,
}

impl Picture {
    /// The image's pixels (`luma`, `w` by `h`, row 0 its first) as drawn by `t` (from the unit
    /// square over the image to the page), when it is set upright: inked where `inked` says.
    pub(crate) fn of(
        t: Affine,
        w: usize,
        h: usize,
        inked: impl Fn(usize) -> bool,
    ) -> Option<Picture> {
        let [a, b, c, d, _, _] = t.as_coeffs();
        // (turned or skewed: not a glyph set upright)
        if b.abs() > 1e-6 || c.abs() > 1e-6 || w == 0 || h == 0 {
            return None;
        }
        let p0 = t * Point::new(0.0, 0.0);
        let p1 = t * Point::new(w as f64, h as f64);
        let (flip_x, flip_y) = (a < 0.0, d < 0.0);
        let mut ink = vec![false; w * h];
        for r in 0..h {
            for col in 0..w {
                let (rr, cc) = (
                    if flip_y { h - 1 - r } else { r },
                    if flip_x { w - 1 - col } else { col },
                );
                ink[rr * w + cc] = inked(r * w + col);
            }
        }
        Some(Picture {
            x0: p0.x.min(p1.x),
            y0: p0.y.min(p1.y),
            x1: p0.x.max(p1.x),
            y1: p0.y.max(p1.y),
            w,
            h,
            ink,
        })
    }
}

/// The pages of a PDF, read. An error when the file is not a PDF it can open.
pub fn read_pages(bytes: &[u8]) -> Result<Vec<Page>, String> {
    let pdf = hayro_syntax::Pdf::new(bytes.to_vec())
        .map_err(|e| format!("not a PDF it can open ({e:?})"))?;
    let cache = InterpreterCache::new();
    let mut out = Vec::new();
    // LilyPond's glyphs, known by their names
    let named = Rc::new(lilypond::glyphs(&pdf));
    for page in pdf.pages().iter() {
        let (w, h) = page.render_dimensions();
        let t = Affine::new(page.initial_transform(true).as_coeffs());
        let mut ctx = Context::new(
            t,
            Rect::new(0.0, 0.0, w as f64, h as f64),
            &cache,
            pdf.xref(),
            InterpreterSettings::default(),
        );
        let mut dev = Collect {
            named: named.clone(),
            ..Collect::default()
        };
        interpret_page(page, &mut ctx, &mut dev);
        dev.off_the_page_dropped(w as f64, h as f64);
        out.push((dev, w as f64));
    }
    // what each font is, from all the pages
    let fonts = font_roles(out.iter().map(|(d, _)| d));
    let mut pages: Vec<Page> = out
        .into_iter()
        .map(|(mut dev, w)| {
            dev.sort_glyphs(&fonts);
            let outlines = std::mem::take(&mut dev.outlines);
            let mut pg = dev.into_page(w);
            // a music font drawn as bare outlines, on a page with none of a font: as pictures
            if pg.size == 0.0 && pg.pictures.is_empty() {
                pg.pictures
                    .extend(outlines.iter().filter_map(crate::pictures::of_outline));
            }
            // a music font drawn as pictures, one to a glyph
            crate::pictures::read(&mut pg);
            pg
        })
        .collect();
    // the kerning, from all the pages' text
    let kerned = std::sync::Arc::new(crate::words::kerned_pairs(&pages));
    for pg in &mut pages {
        pg.kerned = Some(kerned.clone());
    }
    Ok(pages)
}

/// A glyph as drawn, before its font is known for a music font or one of words.
struct Drawn {
    /// The font's key (`TYPE1` and the size, or `TYPE3`, where the PDF library has none).
    font: u128,
    code: u32,
    chars: Vec<char>,
    x0: f64,
    /// The right edge of its outline, and of its advance.
    x1_ink: f64,
    x1_adv: Option<f64>,
    y: f64,
    size: f64,
    run: usize,
    /// Its outline's height, in ems.
    high: f64,
    /// Its outline's signature (`signature`); 0 for a glyph with no outline to be had.
    sig: u64,
    /// For a glyph of a font known by its glyphs' names (LilyPond's): what it is, or None for
    /// one the reader has no use for.
    named: Option<Option<legacy::Sym>>,
}

/// An outline's signature: its on-curve points (each segment's end) to an eighth of a thousandth
/// of the em, sorted, hashed (FNV-1a). The same whichever way round and from whichever point a
/// contour is drawn, and whether its curves are quadratic or cubic.
fn signature(path: &BezPath) -> u64 {
    let mut pts: Vec<(i32, i32)> = path
        .elements()
        .iter()
        .filter_map(|e| match *e {
            PathEl::MoveTo(p)
            | PathEl::LineTo(p)
            | PathEl::QuadTo(_, p)
            | PathEl::CurveTo(_, _, p) => Some(p),
            PathEl::ClosePath => None,
        })
        .map(|p| ((p.x / 8.0).round() as i32, (p.y / 8.0).round() as i32))
        .collect();
    pts.sort();
    pts.dedup();
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for (x, y) in pts {
        for v in [x as u16, y as u16] {
            for b in v.to_le_bytes() {
                h = (h ^ b as u64).wrapping_mul(0x0100_0000_01b3);
            }
        }
    }
    h
}

/// The fonts whose glyphs are to be known by their outlines: a font of no part yet that sets
/// noteheads of a known shape (its codes renumbered, with no Unicode), a font whose codes name
/// other bytes than its outlines are (the Unicode of another font's encoding), and, beside such
/// a font, a companion most of whose glyphs are known.
fn shape_roles(by_font: &HashMap<u128, Vec<&Drawn>>, out: &mut Fonts) {
    let mut companions = Vec::new();
    for (&key, gs) in by_font {
        if key == TYPE3 {
            continue;
        }
        let coded = out.get(&key).copied();
        let (mut heads, mut known, mut differ) = (0, 0, 0);
        for g in gs {
            let Some((role, byte)) = shapes::by_shape(g.sig) else {
                continue;
            };
            known += 1;
            if matches!(role, Role::Main(_)) && legacy::is_head(byte) {
                heads += 1;
            }
            if let Some((_, d)) = coded {
                let uni = g.chars.first().map_or(0, |&c| c as u32);
                if d.byte(g.code, uni) != Some(byte) {
                    differ += 1;
                }
            }
        }
        let by_shape = match coded {
            None => heads >= 8 && known * 2 > gs.len(),
            Some(_) => known >= 8 && differ * 10 > known,
        };
        if by_shape {
            out.insert(key, (Role::Main(Family::Either), Decoding::Shape));
        } else if coded.is_none() && known >= 3 && known * 2 > gs.len() {
            companions.push(key);
        }
    }
    if out.values().any(|v| v.1 == Decoding::Shape) {
        for key in companions {
            out.insert(key, (Role::Special, Decoding::Shape));
        }
    }
}

/// What stands for the Unicode of a glyph that has none.
const NO_UNICODE: char = '\0';

/// The fonts with no key of their own: a Type 3 font's glyphs, and (plus four times the size) a
/// Type 1 font's.
const TYPE3: u128 = 1;
const TYPE1: u128 = 1 << 16;

/// Whether a font's key is a Type 1 font's size, not a font's own key.
fn is_type1(key: u128) -> bool {
    (TYPE1..2 * TYPE1).contains(&key)
}

/// A font's part and how its glyphs name their bytes.
type Fonts = HashMap<u128, (Role, Decoding)>;

/// The legacy music fonts among the fonts drawn with (`legacy.rs`): by name, or, for a font with
/// no name to go by, by what it sets.
fn font_roles<'d>(devs: impl Iterator<Item = &'d Collect> + Clone) -> Fonts {
    let mut by_font: HashMap<u128, Vec<&Drawn>> = HashMap::new();
    let mut names: HashMap<u128, &str> = HashMap::new();
    for d in devs {
        for g in d.drawn.iter().filter(|g| g.named.is_none()) {
            by_font.entry(g.font).or_default().push(g);
        }
        for (k, n) in &d.font_names {
            names.insert(*k, n);
        }
    }
    let mut out = Fonts::new();
    // a PDF with SMuFL noteheads is read as SMuFL
    let smufl = by_font.values().flatten().any(|g| {
        g.chars
            .first()
            .is_some_and(|&c| (0xE0A2..=0xE0A4).contains(&(c as u32)))
    });
    if smufl {
        return out;
    }
    // MuseScore's old font says what it is by its name, and its glyphs by their Unicode
    for (&key, gs) in &by_font {
        if let Some(f) = names.get(&key).and_then(|n| mscore::font_by_name(n)) {
            // (a PDF may hold the font with its glyphs drawn to another scale than its size
            // says: the black notehead's advance tells)
            let head = gs.iter().find_map(|g| {
                let adv = (g.x1_adv? - g.x0) / g.size;
                (g.chars.first() == Some(&mscore::HEAD) && g.size > 0.0).then_some(adv)
            });
            out.insert(key, (Role::MScore(f, mscore::em_of(head)), Decoding::Code));
        }
    }
    let heads_of = |gs: &[&Drawn], d: Decoding, is_head: fn(u8) -> bool| {
        gs.iter()
            .filter(|g| {
                let uni = g.chars.first().map_or(0, |&c| c as u32);
                d.byte(g.code, uni).is_some_and(is_head) && g.high < 0.5
            })
            .count()
    };
    let heads = |gs: &[&Drawn], d: Decoding| heads_of(gs, d, legacy::is_head);
    // the music fonts first: their decoding is the companions' too
    let mut doc_decoding = None;
    let mut doc_capella = false;
    for (&key, gs) in &by_font {
        if key == TYPE3 || out.contains_key(&key) {
            continue;
        }
        let named = names.get(&key).and_then(|n| legacy::role_by_name(n));
        let (mut best, mut n) = legacy::DECODINGS
            .iter()
            .map(|&d| (d, heads(gs, d)))
            .max_by_key(|&(_, n)| n)
            .unwrap();
        // a font with no name that sets more of the capella layout's noteheads than of Sonata's
        let capella = legacy::DECODINGS
            .iter()
            .map(|&d| (d, heads_of(gs, d, legacy::is_capella_head)))
            .max_by_key(|&(_, n)| n)
            .filter(|&(_, c)| named.is_none() && c > 2 * n);
        if let Some((d, c)) = capella {
            (best, n) = (d, c);
        }
        let family = match named {
            Some(Role::Main(f)) => Some(f),
            Some(_) => None,
            // no name: a font a good part of whose glyphs are noteheads. Doremi's where a tall
            // G is its treble clef
            None => (n >= 8 && n * 8 >= gs.len()).then(|| {
                let doremi = gs.iter().any(|g| {
                    let uni = g.chars.first().map_or(0, |&c| c as u32);
                    best.byte(g.code, uni) == Some(0x47) && g.high > 1.0
                });
                if capella.is_some() {
                    Family::Capella
                } else if doremi {
                    Family::Doremi
                } else {
                    Family::Either
                }
            }),
        };
        if let Some(f) = family {
            if n > 0 {
                out.insert(key, (Role::Main(f), best));
                doc_decoding = Some(best);
                doc_capella |= f == Family::Capella;
            }
        }
    }
    let Some(decoding) = doc_decoding else {
        shape_roles(&by_font, &mut out);
        return out;
    };
    for (&key, gs) in &by_font {
        if key == TYPE3 || out.contains_key(&key) {
            continue;
        }
        let private = gs
            .iter()
            .filter(|g| {
                g.chars
                    .first()
                    .is_some_and(|&c| (0xF000..=0xF0FF).contains(&(c as u32)))
            })
            .count();
        let d = if private * 2 > gs.len() {
            Decoding::Private
        } else {
            decoding
        };
        let role = match names.get(&key).and_then(|n| legacy::role_by_name(n)) {
            // (a second copy of the music font, with a few glyphs and no noteheads)
            Some(r) => Some(r),
            // no name, beside capella's font, which has no companions: that font at another
            // size (its small notes and clefs)
            None if private * 2 > gs.len() && doc_capella => Some(Role::Main(Family::Capella)),
            // no name: a symbol font beside the music font. Opus Special where it sets the dots
            // and small heads, else Opus Text (with Opus Special's dots, should it be that)
            None if private * 2 > gs.len() => {
                let byte = |g: &&Drawn| d.byte(g.code, g.chars.first().map_or(0, |&c| c as u32));
                let special = gs
                    .iter()
                    .filter(|g| {
                        matches!(byte(g), Some(0xAA | 0x99 | 0x7B | 0x7D))
                            || (matches!(byte(g), Some(0x65 | 0x66 | 0x45 | 0x46)) && g.high < 0.4)
                    })
                    .count();
                Some(if special * 2 > gs.len() {
                    Role::Special
                } else {
                    Role::Companion
                })
            }
            None => None,
        };
        if let Some(r) = role {
            out.insert(key, (r, d));
        }
    }
    shape_roles(&by_font, &mut out);
    out
}

#[derive(Default)]
struct Collect {
    /// The glyphs known by their names (`lilypond::glyphs`), by the interpreter's key.
    named: Rc<HashMap<u128, Option<legacy::Sym>>>,
    drawn: Vec<Drawn>,
    font_names: HashMap<u128, String>,
    glyphs: Vec<Glyph>,
    letters: Vec<Letter>,
    hlines: Vec<HLine>,
    vlines: Vec<VLine>,
    /// Upright lines drawn as thin filled rectangles (`upright_fill`).
    vfills: Vec<VLine>,
    /// The clip paths in force, innermost last, each as the box it and those outside it leave.
    clips: Vec<Rect>,
    polys: Vec<Vec<(f64, f64)>>,
    curves: Vec<Curve>,
    diagonals: Vec<(f64, f64, f64, f64, f64)>,
    dashed: Vec<HLine>,
    runs: usize,
    /// The closed straight-edged path stroked last, if nothing was drawn since (`Outlined`).
    outlined: Option<Outlined>,
    pictures: Vec<Picture>,
    /// The small filled curved shapes, as drawn: on a page with no music font, a program that
    /// prints its font's glyphs as bare outlines draws each so (`pictures::of_outline`).
    outlines: Vec<BezPath>,
}

/// A closed straight-edged path as stroked: its box, the stroke's width, and how many level,
/// upright and other lines there were before its own. LilyPond draws a stem or a beam so and
/// then fills the same path (a box with rounded corners): the lines are then no lines of their
/// own but the shape's edge.
#[derive(Clone, Copy)]
struct Outlined {
    bbox: Rect,
    w: f64,
    lines: (usize, usize, usize),
}

/// A shape grown by `by` on every side: each corner moved out from the middle.
fn grown(pts: &mut [(f64, f64)], by: f64) {
    let n = pts.len().max(1) as f64;
    let cx = pts.iter().map(|q| q.0).sum::<f64>() / n;
    let cy = pts.iter().map(|q| q.1).sum::<f64>() / n;
    for q in pts.iter_mut() {
        q.0 += if q.0 < cx { -by } else { by };
        q.1 += if q.1 < cy { -by } else { by };
    }
}

/// A straight-edged shape cut to a box (a clip path's): what of it is drawn. Some programs draw
/// the short beam of a dotted pair as a whole beam, clipped to its end.
fn clipped(pts: Vec<(f64, f64)>, clip: &Rect) -> Vec<(f64, f64)> {
    let inside = pts
        .iter()
        .all(|&(x, y)| clip.x0 <= x && x <= clip.x1 && clip.y0 <= y && y <= clip.y1);
    if inside {
        return pts;
    }
    // one side of the box at a time: keep what lies within, cut the edges that cross
    let cut = |pts: Vec<(f64, f64)>, within: &dyn Fn((f64, f64)) -> f64| {
        let mut out = Vec::new();
        for (k, &a) in pts.iter().enumerate() {
            let b = pts[(k + 1) % pts.len()];
            let (da, db) = (within(a), within(b));
            if da >= 0.0 {
                out.push(a);
            }
            if (da >= 0.0) != (db >= 0.0) {
                let t = da / (da - db);
                out.push((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)));
            }
        }
        out
    };
    let pts = cut(pts, &|q| q.0 - clip.x0);
    let pts = cut(pts, &|q| clip.x1 - q.0);
    let pts = cut(pts, &|q| q.1 - clip.y0);
    cut(pts, &|q| clip.y1 - q.1)
}

/// A filled shape that is an upright line: a rectangle with level and upright sides, at least
/// four times as tall as wide. Some programs fill their stems and barlines so, where most stroke
/// them; a beam is never upright.
fn upright_fill(pts: &[(f64, f64)]) -> Option<VLine> {
    if !(4..=5).contains(&pts.len()) {
        return None;
    }
    let (mut x0, mut x1, mut y0, mut y1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN);
    for &(x, y) in pts {
        (x0, x1, y0, y1) = (x0.min(x), x1.max(x), y0.min(y), y1.max(y));
    }
    let (w, h) = (x1 - x0, y1 - y0);
    let e = 0.02 * w.max(0.5);
    let cornered = pts.iter().all(|&(x, y)| {
        ((x - x0).abs() < e || (x - x1).abs() < e) && ((y - y0).abs() < e || (y - y1).abs() < e)
    });
    (cornered && w > 0.0 && h >= 4.0 * w).then_some(VLine {
        x: (x0 + x1) / 2.0,
        y0,
        y1,
        w,
    })
}

/// The stroked lines without those that only outline a filled upright line (a stem filled and
/// then stroked with a hairline is one stem, as wide as its fill), and the filled ones.
fn with_upright_fills(stroked: Vec<VLine>, fills: Vec<VLine>) -> Vec<VLine> {
    if fills.is_empty() {
        return stroked;
    }
    let mut out: Vec<VLine> = stroked
        .into_iter()
        .filter(|v| {
            !fills.iter().any(|f| {
                v.w < f.w
                    && (v.x - f.x).abs() < f.w / 2.0 + 0.1
                    && v.y0 > f.y0 - 0.5
                    && v.y1 < f.y1 + 0.5
            })
        })
        .collect();
    out.extend(fills);
    out
}

/// How much a transform scales lengths (its area scale's square root).
fn scale_of(t: &Affine) -> f64 {
    t.determinant().abs().sqrt()
}

impl Collect {
    /// A filled straight-edged shape of box `b`: an upright line or a shape, with the line
    /// stroked round it just before (`outlined`, the same path) taken into it.
    fn filled(&mut self, mut pts: Vec<(f64, f64)>, b: Rect, outlined: Option<Outlined>) {
        let edge = outlined.filter(|o| {
            (o.bbox.x0 - b.x0).abs() < 0.05
                && (o.bbox.x1 - b.x1).abs() < 0.05
                && (o.bbox.y0 - b.y0).abs() < 0.05
                && (o.bbox.y1 - b.y1).abs() < 0.05
        });
        let mut unstroke = |o: &Outlined| {
            self.hlines.truncate(o.lines.0);
            self.vlines.truncate(o.lines.1);
            self.diagonals.truncate(o.lines.2);
        };
        match (upright_fill(&pts), edge) {
            // a stem thinner than the line round it: one line, as wide as both
            (Some(v), Some(o)) if o.w >= v.w => {
                unstroke(&o);
                self.vfills.push(VLine {
                    x: v.x,
                    y0: v.y0 - o.w / 2.0,
                    y1: v.y1 + o.w / 2.0,
                    w: v.w + o.w,
                });
            }
            (Some(v), _) => self.vfills.push(v),
            // a beam with a line round it (not a level line drawn as a thin box)
            (None, Some(o)) if b.height() > 2.0 * o.w || b.height() > b.width() => {
                unstroke(&o);
                grown(&mut pts, o.w / 2.0);
                self.polys.push(pts);
            }
            (None, _) => self.polys.push(pts),
        }
    }

    /// Every glyph drawn, as a music glyph or as letters, by its font.
    fn sort_glyphs(&mut self, fonts: &Fonts) {
        let mut dots: Vec<Glyph> = Vec::new();
        let lily = self.drawn.iter().any(|g| g.named.is_some());
        let lily_heads = if lily { self.named_head_size() } else { 0.0 };
        for g in std::mem::take(&mut self.drawn) {
            if let Some(named) = g.named {
                let Some(sym) = named else { continue };
                let glyph = Glyph {
                    code: sym.code,
                    x0: g.x0,
                    x1: g.x1_ink,
                    y: g.y,
                    size: g.size,
                };
                match sym.code {
                    lilypond::DOT => dots.push(glyph),
                    c if (lilypond::DIGIT..lilypond::DIGIT + 10).contains(&c) => {
                        let (code, rise) = lilypond::digit(c - lilypond::DIGIT, g.size, lily_heads);
                        self.glyphs.push(Glyph {
                            code,
                            y: g.y - rise * g.size,
                            ..glyph
                        });
                    }
                    _ => self.glyphs.push(glyph),
                }
                continue;
            }
            let Some(&c) = g.chars.first() else { continue };
            let Some(&(role, decoding)) = fonts.get(&g.font) else {
                if c == NO_UNICODE {
                    continue;
                }
                if smufl::is_music(c as u32) {
                    self.glyphs.push(Glyph {
                        code: c as u32,
                        x0: g.x0,
                        x1: g.x1_ink,
                        y: g.y,
                        size: g.size,
                    });
                } else {
                    let x1 = g.x1_adv.unwrap_or(g.x0 + 0.5 * g.size);
                    for ch in g.chars {
                        self.letters.push(Letter {
                            ch,
                            x0: g.x0,
                            x1,
                            base: g.y,
                            size: g.size,
                            run: g.run,
                        });
                    }
                }
                continue;
            };
            // a legacy music font's glyph, as SMuFL's; what the reader has no use for is dropped
            let named = match (role, decoding) {
                (Role::MScore(..), _) => Some((role, 0)),
                (_, Decoding::Shape) => shapes::by_shape(g.sig),
                _ => decoding.byte(g.code, c as u32).map(|b| (role, b)),
            };
            let Some((role, byte)) = named else {
                continue;
            };
            let tall = g.high > 0.4;
            let sym = match role {
                Role::MScore(f, _) => mscore::glyph(f, c as u32),
                Role::Main(f) if is_type1(g.font) => legacy::merged_glyph(f, byte, g.high),
                Role::Main(f) => legacy::main_glyph(f, byte, tall),
                Role::Special => legacy::special_glyph(byte, tall),
                Role::Marks => legacy::marks_glyph(byte, tall),
                Role::Companion => legacy::companion_glyph(byte, g.high),
                Role::Unread => None,
            };
            let Some(sym) = sym else { continue };
            let em = match role {
                Role::MScore(_, em) => em * g.size,
                _ => g.size,
            };
            let glyph = Glyph {
                code: sym.code,
                x0: g.x0 + sym.shift * em,
                x1: g.x1_ink,
                y: g.y - sym.rise * em,
                size: em * sym.scale,
            };
            if sym.code == legacy::DOT_BY_PLACE || sym.code == lilypond::DOT {
                dots.push(glyph);
            } else {
                self.glyphs.push(glyph);
            }
        }
        // a dot is an augmentation dot just right of a notehead, a rest or another such dot, at
        // its height or half a space off it; else a staccato dot
        dots.sort_by(|a, b| a.x0.total_cmp(&b.x0));
        let mut apart: Vec<Glyph> = Vec::new();
        for mut d in dots {
            let sp = d.size / 4.0;
            let beside = self.glyphs.iter().any(|g| {
                (smufl::head(g.code).is_some()
                    || smufl::rest(g.code).is_some()
                    || g.code == smufl::DOT)
                    && d.x0 > g.x1 - 0.2 * sp
                    && d.x0 < g.x1 + 1.6 * sp
                    && (d.y - g.y).abs() < 0.8 * sp
            });
            d.code = match (beside, d.code) {
                (true, _) => smufl::DOT,
                // (LilyPond's staccato dot is another glyph)
                (false, lilypond::DOT) => {
                    apart.push(d);
                    continue;
                }
                (false, _) => 0xE4A2,
            };
            self.glyphs.push(d);
        }
        // LilyPond's dot beside no note: a repeat sign's where it is one of a pair, one over the
        // other a space apart; else a note's dot all the same, set further off
        for d in &apart {
            let pair = apart
                .iter()
                .any(|e| lilypond::repeat_pair((d.x0, d.y), (e.x0, e.y), d.size / 4.0));
            self.glyphs.push(Glyph {
                code: if pair { 0xE044 } else { smufl::DOT },
                ..*d
            });
        }
        if lily {
            self.clefs_with_8();
            self.metronome_notes();
        }
    }

    /// LilyPond sets a metronome mark's note with the staff's own notehead (and a stem, a flag
    /// and a dot like any note's): a notehead with `=` right after it, level with it, is made
    /// the note SMuFL has for metronome marks, so that it is no note of the staff under it.
    fn metronome_notes(&mut self) {
        for k in 0..self.glyphs.len() {
            let g = self.glyphs[k];
            let Some(len) = smufl::head(g.code) else {
                continue;
            };
            let sp = g.size / 4.0;
            let marked = self.letters.iter().any(|l| {
                l.ch == '=' && l.x0 > g.x1 && l.x0 - g.x1 < 4.0 * sp && (l.base - g.y).abs() < sp
            });
            if !marked {
                continue;
            }
            // its flag: at the stem's end, up to four spaces over the head and just right of it
            let flag = self.glyphs.iter().position(|f| {
                smufl::flag(f.code).is_some()
                    && (f.x0 - g.x1).abs() < 0.5 * sp
                    && g.y - f.y > 2.0 * sp
                    && g.y - f.y < 4.5 * sp
            });
            self.glyphs[k].code = match (len.cmp(&crate::frac::Q::ONE), flag) {
                (std::cmp::Ordering::Greater, _) => 0xE1D3,
                (_, None) => 0xE1D5,
                (_, Some(f)) if smufl::flag(self.glyphs[f].code) == Some(1) => 0xE1D7,
                (_, Some(_)) => 0xE1D9,
            };
            if let Some(f) = flag {
                self.glyphs[f].code = 0;
            }
        }
        self.glyphs.retain(|g| g.code != 0);
    }

    /// The commonest size of the noteheads known by name; 0 with none.
    fn named_head_size(&self) -> f64 {
        let mut counts: HashMap<i64, usize> = HashMap::new();
        for g in &self.drawn {
            if let Some(Some(sym)) = g.named {
                if smufl::head(sym.code).is_some() {
                    *counts.entry((g.size * 4.0).round() as i64).or_default() += 1;
                }
            }
        }
        counts
            .into_iter()
            .max_by_key(|&(s, n)| (n, s))
            .map_or(0.0, |(s, _)| s as f64 / 4.0)
    }

    /// LilyPond sets the 8 of a clef an octave off (a tenor's treble clef) as a letter of the
    /// text font, centred under or over the clef: the clef is made the one SMuFL has for it and
    /// the letter taken away.
    fn clefs_with_8(&mut self) {
        for g in self.glyphs.iter_mut() {
            if smufl::clef(g.code).is_none() {
                continue;
            }
            let sp = g.size / 4.0;
            let mid = (g.x0 + g.x1) / 2.0;
            let found = self.letters.iter().position(|l| {
                l.ch == '8'
                    && l.size < g.size
                    && ((l.x0 + l.x1) / 2.0 - mid).abs() < 0.8 * sp
                    && lilypond::clef_with_8(g.code, (l.base - g.y) / sp).is_some()
            });
            if let Some(k) = found {
                let l = self.letters.remove(k);
                g.code = lilypond::clef_with_8(g.code, (l.base - g.y) / sp).unwrap_or(g.code);
            }
        }
    }

    /// What is drawn wholly off the page is not on it: a program may leave a neighbouring
    /// system's staves and notes past the page's edge (cut off by the page's box), where their
    /// lines would stand between this page's own.
    fn off_the_page_dropped(&mut self, width: f64, height: f64) {
        let on =
            |x0: f64, x1: f64, y0: f64, y1: f64| x1 > 0.0 && x0 < width && y1 > 0.0 && y0 < height;
        self.drawn
            .retain(|g| on(g.x0, g.x1_ink.max(g.x0), g.y, g.y));
        self.hlines.retain(|l| on(l.x0, l.x1, l.y, l.y));
        self.vlines.retain(|v| on(v.x, v.x, v.y0, v.y1));
        self.vfills.retain(|v| on(v.x, v.x, v.y0, v.y1));
        self.polys
            .retain(|p| p.iter().any(|&(x, y)| on(x, x, y, y)));
        self.curves.retain(|c| on(c.x0, c.x1, c.y0, c.y1));
        self.diagonals
            .retain(|d| on(d.0, d.2, d.1.min(d.3), d.1.max(d.3)));
    }

    fn into_page(self, width: f64) -> Page {
        let mut counts: HashMap<i64, usize> = HashMap::new();
        for g in self.glyphs.iter().filter(|g| smufl::head(g.code).is_some()) {
            *counts.entry(g.size.round() as i64).or_default() += 1;
        }
        let size = counts
            .into_iter()
            .max_by_key(|&(s, n)| (n, s))
            .map(|(s, _)| s as f64)
            .unwrap_or(0.0);
        // some programs draw a line twice (stroke and outline): once is enough
        let r = |v: f64| (v * 10.0).round() as i64;
        let all_vlines = with_upright_fills(self.vlines, self.vfills);
        let vset: BTreeSet<(i64, i64, i64, i64)> = all_vlines
            .iter()
            .map(|v| (r(v.x), r(v.y0), r(v.y1), r(v.w)))
            .collect();
        // and some draw a barline in pieces, a staff or a gap at a time: pieces that touch, on one
        // x and of one width, are one line
        let mut vlines: Vec<VLine> = Vec::new();
        for (x, y0, y1, w) in vset {
            let v = VLine {
                x: x as f64 / 10.0,
                y0: y0 as f64 / 10.0,
                y1: y1 as f64 / 10.0,
                w: w as f64 / 10.0,
            };
            let joins = vlines.iter_mut().rev().find(|p| {
                (p.x - v.x).abs() < 0.05
                    && (p.w - v.w).abs() < 0.05
                    && v.y0 <= p.y1 + 0.5
                    && v.y0 >= p.y0
            });
            match joins {
                Some(p) => p.y1 = p.y1.max(v.y1),
                None => vlines.push(v),
            }
        }
        // (lengths in points, for a page whose noteheads are their usual size: scaled with them)
        let frames = frames_of(&vlines, if size > 0.0 { size / 20.0 } else { 1.0 });
        Page {
            frames,
            width,
            glyphs: self.glyphs,
            letters: self.letters,
            hlines: self.hlines,
            vlines,
            polys: self.polys,
            curves: self.curves,
            diagonals: self.diagonals,
            dashed: self.dashed,
            kerned: None,
            size,
            pictures: self.pictures,
        }
    }
}

/// Guitar chord frames: four or more thin upright lines of one length, side by side at an even
/// spacing (the strings). `u` is the page's scale: a point where its noteheads are 20 wide.
fn frames_of(vlines: &[VLine], u: f64) -> Vec<(f64, f64, f64, f64)> {
    let mut by_span: HashMap<(i64, i64), Vec<&VLine>> = HashMap::new();
    for v in vlines
        .iter()
        .filter(|v| v.w < 0.6 * u && v.y1 - v.y0 > 4.0 * u)
    {
        by_span
            .entry(((v.y0 * 2.0).round() as i64, (v.y1 * 2.0).round() as i64))
            .or_default()
            .push(v);
    }
    let mut out = Vec::new();
    for vs in by_span.values_mut() {
        vs.sort_by(|a, b| a.x.total_cmp(&b.x));
        let mut run: Vec<&VLine> = Vec::new();
        let mut flush = |run: &mut Vec<&VLine>| {
            if run.len() >= 4 {
                out.push((
                    run[0].x - u,
                    run[0].y0 - u,
                    run.last().unwrap().x + u,
                    run[0].y1 + u,
                ));
            }
            run.clear();
        };
        for v in vs.iter() {
            let even = match run.as_slice() {
                [.., a, b] => ((v.x - b.x) - (b.x - a.x)).abs() < 0.5 * u,
                [b] => v.x - b.x < 8.0 * u,
                [] => true,
            };
            if !even
                || run
                    .last()
                    .is_some_and(|b| v.x - b.x > 8.0 * u || v.x - b.x < u)
            {
                flush(&mut run);
            }
            run.push(v);
        }
        flush(&mut run);
    }
    out
}

impl Page {
    /// The width that parts a stem from a barline: a barline is drawn at least this wide, a stem
    /// thinner. A thirteenth of a staff space, or more where the page's stems (its commonest
    /// upright lines of a stem's length) are drawn that wide or wider.
    pub fn barline_width(&self, sp: f64) -> f64 {
        (0.13 * sp).max(self.stem_width(sp) + 0.05)
    }

    /// The width of the page's commonest upright line of a stem's length; 0 with none.
    pub fn stem_width(&self, sp: f64) -> f64 {
        // (as long as a stem: a barline drawn staff by staff is as tall as the staff)
        let usual = self.commonest_width(|len| len > 2.0 * sp && len < 3.9 * sp);
        if usual > 0.0 {
            return usual;
        }
        // a page of chords alone has no stem so short: its stems are the lines longer than a
        // staff is tall, and shorter than two staves
        self.commonest_width(|len| len > 4.15 * sp && len < 8.0 * sp)
    }

    /// The commonest width of the page's upright lines whose length `is_stem` says yes to.
    fn commonest_width(&self, is_stem: impl Fn(f64) -> bool) -> f64 {
        let mut counts: BTreeMap<i64, usize> = BTreeMap::new();
        for v in self.vlines.iter().filter(|v| is_stem(v.y1 - v.y0)) {
            *counts.entry((v.w * 100.0).round() as i64).or_default() += 1;
        }
        counts
            .iter()
            .max_by_key(|(w, n)| (**n, -**w))
            .map_or(0.0, |(w, _)| *w as f64 / 100.0)
    }

    /// Whether a point stands in a guitar chord frame.
    pub fn in_frame(&self, x: f64, y: f64) -> bool {
        self.frames
            .iter()
            .any(|f| f.0 <= x && x <= f.2 && f.1 <= y && y <= f.3)
    }
}

impl<'a> Device<'a> for Collect {
    fn draw_path(&mut self, path: &BezPath, props: DrawProps<'a>, mode: &DrawMode) {
        let p = props.transform * path.clone();
        let outlined = self.outlined.take();
        match mode {
            DrawMode::Stroke(sp) => {
                let w = sp.line_width as f64 * scale_of(&props.transform);
                let before = (self.hlines.len(), self.vlines.len(), self.diagonals.len());
                let straight = !p
                    .elements()
                    .iter()
                    .any(|e| matches!(e, PathEl::CurveTo(..) | PathEl::QuadTo(..)));
                if straight && matches!(p.elements().last(), Some(PathEl::ClosePath)) {
                    self.outlined = Some(Outlined {
                        bbox: p.bounding_box(),
                        w,
                        lines: before,
                    });
                }
                let mut last = Point::ZERO;
                for el in p.elements() {
                    match *el {
                        PathEl::MoveTo(a) => last = a,
                        PathEl::LineTo(b) => {
                            let a = last;
                            if (a.y - b.y).abs() < 0.5 {
                                self.hlines.push(HLine {
                                    x0: a.x.min(b.x),
                                    x1: a.x.max(b.x),
                                    y: a.y,
                                    w,
                                });
                                if !sp.dash_array.is_empty() {
                                    self.dashed.extend(self.hlines.last());
                                }
                            } else if (a.x - b.x).abs() < 0.5 {
                                self.vlines.push(VLine {
                                    x: a.x,
                                    y0: a.y.min(b.y),
                                    y1: a.y.max(b.y),
                                    w,
                                });
                            } else {
                                let (p, q) = if a.x <= b.x { (a, b) } else { (b, a) };
                                self.diagonals.push((p.x, p.y, q.x, q.y, w));
                            }
                            last = b;
                        }
                        PathEl::QuadTo(_, b) | PathEl::CurveTo(_, _, b) => last = b,
                        PathEl::ClosePath => {}
                    }
                }
            }
            DrawMode::Fill(_) | DrawMode::FillAndStroke(..) => {
                let els = p.elements();
                if els
                    .iter()
                    .any(|e| matches!(e, PathEl::CurveTo(..) | PathEl::QuadTo(..)))
                {
                    let b = p.bounding_box();
                    if b.width() < 40.0 && b.height() < 40.0 {
                        self.outlines.push(p.clone());
                    }
                    self.curves.push(Curve::of(&p));
                    return;
                }
                // a glyph's many-sided outline, small (a sharp drawn in straight lines)
                let b = p.bounding_box();
                if els.len() > 8 && b.width() < 40.0 && b.height() < 40.0 {
                    self.outlines.push(p.clone());
                }
                // each closed part its own shape: some programs fill several beams as one path
                let parts: Vec<&[PathEl]> =
                    match els.iter().skip(1).any(|e| matches!(e, PathEl::MoveTo(_))) {
                        false => vec![els],
                        true => {
                            let mut parts = Vec::new();
                            let mut from = 0;
                            for (i, e) in els.iter().enumerate().skip(1) {
                                if matches!(e, PathEl::MoveTo(_)) {
                                    parts.push(&els[from..i]);
                                    from = i;
                                }
                            }
                            parts.push(&els[from..]);
                            parts
                        }
                    };
                let whole = parts.len() == 1;
                let mut outlined = outlined;
                for part in parts {
                    let lines = part
                        .iter()
                        .filter(|e| matches!(e, PathEl::LineTo(_)))
                        .count();
                    if lines < 3 {
                        continue;
                    }
                    let mut pts = Vec::new();
                    for el in part {
                        match *el {
                            PathEl::MoveTo(a) if pts.is_empty() => pts.push((a.x, a.y)),
                            PathEl::LineTo(b) => pts.push((b.x, b.y)),
                            _ => {}
                        }
                    }
                    if let Some(clip) = self.clips.last() {
                        pts = clipped(pts, clip);
                        if pts.len() < 3 {
                            continue;
                        }
                    }
                    let b = match whole {
                        true => p.bounding_box(),
                        false => BezPath::from_vec(part.to_vec()).bounding_box(),
                    };
                    self.filled(pts, b, outlined.take());
                }
            }
            DrawMode::Invisible => {}
        }
    }

    // hayro hands a rectangular path over as a rectangle (a horizontal beam, often): it is the
    // path it stands for
    fn draw_rect(&mut self, r: &Rect, props: DrawProps<'a>, mode: &DrawMode) {
        self.draw_path(&r.to_path(0.1), props, mode);
    }

    fn push_clip_path(&mut self, clip: &ClipPath) {
        let b = clip.path.bounding_box();
        let b = self.clips.last().map_or(b, |outer| outer.intersect(b));
        self.clips.push(b);
    }
    fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}

    fn draw_glyph_run(&mut self, run: &GlyphRun<'_, 'a>, props: DrawProps<'a>, _: &DrawMode) {
        self.runs += 1;
        for g in run.glyphs() {
            let t = props.transform * g.transform();
            let chars: Vec<char> = match g.as_unicode() {
                Some(BfString::Char(c)) => vec![c],
                Some(BfString::String(s)) => s.chars().collect(),
                // (no Unicode to be had: a music font's glyph may yet be known by its outline)
                None => vec![NO_UNICODE],
            };
            if chars.is_empty() {
                continue;
            }
            let o = t * Point::ZERO;
            // the glyph space is a thousandth of the font size
            let size = scale_of(&t) * 1000.0;
            let mut sig = 0;
            let mut named = None;
            let (font, advance, ink) = match &**g {
                PdfGlyph::Outline(og) => {
                    if !self.named.is_empty() {
                        named = self.named.get(&og.identifier().cache_key()).copied();
                    }
                    // (a Type 1 font has no key to be had: its glyphs of one size stand for one
                    // font, which a music font's are)
                    let font = og
                        .font_data()
                        .map_or(TYPE1 + (size * 4.0).round() as u128, |d| {
                            self.font_names
                                .entry(d.cache_key)
                                .or_insert_with(|| d.postscript_name.unwrap_or_default());
                            d.cache_key
                        });
                    let outline = og.outline();
                    sig = signature(&outline);
                    (
                        font,
                        og.advance_width().map(f64::from),
                        Some(outline.bounding_box()),
                    )
                }
                PdfGlyph::Type3(t3) => (TYPE3, t3.advance_width().map(f64::from), None),
            };
            let x1_adv = advance.map(|a| (t * Point::new(a, 0.0)).x);
            let x1_ink = match ink {
                Some(b) => (t * Point::new(b.x1, 0.0)).x,
                None => x1_adv.unwrap_or(o.x),
            };
            self.drawn.push(Drawn {
                font,
                code: g.char_code(),
                chars,
                x0: o.x,
                x1_ink,
                x1_adv,
                y: o.y,
                size,
                run: self.runs,
                high: ink.map_or(0.0, |b| b.height() / 1000.0),
                sig,
                named,
            });
        }
    }

    fn draw_image(&mut self, image: Image<'a, '_>, props: ImageDrawProps<'a>) {
        let t = props.transform;
        let mut got = None;
        match image {
            // a mask painted in the fill colour: inked where it lets the paint through
            Image::Stencil(s) => s.with_stencil(
                |m, _| {
                    let (w, h) = (m.width as usize, m.height as usize);
                    got = Picture::of(t, w, h, |i| m.data.get(i).is_some_and(|&v| v > 127));
                },
                None,
            ),
            // a picture: inked where it is dark, and not see-through
            Image::Raster(r) => r.with_rgba(
                |img, alpha| {
                    let (w, h) = (img.width() as usize, img.height() as usize);
                    let opaque = |i: usize| match &alpha {
                        Some(a) => a.data.get(i).is_some_and(|&v| v > 127),
                        None => true,
                    };
                    let dark = |i: usize| match &img {
                        ImageData::Rgb(d) => d
                            .data
                            .get(3 * i..3 * i + 3)
                            .is_some_and(|p| (p[0] as u32 + p[1] as u32 + p[2] as u32) < 3 * 128),
                        ImageData::Luma(d) => d.data.get(i).is_some_and(|&v| v < 128),
                    };
                    got = Picture::of(t, w, h, |i| opaque(i) && dark(i));
                },
                None,
            ),
        }
        self.pictures.extend(got);
    }
    fn pop_clip(&mut self) {
        self.clips.pop();
    }
    fn pop_transparency_group(&mut self) {}
}

/// Whether five rows of long lines start and end together, as a staff's lines do: the lines
/// drawn after held syllables under a voice's staff, one a verse and evenly set, are long too,
/// but each ends where its syllable does (and with the staff's top line under them made five).
fn same_ends(run: &[(f64, Vec<(f64, f64)>)], gap: f64) -> bool {
    let ends = |xs: &Vec<(f64, f64)>| {
        (
            xs.iter().map(|x| x.0).fold(f64::MAX, f64::min),
            xs.iter().map(|x| x.1).fold(f64::MIN, f64::max),
        )
    };
    let (l0, r0) = ends(&run[0].1);
    run.iter().all(|(_, xs)| {
        let (l, r) = ends(xs);
        (l - l0).abs() < gap && (r - r0).abs() < gap
    })
}

impl Page {
    /// A staff's ends with the short pieces of its lines that go on from them: a program may
    /// draw a staff's last bar (or its first) as lines of its own, too short to be found as a
    /// staff's. Taken only where all five lines go on from the same place.
    fn with_short_pieces(&self, ys: &[f64; 5], left: f64, right: f64, gap: f64) -> (f64, f64) {
        let pieces: Vec<Vec<&HLine>> = ys
            .iter()
            .map(|&y| {
                self.hlines
                    .iter()
                    .filter(|l| (l.y - y).abs() < 0.15 * gap && l.x1 - l.x0 > gap)
                    .collect()
            })
            .collect();
        let (mut left, mut right) = (left, right);
        loop {
            // each line's piece that starts at the end and goes on past it
            let on: Vec<f64> = pieces
                .iter()
                .filter_map(|row| {
                    row.iter()
                        .filter(|l| (l.x0 - right).abs() < 0.5 * gap && l.x1 > right + 0.5 * gap)
                        .map(|l| l.x1)
                        .reduce(f64::max)
                })
                .collect();
            if on.len() < 5 {
                break;
            }
            right = on.into_iter().fold(f64::MAX, f64::min);
        }
        loop {
            let on: Vec<f64> = pieces
                .iter()
                .filter_map(|row| {
                    row.iter()
                        .filter(|l| (l.x1 - left).abs() < 0.5 * gap && l.x0 < left - 0.5 * gap)
                        .map(|l| l.x0)
                        .reduce(f64::min)
                })
                .collect();
            if on.len() < 5 {
                break;
            }
            left = on.into_iter().fold(f64::MIN, f64::max);
        }
        (left, right)
    }

    /// Five-line staves, top to bottom.
    pub fn staves(&self) -> Vec<Staff> {
        let mut rows: Vec<(f64, Vec<(f64, f64)>)> = Vec::new();
        let mut long: Vec<&HLine> = self
            .hlines
            .iter()
            .filter(|l| l.x1 - l.x0 > 0.07 * self.width)
            .collect();
        long.sort_by(|a, b| a.y.total_cmp(&b.y));
        for l in long {
            let y = (l.y * 10.0).round() / 10.0;
            // one height for a line drawn in pieces
            match rows.last_mut() {
                Some((ry, xs)) if y - *ry < 0.0002 * self.width => xs.push((l.x0, l.x1)),
                _ => rows.push((y, vec![(l.x0, l.x1)])),
            }
        }
        let mut out = Vec::new();
        let mut i = 0;
        while i + 5 <= rows.len() {
            let run = &rows[i..i + 5];
            let gaps: Vec<f64> = (0..4).map(|j| run[j + 1].0 - run[j].0).collect();
            let lo = gaps.iter().cloned().fold(f64::MAX, f64::min);
            let hi = gaps.iter().cloned().fold(f64::MIN, f64::max);
            if lo > 0.0 && lo < 0.03 * self.width && hi - lo < 0.1 * lo && same_ends(run, lo) {
                let xs = run.iter().flat_map(|(_, xs)| xs.iter());
                let left = xs.clone().map(|x| x.0).fold(f64::MAX, f64::min);
                let right = xs.map(|x| x.1).fold(f64::MIN, f64::max);
                let ys = [run[0].0, run[1].0, run[2].0, run[3].0, run[4].0];
                let (left, right) = self.with_short_pieces(&ys, left, right, lo);
                // the top line's pieces, short ones too (a line drawn bar by bar has short bars)
                let mut top: Vec<(f64, f64)> = self
                    .hlines
                    .iter()
                    .filter(|l| (l.y - run[0].0).abs() < 0.15 * lo && l.x1 - l.x0 > 1.0 * lo)
                    .map(|l| (l.x0, l.x1))
                    .collect();
                top.sort_by(|a, b| a.0.total_cmp(&b.0));
                let mut breaks = Vec::new();
                let mut reach = f64::MIN;
                for (x0, x1) in top {
                    if reach > f64::MIN && x0 - reach > 2.0 * lo {
                        breaks.push((reach, x0));
                    }
                    reach = reach.max(x1);
                }
                out.push(Staff {
                    lines: [run[0].0, run[1].0, run[2].0, run[3].0, run[4].0],
                    left,
                    right,
                    breaks,
                });
                i += 5;
            } else {
                i += 1;
            }
        }
        out
    }
}

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

    #[test]
    fn a_curve_keeps_the_heights_of_its_two_ends() {
        // a crescent that arches upwards, its left end at 20 and its right at 18
        let mut p = BezPath::new();
        p.move_to((10.0, 20.0));
        p.curve_to((14.0, 16.0), (26.0, 14.0), (30.0, 18.0));
        p.curve_to((26.0, 15.0), (14.0, 17.0), (10.0, 20.0));
        p.close_path();
        let c = Curve::of(&p);
        assert!((c.x0 - 10.0).abs() < 1e-9 && (c.x1 - 30.0).abs() < 1e-9);
        assert_eq!((c.ya, c.yb), (20.0, 18.0));
        // its ends stand lower than the middle of its box, and 2 apart
        assert!(c.over());
        assert!(!c.level(1.0));
        // one that hangs from level ends
        let mut p = BezPath::new();
        p.move_to((10.0, 20.0));
        p.curve_to((14.0, 24.0), (26.0, 24.0), (30.0, 20.0));
        p.curve_to((26.0, 25.0), (14.0, 25.0), (10.0, 20.0));
        let c = Curve::of(&p);
        assert_eq!((c.ya, c.yb), (20.0, 20.0));
        assert!(!c.over());
        assert!(c.level(1.0));
    }

    #[test]
    fn lines_after_held_syllables_over_a_staff_are_no_staff_with_its_top_line() {
        // four verses' lines after a held syllable, a staff's space apart, end where the
        // syllables do; the piano's staff under them starts a space under the last
        let line = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.5 };
        let mut hlines = vec![
            line(300.0, 380.0, 100.0),
            line(310.0, 370.0, 109.0),
            line(305.0, 390.0, 118.0),
            line(300.0, 350.0, 127.0),
        ];
        for k in 0..5 {
            hlines.push(line(70.0, 500.0, 136.0 + 9.0 * k as f64));
        }
        let pg = Page {
            width: 600.0,
            hlines,
            ..Page::default()
        };
        let staves = pg.staves();
        assert_eq!(staves.len(), 1);
        assert_eq!(staves[0].top(), 136.0);
        assert_eq!(staves[0].bottom(), 172.0);
    }

    #[test]
    fn a_staff_s_last_bar_drawn_as_short_lines_of_its_own_is_the_staff_s() {
        // each line from 70 to 500, and on from 500 to 530 (a bar too short to be found alone)
        let mut hlines = Vec::new();
        for k in 0..5 {
            let y = 100.0 + 5.0 * k as f64;
            hlines.push(HLine {
                x0: 70.0,
                x1: 500.0,
                y,
                w: 0.5,
            });
            hlines.push(HLine {
                x0: 500.0,
                x1: 530.0,
                y,
                w: 0.5,
            });
        }
        // a ledger line level with nothing of the staff's, and a short line on one line only
        hlines.push(HLine {
            x0: 530.0,
            x1: 540.0,
            y: 100.0,
            w: 0.5,
        });
        let pg = Page {
            width: 600.0,
            hlines,
            ..Page::default()
        };
        let staves = pg.staves();
        assert_eq!(staves.len(), 1);
        assert_eq!((staves[0].left, staves[0].right), (70.0, 530.0));
        assert!(staves[0].breaks.is_empty());
    }

    #[test]
    fn a_staff_s_lines_stopped_and_started_again_are_a_break() {
        // a coda set apart on the line: each line drawn from 70 to 150, and again from 170
        let mut hlines = Vec::new();
        for k in 0..5 {
            let y = 100.0 + 3.4 * k as f64;
            hlines.push(HLine {
                x0: 70.0,
                x1: 150.0,
                y,
                w: 0.5,
            });
            hlines.push(HLine {
                x0: 170.0,
                x1: 570.0,
                y,
                w: 0.5,
            });
        }
        let pg = Page {
            width: 600.0,
            hlines,
            ..Page::default()
        };
        let st = pg.staves();
        assert_eq!(st.len(), 1);
        assert_eq!((st[0].left, st[0].right), (70.0, 570.0));
        assert_eq!(st[0].breaks, vec![(150.0, 170.0)]);
    }

    #[test]
    fn a_page_of_chords_alone_has_its_stems_width_from_their_long_stems() {
        // stems 0.7 wide and 26 long (a chord of three and its stem), barlines 0.8 wide and
        // as tall as the staff: no line is of a single note's stem's length
        let line = |x: f64, y0: f64, y1: f64, w: f64| VLine { x, y0, y1, w };
        let mut vlines: Vec<VLine> = (0..6)
            .map(|k| line(80.0 + 16.0 * k as f64, 118.0, 144.0, 0.7))
            .collect();
        vlines.extend((0..3).map(|k| line(160.0 + 100.0 * k as f64, 113.0, 133.0, 0.8)));
        let pg = Page {
            vlines,
            ..Page::default()
        };
        assert_eq!(pg.stem_width(5.0), 0.7);
        assert!((pg.barline_width(5.0) - 0.75).abs() < 1e-9);
        // with a stem of the usual length on the page, that is the width
        let mut pg = pg;
        pg.vlines.push(line(300.0, 120.0, 137.0, 0.5));
        assert_eq!(pg.stem_width(5.0), 0.5);
    }

    #[test]
    fn what_is_drawn_off_the_page_is_not_on_it() {
        // a staff's line on the page, and one of a system left past its left edge
        let line = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.4 };
        let mut dev = Collect {
            hlines: vec![line(67.0, 567.0, 151.0), line(-127.5, -29.1, 152.9)],
            vlines: vec![
                VLine {
                    x: 100.0,
                    y0: 10.0,
                    y1: 30.0,
                    w: 0.5,
                },
                VLine {
                    x: -40.0,
                    y0: 10.0,
                    y1: 30.0,
                    w: 0.5,
                },
                VLine {
                    x: 100.0,
                    y0: 800.0,
                    y1: 830.0,
                    w: 0.5,
                },
            ],
            ..Collect::default()
        };
        let mut on = drawn(7, 0xCF, 0.26);
        (on.x0, on.x1_ink, on.y) = (100.0, 106.0, 150.0);
        let mut off = drawn(7, 0xCF, 0.26);
        (off.x0, off.x1_ink, off.y) = (-60.0, -54.0, 150.0);
        dev.drawn.extend([on, off]);
        dev.off_the_page_dropped(595.0, 792.0);
        assert_eq!(dev.hlines, vec![line(67.0, 567.0, 151.0)]);
        assert_eq!(dev.vlines.len(), 1);
        assert_eq!(dev.drawn.len(), 1);
    }

    #[test]
    fn a_shape_stroked_round_and_then_filled_is_one_shape() {
        let h = |x0: f64, x1: f64, y: f64| HLine { x0, x1, y, w: 0.4 };
        let v = |x: f64, y0: f64, y1: f64| VLine { x, y0, y1, w: 0.4 };
        // LilyPond's stem: a box 0.25 wide and 15 tall, stroked 0.4 wide and then filled
        let mut dev = Collect {
            hlines: vec![
                h(71.0, 583.0, 111.4),
                h(113.25, 113.5, 115.0),
                h(113.25, 113.5, 130.0),
            ],
            vlines: vec![v(113.25, 115.0, 130.0), v(113.5, 115.0, 130.0)],
            ..Collect::default()
        };
        let stem = Rect::new(113.25, 115.0, 113.5, 130.0);
        let round = Some(Outlined {
            bbox: stem,
            w: 0.4,
            lines: (1, 0, 0),
        });
        let corners = |r: Rect| vec![(r.x0, r.y1), (r.x1, r.y1), (r.x1, r.y0), (r.x0, r.y0)];
        dev.filled(corners(stem), stem, round);
        // the staff's line is kept, the stem's own edge is gone, and the stem is 0.65 wide
        assert_eq!(dev.hlines, vec![h(71.0, 583.0, 111.4)]);
        assert!(dev.vlines.is_empty());
        assert_eq!(dev.vfills.len(), 1);
        assert!((dev.vfills[0].w - 0.65).abs() < 1e-9 && (dev.vfills[0].x - 113.375).abs() < 1e-9);
        // its beam: a level box 69 long and 2 thick, whose edge would be a long line in the staff
        let beam = Rect::new(147.7, 130.4, 216.4, 132.4);
        dev.hlines
            .extend([h(147.7, 216.4, 130.4), h(147.7, 216.4, 132.4)]);
        let round = Some(Outlined {
            bbox: beam,
            w: 0.4,
            lines: (1, 0, 0),
        });
        dev.filled(corners(beam), beam, round);
        assert_eq!(dev.hlines.len(), 1);
        let ys: Vec<f64> = dev.polys[0].iter().map(|q| q.1).collect();
        assert!((ys.iter().cloned().fold(f64::MAX, f64::min) - 130.2).abs() < 1e-9);
        assert!((ys.iter().cloned().fold(f64::MIN, f64::max) - 132.6).abs() < 1e-9);
        // a staff's line drawn as a thin box with a line round it stays the lines it was, and a
        // shape with nothing stroked round it (or another path) is itself
        let line = Rect::new(70.0, 100.0, 500.0, 100.3);
        dev.hlines
            .extend([h(70.0, 500.0, 100.0), h(70.0, 500.0, 100.3)]);
        let round = Some(Outlined {
            bbox: line,
            w: 0.2,
            lines: (1, 0, 0),
        });
        dev.filled(corners(line), line, round);
        assert_eq!(dev.hlines.len(), 3);
        dev.filled(corners(beam), beam, round);
        assert_eq!(dev.hlines.len(), 3);
        assert_eq!(dev.polys[2], corners(beam));
    }

    fn named(code: u32, x0: f64, y: f64, size: f64) -> Drawn {
        let mut g = drawn(TYPE1 + 80, 0, 0.26);
        (g.x0, g.x1_ink, g.y, g.size) = (x0, x0 + 0.33 * size, y, size);
        g.named = Some(Some(legacy::Sym {
            code,
            scale: 1.0,
            rise: 0.0,
            shift: 0.0,
        }));
        g
    }

    fn letter(ch: char, x0: f64, base: f64, size: f64) -> Drawn {
        let mut g = drawn(TYPE1 + 44, 0, 0.5);
        (g.chars, g.x0, g.y, g.size) = (vec![ch], x0, base, size);
        g.x1_adv = Some(x0 + 0.5 * size);
        g
    }

    #[test]
    fn glyphs_known_by_their_names_are_read_as_smufl_s() {
        let mut dev = Collect::default();
        // twelve noteheads 20 large; a time signature's 3 on the middle line and an 8 on the
        // bottom one (the staff from 100 to 120); a fingering's 3, small; a brace (nothing)
        dev.drawn
            .extend((0..12).map(|k| named(0xE0A4, 100.0 + 20.0 * k as f64, 110.0, 20.0)));
        dev.drawn
            .push(named(lilypond::DIGIT + 3, 80.0, 110.0, 20.0));
        dev.drawn
            .push(named(lilypond::DIGIT + 8, 80.0, 120.0, 20.0));
        dev.drawn
            .push(named(lilypond::DIGIT + 3, 140.0, 95.0, 11.0));
        let mut brace = named(0, 60.0, 110.0, 20.0);
        brace.named = Some(None);
        dev.drawn.push(brace);
        // a dot beside the first notehead, a repeat sign's pair by the barline, and a dot set
        // well off its note
        dev.drawn.push(named(lilypond::DOT, 109.0, 107.5, 20.0));
        dev.drawn.push(named(lilypond::DOT, 390.0, 107.5, 20.0));
        dev.drawn.push(named(lilypond::DOT, 390.0, 112.5, 20.0));
        dev.drawn.push(named(lilypond::DOT, 372.0, 107.5, 20.0));
        let fonts = font_roles([&dev].into_iter());
        assert!(fonts.is_empty());
        dev.sort_glyphs(&fonts);
        let at = |code: u32| -> Vec<(f64, f64)> {
            let mut v: Vec<(f64, f64)> = (dev.glyphs.iter())
                .filter(|g| g.code == code)
                .map(|g| (g.x0, g.y))
                .collect();
            v.sort_by(|a, b| a.partial_cmp(b).unwrap());
            v
        };
        assert_eq!(at(0xE0A4).len(), 12);
        // the time signature's digits, raised a space to where SMuFL's stand
        assert_eq!(at(0xE083), vec![(80.0, 105.0)]);
        assert_eq!(at(0xE088), vec![(80.0, 115.0)]);
        assert_eq!(at(0xED13), vec![(140.0, 95.0)]);
        assert_eq!(at(smufl::DOT), vec![(109.0, 107.5), (372.0, 107.5)]);
        assert_eq!(at(0xE044), vec![(390.0, 107.5), (390.0, 112.5)]);
        assert_eq!(dev.glyphs.len(), 12 + 3 + 4);
        assert!(dev.letters.is_empty());
    }

    #[test]
    fn a_metronome_mark_s_note_is_no_note_of_the_staff() {
        // a notehead with its flag and `= 64` after it over the staff, and a note of the staff
        let mut dev = Collect::default();
        dev.drawn.push(named(0xE0A4, 107.7, 96.1, 16.4));
        dev.drawn.push(named(0xE240, 113.1, 82.0, 16.4));
        dev.drawn.push(letter('=', 119.6, 98.4, 10.1));
        dev.drawn.push(letter('6', 128.6, 98.4, 10.1));
        dev.drawn.push(named(0xE0A4, 129.7, 131.7, 18.4));
        dev.sort_glyphs(&Fonts::new());
        let codes: Vec<u32> = dev.glyphs.iter().map(|g| g.code).collect();
        assert_eq!(codes, vec![0xE1D7, 0xE0A4]);
        assert_eq!(dev.letters.len(), 2);
    }

    #[test]
    fn an_8_under_a_clef_is_the_clef_s() {
        // a treble clef on the line at 131.7 (a space is 4.6), an italic 8 under it; and a
        // bar's number 8 over another clef's left end, which is not its
        let mut dev = Collect::default();
        let mut clef = named(0xE050, 66.0, 131.7, 18.4);
        clef.x1_ink = 78.0;
        let mut second = named(0xE050, 66.0, 331.7, 18.4);
        second.x1_ink = 78.0;
        dev.drawn.extend([clef, second]);
        dev.drawn.push(letter('8', 69.5, 150.0, 9.0));
        dev.drawn.push(letter('8', 62.0, 300.0, 9.0));
        dev.sort_glyphs(&Fonts::new());
        let codes: Vec<u32> = dev.glyphs.iter().map(|g| g.code).collect();
        assert_eq!(codes, vec![0xE052, 0xE050]);
        assert_eq!(dev.letters.len(), 1);
    }

    #[test]
    fn a_thin_upright_filled_rectangle_is_a_line() {
        // a stem 0.24 wide and 15 tall, filled
        let stem = [(10.0, 30.0), (10.24, 30.0), (10.24, 15.0), (10.0, 15.0)];
        let v = upright_fill(&stem).unwrap();
        assert!((v.x - 10.12).abs() < 1e-9 && (v.w - 0.24).abs() < 1e-9);
        assert_eq!((v.y0, v.y1), (15.0, 30.0));
        // a level beam, a sloped one and a square are shapes
        assert!(upright_fill(&[(0.0, 0.0), (20.0, 0.0), (20.0, 2.0), (0.0, 2.0)]).is_none());
        assert!(upright_fill(&[(0.0, 0.0), (1.0, 3.0), (1.0, 13.0), (0.0, 10.0)]).is_none());
        assert!(upright_fill(&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]).is_none());
        // the hairline stroked round a filled stem is that stem; a stem elsewhere is kept
        let line = |x: f64, y0: f64, y1: f64, w: f64| VLine { x, y0, y1, w };
        let all = with_upright_fills(
            vec![line(10.24, 15.0, 30.0, 0.12), line(40.0, 15.0, 30.0, 0.12)],
            vec![v],
        );
        assert_eq!(all, vec![line(40.0, 15.0, 30.0, 0.12), v]);
    }

    #[test]
    fn a_shape_is_cut_to_its_clip() {
        // a beam from 0 to 30, sloping from 10 to 13, clipped to its last 6: the short beam of
        // a dotted pair
        let beam = vec![(0.0, 10.0), (30.0, 13.0), (30.0, 15.0), (0.0, 12.0)];
        let cut = clipped(beam.clone(), &Rect::new(24.0, 0.0, 31.0, 100.0));
        let xs: Vec<f64> = cut.iter().map(|q| q.0).collect();
        assert_eq!(xs.iter().cloned().fold(f64::MAX, f64::min), 24.0);
        assert_eq!(xs.iter().cloned().fold(f64::MIN, f64::max), 30.0);
        assert!(cut
            .iter()
            .any(|q| (q.0 - 24.0).abs() < 1e-9 && (q.1 - 12.4).abs() < 1e-9));
        assert!(cut
            .iter()
            .any(|q| (q.0 - 24.0).abs() < 1e-9 && (q.1 - 14.4).abs() < 1e-9));
        // within its clip a shape is itself; outside it nothing is drawn
        assert_eq!(
            clipped(beam.clone(), &Rect::new(-1.0, 0.0, 31.0, 100.0)),
            beam
        );
        assert!(clipped(beam, &Rect::new(40.0, 0.0, 50.0, 100.0)).is_empty());
    }

    fn drawn(font: u128, byte: u8, high: f64) -> Drawn {
        Drawn {
            font,
            code: 5,
            chars: vec![char::from_u32(0xF000 + byte as u32).unwrap()],
            x0: 0.0,
            x1_ink: 1.0,
            x1_adv: Some(1.0),
            y: 0.0,
            size: 20.0,
            run: 0,
            high,
            sig: 0,
            named: None,
        }
    }

    #[test]
    fn a_font_whose_codes_say_nothing_is_known_by_its_outlines() {
        // a notehead's outline, one way round in quadratic curves and the other in cubic
        let mut a = BezPath::new();
        a.move_to((112.0, -130.0));
        a.quad_to((64.0, -130.0), (32.0, -107.5));
        a.quad_to((0.0, -85.0), (0.0, -43.0));
        a.line_to((342.0, 44.0));
        a.close_path();
        let mut b = BezPath::new();
        b.move_to((342.0, 44.0));
        b.line_to((0.0, -43.0));
        b.curve_to((0.0, -70.0), (10.0, -90.0), (32.0, -107.5));
        b.curve_to((50.0, -120.0), (80.0, -130.0), (112.0, -130.0));
        b.close_path();
        assert_eq!(signature(&a), signature(&b));
        b.line_to((500.0, 0.0));
        assert_ne!(signature(&a), signature(&b));
        // a font renumbered from 33 up, no Unicode: its noteheads' outlines are Sibelius's
        let (head, clef) = (0xCB90_0F35_019C_D6D1, 0x19DF_1AD5_F989_C437);
        assert_eq!(
            shapes::by_shape(head),
            Some((Role::Main(Family::Opus), 0xCF))
        );
        let mut dev = Collect::default();
        for _ in 0..12 {
            let mut g = drawn(77, 0, 0.26);
            (g.code, g.chars, g.sig) = (40, vec!['('], head);
            dev.drawn.push(g);
        }
        let mut g = drawn(77, 0, 1.7);
        (g.code, g.chars, g.sig) = (35, vec!['#'], clef);
        dev.drawn.push(g);
        let fonts = font_roles([&dev].into_iter());
        assert_eq!(fonts.get(&77).map(|f| f.1), Some(Decoding::Shape));
        dev.sort_glyphs(&fonts);
        let codes: Vec<u32> = dev.glyphs.iter().map(|g| g.code).collect();
        assert_eq!(codes.iter().filter(|&&c| c == 0xE0A4).count(), 12);
        assert!(codes.contains(&0xE050));
    }

    #[test]
    fn a_font_with_no_name_is_known_by_its_noteheads() {
        // capella's: black noteheads at 0xE5, a clef at `A`; beside it the same font smaller
        let mut dev = Collect::default();
        dev.drawn
            .extend((0..20).map(|_| drawn(TYPE1 + 80, 0xE5, 0.26)));
        dev.drawn.push(drawn(TYPE1 + 80, 0x41, 1.7));
        dev.drawn.push(drawn(TYPE1 + 52, 0x70, 0.44));
        let fonts = font_roles([&dev].into_iter());
        let main = (Role::Main(Family::Capella), Decoding::Private);
        assert_eq!(fonts.get(&(TYPE1 + 80)), Some(&main));
        assert_eq!(fonts.get(&(TYPE1 + 52)), Some(&main));
        dev.sort_glyphs(&fonts);
        let codes: BTreeSet<u32> = dev.glyphs.iter().map(|g| g.code).collect();
        assert_eq!(codes, BTreeSet::from([0xE0A4, 0xE050, 0xE520]));
        // Sonata's layout: noteheads at 0xCF, where 0xE4 is an eighth rest
        let mut dev = Collect::default();
        dev.drawn
            .extend((0..20).map(|_| drawn(TYPE1 + 80, 0xCF, 0.26)));
        dev.drawn
            .extend((0..9).map(|_| drawn(TYPE1 + 80, 0xE4, 0.45)));
        let fonts = font_roles([&dev].into_iter());
        let either = (Role::Main(Family::Either), Decoding::Private);
        assert_eq!(fonts.get(&(TYPE1 + 80)), Some(&either));
    }

    #[test]
    fn a_chord_frame_is_found_on_a_page_drawn_large() {
        // six strings 80 long, 17.5 apart, 2 wide: a frame where noteheads are 100 wide, not
        // where they are 20
        let vlines: Vec<VLine> = (0..6)
            .map(|k| VLine {
                x: 400.0 + 17.5 * k as f64,
                y0: 3000.0,
                y1: 3080.0,
                w: 2.0,
            })
            .collect();
        assert_eq!(frames_of(&vlines, 5.0).len(), 1);
        assert!(frames_of(&vlines, 1.0).is_empty());
    }
}