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
//! The score's layout from the vectors alone: its systems (staves a line joins at the left), its
//! parts (staves the barlines join are one piano; a staff with words under it is a voice), and the
//! title and composer printed over the first system.

use crate::page::{Page, Staff};
use crate::words::{lines_of, words_of, Word};

/// A system: its page and its staves, top to bottom.
#[derive(Clone, Debug)]
pub struct System {
    pub page: usize,
    pub staves: Vec<Staff>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
    Voice,
    Piano,
    Other,
}

#[derive(Clone, Debug)]
pub struct Part {
    pub id: String,
    pub name: String,
    pub kind: Kind,
    /// Its name as printed left of its staves in the fullest system, if it is.
    pub printed: Option<String>,
}

impl Part {
    /// The staff names the format writes, top to bottom: `V`, or `P.1 P.2`.
    pub fn staff_names(&self) -> Vec<String> {
        match self.kind {
            Kind::Piano => vec![format!("{}.1", self.id), format!("{}.2", self.id)],
            _ => vec![self.id.clone()],
        }
    }
}

/// Whether a vertical line joins staff `a` to staff `b` below it; `from_x`: only lines right of
/// it (a bar's barline, not the system's opening line).
pub(crate) fn joined(pg: &Page, a: &Staff, b: &Staff, from_x: f64) -> bool {
    let sp = a.sp();
    pg.vlines
        .iter()
        .any(|v| v.x > from_x && v.y0 <= a.top() + 0.5 * sp && v.y1 >= b.bottom() - 0.5 * sp)
}

pub fn systems(pages: &[Page]) -> Vec<System> {
    let mut out = Vec::new();
    for (pi, pg) in pages.iter().enumerate() {
        let staves = pg.staves();
        let mut cur: Vec<Staff> = Vec::new();
        for st in staves {
            let join = cur.last().is_some_and(|a| joined(pg, a, &st, f64::MIN));
            if !join && !cur.is_empty() {
                out.push(System {
                    page: pi,
                    staves: std::mem::take(&mut cur),
                });
            }
            cur.push(st);
        }
        if !cur.is_empty() {
            out.push(System {
                page: pi,
                staves: cur,
            });
        }
    }
    out
}

/// Words under a staff, in the band where a voice's words stand.
fn words_under(pg: &Page, st: &Staff, below: Option<&Staff>) -> usize {
    let sp = st.sp();
    let lo = st.bottom() + 0.6 * sp;
    let hi = below
        .map(|b| b.top() - 0.3 * sp)
        .unwrap_or(st.bottom() + 10.0 * sp);
    words_of(pg)
        .iter()
        .filter(|w| {
            lo <= w.base
                && w.base <= hi
                && st.left < w.x0
                && w.x1 < st.right
                && w.text.chars().any(char::is_alphabetic)
                && !playing_term(&w.text)
        })
        .count()
}

/// Whether a word is one of the terms printed for how to play ("dol.", "cresc.", "pizz."): an
/// instrument's staff has them under it too, so they do not make it a voice's.
fn playing_term(word: &str) -> bool {
    const TERMS: [&str; 40] = [
        "dol",
        "dolce",
        "cresc",
        "crescendo",
        "dim",
        "diminuendo",
        "decresc",
        "rit",
        "ritard",
        "ritardando",
        "rall",
        "rallentando",
        "accel",
        "accelerando",
        "espr",
        "espress",
        "espressivo",
        "legato",
        "leg",
        "stacc",
        "staccato",
        "pizz",
        "arco",
        "ten",
        "tenuto",
        "marc",
        "marcato",
        "sost",
        "sostenuto",
        "sfz",
        "sim",
        "simile",
        "smorz",
        "morendo",
        "string",
        "cantabile",
        "leggiero",
        "rubato",
        "loco",
        "gliss",
    ];
    let w: String = word
        .trim_matches(|c: char| !c.is_alphabetic())
        .to_lowercase();
    TERMS.contains(&w.as_str())
}

