Skip to main content

fm_transcribe/
rewrite.rs

1//! A score's bars rewritten: a staff's lines in a bar replaced by others (a person's answer to a
2//! reader's question about the bar, or a bar typed in). The text is not compiled here: a rewrite
3//! that does not fit (a voice short of its bar, a tie that no longer lands) is for
4//! [`crate::compile`] to say.
5
6use anyhow::{bail, Result};
7
8/// One staff's lines for one bar: `staff` as the `.fmn` names it (`P.2`), `bar` the bar's label
9/// as its `bar` line has it, `fmn` the lines (`P.2: ...`, `P.2/2: ...`), one a voice.
10#[derive(Clone, Debug, PartialEq, Eq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct BarText {
13    pub staff: String,
14    pub bar: String,
15    pub fmn: String,
16}
17
18/// Whether `line` is one of `staff`'s voice lines (`staff:` or `staff/2:`), not its words.
19fn is_voice_of(line: &str, staff: &str) -> bool {
20    let Some(rest) = line.strip_prefix(staff) else {
21        return false;
22    };
23    if let Some(r) = rest.strip_prefix(':') {
24        return r.is_empty() || r.starts_with([' ', '\t']);
25    }
26    match rest.strip_prefix('/') {
27        Some(r) => {
28            let digits = r.chars().take_while(|c| c.is_ascii_digit()).count();
29            digits > 0 && r[digits..].starts_with(':')
30        }
31        None => false,
32    }
33}
34
35/// Whether `line` is a staff's voice line at all (`X:`, `P.1/2:`), words and directives aside.
36fn is_voice(line: &str) -> bool {
37    let Some(colon) = line.find(':') else {
38        return false;
39    };
40    let name = &line[..colon];
41    !name.is_empty()
42        && !name.contains(char::is_whitespace)
43        && is_voice_of(line, name.split('/').next().unwrap_or(name))
44}
45
46/// Whether `line` opens bar `bar` (`bar 12`, `bar 12 system`, ...).
47fn opens(line: &str, bar: &str) -> bool {
48    line.strip_prefix("bar ")
49        .and_then(|r| r.strip_prefix(bar))
50        .is_some_and(|r| r.is_empty() || r.starts_with([' ', '\t']))
51}
52
53/// `fmn` with each of `rewrite`'s staves' lines in its bar replaced by the given lines, in the
54/// place the old ones stood (after the bar's other staves' lines where the staff had none). The
55/// staff's words and the bar's other lines are kept. Fails where a bar is not in the text or a
56/// given line is not one of its staff's.
57pub fn replace_bars(fmn: &str, rewrite: &[BarText]) -> Result<String> {
58    let crlf = fmn.contains("\r\n");
59    let mut lines: Vec<String> = fmn.lines().map(str::to_string).collect();
60    for r in rewrite {
61        let new: Vec<String> = (r.fmn.lines())
62            .map(|l| l.trim_end().to_string())
63            .filter(|l| !l.is_empty())
64            .collect();
65        if new.is_empty() {
66            bail!("bar {}, {}: no lines to put in", r.bar, r.staff);
67        }
68        if let Some(bad) = new.iter().find(|l| !is_voice_of(l, &r.staff)) {
69            bail!(
70                "bar {}, {}: {bad:?} is not a line of {}",
71                r.bar,
72                r.staff,
73                r.staff
74            );
75        }
76        let Some(start) = lines.iter().position(|l| opens(l, &r.bar)) else {
77            bail!("the score has no bar {}", r.bar);
78        };
79        let end = (start + 1..lines.len())
80            .find(|&k| lines[k].starts_with("bar "))
81            .unwrap_or(lines.len());
82        let own: Vec<usize> = (start + 1..end)
83            .filter(|&k| is_voice_of(&lines[k], &r.staff))
84            .collect();
85        let at = match own.first() {
86            Some(&k) => k,
87            None => (start + 1..end)
88                .rev()
89                .find(|&k| is_voice(&lines[k]))
90                .map_or(start + 1, |k| k + 1),
91        };
92        for &k in own.iter().rev() {
93            lines.remove(k);
94        }
95        for (n, l) in new.into_iter().enumerate() {
96            lines.insert(at + n, l);
97        }
98    }
99    let nl = if crlf { "\r\n" } else { "\n" };
100    let mut out = lines.join(nl);
101    if fmn.ends_with('\n') {
102        out.push_str(nl);
103    }
104    Ok(out)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    const SCORE: &str = "title: T\n\npart P \"Piano\" piano\n\nkey 0 major\ntime 4/4\nclef P.1 treble\nclef P.2 bass\n\nbar 1\nP.1: c5/4 d5/4 e5/4 f5/4\nP.1/2: R\nP.2: R\n\nbar 2 system\nP.1: R\nP.2: c3/1\n";
112
113    fn bar(staff: &str, bar: &str, fmn: &str) -> BarText {
114        BarText {
115            staff: staff.into(),
116            bar: bar.into(),
117            fmn: fmn.into(),
118        }
119    }
120
121    #[test]
122    fn a_staffs_lines_are_replaced_in_their_place_and_its_other_voices_dropped() {
123        let out = replace_bars(SCORE, &[bar("P.1", "1", "P.1: g4/1")]).unwrap();
124        assert!(out.contains("bar 1\nP.1: g4/1\nP.2: R\n"), "{out}");
125        assert!(!out.contains("P.1/2"));
126        // the other bar is untouched
127        assert!(out.contains("bar 2 system\nP.1: R\nP.2: c3/1\n"));
128        crate::compile(&out).unwrap();
129    }
130
131    #[test]
132    fn a_bar_with_a_system_mark_takes_two_voices() {
133        let out = replace_bars(SCORE, &[bar("P.1", "2", "P.1: c5/2 d5/2\nP.1/2: e4/1")]).unwrap();
134        assert!(
135            out.contains("bar 2 system\nP.1: c5/2 d5/2\nP.1/2: e4/1\nP.2: c3/1\n"),
136            "{out}"
137        );
138        crate::compile(&out).unwrap();
139    }
140
141    #[test]
142    fn a_staff_with_no_line_in_the_bar_goes_after_the_others() {
143        let text = SCORE.replace("P.2: c3/1\n", "");
144        let out = replace_bars(&text, &[bar("P.2", "2", "P.2: c3/2 g2/2")]).unwrap();
145        assert!(
146            out.ends_with("bar 2 system\nP.1: R\nP.2: c3/2 g2/2\n"),
147            "{out}"
148        );
149    }
150
151    #[test]
152    fn words_stay_and_a_staff_named_like_another_is_not_taken_for_it() {
153        let text = "part V \"Voice\" voice\npart V2 \"Alto\" voice\n\nbar 1\nV: c5/1\nV lyrics: la\nV2: a4/1\n";
154        let out = replace_bars(text, &[bar("V", "1", "V: d5/1")]).unwrap();
155        assert_eq!(
156            out,
157            "part V \"Voice\" voice\npart V2 \"Alto\" voice\n\nbar 1\nV: d5/1\nV lyrics: la\nV2: a4/1\n"
158        );
159    }
160
161    #[test]
162    fn a_missing_bar_or_another_staffs_line_is_refused() {
163        assert!(replace_bars(SCORE, &[bar("P.1", "9", "P.1: R")]).is_err());
164        assert!(replace_bars(SCORE, &[bar("P.1", "1", "P.2: R")]).is_err());
165        assert!(replace_bars(SCORE, &[bar("P.1", "1", "")]).is_err());
166        // bar 1 is not bar 10
167        assert!(replace_bars(SCORE, &[bar("P.1", "10", "P.1: R")]).is_err());
168    }
169
170    #[test]
171    fn crlf_text_stays_crlf() {
172        let text = SCORE.replace('\n', "\r\n");
173        let out = replace_bars(&text, &[bar("P.2", "1", "P.2: c3/1")]).unwrap();
174        assert!(out.contains("bar 1\r\nP.1: c5/4 d5/4 e5/4 f5/4\r\nP.1/2: R\r\nP.2: c3/1\r\n"));
175        assert!(!out.replace("\r\n", "").contains('\n'));
176    }
177}