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
//! Each staff's own time. A score mostly prints one time signature on every staff, but a staff
//! may be in a time of its own (a piano in 6/8 under a voice in 2/4): each staff's printed
//! signature is read, and a staff that prints none where another does keeps the time it had.
//! The score's time is its top staff's; the text says a staff's own where it differs
//! (`time P 6/8`), and each staff's bars are as long as its own time says.

use std::collections::BTreeMap;

use crate::frac::Q;
use crate::page::{Glyph, Staff};
use crate::read::{on_staff_for_time, time_of};
use crate::smufl;
use crate::staff::Res;

/// A time as read: its beats and beat unit.
pub type Time = (i64, i64);

/// What a system shows of its times.
pub struct Seen<'a> {
    pub staff_glyphs: &'a [Vec<Glyph>],
    pub staves: &'a [Staff],
    pub names: &'a [String],
    /// Where the system's first note or rest stands.
    pub first_event: f64,
    /// The bars' edges: the system's left, then each bar's right.
    pub edges: &'a [f64],
    /// The right edges of every staff's notes and rests.
    pub ev_x: &'a [f64],
    pub sp: f64,
    /// The page's notehead size (`on_staff_for_time`).
    pub size: f64,
}

/// A time printed as a sign: `common` (the C) or `cut` (the cut C); none where as numbers.
pub type Sign = Option<&'static str>;

/// A time as the format writes it: its sign's name, or its numbers.
pub fn said(t: Time, sign: Sign) -> String {
    match sign {
        Some(name) => name.to_string(),
        None => format!("{}/{}", t.0, t.1),
    }
}

/// What the systems before left.
pub struct Before<'a> {
    pub score: Time,
    pub staves: &'a BTreeMap<String, Time>,
    /// staff -> the sign its time is printed as, where it is (the score's under no name).
    pub signs: &'a BTreeMap<String, &'static str>,
    /// Whether the score has been seen to print a time signature on every staff.
    pub every: bool,
    /// The score's top staff.
    pub top: &'a str,
}

/// A system's times.
#[derive(Clone, Debug, PartialEq)]
pub struct Times {
    /// staff -> bar -> its time.
    pub at: Vec<Vec<Time>>,
    /// bar -> the score's time.
    pub score: Vec<Time>,
    /// Each staff's time before the system's first bar.
    pub before: Vec<Time>,
    pub every: bool,
    /// staff -> bar -> the sign its time is printed as; bar -> the score's.
    pub signs: Vec<Vec<Sign>>,
    pub score_signs: Vec<Sign>,
}

/// The time signature printed on staff `i` between `lo` and `hi`, if any.
fn printed(s: &Seen, i: usize, lo: f64, hi: f64) -> Option<Res<(Time, Sign)>> {
    let (top, bottom) = (s.staves[i].top(), s.staves[i].bottom());
    let ts: Vec<&Glyph> = s.staff_glyphs[i]
        .iter()
        // (on the staff: a multi-bar rest's count stands off it, in the same digits)
        .filter(|g| smufl::is_time(g.code) && lo <= g.x0 && g.x0 < hi)
        .filter(|g| on_staff_for_time(g, top, bottom, s.sp, s.size))
        .collect();
    let sign = (ts
        .iter()
        .find(|g| g.code == smufl::COMMON)
        .map(|_| "common"))
    .or_else(|| ts.iter().find(|g| g.code == smufl::CUT).map(|_| "cut"));
    (!ts.is_empty()).then(|| time_of(&ts).map(|t| (t, sign)))
}

