Skip to main content

music21/braille/
segment.rs

1//! A part cut into segments of braille music, measure by measure and
2//! grouping by grouping: music21's `braille.segment` and
3//! `braille.noteGrouping`.
4//!
5//! music21 marks the notes of the part it transcribes with attributes for
6//! the time it transcribes them -- the slurs over them, how their beams
7//! read, a full measure's rest -- and writes each sign's English onto the
8//! element. Here each element of a segment is a [`BrailleElement`] that
9//! carries those beside a copy of the element.
10
11use std::collections::{BTreeMap, VecDeque};
12
13use super::SegmentDivision;
14use super::basic::{
15    self, NoteContext, Transcription, barline_to_braille, chord_symbol_to_braille,
16    chord_to_braille, clef_to_braille, dynamic_to_braille, note_to_braille, number_to_braille,
17    rest_to_braille, text_expression_to_braille, transcribe_heading, transcribe_signatures,
18    yield_dots,
19};
20use super::lookup::{self, symbol};
21use super::text::{BrailleKeyboard, BrailleText};
22use crate::{
23    defaults::{FloatType, IntegerType},
24    duration::Duration,
25    error::{Error, Result},
26    makenotation::op_frac,
27    meter::TimeSignature,
28    note::Note,
29    pitch::Pitch,
30    rest::Rest,
31    stream::{Stream, StreamElement, StreamKind},
32};
33
34/// Which kind of grouping an element goes in, in the order a measure's
35/// groupings are written: music21's `Affinity`.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub enum Affinity {
38    /// Key and time signatures.
39    Signature = 3,
40    /// Tempo words.
41    TempoText = 4,
42    /// A metronome mark.
43    MetronomeMark = 5,
44    /// Text of more than one word.
45    LongTextExpression = 6,
46    /// Voices written in accord.
47    Inaccord = 7,
48    /// The first half of a group of notes split to fit a line.
49    SplitNoteGroupingA = 8,
50    /// Notes, rests, chords, dynamics, clefs, short texts.
51    NoteGrouping = 9,
52    /// The second half of a split group, and barlines.
53    SplitNoteGroupingB = 10,
54}
55
56impl Affinity {
57    /// music21's name for a grouping of this kind.
58    pub fn name(self) -> &'static str {
59        match self {
60            Self::Signature => "Signature Grouping",
61            Self::TempoText => "Tempo Text Grouping",
62            Self::MetronomeMark => "Metronome Mark Grouping",
63            Self::LongTextExpression => "Long Text Expression Grouping",
64            Self::Inaccord => "Inaccord Grouping",
65            Self::NoteGrouping => "Note Grouping",
66            Self::SplitNoteGroupingA => "Split Note Grouping A",
67            Self::SplitNoteGroupingB => "Split Note Grouping B",
68        }
69    }
70}
71
72/// The hand a keyboard part is played by.
73#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub enum Hand {
75    /// The left hand: music21's `'left'`.
76    Left,
77    /// The right hand: music21's `'right'`.
78    Right,
79}
80
81/// Where a grouping stands: its measure, its place among the measure's
82/// groupings, its kind and its hand: music21's `SegmentKey`.
83#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
84pub struct SegmentKey {
85    /// The measure's number.
86    pub measure: IntegerType,
87    /// Which run of groupings in the measure, counting from nought.
88    pub ordinal: usize,
89    /// The kind of grouping.
90    pub affinity: Affinity,
91    /// The hand, at a keyboard.
92    pub hand: Option<Hand>,
93}
94
95/// An element of a segment with what music21 keeps on it while
96/// transcribing: where it stands, its affinity, how it sorts, its English,
97/// its note context, and a key signature's predecessor.
98#[derive(Clone, Debug)]
99pub struct BrailleElement {
100    /// A copy of the element, changed as music21 changes it.
101    pub element: StreamElement,
102    /// Its offset in its measure or voice.
103    pub offset: FloatType,
104    /// Its affinity.
105    pub affinity: Affinity,
106    /// How it sorts among elements at its offset: music21's
107    /// `classSortOrder` as braille sets it.
108    pub sort_order: i32,
109    /// Its English: music21's `editorial.brailleEnglish`.
110    pub english: Option<Vec<String>>,
111    /// Its slurs and beams, for a note.
112    pub context: NoteContext,
113    /// The key signature before it, for a key signature: music21's
114    /// `outgoingKeySig`.
115    pub outgoing_key: Option<Option<IntegerType>>,
116    /// Where its leaves start in the part, to find what music21 marked on
117    /// it.
118    pub leaf: usize,
119    /// For a voice, the English of each element it holds once written,
120    /// nothing for one not written.
121    pub voice_english: Vec<Option<Vec<String>>>,
122}
123
124/// A grouping of elements written together: music21's
125/// `BrailleElementGrouping`.
126#[derive(Clone, Debug)]
127pub struct BrailleElementGrouping {
128    /// The elements.
129    pub elements: Vec<BrailleElement>,
130    /// The key signature in force, as sharps.
131    pub key_signature: Option<IntegerType>,
132    /// The time signature in force.
133    pub time_signature: TimeSignature,
134    /// Whether chords are written from the top down; nothing reads as
135    /// upward, as in music21.
136    pub descending_chords: Option<bool>,
137    /// Whether clefs are written.
138    pub show_clef_signs: bool,
139    /// Whether a fingering's upper choice is written first.
140    pub upper_first_in_note_fingering: bool,
141    /// Whether the grouping ends with a music hyphen.
142    pub with_hyphen: bool,
143    /// How many times it is repeated after itself.
144    pub num_repeats: usize,
145}
146
147impl Default for BrailleElementGrouping {
148    fn default() -> Self {
149        Self {
150            elements: Vec::new(),
151            key_signature: Some(0),
152            time_signature: TimeSignature::new(4, 4).expect("4/4 is a meter"),
153            descending_chords: Some(true),
154            show_clef_signs: false,
155            upper_first_in_note_fingering: true,
156            with_hyphen: false,
157            num_repeats: 0,
158        }
159    }
160}
161
162/// music21's `repr` of an element, as a segment's English shows one it has
163/// not transcribed.
164pub(crate) fn element_repr(element: &StreamElement) -> String {
165    match element {
166        StreamElement::Note(note) => format!("<music21.note.Note {}>", note.pitch().name()),
167        StreamElement::Rest(rest) => {
168            let duration = rest.duration();
169            let name = duration.full_name().to_lowercase();
170            let text = if name.chars().count() < 15 {
171                name.replace(' ', "-")
172            } else {
173                let length = duration.quarter_length();
174                if length.fract() == 0.0 {
175                    format!("{}ql", length as i64)
176                } else {
177                    format!("{}ql", crate::statistics::python_repr(length))
178                }
179            };
180            format!("<music21.note.Rest {text}>")
181        }
182        StreamElement::Chord(chord) => {
183            let names: Vec<String> = chord
184                .pitches()
185                .iter()
186                .map(Pitch::name_with_octave)
187                .collect();
188            format!("<music21.chord.Chord {}>", names.join(" "))
189        }
190        StreamElement::Clef(clef) => format!("<music21.clef.{}>", clef.kind().class_name()),
191        StreamElement::Barline(barline) => {
192            format!("<music21.bar.Barline type={}>", barline.bar_type().as_str())
193        }
194        StreamElement::Dynamic(dynamic) => {
195            format!("<music21.dynamics.Dynamic {}>", dynamic.value())
196        }
197        StreamElement::TextExpression(text) => {
198            let content = text.content();
199            let shown = if content.chars().count() >= 13 {
200                format!("{}...", content.chars().take(10).collect::<String>())
201            } else {
202                content.to_string()
203            };
204            format!(
205                "<music21.expressions.TextExpression {}>",
206                crate::common::stringtools::python_str_repr(&shown)
207            )
208        }
209        StreamElement::TempoText(tempo) => tempo.music21_repr(),
210        StreamElement::KeySignature(signature) if signature.is_non_traditional() => {
211            "<music21.key.KeySignature of pitches: []>".to_string()
212        }
213        StreamElement::KeySignature(signature) => format!(
214            "<music21.key.KeySignature of {}>",
215            sharps_description(signature.sharps())
216        ),
217        StreamElement::Key(key) => {
218            // A key's `str` is its tonic and mode alone.
219            let tonic = music21_pitch_name(key.tonic_pitch());
220            let tonic = if key.mode() == "minor" {
221                tonic.to_lowercase()
222            } else {
223                tonic
224            };
225            format!("{tonic} {}", key.mode())
226        }
227        StreamElement::MetronomeMark(mark) => mark.music21_repr(),
228        StreamElement::Unpitched(unpitched) => match unpitched
229            .stored_instrument()
230            .and_then(|instrument| instrument.name())
231        {
232            Some(name) => format!(
233                "<music21.note.Unpitched {}>",
234                crate::common::stringtools::python_str_repr(name)
235            ),
236            None => "<music21.note.Unpitched>".to_string(),
237        },
238        StreamElement::PercussionChord(chord) => {
239            let members: Vec<String> = chord
240                .members()
241                .iter()
242                .map(|member| match member {
243                    crate::percussion::PercussionNote::Note(note) => {
244                        note.pitch().name_with_octave()
245                    }
246                    crate::percussion::PercussionNote::Unpitched(unpitched) => match unpitched
247                        .stored_instrument()
248                        .and_then(|instrument| instrument.name())
249                    {
250                        Some(name) => name.to_string(),
251                        None => format!("unpitched[{}]", unpitched.display_name()),
252                    },
253                })
254                .collect();
255            format!(
256                "<music21.percussion.PercussionChord [{}]>",
257                members.join(" ")
258            )
259        }
260        StreamElement::TimeSignature(meter) => format!(
261            "<music21.meter.TimeSignature {}/{}>",
262            meter.numerator(),
263            meter.denominator()
264        ),
265        StreamElement::Stream(stream) => match stream.id() {
266            Some(id) => format!("<music21.stream.{:?} {id}>", stream.kind()),
267            None => format!("<music21.stream.{:?}>", stream.kind()),
268        },
269        other => format!("<music21.{other:?}>"),
270    }
271}
272
273/// A pitch's name as music21 spells it, a flat as `-`.
274pub(crate) fn music21_pitch_name(pitch: &Pitch) -> String {
275    let modifier = match pitch
276        .written_accidental()
277        .map(|accidental| accidental.name())
278    {
279        Some("flat") => "-",
280        Some("double-flat") => "--",
281        Some("sharp") => "#",
282        Some("double-sharp") => "##",
283        _ => "",
284    };
285    format!("{}{modifier}", pitch.step().as_char())
286}
287
288/// How music21 describes a key signature of so many sharps.
289fn sharps_description(sharps: IntegerType) -> String {
290    match sharps {
291        0 => "no sharps or flats".to_string(),
292        1 => "1 sharp".to_string(),
293        -1 => "1 flat".to_string(),
294        sharps if sharps > 0 => format!("{sharps} sharps"),
295        sharps => format!("{} flats", -sharps),
296    }
297}
298
299/// The affinity and sort order braille gives an element, or nothing for one
300/// it cannot write: music21's `setAffinityCode`.
301fn affinity_of(element: &StreamElement) -> Option<(Affinity, i32)> {
302    Some(match element {
303        StreamElement::Note(_) | StreamElement::Rest(_) | StreamElement::Chord(_) => {
304            (Affinity::NoteGrouping, 10)
305        }
306        StreamElement::ChordSymbol(_) => (Affinity::NoteGrouping, 10),
307        StreamElement::Dynamic(_) => (Affinity::NoteGrouping, 9),
308        StreamElement::Clef(_) => (Affinity::NoteGrouping, 7),
309        StreamElement::Barline(_) => (Affinity::SplitNoteGroupingB, 0),
310        StreamElement::KeySignature(_) | StreamElement::Key(_) => (Affinity::Signature, 1),
311        StreamElement::TimeSignature(_) => (Affinity::Signature, 2),
312        StreamElement::TempoText(_) => (Affinity::TempoText, 3),
313        StreamElement::MetronomeMark(_) => (Affinity::MetronomeMark, 4),
314        StreamElement::Stream(inner) if inner.kind() == StreamKind::Voice => {
315            (Affinity::Inaccord, 10)
316        }
317        // music21's `BrailleTranscriptionHelper` takes no affinity; the
318        // segmenting reads it before asking for one.
319        StreamElement::BrailleSegmentDivision(_) => (Affinity::NoteGrouping, -100),
320        StreamElement::TextExpression(text) => {
321            if text.content().split_whitespace().count() > 1 {
322                (Affinity::LongTextExpression, 8)
323            } else {
324                (Affinity::NoteGrouping, 8)
325            }
326        }
327        _ => return None,
328    })
329}
330
331/// The affinity braille groups an element by and the order it sorts in
332/// among elements at its place, nothing for one braille does not write:
333/// music21's `setAffinityCode`.
334pub fn affinity_code(element: &StreamElement) -> Option<(Affinity, i32)> {
335    affinity_of(element)
336}
337
338/// Whether music21 counts an element a `GeneralNote`.
339fn is_general_note(element: &StreamElement) -> bool {
340    matches!(
341        element,
342        StreamElement::Note(_)
343            | StreamElement::Rest(_)
344            | StreamElement::Chord(_)
345            | StreamElement::ChordSymbol(_)
346            | StreamElement::Unpitched(_)
347            | StreamElement::PercussionChord(_)
348    )
349}
350
351/// Whether music21 counts an element a `NotRest`: a stream's `notes`.
352fn is_not_rest(element: &StreamElement) -> bool {
353    matches!(
354        element,
355        StreamElement::Note(_)
356            | StreamElement::Chord(_)
357            | StreamElement::ChordSymbol(_)
358            | StreamElement::Unpitched(_)
359            | StreamElement::PercussionChord(_)
360    )
361}
362
363/// A measure's or voice's elements as music21 iterates it, each with its
364/// offset and where its leaves start in the part: its left barline, what
365/// it holds, its right barline at its end.
366fn walk_of(stream: &Stream, leaf_base: usize) -> Vec<(FloatType, StreamElement, usize)> {
367    let mut out = Vec::new();
368    if let Some(barline) = stream.left_barline() {
369        out.push((0.0, StreamElement::Barline(barline.clone()), leaf_base));
370    }
371    let mut leaf = leaf_base;
372    for event in stream.events() {
373        let element = event.element().clone();
374        let leaves = match &element {
375            StreamElement::Stream(inner) => inner.leaves().len(),
376            _ => 1,
377        };
378        out.push((event.offset(), element, leaf));
379        leaf += leaves;
380    }
381    if let Some(barline) = stream.right_barline() {
382        out.push((
383            stream.end_offset(),
384            StreamElement::Barline(barline.clone()),
385            leaf,
386        ));
387    }
388    out
389}
390
391/// The elements of a measure or voice braille writes, clefs before the
392/// note they stand before, sorted by offset and braille's sort order:
393/// music21's `extractBrailleElements`.
394pub fn extract_braille_elements(
395    stream: &Stream,
396    leaf_base: usize,
397    contexts: &[NoteContext],
398) -> BrailleElementGrouping {
399    let mut grouping = BrailleElementGrouping::default();
400    let mut last_clef: Option<(FloatType, StreamElement, usize)> = None;
401    for (offset, element, leaf) in walk_of(stream, leaf_base) {
402        if matches!(element, StreamElement::Clef(_)) {
403            last_clef = Some((offset, element, leaf));
404            continue;
405        }
406        if let StreamElement::Barline(barline) = &element
407            && barline.bar_type().as_str() == "regular"
408        {
409            continue;
410        }
411        let Some((affinity, sort_order)) = affinity_of(&element) else {
412            continue;
413        };
414        let attaches = is_general_note(&element)
415            || matches!(&element, StreamElement::Stream(inner) if inner.kind() == StreamKind::Voice);
416        if attaches && let Some((clef_offset, clef, clef_leaf)) = last_clef.take() {
417            grouping.elements.push(BrailleElement {
418                english: Some(vec![element_repr(&clef)]),
419                element: clef,
420                offset: clef_offset,
421                affinity,
422                sort_order: 7,
423                context: NoteContext::default(),
424                outgoing_key: None,
425                leaf: clef_leaf,
426                voice_english: Vec::new(),
427            });
428        }
429        grouping.elements.push(BrailleElement {
430            english: Some(vec![element_repr(&element)]),
431            context: contexts.get(leaf).copied().unwrap_or_default(),
432            element,
433            offset,
434            affinity,
435            sort_order,
436            outgoing_key: None,
437            leaf,
438            voice_english: Vec::new(),
439        });
440    }
441    let order = |left: &BrailleElement, right: &BrailleElement| {
442        left.offset
443            .total_cmp(&right.offset)
444            .then(left.sort_order.cmp(&right.sort_order))
445    };
446    grouping.elements.sort_by(order);
447    let count = grouping.elements.len();
448    if count >= 2
449        && matches!(
450            grouping.elements[count - 1].element,
451            StreamElement::Dynamic(_)
452        )
453        && matches!(
454            grouping.elements[count - 2].element,
455            StreamElement::Barline(_)
456        )
457    {
458        grouping.elements[count - 1].sort_order = -1;
459        grouping.elements.sort_by(order);
460    }
461    grouping
462}
463
464/// The type of a note's first beam, as music21's `beams.getByNumber(1)`
465/// reads it.
466fn first_beam_type(element: &StreamElement) -> Option<String> {
467    let beams = match element {
468        StreamElement::Note(note) => note.beams(),
469        StreamElement::Chord(chord) => chord.beams(),
470        _ => return None,
471    };
472    beams
473        .beams()
474        .iter()
475        .find(|beam| beam.number() == Some(1))
476        .and_then(|beam| beam.beam_type())
477        .map(|kind| kind.as_str().to_string())
478}
479
480/// The whole beat a place falls in, as music21's `int(element.beat)`.
481fn whole_beat(meter: Option<&TimeSignature>, offset: FloatType) -> Option<i64> {
482    meter
483        .and_then(|meter| meter.beat_at_offset(offset).ok())
484        .map(i64::from)
485}
486
487/// Marks the notes of a measure that begin and continue a beamed group of
488/// three or more notes of one value shorter than an eighth, which braille
489/// writes as eighths after the first: music21's `prepareBeamedNotes`. The
490/// marks go in `contexts`, by element.
491pub fn prepare_beamed_notes(
492    items: &[(FloatType, StreamElement)],
493    meter: Option<&TimeSignature>,
494) -> Vec<(bool, bool)> {
495    let mut flags = vec![(false, false); items.len()];
496    // The notes, and the notes and rests, by place in `items`.
497    let notes: Vec<usize> = (0..items.len())
498        .filter(|&i| is_not_rest(&items[i].1))
499        .collect();
500    let general: Vec<usize> = (0..items.len())
501        .filter(|&i| is_general_note(&items[i].1))
502        .collect();
503    let starts: Vec<usize> = notes
504        .iter()
505        .copied()
506        .filter(|&i| first_beam_type(&items[i].1).as_deref() == Some("start"))
507        .collect();
508    let stops: Vec<usize> = notes
509        .iter()
510        .copied()
511        .filter(|&i| first_beam_type(&items[i].1).as_deref() == Some("stop"))
512        .collect();
513    if starts.len() != stops.len() {
514        return flags;
515    }
516    let length = |i: usize| items[i].1.quarter_length();
517    // music21 compares lengths as exact fractions; a sixth summed one way and
518    // another differs as a float.
519    let same_length = |a: FloatType, b: FloatType| (a - b).abs() < 1e-9;
520    for (start, stop) in starts.into_iter().zip(stops) {
521        if length(start) == 0.5 {
522            continue;
523        }
524        let (Some(start_index), Some(stop_index)) = (
525            general.iter().position(|&i| i == start),
526            general.iter().position(|&i| i == stop),
527        ) else {
528            continue;
529        };
530        if (stop_index as i64) - (start_index as i64) + 1 < 3 {
531            continue;
532        }
533        let mut same = (start_index + 1..=stop_index).all(|index| {
534            let i = general[index];
535            same_length(length(i), length(start)) && !matches!(items[i].1, StreamElement::Rest(_))
536        });
537        if let Some(&after) = general.get(stop_index + 1)
538            && matches!(items[after].1, StreamElement::Rest(_))
539            && whole_beat(meter, items[after].0) == whole_beat(meter, items[stop].0)
540        {
541            same = false;
542        }
543        if !same {
544            continue;
545        }
546        if let Some(&after) = general.get(stop_index + 1)
547            && length(after) == 0.5
548        {
549            continue;
550        }
551        flags[start].0 = true;
552        if start_index >= 1 {
553            let before = general[start_index - 1];
554            if matches!(items[before].1, StreamElement::Rest(_))
555                && whole_beat(meter, items[before].0) == whole_beat(meter, items[start].0)
556                && same_length(length(before), length(start))
557            {
558                flags[start].1 = true;
559            }
560        } else {
561            // music21 reads the note before the first as the last of the
562            // measure, as Python indexes a list from its end.
563            let before = general[general.len() - 1];
564            if matches!(items[before].1, StreamElement::Rest(_))
565                && whole_beat(meter, items[before].0) == whole_beat(meter, items[start].0)
566                && same_length(length(before), length(start))
567            {
568                flags[start].1 = true;
569            }
570        }
571        for index in start_index + 1..=stop_index {
572            flags[general[index]].1 = true;
573        }
574    }
575    flags
576}
577
578/// The options music21's translation takes, as a segment reads them.
579#[derive(Clone, Copy, Debug, PartialEq, Eq)]
580#[non_exhaustive]
581pub struct SegmentOptions {
582    /// Whether a key signature cancels the one before it.
583    pub cancel_outgoing_key_sig: bool,
584    /// Whether chords start out written from the top down, as they do
585    /// when this is nothing. A bass or tenor clef then turns them upward
586    /// and a treble or alto clef downward, in its segment and those after
587    /// it.
588    pub descending_chords: Option<bool>,
589    /// How many dummy rests open each segment.
590    pub dummy_rest_length: Option<usize>,
591    /// How many cells a line holds.
592    pub max_line_length: usize,
593    /// Whether clefs are written.
594    pub show_clef_signs: bool,
595    /// Whether a segment starts with its first measure's number.
596    pub show_first_measure_number: bool,
597    /// Which hand's sign starts the lines.
598    pub show_hand: Option<Hand>,
599    /// Whether a segment starts with a heading.
600    pub show_heading: bool,
601    /// Whether a long slur and a tie on one note are both written.
602    pub show_long_slurs_and_ties_together: Option<bool>,
603    /// Whether a short slur and a tie on one note are both written.
604    pub show_short_slurs_and_ties_together: bool,
605    /// Whether a long phrase's slur is written with brackets rather than
606    /// doubled.
607    pub slur_long_phrase_with_brackets: bool,
608    /// Whether octave marks are left out.
609    pub suppress_octave_marks: bool,
610    /// Whether a fingering's upper choice is written first.
611    pub upper_first_in_note_fingering: bool,
612}
613
614impl Default for SegmentOptions {
615    fn default() -> Self {
616        Self {
617            cancel_outgoing_key_sig: true,
618            descending_chords: None,
619            dummy_rest_length: None,
620            max_line_length: 40,
621            show_clef_signs: false,
622            show_first_measure_number: true,
623            show_hand: None,
624            show_heading: true,
625            show_long_slurs_and_ties_together: None,
626            show_short_slurs_and_ties_together: false,
627            slur_long_phrase_with_brackets: true,
628            suppress_octave_marks: false,
629            upper_first_in_note_fingering: true,
630        }
631    }
632}
633
634/// The most notes a slur written after each note covers: music21's
635/// `SEGMENT_MAXNOTESFORSHORTSLUR`.
636const MAX_NOTES_FOR_SHORT_SLUR: usize = 4;
637
638/// The most elements a segment holds before a double or final barline
639/// ends it: music21's `MAX_ELEMENTS_IN_SEGMENT`.
640const MAX_ELEMENTS_IN_SEGMENT: usize = 48;
641
642/// The slurs of a part as each note writes them, by leaf: short slurs after
643/// each note, long ones with brackets or doubled at their ends: music21's
644/// `prepareSlurredNotes`.
645pub fn prepare_slurred_notes(part: &Stream, options: &SegmentOptions) -> Vec<NoteContext> {
646    let leaves = part.leaves();
647    let mut contexts = vec![NoteContext::default(); leaves.len()];
648    if part.spanners().is_empty() {
649        return contexts;
650    }
651    let show_long = options
652        .show_long_slurs_and_ties_together
653        .unwrap_or(options.slur_long_phrase_with_brackets);
654    // The part's notes in music21's flattened order, by leaf.
655    let mut notes: Vec<(FloatType, i32, bool, usize)> = leaves
656        .iter()
657        .enumerate()
658        .filter(|(_, (_, element))| is_not_rest(element))
659        .map(|(leaf, (offset, element))| {
660            let grace = element.duration().is_some_and(Duration::is_grace);
661            (*offset, element.class_sort_order(), !grace, leaf)
662        })
663        .collect();
664    notes.sort_by(|left, right| {
665        left.0
666            .total_cmp(&right.0)
667            .then(left.1.cmp(&right.1))
668            .then(left.2.cmp(&right.2))
669    });
670    let notes: Vec<usize> = notes.into_iter().map(|(_, _, _, leaf)| leaf).collect();
671    let tie_of = |leaf: usize| -> Option<crate::notation::TieType> {
672        match leaves[leaf].1 {
673            StreamElement::Note(note) => note.tie().map(|tie| tie.tie_type()),
674            StreamElement::Chord(chord) => chord.tie().map(|tie| tie.tie_type()),
675            _ => None,
676        }
677    };
678    let at = |index: i64| -> usize {
679        let count = notes.len() as i64;
680        notes[(((index % count) + count) % count) as usize]
681    };
682    for spanner in part.spanners() {
683        if spanner.kind() != crate::spanner::SpannerKind::Slur {
684            continue;
685        }
686        let spanned = spanner.spanned();
687        let (Some(Some(first)), Some(Some(last))) = (spanned.first(), spanned.last()) else {
688            continue;
689        };
690        let (Some(begin), Some(end)) = (
691            notes.iter().position(|leaf| leaf == first),
692            notes.iter().position(|leaf| leaf == last),
693        ) else {
694            continue;
695        };
696        let (mut begin, mut end) = (begin.min(end) as i64, begin.max(end) as i64);
697        let delta = (end - begin) as usize + 1;
698        let short = delta <= MAX_NOTES_FOR_SHORT_SLUR;
699        if (short && !options.show_short_slurs_and_ties_together) || (!short && !show_long) {
700            if tie_of(at(begin)) == Some(crate::notation::TieType::Start) {
701                begin += 1;
702            }
703            if tie_of(at(end)) == Some(crate::notation::TieType::Stop) {
704                end -= 1;
705            }
706        }
707        if short {
708            for index in begin..end {
709                contexts[at(index)].short_slur = true;
710            }
711        } else if options.slur_long_phrase_with_brackets {
712            contexts[at(begin)].begin_long_bracket_slur = true;
713            contexts[at(end)].end_long_bracket_slur = true;
714        } else {
715            contexts[at(begin + 1)].begin_long_double_slur = true;
716            contexts[at(end - 1)].end_long_double_slur = true;
717        }
718    }
719    contexts
720}
721
722/// A part cut into segments of groupings, ready to transcribe: music21's
723/// `BrailleSegment`.
724#[derive(Clone, Debug)]
725pub struct BrailleSegment {
726    /// The groupings, by key.
727    pub groupings: BTreeMap<SegmentKey, BrailleElementGrouping>,
728    /// The options it is written with.
729    pub options: SegmentOptions,
730    /// Whether chords are written from the top down, as the clefs met so
731    /// far say.
732    pub descending_chords: bool,
733    /// Whether the segment ends in the middle of a measure.
734    pub end_hyphen: bool,
735    /// Whether it begins in the middle of a measure.
736    pub begins_mid_measure: bool,
737    /// What music21 marked on each of the part's leaves.
738    pub contexts: Vec<NoteContext>,
739}
740
741impl BrailleSegment {
742    fn new(options: SegmentOptions, contexts: &[NoteContext]) -> Self {
743        Self {
744            groupings: BTreeMap::new(),
745            options,
746            descending_chords: options.descending_chords.unwrap_or(true),
747            end_hyphen: false,
748            begins_mid_measure: false,
749            contexts: contexts.to_vec(),
750        }
751    }
752}
753
754/// A key signature's sharps, as braille reads it.
755fn sharps_of(element: &StreamElement) -> Option<Option<IntegerType>> {
756    match element {
757        StreamElement::Key(key) => Some(Some(key.sharps())),
758        StreamElement::KeySignature(signature) => Some(Some(signature.sharps())),
759        _ => None,
760    }
761}
762
763/// The part's measures with where each one's leaves start.
764fn measures_of(part: &Stream) -> Vec<(&Stream, usize)> {
765    let mut out = Vec::new();
766    let mut leaf = 0;
767    for event in part.events() {
768        match event.element() {
769            StreamElement::Stream(inner) => {
770                if inner.kind() == StreamKind::Measure {
771                    out.push((&**inner, leaf));
772                }
773                leaf += inner.leaves().len();
774            }
775            _ => leaf += 1,
776        }
777    }
778    out
779}
780
781/// The meter standing at each measure of a part, as music21 finds a
782/// measure's context: the last a measure stated, or one in the part before
783/// it.
784fn meters_of(part: &Stream) -> Vec<Option<TimeSignature>> {
785    let loose: Vec<(FloatType, TimeSignature)> = part
786        .events()
787        .iter()
788        .filter_map(|event| match event.element() {
789            StreamElement::TimeSignature(meter) => Some((event.offset(), meter.clone())),
790            _ => None,
791        })
792        .collect();
793    let mut stated: Option<TimeSignature> = None;
794    let mut out = Vec::new();
795    for event in part.events() {
796        let StreamElement::Stream(measure) = event.element() else {
797            continue;
798        };
799        if measure.kind() != StreamKind::Measure {
800            continue;
801        }
802        for inner in measure.events() {
803            if let StreamElement::TimeSignature(meter) = inner.element()
804                && inner.offset() <= 0.0
805            {
806                stated = Some(meter.clone());
807            }
808        }
809        let meter = stated.clone().or_else(|| {
810            loose
811                .iter()
812                .rev()
813                .find(|(at, _)| *at <= event.offset())
814                .map(|(_, meter)| meter.clone())
815        });
816        out.push(meter);
817    }
818    out
819}
820
821/// A part's measures cut into segments of groupings: music21's
822/// `getRawSegments`. A segment ends after a double or final barline once it
823/// holds more than 48 elements.
824pub fn get_raw_segments(
825    part: &Stream,
826    hand: Option<Hand>,
827    contexts: &[NoteContext],
828    options: SegmentOptions,
829) -> Vec<BrailleSegment> {
830    let mut segments = Vec::new();
831    let mut contexts = contexts.to_vec();
832    let mut current = BrailleSegment::new(options, &contexts);
833    let mut in_current = 0;
834    let mut start_new = false;
835    let meters = meters_of(part);
836    for (index, (measure, leaf_base)) in measures_of(part).into_iter().enumerate() {
837        let walk = walk_of(measure, leaf_base);
838        let items: Vec<(FloatType, StreamElement)> = walk
839            .iter()
840            .filter(|(_, element, _)| !matches!(element, StreamElement::Stream(_)))
841            .map(|(offset, element, _)| (*offset, element.clone()))
842            .collect();
843        let leaves: Vec<usize> = walk
844            .iter()
845            .filter(|(_, element, _)| !matches!(element, StreamElement::Stream(_)))
846            .map(|(_, _, leaf)| *leaf)
847            .collect();
848        let flags = prepare_beamed_notes(&items, meters.get(index).and_then(Option::as_ref));
849        for ((item, leaf), (start, continued)) in items.iter().zip(&leaves).zip(flags) {
850            if is_not_rest(&item.1) && *leaf < contexts.len() {
851                contexts[*leaf].beam_start = start;
852                contexts[*leaf].beam_continue = continued;
853            }
854        }
855        let elements = extract_braille_elements(measure, leaf_base, &contexts);
856        let number = IntegerType::from(measure.number());
857        let mut ordinal = 0;
858        let mut previous: Option<Affinity> = None;
859        for element in elements.elements {
860            if start_new {
861                if element.offset != 0.0 {
862                    current.end_hyphen = true;
863                }
864                segments.push(std::mem::replace(
865                    &mut current,
866                    BrailleSegment::new(options, &contexts),
867                ));
868                if element.offset != 0.0 {
869                    current.begins_mid_measure = true;
870                }
871                in_current = 0;
872                if previous.is_some() {
873                    ordinal += 1;
874                }
875                start_new = false;
876            }
877            // A division ends the segment unless it is empty, or optional
878            // and the segment not yet past its length; it is never written.
879            if let StreamElement::BrailleSegmentDivision(division) = &element.element {
880                let waits =
881                    *division == SegmentDivision::Optional && in_current <= MAX_ELEMENTS_IN_SEGMENT;
882                if !waits && in_current > 0 {
883                    start_new = true;
884                }
885                continue;
886            }
887            if let StreamElement::Barline(barline) = &element.element
888                && in_current > MAX_ELEMENTS_IN_SEGMENT
889                && matches!(barline.bar_type().as_str(), "double" | "final")
890            {
891                start_new = true;
892            }
893            if previous.is_some_and(|previous| element.affinity < previous) {
894                ordinal += 1;
895            }
896            let affinity = match element.affinity {
897                Affinity::SplitNoteGroupingA => Affinity::Inaccord,
898                Affinity::SplitNoteGroupingB => Affinity::NoteGrouping,
899                other => other,
900            };
901            let key = SegmentKey {
902                measure: number,
903                ordinal,
904                affinity,
905                hand,
906            };
907            previous = Some(element.affinity);
908            current
909                .groupings
910                .entry(key)
911                .or_default()
912                .elements
913                .push(element);
914            in_current += 1;
915        }
916    }
917    current.contexts = contexts;
918    segments.push(current);
919    segments
920}
921
922/// Whether two elements are equal as music21 compares them.
923fn elements_equal(left: &BrailleElement, right: &BrailleElement) -> bool {
924    super::equality::equal(&left.element, &right.element)
925}
926
927/// Whether two groupings hold equal elements: music21's
928/// `areGroupingsIdentical`.
929fn groupings_identical(left: &[BrailleElement], right: &[BrailleElement]) -> bool {
930    left.len() == right.len()
931        && left
932            .iter()
933            .zip(right)
934            .all(|(left, right)| elements_equal(left, right))
935}
936
937impl BrailleSegment {
938    /// Repeated measures counted, key signatures given their predecessors,
939    /// full measures' rests marked and each grouping told the signatures
940    /// and options in force: music21's `addGroupingAttributes`.
941    pub fn add_grouping_attributes(&mut self) {
942        let mut current_key: Option<IntegerType> = Some(0);
943        let mut current_meter = TimeSignature::new(4, 4).expect("4/4 is a meter");
944        let keys: Vec<SegmentKey> = self.groupings.keys().copied().collect();
945        let mut previous: Option<SegmentKey> = None;
946        for key in keys {
947            if let Some(previous_key) = previous {
948                if key.ordinal >= 1 {
949                    self.groupings
950                        .get_mut(&previous_key)
951                        .expect("a grouping")
952                        .with_hyphen = true;
953                }
954                if previous_key.ordinal == 0
955                    && previous_key.affinity == Affinity::NoteGrouping
956                    && key.ordinal == 0
957                    && key.affinity == Affinity::NoteGrouping
958                {
959                    let previous_elements = &self.groupings[&previous_key].elements;
960                    let these = &self.groupings[&key].elements;
961                    let repeated = if previous_elements
962                        .first()
963                        .is_some_and(|first| matches!(first.element, StreamElement::Clef(_)))
964                    {
965                        groupings_identical(&previous_elements[1..], these)
966                    } else {
967                        groupings_identical(previous_elements, these)
968                    };
969                    if repeated {
970                        self.groupings
971                            .get_mut(&previous_key)
972                            .expect("a grouping")
973                            .num_repeats += 1;
974                        self.groupings.remove(&key);
975                        continue;
976                    }
977                }
978            }
979            let descending = &mut self.descending_chords;
980            let grouping = self.groupings.get_mut(&key).expect("a grouping");
981            if key.affinity == Affinity::Signature {
982                for element in &mut grouping.elements {
983                    if let StreamElement::TimeSignature(meter) = &element.element {
984                        current_meter = meter.clone();
985                    } else if let Some(sharps) = sharps_of(&element.element) {
986                        element.outgoing_key = Some(current_key);
987                        current_key = sharps;
988                    }
989                }
990            } else if matches!(key.affinity, Affinity::Inaccord | Affinity::NoteGrouping) {
991                if let Some(StreamElement::Clef(clef)) =
992                    grouping.elements.first().map(|e| &e.element)
993                {
994                    match clef.kind().class_name() {
995                        "TrebleClef" | "Treble8vbClef" | "Treble8vaClef" | "AltoClef" => {
996                            *descending = true;
997                        }
998                        "BassClef" | "Bass8vbClef" | "Bass8vaClef" | "TenorClef" => {
999                            *descending = false;
1000                        }
1001                        _ => {}
1002                    }
1003                }
1004                let general: Vec<usize> = (0..grouping.elements.len())
1005                    .filter(|&i| is_general_note(&grouping.elements[i].element))
1006                    .collect();
1007                if let [only] = general.as_slice()
1008                    && let StreamElement::Rest(rest) = &mut grouping.elements[*only].element
1009                {
1010                    rest.set_full_measure(crate::rest::FullMeasure::Yes);
1011                }
1012            }
1013            grouping.key_signature = current_key;
1014            grouping.time_signature = current_meter.clone();
1015            grouping.descending_chords = Some(*descending);
1016            grouping.show_clef_signs = self.options.show_clef_signs;
1017            grouping.upper_first_in_note_fingering = self.options.upper_first_in_note_fingering;
1018            previous = Some(key);
1019        }
1020        if self.end_hyphen
1021            && let Some(last) = previous
1022        {
1023            self.groupings
1024                .get_mut(&last)
1025                .expect("a grouping")
1026                .with_hyphen = true;
1027        }
1028    }
1029
1030    /// Runs of four or more notes with one articulation written with it
1031    /// doubled on the first, left off the notes between and once on the
1032    /// last, and a staccato or tenuto over a tie between two of the
1033    /// segment's notes written as a short slur: music21's
1034    /// `fixArticulations`.
1035    pub fn fix_articulations(&mut self) {
1036        // music21's `consolidate`: each run of note groupings with nothing
1037        // else between, as one.
1038        let mut runs: Vec<Vec<(SegmentKey, usize)>> = Vec::new();
1039        let mut in_run = false;
1040        for (key, grouping) in &self.groupings {
1041            if key.affinity != Affinity::NoteGrouping {
1042                in_run = false;
1043                continue;
1044            }
1045            if !in_run {
1046                runs.push(Vec::new());
1047                in_run = true;
1048            }
1049            let run = runs.last_mut().expect("a run");
1050            for (index, element) in grouping.elements.iter().enumerate() {
1051                if matches!(element.element, StreamElement::Note(_)) {
1052                    run.push((*key, index));
1053                }
1054            }
1055        }
1056        for notes in runs {
1057            for start in 0..notes.len() {
1058                let articulations = self.note(notes[start]).articulations().to_vec();
1059                for articulation in &articulations {
1060                    if articulation.is_a("TechnicalIndication") && !articulation.is_a("Bowing") {
1061                        continue;
1062                    }
1063                    self.fix_one_articulation(articulation, &notes, start);
1064                }
1065            }
1066        }
1067    }
1068
1069    fn note(&self, (key, index): (SegmentKey, usize)) -> &Note {
1070        match &self.groupings[&key].elements[index].element {
1071            StreamElement::Note(note) => note,
1072            _ => unreachable!("only notes are gathered"),
1073        }
1074    }
1075
1076    fn element_mut(&mut self, (key, index): (SegmentKey, usize)) -> &mut BrailleElement {
1077        &mut self.groupings.get_mut(&key).expect("a grouping").elements[index]
1078    }
1079
1080    fn note_mut(&mut self, place: (SegmentKey, usize)) -> &mut Note {
1081        match &mut self.element_mut(place).element {
1082            StreamElement::Note(note) => note,
1083            _ => unreachable!("only notes are gathered"),
1084        }
1085    }
1086
1087    fn fix_one_articulation(
1088        &mut self,
1089        articulation: &crate::articulations::Articulation,
1090        notes: &[(SegmentKey, usize)],
1091        start: usize,
1092    ) {
1093        let name = articulation.name();
1094        if (articulation.is_a("Staccato") || articulation.is_a("Tenuto"))
1095            && let Some(tie) = self.note(notes[start]).tie().map(|tie| tie.tie_type())
1096        {
1097            // A tie to a note outside these notes, such as one across a
1098            // segment break, stays a tie.
1099            if tie == crate::notation::TieType::Stop {
1100                if start > 0 {
1101                    let before = notes[start - 1];
1102                    self.note_mut(before).set_tie(None);
1103                    self.element_mut(before).context.short_slur = true;
1104                    self.note_mut(notes[start]).set_tie(None);
1105                }
1106            } else if start + 1 < notes.len() {
1107                self.note_mut(notes[start + 1]).set_tie(None);
1108                self.element_mut(notes[start]).context.short_slur = true;
1109                self.note_mut(notes[start]).set_tie(None);
1110            }
1111        }
1112        let mut sequential = 0;
1113        for &place in &notes[start + 1..] {
1114            if self
1115                .note(place)
1116                .articulations()
1117                .iter()
1118                .any(|other| other.name() == name)
1119            {
1120                sequential += 1;
1121                continue;
1122            }
1123            break;
1124        }
1125        if sequential < 3 {
1126            return;
1127        }
1128        self.note_mut(notes[start])
1129            .articulations_mut()
1130            .push(articulation.clone());
1131        for &place in &notes[start + 1..start + sequential] {
1132            self.note_mut(place)
1133                .articulations_mut()
1134                .retain(|other| other.name() != name);
1135        }
1136    }
1137}
1138
1139/// A part's segments, each told its options, its groupings their
1140/// attributes and its articulations fixed: music21's `findSegments`.
1141pub fn find_segments(
1142    part: &Stream,
1143    hand: Option<Hand>,
1144    options: SegmentOptions,
1145) -> Vec<BrailleSegment> {
1146    let contexts = prepare_slurred_notes(part, &options);
1147    let mut segments = get_raw_segments(part, hand, &contexts, options);
1148    // The direction a clef sets carries into the segments after it.
1149    let mut descending = options.descending_chords.unwrap_or(true);
1150    for segment in &mut segments {
1151        segment.descending_chords = descending;
1152        segment.add_grouping_attributes();
1153        descending = segment.descending_chords;
1154        segment.fix_articulations();
1155    }
1156    segments
1157}
1158
1159/// Writes the elements of a grouping one after another, octaves where
1160/// needed: music21's `NoteGroupingTranscriber`.
1161#[derive(Clone, Debug)]
1162pub struct NoteGroupingTranscriber {
1163    /// Whether the first note shows its octave.
1164    pub show_leading_octave: bool,
1165    previous_note: Option<Pitch>,
1166    previous_element: Option<usize>,
1167    trans: Vec<String>,
1168}
1169
1170impl Default for NoteGroupingTranscriber {
1171    fn default() -> Self {
1172        Self {
1173            show_leading_octave: true,
1174            previous_note: None,
1175            previous_element: None,
1176            trans: Vec::new(),
1177        }
1178    }
1179}
1180
1181impl NoteGroupingTranscriber {
1182    /// A grouping in braille, its elements' English written onto them, and
1183    /// a music hyphen where it ends with one: music21's `transcribeGroup`.
1184    pub fn transcribe_group(&mut self, grouping: &mut BrailleElementGrouping) -> String {
1185        self.previous_note = None;
1186        self.previous_element = None;
1187        self.trans = Vec::new();
1188        for index in 0..grouping.elements.len() {
1189            self.transcribe_one_element(grouping, index);
1190        }
1191        if grouping.with_hyphen {
1192            self.trans.push(symbol("music_hyphen"));
1193        }
1194        self.trans.concat()
1195    }
1196
1197    fn octave_shown(&self, pitch: &Pitch) -> bool {
1198        match &self.previous_note {
1199            None => self.show_leading_octave,
1200            Some(previous) => basic::show_octave_with_note(Some(previous), pitch),
1201        }
1202    }
1203
1204    /// The braille written so far, a sign at a time: music21's `trans`,
1205    /// which its own examples join and print.
1206    pub fn transcribed(&self) -> &[String] {
1207        &self.trans
1208    }
1209
1210    /// One element of a grouping written, the signs appended to what the
1211    /// transcriber has written already and its English onto the element:
1212    /// music21's `transcribeOneElement`, which it calls one at a time and
1213    /// its own examples do too.
1214    ///
1215    /// The element is named by its place in the grouping, since what is
1216    /// written depends on what the grouping says -- the chords' direction,
1217    /// whether clefs are shown, which way a fingering is read -- and on
1218    /// the element before it.
1219    pub fn transcribe_element(&mut self, grouping: &mut BrailleElementGrouping, index: usize) {
1220        self.transcribe_one_element(grouping, index);
1221    }
1222
1223    /// Remembers the pitch just written, so the next note shows its octave
1224    /// only where needed. A note or chord written as the exception sign
1225    /// leaves no pitch, and the next note shows its octave.
1226    fn follow_written_note(&mut self, written: &Transcription, pitch: Pitch) {
1227        if written.braille == symbol("basic_exception") {
1228            self.previous_note = None;
1229            self.show_leading_octave = true;
1230        } else {
1231            self.previous_note = Some(pitch);
1232        }
1233    }
1234
1235    fn transcribe_one_element(&mut self, grouping: &mut BrailleElementGrouping, index: usize) {
1236        let descending = grouping.descending_chords.unwrap_or(false);
1237        let show_clef_signs = grouping.show_clef_signs;
1238        let upper_first = grouping.upper_first_in_note_fingering;
1239        let item = &mut grouping.elements[index];
1240        let written: Option<Transcription> = match &item.element {
1241            StreamElement::Note(note) => {
1242                let shown = self.octave_shown(note.pitch());
1243                let written = note_to_braille(note, shown, upper_first, item.context);
1244                self.follow_written_note(&written, note.pitch().clone());
1245                Some(written)
1246            }
1247            StreamElement::Rest(rest) => Some(rest_to_braille(rest)),
1248            StreamElement::Chord(chord) => {
1249                let mut pitches = chord.pitches();
1250                pitches.sort_by(|left, right| left.ps().total_cmp(&right.ps()));
1251                let chosen = if descending {
1252                    pitches.last().cloned()
1253                } else {
1254                    pitches.first().cloned()
1255                };
1256                chosen.map(|pitch| {
1257                    let shown = self.octave_shown(&pitch);
1258                    let written = chord_to_braille(chord, descending, shown);
1259                    self.follow_written_note(&written, pitch);
1260                    written
1261                })
1262            }
1263            StreamElement::ChordSymbol(chord_symbol) => {
1264                let mut sorted = chord_symbol.pitches().unwrap_or_default();
1265                sorted.sort_by(|left, right| left.ps().total_cmp(&right.ps()));
1266                let chosen = if descending {
1267                    sorted.last()
1268                } else {
1269                    sorted.first()
1270                }
1271                .cloned();
1272                chosen.and_then(|pitch| {
1273                    let shown = self.octave_shown(&pitch);
1274                    let written = chord_symbol_to_braille(chord_symbol, descending, shown)?;
1275                    self.follow_written_note(&written, pitch);
1276                    Some(written)
1277                })
1278            }
1279            StreamElement::Dynamic(dynamic) => {
1280                self.previous_note = None;
1281                self.show_leading_octave = true;
1282                Some(dynamic_to_braille(dynamic, true))
1283            }
1284            StreamElement::TextExpression(text) => {
1285                self.previous_note = None;
1286                self.show_leading_octave = true;
1287                Some(text_expression_to_braille(text, true))
1288            }
1289            StreamElement::Barline(barline) => Some(barline_to_braille(barline)),
1290            StreamElement::Clef(clef) => {
1291                if show_clef_signs {
1292                    self.previous_note = None;
1293                    self.show_leading_octave = true;
1294                    Some(clef_to_braille(clef, false))
1295                } else {
1296                    None
1297                }
1298            }
1299            _ => None,
1300        };
1301        if let Some(written) = written {
1302            item.english = Some(written.english);
1303            self.trans.push(written.braille);
1304        }
1305        self.optionally_add_dot_to_previous(grouping, index);
1306        self.previous_element = Some(index);
1307    }
1308
1309    /// A dot after a dynamic, a clef written out, or text not ending in a
1310    /// full stop, before the next element unless that is itself a dynamic
1311    /// or text: music21's `optionallyAddDotToPrevious`.
1312    fn optionally_add_dot_to_previous(
1313        &mut self,
1314        grouping: &mut BrailleElementGrouping,
1315        index: usize,
1316    ) {
1317        let Some(previous) = self.previous_element else {
1318            return;
1319        };
1320        let Some(last) = self.trans.last() else {
1321            return;
1322        };
1323        if matches!(
1324            grouping.elements[index].element,
1325            StreamElement::Dynamic(_) | StreamElement::TextExpression(_)
1326        ) {
1327            return;
1328        }
1329        let dotted = match &grouping.elements[previous].element {
1330            StreamElement::Dynamic(_) => true,
1331            StreamElement::Clef(_) => grouping.show_clef_signs,
1332            StreamElement::TextExpression(text) => !text.content().ends_with('.'),
1333            _ => false,
1334        };
1335        if !dotted {
1336            return;
1337        }
1338        let Some(first) = last.chars().next() else {
1339            return;
1340        };
1341        if let Some(dot) = yield_dots(first).into_iter().next() {
1342            let at = self.trans.len() - 1;
1343            self.trans.insert(at, dot.clone());
1344            grouping.elements[previous]
1345                .english
1346                .get_or_insert_with(Vec::new)
1347                .push(format!("Dot 3 {dot}"));
1348        }
1349    }
1350}
1351
1352/// A grouping in braille from a fresh transcriber: music21's
1353/// `transcribeNoteGrouping`.
1354pub fn transcribe_note_grouping(
1355    grouping: &mut BrailleElementGrouping,
1356    show_leading_octave: bool,
1357) -> String {
1358    let mut transcriber = NoteGroupingTranscriber {
1359        show_leading_octave,
1360        ..NoteGroupingTranscriber::default()
1361    };
1362    transcriber.transcribe_group(grouping)
1363}
1364
1365/// A measure of groupings split in two at the middle of its bar, or nearer
1366/// its start by `beat_division_offset` divisions of a beat, tied notes kept
1367/// with the first half and each half beamed again: music21's
1368/// `splitNoteGrouping`.
1369///
1370/// # Errors
1371///
1372/// An offset past the beat's divisions, or a meter that cannot be halved.
1373pub fn split_note_grouping(
1374    grouping: &mut BrailleElementGrouping,
1375    beat_division_offset: usize,
1376) -> Result<Option<(BrailleElementGrouping, BrailleElementGrouping)>> {
1377    Ok(split_with_sources(grouping, beat_division_offset)?
1378        .map(|((first, _), (second, _))| (first, second)))
1379}
1380
1381/// A grouping and which of the split grouping's elements it holds.
1382type Half = (BrailleElementGrouping, Vec<usize>);
1383
1384/// An element of a half rebeamed: where it came from, as beamed, and its
1385/// marks for beginning and continuing a beamed group.
1386type Rebeamed = (usize, StreamElement, (bool, bool));
1387
1388/// [`split_note_grouping`], each half with where its elements came from.
1389fn split_with_sources(
1390    grouping: &mut BrailleElementGrouping,
1391    beat_division_offset: usize,
1392) -> Result<Option<(Half, Half)>> {
1393    let meter = grouping.time_signature.clone();
1394    let mut offset = 0.0;
1395    if beat_division_offset != 0 {
1396        let divisions = meter.beat_division_durations()?;
1397        if beat_division_offset > divisions.len() {
1398            // music21's `BrailleSegmentException`, which the segment takes
1399            // as no split.
1400            return Ok(None);
1401        }
1402        if let Some(duration) = divisions.get(divisions.len() - beat_division_offset) {
1403            offset = op_frac(offset + op_frac(duration.quarter_length()));
1404        }
1405    }
1406    let beats = meter.beat_sequence();
1407    let (start_zero, mut end_zero) = match beats.partitioned_by_count(2, false) {
1408        Ok(halves) => halves.level_span(0)[0],
1409        Err(_) => {
1410            let spans = beats.partitioned_by_count(3, false)?.level_span(0);
1411            (spans[0].0, spans[spans.len() - 2].1)
1412        }
1413    };
1414    end_zero -= offset;
1415    let elements = &grouping.elements;
1416    // music21 iterates the measure it builds from the grouping, sorted by
1417    // offset and sort order.
1418    let mut order: Vec<usize> = (0..elements.len()).collect();
1419    order.sort_by(|&a, &b| {
1420        elements[a]
1421            .offset
1422            .total_cmp(&elements[b].offset)
1423            .then(elements[a].sort_order.cmp(&elements[b].sort_order))
1424    });
1425    let mut left: Vec<usize> = Vec::new();
1426    let mut right: Vec<usize> = Vec::new();
1427    for &index in &order {
1428        let at = elements[index].offset;
1429        let barline = matches!(elements[index].element, StreamElement::Barline(_));
1430        if at >= start_zero && (at < end_zero || (at == end_zero && barline)) {
1431            left.push(index);
1432        } else {
1433            right.push(index);
1434        }
1435    }
1436    let highest = elements
1437        .iter()
1438        .map(|element| op_frac(element.offset + element.element.quarter_length()))
1439        .fold(0.0, FloatType::max);
1440    let mut offsets: Vec<FloatType> = elements.iter().map(|element| element.offset).collect();
1441    // Tied notes at the start of the second half go with the first, put
1442    // after what it holds.
1443    while let Some(position) = right
1444        .iter()
1445        .position(|&i| is_not_rest(&elements[i].element))
1446    {
1447        let index = right[position];
1448        let tied = match &elements[index].element {
1449            StreamElement::Note(note) => note.tie().is_some(),
1450            StreamElement::Chord(chord) => chord.tie().is_some(),
1451            _ => false,
1452        };
1453        if !tied {
1454            break;
1455        }
1456        offsets[index] = left
1457            .iter()
1458            .map(|&i| op_frac(offsets[i] + elements[i].element.quarter_length()))
1459            .fold(0.0, FloatType::max);
1460        left.push(index);
1461        right.remove(position);
1462        end_zero += elements[index].element.quarter_length();
1463    }
1464    // Each half beamed as a measure of its own, filled out with a rest, and
1465    // its beamed notes marked again.
1466    let rebeam =
1467        |indices: &[usize], rest_at: FloatType, rest_length: FloatType| -> Result<Vec<Rebeamed>> {
1468            let rest = Rest::new(Duration::new(rest_length.max(0.0))?);
1469            // The measure's events in the order a stream sorts them: by offset,
1470            // in the order they were put in.
1471            let mut placed: Vec<(FloatType, Option<usize>, StreamElement)> = indices
1472                .iter()
1473                .map(|&i| (offsets[i], Some(i), elements[i].element.clone()))
1474                .collect();
1475            placed.push((rest_at, None, StreamElement::Rest(rest)));
1476            placed.sort_by(|a, b| a.0.total_cmp(&b.0));
1477            let mut measure = Stream::with_kind(StreamKind::Measure);
1478            measure.insert(0.0, meter.clone());
1479            for (at, _, element) in &placed {
1480                measure.insert(*at, element.clone());
1481            }
1482            crate::makenotation::make_beams(&mut measure)?;
1483            let beamed: Vec<(FloatType, StreamElement)> = measure
1484                .events()
1485                .iter()
1486                .filter(|event| !matches!(event.element(), StreamElement::TimeSignature(_)))
1487                .map(|event| (event.offset(), event.element().clone()))
1488                .collect();
1489            let flags = prepare_beamed_notes(&beamed, Some(&meter));
1490            Ok(placed
1491                .iter()
1492                .zip(beamed)
1493                .zip(flags)
1494                .filter_map(|(((_, source, _), (_, element)), flags)| {
1495                    source.map(|source| (source, element, flags))
1496                })
1497                .collect())
1498        };
1499    let left_beamed = rebeam(&left, end_zero, highest - end_zero)?;
1500    let right_beamed = rebeam(&right, 0.0, end_zero)?;
1501    // music21 changes the grouping's own elements: their offsets, beams and
1502    // marks stay as the split left them.
1503    for (index, element, (start, continued)) in left_beamed.iter().chain(&right_beamed) {
1504        let item = &mut grouping.elements[*index];
1505        item.offset = offsets[*index];
1506        item.element = element.clone();
1507        if is_not_rest(&item.element) {
1508            item.context.beam_start = *start;
1509            item.context.beam_continue = *continued;
1510        }
1511    }
1512    let half = |beamed: &[Rebeamed]| -> Half {
1513        let mut half = grouping.clone();
1514        half.elements = beamed
1515            .iter()
1516            .map(|(index, _, _)| grouping.elements[*index].clone())
1517            .collect();
1518        (half, beamed.iter().map(|(index, _, _)| *index).collect())
1519    };
1520    Ok(Some((half(&left_beamed), half(&right_beamed))))
1521}
1522
1523impl BrailleSegment {
1524    /// The segment in braille: its heading and first measure number, then
1525    /// each grouping in turn: music21's `transcribe`.
1526    ///
1527    /// # Errors
1528    ///
1529    /// Something too wide for a line, or that music21 cannot write.
1530    pub fn transcribe(&mut self) -> Result<String> {
1531        let hand = match self.options.show_hand {
1532            Some(Hand::Right) => Some("right"),
1533            Some(Hand::Left) => Some("left"),
1534            None => None,
1535        };
1536        let text = BrailleText::new(self.options.max_line_length, hand)?;
1537        let mut transcriber = SegmentTranscriber::new(text);
1538        transcriber.transcribe(self)?;
1539        Ok(transcriber.into_text().render())
1540    }
1541
1542    /// The segment's groupings in English, as music21's `__str__` lists
1543    /// them.
1544    pub fn english(&self) -> String {
1545        let mut entries = Vec::new();
1546        let mut previous: Option<SegmentKey> = None;
1547        for (key, grouping) in &self.groupings {
1548            if previous.is_some_and(|previous| previous.affinity == Affinity::SplitNoteGroupingA) {
1549                previous = Some(*key);
1550                continue;
1551            }
1552            entries.push(format!(
1553                "Measure {}, {} {}:\n{}\n===",
1554                key.measure,
1555                key.affinity.name(),
1556                key.ordinal + 1,
1557                grouping_english(grouping)
1558            ));
1559            previous = Some(*key);
1560        }
1561        [
1562            "---begin segment---".to_string(),
1563            "<music21.braille.segment BrailleSegment>".to_string(),
1564            entries.join("\n"),
1565            "---end segment---".to_string(),
1566        ]
1567        .join("\n")
1568    }
1569}
1570
1571/// A grouping's English, element by element: music21's
1572/// `BrailleElementGrouping.__str__`.
1573fn grouping_english(grouping: &BrailleElementGrouping) -> String {
1574    let mut lines = Vec::new();
1575    let mut previous_was_voice = false;
1576    for element in &grouping.elements {
1577        if let StreamElement::Stream(voice) = &element.element
1578            && voice.kind() == StreamKind::Voice
1579        {
1580            if previous_was_voice {
1581                lines.push(format!("full inaccord {}", symbol("full_inaccord")));
1582            }
1583            for (index, inner) in voice.events().iter().enumerate() {
1584                lines.push(match element.voice_english.get(index) {
1585                    Some(Some(english)) => english.join("\n"),
1586                    _ => element_repr(inner.element()),
1587                });
1588            }
1589            previous_was_voice = true;
1590        } else {
1591            lines.push(match &element.english {
1592                Some(english) => english.join("\n"),
1593                None => element_repr(&element.element),
1594            });
1595            previous_was_voice = false;
1596        }
1597    }
1598    if grouping.num_repeats > 0 {
1599        lines.push(format!("** Grouping x {} **", grouping.num_repeats + 1));
1600    }
1601    if grouping.with_hyphen {
1602        lines.push(format!("music hyphen {}", symbol("music_hyphen")));
1603    }
1604    lines.join("\n")
1605}
1606
1607/// The English of each element of a voice, from the grouping it was
1608/// written in, found by where each stands among the part's leaves.
1609fn voice_english_of(
1610    voice: &Stream,
1611    leaf_base: usize,
1612    written: &BrailleElementGrouping,
1613) -> Vec<Option<Vec<String>>> {
1614    let mut leaf = leaf_base;
1615    voice
1616        .events()
1617        .iter()
1618        .map(|event| {
1619            let english = written
1620                .elements
1621                .iter()
1622                .find(|element| {
1623                    element.leaf == leaf && !matches!(element.element, StreamElement::Stream(_))
1624                })
1625                .and_then(|element| element.english.clone());
1626            leaf += match event.element() {
1627                StreamElement::Stream(inner) => inner.leaves().len(),
1628                _ => 1,
1629            };
1630            english
1631        })
1632        .collect()
1633}
1634
1635/// The English music21 writes on the key signature, time signature, tempo
1636/// words and metronome mark of a heading, in that order: on what it
1637/// transcribes on the way, which leaves out signatures with nothing to
1638/// write and a metronome mark with no number.
1639fn heading_english(
1640    sharps: Option<Option<IntegerType>>,
1641    meter: Option<&TimeSignature>,
1642    tempo: Option<&crate::tempo::TempoText>,
1643    mark: Option<&crate::tempo::MetronomeMark>,
1644    line_length: usize,
1645) -> [Option<Vec<String>>; 4] {
1646    let mut out: [Option<Vec<String>>; 4] = [None, None, None, None];
1647    out[2] = tempo.map(|text| basic::tempo_to_braille(text, line_length).english);
1648    if sharps.is_some() || meter.is_some() || mark.is_some() {
1649        out[3] = mark.and_then(|found| {
1650            basic::metronome_mark_to_braille(found).map(|written| written.english)
1651        });
1652        let empty = meter.is_none() && sharps.is_none_or(|sharps| sharps == Some(0));
1653        if !empty {
1654            out[0] = sharps.map(|sharps| basic::key_sig_to_braille(sharps, None).english);
1655            out[1] = meter.map(|time| basic::time_sig_to_braille(time).english);
1656        }
1657    }
1658    out
1659}
1660
1661/// The state of a segment being written.
1662#[derive(Clone, Debug)]
1663struct SegmentWriter {
1664    text: BrailleText,
1665    keys: VecDeque<SegmentKey>,
1666    current: Option<SegmentKey>,
1667    previous: Option<SegmentKey>,
1668    last_note: Option<Pitch>,
1669}
1670
1671impl SegmentWriter {
1672    fn extract_measure_number(&mut self, segment: &BrailleSegment) -> Result<()> {
1673        let first = self
1674            .keys
1675            .front()
1676            .copied()
1677            .or_else(|| segment.groupings.keys().next().copied());
1678        let Some(first) = first else {
1679            return Ok(());
1680        };
1681        let mut number = number_to_braille(&first.measure.to_string(), true, false)?;
1682        if segment.begins_mid_measure {
1683            number.push_str(&symbol("dot"));
1684        }
1685        self.text.add_measure_number(&number)
1686    }
1687
1688    fn extract_heading(&mut self, segment: &mut BrailleSegment) -> Result<()> {
1689        let mut sharps: Option<Option<IntegerType>> = None;
1690        let mut meter: Option<TimeSignature> = None;
1691        let mut tempo: Option<crate::tempo::TempoText> = None;
1692        let mut mark: Option<crate::tempo::MetronomeMark> = None;
1693        // music21 works through the keys still to write, or, with none
1694        // left, through a fresh list of them all that it then drops.
1695        let from_writer = !self.keys.is_empty();
1696        let mut keys: VecDeque<SegmentKey> = if from_writer {
1697            std::mem::take(&mut self.keys)
1698        } else {
1699            segment.groupings.keys().copied().collect()
1700        };
1701        let mut key_place: Option<(SegmentKey, usize)> = None;
1702        let mut meter_place: Option<(SegmentKey, usize)> = None;
1703        let mut tempo_place: Option<(SegmentKey, usize)> = None;
1704        let mut mark_place: Option<(SegmentKey, usize)> = None;
1705        while let Some(&key) = keys.front() {
1706            if key.affinity > Affinity::MetronomeMark {
1707                break;
1708            }
1709            keys.pop_front();
1710            let grouping = &segment.groupings[&key];
1711            match key.affinity {
1712                Affinity::Signature => {
1713                    if grouping.elements.len() >= 2 {
1714                        sharps = sharps_of(&grouping.elements[0].element);
1715                        key_place = sharps.map(|_| (key, 0));
1716                        if let StreamElement::TimeSignature(time) = &grouping.elements[1].element {
1717                            meter = Some(time.clone());
1718                            meter_place = Some((key, 1));
1719                        }
1720                    } else if let Some(only) = grouping.elements.first() {
1721                        if let Some(found) = sharps_of(&only.element) {
1722                            sharps = Some(found);
1723                            key_place = Some((key, 0));
1724                        } else if let StreamElement::TimeSignature(time) = &only.element {
1725                            meter = Some(time.clone());
1726                            meter_place = Some((key, 0));
1727                        }
1728                    }
1729                }
1730                Affinity::TempoText => {
1731                    if let Some(StreamElement::TempoText(text)) =
1732                        grouping.elements.first().map(|e| &e.element)
1733                    {
1734                        tempo = Some(text.clone());
1735                        tempo_place = Some((key, 0));
1736                    }
1737                }
1738                Affinity::MetronomeMark => {
1739                    if let Some(StreamElement::MetronomeMark(found)) =
1740                        grouping.elements.first().map(|e| &e.element)
1741                    {
1742                        mark = Some(found.clone());
1743                        mark_place = Some((key, 0));
1744                    }
1745                }
1746                _ => {}
1747            }
1748        }
1749        if from_writer {
1750            self.keys = keys;
1751        }
1752        if sharps.is_none() && meter.is_none() && tempo.is_none() && mark.is_none() {
1753            return Ok(());
1754        }
1755        let line_length = self.text.line_length;
1756        let heading = transcribe_heading(
1757            sharps,
1758            meter.as_ref(),
1759            tempo.as_ref(),
1760            mark.as_ref(),
1761            line_length,
1762        )?;
1763        // What music21 transcribes on its way to the heading takes its
1764        // English: the tempo words, the metronome mark with a number, and
1765        // the signatures unless there are none to write.
1766        let mut set = |place: Option<(SegmentKey, usize)>, english: Option<Vec<String>>| {
1767            if let (Some((key, index)), Some(english)) = (place, english) {
1768                segment
1769                    .groupings
1770                    .get_mut(&key)
1771                    .expect("a grouping")
1772                    .elements[index]
1773                    .english = Some(english);
1774            }
1775        };
1776        if let Some(text) = &tempo {
1777            set(
1778                tempo_place,
1779                Some(basic::tempo_to_braille(text, line_length).english),
1780            );
1781        }
1782        if sharps.is_some() || meter.is_some() || mark.is_some() {
1783            if let Some(found) = &mark {
1784                set(
1785                    mark_place,
1786                    basic::metronome_mark_to_braille(found).map(|written| written.english),
1787                );
1788            }
1789            let empty = meter.is_none() && sharps.is_none_or(|sharps| sharps == Some(0));
1790            if !empty {
1791                if let Some(sharps) = sharps {
1792                    set(
1793                        key_place,
1794                        Some(basic::key_sig_to_braille(sharps, None).english),
1795                    );
1796                }
1797                if let Some(time) = &meter {
1798                    set(meter_place, Some(basic::time_sig_to_braille(time).english));
1799                }
1800            }
1801        }
1802        self.text.add_heading(&heading)
1803    }
1804
1805    fn extract_inaccord_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
1806        let key = self.current.expect("a grouping being written");
1807        let grouping = segment.groupings[&key].clone();
1808        let mut pending_clef: Option<BrailleElement> = None;
1809        let mut seen_voice = false;
1810        let mut written: Vec<(usize, Vec<Option<Vec<String>>>)> = Vec::new();
1811        for element in &grouping.elements {
1812            if matches!(element.element, StreamElement::Clef(_)) {
1813                pending_clef = Some(element.clone());
1814                continue;
1815            }
1816            let StreamElement::Stream(voice) = &element.element else {
1817                continue;
1818            };
1819            let mut inner = extract_braille_elements(voice, element.leaf, &segment.contexts);
1820            if let Some(clef) = pending_clef.take() {
1821                inner.elements.insert(0, clef);
1822            }
1823            inner.descending_chords = grouping.descending_chords;
1824            inner.show_clef_signs = grouping.show_clef_signs;
1825            inner.upper_first_in_note_fingering = grouping.upper_first_in_note_fingering;
1826            let mut braille = if seen_voice {
1827                symbol("full_inaccord")
1828            } else {
1829                String::new()
1830            };
1831            braille.push_str(&transcribe_note_grouping(&mut inner, true));
1832            written.push((element.leaf, voice_english_of(voice, element.leaf, &inner)));
1833            self.text.add_inaccord(&braille)?;
1834            seen_voice = true;
1835        }
1836        let stored = segment.groupings.get_mut(&key).expect("a grouping");
1837        for (leaf, english) in written {
1838            if let Some(element) = stored.elements.iter_mut().find(|element| {
1839                element.leaf == leaf && matches!(element.element, StreamElement::Stream(_))
1840            }) {
1841                element.voice_english = english;
1842            }
1843        }
1844        Ok(())
1845    }
1846
1847    fn extract_long_expression_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
1848        let key = self.current.expect("a grouping being written");
1849        let grouping = segment.groupings.get_mut(&key).expect("a grouping");
1850        if let Some(first) = grouping.elements.first_mut()
1851            && let StreamElement::TextExpression(text) = &first.element
1852        {
1853            let written = text_expression_to_braille(text, true);
1854            first.english = Some(written.english);
1855            self.text.add_long_expression(&written.braille)?;
1856        }
1857        Ok(())
1858    }
1859
1860    fn show_leading_octave_from(
1861        &mut self,
1862        grouping: &BrailleElementGrouping,
1863        suppress: bool,
1864    ) -> bool {
1865        if let (Some(previous), Some(current)) = (self.previous, self.current)
1866            && (previous.affinity != Affinity::NoteGrouping
1867                || current.affinity != Affinity::NoteGrouping
1868                || (current.measure == previous.measure
1869                    && current.ordinal == previous.ordinal + 1
1870                    && current.hand == previous.hand))
1871        {
1872            self.last_note = None;
1873        }
1874        if suppress {
1875            return false;
1876        }
1877        let notes: Vec<&Pitch> = grouping
1878            .elements
1879            .iter()
1880            .filter_map(|element| match &element.element {
1881                StreamElement::Note(note) => Some(note.pitch()),
1882                _ => None,
1883            })
1884            .collect();
1885        let mut show = true;
1886        if let (Some(first), Some(last)) = (notes.first(), notes.last()) {
1887            if let Some(previous) = &self.last_note {
1888                show = basic::show_octave_with_note(Some(previous), first);
1889            }
1890            self.last_note = Some((*last).clone());
1891        }
1892        show
1893    }
1894
1895    fn needs_split_to_fit(&mut self, braille: &str) -> bool {
1896        self.needs_split_for(braille.chars().count())
1897    }
1898
1899    fn needs_split_for(&mut self, cells: usize) -> bool {
1900        let quarter = self.text.line_length / 4;
1901        let left = self.text.line_length - self.text.current_line().text_location;
1902        left > quarter && cells > quarter
1903    }
1904
1905    fn extract_note_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
1906        let key = self.current.expect("a grouping being written");
1907        let suppress = segment.options.suppress_octave_marks;
1908        let mut grouping = segment.groupings[&key].clone();
1909        let show_leading = self.show_leading_octave_from(&grouping, suppress);
1910        let mut transcriber = NoteGroupingTranscriber {
1911            show_leading_octave: show_leading,
1912            ..NoteGroupingTranscriber::default()
1913        };
1914        let mut braille = transcriber.transcribe_group(&mut grouping);
1915        let add_space = self
1916            .text
1917            .optional_add_keyboard_symbols_and_dots(Some(&braille))?;
1918        if self.text.current_line().can_append(&braille, add_space) {
1919            self.text.current_line().append(&braille, add_space)?;
1920        } else {
1921            let mut split = false;
1922            if self.needs_split_to_fit(&braille)
1923                && let Some((first, second)) =
1924                    self.split_and_transcribe(segment, &mut grouping, show_leading, add_space)?
1925            {
1926                split = true;
1927                self.text.current_line().append(&first, add_space)?;
1928                self.text.add_to_new_line(&second)?;
1929            }
1930            if !split {
1931                if !show_leading && !suppress {
1932                    transcriber.show_leading_octave = true;
1933                    braille = transcriber.transcribe_group(&mut grouping);
1934                }
1935                self.text.current_line().last_hyphen_to_space();
1936                self.text.add_to_new_line(&braille)?;
1937            }
1938        }
1939        segment.groupings.insert(key, grouping.clone());
1940        self.add_repeat_symbols(grouping.num_repeats)?;
1941        Ok(())
1942    }
1943
1944    fn split_and_transcribe(
1945        &mut self,
1946        segment: &mut BrailleSegment,
1947        grouping: &mut BrailleElementGrouping,
1948        show_leading_octave_on_first: bool,
1949        add_space_to_first: bool,
1950    ) -> Result<Option<(String, String)>> {
1951        let mut transcriber = NoteGroupingTranscriber::default();
1952        let mut offset = 0;
1953        let mut halves = None;
1954        let mut first_braille = String::new();
1955        while offset < 10 {
1956            let Some(((mut first, sources), second)) = split_with_sources(grouping, offset)? else {
1957                return Ok(None);
1958            };
1959            transcriber.show_leading_octave = show_leading_octave_on_first;
1960            first.with_hyphen = true;
1961            first_braille = transcriber.transcribe_group(&mut first);
1962            // The halves hold the grouping's own elements in music21, so what
1963            // writing the first half says of each stays on it.
1964            for (element, source) in first.elements.iter().zip(sources) {
1965                grouping.elements[source].english = element.english.clone();
1966            }
1967            let fits = self
1968                .text
1969                .current_line()
1970                .can_append(&first_braille, add_space_to_first);
1971            halves = Some((first, second));
1972            if fits {
1973                break;
1974            }
1975            offset += 1;
1976        }
1977        let (first, (mut second, second_sources)) = halves.expect("at least one split is tried");
1978        transcriber.show_leading_octave = !segment.options.suppress_octave_marks;
1979        let second_braille = transcriber.transcribe_group(&mut second);
1980        for (element, source) in second.elements.iter().zip(second_sources) {
1981            grouping.elements[source].english = element.english.clone();
1982        }
1983        let key = self.current.expect("a grouping being written");
1984        segment.groupings.insert(
1985            SegmentKey {
1986                affinity: Affinity::SplitNoteGroupingA,
1987                ..key
1988            },
1989            first,
1990        );
1991        segment.groupings.insert(
1992            SegmentKey {
1993                affinity: Affinity::SplitNoteGroupingB,
1994                ..key
1995            },
1996            second,
1997        );
1998        Ok(Some((first_braille, second_braille)))
1999    }
2000
2001    fn add_repeat_symbols(&mut self, times: usize) -> Result<()> {
2002        if (1..3).contains(&times) {
2003            for _ in 0..times {
2004                self.text.add_signatures(&symbol("repeat"))?;
2005            }
2006        } else if times >= 3 {
2007            let number = number_to_braille(&times.to_string(), true, false)?;
2008            self.text.add_signatures(&(symbol("repeat") + &number))?;
2009            self.last_note = None;
2010        }
2011        Ok(())
2012    }
2013
2014    fn extract_signature_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2015        let key = self.current.expect("a grouping being written");
2016        let grouping = segment.groupings.get_mut(&key).expect("a grouping");
2017        let (key_index, meter_index) = match grouping.elements.len() {
2018            0 => (None, None),
2019            1 => {
2020                if sharps_of(&grouping.elements[0].element).is_some() {
2021                    (Some(0), None)
2022                } else {
2023                    (None, Some(0))
2024                }
2025            }
2026            _ => (Some(0), Some(1)),
2027        };
2028        let sharps = key_index.and_then(|index| sharps_of(&grouping.elements[index].element));
2029        let outgoing = if segment.options.cancel_outgoing_key_sig {
2030            key_index.and_then(|index| grouping.elements[index].outgoing_key)
2031        } else {
2032            None
2033        };
2034        let meter = meter_index.and_then(|index| match &grouping.elements[index].element {
2035            StreamElement::TimeSignature(meter) => Some(meter.clone()),
2036            _ => None,
2037        });
2038        let written = transcribe_signatures(sharps, meter.as_ref(), outgoing);
2039        if let Some(index) = key_index
2040            && let Some(sharps) = sharps
2041        {
2042            grouping.elements[index].english =
2043                Some(basic::key_sig_to_braille(sharps, outgoing).english);
2044        }
2045        if let (Some(index), Some(meter)) = (meter_index, &meter) {
2046            grouping.elements[index].english = Some(basic::time_sig_to_braille(meter).english);
2047        }
2048        if !written.braille.is_empty() {
2049            self.text.add_signatures(&written.braille)?;
2050        }
2051        Ok(())
2052    }
2053
2054    fn extract_tempo_text_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2055        let current = self.current.expect("a grouping being written");
2056        self.keys.push_front(current);
2057        let previous = self
2058            .previous
2059            .ok_or_else(|| Error::Notation("tempo text with no grouping before it".to_string()))?;
2060        if previous.affinity == Affinity::Signature {
2061            self.keys.push_front(previous);
2062        }
2063        self.extract_heading(segment)?;
2064        self.extract_measure_number(segment)
2065    }
2066}
2067
2068/// A segment written into a text a step at a time, with what music21's
2069/// segment keeps while it writes: the keys still to write, the grouping
2070/// being written and the one before it, and the last note written.
2071///
2072/// [`BrailleSegment::transcribe`] is [`SegmentTranscriber::transcribe`]
2073/// into a fresh text; each other step is one of music21's `extract*`
2074/// methods, which its own examples call one at a time.
2075#[derive(Clone, Debug)]
2076pub struct SegmentTranscriber {
2077    writer: SegmentWriter,
2078}
2079
2080impl SegmentTranscriber {
2081    /// A transcriber writing into a text, with nothing to write yet.
2082    pub fn new(text: BrailleText) -> Self {
2083        Self {
2084            writer: SegmentWriter {
2085                text,
2086                keys: VecDeque::new(),
2087                current: None,
2088                previous: None,
2089                last_note: None,
2090            },
2091        }
2092    }
2093
2094    /// The text written so far.
2095    pub fn text(&self) -> &BrailleText {
2096        &self.writer.text
2097    }
2098
2099    /// The text, to write into directly.
2100    pub fn text_mut(&mut self) -> &mut BrailleText {
2101        &mut self.writer.text
2102    }
2103
2104    /// The text, once the writing is done.
2105    pub fn into_text(self) -> BrailleText {
2106        self.writer.text
2107    }
2108
2109    /// The keys still to write: music21's `groupingKeysToProcess`.
2110    pub fn keys_mut(&mut self) -> &mut VecDeque<SegmentKey> {
2111        &mut self.writer.keys
2112    }
2113
2114    /// The grouping being written: music21's `currentGroupingKey`.
2115    pub fn current(&self) -> Option<SegmentKey> {
2116        self.writer.current
2117    }
2118
2119    /// Sets the grouping being written.
2120    pub fn set_current(&mut self, key: Option<SegmentKey>) {
2121        self.writer.current = key;
2122    }
2123
2124    /// The grouping written before it: music21's `previousGroupingKey`.
2125    pub fn previous(&self) -> Option<SegmentKey> {
2126        self.writer.previous
2127    }
2128
2129    /// Sets the grouping written before.
2130    pub fn set_previous(&mut self, key: Option<SegmentKey>) {
2131        self.writer.previous = key;
2132    }
2133
2134    /// The pitch of the last note written: music21's `lastNote`.
2135    pub fn last_note(&self) -> Option<&Pitch> {
2136        self.writer.last_note.as_ref()
2137    }
2138
2139    /// Sets the last note written.
2140    pub fn set_last_note(&mut self, pitch: Option<Pitch>) {
2141        self.writer.last_note = pitch;
2142    }
2143
2144    /// The whole segment: its heading and first measure number, then each
2145    /// grouping in turn: music21's `transcribe`.
2146    ///
2147    /// # Errors
2148    ///
2149    /// Something too wide for a line, or that music21 cannot write.
2150    pub fn transcribe(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2151        let writer = &mut self.writer;
2152        writer.keys = segment.groupings.keys().copied().collect();
2153        if segment.options.show_heading {
2154            writer.extract_heading(segment)?;
2155        }
2156        if segment.options.show_first_measure_number {
2157            writer.extract_measure_number(segment)?;
2158        }
2159        if segment.options.dummy_rest_length.is_some() {
2160            self.add_dummy_rests(segment)?;
2161        }
2162        let writer = &mut self.writer;
2163        writer.previous = None;
2164        while let Some(key) = writer.keys.pop_front() {
2165            writer.current = Some(key);
2166            match key.affinity {
2167                Affinity::NoteGrouping => writer.extract_note_grouping(segment)?,
2168                Affinity::Signature => writer.extract_signature_grouping(segment)?,
2169                Affinity::LongTextExpression => writer.extract_long_expression_grouping(segment)?,
2170                Affinity::Inaccord => writer.extract_inaccord_grouping(segment)?,
2171                Affinity::TempoText => writer.extract_tempo_text_grouping(segment)?,
2172                _ => {}
2173            }
2174            writer.previous = writer.current;
2175        }
2176        Ok(())
2177    }
2178
2179    /// The heading out of the signatures, tempo and metronome mark the
2180    /// segment starts with: music21's `extractHeading`.
2181    ///
2182    /// # Errors
2183    ///
2184    /// A heading too wide for a line.
2185    pub fn extract_heading(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2186        self.writer.extract_heading(segment)
2187    }
2188
2189    /// The number of the first measure still to write: music21's
2190    /// `extractMeasureNumber`.
2191    ///
2192    /// # Errors
2193    ///
2194    /// A number too wide for a line.
2195    pub fn extract_measure_number(&mut self, segment: &BrailleSegment) -> Result<()> {
2196        self.writer.extract_measure_number(segment)
2197    }
2198
2199    /// As many dummy rests as the segment asks for: music21's
2200    /// `addDummyRests`.
2201    ///
2202    /// # Errors
2203    ///
2204    /// Rests too many for a line.
2205    pub fn add_dummy_rests(&mut self, segment: &BrailleSegment) -> Result<()> {
2206        let length = segment.options.dummy_rest_length.unwrap_or(0);
2207        let dummy = lookup::rest("dummy").unwrap_or_default().repeat(length);
2208        self.writer.text.add_signatures(&dummy)
2209    }
2210
2211    /// The grouping being written, a group of notes: music21's
2212    /// `extractNoteGrouping`.
2213    ///
2214    /// # Errors
2215    ///
2216    /// No grouping being written, or one too wide for a line.
2217    pub fn extract_note_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2218        self.require_current(segment)?;
2219        self.writer.extract_note_grouping(segment)
2220    }
2221
2222    /// The grouping being written, signatures: music21's
2223    /// `extractSignatureGrouping`.
2224    ///
2225    /// # Errors
2226    ///
2227    /// No grouping being written, or signatures too wide for a line.
2228    pub fn extract_signature_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2229        self.require_current(segment)?;
2230        self.writer.extract_signature_grouping(segment)
2231    }
2232
2233    /// The grouping being written, a long text: music21's
2234    /// `extractLongExpressionGrouping`.
2235    ///
2236    /// # Errors
2237    ///
2238    /// No grouping being written.
2239    pub fn extract_long_expression_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2240        self.require_current(segment)?;
2241        self.writer.extract_long_expression_grouping(segment)
2242    }
2243
2244    /// The grouping being written, voices in accord: music21's
2245    /// `extractInaccordGrouping`.
2246    ///
2247    /// # Errors
2248    ///
2249    /// No grouping being written, or a voice too wide for a line.
2250    pub fn extract_inaccord_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2251        self.require_current(segment)?;
2252        self.writer.extract_inaccord_grouping(segment)
2253    }
2254
2255    /// The grouping being written, tempo words, which start a heading of
2256    /// their own: music21's `extractTempoTextGrouping`.
2257    ///
2258    /// # Errors
2259    ///
2260    /// No grouping being written or none before it.
2261    pub fn extract_tempo_text_grouping(&mut self, segment: &mut BrailleSegment) -> Result<()> {
2262        self.require_current(segment)?;
2263        self.writer.extract_tempo_text_grouping(segment)
2264    }
2265
2266    /// Whether a grouping written next shows its first note's octave:
2267    /// music21's `showLeadingOctaveFromNoteGrouping`.
2268    pub fn show_leading_octave_from(
2269        &mut self,
2270        grouping: &BrailleElementGrouping,
2271        suppress_octave_marks: bool,
2272    ) -> bool {
2273        self.writer
2274            .show_leading_octave_from(grouping, suppress_octave_marks)
2275    }
2276
2277    /// Whether braille this long has to be split to fit what is left of
2278    /// the line: music21's `needsSplitToFit`.
2279    pub fn needs_split_to_fit(&mut self, braille: &str) -> bool {
2280        self.writer.needs_split_to_fit(braille)
2281    }
2282
2283    /// The same for something so many cells long.
2284    pub fn needs_split_for(&mut self, cells: usize) -> bool {
2285        self.writer.needs_split_for(cells)
2286    }
2287
2288    /// The grouping being written split where the line has room, each half
2289    /// written and kept in the segment under its own key: music21's
2290    /// `splitNoteGroupingAndTranscribe`. Nothing where no split fits.
2291    ///
2292    /// # Errors
2293    ///
2294    /// No grouping being written, or a meter that cannot be halved.
2295    pub fn split_and_transcribe(
2296        &mut self,
2297        segment: &mut BrailleSegment,
2298        show_leading_octave_on_first: bool,
2299        add_space_to_first: bool,
2300    ) -> Result<Option<(String, String)>> {
2301        let key = self.require_current(segment)?;
2302        let mut grouping = segment.groupings[&key].clone();
2303        let split = self.writer.split_and_transcribe(
2304            segment,
2305            &mut grouping,
2306            show_leading_octave_on_first,
2307            add_space_to_first,
2308        )?;
2309        segment.groupings.insert(key, grouping);
2310        Ok(split)
2311    }
2312
2313    /// The signs for a grouping repeated so many times: music21's
2314    /// `addRepeatSymbols`.
2315    ///
2316    /// # Errors
2317    ///
2318    /// Signs too wide for a line.
2319    pub fn add_repeat_symbols(&mut self, times: usize) -> Result<()> {
2320        self.writer.add_repeat_symbols(times)
2321    }
2322
2323    /// The grouping being written, which the segment has to hold.
2324    fn require_current(&self, segment: &BrailleSegment) -> Result<SegmentKey> {
2325        self.writer
2326            .current
2327            .filter(|key| segment.groupings.contains_key(key))
2328            .ok_or_else(|| {
2329                Error::Notation("no grouping of the segment is being written".to_string())
2330            })
2331    }
2332}
2333
2334/// The keys of a measure's groupings for the right hand and the left, either
2335/// missing where that hand has none.
2336pub type KeyPair = (Option<SegmentKey>, Option<SegmentKey>);
2337
2338/// A piano's two staves cut into segments of groupings for each hand,
2339/// written side by side: music21's `BrailleGrandSegment`.
2340#[derive(Clone, Debug)]
2341pub struct BrailleGrandSegment {
2342    /// The groupings of both hands, by key.
2343    pub groupings: BTreeMap<SegmentKey, BrailleElementGrouping>,
2344    /// How many cells a line holds.
2345    pub line_length: usize,
2346    /// What music21 marked on each leaf of the right hand's part.
2347    pub right_contexts: Vec<NoteContext>,
2348    /// What music21 marked on each leaf of the left hand's part.
2349    pub left_contexts: Vec<NoteContext>,
2350}
2351
2352impl BrailleGrandSegment {
2353    /// The keys of the two hands, paired measure by measure: music21's
2354    /// `yieldCombinedGroupingKeys`.
2355    pub fn combined_keys(&self) -> Vec<KeyPair> {
2356        let mut keys: Vec<SegmentKey> = self.groupings.keys().copied().collect();
2357        keys.sort_by_key(|key| {
2358            (
2359                key.measure,
2360                key.ordinal,
2361                key.affinity,
2362                if key.hand == Some(Hand::Right) { -1 } else { 1 },
2363            )
2364        });
2365        let matches = |one: &SegmentKey, other: &SegmentKey| {
2366            one.measure == other.measure
2367                && one.ordinal == other.ordinal
2368                && one.affinity == other.affinity
2369        };
2370        let mut out = Vec::new();
2371        let mut stored_right: Option<SegmentKey> = None;
2372        let mut stored_left: Option<SegmentKey> = None;
2373        for key in keys {
2374            match key.hand {
2375                Some(Hand::Right) => {
2376                    if let Some(left) = stored_left.take() {
2377                        if matches(&key, &left)
2378                            || (key.affinity == Affinity::NoteGrouping
2379                                && matches(
2380                                    &SegmentKey {
2381                                        affinity: Affinity::Inaccord,
2382                                        ..key
2383                                    },
2384                                    &left,
2385                                ))
2386                        {
2387                            out.push((Some(key), Some(left)));
2388                        } else {
2389                            out.push((None, Some(left)));
2390                            stored_right = Some(key);
2391                        }
2392                    } else {
2393                        if let Some(right) = stored_right {
2394                            out.push((Some(right), None));
2395                        }
2396                        stored_right = Some(key);
2397                    }
2398                }
2399                Some(Hand::Left) => {
2400                    if let Some(right) = stored_right.take() {
2401                        if matches(&key, &right) {
2402                            out.push((Some(right), Some(key)));
2403                        } else if right.affinity < Affinity::Inaccord {
2404                            out.push((Some(right), None));
2405                            out.push((None, Some(key)));
2406                        } else {
2407                            out.push((Some(right), None));
2408                            stored_left = Some(key);
2409                        }
2410                    } else {
2411                        if let Some(left) = stored_left {
2412                            out.push((None, Some(left)));
2413                        }
2414                        stored_left = Some(key);
2415                    }
2416                }
2417                None => {}
2418            }
2419        }
2420        if let Some(right) = stored_right {
2421            out.push((Some(right), None));
2422        }
2423        if let Some(left) = stored_left {
2424            out.push((None, Some(left)));
2425        }
2426        out
2427    }
2428
2429    /// The two hands in braille: a heading, then each measure's groupings
2430    /// side by side: music21's `transcribe`.
2431    ///
2432    /// # Errors
2433    ///
2434    /// Something too wide for a line, or that music21 cannot write.
2435    pub fn transcribe(&mut self) -> Result<String> {
2436        let mut keyboard = BrailleKeyboard::new(self.line_length);
2437        self.transcribe_into(&mut keyboard)?;
2438        Ok(keyboard.text.render())
2439    }
2440
2441    /// [`BrailleGrandSegment::transcribe`] into a keyboard's text as it
2442    /// stands, rather than a fresh one.
2443    ///
2444    /// # Errors
2445    ///
2446    /// Something too wide for a line, or that music21 cannot write.
2447    pub fn transcribe_into(&mut self, keyboard: &mut BrailleKeyboard) -> Result<()> {
2448        let mut pairs: VecDeque<KeyPair> = self.combined_keys().into();
2449        let Some(last) = pairs.back().copied() else {
2450            return Ok(());
2451        };
2452        let highest = last.0.or(last.1).map_or(0, |key| key.measure);
2453        keyboard.highest_measure_number_length = highest.to_string().chars().count();
2454        self.extract_heading(&mut pairs, keyboard)?;
2455        while let Some(pair) = pairs.pop_front() {
2456            let writes = pair.0.is_some_and(|key| key.affinity >= Affinity::Inaccord)
2457                || pair.1.is_some_and(|key| key.affinity >= Affinity::Inaccord);
2458            if writes {
2459                self.extract_note_grouping(pair, keyboard)?;
2460            }
2461        }
2462        Ok(())
2463    }
2464
2465    /// The heading out of the pairs the segment starts with, which it
2466    /// takes off them: music21's `extractHeading`. Nothing is written
2467    /// where there is nothing for a heading.
2468    ///
2469    /// # Errors
2470    ///
2471    /// A heading too wide for a line.
2472    pub fn extract_heading(
2473        &mut self,
2474        pairs: &mut VecDeque<KeyPair>,
2475        keyboard: &mut BrailleKeyboard,
2476    ) -> Result<()> {
2477        let mut sharps: Option<Option<IntegerType>> = None;
2478        let mut meter: Option<TimeSignature> = None;
2479        let mut tempo: Option<crate::tempo::TempoText> = None;
2480        let mut mark: Option<crate::tempo::MetronomeMark> = None;
2481        let mut places: [Option<(SegmentKey, usize)>; 4] = [None; 4];
2482        while let Some(&(right, left)) = pairs.front() {
2483            let Some(use_key) = right.or(left) else {
2484                break;
2485            };
2486            if use_key.affinity > Affinity::MetronomeMark {
2487                break;
2488            }
2489            pairs.pop_front();
2490            let grouping = &self.groupings[&use_key];
2491            match use_key.affinity {
2492                Affinity::Signature => {
2493                    // Each element read by what it is, the first key and
2494                    // the first meter of the heading winning.
2495                    for (index, held) in grouping.elements.iter().enumerate() {
2496                        if sharps.is_none()
2497                            && let Some(found) = sharps_of(&held.element)
2498                        {
2499                            sharps = Some(found);
2500                            places[0] = found.map(|_| (use_key, index));
2501                        } else if meter.is_none()
2502                            && let StreamElement::TimeSignature(time) = &held.element
2503                        {
2504                            meter = Some(time.clone());
2505                            places[1] = Some((use_key, index));
2506                        }
2507                    }
2508                }
2509                Affinity::TempoText => {
2510                    if let Some(StreamElement::TempoText(text)) =
2511                        grouping.elements.first().map(|e| &e.element)
2512                    {
2513                        tempo = Some(text.clone());
2514                        places[2] = Some((use_key, 0));
2515                    }
2516                }
2517                Affinity::MetronomeMark => {
2518                    if let Some(StreamElement::MetronomeMark(found)) =
2519                        grouping.elements.first().map(|e| &e.element)
2520                    {
2521                        mark = Some(found.clone());
2522                        places[3] = Some((use_key, 0));
2523                    }
2524                }
2525                _ => {}
2526            }
2527        }
2528        if let Ok(heading) = transcribe_heading(
2529            sharps,
2530            meter.as_ref(),
2531            tempo.as_ref(),
2532            mark.as_ref(),
2533            self.line_length,
2534        ) {
2535            let english = heading_english(
2536                sharps,
2537                meter.as_ref(),
2538                tempo.as_ref(),
2539                mark.as_ref(),
2540                self.line_length,
2541            );
2542            for (place, english) in places.into_iter().zip(english) {
2543                if let (Some((key, index)), Some(english)) = (place, english) {
2544                    self.groupings.get_mut(&key).expect("a grouping").elements[index].english =
2545                        Some(english);
2546                }
2547            }
2548            keyboard.text.add_heading(&heading)?;
2549        }
2550        Ok(())
2551    }
2552
2553    /// A measure's pair of groupings written side by side: music21's
2554    /// `extractNoteGrouping`.
2555    ///
2556    /// # Errors
2557    ///
2558    /// A pair with neither hand, or a grouping too wide for a line.
2559    pub fn extract_note_grouping(
2560        &mut self,
2561        (right, left): KeyPair,
2562        keyboard: &mut BrailleKeyboard,
2563    ) -> Result<()> {
2564        let Some(measure) = right.or(left).map(|key| key.measure) else {
2565            return Err(Error::Notation(
2566                "Measure must be defined for leftKey or rightKey".to_string(),
2567            ));
2568        };
2569        let number = number_to_braille(&measure.to_string(), false, false)?;
2570        let right_braille = self.braille_from_key(right)?;
2571        let left_braille = self.braille_from_key(left)?;
2572        keyboard.add_note_groupings(&number, &right_braille, &left_braille)
2573    }
2574
2575    fn braille_from_key(&mut self, key: Option<SegmentKey>) -> Result<String> {
2576        let Some(key) = key else {
2577            return Ok(String::new());
2578        };
2579        let contexts = if key.hand == Some(Hand::Left) {
2580            &self.left_contexts
2581        } else {
2582            &self.right_contexts
2583        };
2584        let grouping = self.groupings.get_mut(&key).expect("a grouping");
2585        if key.affinity == Affinity::Inaccord {
2586            let mut voices = Vec::new();
2587            let (descending, clefs, upper) = (
2588                grouping.descending_chords,
2589                grouping.show_clef_signs,
2590                grouping.upper_first_in_note_fingering,
2591            );
2592            for element in &mut grouping.elements {
2593                let StreamElement::Stream(voice) = &element.element else {
2594                    continue;
2595                };
2596                let mut inner = extract_braille_elements(voice, element.leaf, contexts);
2597                inner.descending_chords = descending;
2598                inner.show_clef_signs = clefs;
2599                inner.upper_first_in_note_fingering = upper;
2600                voices.push(transcribe_note_grouping(&mut inner, true));
2601                element.voice_english = voice_english_of(voice, element.leaf, &inner);
2602            }
2603            Ok(voices.join(&symbol("full_inaccord")))
2604        } else {
2605            Ok(transcribe_note_grouping(grouping, true))
2606        }
2607    }
2608
2609    /// The two hands' groupings in English, as music21's `__str__` lists
2610    /// them.
2611    pub fn english(&self) -> String {
2612        let mut pairs = String::new();
2613        for (right, left) in self.combined_keys() {
2614            let right_full = right.map_or_else(String::new, |key| {
2615                format!(
2616                    "Measure {} Right, {} {}:\n{}",
2617                    key.measure,
2618                    key.affinity.name(),
2619                    key.ordinal + 1,
2620                    grouping_english(&self.groupings[&key])
2621                )
2622            });
2623            let left_full = left.map_or_else(String::new, |key| {
2624                format!(
2625                    "\nMeasure {} Left, {} {}:\n{}",
2626                    key.measure,
2627                    key.affinity.name(),
2628                    key.ordinal + 1,
2629                    grouping_english(&self.groupings[&key])
2630                )
2631            });
2632            pairs.push_str(&[right_full, left_full, "====\n".to_string()].join("\n"));
2633        }
2634        [
2635            "---begin grand segment---".to_string(),
2636            "<music21.braille.segment BrailleGrandSegment>\n===".to_string(),
2637            pairs,
2638            "---end grand segment---".to_string(),
2639        ]
2640        .join("\n")
2641    }
2642}
2643
2644#[cfg(test)]
2645mod tests {
2646    use super::*;
2647    use crate::chord::Chord;
2648
2649    fn element(element: StreamElement) -> BrailleElement {
2650        BrailleElement {
2651            element,
2652            offset: 0.0,
2653            affinity: Affinity::NoteGrouping,
2654            sort_order: 0,
2655            english: None,
2656            context: NoteContext::default(),
2657            outgoing_key: None,
2658            leaf: 0,
2659            voice_english: Vec::new(),
2660        }
2661    }
2662
2663    /// A note after a note or chord written as the exception sign shows
2664    /// its octave.
2665    #[test]
2666    fn octave_after_exception_sign() -> Result<()> {
2667        let short = Duration::new(1.0 / 64.0)?;
2668        let mut short_note = Note::from_name("E4")?;
2669        short_note.set_duration(short.clone());
2670        let short_chord = Chord::new("E4 G4")?.with_duration(short);
2671        for unbrailled in [
2672            StreamElement::Note(short_note),
2673            StreamElement::Chord(short_chord),
2674        ] {
2675            for (show_leading_octave, expected) in [(true, "⠐⠹⠜⠦⠐⠹"), (false, "⠹⠜⠦⠐⠹")]
2676            {
2677                let mut grouping = BrailleElementGrouping {
2678                    elements: vec![
2679                        element(StreamElement::Note(Note::from_name("C4")?)),
2680                        element(unbrailled.clone()),
2681                        element(StreamElement::Note(Note::from_name("C4")?)),
2682                    ],
2683                    ..BrailleElementGrouping::default()
2684                };
2685                let mut transcriber = NoteGroupingTranscriber {
2686                    show_leading_octave,
2687                    ..NoteGroupingTranscriber::default()
2688                };
2689                assert_eq!(transcriber.transcribe_group(&mut grouping), expected);
2690            }
2691        }
2692        Ok(())
2693    }
2694}