/// The parts, from the fullest system: staves joined by their bars' barlines are a piano's (two at
/// a time); a staff alone is a voice when words stand under it, else a part of its own.
pub fn parts(pages: &[Page], systems: &[System]) -> Vec<Part> {
    let Some(full) = systems.iter().max_by_key(|s| s.staves.len()) else {
        return Vec::new();
    };
    let n = full.staves.len();
    let pg = &pages[full.page];
    let shapes = shapes_of(pg, &full.staves);
    // words under a staff anywhere in the score make it a voice
    let mut sung = vec![0usize; n];
    for s in systems.iter().filter(|s| s.staves.len() == n) {
        for i in 0..n {
            sung[i] += words_under(&pages[s.page], &s.staves[i], s.staves.get(i + 1));
        }
    }
    let names = printed_names(pg, &full.staves, &shapes);
    let (mut voices, mut pianos, mut others) = (0, 0, 0);
    let mut out = Vec::new();
    for (k, g) in shapes.iter().enumerate() {
        let (kind, base, count) = if g.len() == 2 {
            pianos += 1;
            (Kind::Piano, "P", pianos)
        } else if sung[g[0]] >= 4 {
            voices += 1;
            (Kind::Voice, "V", voices)
        } else {
            others += 1;
            (Kind::Other, "I", others)
        };
        let id = if count == 1 {
            base.to_string()
        } else {
            format!("{base}{count}")
        };
        let name = names[k].clone().unwrap_or_else(|| {
            match kind {
                Kind::Voice => "Voice",
                Kind::Piano => "Piano",
                Kind::Other => "Part",
            }
            .to_string()
        });
        out.push(Part {
            id,
            name,
            kind,
            printed: names[k].clone(),
        });
    }
    out
}

/// A system's staves in groups, each a part's: staves the bars' barlines join are one piano's
/// (two at a time), a staff alone a part of its own.
fn shapes_of(pg: &Page, staves: &[Staff]) -> Vec<Vec<usize>> {
    let sp = staves[0].sp();
    let left = staves.iter().map(|s| s.left).fold(f64::MAX, f64::min);
    // groups of staves the barlines join
    let mut groups: Vec<Vec<usize>> = Vec::new();
    for i in 0..staves.len() {
        let join = i > 0 && joined(pg, &staves[i - 1], &staves[i], left + 3.0 * sp);
        match groups.last_mut() {
            Some(g) if join => g.push(i),
            _ => groups.push(vec![i]),
        }
    }
    // a group of more than two: its last two the piano, the staves above parts of their own
    // (where a brace is drawn, the two it holds: `choir.rs`)
    let braced = crate::choir::braced(pg, staves);
    let mut shapes: Vec<Vec<usize>> = Vec::new();
    for g in groups {
        if let Some(pairs) = &braced {
            shapes.extend(crate::choir::split(&g, pairs));
        } else if g.len() > 2 {
            for &i in &g[..g.len() - 2] {
                shapes.push(vec![i]);
            }
            shapes.push(g[g.len() - 2..].to_vec());
        } else {
            shapes.push(g);
        }
    }
    shapes
}

/// Whether two printed names of a part are one name: the same letters, or one written short
/// for the other with a full stop ("Pno." for "Piano").
fn same_name(a: &str, b: &str) -> bool {
    let letters = |s: &str| -> Vec<char> {
        s.chars()
            .filter(|c| c.is_alphanumeric())
            .flat_map(char::to_lowercase)
            .collect()
    };
    let (la, lb) = (letters(a), letters(b));
    if la == lb {
        return !la.is_empty();
    }
    let (short, long, dotted) = if la.len() < lb.len() {
        (la, lb, a.trim_end().ends_with('.'))
    } else {
        (lb, la, b.trim_end().ends_with('.'))
    };
    if !dotted || short.is_empty() || short[0] != long[0] {
        return false;
    }
    let mut rest = long.iter();
    short.iter().all(|c| rest.any(|l| l == c))
}

/// The choices of parts for a system's groups of staves, when it shows fewer staves than the
/// score has (a part that rests is not printed there): the groups are parts in the score's
/// order, each of its part's number of staves. With `named`, the names printed left of the
/// staves count: a group named as a part is, is that part; an unnamed one is rather a part that
/// has no name printed. The choices that fit best, each the index of its part group by group.
pub(crate) fn parts_shown(
    pg: &Page,
    staves: &[Staff],
    parts: &[Part],
    named: bool,
) -> Vec<Vec<usize>> {
    let shapes = shapes_of(pg, staves);
    let names = printed_names(pg, staves, &shapes);
    let size = |p: &Part| if p.kind == Kind::Piano { 2 } else { 1 };
    let fit = |k: usize, j: usize| -> Option<i32> {
        if size(&parts[j]) != shapes[k].len() {
            return None;
        }
        Some(match (&names[k], &parts[j].printed) {
            _ if !named => 0,
            (None, None) => 1,
            (None, Some(_)) => 0,
            (Some(a), Some(b)) if same_name(a, b) => 2,
            (Some(_), None) => -1,
            (Some(_), Some(_)) => -2,
        })
    };
    let mut best: Vec<Vec<usize>> = Vec::new();
    let mut best_score = i32::MIN;
    let mut stack: Vec<(Vec<usize>, i32)> = vec![(Vec::new(), 0)];
    while let Some((chosen, score)) = stack.pop() {
        let k = chosen.len();
        if k == shapes.len() {
            if score > best_score {
                best.clear();
                best_score = score;
            }
            if score == best_score {
                best.push(chosen);
            }
            continue;
        }
        let from = chosen.last().map_or(0, |j| j + 1);
        // (leaving enough parts for the groups after this one)
        for j in from..parts.len().saturating_sub(shapes.len() - k - 1) {
            if let Some(s) = fit(k, j) {
                let mut next = chosen.clone();
                next.push(j);
                stack.push((next, score + s));
            }
        }
    }
    best
}