/// Each staff's time through a system. A signature at the system's start stands before its first
/// note; one inside it after the last note of the bar before (perhaps before a repeat's barline)
/// and before the bar's first note. Until the score has printed a signature on every staff at
/// once, the top staff's is every staff's (a lead sheet's large signature is printed once).
pub fn read(s: &Seen, was: &Before) -> Res<Times> {
    let n = s.names.len();
    let bars = s.edges.len().saturating_sub(1);
    let before: Vec<Time> = (s.names.iter())
        .map(|name| was.staves.get(name).copied().unwrap_or(was.score))
        .collect();
    // (a staff with no time of its own so far has the score's, and its sign)
    let mut now: Vec<(Time, Sign)> = (s.names.iter().zip(&before))
        .map(|(name, t)| {
            let whose = match was.staves.contains_key(name) {
                true => name.as_str(),
                false => "",
            };
            (*t, was.signs.get(whose).copied())
        })
        .collect();
    let mut score = (was.score, was.signs.get("").copied());
    let mut every = was.every;
    let mut out = Times {
        at: vec![Vec::new(); n],
        score: Vec::new(),
        before,
        every,
        signs: vec![Vec::new(); n],
        score_signs: Vec::new(),
    };
    for b in 0..bars {
        let (lo, hi) = if b == 0 {
            (f64::MIN, s.first_event)
        } else {
            let within = |a: f64, z: f64| s.ev_x.iter().copied().filter(move |&x| a < x && x < z);
            (
                within(s.edges[b - 1], s.edges[b]).fold(s.edges[b - 1], f64::max),
                within(s.edges[b], s.edges[b + 1]).fold(s.edges[b + 1], f64::min),
            )
        };
        let mut found: Vec<Option<(Time, Sign)>> = Vec::new();
        for i in 0..n {
            found.push(match printed(s, i, lo, hi) {
                Some(t) if i == 0 => Some(t?),
                // (one that cannot be made out on a lower staff is as the top staff's)
                Some(t) => t.ok().or(found[0]),
                None => None,
            });
        }
        every |= n > 1 && found.iter().all(|f| f.is_some());
        if !every {
            if let Some(t) = found[0] {
                now.fill(t);
                score = t;
            }
        } else {
            for (i, f) in found.iter().enumerate() {
                now[i] = f.unwrap_or(now[i]);
            }
            let alike =
                (found.iter()).all(|f| f.is_some() && f.map(|t| t.0) == found[0].map(|t| t.0));
            if s.names[0] == was.top {
                score = now[0];
            } else if alike {
                // (the top staff is not printed here: a signature on every staff is the score's)
                score = now[0];
            }
        }
        for (i, t) in now.iter().enumerate() {
            out.at[i].push(t.0);
            out.signs[i].push(t.1);
        }
        out.score.push(score.0);
        out.score_signs.push(score.1);
    }
    out.every = every;
    Ok(out)
}

/// A bar's length in a time, in quarters.
pub fn bar_len(t: Time) -> Q {
    Q::new(4 * t.0, t.1)
}

/// The lines that say each staff's own time in a bar: `names` the staves in order, `now` each
/// one's time in the bar and `before` in the bar before, `score` the score's time and whether
/// the bar says it anew (`said`: the score's line makes every staff's time the score's again,
/// so a staff that keeps its own says it again). A part whose staves are all in one time says
/// it once (`time P 6/8`), else each staff its own (`time P.2 6/8`).
pub fn own_lines(
    names: &[String],
    (now, signs): (&[Time], &[Sign]),
    before: &[Time],
    score: Time,
    said: bool,
) -> Vec<String> {
    let sign = |i: usize| signs.get(i).copied().flatten();
    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
    let needs = |i: usize| match said {
        true => now[i] != score,
        false => now[i] != before[i],
    };
    let mut lines = Vec::new();
    let mut i = 0;
    while i < names.len() {
        let p = part(&names[i]);
        let end = (i..names.len())
            .find(|&j| part(&names[j]) != p)
            .unwrap_or(names.len());
        if (i..end).any(needs) {
            if (i..end).all(|j| now[j] == now[i]) {
                lines.push(format!("time {p} {}", self::said(now[i], sign(i))));
            } else {
                for j in (i..end).filter(|&j| needs(j)) {
                    lines.push(format!("time {} {}", names[j], self::said(now[j], sign(j))));
                }
            }
        }
        i = end;
    }
    lines
}

/// What the text has said of something each staff has (its key): the score's, and each staff's
/// own where it has one. The lines a bar needs for every staff to have what it should
/// (`want`), `common` being what most have: nothing where each has it already; the score's line
/// where that is no longer `common` (it makes every staff's the score's again), then the own
/// lines of those that differ; else only the own lines of those that changed. A part whose
/// staves all want one thing says it once. `say`: a line for the score (`None`) or for a part
/// or staff by name.
pub fn lines_for<T: Copy + PartialEq>(
    names: &[String],
    want: &[T],
    common: T,
    (score, own): (&mut T, &mut [Option<T>]),
    say: &dyn Fn(Option<&str>, T) -> String,
) -> Vec<String> {
    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
    let has = |i: usize, score: T, own: &[Option<T>]| own[i].unwrap_or(score);
    let mut lines = Vec::new();
    if (0..names.len()).all(|i| has(i, *score, own) == want[i]) {
        return lines;
    }
    // (said again where every staff changes to it from a key of its own: one line for all)
    let all_change = (0..names.len()).all(|i| want[i] == common && has(i, *score, own) != common);
    if common != *score || all_change {
        lines.push(say(None, common));
        *score = common;
        own.fill(None);
    }
    let mut i = 0;
    while i < names.len() {
        let p = part(&names[i]);
        let end = (i..names.len())
            .find(|&j| part(&names[j]) != p)
            .unwrap_or(names.len());
        if (i..end).any(|j| has(j, *score, own) != want[j]) {
            if (i..end).all(|j| want[j] == want[i]) {
                lines.push(say(Some(&p), want[i]));
                own[i..end].fill(Some(want[i]));
            } else {
                for j in i..end {
                    if has(j, *score, own) != want[j] {
                        lines.push(say(Some(&names[j]), want[j]));
                        own[j] = Some(want[j]);
                    }
                }
            }
        }
        i = end;
    }
    lines
}

