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
//! Which parts a system shows when it shows fewer staves than the score has (a program leaves a
//! staff out of a system in which it only rests). The page says it in several ways, and each is
//! held against every choice of parts the staves could be (`layout::parts_shown`: the choices
//! their grouping by barlines and the names printed beside them leave):
//!
//! - the braces and brackets at the system's left. One drawn round two or more staves in the
//!   fullest system is drawn round those of them a short system shows, when it shows two or
//!   more: a system with no brace over its top staves does not show both sopranos a brace joins;
//! - the barlines, which run through the staves of a group as far as they are shown;
//! - the clef each staff opens with, which is the clef its part was last left in (a tenor's
//!   treble clef an octave down is not the soprano's, a cello's bass clef not the voice's);
//! - the words under a staff, which make it a voice's.
//!
//! Where one choice is left, the system is that. Where several are, the staves they agree on
//! are read, and the parts they differ on are left unread through the system: of two sopranos
//! set alike, one printed and one not, nothing on the page says which is printed.

use std::collections::BTreeSet;

use crate::layout::{self, Kind, Part, System};
use crate::page::{Page, Staff};
use crate::smufl;

/// What stands upright at a system's left over two staves or more.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Tall {
    /// A brace (the font's glyph, or drawn as a curve).
    Brace,
    /// A line left of the system's own: a bracket.
    Line,
}

/// A system's grouping as drawn: the braces and brackets at its left, each with the first and
/// last staff it runs over, and whether the barlines join each staff to the one under it.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Marks {
    pub tall: Vec<(Tall, usize, usize)>,
    pub joins: Vec<bool>,
}

/// The grouping drawn on a system.
pub(crate) fn marks(pg: &Page, staves: &[Staff]) -> Marks {
    let sp = staves[0].sp();
    let left = staves.iter().map(|s| s.left).fold(f64::MAX, f64::min);
    let (top, bottom) = (staves[0].top(), staves[staves.len() - 1].bottom());
    // the staves a mark from y0 down to y1 runs over, if it is this system's and they are two
    // or more
    let over = |y0: f64, y1: f64| -> Option<(usize, usize)> {
        if y0 < top - 2.0 * sp || y1 > bottom + 2.0 * sp {
            return None;
        }
        let within: Vec<usize> = (0..staves.len())
            .filter(|&i| {
                let mid = (staves[i].top() + staves[i].bottom()) / 2.0;
                y0 - sp <= mid && mid <= y1 + sp
            })
            .collect();
        (within.len() >= 2).then(|| (within[0], within[within.len() - 1]))
    };
    let beside = |x: f64| left - 8.0 * sp < x && x < left + 0.5 * sp;
    let mut tall: Vec<(Tall, usize, usize)> = Vec::new();
    // (a brace's glyph is set at its foot and is as tall as its size)
    for g in pg
        .glyphs
        .iter()
        .filter(|g| g.code == 0xE000 && beside(g.x0))
    {
        if let Some((a, b)) = over(g.y - g.size, g.y) {
            tall.push((Tall::Brace, a, b));
        }
    }
    for c in pg
        .curves
        .iter()
        .filter(|c| beside(c.x0) && c.x1 < left + 0.5 * sp)
    {
        if c.y1 - c.y0 > 6.0 * sp {
            if let Some((a, b)) = over(c.y0, c.y1) {
                tall.push((Tall::Brace, a, b));
            }
        }
    }
    for v in pg
        .vlines
        .iter()
        .filter(|v| beside(v.x) && v.x < left - 0.4 * sp)
    {
        if let Some((a, b)) = over(v.y0, v.y1) {
            tall.push((Tall::Line, a, b));
        }
    }
    tall.sort();
    tall.dedup();
    let joins = (1..staves.len())
        .map(|i| layout::joined(pg, &staves[i - 1], &staves[i], left + 3.0 * sp))
        .collect();
    Marks { tall, joins }
}

/// The clef each staff of a system opens with: the first clef on it.
pub(crate) fn opening_clefs(pg: &Page, staves: &[Staff]) -> Vec<Option<&'static str>> {
    staves
        .iter()
        .map(|st| {
            let sp = st.sp();
            pg.glyphs
                .iter()
                .filter(|g| {
                    smufl::clef(g.code).is_some()
                        && st.top() - sp <= g.y
                        && g.y <= st.bottom() + sp
                        && g.x0 < st.left + 8.0 * sp
                })
                .min_by(|a, b| a.x0.total_cmp(&b.x0))
                .and_then(|g| smufl::clef_on(g.code, (st.bottom() - g.y) / sp + 1.0))
        })
        .collect()
}