/// For each system, the parts its staves are of (the index of each group's part), where it
/// shows fewer staves than the score has; None for a system that shows them all, or whose
/// staves fit no choice of parts. Where the staves' shapes and printed names leave more than
/// one choice, it is the one whose parts the score's other systems show most, then the one
/// that leaves out the top parts (a voice not printed while it rests). The first system's
/// names are not counted: a program prints the parts' full names there and short ones after.
pub fn systems_parts(
    pages: &[Page],
    systems: &[System],
    parts: &[Part],
) -> Vec<Option<Vec<usize>>> {
    let total: usize = parts.iter().map(|p| p.staff_names().len()).sum();
    let choices: Vec<Vec<Vec<usize>>> = systems
        .iter()
        .enumerate()
        .map(|(si, s)| match s.staves.len() < total {
            true => parts_shown(&pages[s.page], &s.staves, parts, si > 0),
            false => Vec::new(),
        })
        .collect();
    // how many systems show each part for sure
    let mut shown = vec![0usize; parts.len()];
    for c in choices.iter().filter(|c| c.len() == 1) {
        for &j in &c[0] {
            shown[j] += 1;
        }
    }
    choices
        .into_iter()
        .map(|c| {
            c.into_iter()
                .max_by_key(|c| (c.iter().map(|&j| shown[j]).sum::<usize>(), c.clone()))
        })
        .collect()
}

/// A part's name as printed left of its staves, if it is.
fn printed_names(pg: &Page, staves: &[Staff], shapes: &[Vec<usize>]) -> Vec<Option<String>> {
    let words = words_of(pg);
    shapes
        .iter()
        .map(|g| {
            let (a, b) = (&staves[g[0]], &staves[*g.last().unwrap()]);
            let sp = a.sp();
            let mine: Vec<&Word> = words
                .iter()
                .filter(|w| {
                    w.x1 < a.left - 0.5 * sp
                        && a.top() - sp <= w.base
                        && w.base <= b.bottom() + 2.0 * sp
                })
                .collect();
            let text: Vec<&str> = mine.iter().map(|w| w.text.as_str()).collect();
            let t = text.join(" ");
            (!t.is_empty() && t.chars().any(char::is_alphabetic) && !t.contains('"')).then_some(t)
        })
        .collect()
}