/// How much longer the top staff's bar is than staff `i`'s: a start on staff `i`, times this, is
/// where it stands in the top staff's time (a beat of one against a beat of the other).
pub fn scales(times: &[Time]) -> Vec<Q> {
    (times.iter())
        .map(|t| bar_len(times[0]) / bar_len(*t))
        .collect()
}

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

    fn staff(top: f64) -> Staff {
        Staff {
            lines: [0.0, 10.0, 20.0, 30.0, 40.0].map(|y| top + y),
            left: 0.0,
            right: 400.0,
            breaks: Vec::new(),
        }
    }

    fn digit(d: u32, x: f64, y: f64) -> Glyph {
        Glyph {
            code: 0xE080 + d,
            x0: x,
            x1: x + 8.0,
            y,
            size: 10.0,
        }
    }

    fn sig(n: u32, d: u32, x: f64, top: f64) -> Vec<Glyph> {
        vec![digit(n, x, top + 10.0), digit(d, x, top + 30.0)]
    }

    fn seen<'a>(
        glyphs: &'a [Vec<Glyph>],
        staves: &'a [Staff],
        names: &'a [String],
        edges: &'a [f64],
    ) -> Seen<'a> {
        Seen {
            staff_glyphs: glyphs,
            staves,
            names,
            first_event: 60.0,
            edges,
            ev_x: &[100.0, 250.0],
            sp: 10.0,
            size: 10.0,
        }
    }

    #[test]
    fn a_staff_with_no_signature_where_another_changes_keeps_its_time() {
        // every staff opens in 6/8; in the second bar the voice alone turns to 2/4
        let staves = [staff(0.0), staff(100.0), staff(200.0)];
        let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
        let mut glyphs: Vec<Vec<Glyph>> =
            (0..3).map(|i| sig(6, 8, 30.0, 100.0 * i as f64)).collect();
        glyphs[0].extend(sig(2, 4, 210.0, 0.0));
        let edges = [0.0, 200.0, 400.0];
        let none = BTreeMap::new();
        let was = Before {
            score: (4, 4),
            staves: &none,
            signs: &BTreeMap::new(),
            every: false,
            top: "V",
        };
        let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
        assert!(t.every);
        assert_eq!(t.score, vec![(6, 8), (2, 4)]);
        assert_eq!(t.at[0], vec![(6, 8), (2, 4)]);
        assert_eq!(t.at[1], vec![(6, 8), (6, 8)]);
        assert_eq!(t.at[2], vec![(6, 8), (6, 8)]);
        // the score's line makes every staff's time 2/4, so the piano says its own again
        assert_eq!(
            own_lines(
                &names,
                (&[(2, 4), (6, 8), (6, 8)], &[]),
                &[(6, 8); 3],
                (2, 4),
                true
            ),
            vec!["time P 6/8"]
        );
        // and says nothing while nothing changes
        let held = [(2, 4), (6, 8), (6, 8)];
        assert!(own_lines(&names, (&held, &[]), &held, (2, 4), false).is_empty());
        // a bar of the piano's is three quarters against the voice's two
        assert_eq!(scales(&held), vec![Q::ONE, Q::new(2, 3), Q::new(2, 3)]);
    }

    #[test]
    fn a_signature_printed_once_is_every_staffs() {
        // a lead sheet's large signature on the top staff alone: the other staves take it
        let staves = [staff(0.0), staff(100.0)];
        let names: Vec<String> = ["P.1", "P.2"].map(String::from).to_vec();
        let glyphs = vec![sig(3, 4, 30.0, 0.0), Vec::new()];
        let edges = [0.0, 400.0];
        let none = BTreeMap::new();
        let was = Before {
            score: (4, 4),
            staves: &none,
            signs: &BTreeMap::new(),
            every: false,
            top: "P.1",
        };
        let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
        assert!(!t.every);
        assert_eq!(t.at, vec![vec![(3, 4)], vec![(3, 4)]]);
    }

    #[test]
    fn a_staff_in_its_own_key_says_so_once() {
        let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
        let say = |who: Option<&str>, k: i32| match who {
            Some(n) => format!("key {n} {k} major"),
            None => format!("key {k} major"),
        };
        // the score in three flats, the piano's lower staff printed with none
        let (mut score, mut own) = (-3, vec![None; 3]);
        let want = [-3, -3, 0];
        let lines = lines_for(&names, &want, -3, (&mut score, &mut own), &say);
        assert_eq!(lines, vec!["key P.2 0 major"]);
        // nothing more while nothing changes
        assert!(lines_for(&names, &want, -3, (&mut score, &mut own), &say).is_empty());
        // the score turns to two sharps, the lower staff keeps its own: it says so again
        let want = [2, 2, 0];
        let lines = lines_for(&names, &want, 2, (&mut score, &mut own), &say);
        assert_eq!(lines, vec!["key 2 major", "key P.2 0 major"]);
        assert_eq!((score, own.clone()), (2, vec![None, None, Some(0)]));
        // every staff changed inside a bar (`\\key:1` on each line): each has its own, and
        // the bars after say nothing
        own.fill(Some(1));
        assert!(lines_for(&names, &[1, 1, 1], 1, (&mut score, &mut own), &say).is_empty());
        // every staff back to the score's key: its line, once
        let lines = lines_for(&names, &[2, 2, 2], 2, (&mut score, &mut own), &say);
        assert_eq!(lines, vec!["key 2 major"]);
        assert_eq!(own, vec![None; 3]);
        // one staff alone back to it: its own line, the others' staves print nothing new
        own[0] = Some(0);
        let lines = lines_for(&names, &[2, 2, 2], 2, (&mut score, &mut own), &say);
        assert_eq!(lines, vec!["key V 2 major"]);
        // a transposing part in a key of its own
        let names: Vec<String> = ["Cl", "P.1", "P.2"].map(String::from).to_vec();
        let (mut score, mut own) = (0, vec![None; 3]);
        let lines = lines_for(&names, &[2, 0, 0], 0, (&mut score, &mut own), &say);
        assert_eq!(lines, vec!["key Cl 2 major"]);
    }

    #[test]
    fn a_time_printed_as_a_sign_is_said_by_its_name() {
        // the C on both staves, then the cut C on both in the second bar
        let staves = [staff(0.0), staff(100.0)];
        let names: Vec<String> = ["P.1", "P.2"].map(String::from).to_vec();
        let sign = |code: u32, x: f64, top: f64| Glyph {
            code,
            x0: x,
            x1: x + 8.0,
            y: top + 20.0,
            size: 10.0,
        };
        let glyphs: Vec<Vec<Glyph>> = [0.0, 100.0]
            .iter()
            .map(|&top| vec![sign(smufl::COMMON, 30.0, top), sign(smufl::CUT, 210.0, top)])
            .collect();
        let edges = [0.0, 200.0, 400.0];
        let none = BTreeMap::new();
        let was = Before {
            score: (4, 4),
            staves: &none,
            signs: &BTreeMap::new(),
            every: false,
            top: "P.1",
        };
        let t = read(&seen(&glyphs, &staves, &names, &edges), &was).unwrap();
        assert_eq!(t.score, vec![(4, 4), (2, 2)]);
        assert_eq!(t.score_signs, vec![Some("common"), Some("cut")]);
        assert_eq!(said(t.score[0], t.score_signs[0]), "common");
        assert_eq!(said(t.score[1], t.score_signs[1]), "cut");
        assert_eq!(said((3, 4), None), "3/4");
        // the system after is in the cut C still, though it prints nothing
        let signs: BTreeMap<String, &'static str> = [(String::new(), "cut")].into_iter().collect();
        let was = Before {
            score: (2, 2),
            staves: &none,
            signs: &signs,
            every: true,
            top: "P.1",
        };
        let t = read(
            &seen(&[Vec::new(), Vec::new()], &staves, &names, &edges),
            &was,
        )
        .unwrap();
        assert_eq!(t.score_signs, vec![Some("cut"), Some("cut")]);
        assert_eq!(t.signs[1], vec![Some("cut"), Some("cut")]);
    }

    #[test]
    fn one_staff_of_a_part_in_its_own_time_says_so_alone() {
        let names: Vec<String> = ["V", "P.1", "P.2"].map(String::from).to_vec();
        assert_eq!(
            own_lines(
                &names,
                (&[(2, 4), (2, 4), (6, 8)], &[]),
                &[(2, 4); 3],
                (2, 4),
                false
            ),
            vec!["time P.2 6/8"]
        );
    }
}