/// What a short system shows of itself.
#[derive(Clone, Debug, Default)]
pub(crate) struct Seen {
    pub marks: Marks,
    pub clefs: Vec<Option<&'static str>>,
    /// Whether words stand under each staff, as a voice's do.
    pub sung: Vec<bool>,
}

pub(crate) fn seen(pg: &Page, staves: &[Staff]) -> Seen {
    Seen {
        marks: marks(pg, staves),
        clefs: opening_clefs(pg, staves),
        sung: (0..staves.len())
            .map(|i| {
                let st = &staves[i];
                let words = crate::lyrics::band(pg, st, staves.get(i + 1), st.left, st.right);
                words
                    .iter()
                    .filter(|w| w.text.chars().any(char::is_alphabetic))
                    .count()
                    >= 4
            })
            .collect(),
    }
}

/// The parts a short system's staves are read as, and those of the score's parts that the page
/// does not tell apart there (`doubted`: their staves' bars are left unread in this system,
/// shown or not).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Told {
    pub parts: Vec<usize>,
    pub doubted: Vec<usize>,
}

/// The score's staff (counted from the top of the fullest system) under each of a short
/// system's staves, were its groups the parts `choice` names.
fn staves_of(choice: &[usize], parts: &[Part]) -> Vec<(usize, usize)> {
    let mut firsts = Vec::new();
    let mut n = 0;
    for p in parts {
        firsts.push(n);
        n += p.staff_names().len();
    }
    choice
        .iter()
        .flat_map(|&j| (0..parts[j].staff_names().len()).map(move |k| (j, k)))
        .map(|(j, k)| (j, firsts[j] + k))
        .collect()
}

/// The braces and brackets of the fullest system as a system showing only `shown` of its
/// staves has them: each round the staves it still holds, where they are two or more.
fn tall_left(full: &Marks, shown: &[usize]) -> Vec<(Tall, usize, usize)> {
    let mut out: Vec<(Tall, usize, usize)> = full
        .tall
        .iter()
        .filter_map(|&(kind, a, b)| {
            let held: Vec<usize> = (0..shown.len())
                .filter(|&p| a <= shown[p] && shown[p] <= b)
                .collect();
            (held.len() >= 2).then(|| (kind, held[0], held[held.len() - 1]))
        })
        .collect();
    out.sort();
    out.dedup();
    out
}

/// Whether the barlines join each shown staff to the next shown one: where they run through
/// every staff between the two in the fullest system.
fn joins_left(full: &Marks, shown: &[usize]) -> Vec<bool> {
    shown
        .windows(2)
        .map(|w| (w[0]..w[1]).all(|g| full.joins.get(g).copied().unwrap_or(false)))
        .collect()
}

/// A sign on the page, held against a choice of parts: whether it allows it.
type Sign<'a> = dyn Fn(&Vec<usize>) -> bool + 'a;