/// The title (the largest words over the first system) and the composer (a line set to the right
/// under the title), as printed.
pub fn title_and_composer(pg: &Page, first: &Staff) -> (Option<String>, Option<String>) {
    let words: Vec<Word> = words_of(pg)
        .into_iter()
        .filter(|w| w.base < first.top() - 2.0 * first.sp())
        .collect();
    let lines = lines_of(&words, first.sp());
    let Some(ti) = (0..lines.len()).max_by(|&a, &b| lines[a].size.total_cmp(&lines[b].size)) else {
        return (None, None);
    };
    let title = lines[ti].text.clone();
    let composer = lines
        .iter()
        .filter(|l| l.base > lines[ti].base && l.x1 > 0.7 * pg.width && l.x0 > 0.4 * pg.width)
        .min_by(|a, b| a.base.total_cmp(&b.base))
        .map(|l| {
            let t = l.text.as_str();
            let lower = t.to_lowercase();
            [
                "words and music by ",
                "music and words by ",
                "composed by ",
                "music by ",
                "music: ",
                "by ",
            ]
            .iter()
            .find(|p| lower.starts_with(*p))
            .map(|p| t[p.len()..].to_string())
            .unwrap_or_else(|| t.to_string())
        });
    (Some(title), composer)
}

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

    fn staff(top: f64) -> Staff {
        Staff {
            lines: [top, top + 1.0, top + 2.0, top + 3.0, top + 4.0],
            left: 20.0,
            right: 100.0,
            breaks: Vec::new(),
        }
    }

    fn part(id: &str, kind: Kind, printed: Option<&str>) -> Part {
        Part {
            id: id.into(),
            name: id.into(),
            kind,
            printed: printed.map(String::from),
        }
    }

    /// A page of one system: a staff alone at 10 and a piano's two at 20 and 30 (barlines
    /// through both), with `name` printed left of the piano's.
    fn voice_and_piano(name: Option<&str>) -> Page {
        let v = |x: f64, y0: f64, y1: f64| VLine { x, y0, y1, w: 0.2 };
        let mut letters = Vec::new();
        for (k, ch) in name.unwrap_or("").chars().enumerate() {
            letters.push(Letter {
                ch,
                x0: 5.0 + k as f64,
                x1: 6.0 + k as f64,
                base: 28.0,
                size: 2.0,
                run: 0,
            });
        }
        Page {
            width: 120.0,
            vlines: vec![
                v(20.0, 10.0, 34.0),
                v(60.0, 10.0, 14.0),
                v(60.0, 20.0, 34.0),
                v(100.0, 10.0, 14.0),
                v(100.0, 20.0, 34.0),
            ],
            letters,
            ..Page::default()
        }
    }

    #[test]
    fn a_system_s_staves_are_the_parts_their_shapes_and_names_say() {
        // a voice and two pianos, the second named "Pia." where all are shown
        let parts = [
            part("V", Kind::Voice, None),
            part("P", Kind::Piano, None),
            part("P2", Kind::Piano, Some("Pia.")),
        ];
        let staves = [staff(10.0), staff(20.0), staff(30.0)];
        // a staff and an unnamed piano: the voice and the piano that has no name
        let pg = voice_and_piano(None);
        assert_eq!(parts_shown(&pg, &staves, &parts, true), [vec![0, 1]]);
        // a piano named as the second is: the second
        let named = voice_and_piano(Some("Pia."));
        assert_eq!(parts_shown(&named, &staves, &parts, true), [vec![0, 2]]);
        // names not counted (the first system's): either piano
        assert_eq!(parts_shown(&named, &staves, &parts, false).len(), 2);
        // two staves that are no piano's fit no parts of these
        let two = [staff(10.0), staff(40.0)];
        assert!(parts_shown(&pg, &two, &parts, true).is_empty());
    }

    #[test]
    fn a_staff_is_a_voice_by_its_words_not_by_how_to_play_it() {
        // two staves, not joined; under the top one `words` words: "aaaa", or "dim."
        let page = |words: usize, kind: char| {
            let mut letters = Vec::new();
            let text: Vec<char> = match kind {
                'd' => "dim.".chars().collect(),
                _ => "aaaa".chars().collect(),
            };
            for w in 0..words {
                for (k, &ch) in text.iter().enumerate() {
                    letters.push(Letter {
                        ch,
                        x0: 30.0 + 12.0 * w as f64 + k as f64,
                        x1: 31.0 + 12.0 * w as f64 + k as f64,
                        base: 17.0,
                        size: 2.0,
                        run: w,
                    });
                }
            }
            Page {
                width: 120.0,
                letters,
                ..Page::default()
            }
        };
        let sys = |page: usize| System {
            page,
            staves: vec![staff(10.0), staff(30.0)],
        };
        // two words in each of two systems: a voice
        let parts2 = parts(&[page(2, 'a'), page(2, 'a')], &[sys(0), sys(1)]);
        assert_eq!(parts2[0].kind, Kind::Voice);
        assert_eq!(parts2[1].kind, Kind::Other);
        // "dim." twice in each (how to play, under an instrument's staff): no voice
        let terms = parts(&[page(2, 'd'), page(2, 'd')], &[sys(0), sys(1)]);
        assert_eq!(terms[0].kind, Kind::Other);
        assert!(playing_term("cresc.") && playing_term("Dol.") && !playing_term("home."));
    }

    #[test]
    fn a_choice_the_names_leave_open_goes_to_the_parts_shown_most() {
        let parts = [
            part("V", Kind::Voice, None),
            part("P", Kind::Piano, None),
            part("P2", Kind::Piano, Some("Pia.")),
        ];
        let sys = |page: usize| System {
            page,
            staves: vec![staff(10.0), staff(20.0), staff(30.0)],
        };
        // the first system (its names not counted: "Piano" in full there), two with the
        // unnamed piano, one with the second
        let pages = [
            voice_and_piano(Some("Piano")),
            voice_and_piano(None),
            voice_and_piano(None),
            voice_and_piano(Some("Pia.")),
        ];
        let systems = [sys(0), sys(1), sys(2), sys(3)];
        let got = systems_parts(&pages, &systems, &parts);
        assert_eq!(got[0], Some(vec![0, 1]));
        assert_eq!(got[1], Some(vec![0, 1]));
        assert_eq!(got[3], Some(vec![0, 2]));
        // with nothing else to say, the top parts are the ones left out
        let got = systems_parts(&pages[..1], &systems[..1], &parts);
        assert_eq!(got[0], Some(vec![0, 2]));
        assert!(same_name("Pno.", "Piano") && same_name("piano", "Piano"));
        assert!(!same_name("S", "Solo") && !same_name("Pia.", "Voice"));
    }
}