Skip to main content

music21/musicxml/
read.rs

1//! Reading MusicXML: music21's `musicxml.xmlToM21`.
2//!
3//! The document is read measure by measure into a list of elements, each
4//! with its offset, the voice and staff it was written in and the order it
5//! was met in, and the score is put together from those at the end -- which
6//! is where music21 sorts its streams and splits a part written on several
7//! staves into one part for each.
8//!
9//! What the crate does not model is passed over as music21's reader passes
10//! over what it does not know: page layout, fonts, positions, credits.
11
12use crate::articulations::{Articulation, ArticulationKind, Finger};
13use crate::bar::{Barline, BarlineType, Ending, RepeatDirection};
14use crate::chord::Chord;
15use crate::chordsymbol::{ChordStepModification, ChordSymbol};
16use crate::clef::Clef;
17use crate::defaults::{FloatType, IntegerType};
18use crate::duration::{
19    Duration, DurationType, Grace, Tuplet, TupletBracket, TupletShow, TupletType,
20};
21use crate::dynamics::Dynamic;
22use crate::error::{Error, FormatErrorKind, Position, Result};
23use crate::expressions::{
24    ArpeggioType, Expression, Fermata, FermataType, Ornament, OrnamentDelay, OrnamentKind,
25    RehearsalMark, TextExpression,
26};
27use crate::instrument::{Instrument, SearchLanguage};
28use crate::interval::Interval;
29use crate::key::KeySignature;
30use crate::layout::{
31    Layout, PageLayout, ScoreLayout, StaffLayout, StaffType, SystemLayout, Tenths,
32};
33use crate::metadata::{Metadata, MetadataValue};
34use crate::meter::TimeSignature;
35use crate::notation::{
36    Beam, BeamDirection, BeamType, Beams, Justification, Lyric, NoteSize, Notehead, Placement,
37    StemDirection, Syllabic, Tie, TieStyle, TieType,
38};
39use crate::note::Note;
40use crate::percussion::{PercussionChord, PercussionNote, Unpitched};
41use crate::pitch::{Accidental, Pitch};
42use crate::repeat::{RepeatExpression, RepeatExpressionKind};
43use crate::rest::Rest;
44use crate::spanner::{
45    Glissando, LineEnd, LineEnds, MultiRest, OctaveShift, Pedal, PedalForm, PedalObject,
46    PedalObjectKind, PedalType, SlideType, Spanner, SpannerKind,
47};
48use crate::stream::{BarTogether, StaffGroup, Stream, StreamElement, StreamEvent, StreamKind};
49use crate::style::{StyleValue, TextStyle};
50use crate::tempo::{MetricModulation, MetronomeMark};
51use crate::text::TextBox;
52use crate::volume::Volume;
53use crate::xml::Xml;
54
55/// What may be drawn round a mark: music21's `style.Enclosure`.
56const ENCLOSURES: [&str; 15] = [
57    "rectangle",
58    "square",
59    "oval",
60    "circle",
61    "bracket",
62    "triangle",
63    "diamond",
64    "pentagon",
65    "hexagon",
66    "heptagon",
67    "octagon",
68    "nonagon",
69    "decagon",
70    "inverted-bracket",
71    "none",
72];
73
74/// The staff an element is written on where nothing says: music21's
75/// `NO_STAFF_ASSIGNED`.
76const NO_STAFF: i32 = 0;
77
78fn import_error(message: impl Into<String>) -> Error {
79    Error::music_xml(message.into())
80}
81
82/// Reads a MusicXML document -- the text of a `.musicxml` file, or of the
83/// score inside a compressed `.mxl` -- into a score: music21's
84/// `converter.parse` for the format.
85///
86/// ```
87/// use music21::musicxml::from_musicxml;
88///
89/// let score = from_musicxml(
90///     "<score-partwise><part-list><score-part id=\"P1\"><part-name>Flute</part-name>\
91///      </score-part></part-list><part id=\"P1\"><measure number=\"1\">\
92///      <attributes><divisions>1</divisions></attributes>\
93///      <note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration>\
94///      <type>whole</type></note></measure></part></score-partwise>",
95/// )?;
96/// let part = score.parts()[0];
97/// assert_eq!(part.name(), Some("Flute"));
98/// assert_eq!(part.measures()[0].pitches()[0].name_with_octave(), "C4");
99/// # Ok::<(), music21::Error>(())
100/// ```
101pub fn from_musicxml(document: &str) -> Result<Stream> {
102    let root = Xml::parse(document)?;
103    if root.tag != "score-partwise" {
104        return Err(import_error(format!(
105            "only a score-partwise document can be read, not <{}>",
106            root.tag
107        ))
108        .of_kind(FormatErrorKind::Unsupported));
109    }
110    score_of(&root)
111}
112
113/// A `<score-partwise>` already read as XML, read as a score.
114pub(super) fn score_of(root: &Xml) -> Result<Stream> {
115    Importer::default().score(root)
116}
117
118/// A `<score-partwise>` read as a score, with what music21 warns of as
119/// it reads it.
120pub(super) fn score_warned(root: &Xml) -> Result<(Stream, Vec<Error>)> {
121    let mut importer = Importer::default();
122    let read = importer.score(root)?;
123    Ok((read, importer.warnings))
124}
125
126/// The same, its first part starting inside `tuplets`, which are left as
127/// the last part ends.
128pub(super) fn score_within(root: &Xml, tuplets: &mut ActiveTuplets) -> Result<Stream> {
129    let mut importer = Importer {
130        tuplets_before: Some(*tuplets),
131        ..Importer::default()
132    };
133    let read = importer.score(root);
134    *tuplets = importer.tuplets_after;
135    read
136}
137
138// ------------------------------------------------------------------ numbers
139
140/// A number snapped to the nearest fraction music21 would hold it as:
141/// `opFrac`, which keeps a float whose denominator is a small power of two
142/// and otherwise takes the closest fraction with a denominator up to 65535.
143fn op_frac(value: FloatType) -> FloatType {
144    if (value * 32768.0).fract() == 0.0 {
145        return value;
146    }
147    let negative = value < 0.0;
148    let target = value.abs();
149    // Continued fractions, stopping at the last convergent under the limit.
150    let (mut p0, mut q0, mut p1, mut q1) = (0i64, 1i64, 1i64, 0i64);
151    let mut x = target;
152    let (mut best_p, mut best_q) = (target.round() as i64, 1i64);
153    for _ in 0..40 {
154        let a = x.floor();
155        let (p2, q2) = (a as i64 * p1 + p0, a as i64 * q1 + q0);
156        if q2 > 65535 {
157            // The best semiconvergent under the limit, as Python's
158            // `limit_denominator` takes it.
159            let k = (65535 - q0) / q1.max(1);
160            let (sp, sq) = (p0 + k * p1, q0 + k * q1);
161            let semi = (sp as FloatType / sq as FloatType - target).abs();
162            let conv = (p1 as FloatType / q1 as FloatType - target).abs();
163            (best_p, best_q) = if semi < conv { (sp, sq) } else { (p1, q1) };
164            break;
165        }
166        (p0, q0, p1, q1) = (p1, q1, p2, q2);
167        (best_p, best_q) = (p1, q1);
168        let rest = x - a;
169        if rest.abs() < 1e-12 {
170            break;
171        }
172        x = 1.0 / rest;
173    }
174    let snapped = best_p as FloatType / best_q as FloatType;
175    if negative { -snapped } else { snapped }
176}
177
178/// music21's `setSoundTempo`: the quarters a minute a `<sound>`'s `tempo`
179/// attribute plays at, or `None` for one that is nought or no number,
180/// which sets no tempo.
181///
182/// ```
183/// use music21::musicxml::sound_tempo;
184///
185/// assert_eq!(sound_tempo("128"), Some(128.0));
186/// assert_eq!(sound_tempo("0"), None);
187/// ```
188pub fn sound_tempo(tempo: &str) -> Option<FloatType> {
189    parse_float(tempo).filter(|qpm| *qpm != 0.0)
190}
191
192fn parse_float(text: &str) -> Option<FloatType> {
193    text.trim().parse::<FloatType>().ok()
194}
195
196fn parse_int(text: &str) -> Option<IntegerType> {
197    let text = text.trim();
198    text.parse::<IntegerType>().ok().or_else(|| {
199        // Python's `int(float_text)` is not accepted by music21 either, but
200        // a whole number written with a point is common in the wild.
201        text.parse::<FloatType>()
202            .ok()
203            .filter(|value| value.fract() == 0.0)
204            .map(|value| value as IntegerType)
205    })
206}
207
208/// How many strokes a `<tremolo>` says, three where it says nothing a
209/// number can be read from: music21's `xmlToTremolo`.
210fn tremolo_marks(mark: &Xml) -> Result<u8> {
211    let marks = parse_int(mark.stripped()).unwrap_or(3);
212    u8::try_from(marks)
213        .ok()
214        .filter(|marks| *marks <= 8)
215        .ok_or_else(|| import_error("Number of marks must be a number from 0 to 8"))
216}
217
218fn yes(value: Option<&str>) -> bool {
219    value == Some("yes")
220}
221
222fn placement_of(element: &Xml) -> Option<Placement> {
223    element
224        .get("placement")
225        .and_then(|name| Placement::from_name(name).ok())
226}
227
228/// music21's `musicXMLTypeToType`.
229fn duration_type(name: &str) -> Result<DurationType> {
230    let name = match name {
231        "long" => "longa",
232        "32th" => "32nd",
233        other => other,
234    };
235    DurationType::from_music21_name(name)
236        .ok_or_else(|| import_error(format!("found unknown MusicXML type: {name}")))
237}
238
239// ------------------------------------------------------------ what is read
240
241/// One element of a measure as it was read.
242#[derive(Clone, Debug)]
243struct Item {
244    offset: FloatType,
245    /// The order it was put into its stream, which settles the order of
246    /// two elements music21 sorts alike.
247    seq: usize,
248    staff: i32,
249    /// What spanners know it by; nothing for a copy.
250    uid: Option<usize>,
251    element: StreamElement,
252}
253
254impl Item {
255    /// music21's `classSortOrder`.
256    fn order(&self) -> i32 {
257        self.element.class_sort_order()
258    }
259
260    fn is_grace(&self) -> bool {
261        self.element.duration().is_some_and(Duration::is_grace)
262    }
263
264    /// Whether it lasts, as a note, chord or rest does: music21's
265    /// `GeneralNote` that is not a chord symbol.
266    fn is_note_or_rest(&self) -> bool {
267        matches!(
268            self.element,
269            StreamElement::Note(_)
270                | StreamElement::Chord(_)
271                | StreamElement::Rest(_)
272                | StreamElement::Unpitched(_)
273                | StreamElement::PercussionChord(_)
274        )
275    }
276}
277
278/// Elements in the order music21 sorts a stream into: by offset, then by
279/// class, grace notes ahead of the note they lean on, then as inserted.
280fn sorted(mut items: Vec<Item>) -> Vec<Item> {
281    items.sort_by(|left, right| {
282        left.offset
283            .total_cmp(&right.offset)
284            .then(left.order().cmp(&right.order()))
285            .then(right.is_grace().cmp(&left.is_grace()))
286            .then(left.seq.cmp(&right.seq))
287    });
288    items
289}
290
291#[derive(Clone, Debug, Default)]
292struct VoiceIr {
293    id: String,
294    items: Vec<Item>,
295}
296
297#[derive(Clone, Debug, Default)]
298struct MeasureIr {
299    offset: FloatType,
300    number: IntegerType,
301    suffix: Option<String>,
302    hidden: bool,
303    left: Option<Barline>,
304    right: Option<Barline>,
305    ending: Option<Ending>,
306    padding_left: FloatType,
307    padding_right: FloatType,
308    width: Option<StyleValue>,
309    measure_numbering: Option<String>,
310    items: Vec<Item>,
311    voices: Vec<VoiceIr>,
312}
313
314impl MeasureIr {
315    /// Where the last thing in the measure ends: music21's `highestTime`.
316    fn highest_time(&self) -> FloatType {
317        let end = |item: &Item| item.offset + item.element.quarter_length();
318        self.items
319            .iter()
320            .chain(self.voices.iter().flat_map(|voice| &voice.items))
321            .map(end)
322            .fold(0.0, FloatType::max)
323    }
324
325    /// Where the last thing standing in the measure itself ends, its voices
326    /// counted as empty: what music21's `highestTime` answers while the
327    /// measure is still being read, each voice's length having been worked
328    /// out before anything was put in it.
329    fn highest_time_outside_voices(&self) -> FloatType {
330        self.items
331            .iter()
332            .map(|item| item.offset + item.element.quarter_length())
333            .fold(0.0, FloatType::max)
334    }
335}
336
337/// A spanner while its ends are still being met.
338#[derive(Clone, Debug)]
339struct Building {
340    kind: SpannerKind,
341    id_local: Option<String>,
342    complete: bool,
343    uids: Vec<usize>,
344    placement: Option<Placement>,
345    line_type: Option<String>,
346    ends: LineEnds,
347    shift: Option<OctaveShift>,
348    pedal: Pedal,
349    arpeggio: ArpeggioType,
350    slide: SlideType,
351    marks: u8,
352    /// Whether a rest of several measures is drawn with symbols.
353    use_symbols: bool,
354    /// Whether it has been put into a part already.
355    placed: bool,
356}
357
358impl Building {
359    fn new(kind: SpannerKind, id_local: Option<&str>) -> Self {
360        Self {
361            kind,
362            id_local: id_local.map(str::to_string),
363            complete: false,
364            uids: Vec::new(),
365            placement: match kind {
366                SpannerKind::Crescendo | SpannerKind::Diminuendo => Some(Placement::Below),
367                SpannerKind::Ottava | SpannerKind::Line => Some(Placement::Above),
368                _ => None,
369            },
370            line_type: (kind == SpannerKind::Glissando).then(|| "wavy".to_string()),
371            ends: LineEnds::default(),
372            shift: None,
373            pedal: Pedal::default(),
374            arpeggio: ArpeggioType::Normal,
375            slide: SlideType::Chromatic,
376            marks: 3,
377            use_symbols: false,
378            placed: false,
379        }
380    }
381
382    fn add(&mut self, uid: usize) {
383        if !self.uids.contains(&uid) {
384            self.uids.push(uid);
385        }
386    }
387
388    /// music21's `insertFirstSpannedElement`.
389    fn add_first(&mut self, uid: usize) {
390        if !self.uids.contains(&uid) {
391            self.uids.insert(0, uid);
392        }
393    }
394
395    /// The finished spanner, its elements named by where they stand.
396    fn finish(&self, position_of: &dyn Fn(usize) -> Option<usize>) -> Spanner {
397        let positions: Vec<Option<usize>> = self.uids.iter().map(|uid| position_of(*uid)).collect();
398        let mut spanner = match self.kind {
399            SpannerKind::Crescendo | SpannerKind::Diminuendo => {
400                let mut wedge = Spanner::wedge(self.kind, Vec::new());
401                wedge = with_positions(wedge, positions);
402                wedge
403            }
404            SpannerKind::Line => {
405                let mut line = with_positions(Spanner::line(Vec::new()), positions);
406                line.set_ends(self.ends);
407                line
408            }
409            _ => Spanner::with_unplaced(self.kind, positions),
410        };
411        spanner.set_placement(self.placement);
412        spanner.set_id_local(self.id_local.clone());
413        spanner.set_complete(true);
414        if self.kind != SpannerKind::Crescendo && self.kind != SpannerKind::Diminuendo {
415            spanner.set_line_type(self.line_type.clone());
416        }
417        if self.kind == SpannerKind::Line {
418            spanner.set_line_type(Some(
419                self.line_type
420                    .clone()
421                    .unwrap_or_else(|| "solid".to_string()),
422            ));
423        }
424        spanner.set_shift(self.shift);
425        if self.kind == SpannerKind::PedalMark {
426            spanner.set_pedal(Some(self.pedal));
427        }
428        if self.kind == SpannerKind::Glissando {
429            spanner.set_glissando_details(Some(Glissando {
430                slide_type: self.slide,
431                label: None,
432            }));
433        }
434        if self.kind == SpannerKind::TremoloSpanner {
435            // Read already within the range a tremolo allows.
436            let _ = spanner.set_number_of_marks(Some(self.marks));
437        }
438        if self.kind == SpannerKind::MultiMeasureRest {
439            spanner.set_multi_rest(Some(MultiRest {
440                use_symbols: self.use_symbols,
441                ..MultiRest::default()
442            }));
443        }
444        spanner.set_arpeggio(self.arpeggio);
445        spanner
446    }
447}
448
449/// A spanner of the same kind and drawing over other positions.
450fn with_positions(template: Spanner, positions: Vec<Option<usize>>) -> Spanner {
451    let mut spanner = Spanner::with_unplaced(template.kind(), positions);
452    spanner.set_placement(template.placement());
453    spanner.set_line_type(template.line_type().map(str::to_string));
454    spanner.set_spread(template.spread());
455    spanner
456}
457
458/// A first or second ending while its measures are still being met:
459/// music21's `RepeatBracket`.
460#[derive(Clone, Debug)]
461struct Bracket {
462    numbers: Vec<u32>,
463    measures: Vec<usize>,
464    complete: bool,
465}
466
467/// music21's `RepeatBracket.number` setter: nothing at all is nought,
468/// which is written as no number; otherwise `1`, `1, 2` or `1-3`.
469fn bracket_numbers(text: &str) -> Vec<u32> {
470    // music21 falls back to a first ending where it cannot read one.
471    Ending::numbers_from_text(text).unwrap_or_else(|_| vec![1])
472}
473
474// ------------------------------------------------------------- measure fit
475
476/// What is known of a measure as it goes into its part.
477#[derive(Clone, Copy, Debug, PartialEq)]
478pub struct FitAsked {
479    /// Where its contents end, in quarters: music21's `highestTime`.
480    pub highest: FloatType,
481    /// How long a bar of its meter is.
482    pub bar_length: FloatType,
483    /// Whether it holds a note or a rest.
484    pub has_notes: bool,
485    /// Whether it opens the part: nothing before it took any time.
486    pub at_start: bool,
487    /// Whether the measure before it was cut short.
488    pub last_was_short: bool,
489}
490
491/// How a measure sits in its part: music21's
492/// `adjustTimeAttributesFromMeasure`.
493#[derive(Clone, Copy, Debug, Default, PartialEq)]
494pub struct MeasureFit {
495    /// How far the next measure starts after this one.
496    pub shift: FloatType,
497    /// The padding of a pickup, where it is one.
498    pub padding_left: Option<FloatType>,
499    /// What a measure cut short lacks at its end.
500    pub padding_right: Option<FloatType>,
501    /// Whether an empty measure is filled with a bar's rest.
502    pub fill_with_rest: bool,
503    /// Whether it is overfull by an amount music21 takes for a mistake,
504    /// and so takes the bar's length instead; music21 warns then.
505    pub overfull_ignored: bool,
506    /// Whether the next measure follows one cut short.
507    pub last_was_short: bool,
508}
509
510/// Decides how a measure sits in its part, as music21's
511/// `adjustTimeAttributesFromMeasure` does.
512pub fn measure_fit(asked: &FitAsked) -> MeasureFit {
513    let FitAsked {
514        highest,
515        bar_length,
516        has_notes,
517        at_start,
518        last_was_short,
519    } = *asked;
520    let mut fit = MeasureFit {
521        shift: highest,
522        last_was_short,
523        ..MeasureFit::default()
524    };
525
526    // Full, or overfull by a round amount or by a lot, keeps its length.
527    if highest == bar_length {
528        return fit;
529    }
530    if highest > bar_length {
531        let difference = highest - bar_length;
532        let near = |unit: FloatType| {
533            let multiple = (difference / unit).round() * unit;
534            (difference - multiple).abs() < 1e-6
535        };
536        if !(difference > 0.5 || near(0.0625) || near(1.0 / 12.0)) {
537            fit.shift = bar_length;
538            fit.overfull_ignored = true;
539        }
540        return fit;
541    }
542
543    // An empty measure some writers leave the rest out of.
544    if highest == 0.0 && !has_notes {
545        fit.shift = bar_length;
546        fit.fill_with_rest = true;
547        fit.last_was_short = false;
548        return fit;
549    }
550
551    // A short measure is a pickup where it opens the part or follows
552    // another short one, and is cut short at its end otherwise. music21
553    // pads a pickup as `padAsAnacrusis` does, by the share of the bar it
554    // lacks, and a short measure by what it lacks, unsnapped.
555    let anacrusis = op_frac(bar_length * (1.0 - op_frac(highest / bar_length)));
556    if at_start {
557        fit.padding_left = Some(anacrusis);
558    } else if last_was_short {
559        fit.padding_left = Some(anacrusis);
560        fit.last_was_short = false;
561    } else {
562        fit.padding_right = Some(bar_length - op_frac(highest));
563        fit.last_was_short = true;
564    }
565    fit
566}
567
568// ----------------------------------------------------------------- importer
569
570/// The spanners a reading is building, which outlive one element: the
571/// state music21 keeps in its `spannerBundle`. A reading of one element
572/// at a time keeps it between elements, as music21's parsers do.
573#[derive(Clone, Debug, Default)]
574pub struct SpannerState {
575    spanners: Vec<Building>,
576    /// The spanners waiting for the next note, chord or rest, which becomes
577    /// the first thing the one at the front joins.
578    pending: std::collections::VecDeque<usize>,
579    /// Spanners in the order music21's score holds them once it is read, by
580    /// where each stands in `spanners`: one finished in a part may still be
581    /// handed the first note of the next by the queue.
582    finished: Vec<usize>,
583    /// The last uid given to anything read.
584    next_uid: usize,
585    /// Where each pedal mark began, for a `resume` at that very place:
586    /// music21's `pedalToStartOffset`.
587    pedal_starts: Vec<(usize, FloatType)>,
588}
589
590/// A spanner a [`SpannerState`] is building, by where it stands there.
591#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
592pub struct SpannerId(usize);
593
594impl SpannerState {
595    /// A new uid, for something read outside this state -- a note -- that
596    /// a spanner may then join.
597    pub fn new_uid(&mut self) -> usize {
598        self.next_uid += 1;
599        self.next_uid
600    }
601
602    /// The spanner as built so far, standing in no stream: what it says of
603    /// itself, and whether its end has been read.
604    pub fn spanner(&self, id: SpannerId) -> Option<Spanner> {
605        let building = self.spanners.get(id.0)?;
606        let mut spanner = building.finish(&|_| None);
607        spanner.set_complete(building.complete);
608        Some(spanner)
609    }
610
611    /// The uids of what the spanner joins, in order.
612    pub fn joined(&self, id: SpannerId) -> &[usize] {
613        self.spanners
614            .get(id.0)
615            .map_or(&[], |building| building.uids.as_slice())
616    }
617
618    /// Every spanner the state holds, in the order they were begun.
619    pub fn ids(&self) -> impl Iterator<Item = SpannerId> {
620        (0..self.spanners.len()).map(SpannerId)
621    }
622}
623
624/// What one step of spanner reading did: the spanners it handed back
625/// and the ones it began, and the pedal's bounces and gaps it put in the
626/// measure, each with its uid and offset.
627#[derive(Clone, Debug, Default)]
628pub struct SpannersRead {
629    /// What the step hands back, as music21's does: the spanners a
630    /// direction begins, or the one `xmlOneSpanner` found or made.
631    pub returned: Vec<SpannerId>,
632    /// Every spanner begun, in order.
633    pub started: Vec<SpannerId>,
634    /// Each pedal bounce or gap put in, with its uid and offset.
635    pub marks: Vec<(usize, FloatType, PedalObject)>,
636}
637
638/// Which of music21's spanner-reading steps to take.
639#[derive(Clone, Copy, Debug)]
640pub enum SpannerStep {
641    /// `xmlDirectionTypeToSpanners`: a wedge, bracket, dashes, octave
642    /// shift or pedal, its marks on `staff` at `offset`.
643    DirectionType {
644        /// The staff a pedal's marks go on.
645        staff: i32,
646        /// Where in the measure a pedal's marks stand.
647        offset: FloatType,
648    },
649    /// `xmlNotationsToSpanners`: the slurs, wavy lines, tremolos,
650    /// glissandos and arpeggios a `<notations>` joins its note to.
651    Notations,
652    /// `xmlOneSpanner`: the open spanner of a kind and number, or a new
653    /// one where there is none or duplicates are wanted.
654    One {
655        /// The kind of spanner.
656        kind: SpannerKind,
657        /// Whether an open one of the same number is joined or another
658        /// begun.
659        duplicates: DuplicateIds,
660    },
661}
662
663/// Whether a spanner of a number already open is joined or another begun:
664/// music21's `allowDuplicateIds`.
665#[derive(Clone, Copy, Debug, PartialEq, Eq)]
666pub enum DuplicateIds {
667    /// Join the open one.
668    Join,
669    /// Begin another.
670    Allow,
671}
672
673/// One of music21's spanner-reading steps on `element`, within `state`:
674/// `target`, a uid of the state's, is what ends or joins a spanner.
675pub(super) fn spanners_within(
676    element: &Xml,
677    target: Option<usize>,
678    step: SpannerStep,
679    state: &mut SpannerState,
680) -> Result<SpannersRead> {
681    let before = state.spanners.len();
682    let mut importer = Importer {
683        state: std::mem::take(state),
684        ..Importer::default()
685    };
686    let part = Xml::parse("<part id=\"P1\"/>")?;
687    let score_part = Xml::parse("<score-part id=\"P1\"/>")?;
688    let measure = Xml::parse("<measure/>")?;
689    let read = {
690        let mut part_parser = PartParser::new(&mut importer, &part, &score_part, "P1");
691        let mut parser = MeasureParser::new(&mut part_parser, &measure);
692        parser.last_note = target;
693        parser.pedal_starts = std::mem::take(&mut parser.part.importer.state.pedal_starts);
694        let returned = match step {
695            SpannerStep::DirectionType { staff, offset } => {
696                parser.direction_spanners(element, staff, offset)
697            }
698            SpannerStep::Notations => match target {
699                Some(uid) => parser.notation_spanners(element, uid).map(|()| Vec::new()),
700                None => Ok(Vec::new()),
701            },
702            SpannerStep::One { kind, duplicates } => Ok(vec![parser.one_spanner(
703                element,
704                target,
705                kind,
706                duplicates == DuplicateIds::Allow,
707            )]),
708        };
709        parser.part.importer.state.pedal_starts = std::mem::take(&mut parser.pedal_starts);
710        let marks = parser
711            .measure
712            .items
713            .iter()
714            .filter_map(|item| match (&item.element, item.uid) {
715                (StreamElement::PedalObject(mark), Some(uid)) => {
716                    Some((uid, item.offset, mark.clone()))
717                }
718                _ => None,
719            })
720            .collect();
721        let after = parser.part.importer.state.spanners.len();
722        returned.map(|returned| SpannersRead {
723            returned: returned.into_iter().map(SpannerId).collect(),
724            started: (before..after).map(SpannerId).collect(),
725            marks,
726        })
727    };
728    *state = importer.state;
729    read
730}
731
732#[derive(Default)]
733struct Importer {
734    state: SpannerState,
735    finale: bool,
736    /// The tuplets the first part starts inside, for a measure read on its
737    /// own after others: music21's `PartParser.activeTuplets`.
738    tuplets_before: Option<ActiveTuplets>,
739    /// The tuplets the last part read was left inside.
740    tuplets_after: ActiveTuplets,
741    /// What music21 warns of as it reads, in order.
742    warnings: Vec<Error>,
743}
744
745/// The tuplets a part is inside, by number: music21's `activeTuplets`,
746/// nought being the one a note's `<time-modification>` alone implies.
747pub type ActiveTuplets = [Option<Tuplet>; 7];
748
749struct PartGroup<'a> {
750    element: &'a Xml,
751    number: IntegerType,
752    part_ids: Vec<String>,
753}
754
755/// A part as it goes into the score, with the uid of each leaf in the order
756/// the score's leaves run.
757struct BuiltPart {
758    /// The id the part list knows it by, a staff of a part written on
759    /// several being `<part>-Staff<n>`.
760    key: String,
761    stream: Stream,
762    uids: Vec<Option<usize>>,
763}
764
765impl Importer {
766    fn uid(&mut self) -> usize {
767        self.state.new_uid()
768    }
769
770    /// music21's `xmlRootToScore`.
771    fn score(&mut self, root: &Xml) -> Result<Stream> {
772        let metadata = self.metadata(root);
773        let defaults = root.find("defaults").map(score_layout);
774        let credits = root
775            .find_all("credit")
776            .map(text_box)
777            .collect::<Result<Vec<_>>>()?;
778        let (score_parts, groups) = part_list(root);
779
780        let mut built: Vec<BuiltPart> = Vec::new();
781        let mut staff_groups: Vec<StaffGroup> = Vec::new();
782        for part in root.find_all("part") {
783            let id = match part.get("id") {
784                Some(id) => id.to_string(),
785                None => match score_parts.first() {
786                    Some((id, _)) => id.clone(),
787                    None => continue,
788                },
789            };
790            let Some((_, score_part)) = score_parts.iter().find(|(known, _)| *known == id) else {
791                continue;
792            };
793            let first = built.len();
794            let staves = PartParser::new(self, part, score_part, &id).parse()?;
795            let name = staves
796                .first()
797                .and_then(|staff| staff.stream.name().map(str::to_string));
798            let count = staves.len();
799            let split = staves
800                .first()
801                .is_some_and(|staff| staff.stream.kind() == StreamKind::PartStaff && count > 0)
802                && staves.iter().all(|staff| staff.key != id);
803            built.extend(staves);
804            if split {
805                let mut group = StaffGroup::new((first..first + count).collect());
806                group.set_name(name);
807                group.set_symbol(Some("brace"))?;
808                group.set_bar_together(Some(BarTogether::Yes));
809                group.set_name_hidden(true);
810                staff_groups.push(group);
811            }
812        }
813
814        // music21's `partGroups`.
815        for group in &groups {
816            let mut positions = Vec::new();
817            for part_id in &group.part_ids {
818                match built.iter().position(|part| part.key == *part_id) {
819                    Some(position) => positions.push(position),
820                    None => {
821                        let prefix = format!("{part_id}-Staff");
822                        let mut staves: Vec<(usize, &str)> = built
823                            .iter()
824                            .enumerate()
825                            .filter(|(_, part)| part.key.starts_with(&prefix))
826                            .map(|(position, part)| (position, part.key.as_str()))
827                            .collect();
828                        staves.sort_by(|left, right| left.1.cmp(right.1));
829                        if staves.is_empty() {
830                            return Err(import_error(format!(
831                                "Cannot find part in m21PartObjectsById dictionary by Id: {part_id}"
832                            )));
833                        }
834                        positions.extend(staves.into_iter().map(|(position, _)| position));
835                    }
836                }
837            }
838            let mut read = StaffGroup::new(positions);
839            let text = |tag: &str| {
840                group
841                    .element
842                    .find(tag)
843                    .and_then(Xml::text)
844                    .filter(|text| !text.is_empty())
845                    .map(str::to_string)
846            };
847            read.set_name(text("group-name"));
848            read.set_abbreviation(text("group-abbreviation"));
849            match group.element.find("group-symbol") {
850                Some(symbol_element) => {
851                    if let Some(symbol) = text("group-symbol") {
852                        read.set_symbol(Some(&symbol))?;
853                    }
854                    read_position(symbol_element, &mut read.style);
855                }
856                None => read.set_symbol(Some("brace"))?,
857            }
858            read.set_bar_together(Some(match text("group-barline").as_deref() {
859                Some("no") => BarTogether::No,
860                Some("Mensurstrich") => BarTogether::Mensurstrich,
861                _ => BarTogether::Yes,
862            }));
863            staff_groups.push(read);
864        }
865
866        // Whatever was completed and never put into a part goes into the
867        // score, an arpeggio across parts among them.
868        for building in &mut self.state.spanners {
869            if building.kind == SpannerKind::ArpeggioMark {
870                building.complete = true;
871            }
872        }
873        let late: Vec<usize> = (0..self.state.spanners.len())
874            .filter(|index| {
875                self.state.spanners[*index].complete && !self.state.spanners[*index].placed
876            })
877            .collect();
878        self.state.finished.extend(late);
879
880        // The credits sort before the parts, as music21 sorts its text boxes,
881        // and stand before the parts' leaves where spanners count them.
882        let mut uids: Vec<Option<usize>> = vec![None; credits.len()];
883        let mut events: Vec<StreamEvent> = credits
884            .into_iter()
885            .map(|credit| StreamEvent::new(0.0, StreamElement::TextBox(Box::new(credit))))
886            .collect();
887        for part in built {
888            uids.extend(part.uids);
889            events.push(StreamEvent::new(0.0, part.stream));
890        }
891        if let Some(defaults) = defaults {
892            // music21 inserts it first, and sorts it after the parts.
893            events.push(StreamEvent::new(
894                0.0,
895                StreamElement::Layout(Layout::Score(Box::new(defaults))),
896            ));
897        }
898        let mut assembled = Stream::from_events(events);
899        assembled.set_kind(StreamKind::Score);
900        assembled.set_metadata(Some(metadata));
901        if let Some(defaults) = root.find("defaults") {
902            let style = stream_style(defaults)?;
903            if style != crate::style::StreamStyle::default() {
904                assembled.set_stream_style(Some(style));
905            }
906        }
907        for group in staff_groups {
908            assembled.add_staff_group(group);
909        }
910        let position_of = |uid: usize| uids.iter().position(|held| *held == Some(uid));
911        for index in &self.state.finished {
912            assembled.add_spanner(self.state.spanners[*index].finish(&position_of));
913        }
914        Ok(assembled)
915    }
916
917    /// music21's `xmlMetadata`.
918    fn metadata(&mut self, root: &Xml) -> Metadata {
919        let mut metadata = Metadata::new();
920        let add = |metadata: &mut Metadata, element: &Xml, tag: &str, name: &str| {
921            if let Some(text) = element.find(tag).and_then(Xml::text)
922                && !text.is_empty()
923            {
924                metadata.add_text(name, text);
925            }
926        };
927        if let Some(work) = root.find("work") {
928            add(&mut metadata, work, "work-title", "title");
929            add(&mut metadata, work, "work-number", "number");
930            add(&mut metadata, work, "opus", "opusNumber");
931        }
932        add(&mut metadata, root, "movement-number", "movementNumber");
933        add(&mut metadata, root, "movement-title", "movementName");
934        // A title that only repeats the movement name was put there by a
935        // writer for the sake of renderers, and is taken out again.
936        let texts = |metadata: &Metadata, name: &str| -> Vec<String> {
937            metadata
938                .get(name)
939                .iter()
940                .map(|value| value.text().to_string())
941                .collect()
942        };
943        if texts(&metadata, "title") == texts(&metadata, "movementName") {
944            metadata.set("title", Vec::new());
945        }
946
947        let Some(identification) = root.find("identification") else {
948            return metadata;
949        };
950        for creator in identification.find_all("creator") {
951            // A role music21 has a name for is kept under it.
952            let name = match creator.get("type") {
953                Some(role) if crate::metadata::is_contributor_unique_name(role) => role,
954                _ => "otherContributor",
955            };
956            metadata.add(name, creator_value(creator));
957        }
958        if let Some(rights) = identification.find("rights") {
959            metadata.add("copyright", rights_value(rights));
960        }
961        if let Some(encoding) = identification.find("encoding") {
962            let read = encoding_of(encoding);
963            self.finale = read.finale;
964            for software in &read.software {
965                metadata.add_text("software", software);
966            }
967        }
968        if let Some(miscellaneous) = identification.find("miscellaneous") {
969            for field in miscellaneous.find_all("miscellaneous-field") {
970                let Some(name) = field.get("name") else {
971                    continue;
972                };
973                let value = field.text().unwrap_or("");
974                // A namespaced name is kept under the unique name it has.
975                let unique = crate::metadata::STANDARD_PROPERTIES
976                    .iter()
977                    .find(|(unique, namespaced, _)| *unique == name || *namespaced == name)
978                    .map_or(name, |(unique, _, _)| unique);
979                metadata.add_text(unique, value);
980            }
981        }
982        metadata
983    }
984}
985
986/// What an `<encoding>` says of the program that wrote the document.
987#[derive(Clone, Debug, Default, PartialEq, Eq)]
988pub struct Encoding {
989    /// Each `<software>` named, in order.
990    pub software: Vec<String>,
991    /// Whether the first program named is Finale, whose mistakes music21
992    /// works around: its `applyFinaleWorkarounds`.
993    pub finale: bool,
994    /// Whether the document says where every system starts: music21's
995    /// `definesExplicitSystemBreaks`.
996    pub system_breaks: bool,
997    /// Whether it says where every page starts: music21's
998    /// `definesExplicitPageBreaks`.
999    pub page_breaks: bool,
1000}
1001
1002/// music21's `processEncoding`.
1003pub(super) fn encoding_of(encoding: &Xml) -> Encoding {
1004    let mut read = Encoding::default();
1005    for software in encoding.find_all("software") {
1006        let text = software.stripped();
1007        if text.is_empty() {
1008            continue;
1009        }
1010        if read.software.is_empty() && text.contains("Finale") {
1011            read.finale = true;
1012        }
1013        read.software.push(text.to_string());
1014    }
1015    for supports in encoding.find_all("supports") {
1016        let value = supports.get("value").or_else(|| supports.get("type"));
1017        match (supports.get("attribute"), value) {
1018            (Some("new-system"), Some("yes")) => read.system_breaks = true,
1019            (Some("new-page"), Some("yes")) => read.page_breaks = true,
1020            _ => {}
1021        }
1022    }
1023    read
1024}
1025
1026/// music21's `parsePartList`: each `<score-part>` by id, and the groups.
1027fn part_list(root: &Xml) -> (Vec<(String, &Xml)>, Vec<PartGroup<'_>>) {
1028    let mut score_parts = Vec::new();
1029    let mut groups: Vec<PartGroup<'_>> = Vec::new();
1030    let mut open: Vec<usize> = Vec::new();
1031    let Some(list) = root.find("part-list") else {
1032        return (score_parts, groups);
1033    };
1034    for element in &list.children {
1035        match element.tag.as_str() {
1036            "score-part" => {
1037                let id = element.get("id").unwrap_or_default().to_string();
1038                for index in &open {
1039                    groups[*index].part_ids.push(id.clone());
1040                }
1041                score_parts.push((id, element));
1042            }
1043            "part-group" => {
1044                let number = element.get("number").and_then(parse_int).unwrap_or(1);
1045                match element.get("type") {
1046                    Some("start") => {
1047                        open.push(groups.len());
1048                        groups.push(PartGroup {
1049                            element,
1050                            number,
1051                            part_ids: Vec::new(),
1052                        });
1053                    }
1054                    Some("stop") => open.retain(|index| groups[*index].number != number),
1055                    _ => {}
1056                }
1057            }
1058            _ => {}
1059        }
1060    }
1061    (score_parts, groups)
1062}
1063
1064// --------------------------------------------------------------------- part
1065
1066/// music21's `PartParser`.
1067struct PartParser<'a, 'x> {
1068    importer: &'a mut Importer,
1069    part: &'x Xml,
1070    score_part: &'x Xml,
1071    id: String,
1072    name: Option<String>,
1073    abbreviation: Option<String>,
1074    name_hidden: bool,
1075    abbreviation_hidden: bool,
1076    /// The part's instruments with where each starts.
1077    instruments: Vec<(FloatType, Instrument)>,
1078    measures: Vec<MeasureIr>,
1079    brackets: Vec<Bracket>,
1080    multi_staff: bool,
1081    max_staves: i32,
1082    last_divisions: FloatType,
1083    last_meter: Option<TimeSignature>,
1084    last_measure_was_short: bool,
1085    last_measure_offset: FloatType,
1086    last_measure_number: IntegerType,
1087    last_number_suffix: Option<String>,
1088    last_clefs: Vec<(i32, Clef)>,
1089    active_tuplets: ActiveTuplets,
1090    first_measure_parsed: bool,
1091    /// music21's `PartParser.atSoundingPitch`: a part is at sounding pitch
1092    /// until a `<transpose>` says otherwise.
1093    at_sounding_pitch: bool,
1094    /// The arpeggios across chords, by their number and the offset in the
1095    /// part they stand at, each as where it stands among the spanners.
1096    arpeggios: Vec<((String, FloatType), usize)>,
1097    /// The rest of several measures still taking rests, by where it stands
1098    /// among the spanners, and how many more it takes: music21's
1099    /// `activeMultiMeasureRestSpanner` and `multiMeasureRestsToCapture`.
1100    multi_rest: Option<usize>,
1101    multi_rests_left: i64,
1102    /// The rests of several measures that have stopped taking rests, in
1103    /// the order they stopped.
1104    multi_rests: Vec<usize>,
1105}
1106
1107impl<'a, 'x> PartParser<'a, 'x> {
1108    fn new(importer: &'a mut Importer, part: &'x Xml, score_part: &'x Xml, id: &str) -> Self {
1109        let multi_staff = part.find_all("measure").any(|measure| {
1110            measure.find_all("attributes").any(|attributes| {
1111                attributes
1112                    .find_all("staves")
1113                    .any(|staves| parse_int(staves.stripped()).is_some_and(|count| count > 1))
1114            })
1115        });
1116        let active_tuplets = importer.tuplets_before.take().unwrap_or_default();
1117        Self {
1118            importer,
1119            part,
1120            score_part,
1121            id: id.to_string(),
1122            name: None,
1123            abbreviation: None,
1124            name_hidden: false,
1125            abbreviation_hidden: false,
1126            instruments: Vec::new(),
1127            measures: Vec::new(),
1128            brackets: Vec::new(),
1129            multi_staff,
1130            max_staves: 1,
1131            last_divisions: 10080.0,
1132            last_meter: None,
1133            last_measure_was_short: false,
1134            last_measure_offset: 0.0,
1135            last_measure_number: 0,
1136            last_number_suffix: None,
1137            last_clefs: Vec::new(),
1138            active_tuplets,
1139            first_measure_parsed: false,
1140            at_sounding_pitch: true,
1141            arpeggios: Vec::new(),
1142            multi_rest: None,
1143            multi_rests_left: 0,
1144            multi_rests: Vec::new(),
1145        }
1146    }
1147
1148    /// music21's `applyMultiMeasureRest`: a rest read joins the rest of
1149    /// several measures still taking rests, which goes into the part once
1150    /// it has taken as many as it said.
1151    fn take_multi_rest(&mut self, uid: usize) {
1152        let Some(index) = self.multi_rest else {
1153            return;
1154        };
1155        self.importer.state.spanners[index].add(uid);
1156        self.multi_rests_left -= 1;
1157        if self.multi_rests_left == 0 {
1158            self.end_multi_rest();
1159        }
1160    }
1161
1162    /// Puts the rest of several measures still taking rests into the part,
1163    /// whether or not it took all it said it would.
1164    ///
1165    /// One cut short by the part's end or by the next stands in the part as
1166    /// music21's does, counting the rests it took; one that took none is
1167    /// left out.
1168    fn end_multi_rest(&mut self) {
1169        let Some(index) = self.multi_rest.take() else {
1170            return;
1171        };
1172        let building = &mut self.importer.state.spanners[index];
1173        if building.uids.is_empty() {
1174            return;
1175        }
1176        building.complete = true;
1177        building.placed = true;
1178        self.multi_rests.push(index);
1179    }
1180
1181    /// music21's `PartParser.parse`: the part, or one part for each of its
1182    /// staves.
1183    fn parse(mut self) -> Result<Vec<BuiltPart>> {
1184        self.score_part_info()?;
1185        let part = self.part;
1186        let mut last_forward: Option<(usize, bool)> = None;
1187        for measure in part.find_all("measure") {
1188            // What goes wrong inside a measure says which one, by the number
1189            // the document gives it, and in which part.
1190            last_forward = self.measure(measure).map_err(|error| {
1191                error.placed(|| {
1192                    Position::measure(measure.get("number").unwrap_or("")).in_part(&self.id)
1193                })
1194            })?;
1195        }
1196        self.remove_finale_ending_rest(last_forward);
1197        self.end_multi_rest();
1198        self.importer.tuplets_after = self.active_tuplets;
1199
1200        // Endings, from the brackets over the measures.
1201        for bracket in &self.brackets {
1202            for (place, index) in bracket.measures.iter().enumerate() {
1203                let measure = &mut self.measures[*index];
1204                if measure.ending.is_none() {
1205                    measure.ending = Some(Ending::new(
1206                        bracket.numbers.clone(),
1207                        place == 0,
1208                        place + 1 == bracket.measures.len(),
1209                    ));
1210                }
1211            }
1212        }
1213
1214        // Spanners completed by now belong to this part, octave lines last
1215        // and rests of several measures first, music21 having put each of
1216        // those in as it was completed.
1217        let mut ours: Vec<usize> = std::mem::take(&mut self.multi_rests);
1218        for pass in [false, true] {
1219            for (index, building) in self.importer.state.spanners.iter_mut().enumerate() {
1220                let ottava = building.kind == SpannerKind::Ottava;
1221                if building.complete && !building.placed && ottava == pass {
1222                    building.placed = true;
1223                    ours.push(index);
1224                }
1225            }
1226        }
1227        self.importer.state.finished.extend(ours);
1228
1229        if self.max_staves > 1 {
1230            self.separate_staves()
1231        } else {
1232            let kind = if self.multi_staff {
1233                StreamKind::PartStaff
1234            } else {
1235                StreamKind::Part
1236            };
1237            let measures = std::mem::take(&mut self.measures);
1238            let built = self.build(kind, None, measures, &self.instruments.clone());
1239            Ok(vec![BuiltPart {
1240                key: self.id.clone(),
1241                stream: built.0,
1242                uids: built.1,
1243            }])
1244        }
1245    }
1246
1247    /// Puts a part together out of its measures.
1248    fn build(
1249        &self,
1250        kind: StreamKind,
1251        id: Option<String>,
1252        measures: Vec<MeasureIr>,
1253        instruments: &[(FloatType, Instrument)],
1254    ) -> (Stream, Vec<Option<usize>>) {
1255        let mut items: Vec<(Item, Vec<Option<usize>>)> = Vec::new();
1256        let mut seq = 0;
1257        for (offset, instrument) in instruments {
1258            items.push((
1259                Item {
1260                    offset: *offset,
1261                    seq,
1262                    staff: NO_STAFF,
1263                    uid: None,
1264                    element: instrument.clone().into(),
1265                },
1266                vec![None],
1267            ));
1268            seq += 1;
1269        }
1270        for measure in measures {
1271            let offset = measure.offset;
1272            let (stream, uids) = build_measure(measure);
1273            items.push((
1274                Item {
1275                    offset,
1276                    seq,
1277                    staff: NO_STAFF,
1278                    uid: None,
1279                    element: stream.into(),
1280                },
1281                uids,
1282            ));
1283            seq += 1;
1284        }
1285        items.sort_by(|(left, _), (right, _)| {
1286            left.offset
1287                .total_cmp(&right.offset)
1288                .then(left.order().cmp(&right.order()))
1289                .then(left.seq.cmp(&right.seq))
1290        });
1291        let mut uids = Vec::new();
1292        let mut events = Vec::new();
1293        for (item, leaf_uids) in items {
1294            uids.extend(leaf_uids);
1295            events.push(StreamEvent::new(item.offset, item.element));
1296        }
1297        let mut stream = Stream::from_events(events);
1298        stream.set_kind(kind);
1299        stream.set_id(id.or_else(|| {
1300            self.instruments
1301                .first()
1302                .and_then(|(_, instrument)| instrument.best_name().map(str::to_string))
1303        }));
1304        stream.set_name(self.name.clone());
1305        stream.set_abbreviation(self.abbreviation.clone());
1306        // A staff split off a part is music21's `template` of it, which
1307        // copies this.
1308        stream.set_at_sounding_pitch(Some(self.at_sounding_pitch));
1309        // A staff split off a part is a fresh stream, which prints both.
1310        if kind != StreamKind::PartStaff || self.max_staves <= 1 {
1311            stream.set_name_hidden(self.name_hidden);
1312            stream.set_abbreviation_hidden(self.abbreviation_hidden);
1313        }
1314        (stream, uids)
1315    }
1316
1317    /// music21's `parseXmlScorePart` and `getDefaultInstrument`.
1318    fn score_part_info(&mut self) -> Result<()> {
1319        let score_part = self.score_part;
1320        let named = |tag: &str| {
1321            score_part
1322                .find(tag)
1323                .and_then(Xml::text)
1324                .filter(|text| !text.is_empty())
1325                .map(cleaned)
1326        };
1327        let part_name = named("part-name");
1328        let part_abbreviation = named("part-abbreviation");
1329        let name_hidden = score_part
1330            .find("part-name")
1331            .is_some_and(|name| name.get("print-object") == Some("no"));
1332        let abbreviation_hidden = score_part
1333            .find("part-abbreviation")
1334            .is_some_and(|name| name.get("print-object") == Some("no"));
1335
1336        let mut instrument = default_instrument(score_part, &mut self.importer.warnings);
1337        instrument.set_part_id(Some(self.id.clone()));
1338        instrument.set_part_name(part_name.clone());
1339        instrument.set_part_abbreviation(part_abbreviation.clone());
1340        self.name = part_name;
1341        self.abbreviation = part_abbreviation;
1342        self.name_hidden = name_hidden;
1343        self.abbreviation_hidden = abbreviation_hidden;
1344        self.instruments.push((0.0, instrument));
1345        Ok(())
1346    }
1347
1348    /// music21's `xmlMeasureToMeasure`. Hands back where a rest a `<forward>`
1349    /// of Finale's made stands, when it is the last thing read.
1350    fn measure(&mut self, element: &'x Xml) -> Result<Option<(usize, bool)>> {
1351        let mut parser = MeasureParser::new(self, element);
1352        parser.parse()?;
1353        let MeasureParser {
1354            mut measure,
1355            staves,
1356            transposition,
1357            full_measure_rest,
1358            marked_full,
1359            finale_forward,
1360            use_voices,
1361            divisions,
1362            ..
1363        } = parser;
1364        self.last_divisions = divisions;
1365        self.max_staves = self.max_staves.max(staves);
1366        if let Some(transposition) = transposition {
1367            self.update_transposition(transposition);
1368        }
1369        self.first_measure_parsed = true;
1370
1371        // music21's `setLastMeasureInfo`.
1372        if measure.number != self.last_measure_number {
1373            self.last_measure_number = measure.number;
1374            self.last_number_suffix = measure.suffix.clone();
1375        }
1376        let own_meter = measure.items.iter().find_map(|item| match &item.element {
1377            StreamElement::TimeSignature(meter) => Some(meter.clone()),
1378            _ => None,
1379        });
1380        if let Some(meter) = own_meter {
1381            self.last_meter = Some(meter);
1382        } else if self.last_meter.is_none() {
1383            self.last_meter = Some(TimeSignature::new(4, 4)?);
1384        }
1385        let bar_length = self
1386            .last_meter
1387            .as_ref()
1388            .map_or(4.0, TimeSignature::bar_quarter_length);
1389
1390        if full_measure_rest {
1391            // The first rest as music21 walks the measure: what stands in
1392            // the measure itself in order, each voice read through where it
1393            // stands, which is at the start and after the signatures.
1394            let mut walk: Vec<(FloatType, i32, bool, usize, Option<usize>)> = Vec::new();
1395            for (index, voice) in measure.voices.iter().enumerate() {
1396                let first = sorted(voice.items.clone())
1397                    .into_iter()
1398                    .find(|item| matches!(item.element, StreamElement::Rest(_)))
1399                    .and_then(|item| item.uid);
1400                walk.push((0.0, 5, false, index, first));
1401            }
1402            for item in &measure.items {
1403                let rest = matches!(item.element, StreamElement::Rest(_));
1404                walk.push((
1405                    item.offset,
1406                    item.order(),
1407                    !item.is_grace(),
1408                    item.seq + measure.voices.len(),
1409                    item.uid.filter(|_| rest),
1410                ));
1411            }
1412            walk.sort_by(|left, right| {
1413                left.0
1414                    .total_cmp(&right.0)
1415                    .then(left.1.cmp(&right.1))
1416                    .then(left.2.cmp(&right.2))
1417                    .then(left.3.cmp(&right.3))
1418            });
1419            let first_uid = walk.into_iter().find_map(|entry| entry.4);
1420            let first = measure
1421                .items
1422                .iter_mut()
1423                .chain(measure.voices.iter_mut().flat_map(|voice| &mut voice.items))
1424                .filter(|item| first_uid.is_some() && item.uid == first_uid)
1425                .find_map(|item| match &mut item.element {
1426                    StreamElement::Rest(rest) => Some((item.uid, rest)),
1427                    _ => None,
1428                });
1429            if let Some((uid, rest)) = first {
1430                let marked_full = uid.is_some_and(|uid| marked_full.contains(&uid));
1431                let duration = rest.duration().clone();
1432                let whole = matches!(
1433                    duration.type_and_dots(),
1434                    Some((DurationType::Whole | DurationType::Breve, 0))
1435                ) && duration.tuplets().is_empty();
1436                if marked_full || (duration.quarter_length() != bar_length && whole) {
1437                    rest.set_duration(Duration::new(bar_length)?);
1438                    rest.set_full_measure(crate::rest::FullMeasure::Yes);
1439                }
1440            }
1441        }
1442
1443        // music21 sums the lengths as floats and snaps where it inserts.
1444        measure.offset = op_frac(self.last_measure_offset);
1445        let index = self.measures.len();
1446
1447        // music21's `adjustTimeAttributesFromMeasure`.
1448        let has_notes = measure
1449            .items
1450            .iter()
1451            .chain(measure.voices.iter().flat_map(|voice| &voice.items))
1452            .any(Item::is_note_or_rest);
1453        let fit = measure_fit(&FitAsked {
1454            highest: measure.highest_time(),
1455            bar_length,
1456            has_notes,
1457            at_start: self.last_measure_offset == 0.0,
1458            last_was_short: self.last_measure_was_short,
1459        });
1460        if fit.fill_with_rest {
1461            // Some writers leave the rest out of an empty measure.
1462            let uid = self.importer.uid();
1463            measure.items.push(Item {
1464                offset: 0.0,
1465                seq: usize::MAX,
1466                staff: NO_STAFF,
1467                uid: Some(uid),
1468                element: Rest::new(Duration::new(bar_length)?).into(),
1469            });
1470        }
1471        if let Some(padding) = fit.padding_left {
1472            measure.padding_left = padding;
1473        }
1474        if let Some(padding) = fit.padding_right {
1475            measure.padding_right = padding;
1476        }
1477        self.last_measure_was_short = fit.last_was_short;
1478        let shift = fit.shift;
1479        self.last_measure_offset += shift;
1480        self.measures.push(measure);
1481        Ok(finale_forward.map(|_| (index, !use_voices)))
1482    }
1483
1484    /// music21's `removeFinaleIncorrectEndingForwardRest`: a hidden rest
1485    /// Finale's `<forward>` left as the last thing in the last measure.
1486    fn remove_finale_ending_rest(&mut self, last_forward: Option<(usize, bool)>) {
1487        let Some((index, true)) = last_forward else {
1488            return;
1489        };
1490        let Some(measure) = self.measures.get_mut(index) else {
1491            return;
1492        };
1493        let last = sorted(measure.items.clone()).into_iter().rfind(|item| {
1494            item.is_note_or_rest() || matches!(item.element, StreamElement::ChordSymbol(_))
1495        });
1496        if let Some(last) = last
1497            && matches!(&last.element, StreamElement::Rest(rest) if rest.hidden())
1498        {
1499            measure.items.retain(|item| item.seq != last.seq);
1500        }
1501    }
1502
1503    /// music21's `updateTransposition`.
1504    fn update_transposition(&mut self, transposition: Interval) {
1505        let active = self.instruments.last().cloned();
1506        match active {
1507            Some((_, instrument))
1508                if instrument.transposition().is_none() && !self.first_measure_parsed => {}
1509            Some((_, instrument)) => {
1510                let differs = instrument
1511                    .transposition()
1512                    .is_none_or(|held| held.directed_name() != transposition.directed_name());
1513                if differs {
1514                    self.instruments
1515                        .push((self.last_measure_offset, instrument.clone()));
1516                }
1517            }
1518            None => self
1519                .instruments
1520                .push((self.last_measure_offset, Instrument::new())),
1521        }
1522        if let Some((_, instrument)) = self.instruments.last_mut() {
1523            instrument.set_transposition(Some(transposition));
1524        }
1525        self.at_sounding_pitch = false;
1526    }
1527
1528    /// music21's `separateOutPartStaves`: a part written on several staves
1529    /// becomes one part for each, what is written on no staff in particular
1530    /// going into every one.
1531    fn separate_staves(&mut self) -> Result<Vec<BuiltPart>> {
1532        let mut keys: Vec<i32> = Vec::new();
1533        for measure in &self.measures {
1534            for item in measure
1535                .items
1536                .iter()
1537                .chain(measure.voices.iter().flat_map(|voice| &voice.items))
1538            {
1539                if item.staff != NO_STAFF && !keys.contains(&item.staff) {
1540                    keys.push(item.staff);
1541                }
1542            }
1543        }
1544        keys.sort_unstable();
1545
1546        let source = std::mem::take(&mut self.measures);
1547        let mut taken: Vec<usize> = Vec::new();
1548        let mut out = Vec::new();
1549        for key in keys {
1550            let mut measures = Vec::new();
1551            for measure in &source {
1552                let mut copy = MeasureIr {
1553                    offset: measure.offset,
1554                    number: measure.number,
1555                    suffix: measure.suffix.clone(),
1556                    // A measure made for a staff shows its number, whatever
1557                    // the one it was made from did.
1558                    hidden: false,
1559                    left: measure.left.clone(),
1560                    right: measure.right.clone(),
1561                    ending: measure.ending.clone(),
1562                    padding_left: measure.padding_left,
1563                    padding_right: measure.padding_right,
1564                    width: measure.width.clone(),
1565                    // music21 makes the staff's measures from a template,
1566                    // which keeps nothing of how the measure is drawn.
1567                    measure_numbering: None,
1568                    items: Vec::new(),
1569                    voices: Vec::new(),
1570                };
1571                let mut seq = 0usize;
1572                let mut take = |items: &[Item], into: &mut Vec<Item>, seq: &mut usize| {
1573                    for item in sorted(items.to_vec()) {
1574                        if item.staff != NO_STAFF && item.staff != key {
1575                            continue;
1576                        }
1577                        let mut item = item;
1578                        // The element itself goes to the first staff that
1579                        // takes it, and a copy to every one after.
1580                        if taken.contains(&item.seq_key()) {
1581                            item.uid = None;
1582                        } else {
1583                            taken.push(item.seq_key());
1584                        }
1585                        item.seq = *seq;
1586                        *seq += 1;
1587                        into.push(item);
1588                    }
1589                };
1590                take(&measure.items, &mut copy.items, &mut seq);
1591                for voice in &measure.voices {
1592                    let mut items = Vec::new();
1593                    take(&voice.items, &mut items, &mut seq);
1594                    copy.voices.push(VoiceIr {
1595                        id: voice.id.clone(),
1596                        items,
1597                    });
1598                }
1599                // music21's `flattenUnnecessaryVoices`.
1600                copy.voices.retain(|voice| !voice.items.is_empty());
1601                if copy.voices.len() == 1 {
1602                    let voice = copy.voices.remove(0);
1603                    for mut item in sorted(voice.items) {
1604                        item.seq = seq;
1605                        seq += 1;
1606                        copy.items.push(item);
1607                    }
1608                }
1609                measures.push(copy);
1610            }
1611            let id = format!("{}-Staff{key}", self.id);
1612            let instruments = self.instruments.clone();
1613            let (stream, uids) = self.build(
1614                StreamKind::PartStaff,
1615                Some(id.clone()),
1616                measures,
1617                &instruments,
1618            );
1619            out.push(BuiltPart {
1620                key: id,
1621                stream,
1622                uids,
1623            });
1624        }
1625        Ok(out)
1626    }
1627}
1628
1629impl Item {
1630    /// A number no two elements read share, whatever measure or voice they
1631    /// stand in: the uid where there is one.
1632    fn seq_key(&self) -> usize {
1633        self.uid.unwrap_or(usize::MAX)
1634    }
1635}
1636
1637/// A measure put together: the stream, and the uid of each leaf in order.
1638fn build_measure(measure: MeasureIr) -> (Stream, Vec<Option<usize>>) {
1639    let mut entries: Vec<(Item, Vec<Option<usize>>)> = Vec::new();
1640    for (index, voice) in measure.voices.into_iter().enumerate() {
1641        let mut uids = Vec::new();
1642        let mut events = Vec::new();
1643        for item in sorted(voice.items) {
1644            uids.push(item.uid);
1645            events.push(StreamEvent::new(item.offset, item.element));
1646        }
1647        let mut stream = Stream::from_events(events);
1648        stream.set_kind(StreamKind::Voice);
1649        stream.set_id(Some(voice.id));
1650        entries.push((
1651            Item {
1652                offset: 0.0,
1653                // Voices are made before anything is read into the measure.
1654                seq: index,
1655                staff: NO_STAFF,
1656                uid: None,
1657                element: stream.into(),
1658            },
1659            uids,
1660        ));
1661    }
1662    let voices = entries.len();
1663    for mut item in measure.items {
1664        item.seq = item.seq.saturating_add(voices);
1665        let uid = item.uid;
1666        entries.push((item, vec![uid]));
1667    }
1668    entries.sort_by(|(left, _), (right, _)| {
1669        left.offset
1670            .total_cmp(&right.offset)
1671            .then(left.order().cmp(&right.order()))
1672            .then(right.is_grace().cmp(&left.is_grace()))
1673            .then(left.seq.cmp(&right.seq))
1674    });
1675    let mut uids = Vec::new();
1676    let mut events = Vec::new();
1677    for (item, leaf_uids) in entries {
1678        uids.extend(leaf_uids);
1679        events.push(StreamEvent::new(item.offset, item.element));
1680    }
1681    let mut stream = Stream::from_events(events);
1682    stream.set_kind(StreamKind::Measure);
1683    stream.set_number(measure.number);
1684    stream.set_number_suffix(measure.suffix);
1685    stream.set_number_hidden(measure.hidden);
1686    stream.set_left_barline(measure.left);
1687    stream.set_right_barline(measure.right);
1688    stream.set_ending(measure.ending);
1689    stream.set_padding_left(measure.padding_left);
1690    stream.set_padding_right(measure.padding_right);
1691    stream.set_layout_width(measure.width);
1692    stream.set_measure_numbering(measure.measure_numbering);
1693    (stream, uids)
1694}
1695
1696// ------------------------------------------------------------------ measure
1697
1698/// music21's `MeasureParser`.
1699struct MeasureParser<'p, 'a, 'x> {
1700    part: &'p mut PartParser<'a, 'x>,
1701    element: &'x Xml,
1702    measure: MeasureIr,
1703    seq: usize,
1704    divisions: FloatType,
1705    staves: i32,
1706    transposition: Option<Interval>,
1707    use_voices: bool,
1708    last_voice: Option<String>,
1709    offset: FloatType,
1710    /// Notes of a chord being gathered, with the lyrics written on them.
1711    chord_notes: Vec<&'x Xml>,
1712    chord_lyrics: Vec<&'x Xml>,
1713    /// The uid of the last note, chord or rest read.
1714    last_note: Option<usize>,
1715    rests: usize,
1716    notes: usize,
1717    full_measure_rest: bool,
1718    /// The rests that said they fill their measure.
1719    marked_full: Vec<usize>,
1720    /// Whether the rest being read said so.
1721    marking_full: bool,
1722    /// The seq of the last thing read, when it was a rest made of Finale's
1723    /// `<forward>`.
1724    finale_forward: Option<usize>,
1725    pedal_starts: Vec<(usize, FloatType)>,
1726    /// The staff layouts read here, by staff number and offset, each with
1727    /// what it was put in as, where it was put anywhere: music21's
1728    /// `staffLayoutObjects`.
1729    staff_layouts: Vec<((i64, FloatType), Option<usize>)>,
1730}
1731
1732impl<'p, 'a, 'x> MeasureParser<'p, 'a, 'x> {
1733    fn new(part: &'p mut PartParser<'a, 'x>, element: &'x Xml) -> Self {
1734        let divisions = part.last_divisions;
1735        Self {
1736            part,
1737            element,
1738            measure: MeasureIr::default(),
1739            seq: 0,
1740            divisions,
1741            staves: 1,
1742            transposition: None,
1743            use_voices: false,
1744            last_voice: None,
1745            offset: 0.0,
1746            chord_notes: Vec::new(),
1747            chord_lyrics: Vec::new(),
1748            last_note: None,
1749            rests: 0,
1750            notes: 0,
1751            full_measure_rest: false,
1752            marked_full: Vec::new(),
1753            marking_full: false,
1754            finale_forward: None,
1755            pedal_starts: Vec::new(),
1756            staff_layouts: Vec::new(),
1757        }
1758    }
1759
1760    fn parse(&mut self) -> Result<()> {
1761        self.measure_attributes();
1762        self.voice_information();
1763        let element = self.element;
1764        for (index, child) in element.children.iter().enumerate() {
1765            match child.tag.as_str() {
1766                "note" => self.note(child, element.children.get(index + 1))?,
1767                "backup" => {
1768                    if let Some(ticks) = parse_float(child.child_text("duration")) {
1769                        self.offset = op_frac(self.offset - ticks / self.divisions).max(0.0);
1770                    }
1771                }
1772                "forward" => self.forward(child)?,
1773                "direction" => self.direction(child)?,
1774                "attributes" => self.attributes(child)?,
1775                "harmony" => self.harmony(child)?,
1776                "sound" => {
1777                    if child.get("tempo").is_some() {
1778                        let total = self.offset + self.offset_of(child);
1779                        self.sound_tempo(child, None, staff_number(child), total);
1780                    }
1781                }
1782                "barline" => self.barline(child)?,
1783                "print" => self.print(child),
1784                _ => {}
1785            }
1786        }
1787        if self.rests == 1 && self.notes == 0 {
1788            self.full_measure_rest = true;
1789        }
1790        Ok(())
1791    }
1792
1793    /// Puts an element into the measure itself.
1794    fn insert(
1795        &mut self,
1796        offset: FloatType,
1797        staff: i32,
1798        element: impl Into<StreamElement>,
1799    ) -> usize {
1800        let uid = self.part.importer.uid();
1801        self.measure.items.push(Item {
1802            offset: op_frac(offset),
1803            seq: self.seq,
1804            staff,
1805            uid: Some(uid),
1806            element: element.into(),
1807        });
1808        self.seq += 1;
1809        uid
1810    }
1811
1812    /// music21's `insertInMeasureOrVoice`, for a note, chord or rest.
1813    fn insert_note(&mut self, source: &Xml, staff: i32, element: StreamElement) -> usize {
1814        let uid = self.part.importer.uid();
1815        let item = Item {
1816            offset: self.offset,
1817            seq: self.seq,
1818            staff,
1819            uid: Some(uid),
1820            element,
1821        };
1822        self.seq += 1;
1823        if self.use_voices {
1824            let written = source.child_text("voice");
1825            let voice = if written.is_empty() {
1826                self.last_voice.clone().unwrap_or_else(|| "1".to_string())
1827            } else {
1828                self.last_voice = Some(written.to_string());
1829                written.to_string()
1830            };
1831            if let Some(found) = self.measure.voices.iter_mut().find(|held| held.id == voice) {
1832                found.items.push(item);
1833                return uid;
1834            }
1835        }
1836        self.measure.items.push(item);
1837        uid
1838    }
1839
1840    /// music21's `parseMeasureAttributes` and `parseMeasureNumbers`.
1841    fn measure_attributes(&mut self) {
1842        self.measure.hidden = yes(self.element.get("implicit"));
1843        self.measure.width = self.element.get("width").map(StyleValue::read);
1844        let raw = self.element.get("number").unwrap_or("");
1845        // music21's `getNumFromStr`: the digits, and whatever is left.
1846        let digits: String = raw.chars().filter(char::is_ascii_digit).collect();
1847        let rest: String = raw.chars().filter(|c| !c.is_ascii_digit()).collect();
1848        if let Ok(number) = digits.parse::<IntegerType>() {
1849            self.measure.number = number;
1850        }
1851        if !rest.is_empty() {
1852            self.measure.suffix = Some(rest);
1853        }
1854        let last = self.part.last_measure_number;
1855        if self.measure.suffix.as_deref() == Some("X")
1856            && Some(self.measure.number) != last.checked_add(1)
1857        {
1858            let mut suffix = format!("X{}", self.measure.number);
1859            if let Some(before) = &self.part.last_number_suffix {
1860                suffix = format!("{before}{suffix}");
1861            }
1862            self.measure.number = last;
1863            self.measure.suffix = Some(suffix);
1864        }
1865    }
1866
1867    /// music21's `updateVoiceInformation`: a measure naming more than one
1868    /// voice holds a voice for each.
1869    fn voice_information(&mut self) {
1870        let ids = voice_ids(self.element);
1871        if ids.len() > 1 {
1872            self.measure.voices = ids
1873                .into_iter()
1874                .map(|id| VoiceIr {
1875                    id,
1876                    items: Vec::new(),
1877                })
1878                .collect();
1879            self.use_voices = true;
1880        }
1881    }
1882
1883    /// music21's `xmlToOffset`.
1884    fn offset_of(&self, element: &Xml) -> FloatType {
1885        parse_float(element.child_text("offset")).map_or(0.0, |ticks| ticks / self.divisions)
1886    }
1887
1888    /// music21's `xmlForward`.
1889    fn forward(&mut self, element: &'x Xml) -> Result<()> {
1890        let Some(ticks) = parse_float(element.child_text("duration")) else {
1891            return Ok(());
1892        };
1893        let change = op_frac(ticks / self.divisions);
1894        if self.part.importer.finale && change != 0.0 {
1895            // Finale writes a hidden rest as a `<forward>`.
1896            let mut rest = Rest::new(Duration::new(change)?);
1897            rest.set_hidden(true);
1898            let seq = self.seq;
1899            self.insert_note(element, staff_number(element), rest.into());
1900            self.finale_forward = Some(seq);
1901        }
1902        self.offset = op_frac(self.offset + change);
1903        Ok(())
1904    }
1905
1906    /// music21's `parseAttributesTag`.
1907    fn attributes(&mut self, attributes: &'x Xml) -> Result<()> {
1908        for child in &attributes.children {
1909            match child.tag.as_str() {
1910                "time" => {
1911                    if let Some(meter) = time_signature(child)? {
1912                        self.insert(self.offset, staff_number(child), meter);
1913                    }
1914                }
1915                "clef" => {
1916                    let clef = clef_of(child)?;
1917                    let staff = staff_number(child);
1918                    self.insert(self.offset, staff, clef.clone());
1919                    self.part.last_clefs.retain(|(held, _)| *held != staff);
1920                    self.part.last_clefs.push((staff, clef));
1921                }
1922                "key" => {
1923                    let key = key_signature(child)?;
1924                    self.insert(self.offset, staff_number(child), key);
1925                }
1926                "divisions" => {
1927                    if let Some(divisions) = parse_float(child.stripped()) {
1928                        self.divisions = op_frac(divisions);
1929                    }
1930                }
1931                "staves" => {
1932                    if let Some(staves) = parse_int(child.stripped()) {
1933                        self.staves = staves;
1934                    }
1935                }
1936                "transpose" => self.transposition = Some(transpose_interval(child)?),
1937                "staff-details" => self.staff_details(child),
1938                "measure-style" => self.measure_style(child)?,
1939                _ => {}
1940            }
1941        }
1942        Ok(())
1943    }
1944
1945    /// music21's `handleMeasureStyle`: a rest of several measures, which
1946    /// takes the next so many rests the part reads. Its font is the page's.
1947    fn measure_style(&mut self, style: &'x Xml) -> Result<()> {
1948        let Some(multiple) = style.find("multiple-rest") else {
1949            return Ok(());
1950        };
1951        let count = parse_int(multiple.stripped()).ok_or_else(|| {
1952            import_error(format!(
1953                "invalid literal for int() with base 10: '{}'",
1954                multiple.stripped()
1955            ))
1956        })?;
1957        self.part.end_multi_rest();
1958        let mut building = Building::new(SpannerKind::MultiMeasureRest, None);
1959        building.use_symbols = multiple.get("use-symbols") == Some("yes");
1960        self.part.importer.state.spanners.push(building);
1961        self.part.multi_rest = Some(self.part.importer.state.spanners.len() - 1);
1962        self.part.multi_rests_left = i64::from(count);
1963        Ok(())
1964    }
1965
1966    /// music21's `xmlPrint`: a page layout where the print starts a page or
1967    /// says how one is laid out, a system layout where it starts a system,
1968    /// says how one is laid out, or does not concern a page, and a staff
1969    /// layout for each numbered staff it lays out.
1970    fn print(&mut self, print: &'x Xml) {
1971        let says = |name: &str| print.get(name).is_some_and(|value| value != "no");
1972        let page = says("new-page")
1973            || print.get("page-number").is_some()
1974            || print.find("page-layout").is_some();
1975        let system = says("new-system") || print.find("system-layout").is_some();
1976        if page {
1977            let read = print_page_layout(print);
1978            self.insert(0.0, NO_STAFF, StreamElement::Layout(Layout::Page(read)));
1979        }
1980        if system || !page {
1981            let read = print_system_layout(print);
1982            self.insert(0.0, NO_STAFF, StreamElement::Layout(Layout::System(read)));
1983        }
1984        for written in print.find_all("staff-layout") {
1985            let read = staff_layout(written);
1986            let key = (read.staff_number.unwrap_or(1), self.offset);
1987            // music21 keeps it to be added to before knowing whether it is
1988            // put anywhere: one with no number is not, and details for its
1989            // staff added to it are lost with it.
1990            let Some(number) = read.staff_number else {
1991                self.staff_layouts.push((key, None));
1992                continue;
1993            };
1994            let uid = self.insert(
1995                0.0,
1996                i32::try_from(number).unwrap_or(NO_STAFF),
1997                StreamElement::Layout(Layout::Staff(read)),
1998            );
1999            self.staff_layouts.push((key, Some(uid)));
2000        }
2001        if let Some(numbering) = print.find("measure-numbering") {
2002            self.measure.measure_numbering = numbering.text().map(str::to_string);
2003        }
2004    }
2005
2006    /// music21's `handleStaffDetails`: the details of a staff read into the
2007    /// staff layout already standing for it here, or into a new one.
2008    fn staff_details(&mut self, details: &'x Xml) {
2009        let number = details
2010            .get("number")
2011            .and_then(|value| value.trim().parse::<i64>().ok());
2012        let key = (number.unwrap_or(1), self.offset);
2013        let existing = self
2014            .staff_layouts
2015            .iter()
2016            .rev()
2017            .find(|(known, _)| known.0 == key.0 && known.1 == key.1)
2018            .map(|(_, uid)| *uid);
2019        match existing {
2020            Some(Some(uid)) => {
2021                if let Some(item) = self
2022                    .measure
2023                    .items
2024                    .iter_mut()
2025                    .find(|item| item.uid == Some(uid))
2026                    && let StreamElement::Layout(Layout::Staff(layout)) = &mut item.element
2027                {
2028                    read_staff_details(details, layout);
2029                }
2030            }
2031            // Added to one never put anywhere.
2032            Some(None) => {}
2033            None => {
2034                let mut read = StaffLayout::default();
2035                read_staff_details(details, &mut read);
2036                let uid = self.insert(
2037                    self.offset,
2038                    staff_number(details),
2039                    StreamElement::Layout(Layout::Staff(read)),
2040                );
2041                self.staff_layouts.push((key, Some(uid)));
2042            }
2043        }
2044    }
2045
2046    // ----------------------------------------------------------- notes
2047
2048    /// music21's `xmlToNote`.
2049    fn note(&mut self, element: &'x Xml, next: Option<&'x Xml>) -> Result<()> {
2050        let next_is_chord =
2051            next.is_some_and(|next| next.tag == "note" && next.find("chord").is_some());
2052        let is_rest = element.find("rest").is_some();
2053        let mut is_chord = element.find("chord").is_some();
2054        if next_is_chord {
2055            is_chord = true;
2056            let voice = element.child_text("voice");
2057            if element.find("voice").is_some() && !voice.is_empty() {
2058                self.last_voice = Some(voice.to_string());
2059            }
2060        }
2061
2062        let mut increment = 0.0;
2063        if is_chord {
2064            self.chord_notes.push(element);
2065            self.chord_lyrics.extend(element.find_all("lyric"));
2066        } else {
2067            let staff = staff_number(element);
2068            let (mut read, uid) = if is_rest {
2069                self.rests += 1;
2070                let rest = self.rest(element)?;
2071                (ReadNote::Rest(rest), None)
2072            } else {
2073                self.notes += 1;
2074                let (read, uid) = self.simple_note(element, true)?;
2075                (read, Some(uid))
2076            };
2077            let lyrics = lyrics_from(element.find_all("lyric"))?;
2078            let element_value: StreamElement = match &mut read {
2079                ReadNote::Rest(rest) => {
2080                    *rest.lyrics_mut() = lyrics;
2081                    rest.clone().into()
2082                }
2083                ReadNote::Note(note) => {
2084                    *note.lyrics_mut() = lyrics;
2085                    note.clone().into()
2086                }
2087                ReadNote::Unpitched(stroke) => {
2088                    *stroke.written_mut().lyrics_mut() = lyrics;
2089                    stroke.clone().into()
2090                }
2091            };
2092            increment = element_value.quarter_length();
2093            let placed = self.insert_note(element, staff, element_value);
2094            match uid {
2095                // The note was known to its spanners by a number of its own
2096                // before it had a place.
2097                Some(early) => self.rename(early, placed),
2098                None => self.free_pending(placed),
2099            }
2100            if is_rest {
2101                self.part.take_multi_rest(placed);
2102                self.rest_spanners(element, placed)?;
2103                if std::mem::take(&mut self.marking_full) {
2104                    self.marked_full.push(placed);
2105                }
2106            }
2107            self.last_note = Some(placed);
2108        }
2109
2110        if !self.chord_notes.is_empty() && !next_is_chord {
2111            let members = std::mem::take(&mut self.chord_notes);
2112            let lyrics = lyrics_from(std::mem::take(&mut self.chord_lyrics).into_iter())?;
2113            let (chord, member_uids) = self.chord(&members, lyrics)?;
2114            increment = chord.quarter_length();
2115            let source = members
2116                .iter()
2117                .find(|member| member.find("voice").is_some())
2118                .copied()
2119                .unwrap_or(element);
2120            let placed = self.insert_note(source, staff_number(members[0]), chord);
2121            for early in member_uids {
2122                self.rename(early, placed);
2123            }
2124            self.free_pending(placed);
2125            self.last_note = Some(placed);
2126        }
2127
2128        self.offset = op_frac(self.offset + increment);
2129        self.finale_forward = None;
2130        Ok(())
2131    }
2132
2133    /// Spanners that knew an element by one number know it by another.
2134    fn rename(&mut self, from: usize, to: usize) {
2135        for building in &mut self.part.importer.state.spanners {
2136            let mut renamed: Vec<usize> = Vec::new();
2137            for uid in &building.uids {
2138                let uid = if *uid == from { to } else { *uid };
2139                if !renamed.contains(&uid) {
2140                    renamed.push(uid);
2141                }
2142            }
2143            building.uids = renamed;
2144        }
2145    }
2146
2147    /// music21's `freePendingSpannedElementAssignment`.
2148    fn free_pending(&mut self, uid: usize) {
2149        let importer = &mut *self.part.importer;
2150        if let Some(index) = importer.state.pending.pop_front() {
2151            importer.state.spanners[index].add_first(uid);
2152        }
2153    }
2154
2155    /// music21's `xmlToSimpleNote`: a note or a stroke, known to the
2156    /// spanners by the number handed back.
2157    fn simple_note(&mut self, element: &'x Xml, free_spanners: bool) -> Result<(ReadNote, usize)> {
2158        let duration = self.duration(element)?;
2159        let mut note = match element.find("unpitched") {
2160            None => Note::from_pitch(pitch_of(element)?),
2161            Some(unpitched) => {
2162                let step = unpitched
2163                    .child_text("display-step")
2164                    .chars()
2165                    .next()
2166                    .unwrap_or('B');
2167                let octave = parse_int(unpitched.child_text("display-octave")).unwrap_or(4);
2168                Unpitched::displayed_at(step, octave)?.written().clone()
2169            }
2170        };
2171        note.set_duration(duration);
2172
2173        let beams: Vec<&Xml> = element.find_all("beam").collect();
2174        if !beams.is_empty() {
2175            note.set_beams(beams_of(&beams)?);
2176        }
2177        if let Some(stem) = element.find("stem") {
2178            note.set_stem_direction(StemDirection::from_name(stem.stripped())?);
2179        }
2180        if let Some(notehead) = element.find("notehead") {
2181            if let Some(text) = notehead.text().filter(|text| !text.is_empty()) {
2182                note.set_notehead(Notehead::from_name(text)?);
2183            }
2184            if let Some(filled) = notehead.get("filled") {
2185                note.set_notehead_fill(Some(filled == "yes"));
2186            }
2187            if let Some(color) = notehead.get("color") {
2188                note.set_color(Some(color.to_string()));
2189            }
2190            if let Some(parentheses) = notehead.get("parentheses") {
2191                note.set_notehead_parenthesis(parentheses == "yes");
2192            }
2193        }
2194
2195        let uid = self.part.importer.uid();
2196        if free_spanners {
2197            // music21 hands a waiting spanner the note as first read, and a
2198            // grace note is a copy made after that: the spanner is left
2199            // holding a note no stream holds.
2200            let joined = if element.find("grace").is_some() {
2201                self.part.importer.uid()
2202            } else {
2203                uid
2204            };
2205            self.free_pending(joined);
2206        }
2207        let mut general = General {
2208            color: note.color().map(str::to_string),
2209            ..General::default()
2210        };
2211        self.general_note(element, &mut general, note.duration().cloned(), uid, false)?;
2212        note.set_color(general.color);
2213        note.set_hidden(general.hidden);
2214        if let Some(volume) = general.volume {
2215            note.set_volume(Some(volume));
2216        }
2217        note.set_size(general.size);
2218        note.set_tie(general.tie);
2219        if let Some(duration) = general.duration {
2220            note.set_duration(duration);
2221        }
2222        *note.articulations_mut() = general.articulations;
2223        *note.expressions_mut() = general.expressions;
2224
2225        Ok(if element.find("unpitched").is_some() {
2226            let mut stroke = Unpitched::new();
2227            *stroke.written_mut() = note;
2228            (ReadNote::Unpitched(stroke), uid)
2229        } else {
2230            (ReadNote::Note(note), uid)
2231        })
2232    }
2233
2234    /// music21's `xmlToChord`.
2235    fn chord(
2236        &mut self,
2237        members: &[&'x Xml],
2238        lyrics: Vec<Lyric>,
2239    ) -> Result<(StreamElement, Vec<usize>)> {
2240        let mut notes: Vec<(ReadNote, usize)> = Vec::new();
2241        for member in members {
2242            notes.push(self.simple_note(member, false)?);
2243        }
2244        let percussion = members
2245            .iter()
2246            .any(|member| member.find("unpitched").is_some());
2247
2248        // The chord takes the first note's beams, and each kind of mark
2249        // once, read off the notes lowest first.
2250        let mut order: Vec<usize> = (0..notes.len()).collect();
2251        order.sort_by(|left, right| {
2252            let ps = |index: &usize| notes[*index].0.written().pitch().ps();
2253            ps(left).total_cmp(&ps(right))
2254        });
2255        let mut articulations: Vec<Articulation> = Vec::new();
2256        let mut expressions: Vec<Expression> = Vec::new();
2257        let mut uids = Vec::new();
2258        for index in order {
2259            let (read, uid) = &notes[index];
2260            uids.push(*uid);
2261            for articulation in read.written().articulations() {
2262                let repeats = ["Fingering", "StringIndication", "FretIndication"]
2263                    .iter()
2264                    .any(|class| articulation.is_a(class));
2265                if !repeats
2266                    && articulations
2267                        .iter()
2268                        .any(|held| held.kind() == articulation.kind())
2269                {
2270                    continue;
2271                }
2272                articulations.push(articulation.clone());
2273            }
2274            for expression in read.written().expressions() {
2275                let same = |held: &Expression| match (held, expression) {
2276                    (Expression::Ornament(left), Expression::Ornament(right)) => {
2277                        left.kind() == right.kind()
2278                    }
2279                    (Expression::Fermata(_), Expression::Fermata(_)) => true,
2280                    (Expression::Arpeggio(_), Expression::Arpeggio(_)) => true,
2281                    _ => false,
2282                };
2283                if !expressions.iter().any(same) {
2284                    expressions.push(expression.clone());
2285                }
2286            }
2287        }
2288        let beams = notes
2289            .first()
2290            .map(|(read, _)| read.written().beams().clone())
2291            .unwrap_or_default();
2292        let duration = notes
2293            .first()
2294            .and_then(|(read, _)| read.written().duration().cloned());
2295        let stem = notes
2296            .first()
2297            .map_or(StemDirection::Unspecified, |(read, _)| {
2298                read.written().stem_direction()
2299            });
2300        for (read, _) in &mut notes {
2301            let written = read.written_mut();
2302            written.articulations_mut().clear();
2303            written.expressions_mut().clear();
2304        }
2305        if let Some((first, _)) = notes.first_mut() {
2306            first.written_mut().set_beams(Beams::new());
2307            // A chord's lyrics are kept on its first note.
2308            *first.written_mut().lyrics_mut() = lyrics;
2309        }
2310
2311        let element: StreamElement = if percussion {
2312            let members: Vec<PercussionNote> = notes
2313                .into_iter()
2314                .map(|(read, _)| match read {
2315                    ReadNote::Unpitched(stroke) => PercussionNote::Unpitched(stroke),
2316                    ReadNote::Note(note) => PercussionNote::Note(note),
2317                    ReadNote::Rest(_) => unreachable!("a chord holds no rests"),
2318                })
2319                .collect();
2320            let mut chord = PercussionChord::new(members)?;
2321            let written = chord.written_mut();
2322            if let Some(duration) = duration {
2323                written.set_duration(duration);
2324            }
2325            written.set_beams(beams);
2326            *written.articulations_mut() = articulations;
2327            *written.expressions_mut() = expressions;
2328            chord.into()
2329        } else {
2330            let members: Vec<Note> = notes
2331                .into_iter()
2332                .map(|(read, _)| match read {
2333                    ReadNote::Note(note) => note,
2334                    _ => unreachable!("a chord of pitches holds notes"),
2335                })
2336                .collect();
2337            let mut chord = Chord::new(members)?;
2338            if let Some(duration) = duration {
2339                chord.set_duration(duration);
2340            }
2341            chord.set_beams(beams);
2342            // A chord reads its stem off its first note where it has none.
2343            let _ = stem;
2344            *chord.articulations_mut() = articulations;
2345            *chord.expressions_mut() = expressions;
2346            chord.into()
2347        };
2348        Ok((element, uids))
2349    }
2350
2351    /// music21's `xmlToRest`.
2352    fn rest(&mut self, element: &'x Xml) -> Result<Rest> {
2353        let duration = self.duration(element)?;
2354        let mut rest = Rest::new(duration);
2355        let tag = element
2356            .find("rest")
2357            .ok_or_else(|| import_error("a rest without a <rest> tag"))?;
2358        if tag.get("measure") == Some("yes") {
2359            let written = element.child_text("type");
2360            if written.is_empty() || matches!(written, "whole" | "breve") {
2361                self.full_measure_rest = true;
2362                self.marking_full = true;
2363                rest.set_full_measure(crate::rest::FullMeasure::Yes);
2364            }
2365        }
2366        let step = tag.child_text("display-step");
2367        if !step.is_empty() {
2368            let name = format!("{step}{}", tag.child_text("display-octave"));
2369            let displayed = Pitch::from_name(&name)?;
2370            let staff = match staff_number(element) {
2371                NO_STAFF => 1,
2372                staff => staff,
2373            };
2374            let middle = self
2375                .part
2376                .last_clefs
2377                .iter()
2378                .find(|(held, _)| *held == staff)
2379                .and_then(|(_, clef)| clef.lowest_line().filter(|_| clef.places_pitches()))
2380                .map_or(35, |lowest| lowest.saturating_add(4));
2381            let shift = displayed
2382                .checked_diatonic_note_number()
2383                .and_then(|position| position.checked_sub(middle))
2384                .ok_or_else(|| import_error(format!("a rest shown at {name} is too far off")))?;
2385            rest.set_step_shift(shift);
2386        }
2387        let mut general = General::default();
2388        let uid = 0;
2389        self.general_note(
2390            element,
2391            &mut general,
2392            Some(rest.duration().clone()),
2393            uid,
2394            true,
2395        )?;
2396        rest.set_hidden(general.hidden);
2397        rest.set_color(general.color);
2398        rest.set_size(general.size);
2399        if let Some(duration) = general.duration {
2400            rest.set_duration(duration);
2401        }
2402        *rest.articulations_mut() = general.articulations;
2403        *rest.expressions_mut() = general.expressions;
2404        Ok(rest)
2405    }
2406
2407    /// The spanners a rest's notations start or stop, which can only be
2408    /// joined once the rest has a number.
2409    fn rest_spanners(&mut self, element: &'x Xml, uid: usize) -> Result<()> {
2410        for notations in element.find_all("notations") {
2411            self.notation_spanners(notations, uid)?;
2412        }
2413        Ok(())
2414    }
2415
2416    /// music21's `xmlNoteToGeneralNoteHelper`.
2417    fn general_note(
2418        &mut self,
2419        element: &'x Xml,
2420        general: &mut General,
2421        duration: Option<Duration>,
2422        uid: usize,
2423        is_rest: bool,
2424    ) -> Result<()> {
2425        if let Some(color) = element.get("color") {
2426            general.color = Some(color.to_string());
2427        }
2428        general.hidden = element.get("print-object") == Some("no");
2429        if !is_rest && let Some(dynamics) = element.get("dynamics").and_then(parse_float) {
2430            general.volume = Some(Volume::from_velocity_scalar(dynamics * (90.0 / 12700.0))?);
2431        }
2432        if element.get("pizzicato") == Some("yes")
2433            && let Some(kind) = ArticulationKind::from_class_name("Pizzicato")
2434        {
2435            general.articulations.push(Articulation::of_kind(kind));
2436        }
2437        if let Some(written) = element.find("type")
2438            && let Some(size) = written.get("size")
2439        {
2440            general.size = NoteSize::from_name(size);
2441        }
2442        if element.find("tie").is_some() {
2443            general.tie = tie_of(element);
2444        }
2445        if let Some(grace) = element.find("grace") {
2446            // A grace note is written as an eighth where nothing says.
2447            let base = duration.unwrap_or_default();
2448            let mut written = Duration::default();
2449            written.clear();
2450            written.set_tuplets(Vec::new());
2451            for (kind, dots) in base.components() {
2452                written.add_duration_tuple(kind, dots);
2453            }
2454            let unsaid = base.components().is_empty();
2455            if unsaid {
2456                written.add_duration_tuple(DurationType::Eighth, 0);
2457            }
2458            let mut value = written.grace_duration();
2459            let mut marks = Grace::new();
2460            marks.set_value_unsaid(unsaid);
2461            marks.set_slash(matches!(grace.get("slash"), Some("yes") | None));
2462            let share = |name: &str| {
2463                grace
2464                    .get(name)
2465                    .and_then(parse_int)
2466                    .map(|percent| FloatType::from(percent) / 100.0)
2467            };
2468            marks.set_steal_time_previous(share("steal-time-previous"));
2469            marks.set_steal_time_following(share("steal-time-following"));
2470            value.set_grace(Some(marks));
2471            general.duration = Some(value);
2472        }
2473        for notations in element.find_all("notations") {
2474            self.notations(notations, general)?;
2475            if !is_rest {
2476                self.notation_spanners(notations, uid)?;
2477            }
2478        }
2479        Ok(())
2480    }
2481
2482    /// music21's `xmlToDuration`.
2483    fn duration(&mut self, element: &'x Xml) -> Result<Duration> {
2484        let quarter_length = match element.find("duration") {
2485            Some(duration) => {
2486                let ticks = parse_float(duration.stripped())
2487                    .ok_or_else(|| import_error("a <duration> that is not a number"))?;
2488                op_frac(ticks / self.divisions)
2489            }
2490            None => 0.0,
2491        };
2492        let written = element.child_text("type");
2493        if written.is_empty() {
2494            // Some rests say how long they last and nothing else.
2495            return Duration::new(quarter_length);
2496        }
2497        let kind = duration_type(written)?;
2498        let dots = element.find_all("dot").count() as u32;
2499        let tuplets = if element.find("time-modification").is_some() {
2500            self.tuplets(element)?
2501        } else {
2502            Vec::new()
2503        };
2504        if kind.quarter_length_with_dots(dots) == quarter_length && tuplets.is_empty() {
2505            return Duration::new(quarter_length);
2506        }
2507        // Made from the length first, as music21 makes it, so its writing
2508        // counts as worked out even with the written value put in its place.
2509        let mut duration = Duration::new(quarter_length)?;
2510        duration.clear();
2511        duration.set_tuplets(Vec::new());
2512        duration.add_duration_tuple(kind, dots);
2513        duration.set_tuplets(tuplets);
2514        if (duration.quarter_length() - quarter_length).abs() > 1e-7 {
2515            duration.set_linked(false);
2516            duration.set_quarter_length(quarter_length)?;
2517        }
2518        Ok(duration)
2519    }
2520
2521    /// music21's `xmlToTuplets`.
2522    fn tuplets(&mut self, element: &'x Xml) -> Result<Vec<Tuplet>> {
2523        let modification = element
2524            .find("time-modification")
2525            .ok_or_else(|| import_error("Note without time-modification in xmlToTuplets"))?;
2526        let count = |tag: &str, fallback: u32| {
2527            parse_int(modification.child_text(tag)).map_or(fallback, |value| value.max(1) as u32)
2528        };
2529        let normal_type = match modification.child_text("normal-type") {
2530            "" => element.child_text("type"),
2531            written => written,
2532        };
2533        let kind = duration_type(normal_type)?;
2534        let dots = modification.find_all("normal-dot").count() as u32;
2535        let time_mod = Tuplet::new(
2536            count("actual-notes", 3),
2537            count("normal-notes", 2),
2538            kind,
2539            dots,
2540        );
2541
2542        let notations = element.find("notations");
2543        if notations.is_none() {
2544            self.part.active_tuplets[0] = Some(time_mod);
2545        }
2546        let multiplier = |tuplet: &Tuplet| -> (i64, i64) {
2547            // actual notes in the time of normal: each lasts normal/actual,
2548            // scaled by the written values of the two sides.
2549            let ratio = tuplet.multiplier();
2550            (
2551                i64::from(*ratio.numer().unwrap_or(&1)),
2552                i64::from(*ratio.denom().unwrap_or(&1)),
2553            )
2554        };
2555        let divide = |remaining: (i64, i64), by: (i64, i64)| -> (i64, i64) {
2556            reduce(remaining.0 * by.1, remaining.1 * by.0)
2557        };
2558        let mut remaining = multiplier(&time_mod);
2559        let mut returned: [Option<Tuplet>; 8] = Default::default();
2560        // Which of the returned tuplets are the active ones themselves.
2561        let mut from_active = [false; 8];
2562        let mut to_remove: Vec<usize> = Vec::new();
2563        let mut to_stop: Vec<usize> = Vec::new();
2564
2565        if let Some(notations) = notations {
2566            for written in notations.find_all("tuplet") {
2567                let index = written
2568                    .get("number")
2569                    .and_then(parse_int)
2570                    .map_or(1, |number| number.clamp(0, 6) as usize);
2571                let tuplet_type = written.get("type");
2572                if tuplet_type == Some("stop") {
2573                    if let Some(active) = self.part.active_tuplets[index] {
2574                        // One that started on this very note starts and
2575                        // stops on it. music21 asks by value, and so finds
2576                        // an equal tuplet of another number too.
2577                        if returned.iter().flatten().any(|held| *held == active)
2578                            && from_active[index]
2579                            && let Some(held) = &mut returned[index]
2580                        {
2581                            held.set_tuplet_type(Some(TupletType::StartStop));
2582                        }
2583                        to_remove.push(index);
2584                        to_stop.push(index);
2585                    }
2586                    continue;
2587                }
2588                let actual = written.find("tuplet-actual");
2589                let normal = written.find("tuplet-normal");
2590                let mut tuplet = match (actual, normal) {
2591                    (Some(actual), Some(normal)) => {
2592                        let number = |side: &Xml, fallback: u32| {
2593                            parse_int(side.child_text("tuplet-number"))
2594                                .map_or(fallback, |value| value.max(1) as u32)
2595                        };
2596                        let mut tuplet = Tuplet::ratio(number(actual, 3), number(normal, 2));
2597                        let side = |side: &Xml| -> Result<Option<(DurationType, u32)>> {
2598                            match side.find("tuplet-type") {
2599                                Some(written) if written.text().is_some() => Ok(Some((
2600                                    duration_type(written.stripped())?,
2601                                    written.find_all("tuplet-dot").count() as u32,
2602                                ))),
2603                                _ => Ok(None),
2604                            }
2605                        };
2606                        if let Some(value) = side(actual)? {
2607                            tuplet.set_duration_actual(Some(value));
2608                        }
2609                        if let Some(value) = side(normal)? {
2610                            tuplet.set_duration_normal(Some(value));
2611                        }
2612                        tuplet
2613                    }
2614                    _ => time_mod,
2615                };
2616                tuplet
2617                    .set_tuplet_type(tuplet_type.and_then(|name| TupletType::from_name(name).ok()));
2618                let bracket = written.get("bracket");
2619                if let Some(bracket) = bracket {
2620                    tuplet.set_bracket(if bracket == "yes" {
2621                        TupletBracket::Bracket
2622                    } else {
2623                        TupletBracket::None
2624                    });
2625                }
2626                let show_number = written.get("show-number");
2627                if show_number == Some("none") {
2628                    tuplet.set_actual_show(None);
2629                    if bracket.is_none() {
2630                        tuplet.set_bracket(TupletBracket::None);
2631                    }
2632                } else if show_number == Some("both") {
2633                    tuplet.set_normal_show(Some(TupletShow::Number));
2634                }
2635                let both_or_type = |shown: Option<TupletShow>| {
2636                    Some(if shown.is_some() {
2637                        TupletShow::Both
2638                    } else {
2639                        TupletShow::Type
2640                    })
2641                };
2642                if written.get("show-type") == Some("actual") {
2643                    tuplet.set_actual_show(both_or_type(tuplet.actual_show()));
2644                } else if show_number == Some("both") {
2645                    tuplet.set_actual_show(both_or_type(tuplet.actual_show()));
2646                    tuplet.set_normal_show(both_or_type(tuplet.normal_show()));
2647                }
2648                if written.get("line-shape") == Some("curved") {
2649                    tuplet.set_bracket(TupletBracket::Slur);
2650                }
2651                tuplet.set_placement(placement_of(written));
2652                remaining = divide(remaining, multiplier(&tuplet));
2653                returned[index] = Some(tuplet);
2654                from_active[index] = true;
2655                self.part.active_tuplets[index] = Some(tuplet);
2656            }
2657        }
2658
2659        for index in 1..self.part.active_tuplets.len() {
2660            let Some(active) = &self.part.active_tuplets[index] else {
2661                continue;
2662            };
2663            if returned.iter().flatten().any(|held| held == active) {
2664                continue;
2665            }
2666            let mut copy = *active;
2667            copy.set_tuplet_type(if to_stop.contains(&index) {
2668                Some(TupletType::Stop)
2669            } else {
2670                None
2671            });
2672            remaining = divide(remaining, multiplier(&copy));
2673            returned[index] = Some(copy);
2674        }
2675        if remaining != (1, 1) {
2676            let mut remainder = Tuplet::ratio(remaining.1.max(1) as u32, remaining.0.max(1) as u32);
2677            remainder.set_duration_normal(time_mod.duration_normal());
2678            remainder.set_duration_actual(time_mod.duration_actual());
2679            returned[7] = Some(remainder);
2680        }
2681        for index in to_remove {
2682            self.part.active_tuplets[index] = None;
2683        }
2684        Ok(returned.into_iter().flatten().collect())
2685    }
2686
2687    // ------------------------------------------------------- notations
2688
2689    /// music21's `xmlNotations`, apart from the spanners.
2690    fn notations(&mut self, notations: &'x Xml, general: &mut General) -> Result<()> {
2691        for technical in notations.find_all("technical") {
2692            for mark in &technical.children {
2693                if let Some(read) = technical_of(mark, self.divisions) {
2694                    general.articulations.push(read);
2695                }
2696            }
2697        }
2698        for articulations in notations.find_all("articulations") {
2699            for mark in &articulations.children {
2700                if let Some(read) = articulation_of(mark) {
2701                    general.articulations.push(read);
2702                }
2703            }
2704        }
2705        for written in notations.find_all("fermata") {
2706            let mut fermata = Fermata::new();
2707            match written.get("type") {
2708                Some("upright") => fermata.set_fermata_type(FermataType::Upright),
2709                Some("inverted") => fermata.set_fermata_type(FermataType::Inverted),
2710                _ => {}
2711            }
2712            let shape = written.stripped();
2713            if !shape.is_empty() {
2714                fermata.set_shape(Some(shape.to_string()));
2715            }
2716            general.expressions.push(Expression::Fermata(fermata));
2717        }
2718        for tag in ["arpeggiate", "non-arpeggiate"] {
2719            for written in notations.find_all(tag) {
2720                let kind = if tag == "non-arpeggiate" {
2721                    ArpeggioType::NonArpeggio
2722                } else {
2723                    ArpeggioType::from_name(written.get("direction").unwrap_or("normal"))?
2724                };
2725                match written.get("number") {
2726                    None => general.expressions.push(Expression::Arpeggio(kind)),
2727                    Some(number) => general.arpeggio_spanners.push((number.to_string(), kind)),
2728                }
2729            }
2730        }
2731        let mut latest: Option<usize> = None;
2732        for ornaments in notations.find_all("ornaments") {
2733            for mark in &ornaments.children {
2734                if mark.tag == "accidental-mark" {
2735                    let Some(index) = latest else {
2736                        continue;
2737                    };
2738                    let mut accidental = accidental_of(mark)?;
2739                    accidental.set_display_status(Some(true));
2740                    if let Expression::Ornament(ornament) = &mut general.expressions[index] {
2741                        if ornament.is_a("Turn") {
2742                            if mark.get("placement") == Some("below") {
2743                                ornament.set_lower_accidental(Some(accidental));
2744                            } else {
2745                                ornament.set_upper_accidental(Some(accidental));
2746                            }
2747                        } else if ornament.is_a("GeneralMordent") || ornament.is_a("Trill") {
2748                            ornament.set_accidental(Some(accidental))?;
2749                        }
2750                    }
2751                    continue;
2752                }
2753                let class = match mark.tag.as_str() {
2754                    "trill-mark" => "Trill",
2755                    "turn" | "delayed-turn" => "Turn",
2756                    "inverted-turn" | "delayed-inverted-turn" => "InvertedTurn",
2757                    "shake" => "Shake",
2758                    "mordent" => "Mordent",
2759                    "inverted-mordent" => "InvertedMordent",
2760                    "schleifer" => "Schleifer",
2761                    "other-ornament" => "Ornament",
2762                    "tremolo" => {
2763                        if matches!(mark.get("type"), Some("start" | "stop")) {
2764                            continue;
2765                        }
2766                        "Tremolo"
2767                    }
2768                    _ => continue,
2769                };
2770                let Some(kind) = OrnamentKind::from_class_name(class) else {
2771                    continue;
2772                };
2773                let mut ornament = Ornament::of_kind(kind);
2774                match mark.tag.as_str() {
2775                    "delayed-turn" | "delayed-inverted-turn" => {
2776                        ornament.set_delay(OrnamentDelay::Default);
2777                    }
2778                    "turn" | "inverted-turn" => ornament.set_delay(OrnamentDelay::NoDelay),
2779                    "tremolo" => {
2780                        ornament.set_number_of_marks(tremolo_marks(mark)?)?;
2781                    }
2782                    _ => {}
2783                }
2784                if mark.tag != "tremolo" {
2785                    if let Some(placement) = mark.get("placement") {
2786                        ornament.set_placement(Some(placement.to_string()));
2787                    }
2788                    latest = Some(general.expressions.len());
2789                }
2790                general
2791                    .expressions
2792                    .push(Expression::Ornament(Box::new(ornament)));
2793            }
2794        }
2795        Ok(())
2796    }
2797
2798    /// music21's `xmlNotationsToSpanners` and the arpeggios across chords.
2799    fn notation_spanners(&mut self, notations: &'x Xml, uid: usize) -> Result<()> {
2800        for tag in ["arpeggiate", "non-arpeggiate"] {
2801            for written in notations.find_all(tag) {
2802                let Some(number) = written.get("number") else {
2803                    continue;
2804                };
2805                let kind = if tag == "non-arpeggiate" {
2806                    ArpeggioType::NonArpeggio
2807                } else {
2808                    ArpeggioType::from_name(written.get("direction").unwrap_or("normal"))
2809                        .unwrap_or(ArpeggioType::Normal)
2810                };
2811                // A number tells apart arpeggios struck together, which may
2812                // cross staves but not parts.
2813                let key = (
2814                    number.to_string(),
2815                    op_frac(self.part.last_measure_offset + self.offset),
2816                );
2817                let found = self
2818                    .part
2819                    .arpeggios
2820                    .iter()
2821                    .find(|(held, _)| *held == key)
2822                    .map(|(_, index)| *index);
2823                let spanners = &mut self.part.importer.state.spanners;
2824                let index = found.unwrap_or_else(|| {
2825                    let mut building = Building::new(SpannerKind::ArpeggioMark, Some(number));
2826                    building.arpeggio = kind;
2827                    spanners.push(building);
2828                    spanners.len() - 1
2829                });
2830                if found.is_none() {
2831                    self.part.arpeggios.push((key, index));
2832                }
2833                self.part.importer.state.spanners[index].add(uid);
2834            }
2835        }
2836        for ornaments in notations.find_all("ornaments") {
2837            for mark in &ornaments.children {
2838                match mark.tag.as_str() {
2839                    "wavy-line" => {
2840                        self.one_spanner(mark, Some(uid), SpannerKind::TrillExtension, false);
2841                    }
2842                    // music21's `xmlToTremolo`: a tremolo that starts or
2843                    // stops is one between notes.
2844                    "tremolo" if matches!(mark.get("type"), Some("start" | "stop")) => {
2845                        let index =
2846                            self.one_spanner(mark, Some(uid), SpannerKind::TremoloSpanner, false);
2847                        self.part.importer.state.spanners[index].marks = tremolo_marks(mark)?;
2848                    }
2849                    _ => {}
2850                }
2851            }
2852        }
2853        for slur in notations.find_all("slur") {
2854            let index = self.one_spanner(slur, Some(uid), SpannerKind::Slur, false);
2855            let building = &mut self.part.importer.state.spanners[index];
2856            if let Some(line_type) = slur.get("line-type") {
2857                building.line_type = Some(line_type.to_string());
2858            }
2859            if let Some(placement) = placement_of(slur) {
2860                building.placement = Some(placement);
2861            }
2862        }
2863        for tag in ["glissando", "slide"] {
2864            for written in notations.find_all(tag) {
2865                let index = self.one_spanner(written, Some(uid), SpannerKind::Glissando, false);
2866                let building = &mut self.part.importer.state.spanners[index];
2867                if tag == "slide" {
2868                    building.slide = SlideType::Continuous;
2869                }
2870                match written.get("line-type") {
2871                    Some(line_type) => {
2872                        let lower = line_type.to_lowercase();
2873                        if !["solid", "dashed", "dotted", "wavy"].contains(&lower.as_str()) {
2874                            return Err(import_error(format!("not a valid value: {line_type}")));
2875                        }
2876                        building.line_type = Some(lower);
2877                    }
2878                    None if tag == "slide" => building.line_type = Some("solid".to_string()),
2879                    None => {}
2880                }
2881            }
2882        }
2883        Ok(())
2884    }
2885
2886    /// music21's `xmlOneSpanner`: the open spanner of a kind and number, or
2887    /// a new one.
2888    fn one_spanner(
2889        &mut self,
2890        element: &Xml,
2891        target: Option<usize>,
2892        kind: SpannerKind,
2893        allow_duplicates: bool,
2894    ) -> usize {
2895        let id = element.get("number");
2896        let spanners = &mut self.part.importer.state.spanners;
2897        let found = spanners
2898            .iter()
2899            .position(|held| held.kind == kind && !held.complete && held.id_local.as_deref() == id);
2900        let index = match found {
2901            Some(index) if !allow_duplicates => index,
2902            _ => {
2903                let mut building = Building::new(kind, id);
2904                if let Some(placement) = placement_of(element) {
2905                    building.placement = Some(placement);
2906                }
2907                spanners.push(building);
2908                spanners.len() - 1
2909            }
2910        };
2911        if let Some(target) = target {
2912            spanners[index].add(target);
2913        }
2914        if element.get("type") == Some("stop") {
2915            spanners[index].complete = true;
2916        }
2917        index
2918    }
2919
2920    // ------------------------------------------------------ directions
2921
2922    /// music21's `xmlDirection`.
2923    fn direction(&mut self, direction: &'x Xml) -> Result<()> {
2924        let total = self.offset_of(direction) + self.offset;
2925        let staff = staff_number(direction);
2926        let mut metronome_added = false;
2927        for direction_type in direction.find_all("direction-type") {
2928            for specific in &direction_type.children {
2929                self.direction_type(specific, direction, staff, total)?;
2930                if specific.tag == "metronome" {
2931                    metronome_added = true;
2932                }
2933            }
2934        }
2935        if !metronome_added
2936            && let Some(sound) = direction
2937                .find_all("sound")
2938                .find(|sound| sound.get("tempo").is_some())
2939        {
2940            self.sound_tempo(sound, Some(direction), staff, total);
2941        }
2942        Ok(())
2943    }
2944
2945    /// music21's `setSoundTempo`: how fast the music is played, where no
2946    /// mark says.
2947    fn sound_tempo(&mut self, sound: &Xml, direction: Option<&Xml>, staff: i32, total: FloatType) {
2948        let Some(tempo) = sound.get("tempo").and_then(sound_tempo) else {
2949            return;
2950        };
2951        let mut mark = MetronomeMark::default().with_number_sounding(tempo);
2952        if let Some(direction) = direction {
2953            mark.set_placement(placement_of(direction));
2954        }
2955        self.insert(total, staff, mark);
2956    }
2957
2958    /// music21's `setDirectionInDirectionType`.
2959    fn direction_type(
2960        &mut self,
2961        specific: &'x Xml,
2962        direction: &'x Xml,
2963        staff: i32,
2964        total: FloatType,
2965    ) -> Result<()> {
2966        match specific.tag.as_str() {
2967            "dynamics" => {
2968                for written in &specific.children {
2969                    let text = match (written.tag.as_str(), written.stripped()) {
2970                        ("other-dynamic", text) if !text.is_empty() => text,
2971                        (tag, _) => tag,
2972                    };
2973                    let mut dynamic = Dynamic::new(text);
2974                    dynamic.set_placement(placement_of(direction));
2975                    self.insert(total, staff, dynamic);
2976                }
2977            }
2978            "wedge" | "bracket" | "dashes" | "octave-shift" | "pedal" => {
2979                // music21 warns and carries on when one cannot be read.
2980                if let Ok(made) = self.direction_spanners(specific, staff, total) {
2981                    for index in made {
2982                        let building = &mut self.part.importer.state.spanners[index];
2983                        if let Some(placement) = placement_of(specific) {
2984                            building.placement = Some(placement);
2985                        }
2986                        if building.kind != SpannerKind::Crescendo
2987                            && building.kind != SpannerKind::Diminuendo
2988                            && let Some(line_type) = specific.get("line-type")
2989                        {
2990                            building.line_type = Some(line_type.to_string());
2991                        }
2992                    }
2993                }
2994            }
2995            "coda" | "segno" => {
2996                let kind = if specific.tag == "segno" {
2997                    RepeatExpressionKind::Segno
2998                } else {
2999                    RepeatExpressionKind::Coda
3000                };
3001                self.insert(total, staff, RepeatExpression::new(kind));
3002            }
3003            "rehearsal" => {
3004                // music21's `xmlToRehearsalMark`.
3005                let mut mark = RehearsalMark::new(specific.stripped());
3006                if let Some(enclosure) = specific.get("enclosure") {
3007                    let lower = enclosure.to_lowercase();
3008                    if !ENCLOSURES.contains(&lower.as_str()) {
3009                        return Err(import_error(format!(
3010                            "Not a supported enclosure: '{enclosure}'"
3011                        )));
3012                    }
3013                    mark.set_enclosure(Some(lower));
3014                }
3015                mark.set_placement(placement_of(direction));
3016                self.insert(total, staff, mark);
3017            }
3018            "metronome" => {
3019                let tempo = metronome(specific, placement_of(direction))?;
3020                self.insert(total, staff, tempo);
3021            }
3022            "words" => {
3023                let text = specific.stripped();
3024                let placement = placement_of(direction);
3025                // Words that say where to go next are a repeat mark.
3026                let repeat = RepeatExpressionKind::ALL
3027                    .into_iter()
3028                    .find(|kind| RepeatExpression::new(*kind).is_valid_text(text));
3029                match repeat {
3030                    Some(kind) => {
3031                        let mut mark = RepeatExpression::new(kind);
3032                        mark.set_text(text);
3033                        // The words are placed, not the mark: one drawn as
3034                        // its sign, a coda or a segno, stands where music21
3035                        // puts a sign whatever side its words were on.
3036                        if !mark.use_symbol() {
3037                            mark.set_placement(placement);
3038                        }
3039                        self.insert(total, staff, mark);
3040                    }
3041                    None => {
3042                        let mut words = TextExpression::new(text);
3043                        words.set_placement(placement);
3044                        self.insert(total, staff, words);
3045                    }
3046                }
3047            }
3048            _ => {}
3049        }
3050        Ok(())
3051    }
3052
3053    /// music21's `xmlDirectionTypeToSpanners`. Hands back the spanners it
3054    /// started.
3055    fn direction_spanners(
3056        &mut self,
3057        element: &'x Xml,
3058        staff: i32,
3059        total: FloatType,
3060    ) -> Result<Vec<usize>> {
3061        let last = self.last_note;
3062        let id = element.get("number");
3063        let mut made = Vec::new();
3064        let open = |spanners: &[Building], wanted: &dyn Fn(SpannerKind) -> bool| {
3065            spanners.iter().position(|held| {
3066                wanted(held.kind) && !held.complete && held.id_local.as_deref() == id
3067            })
3068        };
3069        match element.tag.as_str() {
3070            "wedge" => {
3071                let kind = match element.get("type") {
3072                    Some("crescendo") => Some(SpannerKind::Crescendo),
3073                    Some("diminuendo") => Some(SpannerKind::Diminuendo),
3074                    Some("stop") => None,
3075                    other => {
3076                        return Err(import_error(format!("Unknown type, {other:?}.")));
3077                    }
3078                };
3079                match kind {
3080                    Some(kind) => {
3081                        let index = self.one_spanner(element, None, kind, true);
3082                        self.part.importer.state.pending.push_back(index);
3083                        made.push(index);
3084                    }
3085                    None => {
3086                        let spanners = &mut self.part.importer.state.spanners;
3087                        let index = open(spanners, &SpannerKind::is_wedge)
3088                            .ok_or_else(|| import_error("Error in getting DynamicWedges"))?;
3089                        spanners[index].complete = true;
3090                        if let Some(last) = last {
3091                            spanners[index].add(last);
3092                        }
3093                    }
3094                }
3095            }
3096            "bracket" | "dashes" => {
3097                let dashes = element.tag == "dashes";
3098                let tick = || -> Result<LineEnd> {
3099                    match element.get("line-end") {
3100                        Some(name) => LineEnd::from_name(name),
3101                        None => Ok(LineEnd::Down),
3102                    }
3103                };
3104                let height = element.get("end-length").and_then(parse_float);
3105                let SpannerState {
3106                    spanners, pending, ..
3107                } = &mut self.part.importer.state;
3108                match element.get("type") {
3109                    Some("start") => {
3110                        let mut building = Building::new(SpannerKind::Line, id);
3111                        if dashes {
3112                            building.ends.start = LineEnd::None;
3113                            building.line_type = Some("dashed".to_string());
3114                        } else {
3115                            building.ends.start_height = height;
3116                            building.ends.start = tick()?;
3117                            if let Some(line_type) = element.get("line-type") {
3118                                building.line_type = Some(line_type.to_string());
3119                            }
3120                        }
3121                        spanners.push(building);
3122                        pending.push_back(spanners.len() - 1);
3123                        made.push(spanners.len() - 1);
3124                    }
3125                    Some("stop") => {
3126                        let Some(index) = open(spanners, &|kind| kind == SpannerKind::Line) else {
3127                            return Ok(made);
3128                        };
3129                        let building = &mut spanners[index];
3130                        building.complete = true;
3131                        if dashes {
3132                            building.ends.end = LineEnd::None;
3133                            building.line_type = Some("dashed".to_string());
3134                        } else {
3135                            building.ends.end = tick()?;
3136                            if height.is_some() {
3137                                building.ends.end_height = height;
3138                            }
3139                            if let Some(line_type) = element.get("line-type") {
3140                                building.line_type = Some(line_type.to_string());
3141                            }
3142                        }
3143                        if let Some(last) = last {
3144                            building.add(last);
3145                        }
3146                    }
3147                    other => {
3148                        return Err(import_error(format!(
3149                            "unidentified mxType of mxBracket: {other:?}"
3150                        )));
3151                    }
3152                }
3153            }
3154            "octave-shift" => {
3155                let SpannerState {
3156                    spanners, pending, ..
3157                } = &mut self.part.importer.state;
3158                match element.get("type") {
3159                    Some(direction @ ("up" | "down")) => {
3160                        let size = element.get("size").and_then(parse_int).unwrap_or(8);
3161                        // An `up` shift is a line under the notes.
3162                        let up = direction == "down";
3163                        let name = match (size, up) {
3164                            (15, true) => "15ma",
3165                            (15, false) => "15mb",
3166                            (22, true) => "22da",
3167                            (22, false) => "22db",
3168                            (_, true) => "8va",
3169                            (_, false) => "8vb",
3170                        };
3171                        let mut building = Building::new(SpannerKind::Ottava, id);
3172                        building.shift = Some(OctaveShift::from_name(name, false)?);
3173                        building.placement = Some(if up {
3174                            Placement::Above
3175                        } else {
3176                            Placement::Below
3177                        });
3178                        spanners.push(building);
3179                        pending.push_back(spanners.len() - 1);
3180                        made.push(spanners.len() - 1);
3181                    }
3182                    Some(kind @ ("continue" | "stop")) => {
3183                        let index = open(spanners, &|kind| kind == SpannerKind::Ottava)
3184                            .ok_or_else(|| import_error("Error in getting Ottava"))?;
3185                        if kind == "continue" {
3186                            pending.push_back(index);
3187                        } else {
3188                            spanners[index].complete = true;
3189                            if let Some(last) = last {
3190                                spanners[index].add(last);
3191                            }
3192                        }
3193                    }
3194                    other => {
3195                        return Err(import_error(format!(
3196                            "unidentified mxType of octave-shift: {other:?}"
3197                        )));
3198                    }
3199                }
3200            }
3201            "pedal" => {
3202                let SpannerState {
3203                    spanners, pending, ..
3204                } = &mut self.part.importer.state;
3205                match element.get("type") {
3206                    Some(kind @ ("start" | "sostenuto")) => {
3207                        let mut building = Building::new(SpannerKind::PedalMark, id);
3208                        building.pedal.pedal_type = Some(if kind == "start" {
3209                            PedalType::Sustain
3210                        } else {
3211                            PedalType::Sostenuto
3212                        });
3213                        if element.get("line") == Some("yes") {
3214                            building.pedal.form = Some(PedalForm::Line);
3215                        } else if element.get("line") == Some("no")
3216                            || element.get("sign") == Some("yes")
3217                        {
3218                            building.pedal.form = Some(PedalForm::Symbol);
3219                        }
3220                        building.pedal.abbreviated = element.get("abbreviated") == Some("yes");
3221                        spanners.push(building);
3222                        pending.push_back(spanners.len() - 1);
3223                        self.pedal_starts.push((spanners.len() - 1, total));
3224                        made.push(spanners.len() - 1);
3225                    }
3226                    Some(kind @ ("continue" | "stop" | "discontinue" | "resume" | "change")) => {
3227                        let index = open(spanners, &|kind| kind == SpannerKind::PedalMark)
3228                            .ok_or_else(|| import_error("Error in getting PedalMark"))?;
3229                        match kind {
3230                            "stop" => {
3231                                spanners[index].complete = true;
3232                                if let Some(last) = last {
3233                                    spanners[index].add(last);
3234                                }
3235                            }
3236                            "resume" => {
3237                                let started = self
3238                                    .pedal_starts
3239                                    .iter()
3240                                    .find(|(held, _)| *held == index)
3241                                    .map(|(_, at)| *at);
3242                                if spanners[index].pedal.form == Some(PedalForm::Symbol)
3243                                    && started == Some(total)
3244                                {
3245                                    spanners[index].pedal.form = Some(PedalForm::SymbolLine);
3246                                } else {
3247                                    self.pedal_object(PedalObjectKind::GapEnd, index, staff, total);
3248                                }
3249                            }
3250                            "discontinue" => {
3251                                self.pedal_object(PedalObjectKind::GapStart, index, staff, total);
3252                            }
3253                            "change" => {
3254                                self.pedal_object(PedalObjectKind::Bounce, index, staff, total);
3255                            }
3256                            // music21 remembers nothing of a pedal that
3257                            // carries on.
3258                            _ => {}
3259                        }
3260                    }
3261                    other => {
3262                        return Err(import_error(format!(
3263                            "unidentified mxType of pedal: {other:?}"
3264                        )));
3265                    }
3266                }
3267            }
3268            _ => {}
3269        }
3270        Ok(made)
3271    }
3272
3273    /// A bounce or a gap in a held pedal, put where the direction stands and
3274    /// joined by the pedal mark it belongs to.
3275    fn pedal_object(&mut self, kind: PedalObjectKind, pedal: usize, staff: i32, total: FloatType) {
3276        let uid = self.insert(total, staff, PedalObject::new(kind));
3277        self.part.importer.state.spanners[pedal].add(uid);
3278    }
3279
3280    /// music21's `xmlHarmony` and `xmlToChordSymbol`.
3281    fn harmony(&mut self, harmony: &'x Xml) -> Result<()> {
3282        let mut kind = harmony.child_text("kind").to_string();
3283        let kind_element = harmony.find("kind");
3284        let mut kind_text = String::new();
3285        if !kind.is_empty() {
3286            for (alias, target) in crate::chordsymbol::CHORD_KIND_ALIASES {
3287                if alias == kind {
3288                    kind = target.to_string();
3289                }
3290            }
3291            let written = kind_element.and_then(|kind| kind.get("text")).unwrap_or("");
3292            if !(written.is_empty() && kind != "none") {
3293                kind_text = written.to_string();
3294            }
3295        }
3296        let pitch_of = |step: &Xml, alter: Option<&Xml>| -> Result<Option<Pitch>> {
3297            let name = match step.text().filter(|text| !text.is_empty()) {
3298                Some(text) => text,
3299                None => match step.get("text") {
3300                    Some(text) => text,
3301                    None => return Ok(None),
3302                },
3303            };
3304            let mut pitch = Pitch::from_name(name.trim())?;
3305            if let Some(alter) = alter.and_then(|alter| parse_float(alter.stripped())) {
3306                pitch.set_written_accidental(Some(Accidental::new(alter)?));
3307            }
3308            Ok(Some(pitch))
3309        };
3310        let bass = match harmony.find("bass") {
3311            Some(bass) => {
3312                let step = bass
3313                    .find("bass-step")
3314                    .ok_or_else(|| import_error("bass-step missing"))?;
3315                pitch_of(step, bass.find("bass-alter"))?
3316            }
3317            None => None,
3318        };
3319        let root = match harmony.find("root") {
3320            Some(root) => match root.find("root-step") {
3321                Some(step) => pitch_of(step, root.find("root-alter"))?,
3322                None => None,
3323            },
3324            None => None,
3325        };
3326
3327        let mut symbol = if kind == "none" {
3328            ChordSymbol::no_chord(Some(kind_text.clone()).filter(|text| !text.is_empty()))
3329        } else {
3330            let root = root.ok_or_else(|| {
3331                import_error("reading a chord symbol given by function is not supported yet")
3332            })?;
3333            let mut symbol = match ChordSymbol::from_kind(root.clone(), &kind, bass.clone()) {
3334                Ok(symbol) => symbol,
3335                // A kind music21 has no notes for is still a symbol of that
3336                // kind on its root.
3337                Err(_) => {
3338                    let mut symbol = ChordSymbol::parse_music21(root.name())?;
3339                    symbol.set_root(root);
3340                    symbol.set_bass(bass);
3341                    symbol.with_kind(&kind)
3342                }
3343            };
3344            symbol.set_kind_text(Some(kind_text));
3345            symbol
3346        };
3347        if !symbol.is_no_chord() {
3348            for degree in harmony.find_all("degree") {
3349                let value = parse_int(degree.child_text("degree-value"))
3350                    .ok_or_else(|| import_error("degree-value missing"))?;
3351                let alter = parse_int(degree.child_text("degree-alter")).unwrap_or(0);
3352                let modification = ChordStepModification::new(
3353                    crate::chordsymbol::ChordStepModificationType::from_music21_name(
3354                        degree.child_text("degree-type"),
3355                    )?,
3356                    value.clamp(0, 255) as u8,
3357                    alter,
3358                )?;
3359                symbol.add_chord_step_modification(modification);
3360            }
3361        }
3362        // An inversion with no bass written puts that chord note in the
3363        // bass, as music21's `ChordSymbol(inversion=...)` does.
3364        let inversion = parse_int(harmony.child_text("inversion")).unwrap_or(0);
3365        if inversion > 0 && symbol.bass().is_none() && !symbol.is_no_chord() {
3366            let pitches = symbol.pitches()?;
3367            if let Some(bass) = usize::try_from(inversion)
3368                .ok()
3369                .and_then(|at| pitches.get(at))
3370            {
3371                symbol.set_bass(Some(bass.clone()));
3372            }
3373        }
3374        symbol.set_placement(placement_of(harmony));
3375        let offset = self.offset + self.offset_of(harmony);
3376        self.insert(offset, staff_number(harmony), symbol);
3377        Ok(())
3378    }
3379
3380    /// music21's `xmlBarline`.
3381    fn barline(&mut self, element: &'x Xml) -> Result<()> {
3382        let right = matches!(element.get("location"), Some("right") | None);
3383        let mut barline = barline_of(element)?;
3384        // A repeat closing a measure ends the passage, whatever the file
3385        // says.
3386        if right && barline.repeat_direction() == Some(RepeatDirection::Start) {
3387            barline = Barline::repeat(RepeatDirection::End, None);
3388        }
3389
3390        if let Some(ending) = element.find("ending") {
3391            let index = self.part.measures.len();
3392            let open = self
3393                .part
3394                .brackets
3395                .iter()
3396                .position(|bracket| !bracket.complete);
3397            let at = match open {
3398                Some(at) => {
3399                    if !self.part.brackets[at].measures.contains(&index) {
3400                        self.part.brackets[at].measures.push(index);
3401                    }
3402                    at
3403                }
3404                None => {
3405                    self.part.brackets.push(Bracket {
3406                        numbers: vec![0],
3407                        measures: vec![index],
3408                        complete: false,
3409                    });
3410                    self.part.brackets.len() - 1
3411                }
3412            };
3413            let bracket = &mut self.part.brackets[at];
3414            if ending.get("type") == Some("start") {
3415                bracket.numbers = bracket_numbers(ending.get("number").unwrap_or("1"));
3416                if let Some(text) = ending.text() {
3417                    let digits = text.strip_suffix('.').unwrap_or(text);
3418                    if !digits.is_empty()
3419                        && digits.chars().all(|c| c.is_ascii_digit())
3420                        && let Ok(number) = digits.parse::<u32>()
3421                    {
3422                        bracket.numbers = vec![number];
3423                    }
3424                }
3425            }
3426            if matches!(ending.get("type"), Some("stop" | "discontinue")) {
3427                bracket.complete = true;
3428            }
3429        }
3430
3431        // A barline may carry a segno or a coda, which MusicXML allows
3432        // inside `<barline>` as well as inside a `<direction>`. music21
3433        // puts each in the measure where the barline stands, at the offset
3434        // the measure has been read to, exactly as it puts one read from a
3435        // direction -- so a document saying it either way reads alike.
3436        for (tag, kind) in [
3437            ("segno", RepeatExpressionKind::Segno),
3438            ("coda", RepeatExpressionKind::Coda),
3439        ] {
3440            if element.find(tag).is_some() {
3441                self.insert(self.offset, NO_STAFF, RepeatExpression::new(kind));
3442            }
3443        }
3444
3445        match element.get("location") {
3446            Some("left") => self.measure.left = Some(barline),
3447            Some("right") | None => self.measure.right = Some(barline),
3448            // A barline in the middle of a measure is an element of its own,
3449            // which music21 appends: after the last thing read so far ends,
3450            // whatever the file's place for it, and at the very start of a
3451            // measure whose notes are all in voices.
3452            Some(_) => {
3453                let end = self.measure.highest_time_outside_voices();
3454                self.insert(end, NO_STAFF, barline);
3455            }
3456        }
3457        Ok(())
3458    }
3459}
3460
3461/// music21's `xmlToRepeat` and `xmlToBarline`: what a `<barline>` draws,
3462/// a repeat in the direction it is written.
3463pub(super) fn barline_of(element: &Xml) -> Result<Barline> {
3464    let style = element.child_text("bar-style");
3465    let barline = match element.find("repeat") {
3466        Some(repeat) => {
3467            let written = match repeat.get("direction").map(str::to_lowercase).as_deref() {
3468                Some("forward") => RepeatDirection::Start,
3469                Some("backward") => RepeatDirection::End,
3470                Some(other) => {
3471                    return Err(import_error(format!(
3472                        "cannot handle mx direction format: {other}"
3473                    )));
3474                }
3475                None => return Err(import_error("Repeat sign direction is required")),
3476            };
3477            // Only an end says how many times.
3478            let times = repeat
3479                .get("times")
3480                .and_then(parse_int)
3481                .map(|times| times.max(0) as u32)
3482                .filter(|_| written == RepeatDirection::End);
3483            // The sign is drawn as its direction draws it, not as the
3484            // file's bar style says.
3485            Barline::repeat(written, times)
3486        }
3487        None => {
3488            let mut barline = Barline::default();
3489            if !style.is_empty() {
3490                barline.set_bar_type(BarlineType::from_name(style)?);
3491            }
3492            barline
3493        }
3494    };
3495    Ok(barline)
3496}
3497
3498/// A name as written, its ends trimmed and its line breaks spaces:
3499/// music21's `_clean`.
3500fn cleaned(text: &str) -> String {
3501    text.trim().replace('\n', " ")
3502}
3503
3504/// music21's `getDefaultInstrument`: the instrument a `<score-part>`'s
3505/// MIDI instrument and score instrument name, before the part's own names
3506/// are put on it; what music21 warns of goes into `warnings`.
3507pub(super) fn default_instrument(score_part: &Xml, warnings: &mut Vec<Error>) -> Instrument {
3508    let adjusted = |text: &str| -> Option<u8> {
3509        parse_int(text).map(|value| value.saturating_sub(1).max(0) as u8)
3510    };
3511    let mut instrument: Option<Instrument> = None;
3512    let mut unpitched = false;
3513    if let Some(midi) = score_part.find("midi-instrument") {
3514        let unpitched_text = midi.child_text("midi-unpitched");
3515        let program_text = midi.child_text("midi-program");
3516        if !unpitched_text.is_empty() {
3517            unpitched = true;
3518            let pitch = adjusted(unpitched_text).unwrap_or(0);
3519            // music21 warns of a key outside the General MIDI map.
3520            if let Err(error) = crate::instrument::for_percussion_key(pitch) {
3521                warnings.push(error);
3522            }
3523            instrument = Some(percussion_instrument(pitch));
3524        } else if !program_text.is_empty() {
3525            let mut read = adjusted(program_text)
3526                .and_then(|program| Instrument::from_midi_program(program).ok())
3527                .unwrap_or_default();
3528            if let Some(channel) = midi
3529                .find("midi-channel")
3530                .and_then(Xml::text)
3531                .and_then(adjusted)
3532            {
3533                read.set_midi_channel(Some(channel));
3534            }
3535            instrument = Some(read);
3536        }
3537    }
3538    let mut instrument = instrument.unwrap_or_default();
3539    let score_instrument = score_part.find("score-instrument");
3540    if let Some(score_instrument) = score_instrument
3541        && !unpitched
3542    {
3543        let name = score_instrument.child_text("instrument-name");
3544        if !name.is_empty() {
3545            let mut from_name =
3546                Instrument::from_name(name, SearchLanguage::All).unwrap_or_default();
3547            from_name.set_midi_channel(instrument.midi_channel());
3548            if from_name.midi_program() == instrument.midi_program() || instrument.is_a("Piano") {
3549                instrument = from_name;
3550            }
3551        }
3552    }
3553    if let Some(score_instrument) = score_instrument {
3554        let named = |tag: &str| {
3555            score_instrument
3556                .find(tag)
3557                .and_then(Xml::text)
3558                .filter(|text| !text.is_empty())
3559        };
3560        if let Some(name) = named("instrument-name") {
3561            instrument.set_name(Some(cleaned(name)));
3562        }
3563        if let Some(abbreviation) = named("instrument-abbreviation") {
3564            instrument.set_abbreviation(Some(cleaned(abbreviation)));
3565        }
3566        if let Some(sound) = named("instrument-sound") {
3567            instrument.set_sound(Some(sound.to_string()));
3568        }
3569    }
3570    instrument
3571}
3572
3573/// General MIDI's drum for a key as the instrument music21 has for it:
3574/// its `PercussionMapper.midiPitchToInstrument`, and a bare unpitched
3575/// instrument carrying the key where the map names nothing -- which is
3576/// what music21's reader makes of the exception its mapper raises. The map
3577/// is the crate's one table, read through
3578/// `instrument::for_percussion_key_or_unmapped`.
3579fn percussion_instrument(key: u8) -> Instrument {
3580    crate::instrument::for_percussion_key_or_unmapped(key)
3581}
3582
3583/// What is read of a note before it is known whether it has a pitch.
3584enum ReadNote {
3585    Note(Note),
3586    Unpitched(Unpitched),
3587    Rest(Rest),
3588}
3589
3590impl ReadNote {
3591    fn written(&self) -> &Note {
3592        match self {
3593            Self::Note(note) => note,
3594            Self::Unpitched(stroke) => stroke.written(),
3595            Self::Rest(_) => unreachable!("a rest is not written as a note"),
3596        }
3597    }
3598
3599    fn written_mut(&mut self) -> &mut Note {
3600        match self {
3601            Self::Note(note) => note,
3602            Self::Unpitched(stroke) => stroke.written_mut(),
3603            Self::Rest(_) => unreachable!("a rest is not written as a note"),
3604        }
3605    }
3606}
3607
3608/// What a `<note>` says that a note, a stroke and a rest all take.
3609#[derive(Default)]
3610struct General {
3611    color: Option<String>,
3612    hidden: bool,
3613    volume: Option<Volume>,
3614    size: Option<NoteSize>,
3615    tie: Option<Tie>,
3616    duration: Option<Duration>,
3617    articulations: Vec<Articulation>,
3618    expressions: Vec<Expression>,
3619    arpeggio_spanners: Vec<(String, ArpeggioType)>,
3620}
3621
3622fn reduce(numerator: i64, denominator: i64) -> (i64, i64) {
3623    fn gcd(a: i64, b: i64) -> i64 {
3624        if b == 0 { a.abs() } else { gcd(b, a % b) }
3625    }
3626    let divisor = gcd(numerator, denominator).max(1);
3627    (numerator / divisor, denominator / divisor)
3628}
3629
3630/// music21's `_setAttributeFromTagText` with `_floatOrIntStr`: the length
3631/// a child gives, where it gives one.
3632fn tenths(element: &Xml, tag: &str) -> Option<Tenths> {
3633    element
3634        .find(tag)
3635        .and_then(Xml::text)
3636        .filter(|text| !text.is_empty())
3637        .and_then(Tenths::parse)
3638}
3639
3640/// music21's `xmlPageLayoutToPageLayout`.
3641pub(super) fn read_page_layout(written: &Xml, read: &mut PageLayout) {
3642    if let Some(height) = tenths(written, "page-height") {
3643        read.page_height = Some(height);
3644    }
3645    if let Some(width) = tenths(written, "page-width") {
3646        read.page_width = Some(width);
3647    }
3648    if let Some(margins) = written.find("page-margins") {
3649        for (tag, place) in [
3650            ("top-margin", &mut read.top_margin),
3651            ("bottom-margin", &mut read.bottom_margin),
3652            ("left-margin", &mut read.left_margin),
3653            ("right-margin", &mut read.right_margin),
3654        ] {
3655            if let Some(margin) = tenths(margins, tag) {
3656                *place = Some(margin);
3657            }
3658        }
3659    }
3660}
3661
3662/// music21's `xmlPrintToPageLayout`: the page a `<print>` starts.
3663pub(super) fn print_page_layout(print: &Xml) -> PageLayout {
3664    let mut read = PageLayout {
3665        is_new: print.get("new-page").map(|value| value == "yes"),
3666        page_number: print
3667            .get("page-number")
3668            .and_then(|value| value.trim().parse().ok()),
3669        ..PageLayout::default()
3670    };
3671    if let Some(written) = print.find("page-layout") {
3672        read_page_layout(written, &mut read);
3673    }
3674    read
3675}
3676
3677/// music21's `xmlPrintToSystemLayout`: the system a `<print>` starts.
3678pub(super) fn print_system_layout(print: &Xml) -> SystemLayout {
3679    let mut read = SystemLayout {
3680        is_new: print.get("new-system").map(|value| value == "yes"),
3681        ..SystemLayout::default()
3682    };
3683    if let Some(written) = print.find("system-layout") {
3684        read_system_layout(written, &mut read);
3685    }
3686    read
3687}
3688
3689/// music21's `xmlSystemLayoutToSystemLayout`.
3690pub(super) fn read_system_layout(written: &Xml, read: &mut SystemLayout) {
3691    if let Some(margins) = written.find("system-margins") {
3692        for (tag, place) in [
3693            ("top-margin", &mut read.top_margin),
3694            ("bottom-margin", &mut read.bottom_margin),
3695            ("left-margin", &mut read.left_margin),
3696            ("right-margin", &mut read.right_margin),
3697        ] {
3698            if let Some(margin) = tenths(margins, tag) {
3699                *place = Some(margin);
3700            }
3701        }
3702    }
3703    if let Some(distance) = tenths(written, "system-distance") {
3704        read.distance = Some(distance);
3705    }
3706    if let Some(distance) = tenths(written, "top-system-distance") {
3707        read.top_distance = Some(distance);
3708    }
3709}
3710
3711/// music21's `xmlStaffLayoutToStaffLayout`.
3712pub(super) fn staff_layout(written: &Xml) -> StaffLayout {
3713    StaffLayout {
3714        distance: tenths(written, "staff-distance"),
3715        staff_number: written
3716            .get("number")
3717            .and_then(|value| value.trim().parse().ok()),
3718        ..StaffLayout::default()
3719    }
3720}
3721
3722/// music21's `xmlStaffLayoutFromStaffDetails`.
3723pub(super) fn read_staff_details(details: &Xml, read: &mut StaffLayout) {
3724    if let Some(number) = details
3725        .get("number")
3726        .and_then(|value| value.trim().parse().ok())
3727    {
3728        read.staff_number = Some(number);
3729    }
3730    match details.get("print-object") {
3731        Some("no") => read.hidden = Some(true),
3732        Some("yes") => read.hidden = Some(false),
3733        _ => {}
3734    }
3735    if let Some(lines) = details
3736        .find("staff-lines")
3737        .and_then(Xml::text)
3738        .and_then(|text| text.trim().parse().ok())
3739    {
3740        read.staff_lines = Some(lines);
3741    }
3742    if let Some(kind) = details
3743        .find("staff-type")
3744        .and_then(Xml::text)
3745        .and_then(|text| StaffType::from_name(text.trim()))
3746    {
3747        read.staff_type = kind;
3748    }
3749    if let Some(size) = tenths(details, "staff-size") {
3750        read.staff_size = Some(size.value());
3751    }
3752}
3753
3754/// music21's `setPosition` and `setColor`: where a mark stands and its
3755/// colour, read into a style.
3756fn read_position(written: &Xml, style: &mut TextStyle) {
3757    let value = |name: &str| written.get(name).map(StyleValue::read);
3758    if let Some(read) = value("default-x") {
3759        style.absolute_x = Some(read);
3760    }
3761    if let Some(read) = value("default-y") {
3762        style.absolute_y = Some(read);
3763    }
3764    if let Some(read) = value("relative-x") {
3765        style.relative_x = Some(read);
3766    }
3767    if let Some(read) = value("relative-y") {
3768        style.relative_y = Some(read);
3769    }
3770    if let Some(color) = written.get("color") {
3771        style.color = Some(color.to_string());
3772    }
3773}
3774
3775/// music21's `setPrintStyleAlign`: where text stands, its font and colour,
3776/// and how it is aligned, read into a style.
3777pub(crate) fn read_print_style_align(written: &Xml, style: &mut TextStyle) -> Result<()> {
3778    let value = |name: &str| written.get(name).map(StyleValue::read);
3779    if let Some(read) = value("default-x") {
3780        style.absolute_x = Some(read);
3781    }
3782    if let Some(read) = value("default-y") {
3783        style.absolute_y = Some(read);
3784    }
3785    if let Some(read) = value("relative-x") {
3786        style.relative_x = Some(read);
3787    }
3788    if let Some(read) = value("relative-y") {
3789        style.relative_y = Some(read);
3790    }
3791    read_font(written, style)?;
3792    if let Some(color) = written.get("color") {
3793        style.color = Some(color.to_string());
3794    }
3795    if let Some(align) = written.get("valign") {
3796        style.set_align_vertical(Some(align))?;
3797    }
3798    if let Some(align) = written.get("halign") {
3799        style.set_align_horizontal(Some(align))?;
3800    }
3801    Ok(())
3802}
3803
3804/// music21's `creatorToContributor`: a `<creator>`, its type its role.
3805pub(super) fn creator_value(creator: &Xml) -> MetadataValue {
3806    let name = creator.stripped();
3807    match creator.get("type") {
3808        Some(role) => MetadataValue::with_role(name, role),
3809        None => MetadataValue::new(name),
3810    }
3811}
3812
3813/// music21's `rightsToCopyright`: a `<rights>`, its type its role. One
3814/// saying nothing is music21's copyright of `None`, which writes `None`.
3815pub(super) fn rights_value(rights: &Xml) -> MetadataValue {
3816    let text = match rights.text() {
3817        Some(text) => text.trim(),
3818        None => "None",
3819    };
3820    match rights.get("type") {
3821        Some(role) => MetadataValue::with_role(text, role),
3822        None => MetadataValue::new(text),
3823    }
3824}
3825
3826/// music21's `setFont`: the family, style, size and weight written.
3827pub(super) fn read_font(written: &Xml, style: &mut TextStyle) -> Result<()> {
3828    if let Some(family) = written.get("font-family") {
3829        style.font_family = Some(
3830            family
3831                .split(',')
3832                .map(|name| name.trim().to_string())
3833                .collect(),
3834        );
3835    }
3836    if let Some(font_style) = written.get("font-style") {
3837        style.set_font_style(Some(font_style))?;
3838    }
3839    if let Some(size) = written.get("font-size") {
3840        style.font_size = Some(StyleValue::read(size));
3841    }
3842    if let Some(weight) = written.get("font-weight") {
3843        style.set_font_weight(Some(weight))?;
3844    }
3845    Ok(())
3846}
3847
3848/// music21's `styleFromXmlDefaults`: the appearance and fonts a score's
3849/// `<defaults>` give, and its lyrics' languages, English where unsaid.
3850pub(super) fn stream_style(defaults: &Xml) -> Result<crate::style::StreamStyle> {
3851    let mut style = crate::style::StreamStyle::default();
3852    if let Some(appearance) = defaults.find("appearance") {
3853        read_appearance(appearance, &mut style);
3854    }
3855    let font = |written: &Xml| -> Result<TextStyle> {
3856        let mut read = TextStyle::default();
3857        read_font(written, &mut read)?;
3858        Ok(read)
3859    };
3860    if let Some(written) = defaults.find("music-font") {
3861        style.music_font = Some(font(written)?);
3862    }
3863    if let Some(written) = defaults.find("word-font") {
3864        style.word_font = Some(font(written)?);
3865    }
3866    for written in defaults.find_all("lyric-font") {
3867        style.lyric_fonts.push((
3868            written.get("name").map(str::to_string),
3869            Some(font(written)?),
3870        ));
3871    }
3872    for written in defaults.find_all("lyric-language") {
3873        let language = written.get("xml:lang").unwrap_or(DEFAULT_LYRIC_LANGUAGE);
3874        style.lyric_languages.push((
3875            written.get("name").map(str::to_string),
3876            Some(language.to_string()),
3877        ));
3878    }
3879    Ok(style)
3880}
3881
3882/// The language music21 takes a lyric to be in where nothing says.
3883const DEFAULT_LYRIC_LANGUAGE: &str = "en";
3884
3885/// music21's `xmlAppearanceToStyle`: line widths, note sizes, distances
3886/// and other appearances, each by its type.
3887pub(super) fn read_appearance(appearance: &Xml, style: &mut crate::style::StreamStyle) {
3888    let pairs = |tag: &str, read: fn(&str) -> StyleValue| -> Vec<(String, StyleValue)> {
3889        appearance
3890            .find_all(tag)
3891            .map(|written| {
3892                let kind = written.get("type").unwrap_or("").to_string();
3893                (kind, read(written.stripped()))
3894            })
3895            .collect()
3896    };
3897    // Each a number but the other appearances, which may be anything.
3898    style
3899        .line_widths
3900        .extend(pairs("line-width", StyleValue::read));
3901    style
3902        .note_sizes
3903        .extend(pairs("note-size", StyleValue::read));
3904    style.distances.extend(pairs("distance", StyleValue::read));
3905    style
3906        .other_appearances
3907        .extend(pairs("other-appearance", |text| {
3908            StyleValue::Text(text.to_string())
3909        }));
3910}
3911
3912/// music21's `xmlCreditToTextBox`: a text box of the credit's words, one
3913/// line each, drawn as its first words say, on the page it names or the
3914/// first. A fresh text box's place, 500 tenths each way, stands where the
3915/// words say none.
3916pub(super) fn text_box(credit: &Xml) -> Result<TextBox> {
3917    let mut read = TextBox::new("");
3918    read.style.set_align_horizontal(None)?;
3919    read.style.set_align_vertical(None)?;
3920    if let Some(page) = credit.get("page") {
3921        read.page = page.trim().parse().map_err(|_| {
3922            import_error(format!("invalid literal for int() with base 10: {page:?}"))
3923        })?;
3924    }
3925    let words: Vec<String> = credit
3926        .find_all("credit-words")
3927        .filter_map(|words| {
3928            words
3929                .text()
3930                .filter(|text| !text.is_empty())
3931                .map(str::to_string)
3932        })
3933        .collect();
3934    if words.is_empty() {
3935        return Ok(read);
3936    }
3937    read.content = words.join("\n");
3938    if let Some(first) = credit.find("credit-words") {
3939        read_print_style_align(first, &mut read.style)?;
3940        read.style.set_justify(first.get("justify"))?;
3941    }
3942    Ok(read)
3943}
3944
3945/// music21's `xmlDefaultsToScoreLayout`.
3946fn score_layout(defaults: &Xml) -> ScoreLayout {
3947    let mut read = ScoreLayout::default();
3948    if let Some(scaling) = defaults.find("scaling") {
3949        read.scaling_millimeters = tenths(scaling, "millimeters");
3950        read.scaling_tenths = tenths(scaling, "tenths");
3951    }
3952    if let Some(written) = defaults.find("page-layout") {
3953        let mut page = PageLayout::default();
3954        read_page_layout(written, &mut page);
3955        read.page_layout = Some(page);
3956    }
3957    if let Some(written) = defaults.find("system-layout") {
3958        let mut system = SystemLayout::default();
3959        read_system_layout(written, &mut system);
3960        read.system_layout = Some(system);
3961    }
3962    read.staff_layouts = defaults
3963        .find_all("staff-layout")
3964        .map(staff_layout)
3965        .collect();
3966    read
3967}
3968
3969/// music21's `getStaffNumber`.
3970pub(super) fn staff_number(element: &Xml) -> i32 {
3971    match element.tag.as_str() {
3972        "harmony" | "forward" | "note" | "direction" => {
3973            parse_int(element.child_text("staff")).unwrap_or(NO_STAFF)
3974        }
3975        "clef" | "staff-details" | "staff-layout" => {
3976            element.get("number").and_then(parse_int).unwrap_or(1)
3977        }
3978        "measure-style" | "key" | "time" | "transpose" => element
3979            .get("number")
3980            .and_then(parse_int)
3981            .unwrap_or(NO_STAFF),
3982        _ => NO_STAFF,
3983    }
3984}
3985
3986/// music21's `xmlToPitch`.
3987pub(super) fn pitch_of(note: &Xml) -> Result<Pitch> {
3988    let Some(written) = note.find("pitch") else {
3989        return Pitch::from_name("C4");
3990    };
3991    let step = written.child_text("step");
3992    let octave = written.child_text("octave");
3993    let mut pitch = Pitch::from_name(format!("{step}{octave}"))?;
3994    let alter = parse_float(written.child_text("alter"));
3995    let accidental = note
3996        .find("accidental")
3997        .filter(|written| !written.stripped().is_empty());
3998    match accidental {
3999        Some(written) => {
4000            if let Ok(mut read) = accidental_of(written) {
4001                read.set_display_status(Some(true));
4002                if let Some(alter) = alter
4003                    && alter != read.alter()
4004                {
4005                    read.set_alter_independently(alter);
4006                }
4007                pitch.set_written_accidental(Some(read));
4008            }
4009        }
4010        None => {
4011            if let Some(alter) = alter {
4012                let mut read = Accidental::new(alter)
4013                    .map_err(|_| import_error(format!("incorrect accidental {alter} for pitch")))?;
4014                read.set_display_status(Some(false));
4015                pitch.set_written_accidental(Some(read));
4016            }
4017        }
4018    }
4019    Ok(pitch)
4020}
4021
4022/// music21's `xmlToAccidental`.
4023pub(super) fn accidental_of(written: &Xml) -> Result<Accidental> {
4024    let name = written.stripped().to_lowercase();
4025    let mut accidental = Accidental::natural();
4026    accidental.set_allowing_non_standard_value(accidental_name(&name))?;
4027    if let Some(color) = written.get("color") {
4028        accidental.set_color(Some(color.to_string()));
4029    }
4030    match (yes(written.get("parentheses")), yes(written.get("bracket"))) {
4031        (true, true) => accidental.set_display_style("both")?,
4032        (true, false) => accidental.set_display_style("parentheses")?,
4033        (false, true) => accidental.set_display_style("bracket")?,
4034        (false, false) => {}
4035    }
4036    Ok(accidental)
4037}
4038
4039/// An accidental's MusicXML name as music21 names it: its
4040/// `mxAccidentalNameToM21`.
4041fn accidental_name(name: &str) -> &str {
4042    match name {
4043        "quarter-sharp" => "half-sharp",
4044        "three-quarters-sharp" => "one-and-a-half-sharp",
4045        "quarter-flat" => "half-flat",
4046        "three-quarters-flat" => "one-and-a-half-flat",
4047        "flat-flat" => "double-flat",
4048        "sharp-sharp" => "double-sharp",
4049        other => other,
4050    }
4051}
4052
4053/// music21's `xmlToBeams`.
4054pub(super) fn beams_of(written: &[&Xml]) -> Result<Beams> {
4055    let mut beams = Beams::new();
4056    for (index, beam) in written.iter().enumerate() {
4057        let text = beam.text().map_or("begin", str::trim);
4058        let (beam_type, direction) = match text {
4059            "begin" => (BeamType::Start, None),
4060            "continue" => (BeamType::Continue, None),
4061            "end" => (BeamType::Stop, None),
4062            "forward hook" => (BeamType::PartialBeam, Some(BeamDirection::Right)),
4063            "backward hook" => (BeamType::PartialBeam, Some(BeamDirection::Left)),
4064            other => {
4065                return Err(import_error(format!(
4066                    "unexpected beam type encountered ({other})"
4067                )));
4068            }
4069        };
4070        let mut read = Beam::new(beam_type, direction);
4071        read.set_number(Some(index as u32 + 1));
4072        beams.beams_mut().push(read);
4073    }
4074    Ok(beams)
4075}
4076
4077/// music21's `xmlToTie`.
4078pub(super) fn tie_of(note: &Xml) -> Option<Tie> {
4079    let types: Vec<&str> = note
4080        .find_all("tie")
4081        .filter_map(|tie| tie.get("type"))
4082        .collect();
4083    let tie_type = if types.len() == 1 {
4084        TieType::from_name(types[0]).ok()?
4085    } else if types.contains(&"stop") && types.contains(&"start") {
4086        TieType::Continue
4087    } else {
4088        TieType::Start
4089    };
4090    let mut tie = Tie::new(tie_type);
4091    if let Some(first) = note
4092        .find("notations")
4093        .and_then(|notations| notations.find("tied"))
4094    {
4095        if let Some(style) = first.get("line-type").filter(|style| *style != "wavy")
4096            && let Ok(style) = TieStyle::from_name(style)
4097        {
4098            tie.set_style(style);
4099        }
4100        match first.get("placement") {
4101            Some(placement) => tie.set_placement(Placement::from_name(placement).ok()),
4102            None => match first.get("orientation") {
4103                Some("over") => tie.set_placement(Some(Placement::Above)),
4104                Some("under") => tie.set_placement(Some(Placement::Below)),
4105                _ => {}
4106            },
4107        }
4108    }
4109    Some(tie)
4110}
4111
4112/// music21's `updateLyricsFromList`: each `<lyric>` read, one numbered
4113/// nought taking its place among them.
4114pub(super) fn lyrics_from<'x>(written: impl Iterator<Item = &'x Xml>) -> Result<Vec<Lyric>> {
4115    let mut out = Vec::new();
4116    for (place, lyric) in written.enumerate() {
4117        let mut read = lyric_of(lyric)?;
4118        // A bare lyric, which only extends one, keeps its number.
4119        let sung = lyric.find("text").is_some();
4120        if sung && read.number() == 0 {
4121            read.set_number(IntegerType::try_from(place + 1).unwrap_or(IntegerType::MAX));
4122        }
4123        out.push(read);
4124    }
4125    Ok(out)
4126}
4127
4128/// music21's `xmlToLyric`: one `<lyric>`, numbered nought where it says
4129/// no number.
4130pub(super) fn lyric_of(lyric: &Xml) -> Result<Lyric> {
4131    let texts: Vec<&Xml> = lyric.find_all("text").collect();
4132    let syllabics: Vec<&Xml> = lyric.find_all("syllabic").collect();
4133    let elisions: Vec<&Xml> = lyric.find_all("elision").collect();
4134    let mut read = Lyric::unsung();
4135    if texts.is_empty() {
4136        // A lyric that only extends one: music21 hands back a bare one.
4137        return Ok(read);
4138    }
4139    if texts.len() == 1 {
4140        if let Some(text) = texts[0].text() {
4141            read.set_text(text.trim());
4142        }
4143        if let Some(syllabic) = syllabics.first()
4144            && let Ok(syllabic) = Syllabic::from_name(syllabic.stripped())
4145        {
4146            read.set_syllabic(syllabic);
4147        }
4148    } else if texts.len() > 1 {
4149        let mut components = Vec::new();
4150        for (index, text) in texts.iter().enumerate() {
4151            let mut component = Lyric::unsung();
4152            if let Some(text) = text.text() {
4153                component.set_text(text.trim());
4154            }
4155            if let Some(syllabic) = syllabics.get(index) {
4156                if let Ok(syllabic) = Syllabic::from_name(syllabic.stripped()) {
4157                    component.set_syllabic(syllabic);
4158                }
4159                if index >= 1
4160                    && let Some(elision) = elisions.get(index - 1)
4161                {
4162                    component.set_elision_before(elision.text().unwrap_or(""));
4163                }
4164            }
4165            components.push(component);
4166        }
4167        read.set_components(components);
4168    }
4169    match lyric.get("number") {
4170        Some(number) => match number.trim().parse::<IntegerType>() {
4171            Ok(number) => read.set_number(number),
4172            Err(_) => {
4173                read.set_number(0);
4174                read.set_identifier(Some(number.to_string()));
4175            }
4176        },
4177        None => read.set_number(0),
4178    }
4179    if let Some(name) = lyric.get("name") {
4180        read.set_identifier(Some(name.to_string()));
4181    }
4182    if let Some(justify) = lyric.get("justify") {
4183        read.set_justify(Some(Justification::from_name(justify)?));
4184    }
4185    if let Some(placement) = lyric.get("placement") {
4186        read.set_placement(Placement::from_name(placement).ok());
4187    }
4188    if lyric.get("print-object") == Some("no") {
4189        read.set_hidden(true);
4190    }
4191    if let Some(color) = lyric.get("color") {
4192        read.set_color(Some(color.to_string()));
4193    }
4194    Ok(read)
4195}
4196
4197/// music21's `xmlToArticulation`.
4198pub(super) fn articulation_of(mark: &Xml) -> Option<Articulation> {
4199    let class = match mark.tag.as_str() {
4200        "accent" => "Accent",
4201        "strong-accent" => "StrongAccent",
4202        "staccato" => "Staccato",
4203        "staccatissimo" => "Staccatissimo",
4204        "spiccato" => "Spiccato",
4205        "tenuto" => "Tenuto",
4206        "detached-legato" => "DetachedLegato",
4207        "scoop" => "Scoop",
4208        "plop" => "Plop",
4209        "doit" => "Doit",
4210        "falloff" => "Falloff",
4211        "breath-mark" => "BreathMark",
4212        "caesura" => "Caesura",
4213        "stress" => "Stress",
4214        "unstress" => "Unstress",
4215        "other-articulation" => "Articulation",
4216        _ => return None,
4217    };
4218    let mut articulation = Articulation::of_kind(ArticulationKind::from_class_name(class)?);
4219    if let Some(placement) = mark.get("placement") {
4220        articulation.set_placement(Some(placement.to_string()));
4221    }
4222    let text = mark.stripped();
4223    match mark.tag.as_str() {
4224        "strong-accent" => {
4225            if let Some(direction) = mark.get("type") {
4226                articulation.set_point_direction(Some(direction.to_string()));
4227            }
4228        }
4229        "breath-mark" if !text.is_empty() => articulation.set_symbol(Some(text.to_string())),
4230        "other-articulation" if !text.is_empty() => {
4231            articulation.set_display_text(Some(text.to_string()));
4232        }
4233        _ => {}
4234    }
4235    Some(articulation)
4236}
4237
4238/// music21's `xmlTechnicalToArticulation`.
4239/// A bend's release is read in `divisions` to the quarter.
4240pub(super) fn technical_of(mark: &Xml, divisions: FloatType) -> Option<Articulation> {
4241    let class = match mark.tag.as_str() {
4242        "up-bow" => "UpBow",
4243        "down-bow" => "DownBow",
4244        "harmonic" => "StringHarmonic",
4245        "open-string" => "OpenString",
4246        "thumb-position" => "StringThumbPosition",
4247        "fingering" => "Fingering",
4248        "pluck" => "FrettedPluck",
4249        "double-tongue" => "DoubleTongue",
4250        "triple-tongue" => "TripleTongue",
4251        "stopped" => "Stopped",
4252        "snap-pizzicato" => "SnapPizzicato",
4253        "string" => "StringIndication",
4254        "bend" => "FretBend",
4255        "tap" => "FretTap",
4256        "fret" => "FretIndication",
4257        "heel" => "OrganHeel",
4258        "toe" => "OrganToe",
4259        "fingernails" => "HarpFingerNails",
4260        "handbell" => "HandbellIndication",
4261        "other-technical" => "TechnicalIndication",
4262        _ => return None,
4263    };
4264    let mut technical = Articulation::of_kind(ArticulationKind::from_class_name(class)?);
4265    let text = mark.stripped();
4266    match mark.tag.as_str() {
4267        "fingering" => {
4268            technical.set_finger(Some(Finger::from_written(mark.text().unwrap_or(""))));
4269            if let Some(substitution) = mark.get("substitution") {
4270                technical.set_substitution(substitution == "yes");
4271            }
4272            if let Some(alternate) = mark.get("alternate") {
4273                technical.set_alternate(alternate == "yes");
4274            }
4275        }
4276        "handbell" | "other-technical" if !text.is_empty() => {
4277            technical.set_display_text(Some(text.to_string()));
4278        }
4279        "fret" | "string" => {
4280            if let Some(number) = parse_int(text) {
4281                technical.set_number(number);
4282            }
4283        }
4284        "harmonic" => {
4285            if mark.find("artificial").is_some() {
4286                technical.set_harmonic_type(Some("artificial".to_string()));
4287            } else if mark.find("natural").is_some() {
4288                technical.set_harmonic_type(Some("natural".to_string()));
4289            }
4290            // music21's `setHarmonic`: which pitch the note is written at.
4291            let pitch_type = [
4292                ("base-pitch", "base"),
4293                ("sounding-pitch", "sounding"),
4294                ("touching-pitch", "touching"),
4295            ]
4296            .into_iter()
4297            .find(|(tag, _)| mark.find(tag).is_some());
4298            if let Some((_, said)) = pitch_type {
4299                technical.set_pitch_type(Some(said.to_string()));
4300            }
4301        }
4302        "bend" => read_bend(mark, &mut technical, divisions),
4303        "heel" | "toe" => {
4304            if let Some(substitution) = mark.get("substitution") {
4305                technical.set_substitution(substitution == "yes");
4306            }
4307        }
4308        _ => {}
4309    }
4310    if let Some(placement) = mark.get("placement") {
4311        technical.set_placement(Some(placement.to_string()));
4312    }
4313    Some(technical)
4314}
4315
4316/// music21's `setBend`: how far a bend goes, whether it is bent before
4317/// it sounds, the bar it is drawn with and when it is let go, in quarters.
4318fn read_bend(mark: &Xml, bend: &mut Articulation, divisions: FloatType) {
4319    if let Some(alter) = mark
4320        .find("bend-alter")
4321        .and_then(|alter| parse_float(alter.stripped()))
4322    {
4323        bend.set_bend_alter(crate::interval::ChromaticInterval::new(alter).ok());
4324    }
4325    if mark.find("pre-bend").is_some() {
4326        bend.set_pre_bend(true);
4327    }
4328    if let Some(bar) = mark.find("with-bar") {
4329        bend.set_with_bar(bar.text().map(str::to_string));
4330    }
4331    if let Some(release) = mark.find("release") {
4332        // A release that says no offset is let go at once.
4333        let at = release
4334            .get("offset")
4335            .and_then(parse_float)
4336            .map_or(0.0, |offset| op_frac(offset / divisions));
4337        bend.set_release(Some(at));
4338    }
4339}
4340
4341/// music21's `xmlToTempoIndication`, for a mark with one note value.
4342/// music21's `xmlToTempoIndication`: a `<metronome>` is a tempo mark, or
4343/// with two note values a metric modulation, placed as its direction says.
4344pub(super) fn metronome(written: &Xml, placement: Option<Placement>) -> Result<StreamElement> {
4345    let mut referents: Vec<Duration> = Vec::new();
4346    let mut numbers: Vec<FloatType> = Vec::new();
4347    for child in &written.children {
4348        match child.tag.as_str() {
4349            "beat-unit" => {
4350                referents.push(Duration::from_type(duration_type(child.stripped())?));
4351            }
4352            "beat-unit-dot" => {
4353                let last = referents
4354                    .last_mut()
4355                    .ok_or_else(|| import_error("encountered metronome components out of order"))?;
4356                let (kind, dots) = last
4357                    .type_and_dots()
4358                    .ok_or_else(|| import_error("a beat unit with no written value"))?;
4359                *last = Duration::from_type_with_dots(kind, dots + 1);
4360            }
4361            "per-minute" => {
4362                if let Some(number) = parse_float(child.stripped()) {
4363                    numbers.push(number);
4364                }
4365            }
4366            _ => {}
4367        }
4368    }
4369    let parentheses = written.get("parentheses") == Some("yes");
4370    if referents.len() > 1 {
4371        // All a file gives are the two note values: neither side has a
4372        // number until the mark in force before it is known.
4373        let mut sides = referents.into_iter();
4374        let mut modulation = MetricModulation::new();
4375        if let Some(old) = sides.next() {
4376            modulation.set_old_referent(old, None);
4377        }
4378        if let Some(new) = sides.next() {
4379            modulation.set_new_referent(new);
4380        }
4381        modulation.set_parentheses(parentheses);
4382        modulation.set_placement(placement);
4383        return Ok(modulation.into());
4384    }
4385    let mut mark = MetronomeMark::default();
4386    if let Some(number) = numbers.first() {
4387        mark.set_number(Some(*number));
4388    }
4389    if let Some(referent) = referents.into_iter().next() {
4390        mark.set_referent(referent);
4391    }
4392    if parentheses {
4393        mark.set_parentheses(true);
4394    }
4395    mark.set_placement(placement);
4396    Ok(mark.into())
4397}
4398
4399/// music21's `xmlToTimeSignature`.
4400pub(super) fn time_signature(written: &Xml) -> Result<Option<TimeSignature>> {
4401    if written.find("senza-misura").is_some() {
4402        return Err(import_error(
4403            "reading a senza misura time signature is not supported yet",
4404        ));
4405    }
4406    let mut numerators = Vec::new();
4407    let mut denominators = Vec::new();
4408    for child in &written.children {
4409        match child.tag.as_str() {
4410            "beats" => numerators.push(child.stripped()),
4411            "beat-type" => denominators.push(child.stripped()),
4412            "interchangeable" => break,
4413            _ => {}
4414        }
4415    }
4416    let ratio = numerators
4417        .iter()
4418        .zip(&denominators)
4419        .map(|(numerator, denominator)| format!("{numerator}/{denominator}"))
4420        .collect::<Vec<_>>()
4421        .join("+");
4422    let mut meter = TimeSignature::from_ratio_string(&ratio)
4423        .map_err(|_| import_error(format!("Cannot process time signature {ratio}")))?;
4424    if let Some(color) = written.get("color") {
4425        meter.set_color(Some(color.to_string()));
4426    }
4427    meter.set_hidden(written.get("print-object") == Some("no"));
4428    match written.get("symbol") {
4429        Some(symbol @ ("common" | "cut" | "single-number" | "normal")) => {
4430            meter.set_symbol(Some(symbol.to_string()));
4431        }
4432        Some("note") => meter.set_symbolize_denominator(true),
4433        _ => {}
4434    }
4435    Ok(Some(meter))
4436}
4437
4438/// music21's `xmlToClef`.
4439pub(super) fn clef_of(written: &Xml) -> Result<Clef> {
4440    let sign = written.child_text("sign");
4441    let mut clef = if matches!(
4442        sign.to_lowercase().as_str(),
4443        "tab" | "percussion" | "none" | "jianpu"
4444    ) {
4445        Clef::from_string(sign, 0)?
4446    } else {
4447        let line = match written.find("line") {
4448            Some(line) => line.stripped(),
4449            None if sign == "G" => "2",
4450            None => "4",
4451        };
4452        let octave_change = parse_int(written.child_text("clef-octave-change")).unwrap_or(0);
4453        Clef::from_string(&format!("{sign}{line}"), octave_change)?
4454    };
4455    if let Some(color) = written.get("color") {
4456        clef.set_color(Some(color.to_string()));
4457    }
4458    Ok(clef)
4459}
4460
4461/// music21's `xmlToKeySignature`: a key where the mode is said and is one
4462/// music21 knows, a signature otherwise.
4463pub(super) fn key_signature(written: &Xml) -> Result<StreamElement> {
4464    let color = written.get("color").map(str::to_string);
4465    if written.find("fifths").is_none() {
4466        let mut signature = non_traditional_key(written)?;
4467        key_octaves(written, &mut signature)?;
4468        signature.set_color(color);
4469        return Ok(signature.into());
4470    }
4471    let sharps = parse_int(written.child_text("fifths")).unwrap_or(0);
4472    let mut signature = KeySignature::new(sharps);
4473    let mode = written.find("mode").and_then(Xml::text).unwrap_or("");
4474    if !mode.is_empty()
4475        && let Ok(mut key) = signature.try_as_key(Some(mode), None)
4476    {
4477        key.set_color(color);
4478        return Ok(key.into());
4479    }
4480    key_octaves(written, &mut signature)?;
4481    signature.set_color(color);
4482    Ok(signature.into())
4483}
4484
4485/// The voices a measure's notes and forwards are written in, sorted:
4486/// music21's `voiceIndices`.
4487pub(super) fn voice_ids(measure: &Xml) -> Vec<String> {
4488    let mut ids: Vec<String> = Vec::new();
4489    for tag in ["note", "forward"] {
4490        for element in measure.find_all(tag) {
4491            let voice = element.child_text("voice");
4492            if !voice.is_empty() && !ids.iter().any(|held| held == voice) {
4493                ids.push(voice.to_string());
4494            }
4495        }
4496    }
4497    ids.sort();
4498    ids
4499}
4500
4501/// music21's `nonTraditionalKeySignature`: a `<key>` of steps, each with
4502/// its alteration and perhaps the accidental it is written with.
4503pub(super) fn non_traditional_key(written: &Xml) -> Result<KeySignature> {
4504    let mut steps = Vec::new();
4505    let mut alters = Vec::new();
4506    let mut accidentals: Vec<Option<&str>> = Vec::new();
4507    let mut last_tag = "";
4508    for child in &written.children {
4509        let tag = child.tag.as_str();
4510        // A step after an alteration that said no accidental has none.
4511        if last_tag == "key-alter" && tag == "key-step" {
4512            accidentals.push(None);
4513        }
4514        match tag {
4515            "key-step" if !child.stripped().is_empty() => steps.push(child.stripped()),
4516            "key-alter" => {
4517                if let Some(alter) = parse_float(child.stripped()) {
4518                    alters.push(alter);
4519                }
4520            }
4521            "key-accidental" => accidentals.push(child.text()),
4522            _ => {}
4523        }
4524        last_tag = tag;
4525    }
4526    if accidentals.len() < alters.len() {
4527        accidentals.push(None);
4528    }
4529    if steps.len() != alters.len() {
4530        return Err(import_error(
4531            "For non traditional signatures each step must have an alter",
4532        ));
4533    }
4534    let mut pitches = Vec::new();
4535    for (index, (step, alter)) in steps.into_iter().zip(alters).enumerate() {
4536        let mut pitch = Pitch::from_name(step)?;
4537        let accidental = match accidentals.get(index).copied().flatten() {
4538            Some(written) => {
4539                let mut accidental = Accidental::natural();
4540                accidental
4541                    .set_allowing_non_standard_value(accidental_name(&written.to_lowercase()))?;
4542                accidental.set_alter(alter)?;
4543                accidental
4544            }
4545            None => Accidental::new(alter)?,
4546        };
4547        pitch.set_written_accidental(Some(accidental));
4548        pitches.push(pitch);
4549    }
4550    Ok(KeySignature::from_altered_pitches(pitches))
4551}
4552
4553/// music21's `mxKeyOctaves`: the octave a `<key-octave>` puts each altered
4554/// pitch of the signature in, by its place among them.
4555pub(super) fn key_octaves(written: &Xml, signature: &mut KeySignature) -> Result<()> {
4556    let octaves: Vec<&Xml> = written.find_all("key-octave").collect();
4557    if octaves.is_empty() {
4558        return Ok(());
4559    }
4560    let mut altered = signature.altered_pitches()?;
4561    for octave in octaves {
4562        // A cancelled signature's octaves are not read yet, as music21's.
4563        if octave.get("cancel") == Some("yes") {
4564            continue;
4565        }
4566        let place = octave
4567            .get("number")
4568            .and_then(parse_int)
4569            .and_then(|number| usize::try_from(number - 1).ok());
4570        let Some(pitch) = place.and_then(|place| altered.get_mut(place)) else {
4571            continue;
4572        };
4573        if let Some(number) = parse_int(octave.stripped()) {
4574            pitch.set_octave(Some(number));
4575        }
4576    }
4577    signature.set_altered_pitches(altered);
4578    Ok(())
4579}
4580
4581/// What a `<time>` of no meter says, `0` or nothing, where it is one:
4582/// music21's `SenzaMisuraTimeSignature`'s text.
4583pub(super) fn senza_misura(written: &Xml) -> Option<String> {
4584    written
4585        .find("senza-misura")
4586        .map(|senza| senza.stripped().to_string())
4587}
4588
4589/// music21's `xmlTransposeToInterval`.
4590pub(super) fn transpose_interval(written: &Xml) -> Result<Interval> {
4591    let mut diatonic = written
4592        .find("diatonic")
4593        .and_then(|d| parse_int(d.stripped()));
4594    let chromatic = written
4595        .find("chromatic")
4596        .and_then(|c| parse_int(c.stripped()));
4597    let too_far = || import_error("a <transpose> too far for an interval");
4598    let mut octave_change = 0;
4599    if let Some(octaves) = written
4600        .find("octave-change")
4601        .and_then(|o| parse_int(o.stripped()))
4602    {
4603        octave_change = octaves.checked_mul(12).ok_or_else(too_far)?;
4604        if let Some(diatonic) = &mut diatonic {
4605            *diatonic = octaves
4606                .checked_mul(7)
4607                .and_then(|steps| diatonic.checked_add(steps))
4608                .ok_or_else(too_far)?;
4609        }
4610    }
4611    let semitones =
4612        |chromatic: IntegerType| chromatic.checked_add(octave_change).ok_or_else(too_far);
4613    match (diatonic, chromatic) {
4614        (Some(diatonic), Some(chromatic)) => {
4615            let actual = |steps: IntegerType| {
4616                let generic = if steps < 0 {
4617                    steps.checked_sub(1)
4618                } else {
4619                    steps.checked_add(1)
4620                };
4621                generic.ok_or_else(too_far)
4622            };
4623            let semitones = semitones(chromatic)?;
4624            Interval::from_generic_and_chromatic(actual(diatonic)?, semitones).or_else(|_| {
4625                let steps = diatonic - octave_change / 12 * 7;
4626                Interval::from_generic_and_chromatic(actual(steps)?, semitones)
4627            })
4628        }
4629        (None, Some(chromatic)) => Interval::from_semitones(semitones(chromatic)?),
4630        _ => Interval::from_name("P1"),
4631    }
4632}
4633
4634#[cfg(test)]
4635mod tests {
4636    use super::*;
4637    use crate::musicxml::{ExportOptions, to_musicxml};
4638
4639    /// A score of one part holding these measures.
4640    fn score(measures: &str) -> String {
4641        format!(
4642            "<?xml version=\"1.0\"?><score-partwise version=\"4.0\"><part-list>             <score-part id=\"P1\"><part-name>Flute</part-name></score-part></part-list>             <part id=\"P1\">{measures}</part></score-partwise>"
4643        )
4644    }
4645
4646    const NOTE: &str = "<note><pitch><step>C</step><octave>4</octave></pitch>                        <duration>1</duration><type>quarter</type></note>";
4647
4648    #[test]
4649    fn a_document_nested_too_deep_is_refused() {
4650        // The score and its part are two levels of their own.
4651        for depth in [crate::xml::MAX_DEPTH - 2, 100_000] {
4652            let document = score(&format!(
4653                "<measure number=\"1\">{NOTE}</measure>{}{}",
4654                "<a>".repeat(depth),
4655                "</a>".repeat(depth)
4656            ));
4657            assert_eq!(
4658                from_musicxml(&document).is_err(),
4659                depth > crate::xml::MAX_DEPTH - 2,
4660                "{depth}"
4661            );
4662        }
4663    }
4664
4665    #[test]
4666    fn a_midi_program_below_any_integer_reads_as_the_first() {
4667        let document = score(&format!("<measure number=\"1\">{NOTE}</measure>")).replace(
4668            "<part-name>Flute</part-name>",
4669            "<part-name>Flute</part-name><midi-instrument id=\"P1-I1\">\
4670             <midi-program>-2147483648</midi-program></midi-instrument>",
4671        );
4672        assert!(from_musicxml(&document).is_ok());
4673    }
4674
4675    #[test]
4676    fn a_rest_shown_past_the_last_octave_is_refused() {
4677        let rest = "<note><rest><display-step>C</display-step>\
4678                    <display-octave>2147483647</display-octave></rest>\
4679                    <duration>1</duration><type>quarter</type></note>";
4680        assert!(from_musicxml(&score(&format!("<measure number=\"1\">{rest}</measure>"))).is_err());
4681    }
4682
4683    #[test]
4684    fn a_refusal_names_its_measure_and_part() {
4685        let rest = "<note><rest><display-step>C</display-step>\
4686                    <display-octave>2147483647</display-octave></rest>\
4687                    <duration>1</duration><type>quarter</type></note>";
4688        let measures = format!(
4689            "<measure number=\"1\">{NOTE}</measure><measure number=\"2a\">{rest}</measure>"
4690        );
4691        let error = from_musicxml(&score(&measures)).unwrap_err();
4692        assert!(
4693            error
4694                .to_string()
4695                .starts_with("MusicXML export error: a rest shown at")
4696        );
4697        assert_eq!(
4698            error.position(),
4699            Some(&Position::measure("2a").in_part("P1"))
4700        );
4701    }
4702
4703    #[test]
4704    fn a_measure_after_the_largest_number_is_read() {
4705        let measures = format!(
4706            "<measure number=\"2147483647\">{NOTE}</measure><measure number=\"5X\">{NOTE}</measure>"
4707        );
4708        assert!(from_musicxml(&score(&measures)).is_ok());
4709    }
4710
4711    #[test]
4712    fn a_transposition_of_too_many_octaves_is_refused() {
4713        for change in [
4714            "<diatonic>1</diatonic><chromatic>2</chromatic>",
4715            "<chromatic>2</chromatic>",
4716        ] {
4717            let transpose = Xml::parse(&format!(
4718                "<transpose>{change}<octave-change>2147483647</octave-change></transpose>"
4719            ))
4720            .unwrap();
4721            assert!(transpose_interval(&transpose).is_err(), "{change}");
4722        }
4723    }
4724
4725    #[test]
4726    fn offsets_are_snapped_as_music21_snaps_them() {
4727        // music21's `opFrac`: a third is a third, not the float nearest it.
4728        assert_eq!(op_frac(0.333_333_333_333_3), 1.0 / 3.0);
4729        assert_eq!(op_frac(0.25), 0.25);
4730        assert_eq!(op_frac(1.0 / 3.0 + 1.0 / 3.0 + 1.0 / 3.0), 1.0);
4731        assert_eq!(op_frac(-2.0 / 3.0), -2.0 / 3.0);
4732    }
4733
4734    #[test]
4735    fn an_ending_is_numbered_as_music21_numbers_it() {
4736        assert_eq!(bracket_numbers(""), [0]);
4737        assert_eq!(bracket_numbers("2"), [2]);
4738        assert_eq!(bracket_numbers("1, 2"), [1, 2]);
4739        assert_eq!(bracket_numbers("1-3"), [1, 2, 3]);
4740        assert_eq!(bracket_numbers("first"), [1]);
4741    }
4742
4743    #[test]
4744    fn a_part_and_its_notes_are_read() {
4745        let read = from_musicxml(&score(&format!(
4746            "<measure number=\"1\"><attributes><divisions>1</divisions>             <key><fifths>-1</fifths><mode>major</mode></key>             <time><beats>2</beats><beat-type>4</beat-type></time>             <clef><sign>G</sign><line>2</line></clef></attributes>{NOTE}             <note><rest/><duration>1</duration><type>quarter</type></note></measure>"
4747        )))
4748        .unwrap();
4749        let part = read.parts()[0];
4750        assert_eq!(part.name(), Some("Flute"));
4751        let measure = part.measures()[0];
4752        assert_eq!(measure.number(), 1);
4753        let kinds: Vec<&str> = measure
4754            .events()
4755            .iter()
4756            .map(|event| match event.element() {
4757                StreamElement::Clef(_) => "clef",
4758                StreamElement::Key(_) => "key",
4759                StreamElement::TimeSignature(_) => "time",
4760                StreamElement::Note(_) => "note",
4761                StreamElement::Rest(_) => "rest",
4762                _ => "other",
4763            })
4764            .collect();
4765        // Sorted as music21 sorts a measure, whatever order the file had.
4766        assert_eq!(kinds, ["clef", "key", "time", "note", "rest"]);
4767        assert_eq!(measure.events()[4].offset(), 1.0);
4768    }
4769
4770    #[test]
4771    fn notes_sharing_a_stem_are_a_chord() {
4772        let read = from_musicxml(&score(&format!(
4773            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>{NOTE}             <note><chord/><pitch><step>E</step><octave>4</octave></pitch>             <duration>1</duration><type>quarter</type></note></measure>"
4774        )))
4775        .unwrap();
4776        let measure = read.parts()[0].measures()[0];
4777        let chords: Vec<_> = measure
4778            .events()
4779            .iter()
4780            .filter_map(|event| match event.element() {
4781                StreamElement::Chord(chord) => Some(chord),
4782                _ => None,
4783            })
4784            .collect();
4785        assert_eq!(chords.len(), 1);
4786        assert_eq!(chords[0].notes().len(), 2);
4787    }
4788
4789    #[test]
4790    fn two_voices_are_two_streams() {
4791        let voiced = |voice: u8| {
4792            format!(
4793                "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>                 <voice>{voice}</voice><type>quarter</type></note>"
4794            )
4795        };
4796        let read = from_musicxml(&score(&format!(
4797            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>{}             <backup><duration>1</duration></backup>{}</measure>",
4798            voiced(1),
4799            voiced(2)
4800        )))
4801        .unwrap();
4802        let measure = read.parts()[0].measures()[0];
4803        let voices = measure.voices();
4804        assert_eq!(voices.len(), 2);
4805        assert_eq!(voices[1].id(), Some("2"));
4806        // The second voice was backed up to the start of the measure.
4807        assert_eq!(voices[1].events()[0].offset(), 0.0);
4808    }
4809
4810    #[test]
4811    fn a_slur_joins_the_notes_it_is_written_on() {
4812        let slurred = |kind: &str| {
4813            format!(
4814                "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>                 <type>quarter</type><notations><slur number=\"1\" type=\"{kind}\"/>                 </notations></note>"
4815            )
4816        };
4817        let read = from_musicxml(&score(&format!(
4818            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>{}{NOTE}{}             </measure>",
4819            slurred("start"),
4820            slurred("stop")
4821        )))
4822        .unwrap();
4823        let spanners = read.spanners();
4824        assert_eq!(spanners.len(), 1);
4825        assert_eq!(spanners[0].kind(), SpannerKind::Slur);
4826        let leaves = read.leaves();
4827        let ends: Vec<usize> = spanners[0].spanned().iter().flatten().copied().collect();
4828        assert_eq!(ends.len(), 2);
4829        assert!(matches!(leaves[ends[0]].1, StreamElement::Note(_)));
4830        assert_eq!(leaves[ends[1]].0, 2.0);
4831    }
4832
4833    #[test]
4834    fn a_hairpin_started_after_a_part_ends_takes_the_next_part_first_note() {
4835        let wedge = |kind: &str| {
4836            format!(
4837                "<direction><direction-type><wedge type=\"{kind}\"/></direction-type></direction>"
4838            )
4839        };
4840        let measure = |step: &str, after: &str| {
4841            format!(
4842                "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>\
4843                 <note><pitch><step>{step}</step><octave>4</octave></pitch><duration>1</duration>\
4844                 <type>quarter</type></note>{after}</measure>"
4845            )
4846        };
4847        let document = format!(
4848            "<?xml version=\"1.0\"?><score-partwise version=\"4.0\"><part-list>\
4849             <score-part id=\"P1\"><part-name>One</part-name></score-part>\
4850             <score-part id=\"P2\"><part-name>Two</part-name></score-part></part-list>\
4851             <part id=\"P1\">{}</part><part id=\"P2\">{}</part></score-partwise>",
4852            measure("C", &(wedge("diminuendo") + &wedge("stop"))),
4853            measure("D", ""),
4854        );
4855        let read = from_musicxml(&document).unwrap();
4856        let spanners = read.spanners();
4857        assert_eq!(spanners.len(), 1);
4858        assert_eq!(spanners[0].kind(), SpannerKind::Diminuendo);
4859        let leaves = read.leaves();
4860        let named: Vec<String> = spanners[0]
4861            .spanned()
4862            .iter()
4863            .flatten()
4864            .map(|position| match leaves[*position].1 {
4865                StreamElement::Note(note) => note.pitch().name_with_octave(),
4866                _ => String::new(),
4867            })
4868            .collect();
4869        // The stop names the note it follows, and the queue then puts the
4870        // next note read, in the next part, first.
4871        assert_eq!(named, ["D4", "C4"]);
4872    }
4873
4874    #[test]
4875    fn a_part_on_two_staves_is_two_parts_in_a_brace() {
4876        let on_staff = |staff: u8| {
4877            format!(
4878                "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>                 <type>quarter</type><staff>{staff}</staff></note>"
4879            )
4880        };
4881        let read = from_musicxml(&score(&format!(
4882            "<measure number=\"1\"><attributes><divisions>1</divisions><staves>2</staves>             </attributes>{}<backup><duration>1</duration></backup>{}</measure>",
4883            on_staff(1),
4884            on_staff(2)
4885        )))
4886        .unwrap();
4887        let parts = read.parts();
4888        assert_eq!(parts.len(), 2);
4889        assert_eq!(parts[0].kind(), StreamKind::PartStaff);
4890        assert_eq!(parts[1].id(), Some("P1-Staff2"));
4891        let groups = read.staff_groups();
4892        assert_eq!(groups.len(), 1);
4893        assert_eq!(groups[0].parts(), [0, 1]);
4894        assert_eq!(groups[0].symbol(), Some("brace"));
4895    }
4896
4897    #[test]
4898    fn what_is_read_is_written_back() {
4899        let document = score(&format!(
4900            "<measure number=\"1\"><attributes><divisions>1</divisions>             <time><beats>1</beats><beat-type>4</beat-type></time>             <clef><sign>G</sign><line>2</line></clef></attributes>{NOTE}</measure>"
4901        ));
4902        let written = to_musicxml(
4903            &from_musicxml(&document).unwrap(),
4904            &ExportOptions::default(),
4905        )
4906        .unwrap();
4907        assert!(written.contains("<part-name>Flute</part-name>"));
4908        assert!(written.contains("<step>C</step>"));
4909        assert!(written.contains("<type>quarter</type>"));
4910        assert!(written.contains("<beat-type>4</beat-type>"));
4911    }
4912
4913    /// A quarter note carrying these notations.
4914    fn noted(notations: &str) -> String {
4915        format!(
4916            "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>\
4917             <type>quarter</type><notations>{notations}</notations></note>"
4918        )
4919    }
4920
4921    /// One measure of a quarter to the division holding these.
4922    fn measure_of(contents: &str) -> String {
4923        score(&format!(
4924            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>\
4925             {contents}</measure>"
4926        ))
4927    }
4928
4929    fn written_back(read: &Stream) -> String {
4930        to_musicxml(read, &ExportOptions::default()).unwrap()
4931    }
4932
4933    #[test]
4934    fn a_glissando_and_a_slide_are_read() {
4935        let read = from_musicxml(&measure_of(&format!(
4936            "{}{}{}",
4937            noted("<glissando number=\"1\" type=\"start\" line-type=\"dashed\">gl.</glissando>"),
4938            noted("<glissando number=\"1\" type=\"stop\"/><slide number=\"2\" type=\"start\"/>"),
4939            noted("<slide number=\"2\" type=\"stop\"/>"),
4940        )))
4941        .unwrap();
4942        let spanners = read.spanners();
4943        assert_eq!(spanners.len(), 2);
4944        assert!(
4945            spanners
4946                .iter()
4947                .all(|spanner| spanner.kind() == SpannerKind::Glissando && spanner.len() == 2)
4948        );
4949        // music21 reads the line and how it is played, and not the words.
4950        assert_eq!(spanners[0].line_type(), Some("dashed"));
4951        assert_eq!(
4952            spanners[0].glissando_details(),
4953            Some(&Glissando {
4954                slide_type: SlideType::Chromatic,
4955                label: None
4956            })
4957        );
4958        // A slide is drawn solid where nothing says.
4959        assert_eq!(spanners[1].line_type(), Some("solid"));
4960        assert_eq!(
4961            spanners[1]
4962                .glissando_details()
4963                .map(|slide| slide.slide_type),
4964            Some(SlideType::Continuous)
4965        );
4966        let written = written_back(&read);
4967        assert!(written.contains("<glissando line-type=\"dashed\" number=\"1\" type=\"start\" />"));
4968        assert!(written.contains("<slide line-type=\"solid\" number=\"2\" type=\"stop\" />"));
4969    }
4970
4971    #[test]
4972    fn a_glissando_drawn_no_way_music21_knows_is_refused() {
4973        let read = from_musicxml(&measure_of(&noted(
4974            "<glissando number=\"1\" type=\"start\" line-type=\"zigzag\"/>",
4975        )));
4976        assert!(read.is_err());
4977    }
4978
4979    #[test]
4980    fn a_tremolo_that_starts_and_stops_is_a_spanner() {
4981        let read = from_musicxml(&measure_of(&format!(
4982            "{}{}{}",
4983            noted("<ornaments><tremolo type=\"start\" placement=\"above\">2</tremolo></ornaments>"),
4984            noted("<ornaments><tremolo type=\"stop\">2</tremolo></ornaments>"),
4985            noted("<ornaments><tremolo type=\"single\">1</tremolo></ornaments>"),
4986        )))
4987        .unwrap();
4988        let spanners = read.spanners();
4989        assert_eq!(spanners.len(), 1);
4990        assert_eq!(spanners[0].kind(), SpannerKind::TremoloSpanner);
4991        assert_eq!(spanners[0].number_of_marks(), Some(2));
4992        assert_eq!(spanners[0].placement(), Some(Placement::Above));
4993        assert_eq!(spanners[0].len(), 2);
4994        // The tremolo on one note is an ornament of that note still.
4995        let ornamented = read
4996            .leaves()
4997            .iter()
4998            .filter(|(_, element)| match element {
4999                StreamElement::Note(note) => !note.expressions().is_empty(),
5000                _ => false,
5001            })
5002            .count();
5003        assert_eq!(ornamented, 1);
5004        let written = written_back(&read);
5005        assert!(written.contains("<tremolo placement=\"above\" type=\"start\">2</tremolo>"));
5006        assert!(written.contains("<tremolo type=\"stop\">2</tremolo>"));
5007    }
5008
5009    #[test]
5010    fn a_multiple_rest_takes_the_rests_it_counts() {
5011        let rest = "<note><rest/><duration>4</duration></note>";
5012        let styled = |count: u32| {
5013            format!(
5014                "<attributes><measure-style><multiple-rest>{count}</multiple-rest>\
5015                 </measure-style></attributes>{rest}"
5016            )
5017        };
5018        let read = from_musicxml(&score(&format!(
5019            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>{}</measure>\
5020             <measure number=\"2\">{rest}</measure>\
5021             <measure number=\"3\">{}</measure>",
5022            styled(2),
5023            styled(3),
5024        )))
5025        .unwrap();
5026        let spanners = read.spanners();
5027        assert_eq!(spanners.len(), 2);
5028        assert_eq!(spanners[0].kind(), SpannerKind::MultiMeasureRest);
5029        assert_eq!(spanners[0].num_rests(), 2);
5030        assert!(
5031            spanners[0]
5032                .multi_rest()
5033                .is_some_and(|said| !said.use_symbols)
5034        );
5035        // The last took one rest of its three before the part ended, and
5036        // music21's writer writes it as one.
5037        assert_eq!(spanners[1].num_rests(), 1);
5038        let written = written_back(&read);
5039        assert_eq!(written.matches("<multiple-rest").count(), 2);
5040        assert!(written.contains("<multiple-rest use-symbols=\"no\">2</multiple-rest>"));
5041        assert!(written.contains("<multiple-rest use-symbols=\"no\">1</multiple-rest>"));
5042    }
5043
5044    fn pedal(attributes: &str) -> String {
5045        format!("<direction><direction-type><pedal {attributes}/></direction-type></direction>")
5046    }
5047
5048    #[test]
5049    fn a_pedal_keeps_its_bounces_and_gaps() {
5050        let read = from_musicxml(&measure_of(&format!(
5051            "{}{NOTE}{}{NOTE}{}{NOTE}{}{NOTE}{}",
5052            pedal("type=\"start\" line=\"yes\" number=\"1\""),
5053            pedal("type=\"change\" line=\"yes\" number=\"1\""),
5054            pedal("type=\"discontinue\" line=\"yes\" number=\"1\""),
5055            pedal("type=\"resume\" line=\"yes\" number=\"1\""),
5056            pedal("type=\"stop\" line=\"yes\" number=\"1\""),
5057        )))
5058        .unwrap();
5059        let spanners = read.spanners();
5060        assert_eq!(spanners.len(), 1);
5061        assert_eq!(spanners[0].kind(), SpannerKind::PedalMark);
5062        let leaves = read.leaves();
5063        let joined: Vec<String> = spanners[0]
5064            .spanned()
5065            .iter()
5066            .flatten()
5067            .map(|position| match leaves[*position] {
5068                (offset, StreamElement::PedalObject(object)) => {
5069                    format!("{} at {offset}", object.kind().class_name())
5070                }
5071                (offset, _) => format!("note at {offset}"),
5072            })
5073            .collect();
5074        assert_eq!(
5075            joined,
5076            [
5077                "note at 0",
5078                "PedalBounce at 1",
5079                "PedalGapStart at 2",
5080                "PedalGapEnd at 3",
5081                "note at 3"
5082            ]
5083        );
5084        let written = written_back(&read);
5085        for kind in ["change", "discontinue", "resume"] {
5086            assert!(written.contains(&format!("<pedal line=\"yes\" type=\"{kind}\" />")));
5087        }
5088    }
5089
5090    #[test]
5091    fn a_sign_with_a_line_resumed_at_once_is_one_pedal() {
5092        let read = from_musicxml(&measure_of(&format!(
5093            "{NOTE}{}{}{NOTE}{}",
5094            pedal("type=\"start\" sign=\"yes\" number=\"1\""),
5095            pedal("type=\"resume\" line=\"yes\" number=\"1\""),
5096            pedal("type=\"stop\" line=\"yes\" number=\"1\""),
5097        )))
5098        .unwrap();
5099        let spanners = read.spanners();
5100        assert_eq!(
5101            spanners[0].pedal().and_then(|pedal| pedal.form),
5102            Some(PedalForm::SymbolLine)
5103        );
5104        assert!(
5105            read.leaves()
5106                .iter()
5107                .all(|(_, element)| !matches!(element, StreamElement::PedalObject(_)))
5108        );
5109        // The line resumes where the pedal mark stands, the start of the
5110        // part, a quarter before the note it goes down on.
5111        let written = written_back(&read);
5112        assert!(written.contains(
5113            "<pedal line=\"yes\" type=\"resume\" />\n        </direction-type>\n        \
5114             <offset sound=\"yes\">-10080</offset>"
5115        ));
5116    }
5117
5118    #[test]
5119    fn a_barline_inside_a_measure_stands_where_music21_appends_it() {
5120        let barline = "<barline location=\"middle\"><bar-style>dashed</bar-style></barline>";
5121        let inner = |document: &str| -> Vec<FloatType> {
5122            let read = from_musicxml(document).unwrap();
5123            let measure = read.parts()[0].measures()[0];
5124            measure
5125                .events()
5126                .iter()
5127                .filter(|event| matches!(event.element(), StreamElement::Barline(_)))
5128                .map(StreamEvent::offset)
5129                .collect()
5130        };
5131        // After what has been read, wherever the file would have it.
5132        assert_eq!(
5133            inner(&measure_of(&format!(
5134                "{NOTE}{NOTE}{barline}{NOTE}{NOTE}{barline}"
5135            ))),
5136            [2.0, 4.0]
5137        );
5138        // And at the start of a measure whose notes are all in voices.
5139        let voiced = |voice: u8| {
5140            format!(
5141                "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>\
5142                 <voice>{voice}</voice><type>quarter</type></note>"
5143            )
5144        };
5145        assert_eq!(
5146            inner(&measure_of(&format!(
5147                "{}{barline}<backup><duration>1</duration></backup>{}",
5148                voiced(1),
5149                voiced(2)
5150            ))),
5151            [0.0]
5152        );
5153        // Nothing is written for one.
5154        let read = from_musicxml(&measure_of(&format!("{NOTE}{barline}{NOTE}"))).unwrap();
5155        assert!(!written_back(&read).contains("<barline"));
5156    }
5157
5158    #[test]
5159    fn a_lyric_says_how_it_is_drawn() {
5160        let read = from_musicxml(&measure_of(
5161            "<note><pitch><step>C</step><octave>4</octave></pitch><duration>1</duration>\
5162             <type>quarter</type><lyric number=\"1\" justify=\"left\" placement=\"below\" \
5163             print-object=\"yes\"><syllabic>single</syllabic><text>la</text></lyric></note>",
5164        ))
5165        .unwrap();
5166        let leaves = read.leaves();
5167        let note = leaves
5168            .iter()
5169            .find_map(|(_, element)| match element {
5170                StreamElement::Note(note) => Some(note),
5171                _ => None,
5172            })
5173            .expect("the measure holds a note");
5174        let lyric = &note.lyrics()[0];
5175        assert_eq!(lyric.justify(), Some(Justification::Left));
5176        assert_eq!(lyric.placement(), Some(Placement::Below));
5177        assert!(!lyric.is_hidden());
5178        assert!(
5179            written_back(&read)
5180                .contains("<lyric justify=\"left\" name=\"1\" number=\"1\" placement=\"below\">")
5181        );
5182    }
5183
5184    #[test]
5185    fn a_rehearsal_mark_is_read_and_written_centred() {
5186        let read = from_musicxml(&measure_of(&format!(
5187            "<direction placement=\"above\"><direction-type>             <rehearsal enclosure=\"square\">A</rehearsal></direction-type></direction>{NOTE}"
5188        )))
5189        .unwrap();
5190        let leaves = read.leaves();
5191        let mark = leaves
5192            .iter()
5193            .find_map(|(_, element)| match element {
5194                StreamElement::RehearsalMark(mark) => Some(mark),
5195                _ => None,
5196            })
5197            .expect("the measure holds a rehearsal mark");
5198        assert_eq!(mark.content(), "A");
5199        assert_eq!(mark.enclosure(), Some("square"));
5200        assert_eq!(mark.placement(), Some(Placement::Above));
5201        assert!(written_back(&read).contains(
5202            "<rehearsal enclosure=\"square\" halign=\"center\" valign=\"middle\">A</rehearsal>"
5203        ));
5204        // music21 raises on an enclosure it has no name for.
5205        assert!(
5206            from_musicxml(&measure_of(
5207                "<direction><direction-type><rehearsal enclosure=\"star\">A</rehearsal>                 </direction-type></direction>"
5208            ))
5209            .is_err()
5210        );
5211    }
5212
5213    #[test]
5214    fn a_rests_colour_is_read_and_written_back() {
5215        let read = from_musicxml(&score(
5216            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>             <note color=\"#FF0000\"><rest/><duration>1</duration><type>quarter</type></note>             </measure>",
5217        ))
5218        .unwrap();
5219        let leaves = read.leaves();
5220        let rest = leaves
5221            .iter()
5222            .find_map(|(_, element)| match element {
5223                StreamElement::Rest(rest) => Some(rest),
5224                _ => None,
5225            })
5226            .expect("the measure holds a rest");
5227        assert_eq!(rest.color(), Some("#FF0000"));
5228        assert!(written_back(&read).contains("<note color=\"#FF0000\">"));
5229    }
5230
5231    #[test]
5232    fn a_chord_symbols_inversion_puts_that_note_in_the_bass() {
5233        let read = from_musicxml(&score(&format!(
5234            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>\
5235             <harmony><root><root-step>C</root-step></root><kind>major</kind>\
5236             <inversion>1</inversion></harmony>{NOTE}</measure>"
5237        )))
5238        .unwrap();
5239        let leaves = read.leaves();
5240        let symbol = leaves
5241            .iter()
5242            .find_map(|(_, element)| match element {
5243                StreamElement::ChordSymbol(symbol) => Some(symbol),
5244                _ => None,
5245            })
5246            .expect("the measure holds a chord symbol");
5247        assert_eq!(symbol.bass().map(Pitch::name), Some("E".to_string()));
5248    }
5249
5250    #[test]
5251    fn a_time_signature_may_be_left_unprinted() {
5252        let read = from_musicxml(&score(
5253            "<measure number=\"1\"><attributes><divisions>1</divisions>             <time print-object=\"no\"><beats>3</beats><beat-type>4</beat-type></time>             </attributes></measure>",
5254        ))
5255        .unwrap();
5256        let leaves = read.leaves();
5257        let meter = leaves
5258            .iter()
5259            .find_map(|(_, element)| match element {
5260                StreamElement::TimeSignature(meter) => Some(meter),
5261                _ => None,
5262            })
5263            .expect("the measure holds a time signature");
5264        assert!(meter.is_hidden());
5265        assert!(written_back(&read).contains("<time print-object=\"no\">"));
5266    }
5267
5268    #[test]
5269    fn a_metric_modulation_takes_its_numbers_from_the_tempo_before_it() {
5270        // Read off music21: a dotted quarter at 110, then a quarter becoming
5271        // a dotted quarter, sounds at 247.5 quarters a minute.
5272        let read = from_musicxml(&score(&format!(
5273            "<measure number=\"1\"><attributes><divisions>1</divisions></attributes>\
5274             <direction><direction-type><metronome><beat-unit>quarter</beat-unit>\
5275             <beat-unit-dot/><per-minute>110</per-minute></metronome></direction-type>\
5276             </direction>{NOTE}</measure><measure number=\"2\">\
5277             <direction placement=\"above\"><direction-type><metronome>\
5278             <beat-unit>quarter</beat-unit><beat-unit>quarter</beat-unit><beat-unit-dot/>\
5279             </metronome></direction-type></direction>{NOTE}</measure>"
5280        )))
5281        .unwrap();
5282        let leaves = read.leaves();
5283        let modulation = leaves
5284            .iter()
5285            .find_map(|(_, element)| match element {
5286                StreamElement::MetricModulation(modulation) => Some(modulation),
5287                _ => None,
5288            })
5289            .expect("the second measure holds a metric modulation");
5290        // As read, neither side has a number: a file gives the note values.
5291        assert_eq!(
5292            modulation.old_metronome().and_then(|old| old.number()),
5293            None
5294        );
5295        assert_eq!(modulation.placement(), Some(Placement::Above));
5296        let written = written_back(&read);
5297        assert!(written.contains(
5298            "<metronome parentheses=\"no\">\n            <beat-unit>quarter</beat-unit>\n            \
5299             <beat-unit>quarter</beat-unit>\n            <beat-unit-dot />\n          \
5300             </metronome>\n        </direction-type>\n        <sound tempo=\"247.5\" />"
5301        ));
5302    }
5303
5304    #[test]
5305    fn words_naming_a_coda_place_no_sign() {
5306        let words = |text: &str| {
5307            format!(
5308                "<direction placement=\"above\"><direction-type><words>{text}</words>                 </direction-type></direction>"
5309            )
5310        };
5311        let read = from_musicxml(&measure_of(&format!(
5312            "{}{NOTE}{}",
5313            words("Coda"),
5314            words("Fine")
5315        )))
5316        .unwrap();
5317        let placed: Vec<Option<Placement>> = read
5318            .leaves()
5319            .iter()
5320            .filter_map(|(_, element)| match element {
5321                StreamElement::RepeatExpression(mark) => Some(mark.placement()),
5322                _ => None,
5323            })
5324            .collect();
5325        // The coda is drawn as its sign, which music21 places nowhere; the
5326        // words of a fine stay where they were written.
5327        assert_eq!(placed, [None, Some(Placement::Above)]);
5328    }
5329
5330    #[test]
5331    fn a_document_that_is_not_a_score_is_refused() {
5332        assert!(from_musicxml("<opus/>").is_err());
5333        assert!(from_musicxml("not xml at all").is_err());
5334    }
5335
5336    #[test]
5337    fn a_group_symbol_keeps_where_it_is_drawn() {
5338        let document = format!(
5339            "<?xml version=\"1.0\"?><score-partwise version=\"4.0\"><part-list>\
5340             <part-group number=\"1\" type=\"start\"><group-symbol default-x=\"-8\" \
5341             color=\"#FF0000\">bracket</group-symbol></part-group>\
5342             <score-part id=\"P1\"><part-name>Flute</part-name></score-part>\
5343             <part-group number=\"1\" type=\"stop\"/></part-list>\
5344             <part id=\"P1\"><measure number=\"1\"><attributes><divisions>1\
5345             </divisions></attributes>{NOTE}</measure></part></score-partwise>"
5346        );
5347        let read = from_musicxml(&document).unwrap();
5348        let group = &read.staff_groups()[0];
5349        assert_eq!(group.symbol(), Some("bracket"));
5350        assert_eq!(group.style.absolute_x, Some(StyleValue::Whole(-8)));
5351        assert_eq!(group.style.color.as_deref(), Some("#FF0000"));
5352    }
5353
5354    #[test]
5355    fn credits_are_read_and_written_as_music21_keeps_them() {
5356        let document = format!(
5357            "<?xml version=\"1.0\"?><score-partwise version=\"4.0\">\
5358             <credit page=\"2\"><credit-words default-x=\"600.5\" default-y=\"1500\" \
5359             font-size=\"22.0\" font-style=\"bolditalic\" justify=\"Center\" valign=\"top\">\
5360             Sonata</credit-words><credit-words>in G</credit-words></credit>\
5361             <credit><credit-words halign=\"right\">Anon</credit-words></credit>\
5362             <part-list><score-part id=\"P1\"><part-name>Flute</part-name></score-part>\
5363             </part-list><part id=\"P1\"><measure number=\"1\"><attributes><divisions>1\
5364             </divisions></attributes>{NOTE}</measure></part></score-partwise>"
5365        );
5366        let read = from_musicxml(&document).unwrap();
5367        let boxes: Vec<&TextBox> = read
5368            .events()
5369            .iter()
5370            .filter_map(|event| match event.element() {
5371                StreamElement::TextBox(text) => Some(&**text),
5372                _ => None,
5373            })
5374            .collect();
5375        assert_eq!(boxes.len(), 2);
5376        assert_eq!(boxes[0].content, "Sonata\nin G");
5377        assert_eq!(boxes[0].page, 2);
5378        assert_eq!(boxes[0].style.font_size, Some(StyleValue::Whole(22)));
5379        assert_eq!(boxes[0].style.justify(), Some("center"));
5380        // A credit that says no place stands where a fresh text box does.
5381        assert_eq!(boxes[1].style.absolute_x, Some(StyleValue::Whole(500)));
5382        assert_eq!(boxes[1].page, 1);
5383
5384        let written = written_back(&read);
5385        for expected in [
5386            "<credit page=\"2\">",
5387            "default-x=\"600.5\"",
5388            "font-size=\"22\"",
5389            "font-style=\"italic\"",
5390            "font-weight=\"bold\"",
5391            "justify=\"center\"",
5392            "xml:space=\"preserve\"",
5393            "<credit-words default-x=\"500\" default-y=\"500\" halign=\"right\">Anon</credit-words>",
5394        ] {
5395            assert!(written.contains(expected), "{expected} in\n{written}");
5396        }
5397        assert!(written.find("<credit").unwrap() < written.find("<part-list>").unwrap());
5398        // A page that is no number is refused, as music21's `int` refuses it.
5399        assert!(from_musicxml("<score-partwise><credit page=\"x\"/></score-partwise>").is_err());
5400    }
5401
5402    #[test]
5403    fn layouts_are_read_and_written_as_music21_keeps_them() {
5404        let document = format!(
5405            "<?xml version=\"1.0\"?><score-partwise version=\"4.0\">             <defaults><scaling><millimeters>6.5</millimeters><tenths>40</tenths></scaling>             <page-layout><page-height>1800.0</page-height><page-width>1400</page-width>             <page-margins><left-margin>80</left-margin><right-margin>80</right-margin>             </page-margins></page-layout><staff-layout><staff-distance>90</staff-distance>             </staff-layout></defaults><part-list><score-part id=\"P1\"><part-name>Flute             </part-name></score-part></part-list><part id=\"P1\"><measure number=\"1\">             <print new-system=\"yes\"><system-layout><system-distance>120</system-distance>             </system-layout><staff-layout number=\"1\"><staff-distance>70.5</staff-distance>             </staff-layout><measure-numbering>system</measure-numbering></print>             <attributes><divisions>1</divisions><staff-details number=\"1\" print-object=\"no\">             <staff-lines>4</staff-lines></staff-details></attributes>{NOTE}</measure></part>             </score-partwise>"
5406        );
5407        let read = from_musicxml(&document).unwrap();
5408        let score_layout = read
5409            .events()
5410            .iter()
5411            .find_map(|event| match event.element() {
5412                StreamElement::Layout(Layout::Score(layout)) => Some(layout),
5413                _ => None,
5414            })
5415            .expect("the defaults are a score layout");
5416        // `1800.0` is kept whole, as music21's `_floatOrIntStr` keeps it.
5417        assert_eq!(
5418            score_layout.page_layout.as_ref().unwrap().page_height,
5419            Some(Tenths::Whole(1800))
5420        );
5421        assert_eq!(
5422            score_layout.scaling_millimeters,
5423            Some(Tenths::Fraction(6.5))
5424        );
5425        let measure = &read.parts()[0].measures()[0];
5426        assert_eq!(measure.measure_numbering(), Some("system"));
5427        let staff = measure
5428            .events()
5429            .iter()
5430            .find_map(|event| match event.element() {
5431                StreamElement::Layout(Layout::Staff(layout)) => Some(layout),
5432                _ => None,
5433            })
5434            .expect("a staff layout");
5435        // The details are read into the staff layout the print made.
5436        assert_eq!(staff.distance, Some(Tenths::Fraction(70.5)));
5437        assert_eq!(staff.staff_lines, Some(4));
5438        assert_eq!(staff.hidden, Some(true));
5439
5440        let written = written_back(&read);
5441        for expected in [
5442            "<millimeters>6.5</millimeters>",
5443            "<page-height>1800</page-height>",
5444            "<staff-distance>90</staff-distance>",
5445            "<print new-system=\"yes\">",
5446            "<system-distance>120</system-distance>",
5447            "<staff-layout number=\"1\">",
5448            "<measure-numbering>system</measure-numbering>",
5449            "<staff-details print-object=\"no\">",
5450            "<staff-lines>4</staff-lines>",
5451        ] {
5452            assert!(
5453                written.contains(expected),
5454                "{expected} in
5455{written}"
5456            );
5457        }
5458    }
5459}