/// Of the `choices` of parts for a short system, the ones the page allows, and so what the
/// system is read as. `full`: the fullest system's grouping; `clef_before`: the clef a staff
/// (by name) was last left in, where it has been read; `prefer`: the choice to read by when
/// more than one is left; `goes_on`: whether a tie or slur ran on into this system from a staff
/// (by name) at the end of the system before, so that its part has a note here and is shown. A
/// sign that leaves no choice at all is not counted (it was misread, or the program sets it
/// otherwise). None when there is no choice to begin with.
pub(crate) fn tell(
    choices: &[Vec<usize>],
    parts: &[Part],
    full: &Marks,
    seen: &Seen,
    clef_before: &dyn Fn(&str) -> Option<&'static str>,
    goes_on: &dyn Fn(&str) -> bool,
    prefer: Option<&Vec<usize>>,
) -> Option<Told> {
    let mut left: Vec<&Vec<usize>> = choices.iter().collect();
    let some_voice = parts.iter().any(|p| p.kind == Kind::Voice);
    let by_tall = |c: &Vec<usize>| {
        let shown: Vec<usize> = staves_of(c, parts).iter().map(|s| s.1).collect();
        tall_left(full, &shown) == seen.marks.tall
    };
    let by_joins = |c: &Vec<usize>| {
        let shown: Vec<usize> = staves_of(c, parts).iter().map(|s| s.1).collect();
        joins_left(full, &shown) == seen.marks.joins
    };
    let by_clefs = |c: &Vec<usize>| {
        let names = c.iter().flat_map(|&j| parts[j].staff_names());
        names
            .zip(&seen.clefs)
            .all(|(name, here)| match (clef_before(&name), here) {
                (Some(before), Some(here)) => before == *here,
                _ => true,
            })
    };
    let by_words = |c: &Vec<usize>| {
        let kinds = c.iter().flat_map(|&j| {
            let n = parts[j].staff_names().len();
            (0..n).map(move |_| &parts[j].kind)
        });
        !some_voice
            || kinds
                .zip(&seen.sung)
                .all(|(kind, sung)| !sung || *kind != Kind::Other)
    };
    let by_going_on = |c: &Vec<usize>| {
        (0..parts.len())
            .filter(|j| !c.contains(j))
            .all(|j| !parts[j].staff_names().iter().any(|n| goes_on(n)))
    };
    let signs: [&Sign; 5] = [&by_tall, &by_joins, &by_clefs, &by_words, &by_going_on];
    for sign in signs {
        let kept: Vec<&Vec<usize>> = left.iter().copied().filter(|c| sign(c)).collect();
        if !kept.is_empty() {
            left = kept;
        }
    }
    let read = match prefer.filter(|p| left.contains(p)) {
        Some(p) => p,
        None => left.iter().copied().max()?,
    };
    // the parts the choices left differ on, staff by staff
    let all: Vec<Vec<usize>> = left
        .iter()
        .map(|c| staves_of(c, parts).iter().map(|s| s.0).collect())
        .collect();
    let mut doubted: BTreeSet<usize> = BTreeSet::new();
    for i in 0..all[0].len() {
        if all.iter().any(|c| c[i] != all[0][i]) {
            doubted.extend(all.iter().map(|c| c[i]));
        }
    }
    Some(Told {
        parts: read.clone(),
        doubted: doubted.into_iter().collect(),
    })
}

/// What is known of the score before any system is read: the fullest system's grouping, and
/// each short system's choices of parts with what it shows.
pub(crate) struct Short {
    full: Marks,
    /// By system: its choices and what it shows; None for a system that shows every staff.
    systems: Vec<Option<(Vec<Vec<usize>>, Seen)>>,
}

pub(crate) fn short(pages: &[Page], systems: &[System], parts: &[Part]) -> Short {
    let total: usize = parts.iter().map(|p| p.staff_names().len()).sum();
    let full = systems
        .iter()
        .max_by_key(|s| s.staves.len())
        .map(|s| marks(&pages[s.page], &s.staves))
        .unwrap_or_default();
    let systems = systems
        .iter()
        .enumerate()
        .map(|(si, s)| {
            (s.staves.len() < total).then(|| {
                let pg = &pages[s.page];
                (
                    layout::parts_shown(pg, &s.staves, parts, si > 0),
                    seen(pg, &s.staves),
                )
            })
        })
        .collect();
    Short { full, systems }
}

impl Short {
    /// System `si` told: see [`tell`].
    pub(crate) fn tell(
        &self,
        si: usize,
        parts: &[Part],
        clef_before: &dyn Fn(&str) -> Option<&'static str>,
        goes_on: &dyn Fn(&str) -> bool,
        prefer: Option<&Vec<usize>>,
    ) -> Option<Told> {
        let (choices, seen) = self.systems.get(si)?.as_ref()?;
        tell(
            choices,
            parts,
            &self.full,
            seen,
            clef_before,
            goes_on,
            prefer,
        )
    }
}

/// Why a doubted part's bars in a system are left unread: the parts it may be mistaken for.
pub(crate) fn why(staff: &str, doubted: &[usize], parts: &[Part]) -> String {
    let ids: Vec<&str> = doubted.iter().map(|&j| parts[j].id.as_str()).collect();
    format!(
        "{staff}: its system leaves staves out, and nothing on the page says which of {} it shows",
        ids.join(", ")
    )
}

