Skip to main content

music21/braille/
translate.rs

1//! Scores, parts and measures in braille: music21's `braille.translate`.
2
3use super::basic::word_to_braille;
4use super::lookup;
5use super::segment::{BrailleGrandSegment, Hand, SegmentOptions, find_segments};
6use crate::{
7    error::{Error, Result},
8    metadata::Metadata,
9    stream::{Stream, StreamElement, StreamKind},
10};
11
12/// How music21's braille translation is asked to write: its keyword
13/// arguments.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct BrailleOptions {
17    /// Whether the stream is written as it stands, or first given the
18    /// notation it leaves unsaid as music21's `makeNotation` gives it.
19    pub in_place: bool,
20    /// Whether each segment is written as music21's English listing of its
21    /// groupings instead of braille.
22    pub debug: bool,
23    /// The options each segment is written with.
24    pub segment: SegmentOptions,
25}
26
27/// A score, part or measure in braille, as music21's `objectToBraille`
28/// writes one: a score part by part, two piano staves side by side, a part
29/// segment by segment.
30///
31/// # Errors
32///
33/// A stream of another kind, or music that music21 cannot write.
34pub fn stream_to_braille(stream: &Stream, options: &BrailleOptions) -> Result<String> {
35    match stream.kind() {
36        StreamKind::Part | StreamKind::PartStaff => part_to_braille(stream, options),
37        StreamKind::Measure => measure_to_braille(stream, options),
38        StreamKind::Score => score_to_braille(stream, options),
39        StreamKind::Opus => {
40            let scores: Vec<String> = stream
41                .events()
42                .iter()
43                .filter_map(|event| event.element().as_stream())
44                .filter(|inner| inner.kind() == StreamKind::Score)
45                .map(|score| score_to_braille(score, options))
46                .collect::<Result<_>>()?;
47            Ok(scores.join("\n\n"))
48        }
49        _ => {
50            let staves: Vec<&Stream> = stream
51                .events()
52                .iter()
53                .filter_map(|event| event.element().as_stream())
54                .filter(|inner| inner.kind() == StreamKind::PartStaff)
55                .collect();
56            if staves.len() == 2 {
57                score_to_braille(stream, options)
58            } else {
59                Err(Error::Notation(
60                    "Stream cannot be translated to Braille.".to_string(),
61                ))
62            }
63        }
64    }
65}
66
67/// A score in braille: its metadata, then each part, a piano's two staves
68/// together: music21's `scoreToBraille`.
69///
70/// # Errors
71///
72/// Music music21 cannot write.
73pub fn score_to_braille(score: &Stream, options: &BrailleOptions) -> Result<String> {
74    let mut lines = Vec::new();
75    if let Some(metadata) = score.metadata() {
76        lines.push(metadata_to_string(metadata, !options.debug)?);
77    }
78    let mut pending: Option<Stream> = None;
79    let mut first_leaf = 0;
80    for event in score.events() {
81        let leaves = match event.element() {
82            StreamElement::Stream(inner) => inner.leaves().len(),
83            _ => 1,
84        };
85        let start = first_leaf;
86        first_leaf += leaves;
87        let Some(part) = event.element().as_stream() else {
88            continue;
89        };
90        let part = &with_own_spanners(score, part, start);
91        match part.kind() {
92            StreamKind::PartStaff => {
93                if let Some(upper) = pending.take() {
94                    lines.push(keyboard_parts_to_braille(&upper, part, options)?);
95                } else {
96                    pending = Some(part.clone());
97                }
98            }
99            StreamKind::Part => {
100                if let Some(alone) = pending.take() {
101                    lines.push(part_to_braille(&alone, options)?);
102                }
103                lines.push(part_to_braille(part, options)?);
104            }
105            _ => {}
106        }
107    }
108    if let Some(alone) = pending {
109        lines.push(part_to_braille(&alone, options)?);
110    }
111    Ok(lines.join("\n"))
112}
113
114/// A part of a score with the spanners music21 keeps in it: those of the
115/// score that start and end among the part's elements, braille reading a
116/// slur by its ends alone. music21 keeps every spanner of a part written on
117/// several staves on its first staff, so a later staff has none. `start` is
118/// where the part's leaves start among the score's.
119fn with_own_spanners(score: &Stream, part: &Stream, start: usize) -> Stream {
120    let mut part = part.clone();
121    let later_staff = part.kind() == StreamKind::PartStaff
122        && part
123            .id()
124            .and_then(|id| id.rsplit_once("-Staff"))
125            .is_some_and(|(_, number)| number != "1");
126    if later_staff {
127        return part;
128    }
129    let end = start + part.leaves().len();
130    let inside = |place: Option<&Option<usize>>| {
131        place.is_some_and(|place| place.is_some_and(|place| (start..end).contains(&place)))
132    };
133    for spanner in score.spanners() {
134        let places = spanner.spanned();
135        if inside(places.first()) && inside(places.last()) {
136            let mut own = spanner.clone();
137            let moved: Vec<Option<usize>> =
138                (0..end).map(|place| place.checked_sub(start)).collect();
139            own.move_places(&moved);
140            part.add_spanner(own);
141        }
142    }
143    part
144}
145
146/// A score's metadata, a line each sorted, as `Name: value` or its braille:
147/// music21's `metadataToString`.
148///
149/// # Errors
150///
151/// A character braille has no sign for.
152pub fn metadata_to_string(metadata: &Metadata, braille: bool) -> Result<String> {
153    let mut lines = Vec::new();
154    for (unique_name, value) in metadata.all() {
155        if unique_name == "software" {
156            continue;
157        }
158        let Some(namespace) = crate::metadata::namespace_name(unique_name) else {
159            continue;
160        };
161        if namespace.starts_with("m21FileInfo:") {
162            continue;
163        }
164        let words = split_camel_case(unique_name);
165        let mut line = format!(
166            "{}: {}",
167            crate::common::stringtools::title_case(&words.join(" ")),
168            value.text()
169        );
170        if braille {
171            let written: Vec<String> = line
172                .split_whitespace()
173                .map(|word| word_to_braille(word, false))
174                .collect::<Result<_>>()?;
175            line = written.join(&lookup::alphabet(' ').unwrap_or_default());
176        }
177        lines.push(line);
178    }
179    lines.sort();
180    Ok(lines.join("\n"))
181}
182
183/// The words of a camel-cased name, as music21 finds them with
184/// `([A-Z]*[a-z]+)`.
185fn split_camel_case(name: &str) -> Vec<String> {
186    let characters: Vec<char> = name.chars().collect();
187    let mut words = Vec::new();
188    let mut index = 0;
189    while index < characters.len() {
190        let start = index;
191        let mut upper_end = index;
192        while upper_end < characters.len() && characters[upper_end].is_ascii_uppercase() {
193            upper_end += 1;
194        }
195        let mut lower_end = upper_end;
196        while lower_end < characters.len() && characters[lower_end].is_ascii_lowercase() {
197            lower_end += 1;
198        }
199        if lower_end > upper_end {
200            words.push(characters[start..lower_end].iter().collect());
201            index = lower_end;
202        } else {
203            index = start + 1;
204        }
205    }
206    words
207}
208
209/// A copy of a part with the notation it leaves unsaid made, as music21's
210/// `makeNotation(cautionaryNotImmediateRepeat=False)` makes it.
211fn notated(part: &Stream, options: &BrailleOptions) -> Result<Stream> {
212    let mut part = part.clone();
213    if !options.in_place {
214        crate::makenotation::make_part_notation_keeping_spanners(&mut part, false)?;
215    }
216    Ok(part)
217}
218
219/// A part in braille, segment by segment: music21's `partToBraille`.
220///
221/// # Errors
222///
223/// Music music21 cannot write.
224pub fn part_to_braille(part: &Stream, options: &BrailleOptions) -> Result<String> {
225    let part = notated(part, options)?;
226    let mut segments = find_segments(&part, None, options.segment);
227    let mut written = Vec::new();
228    for segment in &mut segments {
229        let braille = segment.transcribe()?;
230        written.push(if options.debug {
231            segment.english()
232        } else {
233            braille
234        });
235    }
236    Ok(written.join("\n"))
237}
238
239/// A measure in braille, as the one measure of a part with no heading or
240/// measure number unless asked: music21's `measureToBraille`.
241///
242/// # Errors
243///
244/// Music music21 cannot write.
245pub fn measure_to_braille(measure: &Stream, options: &BrailleOptions) -> Result<String> {
246    let mut part = Stream::with_kind(StreamKind::Part);
247    part.push(measure.clone());
248    if !options.in_place {
249        // music21's `Measure.makeNotation(cautionaryNotImmediateRepeat=False)`,
250        // which is the *measure's* notation and not a part's: running a
251        // part's steps over a lone measure cuts it into measures again and
252        // the notes end up a level deeper, where nothing transcribing a
253        // part looks for them.
254        crate::makenotation::keeping_spanners(
255            &mut part,
256            crate::makenotation::Kept::Retained,
257            &mut crate::makenotation::make_measure_notation,
258        )?;
259    }
260    part_to_braille(
261        &part,
262        &BrailleOptions {
263            in_place: true,
264            ..*options
265        },
266    )
267}
268
269/// A piano's two staves in braille, side by side measure by measure:
270/// music21's `keyboardPartsToBraille`.
271///
272/// # Errors
273///
274/// Music music21 cannot write.
275pub fn keyboard_parts_to_braille(
276    upper: &Stream,
277    lower: &Stream,
278    options: &BrailleOptions,
279) -> Result<String> {
280    let upper = notated(upper, options)?;
281    let lower = notated(lower, options)?;
282    let right = find_segments(&upper, Some(Hand::Right), options.segment);
283    let left = find_segments(&lower, Some(Hand::Left), options.segment);
284    let mut written = Vec::new();
285    for (right, left) in right.into_iter().zip(left) {
286        let mut grand = BrailleGrandSegment {
287            groupings: right.groupings.into_iter().chain(left.groupings).collect(),
288            line_length: options.segment.max_line_length,
289            right_contexts: right.contexts,
290            left_contexts: left.contexts,
291        };
292        let braille = grand.transcribe()?;
293        written.push(if options.debug {
294            grand.english()
295        } else {
296            braille
297        });
298    }
299    Ok(written.join("\n"))
300}
301
302/// An element that is not a stream, in braille as the one element of a
303/// measure: music21's `objectToBraille` given one.
304///
305/// # Errors
306///
307/// Music music21 cannot write.
308pub fn element_to_braille(element: StreamElement, options: &BrailleOptions) -> Result<String> {
309    if element.as_stream().is_some() {
310        return Err(Error::Notation(
311            "Stream cannot be translated to Braille.".to_string(),
312        ));
313    }
314    let mut measure = Stream::with_kind(StreamKind::Measure);
315    measure.push(element);
316    let mut part = Stream::with_kind(StreamKind::Part);
317    part.push(measure);
318    let mut segment = options.segment;
319    segment.show_first_measure_number = false;
320    segment.show_heading = false;
321    part_to_braille(
322        &part,
323        &BrailleOptions {
324            in_place: true,
325            segment,
326            ..*options
327        },
328    )
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::braille::SegmentDivision;
335    use crate::defaults::IntegerType;
336    use crate::{Duration, KeySignature, Note, StreamKind};
337
338    /// Two measures of one whole note, a key of two sharps in the first.
339    fn staff(name: &str) -> Stream {
340        let mut staff = Stream::with_kind(StreamKind::PartStaff);
341        for number in 1..=2 {
342            let mut measure = Stream::with_kind(StreamKind::Measure);
343            measure.set_number(number);
344            if number == 1 {
345                measure.push(KeySignature::new(2));
346            }
347            let note = Note::from_name(name)
348                .unwrap()
349                .with_duration(Duration::new(4.0).unwrap());
350            measure.push(note);
351            staff.insert(4.0 * (number - 1) as f64, measure);
352        }
353        staff
354    }
355
356    /// music21 36d9144c0: a key signature standing alone heads the two
357    /// hands as a key signature, where it used to be read as a meter.
358    #[test]
359    fn a_lone_key_signature_heads_the_keyboard() {
360        let written =
361            keyboard_parts_to_braille(&staff("D5"), &staff("D3"), &BrailleOptions::default())
362                .unwrap();
363        assert_eq!(written, "⠀⠀⠩⠩⠀⠀\n⠁⠀⠨⠜⠨⠵\n⠀⠀⠸⠜⠸⠵");
364    }
365
366    /// music21's `getRawSegments` example: `3/4 c4 c c e e e g g g c'2.`
367    /// with a division in a measure, transcribed.
368    fn divided(measure: IntegerType, offset: f64, division: SegmentDivision) -> String {
369        let mut part =
370            crate::tinynotation::from_tiny_notation("3/4 c4 c c e e e g g g c'2.").unwrap();
371        crate::makenotation::make_notation(&mut part).unwrap();
372        for event in part.events_mut() {
373            let StreamElement::Stream(held) = event.element_mut() else {
374                continue;
375            };
376            if held.number() != measure {
377                continue;
378            }
379            held.insert(offset, division);
380        }
381        stream_to_braille(&part, &BrailleOptions::default()).unwrap()
382    }
383
384    /// A division starts a new segment there, in the middle of a measure
385    /// or not at all where the segment is empty; an optional one only once
386    /// the segment holds 48 elements.
387    #[test]
388    fn a_segment_division_divides_the_segment() {
389        let whole = "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠉⠲⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠼⠁⠀⠐⠹⠹⠹⠀⠫⠫⠫⠀⠳⠳⠳⠀⠨⠝⠄⠣⠅";
390        assert_eq!(
391            divided(2, 1.0, SegmentDivision::Required),
392            "⠀⠀⠀⠼⠉⠲⠀⠀⠀⠀\n⠼⠁⠀⠐⠹⠹⠹⠀⠫⠐\n⠼⠃⠄⠀⠐⠫⠫⠀⠳⠳⠳⠀⠨⠝⠄⠣⠅"
393        );
394        assert_eq!(divided(1, 1.0, SegmentDivision::Optional), whole);
395        assert_eq!(divided(1, 0.0, SegmentDivision::Required), whole);
396    }
397
398    /// One measure of a whole note, with a key of two sharps and four-four
399    /// where `signed`.
400    fn one_measure(name: &str, signed: bool) -> Stream {
401        let mut staff = Stream::with_kind(StreamKind::PartStaff);
402        let mut measure = Stream::with_kind(StreamKind::Measure);
403        measure.set_number(1);
404        if signed {
405            measure.push(KeySignature::new(2));
406            measure.push(crate::TimeSignature::new(4, 4).unwrap());
407        }
408        measure.push(
409            Note::from_name(name)
410                .unwrap()
411                .with_duration(Duration::new(4.0).unwrap()),
412        );
413        staff.insert(0.0, measure);
414        staff
415    }
416
417    /// The signatures of either hand alone head the two hands.
418    #[test]
419    fn either_hands_signatures_head_the_keyboard() {
420        for left_signed in [false, true] {
421            let written = keyboard_parts_to_braille(
422                &one_measure("C5", !left_signed),
423                &one_measure("C3", left_signed),
424                &BrailleOptions::default(),
425            )
426            .unwrap();
427            let heading = written.lines().next().unwrap().trim_matches('\u{2800}');
428            assert_eq!(heading, "⠩⠩⠼⠙⠲");
429        }
430    }
431
432    /// Four eighths, each with `counts` staccatos, as one measure of a
433    /// part, cut into segments.
434    fn staccato_counts(counts: &[usize]) -> Vec<usize> {
435        use crate::articulations::{Articulation, ArticulationKind};
436        let mut part = Stream::with_kind(StreamKind::Part);
437        let mut measure = Stream::with_kind(StreamKind::Measure);
438        measure.set_number(1);
439        for &count in counts {
440            let mut note = Note::from_name("C4")
441                .unwrap()
442                .with_duration(Duration::new(0.5).unwrap());
443            for _ in 0..count {
444                note.articulations_mut()
445                    .push(Articulation::of_kind(ArticulationKind::Staccato));
446            }
447            measure.push(note);
448        }
449        part.insert(0.0, measure);
450        let segments = find_segments(&part, None, SegmentOptions::default());
451        segments
452            .iter()
453            .flat_map(|segment| segment.groupings.values())
454            .flat_map(|grouping| &grouping.elements)
455            .filter_map(|element| match &element.element {
456                StreamElement::Note(note) => Some(note.articulations().len()),
457                _ => None,
458            })
459            .collect()
460    }
461
462    /// Four staccatos in a row: two on the first note, none on those
463    /// between and one on the last; three in a row are left as they are.
464    #[test]
465    fn four_staccatos_in_a_row_are_doubled_on_the_first() {
466        assert_eq!(staccato_counts(&[1, 1, 1, 1]), [2, 0, 0, 1]);
467        assert_eq!(staccato_counts(&[1, 2, 1, 1]), [2, 0, 0, 1]);
468        assert_eq!(staccato_counts(&[1, 1, 1]), [1, 1, 1]);
469    }
470
471    /// A chord's direction set by a clef carries into the next segment;
472    /// with no clef, chords are written from the top down.
473    #[test]
474    fn a_clefs_chord_direction_carries_into_the_next_segment() {
475        for (clef, expected) in [
476            (Some(crate::Clef::treble()), true),
477            (Some(crate::Clef::bass()), false),
478            (None, true),
479        ] {
480            let mut part = Stream::with_kind(StreamKind::Part);
481            for number in 1..=3 {
482                let mut measure = Stream::with_kind(StreamKind::Measure);
483                measure.set_number(number);
484                if number == 1
485                    && let Some(clef) = &clef
486                {
487                    measure.push(clef.clone());
488                }
489                if number == 3 {
490                    measure.push(SegmentDivision::Required);
491                }
492                measure.push(
493                    crate::Chord::new("C3 E3 G3")
494                        .unwrap()
495                        .with_duration(Duration::new(4.0).unwrap()),
496                );
497                part.insert(4.0 * f64::from(number - 1), measure);
498            }
499            let segments = find_segments(&part, None, SegmentOptions::default());
500            assert_eq!(segments.len(), 2);
501            for segment in &segments {
502                for (key, grouping) in &segment.groupings {
503                    if key.affinity == crate::braille::segment::Affinity::NoteGrouping {
504                        assert_eq!(grouping.descending_chords, Some(expected));
505                    }
506                }
507            }
508        }
509    }
510}