Skip to main content

music21/
musedata.rs

1//! MuseData, the Center for Computer Assisted Research in the Humanities'
2//! encoding: music21's `musedata` and `musedata.translate`.
3//!
4//! A MuseData file holds one part or several, each ended by a `/END` line,
5//! and a work is usually a file per part. [`from_musedata`] reads the files
6//! of a work into a score of a part each. Both of the encoding's stages are
7//! read: stage 2, with its `$` attribute records and its columns for beams,
8//! accidentals, notations and lyrics, and the older stage 1.
9
10pub mod base12_26;
11pub mod base40;
12
13use std::collections::HashMap;
14
15use crate::articulations::{Articulation, ArticulationKind};
16use crate::bar::{Barline, BarlineType, RepeatDirection};
17use crate::chord::Chord;
18use crate::clef::{Clef, ClefKind};
19use crate::defaults::{FloatType, IntegerType};
20use crate::duration::Duration;
21use crate::dynamics::Dynamic;
22use crate::error::{Error, Position, Result};
23use crate::expressions::{Expression, Fermata, Ornament, OrnamentKind};
24use crate::interval::Interval;
25use crate::key::KeySignature;
26use crate::makenotation::{make_accidentals, make_beams, op_frac};
27use crate::metadata::Metadata;
28use crate::meter::TimeSignature;
29use crate::notation::{BeamDirection, BeamType, Beams, Tie, TieType};
30use crate::note::Note;
31use crate::pitch::Pitch;
32use crate::pitch::accidental::Accidental;
33use crate::rest::Rest;
34use crate::spanner::Spanner;
35use crate::stream::{Stream, StreamElement, StreamEvent, StreamKind};
36use crate::tempo::TempoText;
37
38fn error(message: impl Into<String>) -> Error {
39    Error::muse_data(message.into())
40}
41
42/// Reads the files of a MuseData work, in order, into a score, as music21's
43/// `converter.parse` reads a work's directory or a single file.
44///
45/// Each part is a part of the score, named as its header names it, in
46/// measures as its `measure` records divide it, each measure opening with
47/// the barline its record draws and the first with the clef, key, meter and
48/// any tempo word the part's attribute record gives. Notes, chords and
49/// rests take their lengths from the divisions of a quarter note; a stage-2
50/// file also gives each note its beams, the accidental it shows, its
51/// articulations, fermatas, ornaments and dynamics, and its lyrics, and a
52/// `back` record starts another voice. A part written for a transposing
53/// instrument (`X:`) is turned to the pitch it sounds, and its accidentals
54/// are worked out again; a stage-1 part is given its best clef, its beams
55/// and its accidentals. Stage-2 slur marks become slurs. The work's title,
56/// number and movement are kept.
57///
58/// music21's own habits are kept: every measure starts with a barline, the
59/// first measure is numbered one (a pickup before it zero), a measure's number is every digit of its
60/// record (so `mheavy2 12` is measure 212), and a pitch of double sharps
61/// reads as a single sharp, of double flats as a single flat. Cue and grace
62/// notes are passed over, as is an attribute record after the first.
63///
64/// ```
65/// use music21::musedata::from_musedata;
66///
67/// let part = "\n\n\n01/01/01 x\nWK#:1 MV#:1\nsource\nWork\nMovement\nFlute\n\
68/// 1 0\nGroup memberships: score\nscore: part 1 of 1\n\
69/// $  K:0   Q:2   T:2/4   C:4\nC5     2        q     u\nD5     2        q     u\n\
70/// measure 2\nE5     4        h     u\n/END\n";
71/// let score = from_musedata(&[part])?;
72/// assert_eq!(score.parts()[0].measures().len(), 2);
73/// # Ok::<(), music21::Error>(())
74/// ```
75///
76/// # Errors
77///
78/// A file with no part in it, an attribute record music21 cannot read, a
79/// clef or barline it does not know, a record whose length is not a number,
80/// or a transposition it has no interval for.
81pub fn from_musedata(files: &[&str]) -> Result<Stream> {
82    let mut parts = Vec::new();
83    for text in files {
84        parts.extend(split_parts(text)?);
85    }
86    score_of(&parts, Header::Read)
87}
88
89/// Whether [`from_musedata_parts`] reads the work's title, number and
90/// movement into the score's metadata.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum Header {
93    /// Read, as music21's `museDataWorkToStreamScore` reads it.
94    Read,
95    /// Left out, as music21's `musedataPartToStreamPart` leaves it.
96    Skipped,
97}
98
99/// Reads parts already split from their files, each the lines of one part
100/// as music21's `MuseDataPart.src` holds them, into a score: music21's
101/// `museDataWorkToStreamScore`, or with [`Header::Skipped`] its
102/// `musedataPartToStreamPart` for each.
103///
104/// # Errors
105///
106/// As [`from_musedata`], and a part of one line or none.
107pub fn from_musedata_parts(parts: &[Vec<String>], header: Header) -> Result<Stream> {
108    let mut read = Vec::new();
109    for lines in parts {
110        let numbers = (1..=lines.len()).collect();
111        read.push(Part::new(lines.clone(), numbers)?);
112    }
113    score_of(&read, header)
114}
115
116/// The score of a work's parts, each holding its slurs.
117fn score_of(parts: &[Part], header: Header) -> Result<Stream> {
118    let first = parts
119        .first()
120        .ok_or_else(|| error("a MuseData work with no parts"))?;
121    let mut score = Stream::with_kind(StreamKind::Score);
122    if header == Header::Read {
123        score.set_metadata(Some(work_metadata(first)));
124    }
125    for part in parts {
126        let (mut made, joined) = part.to_part()?;
127        // Each slur goes in its part, naming its notes by their places
128        // among the part's notes and chords in the order they were read.
129        let read: Vec<usize> = made
130            .leaves()
131            .into_iter()
132            .enumerate()
133            .filter(|(_, (_, element))| {
134                matches!(element, StreamElement::Note(_) | StreamElement::Chord(_))
135            })
136            .map(|(position, _)| position)
137            .collect();
138        for (start, stop) in joined {
139            if let (Some(first), Some(last)) = (read.get(start), read.get(stop)) {
140                made.add_spanner(Spanner::slur(vec![*first, *last]));
141            }
142        }
143        score.insert(0.0, made);
144    }
145    Ok(score)
146}
147
148/// The work's title, number and movement, as the first part names them.
149fn work_metadata(first: &Part) -> Metadata {
150    let mut metadata = Metadata::new();
151    if let Some(title) = first.work_title() {
152        metadata.add_text("title", title);
153    }
154    if let Some(number) = first.movement_number() {
155        metadata.add_text("movementNumber", number);
156    }
157    if let Some(name) = first.movement_title() {
158        metadata.add_text("movementName", name);
159    }
160    if let Some(number) = first.work_number() {
161        metadata.add_text("number", number);
162    }
163    metadata
164}
165
166/// The slurs of one part, as music21's `_SlurCollector` builds them: the
167/// marks ( ) [ ] { } and z x start and stop slurs 1 to 4, a stop closing the
168/// open slur of its number. Notes and chords are counted in the order they
169/// are read.
170#[derive(Clone, Debug, Default)]
171pub struct Slurs {
172    open: [Option<usize>; 4],
173    joined: Vec<(usize, usize)>,
174    read: usize,
175}
176
177impl Slurs {
178    const STARTS: [char; 4] = ['(', '[', '{', 'z'];
179    const STOPS: [char; 4] = [')', ']', '}', 'x'];
180
181    /// Stops, then starts, the slurs the marks name on the next note or
182    /// chord, so one note can end a slur and begin the next of its number.
183    /// Hands back the slurs it stops, each as the places of its first and
184    /// last notes among those added.
185    pub fn add(&mut self, marks: &str) -> Vec<(usize, usize)> {
186        let at = self.read;
187        self.read += 1;
188        let mut stopped = Vec::new();
189        for mark in marks.chars() {
190            if let Some(number) = Self::STOPS.iter().position(|stop| *stop == mark)
191                && let Some(start) = self.open[number].take()
192            {
193                stopped.push((start, at));
194            }
195        }
196        self.joined.extend(stopped.iter().copied());
197        for mark in marks.chars() {
198            if let Some(number) = Self::STARTS.iter().position(|start| *start == mark) {
199                self.open[number] = Some(at);
200            }
201        }
202        stopped
203    }
204
205    /// The open slurs, by number from nought, each as the place of its first
206    /// note.
207    pub fn open(&self) -> &[Option<usize>; 4] {
208        &self.open
209    }
210}
211
212/// music21's `MuseDataFile.readstr`: the parts of one file, comments and
213/// `@` lines left out, read the same with Windows line endings.
214///
215/// # Errors
216///
217/// A stage-1 part of one line.
218pub fn split_parts(text: &str) -> Result<Vec<Part>> {
219    let mut parts = Vec::new();
220    let mut lines: Vec<String> = Vec::new();
221    // The line of the file each of them is, counted from one.
222    let mut numbers: Vec<usize> = Vec::new();
223    let mut comment = false;
224    for (index, line) in text.replace("\r\n", "\n").split('\n').enumerate() {
225        if line.starts_with('&') {
226            comment = !comment;
227            continue;
228        }
229        if comment || line.starts_with('@') {
230            continue;
231        }
232        if line.starts_with("/END") || line.starts_with("END") {
233            if lines.len() <= 1 {
234                lines.clear();
235                numbers.clear();
236                continue;
237            }
238            let at = numbers.first().copied().unwrap_or(index + 1);
239            let part = Part::new(std::mem::take(&mut lines), std::mem::take(&mut numbers))
240                .map_err(|error| error.placed(|| Position::line(at)))?;
241            parts.push(part);
242        } else if !line.starts_with("/eof") {
243            lines.push(line.to_string());
244            numbers.push(index + 1);
245        }
246    }
247    Ok(parts)
248}
249
250/// Every digit of a string, in order: music21's `getNumFromStr`.
251fn digits(text: &str) -> String {
252    text.chars().filter(char::is_ascii_digit).collect()
253}
254
255/// Whether [`Part::letters_after`] keeps the spaces it passes.
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
257pub enum Spaces {
258    /// Passed over.
259    Dropped,
260    /// Kept.
261    Kept,
262}
263
264/// Whether [`Part::letters_after`] reads the line as written.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum Case {
267    /// As written.
268    Kept,
269    /// Lowered, tag and line alike.
270    Lowered,
271}
272
273/// The stage of the encoding a part is written in: stage 2 has `$`
274/// attribute records and columns stage 1 lacks.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub enum Stage {
277    /// The older encoding, without attribute records.
278    One,
279    /// The encoding with `$` attribute records.
280    Two,
281}
282
283/// A part's lines and the stage they are written in: music21's
284/// `MuseDataPart`.
285#[derive(Clone, Debug)]
286pub struct Part {
287    lines: Vec<String>,
288    /// The line of its file each line is, counted from one.
289    numbers: Vec<usize>,
290    stage: Stage,
291}
292
293impl Part {
294    /// A part of `lines` already read, in `stage`: music21's
295    /// `MuseDataPart(src, stage)` for a source it keeps as it is.
296    pub fn with_stage(lines: Vec<String>, stage: Stage) -> Self {
297        let numbers = (1..=lines.len()).collect();
298        Self {
299            lines,
300            numbers,
301            stage,
302        }
303    }
304
305    /// music21's `_determineStage`: stage 2 where any line is an attribute
306    /// record.
307    pub fn stage_of(lines: &[String]) -> Stage {
308        if lines.iter().any(|line| line.starts_with('$')) {
309            Stage::Two
310        } else {
311            Stage::One
312        }
313    }
314
315    /// music21's `_scrubStage1`: the lines without the blank ones they open
316    /// with.
317    ///
318    /// # Errors
319    ///
320    /// Lines of one or none.
321    pub fn scrubbed(lines: &[String]) -> Result<Vec<String>> {
322        if lines.len() <= 1 {
323            return Err(error("cannot scrub empty source"));
324        }
325        Ok(lines
326            .iter()
327            .skip_while(|line| line.trim().is_empty())
328            .cloned()
329            .collect())
330    }
331
332    /// The part's lines, a stage-1 part's leading blank lines dropped.
333    pub fn lines(&self) -> &[String] {
334        &self.lines
335    }
336
337    /// The stage the part is written in.
338    pub fn stage(&self) -> Stage {
339        self.stage
340    }
341
342    /// music21's `MuseDataPart`: stage 2 where any line is an attribute
343    /// record, stage 1 otherwise, whose leading blank lines are dropped.
344    fn new(lines: Vec<String>, numbers: Vec<usize>) -> Result<Self> {
345        if lines.iter().any(|line| line.starts_with('$')) {
346            return Ok(Self {
347                lines,
348                numbers,
349                stage: Stage::Two,
350            });
351        }
352        if lines.len() <= 1 {
353            return Err(error("cannot scrub empty source"));
354        }
355        let (lines, numbers) = lines
356            .into_iter()
357            .zip(numbers)
358            .skip_while(|(line, _)| line.trim().is_empty())
359            .unzip();
360        Ok(Self {
361            lines,
362            numbers,
363            stage: Stage::One,
364        })
365    }
366
367    /// Where the line at `index` stands in the file, in this part.
368    fn place(&self, index: usize) -> Position {
369        let position = Position {
370            line: self.numbers.get(index).copied(),
371            ..Position::default()
372        };
373        match self.part_name() {
374            Some(name) => position.in_part(name),
375            None => position,
376        }
377    }
378
379    /// Where the attribute record stands: what goes wrong reading a
380    /// part's key, meter, clef or divisions is placed there.
381    fn attributes_place(&self) -> Position {
382        let index = match self.stage {
383            Stage::One => Some(6),
384            Stage::Two => self
385                .lines
386                .iter()
387                .skip(11)
388                .position(|line| line.starts_with('$'))
389                .map(|index| index + 11),
390        };
391        match index {
392            Some(index) => self.place(index),
393            None => self.place(usize::MAX),
394        }
395    }
396
397    fn line(&self, index: usize) -> Result<&str> {
398        self.lines
399            .get(index)
400            .map(String::as_str)
401            .ok_or_else(|| error("a header shorter than MuseData's"))
402    }
403
404    /// music21's `_getDigitsFollowingTag`: the digits after a tag, spaces
405    /// passed over, `-` and `/` kept, anything else ending it.
406    ///
407    /// ```
408    /// use music21::musedata::Part;
409    ///
410    /// assert_eq!(Part::digits_after("$ K:-3   Q:4   T:3/4   C:22", "T:"), "3/4");
411    /// ```
412    pub fn digits_after(line: &str, tag: &str) -> String {
413        let Some(at) = line.find(tag) else {
414            return String::new();
415        };
416        let mut out = String::new();
417        for c in line[at + tag.len()..].chars() {
418            if c.is_ascii_digit() || c == '-' || c == '/' {
419                out.push(c);
420            } else if !c.is_whitespace() {
421                break;
422            }
423        }
424        out
425    }
426
427    /// `_getAlphasFollowingTag` with `keepSpace` and `keepCase`: the letters,
428    /// spaces and commas after a tag.
429    fn words_after(line: &str, tag: &str) -> String {
430        Self::letters_after(line, tag, Spaces::Kept, Case::Kept)
431    }
432
433    /// music21's `_getAlphasFollowingTag`: the letters and commas after a
434    /// tag, spaces passed over or kept, anything else ending it; with
435    /// [`Case::Lowered`] line and tag are lowered first.
436    ///
437    /// ```
438    /// use music21::musedata::{Case, Part, Spaces};
439    ///
440    /// let line = "Group memberships: sound, score";
441    /// let read = Part::letters_after(line, "Group memberships:", Spaces::Dropped, Case::Lowered);
442    /// assert_eq!(read, "sound,score");
443    /// ```
444    pub fn letters_after(line: &str, tag: &str, spaces: Spaces, case: Case) -> String {
445        let (line, tag) = match case {
446            Case::Kept => (line.to_string(), tag.to_string()),
447            Case::Lowered => (line.to_lowercase(), tag.to_lowercase()),
448        };
449        let Some(at) = line.find(&tag) else {
450            return String::new();
451        };
452        let mut out = String::new();
453        for c in line[at + tag.len()..].chars() {
454            if c.is_alphabetic() || c == ',' {
455                out.push(c);
456            } else if c.is_whitespace() {
457                if spaces == Spaces::Kept {
458                    out.push(c);
459                }
460            } else {
461                break;
462            }
463        }
464        out
465    }
466
467    /// music21's `getSource`: where the encoding was taken from.
468    pub fn source(&self) -> Option<String> {
469        if self.stage == Stage::Two {
470            return self.lines.get(5).cloned();
471        }
472        let mut joined = String::new();
473        for index in 2..=4 {
474            joined.push_str(self.lines.get(index)?.trim());
475        }
476        Some(joined)
477    }
478
479    /// music21's `getGroupMemberships`: the groups the part belongs to.
480    pub fn group_memberships(&self) -> Vec<String> {
481        if self.stage == Stage::One {
482            return Vec::new();
483        }
484        let Some(line) = self.lines.get(10) else {
485            return Vec::new();
486        };
487        Self::letters_after(line, "group memberships:", Spaces::Dropped, Case::Lowered)
488            .split(',')
489            .map(str::trim)
490            .filter(|entry| !entry.is_empty())
491            .map(str::to_string)
492            .collect()
493    }
494
495    /// The `membership:` line among those before the attribute record, and
496    /// the digits after `tag` in it.
497    fn membership_digits(&self, membership: &str, tag: &str) -> Option<String> {
498        self.lines
499            .iter()
500            .skip(11)
501            .take_while(|line| !line.starts_with('$'))
502            .find(|line| line.starts_with(membership))
503            .map(|line| Self::digits_after(line, tag))
504    }
505
506    /// music21's `getGroupMembershipsTotal`: how many parts the group has.
507    ///
508    /// # Errors
509    ///
510    /// A count that is no number.
511    pub fn group_total(&self, membership: &str) -> Result<Option<IntegerType>> {
512        if self.stage == Stage::One {
513            let line = self.line(5)?;
514            return Self::integer(line.split(' ').next().unwrap_or("")).map(Some);
515        }
516        self.membership_digits(membership, "of")
517            .map(|raw| Self::integer(&raw))
518            .transpose()
519    }
520
521    /// music21's `getGroupMembershipNumber`: the part's place in the group,
522    /// as written. music21 hands stage 1's back as text, stage 2's as a
523    /// number.
524    ///
525    /// # Errors
526    ///
527    /// A stage-1 header too short.
528    pub fn group_number(&self, membership: &str) -> Result<Option<String>> {
529        if self.stage == Stage::One {
530            let line = self.line(5)?;
531            return Ok(line.split(' ').nth(1).map(str::to_string));
532        }
533        Ok(self.membership_digits(membership, "part"))
534    }
535
536    /// music21's `getWorkNumber`: the opus number, as written.
537    pub fn work_number(&self) -> Option<String> {
538        if self.stage == Stage::One {
539            let data: String = self.lines.get(1)?.chars().take(6).collect();
540            let data = data.trim();
541            Some(if data.contains(',') {
542                data.split(',').nth(1).unwrap_or("").to_string()
543            } else {
544                data.to_string()
545            })
546        } else {
547            Some(Self::digits_after(self.lines.get(4)?, "WK#:"))
548        }
549    }
550
551    /// music21's `getMovementNumber`, as written.
552    pub fn movement_number(&self) -> Option<String> {
553        if self.stage == Stage::One {
554            Some(
555                self.lines
556                    .get(1)?
557                    .chars()
558                    .skip(6)
559                    .collect::<String>()
560                    .trim()
561                    .to_string(),
562            )
563        } else {
564            Some(Self::digits_after(self.lines.get(4)?, "MV#:"))
565        }
566    }
567
568    /// music21's `getWorkTitle`: for stage 1, the catalogue number.
569    pub fn work_title(&self) -> Option<String> {
570        if self.stage == Stage::One {
571            Some(self.lines.first()?.trim().to_string())
572        } else {
573            self.lines.get(6).cloned()
574        }
575    }
576
577    /// music21's `getMovementTitle`; none for stage 1.
578    pub fn movement_title(&self) -> Option<String> {
579        if self.stage == Stage::One {
580            None
581        } else {
582            self.lines.get(7).cloned()
583        }
584    }
585
586    /// music21's `getPartName`; none for stage 1.
587    pub fn part_name(&self) -> Option<String> {
588        if self.stage == Stage::One {
589            None
590        } else {
591            self.lines.get(8).map(|name| name.trim().to_string())
592        }
593    }
594
595    /// music21's `_getAttributesRecord`: the first line opening with `$`,
596    /// or stage 1's two attribute lines joined.
597    ///
598    /// # Errors
599    ///
600    /// A part with no attribute record.
601    pub fn attributes(&self) -> Result<String> {
602        if self.stage == Stage::One {
603            return Ok(format!("{} {}", self.line(6)?.trim(), self.line(7)?.trim()));
604        }
605        self.lines
606            .iter()
607            .skip(11)
608            .find(|line| line.starts_with('$'))
609            .cloned()
610            .ok_or_else(|| error("a part with no attribute record"))
611    }
612
613    /// The stage-1 attribute record's fields, split as music21 splits it.
614    fn stage_one_field(&self, index: usize) -> Result<String> {
615        self.attributes()?
616            .split(' ')
617            .nth(index)
618            .map(str::to_string)
619            .ok_or_else(|| error("a stage-1 attribute record too short"))
620    }
621
622    fn integer(text: &str) -> Result<IntegerType> {
623        text.trim()
624            .parse()
625            .map_err(|_| error(format!("{text:?} is not a number")))
626    }
627
628    /// music21's `getKeyParameters`: the signature's sharps, flats below
629    /// nought.
630    ///
631    /// # Errors
632    ///
633    /// A key that is no number.
634    pub fn key_parameters(&self) -> Result<IntegerType> {
635        if self.stage == Stage::One {
636            return Self::integer(&self.stage_one_field(1)?);
637        }
638        Self::integer(&Self::digits_after(&self.attributes()?, "K:"))
639    }
640
641    /// music21's `getKeySignature`.
642    ///
643    /// # Errors
644    ///
645    /// As [`Part::key_parameters`].
646    pub fn key_signature(&self) -> Result<KeySignature> {
647        Ok(KeySignature::new(self.key_parameters()?))
648    }
649
650    /// music21's `getTimeSignatureObject`.
651    ///
652    /// # Errors
653    ///
654    /// As [`Part::time_signature_parameters`].
655    pub fn time_signature(&self) -> Result<TimeSignature> {
656        TimeSignature::from_ratio_string(&self.time_signature_parameters()?)
657    }
658
659    /// music21's `getTimeSignatureParameters`: the meter as `3/4`, a meter
660    /// of `1/1` or over nought as `4/4`.
661    ///
662    /// # Errors
663    ///
664    /// A meter that is not two numbers.
665    pub fn time_signature_parameters(&self) -> Result<String> {
666        let (numerator, denominator) = if self.stage == Stage::One {
667            (
668                Self::integer(&self.stage_one_field(4)?)?,
669                Self::integer(&self.stage_one_field(5)?)?,
670            )
671        } else {
672            let written = Self::digits_after(&self.attributes()?, "T:");
673            let (numerator, denominator) = written
674                .split_once('/')
675                .filter(|(_, denominator)| !denominator.contains('/'))
676                .ok_or_else(|| error(format!("no meter in {written:?}")))?;
677            (Self::integer(numerator)?, Self::integer(denominator)?)
678        };
679        if (numerator == 1 && denominator == 1) || denominator == 0 {
680            return Ok("4/4".to_string());
681        }
682        Ok(format!("{numerator}/{denominator}"))
683    }
684
685    /// music21's `_getNumberOfStaves`: `S:`, one where unwritten.
686    ///
687    /// # Errors
688    ///
689    /// A count that is no number.
690    pub fn staff_count(&self) -> Result<IntegerType> {
691        if self.stage == Stage::One {
692            return Ok(1);
693        }
694        match Self::digits_after(&self.attributes()?, "S:").as_str() {
695            "" => Ok(1),
696            raw => Self::integer(raw),
697        }
698    }
699
700    /// music21's `_getClefParameters`: `C:`, or each staff's `Cn:`, as
701    /// written; stage 1's ninth attribute field.
702    ///
703    /// # Errors
704    ///
705    /// A part with no attribute record.
706    pub fn clef_parameters(&self) -> Result<Vec<String>> {
707        if self.stage == Stage::One {
708            return Ok(vec![self.stage_one_field(8)?]);
709        }
710        let line = self.attributes()?;
711        let written = Self::digits_after(&line, "C:");
712        if !written.is_empty() {
713            return Ok(vec![written]);
714        }
715        let mut found = Vec::new();
716        for staff in 1..=self.staff_count()? {
717            let raw = Self::digits_after(&line, &format!("C{staff}:"));
718            if !raw.is_empty() {
719                found.push(raw);
720            }
721        }
722        Ok(found)
723    }
724
725    fn clef(&self) -> Result<Option<Clef>> {
726        self.clef_for(1)
727    }
728
729    /// music21's `getClefObject`: the clef of staff `voice`, counted from
730    /// one; none for stage 1.
731    ///
732    /// # Errors
733    ///
734    /// No clef for the staff, or a code music21 does not know.
735    pub fn clef_for(&self, voice: usize) -> Result<Option<Clef>> {
736        if self.stage == Stage::One {
737            return Ok(None);
738        }
739        let written = self
740            .clef_parameters()?
741            .get(voice.saturating_sub(1))
742            .cloned()
743            .ok_or_else(|| error("a part with no clef"))?;
744        let kind = match Self::integer(&written)?.to_string().as_str() {
745            "5" => ClefKind::FrenchViolinClef,
746            "4" => ClefKind::TrebleClef,
747            "34" => ClefKind::Treble8vbClef,
748            "64" => ClefKind::Treble8vaClef,
749            "3" => ClefKind::GSopranoClef,
750            "11" => ClefKind::CBaritoneClef,
751            "12" => ClefKind::TenorClef,
752            "13" => ClefKind::AltoClef,
753            "14" => ClefKind::MezzoSopranoClef,
754            "15" => ClefKind::SopranoClef,
755            "22" => ClefKind::BassClef,
756            "23" => ClefKind::FBaritoneClef,
757            "52" => ClefKind::Bass8vbClef,
758            "82" => ClefKind::Bass8vaClef,
759            other => return Err(error(format!("cannot determine clef from: {other}"))),
760        };
761        Ok(Some(Clef::of_kind(kind)))
762    }
763
764    /// music21's `getDirective`: `D:`, usually a tempo word.
765    ///
766    /// # Errors
767    ///
768    /// A part with no attribute record.
769    pub fn directive(&self) -> Result<Option<String>> {
770        if self.stage == Stage::One {
771            return Ok(None);
772        }
773        let words = Self::words_after(&self.attributes()?, "D:");
774        Ok((!words.is_empty()).then(|| words.trim().to_string()))
775    }
776
777    /// music21's `getTranspositionIntervalObject`: the interval a
778    /// transposing part is written at.
779    ///
780    /// # Errors
781    ///
782    /// A transposition with no interval.
783    pub fn transposition(&self) -> Result<Option<Interval>> {
784        self.transposition_parameters()?
785            .map(base40_interval)
786            .transpose()
787    }
788
789    /// music21's `_getTranspositionParameters`: `X:`, in base 40.
790    ///
791    /// # Errors
792    ///
793    /// A transposition that is no number.
794    pub fn transposition_parameters(&self) -> Result<Option<IntegerType>> {
795        if self.stage == Stage::One {
796            return Ok(None);
797        }
798        match Self::digits_after(&self.attributes()?, "X:").as_str() {
799            "" => Ok(None),
800            raw => Self::integer(raw).map(Some),
801        }
802    }
803
804    /// Divisions of a quarter note: `Q:`, or in stage 1 the divisions of a
805    /// bar over the bar's length in quarters.
806    pub fn divisions(&self) -> Result<FloatType> {
807        if self.stage == Stage::One {
808            let bar = Self::integer(&self.stage_one_field(2)?)?;
809            Ok(FloatType::from(bar) / self.time_signature()?.bar_duration().quarter_length())
810        } else {
811            Ok(FloatType::from(Self::integer(&Self::digits_after(
812                &self.attributes()?,
813                "Q:",
814            ))?))
815        }
816    }
817
818    /// `_getMeasureBoundaryIndices`: the lines of each measure, from its
819    /// first up to the one after its last.
820    pub fn measure_bounds(&self) -> Result<Vec<(usize, usize)>> {
821        let lines = &self.lines;
822        let end = lines.len();
823        let mut marks = Vec::new();
824        let mut first_after: Option<usize> = None;
825        let mut attributes = 0;
826        for (index, line) in lines.iter().enumerate() {
827            if self.stage == Stage::Two {
828                if line.starts_with('$') {
829                    attributes += 1;
830                    continue;
831                }
832                if attributes > 0 && first_after.is_none() {
833                    first_after = Some(index);
834                }
835            }
836            if line.starts_with('m') {
837                marks.push(index);
838            }
839        }
840        let first_mark = *marks
841            .first()
842            .ok_or_else(|| error("a part with no measure records"))?;
843        if self.stage == Stage::One {
844            first_after = Some(first_mark);
845        }
846        let mut bounds = Vec::new();
847        let start = if Some(first_mark) == first_after {
848            if marks.len() == 1 {
849                bounds.push((first_mark, end));
850                None
851            } else {
852                bounds.push((first_mark, marks[1]));
853                Some(1)
854            }
855        } else {
856            let first_after =
857                first_after.ok_or_else(|| error("a part with nothing after its attributes"))?;
858            bounds.push((first_after, first_mark));
859            Some(0)
860        };
861        if let Some(start) = start {
862            for index in start..marks.len() {
863                bounds.push((marks[index], marks.get(index + 1).copied().unwrap_or(end)));
864            }
865        }
866        Ok(bounds)
867    }
868
869    /// music21's `musedataPartToStreamPart`.
870    fn to_part(&self) -> Result<(Stream, Vec<(usize, usize)>)> {
871        let mut part = Stream::with_kind(StreamKind::Part);
872        let name = self.part_name();
873        part.set_id(name.clone());
874        part.set_name(name);
875        let header = |error: Error| error.placed(|| self.attributes_place());
876        let divisions = self.divisions().map_err(header)?;
877        let bounds = self.measure_bounds()?;
878        let measures: Vec<&[String]> = bounds
879            .iter()
880            .map(|(start, end)| self.lines.get(*start..*end).unwrap_or(&[]))
881            .collect();
882        // The last note, chord or rest of each voice, by its number, for the
883        // ties across measures; a measure without voices continues voice 0.
884        let mut last_by_voice: HashMap<usize, Option<Option<TieType>>> = HashMap::new();
885        let mut slurs = Slurs::default();
886        let mut bars = 0;
887        for (index, lines) in measures.iter().enumerate() {
888            if !has_notes(lines) {
889                continue;
890            }
891            // What goes wrong inside a measure says which, by the number
892            // its record gives it, and the line it opens on.
893            let first = bounds[index].0;
894            let here = |error: Error| {
895                error.placed(|| {
896                    let mut position = self.place(first);
897                    position.measure = measure_number(lines).ok();
898                    position
899                })
900            };
901            let mut measure = measure_object(lines).map_err(here)?;
902            if let Some(next) = measures.get(index + 1)
903                && !has_notes(next)
904            {
905                let after = bounds[index + 1].0;
906                let barline = bar_object(next).map_err(|error| error.placed(|| self.place(after)));
907                measure.set_right_barline(Some(barline.map_err(here)?));
908            }
909            if bars == 0 {
910                if let Some(clef) = self.clef().map_err(header)? {
911                    append_at(&mut measure, 0.0, StreamElement::Clef(clef));
912                }
913                append_at(
914                    &mut measure,
915                    0.0,
916                    StreamElement::TimeSignature(self.time_signature().map_err(header)?),
917                );
918                append_at(
919                    &mut measure,
920                    0.0,
921                    StreamElement::KeySignature(self.key_signature().map_err(header)?),
922                );
923                if let Some(directive) = self.directive().map_err(header)? {
924                    let words = TempoText::new(directive);
925                    if words.is_common_tempo_text() {
926                        append_at(
927                            &mut measure,
928                            0.0,
929                            StreamElement::MetronomeMark(words.metronome_mark()),
930                        );
931                    }
932                }
933            }
934            self.fill(
935                &mut measure,
936                lines,
937                first,
938                divisions,
939                &mut last_by_voice,
940                &mut slurs,
941            )
942            .map_err(here)?;
943            if bars == 0 {
944                let bar = self.time_signature()?.bar_duration().quarter_length();
945                let length = measure.end_offset();
946                if length / bar < 1.0 {
947                    measure.set_padding_left(bar - length);
948                }
949            }
950            part.push(measure);
951            bars += 1;
952        }
953        if let Some(interval) = self.transposition().map_err(header)? {
954            let mut failure = None;
955            part.for_each_mut(&mut |_, element| {
956                let moved = match element {
957                    StreamElement::Note(note) => note.transpose(&interval).map(StreamElement::Note),
958                    StreamElement::Chord(chord) => {
959                        chord.transpose(&interval).map(StreamElement::Chord)
960                    }
961                    StreamElement::KeySignature(signature) => signature
962                        .transpose(&interval)
963                        .map(StreamElement::KeySignature),
964                    _ => return,
965                };
966                match moved {
967                    Ok(moved) => *element = moved,
968                    Err(error) => failure = Some(error),
969                }
970            });
971            if let Some(error) = failure {
972                return Err(error);
973            }
974            make_accidentals(&mut part);
975        }
976        if self.stage == Stage::One {
977            // A stage-1 part states no clef for this to replace.
978            let clef = Clef::best_for(&part.pitches(), false);
979            if let Some(StreamElement::Stream(first)) = part
980                .events_mut()
981                .iter_mut()
982                .map(StreamEvent::element_mut)
983                .find(|element| {
984                    matches!(element, StreamElement::Stream(inner) if inner.kind() == StreamKind::Measure)
985                })
986            {
987                append_at(first, 0.0, StreamElement::Clef(clef));
988            }
989            // music21 warns and carries on where a meter cannot beam its bar.
990            let _ = make_beams(&mut part);
991            make_accidentals(&mut part);
992        }
993        Ok((part, slurs.joined))
994    }
995
996    /// The notes, chords and rests of one measure's records, in voices where
997    /// a `back` record says to start another. Each voice ties on from the
998    /// voice of its number in the measure before.
999    fn fill(
1000        &self,
1001        measure: &mut Stream,
1002        lines: &[String],
1003        first: usize,
1004        divisions: FloatType,
1005        last_by_voice: &mut HashMap<usize, Option<Option<TieType>>>,
1006        slurs: &mut Slurs,
1007    ) -> Result<()> {
1008        let voices = lines.iter().any(|line| line.starts_with("back"));
1009        let mut voice = voices.then(|| Stream::with_kind(StreamKind::Voice));
1010        let mut pending: Vec<Record<'_>> = Vec::new();
1011        let mut number = 0;
1012        let mut last = last_by_voice.get(&number).copied().flatten();
1013        let previous = &mut last;
1014        for (index, line) in lines.iter().enumerate() {
1015            let record = Record {
1016                line,
1017                stage: self.stage,
1018                number: self.numbers.get(first + index).copied(),
1019            };
1020            if record.is_back() {
1021                self.flush(
1022                    &mut pending,
1023                    measure,
1024                    voice.as_mut(),
1025                    divisions,
1026                    previous,
1027                    slurs,
1028                )?;
1029                if let Some(done) = voice.replace(Stream::with_kind(StreamKind::Voice)) {
1030                    append_at(measure, 0.0, StreamElement::Stream(Box::new(done)));
1031                }
1032                last_by_voice.insert(number, *previous);
1033                number += 1;
1034                *previous = last_by_voice.get(&number).copied().flatten();
1035            }
1036            if record.is_rest() {
1037                self.flush(
1038                    &mut pending,
1039                    measure,
1040                    voice.as_mut(),
1041                    divisions,
1042                    previous,
1043                    slurs,
1044                )?;
1045                let length = record
1046                    .quarter_length(divisions)
1047                    .and_then(Duration::new)
1048                    .map_err(|error| record.placed(error))?;
1049                let rest = Rest::new(length);
1050                let target = voice.as_mut().unwrap_or(&mut *measure);
1051                append(target, StreamElement::Rest(rest));
1052                *previous = Some(None);
1053            } else if record.is_chord() {
1054                pending.push(record);
1055            } else if record.is_note() {
1056                self.flush(
1057                    &mut pending,
1058                    measure,
1059                    voice.as_mut(),
1060                    divisions,
1061                    previous,
1062                    slurs,
1063                )?;
1064                pending.push(record);
1065            }
1066        }
1067        self.flush(
1068            &mut pending,
1069            measure,
1070            voice.as_mut(),
1071            divisions,
1072            previous,
1073            slurs,
1074        )?;
1075        last_by_voice.insert(number, *previous);
1076        if let Some(voice) = voice
1077            && !voice.is_empty()
1078        {
1079            append_at(measure, 0.0, StreamElement::Stream(Box::new(voice)));
1080        }
1081        Ok(())
1082    }
1083
1084    /// music21's `_processPending`: the records waiting turned into a note
1085    /// or chord, its dynamics put beside it.
1086    fn flush(
1087        &self,
1088        pending: &mut Vec<Record<'_>>,
1089        measure: &mut Stream,
1090        voice: Option<&mut Stream>,
1091        divisions: FloatType,
1092        previous: &mut Option<Option<TieType>>,
1093        slurs: &mut Slurs,
1094    ) -> Result<()> {
1095        if pending.is_empty() {
1096            return Ok(());
1097        }
1098        let records = std::mem::take(pending);
1099        slurs.add(&records[0].slur_marks());
1100        let (element, dynamics, tie) = note_or_chord(&records, divisions, *previous)
1101            .map_err(|error| records[0].placed(error))?;
1102        *previous = Some(tie);
1103        let target = voice.unwrap_or(measure);
1104        let at = target.end_offset();
1105        append_at(target, at, element);
1106        for dynamic in dynamics {
1107            append_at(target, at, StreamElement::Dynamic(dynamic));
1108        }
1109        Ok(())
1110    }
1111}
1112
1113/// music21's `append`: at the end of the stream, sorted among what stands
1114/// there.
1115fn append(stream: &mut Stream, element: StreamElement) {
1116    let at = stream.end_offset();
1117    append_at(stream, at, element);
1118}
1119
1120/// music21's `insert`: sorted among what already stands at the offset.
1121fn append_at(stream: &mut Stream, offset: FloatType, element: StreamElement) {
1122    stream.insert_sorted(vec![StreamEvent::new(offset, element)]);
1123}
1124
1125/// music21's `MuseDataMeasure.hasNotes`: whether a record of the measure
1126/// is a note, rest, cue or grace note.
1127pub fn has_notes(lines: &[String]) -> bool {
1128    lines.iter().any(|line| {
1129        line.chars()
1130            .next()
1131            .is_some_and(|c| "ABCDEFGrgc".contains(c))
1132    })
1133}
1134
1135/// music21's `MuseDataMeasure.hasVoices`: whether a record of the measure
1136/// is a `back`.
1137pub fn has_voices(lines: &[String]) -> bool {
1138    lines.iter().any(|line| line.starts_with("back"))
1139}
1140
1141/// music21's `MuseDataDirectory.isMusedataFile`: whether a path names a
1142/// MuseData file, by its name alone.
1143///
1144/// ```
1145/// use music21::musedata::is_musedata_file;
1146///
1147/// assert!(is_musedata_file("test01/01.md"));
1148/// assert!(!is_musedata_file("test01/mchan1"));
1149/// ```
1150pub fn is_musedata_file(path: &str) -> bool {
1151    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
1152    if path.ends_with(".md") {
1153        return true;
1154    }
1155    if name.starts_with("mchan") {
1156        return false;
1157    }
1158    let skipped = path.ends_with(".py")
1159        || path.ends_with('/')
1160        || path.ends_with(std::path::MAIN_SEPARATOR)
1161        || name.starts_with('.')
1162        || path.ends_with(".svn-base");
1163    !skipped
1164}
1165
1166/// music21's `MuseDataDirectory._prepareGroups`: the paths of a work's
1167/// parts, MuseData files with a digit in the name, the score file left
1168/// out where there are parts, sorted.
1169pub fn part_paths(paths: &[String]) -> Vec<String> {
1170    let name_of = |path: &str| path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
1171    let mut found: Vec<String> = paths
1172        .iter()
1173        .filter(|path| is_musedata_file(path) && !digits(&name_of(path)).is_empty())
1174        .cloned()
1175        .collect();
1176    if found.len() > 1 {
1177        found.retain(|path| {
1178            let letters: String = name_of(path)
1179                .chars()
1180                .filter(|c| !c.is_ascii_digit())
1181                .collect();
1182            !letters.starts_with('s')
1183        });
1184    }
1185    found.sort();
1186    found
1187}
1188
1189/// The record opening a measure, as music21 reads it: its own line where it
1190/// is a measure record, `measure` otherwise.
1191fn measure_line(lines: &[String]) -> Result<String> {
1192    let line = lines
1193        .first()
1194        .ok_or_else(|| error("a measure with no records"))?
1195        .trim()
1196        .to_string();
1197    Ok(if line.starts_with('m') {
1198        line
1199    } else {
1200        "measure".to_string()
1201    })
1202}
1203
1204/// music21's `MuseDataMeasure.getBarObject`: the barline the measure's
1205/// record draws.
1206///
1207/// # Errors
1208///
1209/// No records, or a barline music21 does not know.
1210pub fn bar_object(lines: &[String]) -> Result<Barline> {
1211    let line = measure_line(lines)?;
1212    let kind: String = line.chars().skip(1).take(6).collect();
1213    let bar_type = match kind.as_str() {
1214        "easure" => BarlineType::Regular,
1215        "dotted" => BarlineType::Dotted,
1216        "double" => BarlineType::Double,
1217        "heavy1" | "heavy" => BarlineType::Heavy,
1218        "heavy2" => BarlineType::Final,
1219        "heavy3" => BarlineType::HeavyLight,
1220        "heavy4" | "heave4" => BarlineType::HeavyHeavy,
1221        other => {
1222            return Err(error(format!(
1223                "cannot process bar data definition: {other}"
1224            )));
1225        }
1226    };
1227    let flag: String = line.chars().skip(16).collect();
1228    let flag = flag.trim();
1229    let mut barline = Barline::new(bar_type);
1230    if line.chars().count() > 16 && !flag.is_empty() {
1231        let direction = if flag.contains(":|") {
1232            Some(RepeatDirection::End)
1233        } else if flag.contains("|:") {
1234            Some(RepeatDirection::Start)
1235        } else {
1236            None
1237        };
1238        if let Some(direction) = direction {
1239            barline = Barline::repeat(direction, None);
1240            barline.set_bar_type(bar_type);
1241        }
1242    }
1243    Ok(barline)
1244}
1245
1246/// The number a measure's record gives it, as music21 reads it: every
1247/// digit of the record, `1` where it gives none, and `0` for the notes
1248/// before the first record, a pickup.
1249fn measure_number(lines: &[String]) -> Result<String> {
1250    let line = measure_line(lines)?;
1251    let rest: String = line.chars().skip(8).collect();
1252    let opens_with_record = lines
1253        .first()
1254        .is_some_and(|first| first.trim().starts_with('m'));
1255    Ok(if line.chars().count() >= 9 && !rest.trim().is_empty() {
1256        digits(&line)
1257    } else if opens_with_record {
1258        "1".to_string()
1259    } else {
1260        "0".to_string()
1261    })
1262}
1263
1264/// `MuseDataMeasure.getMeasureObject`: a measure numbered as its record
1265/// says, opening with its barline.
1266///
1267/// # Errors
1268///
1269/// As [`bar_object`].
1270pub fn measure_object(lines: &[String]) -> Result<Stream> {
1271    let number = measure_number(lines)?;
1272    let mut measure = Stream::with_kind(StreamKind::Measure);
1273    measure.set_left_barline(Some(bar_object(lines)?));
1274    if !number.is_empty() {
1275        measure.set_number(
1276            number
1277                .parse()
1278                .map_err(|_| error(format!("measure number {number}")))?,
1279        );
1280    }
1281    Ok(measure)
1282}
1283
1284/// One line of a measure: music21's `MuseDataRecord`.
1285#[derive(Clone, Copy, Debug)]
1286pub struct Record<'a> {
1287    line: &'a str,
1288    stage: Stage,
1289    /// The line of the file it is, counted from one.
1290    number: Option<usize>,
1291}
1292
1293impl<'a> Record<'a> {
1294    /// A record of `line`, written in `stage`.
1295    pub fn new(line: &'a str, stage: Stage) -> Self {
1296        Self {
1297            line,
1298            stage,
1299            number: None,
1300        }
1301    }
1302}
1303
1304impl Record<'_> {
1305    /// `error`, placed at this record's line.
1306    fn placed(&self, error: Error) -> Error {
1307        match self.number {
1308            Some(number) => error.placed(|| Position::line(number)),
1309            None => error,
1310        }
1311    }
1312
1313    fn first(&self) -> Option<char> {
1314        self.line.chars().next()
1315    }
1316
1317    /// The character at a column, counted from nought.
1318    fn at(&self, column: usize) -> Option<char> {
1319        self.line.chars().nth(column)
1320    }
1321
1322    /// The characters from one column up to another.
1323    fn columns(&self, from: usize, to: usize) -> String {
1324        self.line
1325            .chars()
1326            .skip(from)
1327            .take(to.saturating_sub(from))
1328            .collect()
1329    }
1330
1331    /// music21's `isRest`.
1332    pub fn is_rest(&self) -> bool {
1333        self.first() == Some('r')
1334    }
1335
1336    /// music21's `isNote`.
1337    pub fn is_note(&self) -> bool {
1338        self.first().is_some_and(|c| "ABCDEFG".contains(c))
1339    }
1340
1341    /// music21's `isChord`: a further pitch of the note before.
1342    pub fn is_chord(&self) -> bool {
1343        self.first() == Some(' ') && self.at(1).is_some_and(|c| "ABCDEFG".contains(c))
1344    }
1345
1346    /// music21's `isBack`.
1347    pub fn is_back(&self) -> bool {
1348        self.line.starts_with("back")
1349    }
1350
1351    /// music21's `isTied`.
1352    pub fn is_tied(&self) -> bool {
1353        let column = if self.stage == Stage::One { 7 } else { 8 };
1354        self.at(column) == Some('-')
1355    }
1356
1357    /// music21's `isCueOrGrace`.
1358    pub fn is_cue_or_grace(&self) -> bool {
1359        self.first().is_some_and(|c| c == 'c' || c == 'g')
1360    }
1361
1362    /// music21's `_getPitchParameters`: the pitch's name as music21 writes
1363    /// it, `E-4`.
1364    ///
1365    /// # Errors
1366    ///
1367    /// A record that is no note, chord tone, cue or grace note.
1368    pub fn pitch_parameters(&self) -> Result<String> {
1369        let token = if self.is_note() {
1370            self.line
1371        } else if self.is_cue_or_grace() || self.is_chord() {
1372            self.line.get(1..).unwrap_or("")
1373        } else {
1374            return Err(error(
1375                "cannot get pitch parameters from this kind of record",
1376            ));
1377        };
1378        let data = token.split_whitespace().next().unwrap_or("");
1379        let step = data
1380            .chars()
1381            .next()
1382            .ok_or_else(|| error("a note with no pitch"))?;
1383        // music21 asks for one sharp before two, and one flat before two.
1384        let accidental = if data.contains('#') {
1385            "#"
1386        } else if data.contains('f') {
1387            "-"
1388        } else {
1389            ""
1390        };
1391        Ok(format!("{step}{accidental}{}", digits(data)))
1392    }
1393
1394    /// music21's `getPitchObject`: the pitch, with the accidental column 19
1395    /// shows.
1396    ///
1397    /// # Errors
1398    ///
1399    /// As [`Record::pitch_parameters`].
1400    pub fn pitch(&self) -> Result<Pitch> {
1401        let mut pitch = Pitch::from_name(self.pitch_parameters()?)?;
1402        if self.stage == Stage::One {
1403            return Ok(pitch);
1404        }
1405        if let Some(accidental) = pitch.written_accidental_mut() {
1406            accidental.set_display_status(Some(false));
1407        }
1408        if let Some(shown) = self.shown_accidental()? {
1409            pitch.set_accidental(shown);
1410            if let Some(accidental) = pitch.written_accidental_mut() {
1411                accidental.set_display_type("always")?;
1412                accidental.set_display_status(Some(true));
1413            }
1414        }
1415        if self.has_cautionary_accidental()
1416            && let Some(accidental) = pitch.written_accidental_mut()
1417        {
1418            accidental.set_display_status(Some(true));
1419        }
1420        Ok(pitch)
1421    }
1422
1423    /// music21's `hasCautionaryAccidental`: a `+` among the notations.
1424    pub fn has_cautionary_accidental(&self) -> bool {
1425        self.notations()
1426            .is_some_and(|notations| notations.contains('+'))
1427    }
1428
1429    /// music21's `getDots`: none for stage 1.
1430    pub fn dots(&self) -> Option<u8> {
1431        if self.stage == Stage::One {
1432            return None;
1433        }
1434        Some(match self.at(17) {
1435            Some('.') => 1,
1436            Some(':') => 2,
1437            _ => 0,
1438        })
1439    }
1440
1441    /// music21's `_getAccidentalObject`: the accidental column 19 shows.
1442    ///
1443    /// # Errors
1444    ///
1445    /// None in practice: each name is one the crate knows.
1446    pub fn shown_accidental(&self) -> Result<Option<Accidental>> {
1447        if self.line.chars().count() <= 18 {
1448            return Ok(None);
1449        }
1450        let name = match self.at(18) {
1451            Some('#' | 'S') => "sharp",
1452            Some('n') => "natural",
1453            Some('f' | 'F') => "flat",
1454            Some('x' | 'X') => "double-sharp",
1455            Some('&') => "double-flat",
1456            _ => return Ok(None),
1457        };
1458        Accidental::new(name).map(Some)
1459    }
1460
1461    /// music21's `getQuarterLength`, at `divisions` to the quarter.
1462    ///
1463    /// # Errors
1464    ///
1465    /// A length that is no number.
1466    pub fn quarter_length(&self, divisions: FloatType) -> Result<FloatType> {
1467        let mut count = if self.stage == Stage::One {
1468            Part::integer(&self.columns(5, 7))?
1469        } else {
1470            Part::integer(&self.columns(5, 8))?
1471        };
1472        if let Some(blank) = self.at(4)
1473            && blank != ' '
1474        {
1475            let hundreds = blank.to_digit(10).ok_or_else(|| {
1476                error(format!(
1477                    "Error in parsing: {}\n   Column 5 must be blank.",
1478                    self.line
1479                ))
1480            })?;
1481            count += 100 * IntegerType::try_from(hundreds).unwrap_or(0);
1482        }
1483        Ok(op_frac(FloatType::from(count) / divisions))
1484    }
1485
1486    /// music21's `getLyrics`: each verse's syllable.
1487    pub fn lyrics(&self) -> Option<Vec<String>> {
1488        if self.stage == Stage::One || self.line.chars().count() < 44 {
1489            return None;
1490        }
1491        Some(
1492            self.line
1493                .chars()
1494                .skip(43)
1495                .collect::<String>()
1496                .split('|')
1497                .map(|lyric| lyric.trim().to_string())
1498                .collect(),
1499        )
1500    }
1501
1502    /// music21's `getBeams`: the beam column, trailing spaces taken off.
1503    pub fn beams(&self) -> Option<String> {
1504        if self.stage == Stage::One {
1505            return None;
1506        }
1507        let data = self.columns(25, 31);
1508        (!data.is_empty()).then(|| data.trim_end().to_string())
1509    }
1510
1511    /// `getSlurSymbols`: the slur marks among the notations, in the order
1512    /// they are written; a stage-1 record has none.
1513    pub fn slur_marks(&self) -> String {
1514        if self.stage == Stage::One {
1515            return String::new();
1516        }
1517        self.notations()
1518            .unwrap_or_default()
1519            .chars()
1520            .filter(|mark| "()[]{}zx".contains(*mark))
1521            .collect()
1522    }
1523
1524    /// music21's `_getAdditionalNotations`: columns 32 to 43.
1525    pub fn notations(&self) -> Option<String> {
1526        if self.line.chars().count() < 31 {
1527            return None;
1528        }
1529        Some(self.columns(31, 43).trim().to_string())
1530    }
1531
1532    /// music21's `getArticulationObjects`.
1533    pub fn articulations(&self) -> Vec<Articulation> {
1534        let Some(notations) = self.notations() else {
1535            return Vec::new();
1536        };
1537        notations
1538            .chars()
1539            .filter_map(|c| {
1540                let kind = match c {
1541                    'A' | 'V' => ArticulationKind::StrongAccent,
1542                    '>' => ArticulationKind::Accent,
1543                    '.' => ArticulationKind::Staccato,
1544                    '_' => ArticulationKind::Tenuto,
1545                    '=' => ArticulationKind::DetachedLegato,
1546                    'i' => ArticulationKind::Spiccato,
1547                    ',' => ArticulationKind::BreathMark,
1548                    _ => return None,
1549                };
1550                Some(Articulation::of_kind(kind))
1551            })
1552            .collect()
1553    }
1554
1555    /// music21's `getExpressionObjects`.
1556    pub fn expressions(&self) -> Vec<Expression> {
1557        let Some(notations) = self.notations() else {
1558            return Vec::new();
1559        };
1560        notations
1561            .chars()
1562            .filter_map(|c| match c {
1563                'F' | 'E' => Some(Expression::from(Fermata::new())),
1564                't' => Some(Expression::from(Ornament::of_kind(OrnamentKind::Trill))),
1565                'r' => Some(Expression::from(Ornament::of_kind(OrnamentKind::Turn))),
1566                'M' => Some(Expression::from(Ornament::of_kind(OrnamentKind::Mordent))),
1567                _ => None,
1568            })
1569            .collect()
1570    }
1571
1572    /// `getDynamicObjects`: each mark found once, in music21's order of
1573    /// looking, and taken out of what is left to look in.
1574    pub fn dynamics(&self) -> Vec<Dynamic> {
1575        let Some(mut data) = self.notations() else {
1576            return Vec::new();
1577        };
1578        let mut out = Vec::new();
1579        for target in [
1580            "ppp", "fff", "pp", "ff", "fp", "mp", "mf", "p", "f", "m", "Z", "Zp", "R",
1581        ] {
1582            let Some(at) = data.find(target) else {
1583                continue;
1584            };
1585            data.replace_range(at..at + target.len(), "");
1586            let value = match target {
1587                "m" => "mp",
1588                "Z" | "Zp" | "R" => "sf",
1589                other => other,
1590            };
1591            out.push(Dynamic::new(value));
1592        }
1593        out
1594    }
1595}
1596
1597/// music21's `_musedataBeamToBeams`: the beams a record's beam column
1598/// writes, `[` starting, `]` stopping, `=` continuing and `/` and `\\`
1599/// partial to the right and left.
1600///
1601/// ```
1602/// use music21::musedata::beams_of;
1603///
1604/// assert_eq!(beams_of("]/").len(), 2);
1605/// ```
1606pub fn beams_of(written: &str) -> Beams {
1607    let mut beams = Beams::default();
1608    for c in written.chars() {
1609        let (kind, direction) = match c {
1610            '[' => (BeamType::Start, None),
1611            ']' => (BeamType::Stop, None),
1612            '=' => (BeamType::Continue, None),
1613            '/' => (BeamType::PartialBeam, Some(BeamDirection::Right)),
1614            '\\' => (BeamType::PartialBeam, Some(BeamDirection::Left)),
1615            _ => continue,
1616        };
1617        beams.append(kind, direction);
1618    }
1619    beams
1620}
1621
1622/// `_musedataRecordListToNoteOrChord`: a note, or a chord of several
1623/// records, what the first record says of it, the dynamics it carries, and
1624/// the tie it leaves for the next.
1625fn note_or_chord(
1626    records: &[Record<'_>],
1627    divisions: FloatType,
1628    previous: Option<Option<TieType>>,
1629) -> Result<(StreamElement, Vec<Dynamic>, Option<TieType>)> {
1630    let first = records[0];
1631    let duration = Duration::new(first.quarter_length(divisions)?)?;
1632    let held = matches!(previous, Some(Some(TieType::Start | TieType::Continue)));
1633    let tie = if first.is_tied() {
1634        Some(if held {
1635            TieType::Continue
1636        } else {
1637            TieType::Start
1638        })
1639    } else if held {
1640        Some(TieType::Stop)
1641    } else {
1642        None
1643    };
1644    let mut pitches = Vec::new();
1645    for record in records {
1646        pitches.push(record.pitch()?);
1647    }
1648    let lyrics = first.lyrics();
1649    let beams = first.beams().map(|written| beams_of(&written));
1650    let element = if pitches.len() == 1 {
1651        let mut note = Note::from_pitch(pitches.remove(0)).with_duration(duration);
1652        for lyric in lyrics.iter().flatten() {
1653            note.add_lyric(lyric, None, false)?;
1654        }
1655        if let Some(beams) = beams {
1656            note.set_beams(beams);
1657        }
1658        note.articulations_mut().extend(first.articulations());
1659        note.expressions_mut().extend(first.expressions());
1660        note.set_tie(tie.map(Tie::new));
1661        StreamElement::Note(note)
1662    } else {
1663        let notes: Vec<Note> = pitches.into_iter().map(Note::from_pitch).collect();
1664        let mut chord = Chord::new(notes)?.with_duration(duration);
1665        for lyric in lyrics.iter().flatten() {
1666            chord.add_lyric(lyric, None, false)?;
1667        }
1668        if let Some(beams) = beams {
1669            chord.set_beams(beams);
1670        }
1671        chord.articulations_mut().extend(first.articulations());
1672        chord.expressions_mut().extend(first.expressions());
1673        for note in chord.notes_mut() {
1674            note.set_tie(tie.map(Tie::new));
1675        }
1676        StreamElement::Chord(chord)
1677    };
1678    Ok((element, first.dynamics(), tie))
1679}
1680
1681/// music21's `_musedataRecordListToNoteOrChord`, over the lines of the
1682/// records: a note, or a chord of several, at `divisions` to the quarter,
1683/// with the dynamics the first record carries and the tie it leaves.
1684/// `previous` is the tie of the note before, where there is a note before.
1685///
1686/// # Errors
1687///
1688/// No records, a pitch or a length that cannot be read.
1689pub fn record_note(
1690    lines: &[String],
1691    stage: Stage,
1692    divisions: FloatType,
1693    previous: Option<Option<TieType>>,
1694) -> Result<(StreamElement, Vec<Dynamic>, Option<TieType>)> {
1695    let records: Vec<Record<'_>> = lines
1696        .iter()
1697        .map(|line| Record {
1698            line,
1699            stage,
1700            number: None,
1701        })
1702        .collect();
1703    if records.is_empty() {
1704        return Err(error("a note of no records"));
1705    }
1706    note_or_chord(&records, divisions, previous)
1707}
1708
1709/// music21's `base40DeltaToInterval`, refused as a MuseData error.
1710fn base40_interval(delta: i32) -> Result<Interval> {
1711    base40::delta_to_interval(delta).map_err(|refused| error(refused.message()))
1712}
1713
1714#[cfg(test)]
1715mod tests {
1716    use super::*;
1717
1718    #[test]
1719    fn a_base40_distance_is_an_interval_with_its_octaves() {
1720        assert_eq!(base40_interval(-11).unwrap().directed_name(), "m-3");
1721        assert_eq!(base40_interval(23).unwrap().directed_name(), "P5");
1722        assert_eq!(base40_interval(63).unwrap().directed_name(), "P12");
1723        assert!(base40_interval(2).is_err());
1724    }
1725
1726    #[test]
1727    fn a_measure_number_is_every_digit_of_its_record_and_a_pickup_is_0() {
1728        let lines = ["mheavy2 12".to_string(), "C4 1 q".to_string()];
1729        assert_eq!(measure_object(&lines).unwrap().number(), 212);
1730        let lines = ["measure".to_string(), "C4 1 q".to_string()];
1731        assert_eq!(measure_object(&lines).unwrap().number(), 1);
1732        let lines = ["C4 1 q".to_string()];
1733        assert_eq!(measure_object(&lines).unwrap().number(), 0);
1734    }
1735
1736    #[test]
1737    fn a_refusal_says_its_line_measure_and_part() {
1738        let part = |attributes: &str, record: &str| {
1739            format!(
1740                "\n\n\n01/01/01 x\nWK#:1 MV#:1\nsource\nWork\nMovement\nFlute\n\
1741                 1 0\nGroup memberships: score\nscore: part 1 of 1\n\
1742                 & a comment\n&\n{attributes}\nC5     2        q     u\n\
1743                 D5     2        q     u\nmeasure 2\n{record}\n/END\n"
1744            )
1745        };
1746        let error =
1747            from_musedata(&[&part("$  K:0   Q:2   T:2/4   C:4", "E5     x        h")]).unwrap_err();
1748        assert_eq!(error.to_string(), "MuseData error: \"  x\" is not a number");
1749        let mut wanted = Position::line(19).in_part("Flute");
1750        wanted.measure = Some("2".to_string());
1751        assert_eq!(error.position(), Some(&wanted));
1752
1753        let error =
1754            from_musedata(&[&part("$  K:0   Q:2   T:x/4   C:4", "E5     4        h")]).unwrap_err();
1755        assert_eq!(error.position(), Some(&Position::line(15).in_part("Flute")));
1756    }
1757
1758    #[test]
1759    fn beams_are_read_from_their_column() {
1760        let beams = beams_of("[[/");
1761        assert_eq!(beams.len(), 3);
1762    }
1763
1764    #[test]
1765    fn a_dynamic_is_taken_out_before_the_next_is_looked_for() {
1766        let record = Record {
1767            line: "C5     3        e     d  [     pp.",
1768            stage: Stage::Two,
1769            number: None,
1770        };
1771        let values: Vec<String> = record
1772            .dynamics()
1773            .iter()
1774            .map(|dynamic| dynamic.value().to_string())
1775            .collect();
1776        assert_eq!(values, ["pp"]);
1777    }
1778
1779    #[test]
1780    fn ties_stay_in_their_voice_across_a_back() {
1781        let part = "\n\n\n04/16/93 E. Correia\nWK#:581       MV#:3c\n\
1782            Breitkopf & Hartel, Vol. 13\nClarinet Quintet\nTrio II\nPiano\n1 0\n\
1783            Group memberships: score\nscore: part 1 of 1\n\
1784            $  K:0   Q:1   T:2/4   C:4\nmeasure 1\nC5     1        q     u\n\
1785            E5     1-       q     u\nback   2\nC4     1        q     d\n\
1786            G3     1-       q     d\nmeasure 2\nE5     2        h     u\n\
1787            back   2\nG3     1        q     d\nA3     1        q     d\n\
1788            measure 3\nF5     2        h\n/END\n";
1789        let score = from_musedata(&[part]).expect("the part is read");
1790        let ties = |stream: &Stream| -> Vec<Option<&'static str>> {
1791            stream
1792                .notes()
1793                .iter()
1794                .map(|(_, element)| match element {
1795                    StreamElement::Note(note) => note.tie().map(|tie| tie.tie_type().as_str()),
1796                    _ => None,
1797                })
1798                .collect()
1799        };
1800        let parts = score.parts();
1801        let measures = parts[0].measures();
1802        let first = measures[0].voices();
1803        let second = measures[1].voices();
1804        assert_eq!(ties(first[0]), [None, Some("start")]);
1805        assert_eq!(ties(first[1]), [None, Some("start")]);
1806        assert_eq!(ties(second[0]), [Some("stop")]);
1807        assert_eq!(ties(second[1]), [Some("stop"), None]);
1808        assert_eq!(ties(measures[2]), [None]);
1809    }
1810
1811    #[test]
1812    fn windows_line_endings_are_read_as_unix_ones() {
1813        let unix = "Title\nSource\n$ K:0 Q:4 T:4/4 C:4\nC4 4 q\n/END\n";
1814        let windows = unix.replace('\n', "\r\n");
1815        let lines = |text: &str| -> Vec<Vec<String>> {
1816            split_parts(text)
1817                .expect("the parts are read")
1818                .into_iter()
1819                .map(|part| part.lines)
1820                .collect()
1821        };
1822        assert_eq!(lines(&windows), lines(unix));
1823        assert!(
1824            lines(&windows)
1825                .iter()
1826                .flatten()
1827                .all(|line| !line.contains('\r'))
1828        );
1829    }
1830
1831    /// A stage-2 header as music21's test files write one.
1832    fn header_part() -> Part {
1833        let lines: Vec<String> = [
1834            "",
1835            "",
1836            "",
1837            "",
1838            "WK#:1         MV#:2",
1839            "Synthetic",
1840            "Air",
1841            "Second",
1842            "Upper",
1843            "",
1844            "Group memberships: sound, score",
1845            "sound: part 1 of 2",
1846            "score: part 1 of 2",
1847            "$  K:-1   Q:4   T:3/4   C:4   D:Andante",
1848            "measure 1",
1849            "C4     4        q     u",
1850        ]
1851        .iter()
1852        .map(|line| line.to_string())
1853        .collect();
1854        Part::with_stage(lines, Stage::Two)
1855    }
1856
1857    #[test]
1858    fn a_part_answers_music21_s_header_questions() {
1859        let part = header_part();
1860        assert_eq!(part.work_number().as_deref(), Some("1"));
1861        assert_eq!(part.source().as_deref(), Some("Synthetic"));
1862        assert_eq!(part.group_memberships(), ["sound", "score"]);
1863        assert_eq!(part.group_total("score").unwrap(), Some(2));
1864        assert_eq!(part.group_number("sound").unwrap().as_deref(), Some("1"));
1865        assert_eq!(part.key_parameters().unwrap(), -1);
1866        assert_eq!(part.time_signature_parameters().unwrap(), "3/4");
1867        assert_eq!(part.clef_parameters().unwrap(), ["4"]);
1868        assert_eq!(part.directive().unwrap().as_deref(), Some("Andante"));
1869        assert_eq!(part.transposition_parameters().unwrap(), None);
1870        // music21's `_getMeasureBoundaryIndices` docstring, ends exclusive.
1871        let lines: Vec<String> = ["$", "m", "B", "C", "m", "D", "E", "m", "F", "D"]
1872            .iter()
1873            .map(|line| line.to_string())
1874            .collect();
1875        let bounds = Part::with_stage(lines, Stage::Two)
1876            .measure_bounds()
1877            .unwrap();
1878        assert_eq!(bounds, [(1, 4), (4, 7), (7, 10)]);
1879    }
1880
1881    #[test]
1882    fn a_record_answers_music21_s_questions() {
1883        let record = Record::new("F#4    1        s #   d  ==", Stage::Two);
1884        assert_eq!(record.pitch_parameters().unwrap(), "F#4");
1885        assert!(record.shown_accidental().unwrap().is_some());
1886        assert_eq!(record.dots(), Some(0));
1887        let marked = Record::new("F5     3        t n   d  ==[   (+", Stage::Two);
1888        assert!(marked.has_cautionary_accidental());
1889        assert!(Record::new("back   4", Stage::Two).is_back());
1890        assert!(
1891            Record::new("back   4", Stage::Two)
1892                .pitch_parameters()
1893                .is_err()
1894        );
1895    }
1896
1897    #[test]
1898    fn a_directory_keeps_its_part_files() {
1899        let names: Vec<String> = [
1900            "w/02.md", "w/s01", "w/01.md", "w/mchan1", "w/.svn", "w/notes",
1901        ]
1902        .iter()
1903        .map(|name| name.to_string())
1904        .collect();
1905        assert_eq!(part_paths(&names), ["w/01.md", "w/02.md"]);
1906    }
1907}