/// Why a short system's bars are left unread when its staves fit none of the score's parts.
pub(crate) fn why_unfit(staff: &str) -> String {
    format!(
        "{staff}: its system leaves staves out, and its staves fit no choice of the score's parts"
    )
}

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

    fn part(id: &str, kind: Kind) -> Part {
        Part {
            id: id.into(),
            name: id.into(),
            kind,
            printed: None,
        }
    }

    /// Two voices and a piano, the fullest system's staves joined only within the piano.
    fn two_voices() -> (Vec<Part>, Marks) {
        let parts = vec![
            part("V", Kind::Voice),
            part("V2", Kind::Voice),
            part("P", Kind::Piano),
        ];
        let full = Marks {
            tall: vec![(Tall::Brace, 2, 3)],
            joins: vec![false, false, true],
        };
        (parts, full)
    }

    fn seen_one_voice(sung: bool) -> Seen {
        Seen {
            marks: Marks {
                tall: vec![(Tall::Brace, 1, 2)],
                joins: vec![false, true],
            },
            clefs: vec![Some("treble"), Some("treble"), Some("bass")],
            sung: vec![sung, false, false],
        }
    }

    #[test]
    fn two_voices_set_alike_are_doubted() {
        let (parts, full) = two_voices();
        let choices = vec![vec![0, 2], vec![1, 2]];
        let none = |_: &str| None;
        let no = |_: &str| false;
        let told = tell(
            &choices,
            &parts,
            &full,
            &seen_one_voice(true),
            &none,
            &no,
            None,
        );
        assert_eq!(told.unwrap().doubted, [0, 1]);
    }

    #[test]
    fn a_tie_into_the_system_says_which_voice_it_shows() {
        let (parts, full) = two_voices();
        let choices = vec![vec![0, 2], vec![1, 2]];
        let none = |_: &str| None;
        let on = |n: &str| n == "V2";
        let told = tell(
            &choices,
            &parts,
            &full,
            &seen_one_voice(true),
            &none,
            &on,
            None,
        );
        assert_eq!(
            told,
            Some(Told {
                parts: vec![1, 2],
                doubted: vec![]
            })
        );
        // a tie from both: no choice keeps both, so it says nothing
        let both = |n: &str| n == "V" || n == "V2";
        let told = tell(
            &choices,
            &parts,
            &full,
            &seen_one_voice(true),
            &none,
            &both,
            None,
        );
        assert_eq!(told.unwrap().doubted, [0, 1]);
    }

    #[test]
    fn words_under_a_staff_make_it_the_voice_not_the_instrument() {
        let parts = vec![
            part("I", Kind::Other),
            part("V", Kind::Voice),
            part("P", Kind::Piano),
        ];
        let full = Marks {
            tall: vec![(Tall::Brace, 2, 3)],
            joins: vec![false, false, true],
        };
        let choices = vec![vec![0, 2], vec![1, 2]];
        let none = |_: &str| None;
        let no = |_: &str| false;
        // words under the piano's upper staff too (its marks): they do not count against it
        let mut seen = seen_one_voice(true);
        seen.sung[1] = true;
        let told = tell(&choices, &parts, &full, &seen, &none, &no, None).unwrap();
        assert_eq!((told.parts, told.doubted), (vec![1, 2], vec![]));
        // no words: the instrument or the voice
        let told = tell(
            &choices,
            &parts,
            &full,
            &seen_one_voice(false),
            &none,
            &no,
            None,
        );
        assert_eq!(told.unwrap().doubted, [0, 1]);
    }

    #[test]
    fn a_tenor_s_clef_is_not_the_soprano_s() {
        let parts = vec![
            part("V", Kind::Voice),
            part("V2", Kind::Voice),
            part("P", Kind::Piano),
        ];
        let (_, full) = two_voices();
        let choices = vec![vec![0, 2], vec![1, 2]];
        let before = |n: &str| match n {
            "V" => Some("treble"),
            "V2" => Some("treble8"),
            _ => None,
        };
        let no = |_: &str| false;
        let mut seen = seen_one_voice(true);
        seen.clefs[0] = Some("treble8");
        let told = tell(&choices, &parts, &full, &seen, &before, &no, None).unwrap();
        assert_eq!((told.parts, told.doubted), (vec![1, 2], vec![]));
    }

    #[test]
    fn a_brace_left_over_two_staves_shows_both_it_joins() {
        // two pianos, a brace round each; a system of one piano shows one brace either way, but
        // a system of a voice and a piano: barlines joined only within the piano
        let parts = vec![
            part("V", Kind::Voice),
            part("P", Kind::Piano),
            part("P2", Kind::Piano),
        ];
        let full = Marks {
            tall: vec![(Tall::Brace, 1, 2), (Tall::Brace, 3, 4)],
            joins: vec![false, true, false, true],
        };
        let seen = Seen {
            marks: Marks {
                tall: vec![(Tall::Brace, 0, 1), (Tall::Brace, 2, 3)],
                joins: vec![true, false, true],
            },
            clefs: vec![None; 4],
            sung: vec![false; 4],
        };
        let choices = vec![vec![1, 2]];
        let none = |_: &str| None;
        let no = |_: &str| false;
        let told = tell(&choices, &parts, &full, &seen, &none, &no, None).unwrap();
        assert_eq!((told.parts, told.doubted), (vec![1, 2], vec![]));
    }
}