1use super::basic::word_to_braille;
4use super::lookup;
5use super::segment::{BrailleGrandSegment, Hand, SegmentOptions, find_segments};
6use crate::{
7 error::{Error, Result},
8 metadata::Metadata,
9 stream::{Stream, StreamElement, StreamKind},
10};
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct BrailleOptions {
17 pub in_place: bool,
20 pub debug: bool,
23 pub segment: SegmentOptions,
25}
26
27pub fn stream_to_braille(stream: &Stream, options: &BrailleOptions) -> Result<String> {
35 match stream.kind() {
36 StreamKind::Part | StreamKind::PartStaff => part_to_braille(stream, options),
37 StreamKind::Measure => measure_to_braille(stream, options),
38 StreamKind::Score => score_to_braille(stream, options),
39 StreamKind::Opus => {
40 let scores: Vec<String> = stream
41 .events()
42 .iter()
43 .filter_map(|event| event.element().as_stream())
44 .filter(|inner| inner.kind() == StreamKind::Score)
45 .map(|score| score_to_braille(score, options))
46 .collect::<Result<_>>()?;
47 Ok(scores.join("\n\n"))
48 }
49 _ => {
50 let staves: Vec<&Stream> = stream
51 .events()
52 .iter()
53 .filter_map(|event| event.element().as_stream())
54 .filter(|inner| inner.kind() == StreamKind::PartStaff)
55 .collect();
56 if staves.len() == 2 {
57 score_to_braille(stream, options)
58 } else {
59 Err(Error::Notation(
60 "Stream cannot be translated to Braille.".to_string(),
61 ))
62 }
63 }
64 }
65}
66
67pub fn score_to_braille(score: &Stream, options: &BrailleOptions) -> Result<String> {
74 let mut lines = Vec::new();
75 if let Some(metadata) = score.metadata() {
76 lines.push(metadata_to_string(metadata, !options.debug)?);
77 }
78 let mut pending: Option<Stream> = None;
79 let mut first_leaf = 0;
80 for event in score.events() {
81 let leaves = match event.element() {
82 StreamElement::Stream(inner) => inner.leaves().len(),
83 _ => 1,
84 };
85 let start = first_leaf;
86 first_leaf += leaves;
87 let Some(part) = event.element().as_stream() else {
88 continue;
89 };
90 let part = &with_own_spanners(score, part, start);
91 match part.kind() {
92 StreamKind::PartStaff => {
93 if let Some(upper) = pending.take() {
94 lines.push(keyboard_parts_to_braille(&upper, part, options)?);
95 } else {
96 pending = Some(part.clone());
97 }
98 }
99 StreamKind::Part => {
100 if let Some(alone) = pending.take() {
101 lines.push(part_to_braille(&alone, options)?);
102 }
103 lines.push(part_to_braille(part, options)?);
104 }
105 _ => {}
106 }
107 }
108 if let Some(alone) = pending {
109 lines.push(part_to_braille(&alone, options)?);
110 }
111 Ok(lines.join("\n"))
112}
113
114fn with_own_spanners(score: &Stream, part: &Stream, start: usize) -> Stream {
120 let mut part = part.clone();
121 let later_staff = part.kind() == StreamKind::PartStaff
122 && part
123 .id()
124 .and_then(|id| id.rsplit_once("-Staff"))
125 .is_some_and(|(_, number)| number != "1");
126 if later_staff {
127 return part;
128 }
129 let end = start + part.leaves().len();
130 let inside = |place: Option<&Option<usize>>| {
131 place.is_some_and(|place| place.is_some_and(|place| (start..end).contains(&place)))
132 };
133 for spanner in score.spanners() {
134 let places = spanner.spanned();
135 if inside(places.first()) && inside(places.last()) {
136 let mut own = spanner.clone();
137 let moved: Vec<Option<usize>> =
138 (0..end).map(|place| place.checked_sub(start)).collect();
139 own.move_places(&moved);
140 part.add_spanner(own);
141 }
142 }
143 part
144}
145
146pub fn metadata_to_string(metadata: &Metadata, braille: bool) -> Result<String> {
153 let mut lines = Vec::new();
154 for (unique_name, value) in metadata.all() {
155 if unique_name == "software" {
156 continue;
157 }
158 let Some(namespace) = crate::metadata::namespace_name(unique_name) else {
159 continue;
160 };
161 if namespace.starts_with("m21FileInfo:") {
162 continue;
163 }
164 let words = split_camel_case(unique_name);
165 let mut line = format!(
166 "{}: {}",
167 crate::common::stringtools::title_case(&words.join(" ")),
168 value.text()
169 );
170 if braille {
171 let written: Vec<String> = line
172 .split_whitespace()
173 .map(|word| word_to_braille(word, false))
174 .collect::<Result<_>>()?;
175 line = written.join(&lookup::alphabet(' ').unwrap_or_default());
176 }
177 lines.push(line);
178 }
179 lines.sort();
180 Ok(lines.join("\n"))
181}
182
183fn split_camel_case(name: &str) -> Vec<String> {
186 let characters: Vec<char> = name.chars().collect();
187 let mut words = Vec::new();
188 let mut index = 0;
189 while index < characters.len() {
190 let start = index;
191 let mut upper_end = index;
192 while upper_end < characters.len() && characters[upper_end].is_ascii_uppercase() {
193 upper_end += 1;
194 }
195 let mut lower_end = upper_end;
196 while lower_end < characters.len() && characters[lower_end].is_ascii_lowercase() {
197 lower_end += 1;
198 }
199 if lower_end > upper_end {
200 words.push(characters[start..lower_end].iter().collect());
201 index = lower_end;
202 } else {
203 index = start + 1;
204 }
205 }
206 words
207}
208
209fn notated(part: &Stream, options: &BrailleOptions) -> Result<Stream> {
212 let mut part = part.clone();
213 if !options.in_place {
214 crate::makenotation::make_part_notation_keeping_spanners(&mut part, false)?;
215 }
216 Ok(part)
217}
218
219pub fn part_to_braille(part: &Stream, options: &BrailleOptions) -> Result<String> {
225 let part = notated(part, options)?;
226 let mut segments = find_segments(&part, None, options.segment);
227 let mut written = Vec::new();
228 for segment in &mut segments {
229 let braille = segment.transcribe()?;
230 written.push(if options.debug {
231 segment.english()
232 } else {
233 braille
234 });
235 }
236 Ok(written.join("\n"))
237}
238
239pub fn measure_to_braille(measure: &Stream, options: &BrailleOptions) -> Result<String> {
246 let mut part = Stream::with_kind(StreamKind::Part);
247 part.push(measure.clone());
248 if !options.in_place {
249 crate::makenotation::keeping_spanners(
255 &mut part,
256 crate::makenotation::Kept::Retained,
257 &mut crate::makenotation::make_measure_notation,
258 )?;
259 }
260 part_to_braille(
261 &part,
262 &BrailleOptions {
263 in_place: true,
264 ..*options
265 },
266 )
267}
268
269pub fn keyboard_parts_to_braille(
276 upper: &Stream,
277 lower: &Stream,
278 options: &BrailleOptions,
279) -> Result<String> {
280 let upper = notated(upper, options)?;
281 let lower = notated(lower, options)?;
282 let right = find_segments(&upper, Some(Hand::Right), options.segment);
283 let left = find_segments(&lower, Some(Hand::Left), options.segment);
284 let mut written = Vec::new();
285 for (right, left) in right.into_iter().zip(left) {
286 let mut grand = BrailleGrandSegment {
287 groupings: right.groupings.into_iter().chain(left.groupings).collect(),
288 line_length: options.segment.max_line_length,
289 right_contexts: right.contexts,
290 left_contexts: left.contexts,
291 };
292 let braille = grand.transcribe()?;
293 written.push(if options.debug {
294 grand.english()
295 } else {
296 braille
297 });
298 }
299 Ok(written.join("\n"))
300}
301
302pub fn element_to_braille(element: StreamElement, options: &BrailleOptions) -> Result<String> {
309 if element.as_stream().is_some() {
310 return Err(Error::Notation(
311 "Stream cannot be translated to Braille.".to_string(),
312 ));
313 }
314 let mut measure = Stream::with_kind(StreamKind::Measure);
315 measure.push(element);
316 let mut part = Stream::with_kind(StreamKind::Part);
317 part.push(measure);
318 let mut segment = options.segment;
319 segment.show_first_measure_number = false;
320 segment.show_heading = false;
321 part_to_braille(
322 &part,
323 &BrailleOptions {
324 in_place: true,
325 segment,
326 ..*options
327 },
328 )
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334 use crate::braille::SegmentDivision;
335 use crate::defaults::IntegerType;
336 use crate::{Duration, KeySignature, Note, StreamKind};
337
338 fn staff(name: &str) -> Stream {
340 let mut staff = Stream::with_kind(StreamKind::PartStaff);
341 for number in 1..=2 {
342 let mut measure = Stream::with_kind(StreamKind::Measure);
343 measure.set_number(number);
344 if number == 1 {
345 measure.push(KeySignature::new(2));
346 }
347 let note = Note::from_name(name)
348 .unwrap()
349 .with_duration(Duration::new(4.0).unwrap());
350 measure.push(note);
351 staff.insert(4.0 * (number - 1) as f64, measure);
352 }
353 staff
354 }
355
356 #[test]
359 fn a_lone_key_signature_heads_the_keyboard() {
360 let written =
361 keyboard_parts_to_braille(&staff("D5"), &staff("D3"), &BrailleOptions::default())
362 .unwrap();
363 assert_eq!(written, "⠀⠀⠩⠩⠀⠀\n⠁⠀⠨⠜⠨⠵\n⠀⠀⠸⠜⠸⠵");
364 }
365
366 fn divided(measure: IntegerType, offset: f64, division: SegmentDivision) -> String {
369 let mut part =
370 crate::tinynotation::from_tiny_notation("3/4 c4 c c e e e g g g c'2.").unwrap();
371 crate::makenotation::make_notation(&mut part).unwrap();
372 for event in part.events_mut() {
373 let StreamElement::Stream(held) = event.element_mut() else {
374 continue;
375 };
376 if held.number() != measure {
377 continue;
378 }
379 held.insert(offset, division);
380 }
381 stream_to_braille(&part, &BrailleOptions::default()).unwrap()
382 }
383
384 #[test]
388 fn a_segment_division_divides_the_segment() {
389 let whole = "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠉⠲⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠼⠁⠀⠐⠹⠹⠹⠀⠫⠫⠫⠀⠳⠳⠳⠀⠨⠝⠄⠣⠅";
390 assert_eq!(
391 divided(2, 1.0, SegmentDivision::Required),
392 "⠀⠀⠀⠼⠉⠲⠀⠀⠀⠀\n⠼⠁⠀⠐⠹⠹⠹⠀⠫⠐\n⠼⠃⠄⠀⠐⠫⠫⠀⠳⠳⠳⠀⠨⠝⠄⠣⠅"
393 );
394 assert_eq!(divided(1, 1.0, SegmentDivision::Optional), whole);
395 assert_eq!(divided(1, 0.0, SegmentDivision::Required), whole);
396 }
397
398 fn one_measure(name: &str, signed: bool) -> Stream {
401 let mut staff = Stream::with_kind(StreamKind::PartStaff);
402 let mut measure = Stream::with_kind(StreamKind::Measure);
403 measure.set_number(1);
404 if signed {
405 measure.push(KeySignature::new(2));
406 measure.push(crate::TimeSignature::new(4, 4).unwrap());
407 }
408 measure.push(
409 Note::from_name(name)
410 .unwrap()
411 .with_duration(Duration::new(4.0).unwrap()),
412 );
413 staff.insert(0.0, measure);
414 staff
415 }
416
417 #[test]
419 fn either_hands_signatures_head_the_keyboard() {
420 for left_signed in [false, true] {
421 let written = keyboard_parts_to_braille(
422 &one_measure("C5", !left_signed),
423 &one_measure("C3", left_signed),
424 &BrailleOptions::default(),
425 )
426 .unwrap();
427 let heading = written.lines().next().unwrap().trim_matches('\u{2800}');
428 assert_eq!(heading, "⠩⠩⠼⠙⠲");
429 }
430 }
431
432 fn staccato_counts(counts: &[usize]) -> Vec<usize> {
435 use crate::articulations::{Articulation, ArticulationKind};
436 let mut part = Stream::with_kind(StreamKind::Part);
437 let mut measure = Stream::with_kind(StreamKind::Measure);
438 measure.set_number(1);
439 for &count in counts {
440 let mut note = Note::from_name("C4")
441 .unwrap()
442 .with_duration(Duration::new(0.5).unwrap());
443 for _ in 0..count {
444 note.articulations_mut()
445 .push(Articulation::of_kind(ArticulationKind::Staccato));
446 }
447 measure.push(note);
448 }
449 part.insert(0.0, measure);
450 let segments = find_segments(&part, None, SegmentOptions::default());
451 segments
452 .iter()
453 .flat_map(|segment| segment.groupings.values())
454 .flat_map(|grouping| &grouping.elements)
455 .filter_map(|element| match &element.element {
456 StreamElement::Note(note) => Some(note.articulations().len()),
457 _ => None,
458 })
459 .collect()
460 }
461
462 #[test]
465 fn four_staccatos_in_a_row_are_doubled_on_the_first() {
466 assert_eq!(staccato_counts(&[1, 1, 1, 1]), [2, 0, 0, 1]);
467 assert_eq!(staccato_counts(&[1, 2, 1, 1]), [2, 0, 0, 1]);
468 assert_eq!(staccato_counts(&[1, 1, 1]), [1, 1, 1]);
469 }
470
471 #[test]
474 fn a_clefs_chord_direction_carries_into_the_next_segment() {
475 for (clef, expected) in [
476 (Some(crate::Clef::treble()), true),
477 (Some(crate::Clef::bass()), false),
478 (None, true),
479 ] {
480 let mut part = Stream::with_kind(StreamKind::Part);
481 for number in 1..=3 {
482 let mut measure = Stream::with_kind(StreamKind::Measure);
483 measure.set_number(number);
484 if number == 1
485 && let Some(clef) = &clef
486 {
487 measure.push(clef.clone());
488 }
489 if number == 3 {
490 measure.push(SegmentDivision::Required);
491 }
492 measure.push(
493 crate::Chord::new("C3 E3 G3")
494 .unwrap()
495 .with_duration(Duration::new(4.0).unwrap()),
496 );
497 part.insert(4.0 * f64::from(number - 1), measure);
498 }
499 let segments = find_segments(&part, None, SegmentOptions::default());
500 assert_eq!(segments.len(), 2);
501 for segment in &segments {
502 for (key, grouping) in &segment.groupings {
503 if key.affinity == crate::braille::segment::Affinity::NoteGrouping {
504 assert_eq!(grouping.descending_chords, Some(expected));
505 }
506 }
507 }
508 }
509 }
510}