Skip to main content

music21/musicxml/
mod.rs

1//! MusicXML export: music21's `musicxml.m21ToXml`.
2//!
3//! [`to_musicxml`] writes a score as a `score-partwise` document, element for
4//! element as music21's `ScoreExporter` writes it with `makeNotation=False`:
5//! the score is taken as already notated, so its measures, beams, ties and
6//! the accidentals it shows are written as they stand rather than worked out
7//! again. A score is parts holding measures, a measure may hold voices, and a
8//! stream holding no parts is written as one part.
9//!
10//! [`ExportOptions::make_notation`] asks for the notation to be worked out
11//! first, as music21's exporter does by default: a part of loose notes, or a
12//! score whose lengths no single note value writes, is then written as
13//! music21 writes it.
14//!
15//! The writer does no file IO; it hands back the document as a string.
16
17mod fragment;
18mod notate;
19mod partstaff;
20mod read;
21pub mod step;
22mod tree;
23
24pub use fragment::{
25    Joined, Surroundings, chord_with_fret_board_xml, element_xml, frame_note_xml, frame_xml,
26    instrument_xml, layout_xml, part_group_xml, score_header_xml, staff_details_xml, transpose_xml,
27};
28pub use partstaff::{
29    Across, STAFF_TAGGED, StaffDifferences, XmlTree, add_staff_tags, add_staff_tags_to_staves,
30    join as join_staves, measure_number_comes_before, move_measure_contents,
31    move_part_staff_contents, process_subsequent_part_staff, set_earliest_attributes_and_clefs,
32};
33pub use read::{from_musicxml, sound_tempo};
34
35use crate::articulations::Articulation;
36use crate::bar::{Barline, Ending, RepeatDirection};
37use crate::chord::Chord;
38use crate::chordsymbol::{ChordSymbol, KeyDisplay, NumeralFigure};
39use crate::clef::Clef;
40use crate::defaults::FloatType;
41use crate::duration::{Duration, DurationType, Tuplet};
42use crate::dynamics::Dynamic;
43use crate::error::{Error, Result};
44use crate::expressions::{ArpeggioType, Expression, Ornament};
45use crate::instrument::Instrument;
46use crate::interval::Interval;
47use crate::key::KeySignature;
48use crate::layout::{Layout, PageLayout, StaffLayout, StaffType, SystemLayout, Tenths};
49use crate::metadata::{Metadata, namespace_name};
50use crate::meter::TimeSignature;
51use crate::notation::{
52    Beam, BeamDirection, BeamType, Beams, Lyric, Notehead, Placement, StemDirection, Tie,
53};
54use crate::note::Note;
55use crate::pitch::{Accidental, Pitch};
56use crate::repeat::{RepeatExpression, RepeatExpressionKind};
57use crate::rest::{FullMeasure, Rest};
58use crate::spanner::{
59    PedalForm, PedalObject, PedalObjectKind, PedalType, SlideType, Spanner, SpannerKind,
60};
61use crate::stream::{StaffGroup, Stream, StreamElement, StreamKind};
62use crate::style::TextStyle;
63use crate::tempo::{MetricModulation, MetronomeMark};
64use crate::text::TextBox;
65
66use tree::Element;
67
68/// How many divisions of a quarter note durations are counted in: music21's
69/// `defaults.divisionsPerQuarter`, `32 * 3 * 3 * 5 * 7`, which counts every
70/// tuplet music21 writes in whole numbers.
71pub const DIVISIONS_PER_QUARTER: FloatType = 10080.0;
72
73/// The MusicXML version written.
74pub const MUSICXML_VERSION: &str = "4.0";
75
76/// music21's `xmlObjects.isValidXSDID`: whether text is an `xsd:ID`, an
77/// XML name with no colon, which an element's `id` attribute has to be.
78///
79/// ```
80/// use music21::musicxml::is_valid_xsd_id;
81///
82/// assert!(is_valid_xsd_id("hel_lo"));
83/// assert!(!is_valid_xsd_id("4sad"));
84/// assert!(!is_valid_xsd_id(""));
85/// ```
86pub fn is_valid_xsd_id(text: &str) -> bool {
87    let mut chars = text.chars();
88    let Some(first) = chars.next() else {
89        return false;
90    };
91    if !(first.is_ascii_alphabetic() || first == '_') {
92        return false;
93    }
94    chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | '-'))
95}
96
97/// What a document says about how it was made, where the score does not say.
98///
99/// The defaults are music21's own, so that a score written here reads as the
100/// one music21 writes; a caller making a document of its own will want its
101/// own title and author, or none.
102#[derive(Clone, Debug, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct ExportOptions {
105    /// The `<encoding-date>`, as `YYYY-MM-DD`. music21 writes the day it ran;
106    /// the crate reads no clock, so the date is written only when given.
107    pub encoding_date: Option<String>,
108    /// The `<software>` line written when the score carries no metadata.
109    /// A score with metadata names its software there instead.
110    pub software: String,
111    /// The movement title of a score with no title of its own: music21's
112    /// `defaults.title`, `Music21 Fragment`.
113    pub default_title: Option<String>,
114    /// The composer named when the score names no contributor: music21's
115    /// `defaults.author`, `Music21`.
116    pub default_author: Option<String>,
117    /// Whether to work out the notation the score leaves unsaid before
118    /// writing it, as music21's exporter does with `makeNotation=True`:
119    /// gaps filled with unprinted rests, a part with no measures cut into
120    /// them, notes running past a barline cut and tied, accidentals decided,
121    /// notes beamed and tuplets bracketed where the part has none yet, and
122    /// lengths no single note value writes cut into tied values. A measure
123    /// or a voice handed in alone is written as a part of one measure, given
124    /// the meter and clef its notes fit where it states none. The score
125    /// handed in is not changed.
126    ///
127    /// Off, the score is written as it stands, which is music21's
128    /// `makeNotation=False`: a caller that has made its notation already
129    /// gets exactly what it made.
130    pub make_notation: bool,
131}
132
133impl Default for ExportOptions {
134    fn default() -> Self {
135        Self {
136            encoding_date: None,
137            software: format!("music21-rs v.{}", env!("CARGO_PKG_VERSION")),
138            default_title: Some("Music21 Fragment".to_string()),
139            default_author: Some("Music21".to_string()),
140            make_notation: false,
141        }
142    }
143}
144
145/// Writes a score as a MusicXML document.
146///
147/// ```
148/// use music21::{Duration, Note, Stream, StreamKind, TimeSignature};
149/// use music21::musicxml::{ExportOptions, to_musicxml};
150///
151/// let mut measure = Stream::with_kind(StreamKind::Measure);
152/// measure.set_number(1);
153/// measure.insert(0.0, TimeSignature::new(1, 4)?);
154/// measure.push(Note::from_name("D#4")?.with_duration(Duration::quarter()));
155/// let mut part = Stream::with_kind(StreamKind::Part);
156/// part.push(measure);
157/// let mut score = Stream::with_kind(StreamKind::Score);
158/// score.push(part);
159///
160/// let xml = to_musicxml(&score, &ExportOptions::default())?;
161/// assert!(xml.contains("<step>D</step>"));
162/// assert!(xml.contains("<alter>1</alter>"));
163/// assert!(xml.contains("<duration>10080</duration>"));
164/// # Ok::<(), music21::Error>(())
165/// ```
166///
167/// With [`ExportOptions::make_notation`] a part or a stream of loose notes
168/// may be handed in as readily as a score:
169///
170/// ```
171/// use music21::{Duration, Note, Stream, StreamKind, TimeSignature};
172/// use music21::musicxml::{ExportOptions, to_musicxml};
173///
174/// let mut part = Stream::with_kind(StreamKind::Part);
175/// part.insert(0.0, TimeSignature::new(3, 4)?);
176/// part.insert(0.0, Note::from_name("C4")?.with_duration(Duration::new(5.0)?));
177/// let mut options = ExportOptions::default();
178/// options.make_notation = true;
179/// let xml = to_musicxml(&part, &options)?;
180/// // A dotted half tied to a half, in two measures.
181/// assert_eq!(xml.matches("<measure ").count(), 2);
182/// assert!(xml.contains("<tie type=\"start\" />"));
183/// # Ok::<(), music21::Error>(())
184/// ```
185///
186/// # Errors
187///
188/// A part with no measures, a score nested in a score, a duration no single
189/// note value writes, and anything the crate cannot yet write: each as
190/// music21's `MusicXMLExportException` says it where music21 raises. Making
191/// the notation first leaves only what no notation can write: a length no
192/// tie of note values reaches that is not an unprinted rest.
193pub fn to_musicxml(score: &Stream, options: &ExportOptions) -> Result<String> {
194    // music21's exporter turns a part at sounding pitch to the pitch its
195    // instruments read, and the notes under an octave line to where they
196    // sound (`toWrittenPitch(ottavasToSounding=True)`), before it writes;
197    // making the notation does that itself, at the point music21 does it.
198    let prepared;
199    let score = if options.make_notation {
200        prepared = notate::notated(score)?;
201        &prepared
202    } else if holds_sounding_pitch(score) || score.holds_transposing_ottava() {
203        prepared = score.to_written_pitch_by(true)?;
204        &prepared
205    } else {
206        score
207    };
208    let root = score_element(score, options)?;
209    Ok(format!(
210        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE score-partwise  PUBLIC \
211         \"-//Recordare//DTD MusicXML {MUSICXML_VERSION} Partwise//EN\" \
212         \"http://www.musicxml.org/dtds/partwise.dtd\">\n{}",
213        root.dump()
214    ))
215}
216
217/// A copy of a stream, or of an element put in one, with the notation it
218/// leaves unsaid worked out, as [`ExportOptions::make_notation`] works it
219/// out before writing: music21's `GeneralObjectExporter.fromGeneralObject`
220/// and the score's `makeNotation`. What comes back is a score.
221///
222/// ```
223/// use music21::{Duration, Note, Stream, StreamKind};
224/// use music21::musicxml::make_notation;
225///
226/// let mut part = Stream::with_kind(StreamKind::Part);
227/// part.push(Note::from_name("C4")?.with_duration(Duration::new(8.0)?));
228/// let score = make_notation(&part)?;
229/// assert_eq!(score.kind(), StreamKind::Score);
230/// assert_eq!(score.parts()[0].measures().len(), 2);
231/// # Ok::<(), music21::Error>(())
232/// ```
233///
234/// # Errors
235///
236/// A kind of stream music21 writes no score of, and what making the
237/// notation refuses.
238pub fn make_notation(stream: &Stream) -> Result<Stream> {
239    notate::notated(stream)
240}
241
242/// Whether anything in the stream, itself included, says it is at sounding
243/// pitch: nothing else is moved by writing it at written pitch.
244fn holds_sounding_pitch(stream: &Stream) -> bool {
245    stream.at_sounding_pitch() == Some(true)
246        || stream
247            .events()
248            .iter()
249            .filter_map(|event| event.element().as_stream())
250            .any(holds_sounding_pitch)
251}
252
253fn export_error(message: impl Into<String>) -> Error {
254    Error::music_xml(message.into())
255}
256
257// ------------------------------------------------------------------ score
258
259/// music21's `ScoreExporter.parse`.
260fn score_element(score: &Stream, options: &ExportOptions) -> Result<Element> {
261    if score.is_empty() {
262        return score_element(&empty_score(), options);
263    }
264    let parts = score_parts(score)?;
265    let groups = score.staff_groups();
266    let joined = joinable_groups(&parts, groups).into_indices();
267    let voice_bases = voice_bases(&parts, groups, &joined);
268    let numbered = id_locals(score, &parts);
269    let mut shared = Shared::default();
270    let mut exported = Vec::with_capacity(parts.len());
271    for (index, part) in parts.iter().copied().enumerate() {
272        let spanners = numbered.clone();
273        let mut role = StaffRole::default();
274        for group in &joined {
275            let parts_of = groups[*group].parts();
276            if let Some(at) = parts_of.iter().position(|position| *position == index) {
277                role.previous = at.checked_sub(1).map(|before| parts[parts_of[before]]);
278                role.later = at > 0;
279                if at == 0 {
280                    role.followers = parts_of[1..]
281                        .iter()
282                        .map(|position| parts[*position])
283                        .collect();
284                }
285            }
286        }
287        let previous = role.previous;
288        exported.push(Some(PartExporter::new(part, &mut shared, &role)?.parse(
289            spanners,
290            previous,
291            &voice_bases,
292        )?));
293    }
294
295    // music21's `joinPartStaffs`: each group's staves written into its first.
296    for group in &joined {
297        let positions = groups[*group].parts();
298        let mut roots: Vec<Element> = positions
299            .iter()
300            .map(|position| {
301                exported[*position]
302                    .as_mut()
303                    .map(|part| std::mem::replace(&mut part.part, Element::new("part")))
304                    .expect("a staff is joined into one group only")
305            })
306            .collect();
307        let staves: Vec<&Stream> = positions.iter().map(|position| parts[*position]).collect();
308        partstaff::join(&mut roots, staff_differences(&staves))?;
309        let first = roots.swap_remove(0);
310        if let Some(part) = exported[positions[0]].as_mut() {
311            part.part = first;
312        }
313        for position in &positions[1..] {
314            exported[*position] = None;
315        }
316    }
317
318    let mut root = Element::new("score-partwise");
319    root.set("version", MUSICXML_VERSION);
320    let metadata = score.metadata();
321    set_titles(&mut root, metadata, options);
322    set_identification(&mut root, metadata, options);
323    set_defaults(&mut root, score);
324    for event in score.events() {
325        if let StreamElement::TextBox(text) = event.element() {
326            root.push(credit_element(text)?);
327        }
328    }
329    set_part_list(root.sub("part-list"), &exported, groups, &joined);
330    for (index, part) in exported.into_iter().flatten().enumerate() {
331        add_divider_comment(&mut root, &format!("Part {}", index + 1));
332        root.push(part.part);
333    }
334    Ok(root)
335}
336
337/// Where a part stands among the staves of a group written as one part.
338#[derive(Default)]
339struct StaffRole<'a> {
340    /// The staff before it in its group.
341    previous: Option<&'a Stream>,
342    /// The staves after it, where it is its group's first.
343    followers: Vec<&'a Stream>,
344    /// Whether it is a staff after its group's first.
345    later: bool,
346}
347
348/// The parts a score is written as: its parts, or the score itself as one
349/// where it holds none.
350fn score_parts(score: &Stream) -> Result<Vec<&Stream>> {
351    if !has_part_like_streams(score) {
352        return Ok(vec![score]);
353    }
354    for event in score.events() {
355        if let StreamElement::Stream(inner) = event.element()
356            && matches!(inner.kind(), StreamKind::Score | StreamKind::Opus)
357        {
358            return Err(export_error(
359                "Exporting scores nested inside scores is not supported",
360            ));
361        }
362    }
363    Ok(score
364        .events()
365        .iter()
366        .filter_map(|event| event.element().as_stream())
367        .filter(|stream| matches!(stream.kind(), StreamKind::Part | StreamKind::PartStaff))
368        .collect())
369}
370
371/// Which of a score's staff groups are written as one part each.
372#[derive(Clone, Debug, PartialEq, Eq)]
373pub enum JoinableGroups {
374    /// These, by index into the score's staff groups.
375    Joined(Vec<usize>),
376    /// Two of the groups that could be joined share a staff, so none is.
377    Overlapping,
378}
379
380impl JoinableGroups {
381    /// The groups joined, by index; none where they overlap.
382    pub fn into_indices(self) -> Vec<usize> {
383        match self {
384            Self::Joined(indices) => indices,
385            Self::Overlapping => Vec::new(),
386        }
387    }
388}
389
390/// music21's `joinableGroups` for a whole score: the staff groups whose
391/// staves are written as one `<part>`.
392///
393/// ```
394/// use music21::{Stream, StreamKind};
395/// use music21::musicxml::{JoinableGroups, joinable_staff_groups};
396///
397/// let score = Stream::with_kind(StreamKind::Score);
398/// assert_eq!(joinable_staff_groups(&score)?, JoinableGroups::Joined(Vec::new()));
399/// # Ok::<(), music21::Error>(())
400/// ```
401///
402/// # Errors
403///
404/// A score nested in the score.
405pub fn joinable_staff_groups(score: &Stream) -> Result<JoinableGroups> {
406    Ok(joinable_groups(&score_parts(score)?, score.staff_groups()))
407}
408
409/// music21's `joinableGroups`: the staff groups whose staves are written as
410/// one part, by index into the score's groups. A group of more than one
411/// `PartStaff`, each with measures; a second group over the same staves is
412/// passed over; and if any two overlap, none is joined.
413fn joinable_groups(parts: &[&Stream], groups: &[StaffGroup]) -> JoinableGroups {
414    let mut joinable: Vec<usize> = Vec::new();
415    for (index, group) in groups.iter().enumerate() {
416        let staves = group.parts();
417        if staves.len() <= 1 {
418            continue;
419        }
420        let fits = staves.iter().all(|position| {
421            parts.get(*position).is_some_and(|part| {
422                part.kind() == StreamKind::PartStaff && !part.measures().is_empty()
423            })
424        });
425        if !fits
426            || joinable
427                .iter()
428                .any(|known| groups[*known].parts() == staves)
429        {
430            continue;
431        }
432        joinable.push(index);
433    }
434    let mut seen: Vec<usize> = Vec::new();
435    for index in &joinable {
436        for position in groups[*index].parts() {
437            if seen.contains(position) {
438                return JoinableGroups::Overlapping;
439            }
440            seen.push(*position);
441        }
442    }
443    JoinableGroups::Joined(joinable)
444}
445
446/// music21's `renumberVoicesWithinStaffGroups`: in a group of staves, a voice
447/// with no id of its own is numbered on from the voices of the staves above
448/// it in the measures starting where its measure does. Each measure is
449/// given the number its first such voice takes after one.
450fn voice_bases(
451    parts: &[&Stream],
452    groups: &[StaffGroup],
453    joined: &[usize],
454) -> std::collections::HashMap<usize, u32> {
455    let mut bases = std::collections::HashMap::new();
456    for group in joined {
457        let mut measures: Vec<(FloatType, usize, &Stream)> = Vec::new();
458        for (staff, position) in groups[*group].parts().iter().enumerate() {
459            for event in parts[*position].events() {
460                if let Some(measure) = event
461                    .element()
462                    .as_stream()
463                    .filter(|stream| stream.kind() == StreamKind::Measure)
464                {
465                    measures.push((event.offset(), staff, measure));
466                }
467            }
468        }
469        measures.sort_by(|left, right| left.0.total_cmp(&right.0).then(left.1.cmp(&right.1)));
470        let mut next = 0;
471        let mut stack_offset = None;
472        for (offset, _, measure) in measures {
473            if stack_offset != Some(offset) {
474                stack_offset = Some(offset);
475                next = 0;
476            }
477            bases.insert(measure as *const Stream as usize, next);
478            next += measure
479                .voices()
480                .iter()
481                .filter(|voice| voice.id().is_none())
482                .count() as u32;
483        }
484    }
485    bases
486}
487
488/// The first of some kind of mark anywhere in a staff.
489fn first_of<'a>(
490    staff: &'a Stream,
491    pick: impl Fn(&'a StreamElement) -> bool,
492) -> Option<&'a StreamElement> {
493    staff
494        .recurse()
495        .into_iter()
496        .map(|(_, element)| element)
497        .find(|element| pick(element))
498}
499
500fn first_key(staff: &Stream) -> Option<&StreamElement> {
501    first_of(staff, |element| {
502        matches!(
503            element,
504            StreamElement::Key(_) | StreamElement::KeySignature(_)
505        )
506    })
507}
508
509fn first_meter(staff: &Stream) -> Option<&StreamElement> {
510    first_of(staff, |element| {
511        matches!(element, StreamElement::TimeSignature(_))
512    })
513}
514
515/// Which marks a group's staves start with differently: music21's
516/// `isMultiAttribute` for keys and for meters.
517///
518/// ```
519/// use music21::{KeySignature, Stream, StreamKind};
520/// use music21::musicxml::{Across, staff_differences};
521///
522/// let mut upper = Stream::with_kind(StreamKind::PartStaff);
523/// upper.insert(0.0, KeySignature::new(1));
524/// let mut lower = Stream::with_kind(StreamKind::PartStaff);
525/// lower.insert(0.0, KeySignature::new(2));
526/// assert_eq!(staff_differences(&[&upper, &lower]).keys, Across::Different);
527/// assert_eq!(staff_differences(&[&upper, &lower]).meters, Across::Same);
528/// ```
529pub fn staff_differences(staves: &[&Stream]) -> StaffDifferences {
530    let across = |different| {
531        if different {
532            Across::Different
533        } else {
534            Across::Same
535        }
536    };
537    StaffDifferences {
538        keys: across(differs_across(staves, first_key, same_key)),
539        meters: across(differs_across(staves, first_meter, same_meter)),
540    }
541}
542
543/// Whether a later staff's first mark of a kind differs from the first
544/// staff's: music21's `isMultiAttribute`.
545fn differs_across(
546    staves: &[&Stream],
547    first: impl Fn(&Stream) -> Option<&StreamElement>,
548    same: impl Fn(&StreamElement, &StreamElement) -> bool,
549) -> bool {
550    let mut initial: Option<&StreamElement> = None;
551    for staff in staves {
552        match initial {
553            None => initial = first(staff),
554            Some(initial) => {
555                if let Some(later) = first(staff)
556                    && !same(later, initial)
557                {
558                    return true;
559                }
560            }
561        }
562    }
563    false
564}
565
566/// music21's `==` between two key signatures: a key equals a key of the same
567/// tonic and mode, a signature a signature of the same sharps, and a key
568/// never a bare signature.
569fn same_key(left: &StreamElement, right: &StreamElement) -> bool {
570    match (left, right) {
571        (StreamElement::Key(left), StreamElement::Key(right)) => {
572            left.tonic().name() == right.tonic().name() && left.mode() == right.mode()
573        }
574        (StreamElement::KeySignature(left), StreamElement::KeySignature(right)) => {
575            left.sharps() == right.sharps()
576                && left.altered_pitches().ok().map(|pitches| {
577                    pitches
578                        .iter()
579                        .map(Pitch::name_with_octave)
580                        .collect::<Vec<_>>()
581                }) == right.altered_pitches().ok().map(|pitches| {
582                    pitches
583                        .iter()
584                        .map(Pitch::name_with_octave)
585                        .collect::<Vec<_>>()
586                })
587        }
588        _ => false,
589    }
590}
591
592/// music21's `ratioEqual` between two meters.
593fn same_meter(left: &StreamElement, right: &StreamElement) -> bool {
594    match (left, right) {
595        (StreamElement::TimeSignature(left), StreamElement::TimeSignature(right)) => {
596            left.numerator() == right.numerator() && left.denominator() == right.denominator()
597        }
598        _ => false,
599    }
600}
601
602/// music21's `setPartList`: each part's `<score-part>`, with a staff group
603/// opened before the first part it spans and closed after the last, groups
604/// numbered from one in the order they open.
605fn set_part_list(
606    part_list: &mut Element,
607    parts: &[Option<ExportedPart>],
608    groups: &[StaffGroup],
609    joined: &[usize],
610) {
611    let mut numbers: Vec<Option<usize>> = vec![None; groups.len()];
612    let mut next = 1;
613    for (index, part) in parts.iter().enumerate() {
614        let Some(part) = part else {
615            continue;
616        };
617        for (group_index, group) in groups.iter().enumerate() {
618            if joined.contains(&group_index) {
619                continue;
620            }
621            if group.parts().first() == Some(&index) {
622                let mut start = staff_group_element(group);
623                start.set("number", next.to_string());
624                numbers[group_index] = Some(next);
625                next += 1;
626                part_list.push(start);
627            }
628        }
629        part_list.push(part.score_part.clone());
630        for (group_index, group) in groups.iter().enumerate() {
631            if joined.contains(&group_index) {
632                continue;
633            }
634            if group.parts().last() == Some(&index) {
635                let mut stop = Element::new("part-group");
636                stop.set("type", "stop");
637                if let Some(number) = numbers[group_index] {
638                    stop.set("number", number.to_string());
639                }
640                part_list.push(stop);
641            }
642        }
643    }
644}
645
646/// music21's `staffGroupToXmlPartGroup`.
647fn staff_group_element(group: &StaffGroup) -> Element {
648    let mut element = Element::new("part-group");
649    element.set("type", "start");
650    if let Some(name) = group.name() {
651        element.sub_text("group-name", name);
652    }
653    if group.name_hidden() {
654        element.sub("group-name-display").set("print-object", "no");
655    }
656    if let Some(abbreviation) = group.abbreviation() {
657        element.sub_text("group-abbreviation", abbreviation);
658    }
659    if let Some(symbol) = group.symbol() {
660        element.sub_text("group-symbol", symbol);
661    }
662    let barline = element.sub("group-barline");
663    if let Some(bar_together) = group.bar_together() {
664        barline.set_text(bar_together.as_str());
665    }
666    element
667}
668
669/// A note at one end of a spanner's range: the element holding it and its
670/// pitch space.
671type Extreme = (*const StreamElement, FloatType);
672
673/// The number each arpeggio across several chords is written with in one
674/// measure, one to sixteen and round again, in the order they are met:
675/// music21's `getArpeggioNumber`.
676#[derive(Default)]
677struct ArpeggioNumbers {
678    known: std::cell::RefCell<Vec<(*const Spanner, u32)>>,
679}
680
681impl ArpeggioNumbers {
682    fn number(&self, spanner: &Spanner) -> u32 {
683        let mut known = self.known.borrow_mut();
684        if let Some((_, number)) = known.iter().find(|(held, _)| std::ptr::eq(*held, spanner)) {
685            return *number;
686        }
687        let number = known.len() as u32 % 16 + 1;
688        known.push((spanner, number));
689        number
690    }
691}
692
693/// A spanner with the number it is written with and the elements it joins.
694#[derive(Clone)]
695struct Numbered<'a> {
696    spanner: &'a Spanner,
697    id_local: u32,
698    /// Each element joined, or nothing for one standing in no stream.
699    elements: Vec<Option<&'a StreamElement>>,
700}
701
702impl Numbered<'_> {
703    fn is(joined: Option<&Option<&StreamElement>>, element: *const StreamElement) -> bool {
704        joined.is_some_and(|joined| joined.is_some_and(|joined| std::ptr::eq(joined, element)))
705    }
706
707    fn holds(&self, element: *const StreamElement) -> bool {
708        self.elements
709            .iter()
710            .any(|joined| Self::is(Some(joined), element))
711    }
712
713    fn is_first(&self, element: *const StreamElement) -> bool {
714        Self::is(self.elements.first(), element)
715    }
716
717    fn is_last(&self, element: *const StreamElement) -> bool {
718        Self::is(self.elements.last(), element)
719    }
720
721    /// The lowest and the highest note the spanner joins, each as the
722    /// element holding it and its place in that element's chord: music21's
723    /// `noteExtremes`, which takes the first of equal pitches either way.
724    fn note_extremes(&self) -> Option<(Extreme, Extreme)> {
725        let mut notes: Vec<Extreme> = Vec::new();
726        for element in self.elements.iter().flatten() {
727            match element {
728                StreamElement::Note(note) => notes.push((*element, note.pitch().ps())),
729                StreamElement::Chord(chord) => {
730                    for note in chord.notes() {
731                        notes.push((*element, note.pitch().ps()));
732                    }
733                }
734                _ => {}
735            }
736        }
737        let first = *notes.first()?;
738        let (mut lowest, mut highest) = (first, first);
739        for note in notes {
740            if note.1 < lowest.1 {
741                lowest = note;
742            }
743            if note.1 > highest.1 {
744                highest = note;
745            }
746        }
747        Some((lowest, highest))
748    }
749}
750
751/// music21's `MetricModulation.updateByContext`, as its exporter sets it off
752/// by asking each modulation of a part for its two marks: one with a side
753/// that has no number yet takes it from the tempo in force before it -- the
754/// last mark, tempo word or modulation standing earlier in the part, and
755/// none standing where it stands itself.
756fn resolved_modulations(part: &Stream) -> Vec<(*const StreamElement, MetricModulation)> {
757    let mut elements = part.recurse();
758    elements.sort_by(|left, right| left.0.total_cmp(&right.0));
759    // Every tempo so far with where it stands, as the mark it sounds at.
760    let mut tempos: Vec<(FloatType, Option<MetronomeMark>)> = Vec::new();
761    let mut resolved = Vec::new();
762    for (offset, element) in elements {
763        match element {
764            StreamElement::MetronomeMark(mark) => tempos.push((offset, Some(mark.clone()))),
765            StreamElement::TempoText(text) => tempos.push((offset, Some(text.metronome_mark()))),
766            StreamElement::MetricModulation(modulation) => {
767                let previous = tempos
768                    .iter()
769                    .rev()
770                    .find(|(at, _)| *at < offset)
771                    .and_then(|(_, mark)| mark.as_ref());
772                let mut modulation = (**modulation).clone();
773                let unnumbered =
774                    |side: Option<&MetronomeMark>| side.is_some_and(|mark| mark.number().is_none());
775                if unnumbered(modulation.old_metronome()) {
776                    modulation.update_from(previous);
777                }
778                if unnumbered(modulation.new_metronome()) {
779                    modulation.update_from(previous);
780                }
781                tempos.push((offset, modulation.new_metronome().cloned()));
782                resolved.push((element as *const StreamElement, modulation));
783            }
784            _ => {}
785        }
786    }
787    resolved
788}
789
790/// music21's `setIdLocals` over the score's spanners: each kind numbered
791/// one to six and round again -- the number MusicXML pairs a spanner's start
792/// with its stop by -- in the order the score holds them, its own first and
793/// then each part's. Each is resolved to the elements it joins, wherever in
794/// the score they stand.
795fn id_locals<'a>(score: &'a Stream, parts: &[&'a Stream]) -> Vec<Numbered<'a>> {
796    let resolve = |holder: &'a Stream, spanner: &'a Spanner| {
797        let leaves = holder.leaves();
798        spanner
799            .spanned()
800            .iter()
801            .map(|position| {
802                position
803                    .and_then(|position| leaves.get(position))
804                    .map(|(_, element)| *element)
805            })
806            .collect::<Vec<_>>()
807    };
808    let mut held: Vec<(&'a Spanner, Vec<Option<&'a StreamElement>>)> = Vec::new();
809    for spanner in score.spanners() {
810        held.push((spanner, resolve(score, spanner)));
811    }
812    for part in parts {
813        if std::ptr::eq(*part, score) {
814            continue;
815        }
816        for spanner in part.spanners() {
817            held.push((spanner, resolve(part, spanner)));
818        }
819    }
820    let mut counts: Vec<(&'static str, u32)> = Vec::new();
821    held.into_iter()
822        .map(|(spanner, elements)| {
823            let class = spanner.kind().numbering_class();
824            let index = match counts.iter_mut().find(|(known, _)| *known == class) {
825                Some((_, count)) => {
826                    *count += 1;
827                    *count - 1
828                }
829                None => {
830                    counts.push((class, 1));
831                    0
832                }
833            };
834            Numbered {
835                spanner,
836                id_local: index % 6 + 1,
837                elements,
838            }
839        })
840        .collect()
841}
842
843/// Whether a stream holds parts: music21's `hasPartLikeStreams`.
844fn has_part_like_streams(stream: &Stream) -> bool {
845    stream.events().iter().any(|event| {
846        event
847            .element()
848            .as_stream()
849            .is_some_and(|inner| matches!(inner.kind(), StreamKind::Part | StreamKind::PartStaff))
850    })
851}
852
853/// music21's `emptyObject`: "This Page Intentionally Left Blank", a whole
854/// rest in one measure.
855fn empty_score() -> Stream {
856    let mut measure = Stream::with_kind(StreamKind::Measure);
857    measure.push(Rest::new(Duration::whole()));
858    let mut part = Stream::with_kind(StreamKind::Part);
859    part.push(measure);
860    let mut score = Stream::with_kind(StreamKind::Score);
861    score.push(part);
862    let mut metadata = Metadata::new();
863    metadata.add_text("title", "This Page Intentionally Left Blank");
864    score.set_metadata(Some(metadata));
865    score
866}
867
868/// music21's `romanNumeralToXml`: a harmony read off a numeral's chord
869/// has its root and bass taken out and MusicXML 4's `<numeral>` put first.
870fn numeral_in_place_of_root(harmony: &mut Element, figure: &NumeralFigure) {
871    harmony.children_mut().retain(|node| {
872        !matches!(node, tree::Node::Element(element) if matches!(element.tag(), "root" | "bass"))
873    });
874    let mut numeral = Element::new("numeral");
875    let root = numeral.sub("numeral-root");
876    root.set("text", figure.figure.clone());
877    root.set_text(figure.degree.to_string());
878    if let Some(alter) = figure.front_alteration {
879        let written = numeral.sub("numeral-alter");
880        written.set_text(format!("{alter:?}"));
881        written.set("location", "left");
882    }
883    let key = numeral.sub("numeral-key");
884    if figure.key == KeyDisplay::Hidden {
885        key.set("print-object", "no");
886    }
887    key.sub_text("numeral-fifths", figure.fifths.to_string());
888    key.sub_text("numeral-mode", figure.mode.clone());
889    harmony
890        .children_mut()
891        .insert(0, tree::Node::Element(numeral));
892}
893
894/// music21's `fretBoardToXml`: a diagram's strings, the frets it shows,
895/// and a `<frame-note>` for each stopped string, lowest first. Nothing for
896/// a board with no notes.
897fn frame_element(board: &crate::tablature::FretBoard) -> Option<Element> {
898    if board.fret_notes.is_empty() {
899        return None;
900    }
901    let mut frame = Element::new("frame");
902    frame.sub_text("frame-strings", board.strings.to_string());
903    frame.sub_text("frame-frets", board.display_frets.to_string());
904    for note in board.fret_notes_lowest_first() {
905        frame.push(frame_note_element(note));
906    }
907    Some(frame)
908}
909
910/// music21's `fretNoteToXml`: a stopped string's string, fret and finger.
911fn frame_note_element(note: &crate::tablature::FretNote) -> Element {
912    let mut element = Element::new("frame-note");
913    for (tag, value) in [
914        ("string", note.string),
915        ("fret", note.fret),
916        ("fingering", note.fingering),
917    ] {
918        if let Some(value) = value {
919            element.sub_text(tag, value.to_string());
920        }
921    }
922    element
923}
924
925/// music21's `addDividerComment`.
926fn add_divider_comment(root: &mut Element, comment: &str) {
927    root.push_comment(divider_text(comment));
928}
929
930/// The text of the comment music21's `addDividerComment` writes: the
931/// comment centred in signs that pad it out to sixty characters.
932///
933/// ```
934/// use music21::musicxml::divider_text;
935///
936/// assert_eq!(divider_text("Part 1"), format!("{} Part 1 {}", "=".repeat(27), "=".repeat(27)));
937/// ```
938pub fn divider_text(comment: &str) -> String {
939    let length = comment.chars().count().min(DIVIDER_WIDTH);
940    let low = (DIVIDER_WIDTH - length) / 2;
941    let high = (DIVIDER_WIDTH - length).div_ceil(2);
942    format!("{} {comment} {}", "=".repeat(low), "=".repeat(high))
943}
944
945/// How wide music21 pads a divider comment.
946const DIVIDER_WIDTH: usize = 60;
947
948/// music21's `setTitles`.
949fn set_titles(root: &mut Element, metadata: Option<&Metadata>, options: &ExportOptions) {
950    let title = metadata.and_then(|md| md.first_text("title"));
951    if let Some(title) = title {
952        root.sub("work").sub_text("work-title", title);
953    }
954    if let Some(number) = metadata.and_then(|md| md.first_text("movementNumber")) {
955        root.sub_text("movement-number", number);
956    }
957    let movement_title = metadata
958        .and_then(|md| md.first_text("movementName"))
959        .or(title)
960        .or(options.default_title.as_deref());
961    if let Some(movement_title) = movement_title {
962        root.sub_text("movement-title", movement_title);
963    }
964}
965
966/// music21's `setIdentification`, with `setEncoding` and
967/// `metadataToMiscellaneous`.
968fn set_identification(root: &mut Element, metadata: Option<&Metadata>, options: &ExportOptions) {
969    let identification = root.sub("identification");
970    let mut found_one = false;
971    if let Some(md) = metadata {
972        for (_, contributor) in md.contributors() {
973            let creator = identification.sub("creator");
974            if let Some(role) = contributor.role() {
975                creator.set("type", role);
976            }
977            creator.set_text(contributor.text());
978            found_one = true;
979        }
980    }
981    if !found_one && let Some(author) = &options.default_author {
982        let creator = identification.sub("creator");
983        creator.set("type", "composer");
984        creator.set_text(author.as_str());
985    }
986    if let Some(md) = metadata {
987        for copyright in md.get("copyright") {
988            let rights = identification.sub("rights");
989            if let Some(role) = copyright.role() {
990                rights.set("type", role);
991            }
992            rights.set_text(copyright.text());
993        }
994    }
995
996    let encoding = identification.sub("encoding");
997    if let Some(date) = &options.encoding_date {
998        encoding.sub_text("encoding-date", date.as_str());
999    }
1000    match metadata {
1001        Some(md) => {
1002            let mut found_music21 = false;
1003            for software in md.get("software") {
1004                if software.text().contains("music21 v.") {
1005                    if found_music21 {
1006                        continue;
1007                    }
1008                    found_music21 = true;
1009                }
1010                encoding.sub_text("software", software.text());
1011            }
1012        }
1013        None => encoding.sub_text("software", options.software.as_str()),
1014    }
1015    for element in ["beam", "stem", "accidental"] {
1016        let supports = encoding.sub("supports");
1017        supports.set("element", element);
1018        supports.set("type", "yes");
1019    }
1020
1021    if let Some(md) = metadata {
1022        let mut miscellaneous = Element::new("miscellaneous");
1023        let (mut skipped_name, mut skipped_number, mut skipped_title) = (false, false, false);
1024        for (unique_name, value) in md.all() {
1025            if crate::metadata::is_contributor_unique_name(unique_name) {
1026                continue;
1027            }
1028            match unique_name {
1029                "software" | "copyright" => continue,
1030                "movementName" if !skipped_name => {
1031                    skipped_name = true;
1032                    continue;
1033                }
1034                "movementNumber" if !skipped_number => {
1035                    skipped_number = true;
1036                    continue;
1037                }
1038                "title" if !skipped_title => {
1039                    skipped_title = true;
1040                    continue;
1041                }
1042                _ => {}
1043            }
1044            let name = namespace_name(unique_name).unwrap_or(unique_name);
1045            if name.starts_with("m21FileInfo:") {
1046                continue;
1047            }
1048            let field = miscellaneous.sub("miscellaneous-field");
1049            field.set("name", name);
1050            field.set_text(value.text());
1051        }
1052        if miscellaneous.len() > 0 {
1053            identification.push(miscellaneous);
1054        }
1055    }
1056}
1057
1058/// music21's `setDefaults`: the scaling and the page, system and staff
1059/// layouts of the score's first score layout, or music21's own scaling
1060/// where it has none.
1061fn set_defaults(root: &mut Element, score: &Stream) {
1062    let first = score
1063        .events()
1064        .iter()
1065        .find_map(|event| match event.element() {
1066            StreamElement::Layout(Layout::Score(layout)) => Some(layout),
1067            _ => None,
1068        });
1069    let defaults = root.sub("defaults");
1070    match first {
1071        Some(layout) => set_layout_defaults(defaults, layout),
1072        None => {
1073            let scaling = defaults.sub("scaling");
1074            scaling.sub_text("millimeters", "7");
1075            scaling.sub_text("tenths", "40");
1076        }
1077    }
1078    if let Some(style) = score.stream_style() {
1079        add_style_to_defaults(defaults, style);
1080    }
1081}
1082
1083/// What a score layout puts in `<defaults>`: scaling, and its page,
1084/// system and staff layouts.
1085fn set_layout_defaults(defaults: &mut Element, layout: &crate::layout::ScoreLayout) {
1086    if layout.scaling_millimeters.is_some() || layout.scaling_tenths.is_some() {
1087        let said = |value: Option<Tenths>| {
1088            value.map_or_else(|| "None".to_string(), |value| value.to_string())
1089        };
1090        let scaling = defaults.sub("scaling");
1091        scaling.sub_text("millimeters", said(layout.scaling_millimeters));
1092        scaling.sub_text("tenths", said(layout.scaling_tenths));
1093    }
1094    if let Some(page) = &layout.page_layout {
1095        defaults.push(page_layout_element(page));
1096    }
1097    if let Some(system) = &layout.system_layout {
1098        defaults.push(system_layout_element(system));
1099    }
1100    for staff in &layout.staff_layouts {
1101        defaults.push(staff_layout_element(staff));
1102    }
1103}
1104
1105/// music21's `addStyleToXmlDefaults`: a score style's `<appearance>`, its
1106/// music and word fonts, and a font and a language for each lyric name.
1107fn add_style_to_defaults(defaults: &mut Element, style: &crate::style::StreamStyle) {
1108    if let Some(appearance) = appearance_element(style) {
1109        defaults.push(appearance);
1110    }
1111    for (tag, font) in [
1112        ("music-font", &style.music_font),
1113        ("word-font", &style.word_font),
1114    ] {
1115        if let Some(font) = font {
1116            set_font(defaults.sub(tag), font);
1117        }
1118    }
1119    for (name, font) in &style.lyric_fonts {
1120        let written = defaults.sub("lyric-font");
1121        if let Some(font) = font {
1122            set_font(written, font);
1123        }
1124        if let Some(name) = name {
1125            written.set("name", name.as_str());
1126        }
1127    }
1128    for (name, language) in &style.lyric_languages {
1129        let written = defaults.sub("lyric-language");
1130        if let Some(name) = name {
1131            written.set("name", name.as_str());
1132        }
1133        if let Some(language) = language {
1134            written.set("xml:lang", language.as_str());
1135        }
1136    }
1137}
1138
1139/// music21's `styleToXmlAppearance`: a score style's line widths, note
1140/// sizes, distances and other appearances. None where it has none, as
1141/// MusicXML's `<appearance>` cannot be empty.
1142fn appearance_element(style: &crate::style::StreamStyle) -> Option<Element> {
1143    if !style.has_appearance() {
1144        return None;
1145    }
1146    let mut appearance = Element::new("appearance");
1147    for (listed, tag) in [
1148        (&style.line_widths, "line-width"),
1149        (&style.note_sizes, "note-size"),
1150        (&style.distances, "distance"),
1151        (&style.other_appearances, "other-appearance"),
1152    ] {
1153        for (kind, value) in listed {
1154            let written = appearance.sub(tag);
1155            written.set("type", kind.as_str());
1156            written.set_text(value.to_string());
1157        }
1158    }
1159    Some(appearance)
1160}
1161
1162/// music21's `setFont`: a font's style, size, weight and family. MusicXML's
1163/// font-style has no bold, which music21 writes as a weight.
1164fn set_font(element: &mut Element, style: &TextStyle) {
1165    if let Some(font_style) = style.font_style() {
1166        element.set("font-style", font_style);
1167    }
1168    if let Some(size) = &style.font_size {
1169        element.set("font-size", size.to_string());
1170    }
1171    if let Some(weight) = style.font_weight() {
1172        element.set("font-weight", weight);
1173    }
1174    match style.font_style() {
1175        Some("bold") => {
1176            element.set("font-weight", "bold");
1177            element.remove_attribute("font-style");
1178        }
1179        Some("bolditalic") => {
1180            element.set("font-weight", "bold");
1181            element.set("font-style", "italic");
1182        }
1183        _ => {}
1184    }
1185    if let Some(family) = style
1186        .font_family
1187        .as_ref()
1188        .filter(|family| !family.is_empty())
1189    {
1190        element.set("font-family", family.join(","));
1191    }
1192}
1193
1194/// music21's `setPrintStyleAlign`: where text stands, its font and colour,
1195/// and how it is aligned, each as an attribute where the style says it.
1196pub(crate) fn set_print_style_align(element: &mut Element, style: &TextStyle) -> Result<()> {
1197    for (name, value) in [
1198        ("default-x", &style.absolute_x),
1199        ("default-y", &style.absolute_y),
1200        ("relative-x", &style.relative_x),
1201        ("relative-y", &style.relative_y),
1202    ] {
1203        if let Some(value) = value {
1204            element.set(name, value.to_string());
1205        }
1206    }
1207    set_font(element, style);
1208    if let Some(color) = &style.color {
1209        element.set("color", normalize_color(color)?);
1210    }
1211    if let Some(align) = style.align_vertical() {
1212        element.set("valign", align);
1213    }
1214    if let Some(align) = style.align_horizontal() {
1215        element.set("halign", align);
1216    }
1217    Ok(())
1218}
1219
1220/// music21's `textBoxToXmlCredit`: the box's text as the words of a credit
1221/// on its page, drawn as its style says.
1222fn credit_element(text: &TextBox) -> Result<Element> {
1223    let mut credit = Element::new("credit");
1224    credit.set("page", text.page.to_string());
1225    let mut words = Element::new("credit-words");
1226    if text.content.contains('\n') {
1227        words.set("xml:space", "preserve");
1228    }
1229    words.set_text(text.content.clone());
1230    set_print_style_align(&mut words, &text.style)?;
1231    if let Some(justify) = text.style.justify() {
1232        words.set("justify", justify);
1233    }
1234    credit.push(words);
1235    Ok(credit)
1236}
1237
1238/// music21's `_setTagTextFromAttribute`: a child with the value, where
1239/// there is one.
1240fn sub_tenths(element: &mut Element, tag: &'static str, value: Option<Tenths>) {
1241    if let Some(value) = value {
1242        element.sub_text(tag, value.to_string());
1243    }
1244}
1245
1246/// music21's `pageLayoutToXmlPageLayout`.
1247fn page_layout_element(page: &PageLayout) -> Element {
1248    let mut element = Element::new("page-layout");
1249    sub_tenths(&mut element, "page-height", page.page_height);
1250    sub_tenths(&mut element, "page-width", page.page_width);
1251    let mut margins = Element::new("page-margins");
1252    sub_tenths(&mut margins, "left-margin", page.left_margin);
1253    sub_tenths(&mut margins, "right-margin", page.right_margin);
1254    sub_tenths(&mut margins, "top-margin", page.top_margin);
1255    sub_tenths(&mut margins, "bottom-margin", page.bottom_margin);
1256    if margins.len() > 0 {
1257        element.push(margins);
1258    }
1259    element
1260}
1261
1262/// music21's `systemLayoutToXmlSystemLayout`.
1263fn system_layout_element(system: &SystemLayout) -> Element {
1264    let mut element = Element::new("system-layout");
1265    let mut margins = Element::new("system-margins");
1266    sub_tenths(&mut margins, "top-margin", system.top_margin);
1267    sub_tenths(&mut margins, "bottom-margin", system.bottom_margin);
1268    sub_tenths(&mut margins, "left-margin", system.left_margin);
1269    sub_tenths(&mut margins, "right-margin", system.right_margin);
1270    if margins.len() > 0 {
1271        element.push(margins);
1272    }
1273    sub_tenths(&mut element, "system-distance", system.distance);
1274    sub_tenths(&mut element, "top-system-distance", system.top_distance);
1275    element
1276}
1277
1278/// music21's `staffLayoutToXmlStaffLayout`.
1279fn staff_layout_element(staff: &StaffLayout) -> Element {
1280    let mut element = Element::new("staff-layout");
1281    sub_tenths(&mut element, "staff-distance", staff.distance);
1282    if let Some(number) = staff.staff_number {
1283        element.set("number", number.to_string());
1284    }
1285    element
1286}
1287
1288/// music21's `staffLayoutToXmlStaffDetails`: whether the staff is printed,
1289/// what it is for where that is not ordinary, and its lines.
1290fn staff_details_element(staff: &StaffLayout) -> Element {
1291    let mut element = Element::new("staff-details");
1292    element.set(
1293        "print-object",
1294        if staff.hidden == Some(true) {
1295            "no"
1296        } else {
1297            "yes"
1298        },
1299    );
1300    if !matches!(staff.staff_type, StaffType::Regular | StaffType::Other) {
1301        element.sub_text("staff-type", staff.staff_type.as_str());
1302    }
1303    if let Some(lines) = staff.staff_lines {
1304        element.sub_text("staff-lines", lines.to_string());
1305    }
1306    element
1307}
1308
1309/// music21's `yesNo` of an attribute it sets only where it has a value.
1310fn set_yes_no(element: &mut Element, name: &'static str, value: Option<bool>) {
1311    if let Some(value) = value {
1312        element.set(name, if value { "yes" } else { "no" });
1313    }
1314}
1315
1316// ------------------------------------------------------------------- part
1317
1318/// What the parts of one score share while they are written: the MIDI
1319/// channels, instrument ids and part ids already given out.
1320#[derive(Default)]
1321struct Shared {
1322    midi_channels: Vec<Option<u8>>,
1323    instrument_ids: Vec<String>,
1324    part_ids: Vec<String>,
1325}
1326
1327struct ExportedPart {
1328    part: Element,
1329    score_part: Element,
1330}
1331
1332/// An instrument with the offset it starts at within its part.
1333struct PlacedInstrument {
1334    offset: FloatType,
1335    instrument: Instrument,
1336}
1337
1338/// music21's `PartExporter`.
1339struct PartExporter<'a> {
1340    stream: &'a Stream,
1341    instruments: Vec<PlacedInstrument>,
1342}
1343
1344impl<'a> PartExporter<'a> {
1345    /// music21's `instrumentSetup`.
1346    fn new(stream: &'a Stream, shared: &mut Shared, role: &StaffRole<'_>) -> Result<Self> {
1347        let mut instruments = instruments_of(stream);
1348        if instruments.is_empty() {
1349            let mut default = Instrument::new();
1350            default.set_part_name(Some(String::new()));
1351            instruments.push(PlacedInstrument {
1352                offset: 0.0,
1353                instrument: default,
1354            });
1355        }
1356
1357        // music21 gives a part whose id is taken, or who has none, a random
1358        // one; the part's own id, then the first free `P<n>`, is used here.
1359        let first = &mut instruments[0].instrument;
1360        let taken = |id: &str| shared.part_ids.iter().any(|known| known == id);
1361        if first.part_id().is_none_or(taken) {
1362            let fresh = stream
1363                .id()
1364                .filter(|id| !taken(id))
1365                .map(str::to_string)
1366                .unwrap_or_else(|| {
1367                    (1..)
1368                        .map(|number| format!("P{number}"))
1369                        .find(|candidate| !taken(candidate))
1370                        .expect("there is always an unused number")
1371                });
1372            first.set_part_id(Some(fresh));
1373        }
1374        let part_id = first.part_id().unwrap_or_default().to_string();
1375
1376        // music21's `mergeInstrumentStreamPartStaffAware`: the first staff of
1377        // a group plays the instruments of every staff in it, and the staves
1378        // after it leave theirs to the first.
1379        if role.later {
1380            return Ok(Self {
1381                stream,
1382                instruments,
1383            });
1384        }
1385        for follower in &role.followers {
1386            let mut theirs = instruments_of(follower);
1387            if theirs.is_empty() {
1388                let mut default = Instrument::new();
1389                default.set_part_name(Some(String::new()));
1390                theirs.push(PlacedInstrument {
1391                    offset: 0.0,
1392                    instrument: default,
1393                });
1394            }
1395            instruments.extend(theirs);
1396            instruments = deduplicate(instruments);
1397        }
1398
1399        let mut seen: Vec<String> = Vec::new();
1400        for (index, placed) in instruments.iter_mut().enumerate() {
1401            let instrument = &mut placed.instrument;
1402            if seen.iter().any(|kind| kind == instrument.kind()) {
1403                continue;
1404            }
1405            seen.push(instrument.kind().to_string());
1406            if instrument
1407                .midi_channel()
1408                .is_none_or(|channel| shared.midi_channels.contains(&Some(channel)))
1409            {
1410                let used: Vec<u8> = shared.midi_channels.iter().flatten().copied().collect();
1411                // music21 warns and carries on when it runs out of channels.
1412                let _ = instrument.auto_assign_midi_channel(&used, 16);
1413            }
1414            shared.midi_channels.push(instrument.midi_channel());
1415            let duplicate = instrument
1416                .instrument_id()
1417                .is_none_or(|id| shared.instrument_ids.iter().any(|known| known == id));
1418            if duplicate {
1419                let fresh = (1..)
1420                    .map(|number| format!("{part_id}-I{number}"))
1421                    .find(|candidate| !shared.instrument_ids.contains(candidate))
1422                    .expect("there is always an unused number");
1423                instrument.set_instrument_id(Some(fresh));
1424            }
1425            shared
1426                .instrument_ids
1427                .push(instrument.instrument_id().unwrap_or_default().to_string());
1428            if index == 0 {
1429                shared.part_ids.push(part_id.clone());
1430            }
1431        }
1432        Ok(Self {
1433            stream,
1434            instruments,
1435        })
1436    }
1437
1438    fn part_id(&self) -> &str {
1439        self.instruments[0].instrument.part_id().unwrap_or_default()
1440    }
1441
1442    /// music21's `PartExporter.parse`, with `makeNotation=False`.
1443    fn parse(
1444        self,
1445        spanners: Vec<Numbered<'a>>,
1446        previous: Option<&'a Stream>,
1447        voice_bases: &'a std::collections::HashMap<usize, u32>,
1448    ) -> Result<ExportedPart> {
1449        let measures: Vec<(FloatType, &Stream)> = self
1450            .stream
1451            .events()
1452            .iter()
1453            .filter_map(|event| {
1454                event
1455                    .element()
1456                    .as_stream()
1457                    .filter(|stream| stream.kind() == StreamKind::Measure)
1458                    .map(|stream| (event.offset(), stream))
1459            })
1460            .collect();
1461        if measures.is_empty() {
1462            return Err(export_error(
1463                "Cannot export with makeNotation=False if there are no measures",
1464            ));
1465        }
1466
1467        let mut part = Element::new("part");
1468        part.set("id", self.part_id());
1469        let mut context = PartContext {
1470            instruments: &self.instruments,
1471            own_instruments: self
1472                .stream
1473                .recurse()
1474                .into_iter()
1475                .filter_map(|(offset, element)| match element {
1476                    StreamElement::Instrument(instrument) => Some((offset, &**instrument)),
1477                    _ => None,
1478                })
1479                .collect(),
1480            own_clefs: self
1481                .stream
1482                .recurse()
1483                .into_iter()
1484                .filter_map(|(offset, element)| match element {
1485                    StreamElement::Clef(clef)
1486                        if clef.places_pitches() && clef.lowest_line().is_some() =>
1487                    {
1488                        Some((offset, clef))
1489                    }
1490                    _ => None,
1491                })
1492                .collect(),
1493            meter: None,
1494            last_divisions: None,
1495            spanners,
1496            clef: None,
1497            previous,
1498            voice_bases,
1499            modulations: resolved_modulations(self.stream),
1500        };
1501        for (offset, measure) in measures {
1502            add_divider_comment(&mut part, &format!("Measure {}", measure.number()));
1503            part.push(MeasureExporter::new(measure, offset, &mut context).parse()?);
1504        }
1505        Ok(ExportedPart {
1506            score_part: self.score_part(),
1507            part,
1508        })
1509    }
1510
1511    /// music21's `getXmlScorePart`.
1512    fn score_part(&self) -> Element {
1513        let mut score_part = Element::new("score-part");
1514        score_part.set("id", self.part_id());
1515        let name = score_part.sub("part-name");
1516        name.set_text(part_name(self.stream).unwrap_or_default());
1517        if self.stream.name_hidden() {
1518            name.set("print-object", "no");
1519        }
1520        if let Some(abbreviation) = part_abbreviation(self.stream) {
1521            let element = score_part.sub("part-abbreviation");
1522            element.set_text(abbreviation);
1523            if self.stream.abbreviation_hidden() {
1524                element.set("print-object", "no");
1525            }
1526        }
1527        let mut seen: Vec<&str> = Vec::new();
1528        for placed in &self.instruments {
1529            let instrument = &placed.instrument;
1530            if seen.contains(&instrument.kind()) {
1531                continue;
1532            }
1533            if instrument.name().is_some()
1534                || instrument.abbreviation().is_some()
1535                || instrument.midi_program().is_some()
1536            {
1537                score_part.push(score_instrument(instrument));
1538                seen.push(instrument.kind());
1539            }
1540        }
1541        let mut seen: Vec<&str> = Vec::new();
1542        for placed in &self.instruments {
1543            let instrument = &placed.instrument;
1544            if seen.contains(&instrument.kind()) {
1545                continue;
1546            }
1547            if instrument.midi_program().is_some() || instrument.is_a("UnpitchedPercussion") {
1548                score_part.push(midi_instrument(instrument));
1549                seen.push(instrument.kind());
1550            }
1551        }
1552        score_part
1553    }
1554}
1555
1556/// Every instrument anywhere in a part, with where it starts.
1557fn instruments_of(stream: &Stream) -> Vec<PlacedInstrument> {
1558    stream
1559        .recurse()
1560        .into_iter()
1561        .filter_map(|(offset, element)| match element {
1562            StreamElement::Instrument(instrument) => Some(PlacedInstrument {
1563                offset,
1564                instrument: (**instrument).clone(),
1565            }),
1566            _ => None,
1567        })
1568        .collect()
1569}
1570
1571/// music21's `instrument.deduplicate`: at each offset where the instruments
1572/// agree on their names, where each says the same or nothing, the names are
1573/// shared out, one instrument of each kind is kept, and a bare `Instrument`
1574/// gives way to one of a kind.
1575fn deduplicate(mut instruments: Vec<PlacedInstrument>) -> Vec<PlacedInstrument> {
1576    instruments.sort_by(|left, right| left.offset.total_cmp(&right.offset));
1577    let mut out: Vec<PlacedInstrument> = Vec::new();
1578    let mut start = 0;
1579    while start < instruments.len() {
1580        let offset = instruments[start].offset;
1581        let end = instruments[start..]
1582            .iter()
1583            .position(|placed| placed.offset != offset)
1584            .map_or(instruments.len(), |length| start + length);
1585        let group = &instruments[start..end];
1586        let agreed = |read: fn(&Instrument) -> Option<&str>| -> Option<Option<String>> {
1587            let mut said: Option<&str> = None;
1588            for placed in group {
1589                match (said, read(&placed.instrument)) {
1590                    (_, None) => {}
1591                    (None, Some(name)) => said = Some(name),
1592                    (Some(known), Some(name)) if known == name => {}
1593                    _ => return None,
1594                }
1595            }
1596            Some(said.map(str::to_string))
1597        };
1598        match (agreed(Instrument::part_name), agreed(Instrument::name)) {
1599            (Some(part_name), Some(name)) if group.len() > 1 => {
1600                let has_specific = group
1601                    .iter()
1602                    .any(|placed| placed.instrument.kind() != "Instrument");
1603                let mut kept: Vec<PlacedInstrument> = Vec::new();
1604                for placed in group {
1605                    let kind = placed.instrument.kind();
1606                    if (has_specific && kind == "Instrument")
1607                        || kept.iter().any(|known| known.instrument.kind() == kind)
1608                    {
1609                        continue;
1610                    }
1611                    let mut instrument = placed.instrument.clone();
1612                    instrument.set_part_name(part_name.clone());
1613                    instrument.set_name(name.clone());
1614                    kept.push(PlacedInstrument { offset, instrument });
1615                }
1616                out.extend(kept);
1617            }
1618            _ => out.extend(group.iter().map(|placed| PlacedInstrument {
1619                offset,
1620                instrument: placed.instrument.clone(),
1621            })),
1622        }
1623        start = end;
1624    }
1625    out
1626}
1627
1628/// music21's `Part.partName`: the part's own, else the first instrument
1629/// held directly that names one.
1630fn part_name(part: &Stream) -> Option<&str> {
1631    part.name().or_else(|| {
1632        held_instruments(part)
1633            .into_iter()
1634            .find_map(|instrument| instrument.part_name().or(instrument.name()))
1635    })
1636}
1637
1638/// Every instrument a part holds, those inside its measures too.
1639fn held_instruments(part: &Stream) -> Vec<&Instrument> {
1640    part.recurse()
1641        .into_iter()
1642        .filter_map(|(_, element)| match element {
1643            StreamElement::Instrument(instrument) => Some(&**instrument),
1644            _ => None,
1645        })
1646        .collect()
1647}
1648
1649/// music21's `Part.partAbbreviation`, read the same way.
1650fn part_abbreviation(part: &Stream) -> Option<&str> {
1651    part.abbreviation().or_else(|| {
1652        held_instruments(part)
1653            .into_iter()
1654            .find_map(|instrument| instrument.part_abbreviation().or(instrument.abbreviation()))
1655    })
1656}
1657
1658/// music21's `instrumentToXmlScoreInstrument`.
1659fn score_instrument(instrument: &Instrument) -> Element {
1660    let mut element = Element::new("score-instrument");
1661    element.set("id", instrument.instrument_id().unwrap_or_default());
1662    element.sub_text(
1663        "instrument-name",
1664        instrument.name().unwrap_or("None").to_string(),
1665    );
1666    if let Some(abbreviation) = instrument.abbreviation() {
1667        element.sub_text("instrument-abbreviation", abbreviation);
1668    }
1669    element
1670}
1671
1672/// music21's `instrumentToXmlMidiInstrument`.
1673fn midi_instrument(instrument: &Instrument) -> Element {
1674    let mut element = Element::new("midi-instrument");
1675    element.set("id", instrument.instrument_id().unwrap_or_default());
1676    let channel = instrument.midi_channel().unwrap_or(0);
1677    element.sub_text("midi-channel", (u32::from(channel) + 1).to_string());
1678    if let Some(program) = instrument.midi_program() {
1679        element.sub_text("midi-program", (u32::from(program) + 1).to_string());
1680    }
1681    if instrument.is_a("UnpitchedPercussion")
1682        && let Some(pitch) = instrument.percussion_pitch()
1683    {
1684        element.sub_text("midi-unpitched", (u32::from(pitch) + 1).to_string());
1685    }
1686    element
1687}
1688
1689/// What a measure needs to know of the part around it.
1690struct PartContext<'a> {
1691    instruments: &'a [PlacedInstrument],
1692    /// The instruments standing in this staff itself, in the order it holds
1693    /// them, which is where a note looks for the one that plays it.
1694    own_instruments: Vec<(FloatType, &'a Instrument)>,
1695    /// The clefs placing pitches that stand in this staff, in order.
1696    own_clefs: Vec<(FloatType, &'a Clef)>,
1697    /// The metre in force where the measure being written starts.
1698    meter: Option<TimeSignature>,
1699    last_divisions: Option<FloatType>,
1700    /// The score's spanners, each with the number it is written with and
1701    /// the elements it joins.
1702    spanners: Vec<Numbered<'a>>,
1703    /// The part's metric modulations as they are once each has taken its
1704    /// numbers from the tempo in force before it.
1705    modulations: Vec<(*const StreamElement, MetricModulation)>,
1706    /// The clef in force where the writer has got to.
1707    clef: Option<Clef>,
1708    /// The staff before this one where it is one of several written as one
1709    /// part: a key or meter that staff already says is not said again.
1710    previous: Option<&'a Stream>,
1711    /// Where the voices with no id of their own start numbering, measure by
1712    /// measure, in a staff written with others.
1713    voice_bases: &'a std::collections::HashMap<usize, u32>,
1714}
1715
1716// ---------------------------------------------------------------- measure
1717
1718/// music21's `MeasureExporter`.
1719struct MeasureExporter<'a, 'b> {
1720    stream: &'a Stream,
1721    /// Where the measure starts within its part.
1722    start: FloatType,
1723    context: &'a mut PartContext<'b>,
1724    root: Element,
1725    offset_in_measure: FloatType,
1726    current_voice: Option<String>,
1727    next_free_voice: u32,
1728    arpeggios: ArpeggioNumbers,
1729    /// Where in the measure the element being written stands.
1730    element_offset: FloatType,
1731}
1732
1733impl<'a, 'b> MeasureExporter<'a, 'b> {
1734    fn new(stream: &'a Stream, start: FloatType, context: &'a mut PartContext<'b>) -> Self {
1735        let next_free_voice = context
1736            .voice_bases
1737            .get(&(stream as *const Stream as usize))
1738            .map_or(1, |base| base + 1);
1739        Self {
1740            stream,
1741            start,
1742            context,
1743            root: Element::new("measure"),
1744            offset_in_measure: 0.0,
1745            current_voice: None,
1746            next_free_voice,
1747            arpeggios: ArpeggioNumbers::default(),
1748            element_offset: 0.0,
1749        }
1750    }
1751
1752    /// music21's `_matchesPreviousPartStaffInGroup`: whether the staff above
1753    /// this one says the same at the start of its measure of this number.
1754    fn matches_previous_staff(
1755        &self,
1756        element: &StreamElement,
1757        pick: impl Fn(&StreamElement) -> bool,
1758        same: impl Fn(&StreamElement, &StreamElement) -> bool,
1759    ) -> bool {
1760        let Some(previous) = self.context.previous else {
1761            return false;
1762        };
1763        let Some(measure) = previous
1764            .measures()
1765            .into_iter()
1766            .find(|measure| measure.number() == self.stream.number())
1767        else {
1768            return false;
1769        };
1770        measure
1771            .events()
1772            .iter()
1773            .filter(|event| event.offset() == 0.0)
1774            .map(|event| event.element())
1775            .find(|candidate| pick(candidate))
1776            .is_some_and(|theirs| same(element, theirs))
1777    }
1778
1779    /// music21's `MeasureExporter.parse`.
1780    fn parse(mut self) -> Result<Element> {
1781        let transposition = self.transposition();
1782        // setMxAttributes
1783        self.root.set("number", self.stream.number_with_suffix());
1784        self.root.set(
1785            "implicit",
1786            if self.stream.number_hidden() {
1787                "yes"
1788            } else {
1789                "no"
1790            },
1791        );
1792        self.set_print();
1793        self.set_attributes_for_start_of_measure(transposition.as_ref())?;
1794        // music21's `setLeftBarline` and `setRightBarline`: a barline where
1795        // the measure has one, or where an ending opens or closes on it.
1796        let ending = self.stream.ending();
1797        let opens = ending.filter(|ending| ending.starts());
1798        if self.stream.left_barline().is_some() || opens.is_some() {
1799            let barline = barline_element(
1800                self.stream.left_barline(),
1801                "left",
1802                opens.map(|ending| (ending, "start")),
1803            );
1804            self.root.push(barline);
1805        }
1806        self.main_elements_parse()?;
1807        let closes = ending.filter(|ending| ending.stops());
1808        if self.stream.right_barline().is_some() || closes.is_some() {
1809            let barline = barline_element(
1810                self.stream.right_barline(),
1811                "right",
1812                closes.map(|ending| (ending, "stop")),
1813            );
1814            self.root.push(barline);
1815        }
1816        if let Some(meter) = last_of(self.stream, |element| match element {
1817            StreamElement::TimeSignature(meter) => Some(meter.clone()),
1818            _ => None,
1819        }) {
1820            self.context.meter = Some(meter);
1821        }
1822        Ok(self.root)
1823    }
1824
1825    /// music21's `setTranspose`: the transposition of an instrument starting
1826    /// within this measure.
1827    fn transposition(&self) -> Option<Interval> {
1828        let end = self.start + self.stream.end_offset();
1829        self.context
1830            .instruments
1831            .iter()
1832            .find(|placed| {
1833                placed.offset >= self.start && (placed.offset < end || placed.offset == self.start)
1834            })
1835            .and_then(|placed| placed.instrument.transposition().cloned())
1836    }
1837
1838    /// music21's `setMxPrint`: a `<print>` from the measure's first page,
1839    /// system and staff layouts, where it has any.
1840    fn set_print(&mut self) {
1841        let layouts: Vec<&Layout> = self
1842            .stream
1843            .events()
1844            .iter()
1845            .filter_map(|event| match event.element() {
1846                StreamElement::Layout(layout) => Some(layout),
1847                _ => None,
1848            })
1849            .collect();
1850        let mut print: Option<Element> = None;
1851        if let Some(page) = layouts.iter().find_map(|layout| match layout {
1852            Layout::Page(page) => Some(page),
1853            _ => None,
1854        }) {
1855            let mut element = Element::new("print");
1856            set_yes_no(&mut element, "new-page", page.is_new);
1857            if let Some(number) = page.page_number {
1858                element.set("page-number", number.to_string());
1859            }
1860            let laid = page_layout_element(page);
1861            if laid.len() > 0 {
1862                element.push(laid);
1863            }
1864            print = Some(element);
1865        }
1866        if let Some(system) = layouts.iter().find_map(|layout| match layout {
1867            Layout::System(system) => Some(system),
1868            _ => None,
1869        }) {
1870            let element = print.get_or_insert_with(|| Element::new("print"));
1871            set_yes_no(element, "new-system", system.is_new);
1872            let laid = system_layout_element(system);
1873            if laid.len() > 0 {
1874                element.push(laid);
1875            }
1876        }
1877        if let Some(staff) = layouts.iter().find_map(|layout| match layout {
1878            Layout::Staff(staff) => Some(staff),
1879            _ => None,
1880        }) {
1881            print
1882                .get_or_insert_with(|| Element::new("print"))
1883                .push(staff_layout_element(staff));
1884        }
1885        // music21 says how measures are numbered only in a measure it lays
1886        // out.
1887        if !layouts.is_empty()
1888            && let Some(numbering) = self.stream.measure_numbering()
1889        {
1890            print
1891                .get_or_insert_with(|| Element::new("print"))
1892                .sub_text("measure-numbering", numbering.to_string());
1893        }
1894        if let Some(print) = print {
1895            self.root.push(print);
1896        }
1897    }
1898
1899    /// music21's `setMxAttributesObjectForStartOfMeasure`.
1900    fn set_attributes_for_start_of_measure(
1901        &mut self,
1902        transposition: Option<&Interval>,
1903    ) -> Result<()> {
1904        let mut attributes = Element::new("attributes");
1905        if self.context.last_divisions != Some(DIVISIONS_PER_QUARTER) {
1906            attributes.sub_text("divisions", format_int(DIVISIONS_PER_QUARTER));
1907            self.context.last_divisions = Some(DIVISIONS_PER_QUARTER);
1908        }
1909        for event in self
1910            .stream
1911            .events()
1912            .iter()
1913            .filter(|event| event.offset() == 0.0)
1914        {
1915            if let Some(key) = key_element(event.element()) {
1916                let is_key = |element: &StreamElement| {
1917                    matches!(
1918                        element,
1919                        StreamElement::Key(_) | StreamElement::KeySignature(_)
1920                    )
1921                };
1922                if !self.matches_previous_staff(event.element(), is_key, same_key) {
1923                    attributes.push(key?);
1924                }
1925                break;
1926            }
1927        }
1928        for event in self
1929            .stream
1930            .events()
1931            .iter()
1932            .filter(|event| event.offset() == 0.0)
1933        {
1934            if let StreamElement::TimeSignature(meter) = event.element() {
1935                let is_meter =
1936                    |element: &StreamElement| matches!(element, StreamElement::TimeSignature(_));
1937                if !self.matches_previous_staff(event.element(), is_meter, same_meter) {
1938                    attributes.push(time_signature_element(meter)?);
1939                }
1940                self.context.meter = Some(meter.clone());
1941                break;
1942            }
1943        }
1944        for event in self
1945            .stream
1946            .events()
1947            .iter()
1948            .filter(|event| event.offset() == 0.0)
1949        {
1950            if let StreamElement::Clef(clef) = event.element() {
1951                attributes.push(clef_element(clef)?);
1952                break;
1953            }
1954        }
1955        if let Some(staff) = self
1956            .stream
1957            .events()
1958            .iter()
1959            .find_map(|event| match event.element() {
1960                StreamElement::Layout(Layout::Staff(staff)) => Some(staff),
1961                _ => None,
1962            })
1963        {
1964            attributes.push(staff_details_element(staff));
1965        }
1966        if let Some(interval) = transposition {
1967            attributes.push(transpose_element(interval));
1968        }
1969        if let Some(style) = self.measure_style() {
1970            attributes.push(style);
1971        }
1972        if attributes.len() > 0 || attributes.has_attributes() {
1973            self.root.push(attributes);
1974        }
1975        Ok(())
1976    }
1977
1978    /// music21's `measureStyle`: a rest of several measures, written in
1979    /// the measure whose first rest starts one. Rests inside voices do not
1980    /// count.
1981    fn measure_style(&self) -> Option<Element> {
1982        let rest = self
1983            .stream
1984            .events()
1985            .iter()
1986            .find_map(|event| match event.element() {
1987                element @ StreamElement::Rest(_) => Some(element as *const StreamElement),
1988                _ => None,
1989            })?;
1990        let numbered = self.context.spanners.iter().find(|numbered| {
1991            numbered.spanner.kind() == SpannerKind::MultiMeasureRest && numbered.holds(rest)
1992        })?;
1993        if !numbered.is_first(rest) {
1994            return None;
1995        }
1996        let use_symbols = numbered
1997            .spanner
1998            .multi_rest()
1999            .is_none_or(|said| said.use_symbols);
2000        let mut multiple = Element::new("multiple-rest");
2001        multiple.set("use-symbols", if use_symbols { "yes" } else { "no" });
2002        multiple.set_text(numbered.spanner.num_rests().to_string());
2003        let mut style = Element::new("measure-style");
2004        style.push(multiple);
2005        Some(style)
2006    }
2007
2008    /// music21's `mainElementsParse`.
2009    fn main_elements_parse(&mut self) -> Result<()> {
2010        let voices: Vec<&Stream> = self.stream.voices();
2011        if voices.is_empty() {
2012            return self.parse_flat_elements(self.stream, false, false);
2013        }
2014        self.parse_flat_elements(self.stream, false, true)?;
2015        let count = voices.len();
2016        for (index, voice) in voices.into_iter().enumerate() {
2017            self.parse_flat_elements(voice, true, index + 1 != count)?;
2018        }
2019        Ok(())
2020    }
2021
2022    /// music21's `parseFlatElements`: the elements of a measure or voice,
2023    /// grouped by offset, marks before notes within each group.
2024    fn parse_flat_elements(
2025        &mut self,
2026        stream: &Stream,
2027        is_voice: bool,
2028        backup_afterwards: bool,
2029    ) -> Result<()> {
2030        self.offset_in_measure = 0.0;
2031        self.current_voice = if is_voice {
2032            Some(match stream.id() {
2033                Some(id) => id.to_string(),
2034                None => {
2035                    let number = self.next_free_voice;
2036                    self.next_free_voice += 1;
2037                    number.to_string()
2038                }
2039            })
2040        } else {
2041            None
2042        };
2043
2044        let events: Vec<(FloatType, &StreamElement)> = stream
2045            .events()
2046            .iter()
2047            .filter(|event| !matches!(event.element(), StreamElement::Stream(inner) if inner.kind() == StreamKind::Voice))
2048            .map(|event| (event.offset(), event.element()))
2049            .collect();
2050        let mut index = 0;
2051        while index < events.len() {
2052            let group_offset = events[index].0;
2053            let mut end = index;
2054            while end < events.len() && events[end].0 == group_offset {
2055                end += 1;
2056            }
2057            let group = &events[index..end];
2058            let forward = group_offset - self.offset_in_measure;
2059            if forward > 0.0
2060                && group.iter().any(|(_, element)| {
2061                    is_general_note(element) || matches!(element, StreamElement::Clef(_))
2062                })
2063            {
2064                self.move_forward(forward);
2065            }
2066            let mut notes_for_later = Vec::new();
2067            for &(offset, element) in group {
2068                if is_written_as_note(element) {
2069                    notes_for_later.push((offset, element));
2070                } else {
2071                    self.parse_one_element(offset, element)?;
2072                }
2073            }
2074            for (offset, element) in notes_for_later {
2075                // An unprinted rest of a length no note value writes is
2076                // left as a gap, which the next element is moved past.
2077                if let StreamElement::Rest(rest) = element
2078                    && rest.hidden()
2079                    && rest.quarter_length() != 0.0
2080                    && rest.duration().components().is_empty()
2081                {
2082                    continue;
2083                }
2084                self.parse_one_element(offset, element)?;
2085            }
2086            index = end;
2087        }
2088
2089        if backup_afterwards && self.offset_in_measure != 0.0 {
2090            self.move_backward(self.offset_in_measure);
2091        }
2092        self.current_voice = None;
2093        Ok(())
2094    }
2095
2096    /// music21's `moveForward`.
2097    fn move_forward(&mut self, by: FloatType) {
2098        let amount = divisions(by);
2099        if amount != 0 {
2100            self.root
2101                .sub("forward")
2102                .sub_text("duration", amount.to_string());
2103            self.offset_in_measure += by;
2104        }
2105    }
2106
2107    /// music21's `moveBackward`.
2108    fn move_backward(&mut self, by: FloatType) {
2109        let amount = divisions(by);
2110        if amount != 0 {
2111            self.root
2112                .sub("backup")
2113                .sub_text("duration", amount.to_string());
2114            self.offset_in_measure -= by;
2115        }
2116    }
2117
2118    /// music21's `parseOneElement`.
2119    fn parse_one_element(&mut self, offset: FloatType, element: &StreamElement) -> Result<()> {
2120        let position = element as *const StreamElement;
2121        // Asked before the writer moves past the element, which is where a
2122        // pedal's resumed line counts its offset from.
2123        let (before, after) =
2124            related_spanners(position, &self.context.spanners, self.offset_in_measure);
2125        if is_written_as_note(element) {
2126            self.offset_in_measure += element.quarter_length();
2127        }
2128        for direction in before {
2129            self.root.push(direction);
2130        }
2131        self.write_element(offset, element, position)?;
2132        for direction in after {
2133            self.root.push(direction);
2134        }
2135        Ok(())
2136    }
2137
2138    /// The element itself, as `parseOneElement` writes it between the
2139    /// directions its spanners open and close with.
2140    fn write_element(
2141        &mut self,
2142        offset: FloatType,
2143        element: &StreamElement,
2144        position: *const StreamElement,
2145    ) -> Result<()> {
2146        self.element_offset = offset;
2147        match element {
2148            StreamElement::Note(note) => {
2149                let mxnote = self.note_element(note, 0, None, Some(position))?;
2150                self.root.push(mxnote);
2151            }
2152            // music21 sorts a chord in place before writing it.
2153            StreamElement::Chord(chord) => {
2154                self.chord_elements(&written_order(chord), Some(position))?
2155            }
2156            StreamElement::Unpitched(stroke) => {
2157                let mxnote =
2158                    self.written_note_element(stroke.written(), 0, None, Some(position), true)?;
2159                self.root.push(mxnote);
2160            }
2161            StreamElement::PercussionChord(chord) => {
2162                // Unlike a chord of pitches, its members stay in the order
2163                // they were given.
2164                let written = chord.written();
2165                for (index, note) in written.notes().iter().enumerate() {
2166                    let element = self.written_note_element(
2167                        note,
2168                        index,
2169                        Some(written),
2170                        Some(position),
2171                        chord.is_unpitched(index),
2172                    )?;
2173                    self.root.push(element);
2174                }
2175            }
2176            StreamElement::Rest(rest) => {
2177                let mxnote = self.rest_element(rest, offset, Some(position))?;
2178                self.root.push(mxnote);
2179            }
2180            StreamElement::Dynamic(dynamic) => self.dynamic_element(dynamic, offset)?,
2181            StreamElement::MetronomeMark(mark) => self.tempo_elements(mark, offset)?,
2182            StreamElement::MetricModulation(modulation) => {
2183                let resolved = self
2184                    .context
2185                    .modulations
2186                    .iter()
2187                    .find(|(held, _)| std::ptr::eq(*held, position))
2188                    .map_or(&**modulation, |(_, resolved)| resolved);
2189                let direction = self.metric_modulation_element(resolved, offset)?;
2190                self.root.push(direction);
2191            }
2192            StreamElement::TempoText(text) => {
2193                let direction = self.tempo_words(text.text(), text.placement(), offset);
2194                self.root.push(direction);
2195            }
2196            StreamElement::TextExpression(text) => {
2197                // music21's `textExpressionToXml`.
2198                let words = Element::with_text("words", text.content());
2199                let direction = self.direction(words, text.placement(), offset, false);
2200                self.root.push(direction);
2201            }
2202            StreamElement::RepeatExpression(mark) => {
2203                let direction = self.repeat_expression_element(mark, offset);
2204                self.root.push(direction);
2205            }
2206            StreamElement::KeySignature(_) | StreamElement::Key(_) => {
2207                if let Some(key) = key_element(element) {
2208                    let key = key?;
2209                    self.wrap_in_attributes(key);
2210                }
2211            }
2212            StreamElement::TimeSignature(meter) => {
2213                let meter = time_signature_element(meter)?;
2214                self.wrap_in_attributes(meter);
2215            }
2216            StreamElement::Clef(clef) => {
2217                self.context.clef = Some(clef.clone());
2218                let clef = clef_element(clef)?;
2219                self.wrap_in_attributes(clef);
2220            }
2221            // music21 writes nothing for an instrument inside a measure: it
2222            // is read into the part list instead.
2223            StreamElement::Instrument(_) => {}
2224            StreamElement::ChordSymbol(symbol) => {
2225                let harmony = self.harmony_element(symbol, offset)?;
2226                self.root.push(harmony);
2227            }
2228            StreamElement::Stream(inner) => {
2229                return Err(export_error(format!(
2230                    "a {} inside a measure cannot be written",
2231                    inner.kind()
2232                )));
2233            }
2234            StreamElement::PedalObject(object) => self.pedal_object_elements(object, position),
2235            StreamElement::RehearsalMark(mark) => {
2236                // music21's `rehearsalMarkToXml`: a mark is centred on where
2237                // it stands, as its class starts every mark out.
2238                let mut rehearsal = Element::with_text("rehearsal", mark.content());
2239                if let Some(enclosure) = mark.enclosure() {
2240                    rehearsal.set("enclosure", enclosure);
2241                }
2242                rehearsal.set("halign", "center");
2243                rehearsal.set("valign", "middle");
2244                let direction = self.direction(rehearsal, mark.placement(), offset, true);
2245                self.root.push(direction);
2246            }
2247            // music21 writes nothing for a barline standing inside a
2248            // measure: `Barline` is one of `ignoreOnParseClasses`. A
2249            // manuscript's break is no class its exporter knows.
2250            StreamElement::Barline(_)
2251            | StreamElement::Break(_)
2252            | StreamElement::Layout(_)
2253            | StreamElement::TextBox(_)
2254            | StreamElement::Variant(_)
2255            | StreamElement::GlobalComment(_)
2256            | StreamElement::MiscTandem(_)
2257            | StreamElement::SpineComment(_)
2258            | StreamElement::BrailleSegmentDivision(_) => {}
2259        }
2260        Ok(())
2261    }
2262
2263    /// music21's `pedalObjectToXml`: a bounce or a gap in a held pedal, as
2264    /// the pedal mark holding it is drawn. One no pedal mark holds writes
2265    /// nothing.
2266    fn pedal_object_elements(&mut self, object: &PedalObject, position: *const StreamElement) {
2267        let Some(pedal) = self
2268            .context
2269            .spanners
2270            .iter()
2271            .find(|numbered| {
2272                numbered.spanner.kind() == SpannerKind::PedalMark && numbered.holds(position)
2273            })
2274            .map(|numbered| numbered.spanner.pedal().unwrap_or_default())
2275        else {
2276            return;
2277        };
2278        let lined = pedal.form.is_some_and(PedalForm::has_line);
2279        // Soft and silent pedals have no start of their own in MusicXML, and
2280        // music21 writes them, and a pedal that does not say, as `sustain`.
2281        let down = match pedal.pedal_type {
2282            Some(PedalType::Sostenuto) => "sostenuto",
2283            Some(PedalType::Sustain) => "start",
2284            _ => "sustain",
2285        };
2286        let types: &[&str] = match object.kind() {
2287            PedalObjectKind::Bounce => match pedal.form {
2288                Some(PedalForm::Line | PedalForm::SymbolLine) => &["change"],
2289                Some(PedalForm::SymbolAlt) => &[down],
2290                Some(PedalForm::Symbol) => &["stop", down],
2291                None => return,
2292            },
2293            PedalObjectKind::GapStart => &["discontinue"],
2294            PedalObjectKind::GapEnd => &["resume"],
2295        };
2296        for kind in types {
2297            let mut mark = Element::new("pedal");
2298            mark.set("type", *kind);
2299            mark.set(if lined { "line" } else { "sign" }, "yes");
2300            let direction = self.direction(mark, object.placement(), self.element_offset, true);
2301            self.root.push(direction);
2302        }
2303    }
2304
2305    /// music21's `wrapObjectInAttributes`: a mark after the start of a
2306    /// measure gets an `<attributes>` of its own; one at the start is already
2307    /// in the measure's first.
2308    fn wrap_in_attributes(&mut self, element: Element) {
2309        if self.offset_in_measure == 0.0 {
2310            return;
2311        }
2312        let mut attributes = Element::new("attributes");
2313        attributes.push(element);
2314        self.root.push(attributes);
2315    }
2316
2317    // --------------------------------------------------------- notes
2318
2319    /// music21's `noteToXml`, for a note alone or the `index`th of a chord.
2320    fn note_element(
2321        &self,
2322        note: &Note,
2323        index: usize,
2324        chord: Option<&Chord>,
2325        position: Option<*const StreamElement>,
2326    ) -> Result<Element> {
2327        self.written_note_element(note, index, chord, position, false)
2328    }
2329
2330    /// `noteToXml` for a note, or `unpitchedToXml` for a stroke with no
2331    /// pitch, which is written where it is displayed and has no accidental.
2332    fn written_note_element(
2333        &self,
2334        note: &Note,
2335        index: usize,
2336        chord: Option<&Chord>,
2337        position: Option<*const StreamElement>,
2338        unpitched: bool,
2339    ) -> Result<Element> {
2340        let in_chord = index != 0;
2341        let mut mxnote = Element::new("note");
2342        if chord.is_some()
2343            && let Some(color) = note.color()
2344        {
2345            mxnote.set("color", normalize_color(color)?);
2346        }
2347        if let Some(color) = chord.map_or(note.color(), Chord::color) {
2348            mxnote.set("color", normalize_color(color)?);
2349        }
2350        let volume = match chord {
2351            Some(chord) => chord.has_volume_information().then(|| chord.volume()),
2352            None => note.has_volume_information().then(|| note.volume()),
2353        };
2354        if let Some(scalar) = volume.and_then(|volume| volume.velocity_scalar()) {
2355            let velocity = scalar * 100.0 * (127.0 / 90.0);
2356            mxnote.set("dynamics", format!("{velocity:.2}"));
2357        }
2358        // An id is written only where it is a name XML takes as one.
2359        if let Some(id) = note.id()
2360            && id
2361                .chars()
2362                .next()
2363                .is_some_and(|first| first.is_alphabetic() || first == '_')
2364            && id
2365                .chars()
2366                .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
2367        {
2368            mxnote.set("id", id);
2369        }
2370        let duration = chord
2371            .map_or_else(|| note.duration(), Chord::duration)
2372            .cloned()
2373            .unwrap_or_default();
2374        if note.hidden() {
2375            mxnote.set("print-object", "no");
2376            mxnote.set("print-spacing", "yes");
2377        }
2378        if chord
2379            .map_or(note.articulations(), Chord::articulations)
2380            .iter()
2381            .any(|articulation| articulation.is_a("Pizzicato"))
2382        {
2383            mxnote.set("pizzicato", "yes");
2384        }
2385
2386        if let Some(grace) = duration.grace() {
2387            let element = mxnote.sub("grace");
2388            element.set("slash", yes_no(grace.slash()));
2389            if let Some(share) = grace.steal_time_previous() {
2390                element.set("steal-time-previous", fraction_to_percent(share));
2391            }
2392            if let Some(share) = grace.steal_time_following() {
2393                element.set("steal-time-following", fraction_to_percent(share));
2394            }
2395        }
2396        if in_chord {
2397            mxnote.sub("chord");
2398        }
2399        if unpitched {
2400            let displayed = mxnote.sub("unpitched");
2401            displayed.sub_text("display-step", note.pitch().step().as_char().to_string());
2402            displayed.sub_text(
2403                "display-octave",
2404                musicxml_octave(note.pitch().implicit_octave()).to_string(),
2405            );
2406        } else {
2407            mxnote.push(pitch_element(note.pitch()));
2408        }
2409        if !duration.is_grace() {
2410            mxnote.sub_text("duration", divisions(duration.quarter_length()).to_string());
2411        }
2412        if let Some(tie) = note.tie() {
2413            for element in tie_elements(tie) {
2414                mxnote.push(element);
2415            }
2416        }
2417        let stored = chord.map_or(note.stored_instrument(), Chord::stored_instrument);
2418        self.set_note_instrument(&mut mxnote, stored)?;
2419        if let Some(voice) = &self.current_voice {
2420            mxnote.sub_text("voice", voice.as_str());
2421        }
2422        // A grace note with no written value of its own is an eighth.
2423        let (written_type, dots) = match written_type(&duration) {
2424            Err(_) if duration.is_grace() && duration.components().is_empty() => ("eighth", 0),
2425            other => other?,
2426        };
2427        let written = mxnote.sub("type");
2428        written.set_text(written_type);
2429        if let Some(size) = note.size() {
2430            written.set("size", size.as_str());
2431        }
2432        for _ in 0..dots {
2433            mxnote.sub("dot");
2434        }
2435        if !unpitched
2436            && let Some(accidental) = note.pitch().written_accidental()
2437            && accidental.display_status() != Some(false)
2438        {
2439            mxnote.push(accidental_element(accidental, "accidental")?);
2440        }
2441        if let Some(modification) = time_modification(&duration)? {
2442            mxnote.push(modification);
2443        }
2444
2445        let chord_stem = chord.map_or(note.stem_direction(), Chord::stem_direction);
2446        let stem = if !in_chord && chord_stem != StemDirection::Unspecified {
2447            Some(chord_stem)
2448        } else if chord.is_some() && note.stem_direction() != StemDirection::Unspecified {
2449            Some(note.stem_direction())
2450        } else {
2451            None
2452        };
2453        if let Some(stem) = stem {
2454            let text = match stem {
2455                StemDirection::NoStem => "none",
2456                other => other.as_str(),
2457            };
2458            mxnote.sub_text("stem", text);
2459        }
2460
2461        if let Some(notehead) = notehead_for(note, chord)? {
2462            mxnote.push(notehead);
2463        }
2464        if !in_chord {
2465            let beams = chord.map_or(note.beams(), Chord::beams);
2466            for element in beam_elements(beams)? {
2467                mxnote.push(element);
2468            }
2469        }
2470
2471        let spanners: &[Numbered<'_>] = match position {
2472            Some(_) => &self.context.spanners,
2473            None => &[],
2474        };
2475        let pitch = note.pitch().ps();
2476        let mut notations = note_notations(
2477            note,
2478            index,
2479            chord,
2480            position,
2481            spanners,
2482            &self.arpeggios,
2483            pitch,
2484        )?;
2485        if !in_chord {
2486            notations.extend(tuplet_notations(&duration)?);
2487        }
2488        if !notations.is_empty() {
2489            let mxnotations = mxnote.sub("notations");
2490            for element in notations {
2491                mxnotations.push(element);
2492            }
2493        }
2494        if !in_chord {
2495            let lyrics = chord.map_or(note.lyrics(), Chord::lyrics);
2496            for lyric in lyrics {
2497                if lyric.explicit_text().is_none() {
2498                    continue;
2499                }
2500                mxnote.push(lyric_element(lyric)?);
2501            }
2502        }
2503        Ok(mxnote)
2504    }
2505
2506    /// music21's `setNoteInstrument`: which instrument plays a note, where
2507    /// a part has more than one.
2508    ///
2509    /// The instrument is the one kept on the note or its chord, or else the
2510    /// last one standing in the staff at or before the note; it is named by
2511    /// the id of the part's first instrument of the same kind.
2512    fn set_note_instrument(&self, mxnote: &mut Element, stored: Option<&Instrument>) -> Result<()> {
2513        if self.context.instruments.len() <= 1 {
2514            return Ok(());
2515        }
2516        let at = self.start + self.element_offset;
2517        let default;
2518        let closest = match stored.or_else(|| {
2519            self.context
2520                .own_instruments
2521                .iter()
2522                .rev()
2523                .find(|(offset, _)| *offset <= at)
2524                .map(|(_, instrument)| *instrument)
2525        }) {
2526            Some(instrument) => instrument,
2527            None => {
2528                default = Instrument::new();
2529                &default
2530            }
2531        };
2532        let named = self
2533            .context
2534            .instruments
2535            .iter()
2536            .find(|placed| placed.instrument.kind() == closest.kind())
2537            .ok_or_else(|| {
2538                export_error(format!(
2539                    "Instrument instance {} for a note not found in instrumentStream",
2540                    closest.kind()
2541                ))
2542            })?;
2543        let element = mxnote.sub("instrument");
2544        if let Some(id) = named.instrument.instrument_id() {
2545            element.set("id", id);
2546        }
2547        Ok(())
2548    }
2549
2550    /// music21's `chordToXml`: a `<note>` for each of the chord's notes,
2551    /// in the order the chord holds them, every one after the first marked `<chord/>`.
2552    fn chord_elements(
2553        &mut self,
2554        chord: &Chord,
2555        position: Option<*const StreamElement>,
2556    ) -> Result<()> {
2557        for (index, note) in chord.notes().iter().enumerate() {
2558            let element = self.note_element(note, index, Some(chord), position)?;
2559            self.root.push(element);
2560        }
2561        Ok(())
2562    }
2563
2564    /// music21's `restToXml`.
2565    fn rest_element(
2566        &self,
2567        rest: &Rest,
2568        offset: FloatType,
2569        position: Option<*const StreamElement>,
2570    ) -> Result<Element> {
2571        let mut mxnote = Element::new("note");
2572        if let Some(color) = rest.color() {
2573            mxnote.set("color", normalize_color(color)?);
2574        }
2575        if rest.hidden() {
2576            mxnote.set("print-object", "no");
2577            mxnote.set("print-spacing", "yes");
2578        }
2579        let duration = rest.duration();
2580        // music21's `fullMeasure` first, and for its `'auto'` the bar.
2581        let full_measure = match rest.full_measure() {
2582            FullMeasure::Yes | FullMeasure::Always => true,
2583            FullMeasure::No => false,
2584            FullMeasure::Auto => self
2585                .meter_at(offset)
2586                .is_some_and(|meter| meter.bar_quarter_length() == duration.quarter_length()),
2587        };
2588        let mxrest = mxnote.sub("rest");
2589        if full_measure {
2590            mxrest.set("measure", "yes");
2591        }
2592        if rest.step_shift() != 0 {
2593            // music21 counts from the middle line of the clef in force, a
2594            // treble clef's where there is none that places pitches.
2595            // The clef is the last one standing in the staff at or before
2596            // the rest, wherever the writer has got to in another voice.
2597            let at = self.start + offset;
2598            let lowest = self
2599                .context
2600                .own_clefs
2601                .iter()
2602                .rev()
2603                .find(|(clef_offset, _)| *clef_offset <= at)
2604                .and_then(|(_, clef)| clef.lowest_line())
2605                .or_else(|| Clef::treble().lowest_line())
2606                .unwrap_or(31);
2607            let (step, octave) = step_and_octave(lowest + 4 + rest.step_shift());
2608            mxrest.sub_text("display-step", step.to_string());
2609            mxrest.sub_text("display-octave", musicxml_octave(octave).to_string());
2610        }
2611        mxnote.sub_text("duration", divisions(duration.quarter_length()).to_string());
2612        if let Some(tie) = rest.tie() {
2613            for element in tie_elements(tie) {
2614                mxnote.push(element);
2615            }
2616        }
2617        if let Some(voice) = &self.current_voice {
2618            mxnote.sub_text("voice", voice.as_str());
2619        }
2620        if !full_measure {
2621            let (written_type, dots) = written_type(duration)?;
2622            let written = mxnote.sub("type");
2623            written.set_text(written_type);
2624            if let Some(size) = rest.size() {
2625                written.set("size", size.as_str());
2626            }
2627            for _ in 0..dots {
2628                mxnote.sub("dot");
2629            }
2630        }
2631        if let Some(modification) = time_modification(duration)? {
2632            mxnote.push(modification);
2633        }
2634        let mut notations = notations(
2635            Marks {
2636                expressions: rest.expressions(),
2637                articulations: rest.articulations(),
2638                tie: rest.tie(),
2639                index: 0,
2640                last: 0,
2641                arpeggios: &self.arpeggios,
2642                pitch: None,
2643            },
2644            position,
2645            &self.context.spanners,
2646        )?;
2647        notations.extend(tuplet_notations(duration)?);
2648        if !notations.is_empty() {
2649            let mxnotations = mxnote.sub("notations");
2650            for element in notations {
2651                mxnotations.push(element);
2652            }
2653        }
2654        for lyric in rest.lyrics() {
2655            if lyric.explicit_text().is_none() {
2656                continue;
2657            }
2658            mxnote.push(lyric_element(lyric)?);
2659        }
2660        Ok(mxnote)
2661    }
2662
2663    /// The metre in force at an offset within the measure: music21's
2664    /// `getContextByClass(TimeSignature)` from a rest.
2665    fn meter_at(&self, offset: FloatType) -> Option<TimeSignature> {
2666        self.stream
2667            .events()
2668            .iter()
2669            .rev()
2670            .filter(|event| event.offset() <= offset)
2671            .find_map(|event| match event.element() {
2672                StreamElement::TimeSignature(meter) => Some(meter.clone()),
2673                _ => None,
2674            })
2675            .or_else(|| self.context.meter.clone())
2676    }
2677
2678    // ---------------------------------------------------- directions
2679
2680    /// music21's `setOffsetOptional`: an `<offset>` for a direction that does
2681    /// not stand where the writer has got to.
2682    fn offset_element(&self, offset: FloatType, sound: bool) -> Option<Element> {
2683        offset_element_from(offset, self.offset_in_measure, sound)
2684    }
2685
2686    /// music21's `placeInDirection`.
2687    fn direction(
2688        &self,
2689        inner: Element,
2690        placement: Option<Placement>,
2691        offset: FloatType,
2692        sound: bool,
2693    ) -> Element {
2694        let mut direction = Element::new("direction");
2695        direction.sub("direction-type").push(inner);
2696        if let Some(placement) = placement {
2697            direction.set("placement", placement.as_str());
2698        }
2699        if let Some(element) = self.offset_element(offset, sound) {
2700            direction.push(element);
2701        }
2702        direction
2703    }
2704
2705    /// music21's `segnoToXml` and `codaToXml` for a sign, and
2706    /// `textExpressionToXml` for words: a sign stands two staff lines up,
2707    /// and words are justified as their kind of mark is.
2708    fn repeat_expression_element(&self, mark: &RepeatExpression, offset: FloatType) -> Element {
2709        if mark.use_symbol() && mark.kind().has_symbol() {
2710            let tag = match mark.kind() {
2711                RepeatExpressionKind::Segno => "segno",
2712                _ => "coda",
2713            };
2714            let mut sign = Element::new(tag);
2715            sign.set("default-y", "20");
2716            return self.direction(sign, mark.placement(), offset, true);
2717        }
2718        let mut words = Element::with_text("words", mark.text());
2719        words.set("justify", mark.kind().justify());
2720        self.direction(words, mark.placement(), offset, false)
2721    }
2722
2723    /// music21's `chordSymbolToXml`, and `noChordToXml` for a symbol saying
2724    /// nothing sounds.
2725    fn harmony_element(&self, symbol: &ChordSymbol, offset: FloatType) -> Result<Element> {
2726        let mut harmony = Element::new("harmony");
2727        if let Some(placement) = symbol.placement() {
2728            harmony.set("placement", placement.as_str());
2729        }
2730        let alter_of = |pitch: &Pitch| {
2731            pitch
2732                .written_accidental()
2733                .map(|accidental| accidental.alter())
2734        };
2735        if symbol.is_no_chord() {
2736            let root = harmony.sub("root");
2737            let step = root.sub("root-step");
2738            step.set_text("C");
2739            step.set("text", "");
2740            let kind = harmony.sub("kind");
2741            kind.set_text("none");
2742            kind.set(
2743                "text",
2744                symbol.kind_text().ok_or_else(|| {
2745                    export_error("NoChord object's chordKindStr must be non-empty")
2746                })?,
2747            );
2748        } else {
2749            let root = symbol.root();
2750            let written = harmony.sub("root");
2751            written.sub_text("root-step", root.step().as_char().to_string());
2752            if let Some(alter) = alter_of(root) {
2753                written.sub_text("root-alter", num_to_int_or_float(alter));
2754            }
2755            let mut kind = symbol.kind().unwrap_or("none");
2756            for (alias, target) in crate::chordsymbol::CHORD_KIND_ALIASES {
2757                if target == kind {
2758                    kind = alias;
2759                }
2760            }
2761            let written = harmony.sub("kind");
2762            written.set_text(kind);
2763            if let Some(text) = symbol.kind_text() {
2764                written.set("text", text);
2765            }
2766            // music21 reads the inversion off the chord the symbol sounds,
2767            // counted from the symbol's own root.
2768            let sounded = symbol.pitches().ok().filter(|pitches| !pitches.is_empty());
2769            let chord = sounded
2770                .as_ref()
2771                .and_then(|pitches| Chord::new(pitches.as_slice()).ok())
2772                .map(|mut chord| {
2773                    chord.set_root(Some(root.clone()));
2774                    chord
2775                });
2776            if let Some(inversion) = chord.as_ref().and_then(Chord::inversion)
2777                && inversion != 0
2778            {
2779                harmony.sub_text("inversion", inversion.to_string());
2780            }
2781            let bass = symbol.bass().cloned().or_else(|| {
2782                sounded
2783                    .as_ref()
2784                    .and_then(|pitches| pitches.first().cloned())
2785            });
2786            if let Some(bass) = bass
2787                && bass.name() != root.name()
2788            {
2789                let written = harmony.sub("bass");
2790                written.sub_text("bass-step", bass.step().as_char().to_string());
2791                if let Some(alter) = alter_of(&bass) {
2792                    written.sub_text("bass-alter", num_to_int_or_float(alter));
2793                }
2794            }
2795            for modification in symbol.chord_step_modifications() {
2796                let degree = harmony.sub("degree");
2797                degree.sub_text("degree-value", modification.degree().to_string());
2798                degree.sub_text(
2799                    "degree-alter",
2800                    num_to_int_or_float(modification.interval().semitones()),
2801                );
2802                degree.sub_text(
2803                    "degree-type",
2804                    modification.modification_type().music21_name(),
2805                );
2806            }
2807        }
2808        if let Some(figure) = symbol.numeral() {
2809            numeral_in_place_of_root(&mut harmony, figure);
2810        }
2811        if let Some(element) = self.offset_element(offset, true) {
2812            harmony.push(element);
2813        }
2814        Ok(harmony)
2815    }
2816
2817    /// music21's `dynamicToXml`.
2818    fn dynamic_element(&mut self, dynamic: &Dynamic, offset: FloatType) -> Result<()> {
2819        let mut dynamics = Element::new("dynamics");
2820        if DYNAMIC_MARKS.contains(&dynamic.value()) {
2821            dynamics.sub(dynamic_tag(dynamic.value()));
2822        } else {
2823            dynamics.sub_text("other-dynamics", dynamic.value());
2824        }
2825        // music21's `setPrintStyleAlign`: where the style puts it.
2826        set_print_style_align(&mut dynamics, dynamic.style())?;
2827        let mut direction = self.direction(dynamics, dynamic.placement(), offset, true);
2828        let volume = (dynamic.volume_scalar() * 127.0) as i64;
2829        direction.sub("sound").set("dynamics", volume.to_string());
2830        self.root.push(direction);
2831        Ok(())
2832    }
2833
2834    /// music21's `tempoIndicationToXml` for a metronome mark: the mark, and
2835    /// its word as a direction of its own where the word was written.
2836    fn tempo_elements(&mut self, mark: &MetronomeMark, offset: FloatType) -> Result<()> {
2837        let shown = !mark.number_implicit() && mark.number().is_some();
2838        let direction = if shown {
2839            let mut metronome = Element::new("metronome");
2840            let (beat_unit, dots) = written_type(mark.referent())?;
2841            metronome.sub_text("beat-unit", beat_unit);
2842            for _ in 0..dots {
2843                metronome.sub("beat-unit-dot");
2844            }
2845            if let Some(number) = mark.number() {
2846                metronome.sub_text("per-minute", num_to_int_or_float(number));
2847            }
2848            metronome.set("parentheses", yes_no(mark.parentheses()));
2849            self.direction(metronome, mark.placement(), offset, true)
2850        } else {
2851            self.direction(Element::new("words"), mark.placement(), offset, true)
2852        };
2853        let mut direction = direction;
2854        if let Some(bpm) = mark.sounding_quarter_bpm().filter(|bpm| *bpm != 0.0) {
2855            direction
2856                .sub("sound")
2857                .set("tempo", num_to_int_or_float(bpm));
2858        }
2859        self.root.push(direction);
2860
2861        if let Some(text) = mark.text_expression(false) {
2862            let direction = self.tempo_words(text, None, offset);
2863            self.root.push(direction);
2864        }
2865        Ok(())
2866    }
2867
2868    /// music21's `tempoIndicationToXml` for a metric modulation: the two
2869    /// note values side by side, neither with its number, and the speed the
2870    /// new one is played at.
2871    fn metric_modulation_element(
2872        &self,
2873        modulation: &MetricModulation,
2874        offset: FloatType,
2875    ) -> Result<Element> {
2876        let mut metronome = Element::new("metronome");
2877        for side in [modulation.old_metronome(), modulation.new_metronome()] {
2878            let side = side.ok_or_else(|| {
2879                export_error("a metric modulation needs a mark on both sides to be written")
2880            })?;
2881            let (beat_unit, dots) = written_type(side.referent())?;
2882            metronome.sub_text("beat-unit", beat_unit);
2883            for _ in 0..dots {
2884                metronome.sub("beat-unit-dot");
2885            }
2886        }
2887        metronome.set("parentheses", yes_no(modulation.parentheses()));
2888        let mut direction = self.direction(metronome, modulation.placement(), offset, true);
2889        if let Some(bpm) = modulation
2890            .new_metronome()
2891            .and_then(MetronomeMark::sounding_quarter_bpm)
2892            .filter(|bpm| *bpm != 0.0)
2893        {
2894            direction
2895                .sub("sound")
2896                .set("tempo", num_to_int_or_float(bpm));
2897        }
2898        Ok(direction)
2899    }
2900
2901    /// A tempo said in words, as music21's `TempoText.applyTextFormatting`
2902    /// sets them: bold, four and a half staff lines up.
2903    fn tempo_words(&self, text: &str, placement: Option<Placement>, offset: FloatType) -> Element {
2904        let mut words = Element::with_text("words", text);
2905        words.set("default-y", "45");
2906        words.set("font-weight", "bold");
2907        self.direction(words, placement, offset, false)
2908    }
2909}
2910
2911/// music21's `noteToNotations`: what goes inside a note's `<notations>`,
2912/// less the tuplet brackets, which the caller adds after.
2913///
2914/// Expressions come from the chord where the note is one of a chord's. An
2915/// arpeggio is written on every note of it, a bracket against arpeggiating
2916/// on the bottom and top notes only, and everything else on the first note
2917/// alone; ornaments are gathered into one `<ornaments>` at the end.
2918fn note_notations(
2919    note: &Note,
2920    index: usize,
2921    chord: Option<&Chord>,
2922    position: Option<*const StreamElement>,
2923    spanners: &[Numbered<'_>],
2924    arpeggios: &ArpeggioNumbers,
2925    pitch: FloatType,
2926) -> Result<Vec<Element>> {
2927    notations(
2928        Marks {
2929            expressions: chord.map_or(note.expressions(), Chord::expressions),
2930            articulations: chord.map_or(note.articulations(), Chord::articulations),
2931            tie: note.tie(),
2932            index,
2933            last: chord.map_or(0, |chord| chord.notes().len().saturating_sub(1)),
2934            arpeggios,
2935            pitch: Some(pitch),
2936        },
2937        position,
2938        spanners,
2939    )
2940}
2941
2942/// What goes into one `<note>`'s notations: the expressions and
2943/// articulations it is written with, its tie, and which note of its chord it
2944/// is, the last being the top.
2945struct Marks<'a> {
2946    expressions: &'a [Expression],
2947    articulations: &'a [Articulation],
2948    tie: Option<&'a Tie>,
2949    index: usize,
2950    last: usize,
2951    /// The numbers the measure's arpeggios across chords are written with.
2952    arpeggios: &'a ArpeggioNumbers,
2953    /// The note's pitch space, where it is a note.
2954    pitch: Option<FloatType>,
2955}
2956
2957/// music21's `noteToNotations`, for a note or a rest.
2958fn notations(
2959    marks: Marks<'_>,
2960    position: Option<*const StreamElement>,
2961    spanners: &[Numbered<'_>],
2962) -> Result<Vec<Element>> {
2963    let index = marks.index;
2964    let first = index == 0;
2965    let mut notations = Vec::new();
2966    let (articulations, technical) = articulation_elements(marks.articulations, index);
2967    let mut ornaments: Option<Element> = None;
2968    for expression in marks.expressions {
2969        match expression {
2970            Expression::Arpeggio(ArpeggioType::NonArpeggio) => {
2971                let last = marks.last;
2972                let side = if first {
2973                    Some("bottom")
2974                } else if index == last {
2975                    Some("top")
2976                } else {
2977                    None
2978                };
2979                if let Some(side) = side {
2980                    let mut element = Element::new("non-arpeggiate");
2981                    element.set("type", side);
2982                    notations.push(element);
2983                }
2984            }
2985            Expression::Arpeggio(arpeggio) => {
2986                let mut element = Element::new("arpeggiate");
2987                if *arpeggio != ArpeggioType::Normal {
2988                    element.set("direction", arpeggio.as_str());
2989                }
2990                notations.push(element);
2991            }
2992            Expression::Fermata(fermata) if first => {
2993                let mut element = Element::new("fermata");
2994                element.set("type", fermata.fermata_type().as_str());
2995                if let Some(shape @ ("angled" | "square")) = fermata.shape() {
2996                    element.set_text(shape);
2997                }
2998                notations.push(element);
2999            }
3000            Expression::Ornament(ornament) if first => {
3001                let written = ornaments.get_or_insert_with(|| Element::new("ornaments"));
3002                written.push(ornament_element(ornament));
3003                for mark in ornament_accidental_marks(ornament)? {
3004                    written.push(mark);
3005                }
3006            }
3007            Expression::Fermata(_) | Expression::Ornament(_) => {}
3008        }
3009    }
3010    if let Some(tie) = marks.tie {
3011        notations.extend(tied_elements(tie));
3012    }
3013    if let Some(position) = position {
3014        notations.extend(spanner_notations(position, spanners, &marks));
3015    }
3016    notations.extend(articulations);
3017    notations.extend(technical);
3018    notations.extend(ornaments);
3019    Ok(notations)
3020}
3021
3022/// A chord in the order music21's exporter writes it: sorted by staff
3023/// position and pitch space. Its fingerings stay as they are, since they
3024/// go to the notes from the lowest up.
3025fn written_order(chord: &Chord) -> Chord {
3026    chord.sort_ascending()
3027}
3028
3029/// The `<articulations>` and `<technical>` of a note, the `index`th of its
3030/// chord where it is one: a fingering is written on the note it is the
3031/// turn of, anything else on the first note only. A pizzicato is written as
3032/// an attribute of the note instead, and a string numbered below one not at
3033/// all.
3034fn articulation_elements(
3035    articulations: &[Articulation],
3036    index: usize,
3037) -> (Option<Element>, Option<Element>) {
3038    let mut fingering = 0;
3039    let mut applicable = Vec::new();
3040    for articulation in articulations {
3041        if articulation.is_a("Fingering") {
3042            if fingering == index {
3043                applicable.push(articulation);
3044            }
3045            fingering += 1;
3046        } else if index == 0 && !articulation.is_a("HammerOn") && !articulation.is_a("PullOff") {
3047            applicable.push(articulation);
3048        }
3049    }
3050    let mut written: Option<Element> = None;
3051    let mut technical: Option<Element> = None;
3052    for articulation in applicable {
3053        if articulation.is_a("Pizzicato")
3054            || (articulation.is_a("StringIndication") && articulation.number() < 1)
3055        {
3056            continue;
3057        }
3058        if articulation.is_a("TechnicalIndication") {
3059            technical
3060                .get_or_insert_with(|| Element::new("technical"))
3061                .push(technical_element(articulation));
3062        } else {
3063            written
3064                .get_or_insert_with(|| Element::new("articulations"))
3065                .push(articulation_element(articulation));
3066        }
3067    }
3068    (written, technical)
3069}
3070
3071/// music21's `xmlObjects.ARTICULATION_MARKS_REV`, in the order it is
3072/// searched: the staccato and the accent last, as they are what others
3073/// descend from.
3074const ARTICULATION_NAMES: [(&str, &str); 15] = [
3075    ("StrongAccent", "strong-accent"),
3076    ("Staccatissimo", "staccatissimo"),
3077    ("Spiccato", "spiccato"),
3078    ("Tenuto", "tenuto"),
3079    ("DetachedLegato", "detached-legato"),
3080    ("Scoop", "scoop"),
3081    ("Plop", "plop"),
3082    ("Doit", "doit"),
3083    ("Falloff", "falloff"),
3084    ("BreathMark", "breath-mark"),
3085    ("Caesura", "caesura"),
3086    ("Stress", "stress"),
3087    ("Unstress", "unstress"),
3088    ("Staccato", "staccato"),
3089    ("Accent", "accent"),
3090];
3091
3092/// music21's `articulationToXmlArticulation`.
3093fn articulation_element(articulation: &Articulation) -> Element {
3094    let name = ARTICULATION_NAMES
3095        .iter()
3096        .find(|(class, _)| articulation.is_a(class))
3097        .map_or("other-articulation", |(_, name)| name);
3098    let mut element = Element::new(name);
3099    if let Some(placement) = articulation.placement() {
3100        element.set("placement", placement);
3101    }
3102    match name {
3103        "strong-accent" => {
3104            element.set("type", articulation.point_direction().unwrap_or("None"));
3105        }
3106        "breath-mark" => {
3107            if let Some(symbol) = articulation.symbol() {
3108                element.set_text(symbol);
3109            }
3110        }
3111        "other-articulation" => {
3112            if let Some(text) = articulation.display_text() {
3113                element.set_text(text);
3114            }
3115        }
3116        _ => {}
3117    }
3118    element
3119}
3120
3121/// music21's `xmlObjects.TECHNICAL_MARKS_REV`, in the order it is searched.
3122const TECHNICAL_NAMES: [(&str, &str); 20] = [
3123    ("UpBow", "up-bow"),
3124    ("DownBow", "down-bow"),
3125    ("StringHarmonic", "harmonic"),
3126    ("OpenString", "open-string"),
3127    ("StringThumbPosition", "thumb-position"),
3128    ("Fingering", "fingering"),
3129    ("FrettedPluck", "pluck"),
3130    ("DoubleTongue", "double-tongue"),
3131    ("TripleTongue", "triple-tongue"),
3132    ("Stopped", "stopped"),
3133    ("SnapPizzicato", "snap-pizzicato"),
3134    ("StringIndication", "string"),
3135    ("FretBend", "bend"),
3136    ("FretTap", "tap"),
3137    ("FretIndication", "fret"),
3138    ("OrganHeel", "heel"),
3139    ("OrganToe", "toe"),
3140    ("HarpFingerNails", "fingernails"),
3141    ("HandbellIndication", "handbell"),
3142    ("Harmonic", "harmonic"),
3143];
3144
3145/// music21's `articulationToXmlTechnical`.
3146fn technical_element(articulation: &Articulation) -> Element {
3147    use crate::articulations::Finger;
3148    let name = TECHNICAL_NAMES
3149        .iter()
3150        .find(|(class, _)| articulation.is_a(class))
3151        .map_or("other-technical", |(_, name)| name);
3152    let mut element = Element::new(name);
3153    if let Some(placement) = articulation.placement() {
3154        element.set("placement", placement);
3155    }
3156    match name {
3157        "fingering" => {
3158            element.set_text(match articulation.finger() {
3159                Some(Finger::Number(number)) => number.to_string(),
3160                Some(Finger::Written(text)) => text.clone(),
3161                None => "None".to_string(),
3162            });
3163            element.set("alternate", yes_no(articulation.alternate()));
3164            element.set("substitution", yes_no(articulation.substitution()));
3165        }
3166        "heel" | "toe" => element.set("substitution", yes_no(articulation.substitution())),
3167        "string" | "fret" => element.set_text(articulation.number().to_string()),
3168        "bend" => {
3169            let alter = element.sub("bend-alter");
3170            if let Some(interval) = articulation.bend_alter() {
3171                alter.set_text(num_to_int_or_float(interval.semitones()));
3172            }
3173            if articulation.pre_bend() {
3174                element.sub("pre-bend");
3175            }
3176            if let Some(release) = articulation.release() {
3177                let offset = (DIVISIONS_PER_QUARTER * release) as i64;
3178                element.sub("release").set("offset", offset.to_string());
3179            }
3180            if let Some(with_bar) = articulation.with_bar() {
3181                element.sub_text("with-bar", with_bar);
3182            }
3183        }
3184        "harmonic" => {
3185            if articulation.is_a("StringHarmonic") {
3186                match articulation.harmonic_type() {
3187                    Some("artificial") => {
3188                        element.sub("artificial");
3189                    }
3190                    Some("natural") => {
3191                        element.sub("natural");
3192                    }
3193                    _ => {}
3194                }
3195                match articulation.pitch_type() {
3196                    Some("base") => {
3197                        element.sub("base-pitch");
3198                    }
3199                    Some("sounding") => {
3200                        element.sub("sounding-pitch");
3201                    }
3202                    Some("touching") => {
3203                        element.sub("touching-pitch");
3204                    }
3205                    _ => {}
3206                }
3207            }
3208        }
3209        "handbell" | "other-technical" => {
3210            if let Some(text) = articulation.display_text() {
3211                element.set_text(text);
3212            }
3213        }
3214        _ => {}
3215    }
3216    element
3217}
3218
3219/// music21's `relatedSpanners`: the directions a hairpin opens with before
3220/// the element it starts on, and closes with after the one it ends on. A
3221/// hairpin over one element does both. A pedal drawn as a sign and a line
3222/// resumes its line straight after the sign, at the pedal mark's own offset
3223/// counted from `offset_in_measure`: music21's `makePedalResumeLineXml`.
3224fn related_spanners(
3225    position: *const StreamElement,
3226    spanners: &[Numbered<'_>],
3227    offset_in_measure: FloatType,
3228) -> (Vec<Element>, Vec<Element>) {
3229    let mut before = Vec::new();
3230    let mut after = Vec::new();
3231    // music21 asks the octave lines first, then the hairpins, the lines and
3232    // the pedal marks, and of each only those holding the element.
3233    let of_kind = |wanted: fn(SpannerKind) -> bool| {
3234        spanners
3235            .iter()
3236            .filter(move |numbered| wanted(numbered.spanner.kind()))
3237    };
3238    let ordered = of_kind(|kind| kind == SpannerKind::Ottava)
3239        .chain(of_kind(SpannerKind::is_wedge))
3240        .chain(of_kind(|kind| kind == SpannerKind::Line))
3241        .chain(of_kind(|kind| kind == SpannerKind::PedalMark));
3242    for numbered in ordered {
3243        let (spanner, id_local) = (numbered.spanner, numbered.id_local);
3244        if !numbered.holds(position) {
3245            continue;
3246        }
3247        let single = numbered.elements.len() == 1;
3248        let starts = single || numbered.is_first(position);
3249        let stops = single || numbered.is_last(position);
3250        for (here, start) in [(starts, true), (stops, false)] {
3251            if !here {
3252                continue;
3253            }
3254            let mark = match spanner.kind() {
3255                SpannerKind::Ottava => parameterised("octave-shift", spanner, id_local, start),
3256                SpannerKind::Line => {
3257                    let mut bracket = parameterised("bracket", spanner, id_local, start);
3258                    bracket.set("line-type", spanner.line_type().unwrap_or("solid"));
3259                    bracket
3260                }
3261                _ => parameterised(
3262                    if spanner.kind() == SpannerKind::PedalMark {
3263                        "pedal"
3264                    } else {
3265                        "wedge"
3266                    },
3267                    spanner,
3268                    id_local,
3269                    start,
3270                ),
3271            };
3272            let mut direction = Element::new("direction");
3273            if let Some(placement) = spanner.placement() {
3274                direction.set("placement", placement.as_str());
3275            }
3276            direction.sub("direction-type").push(mark);
3277            if start {
3278                before.push(direction);
3279            } else {
3280                after.push(direction);
3281            }
3282            if start
3283                && spanner.kind() == SpannerKind::PedalMark
3284                && spanner.pedal().and_then(|pedal| pedal.form) == Some(PedalForm::SymbolLine)
3285            {
3286                let mut line = Element::new("pedal");
3287                line.set("type", "resume");
3288                line.set("line", "yes");
3289                let mut direction = Element::new("direction");
3290                direction.sub("direction-type").push(line);
3291                if let Some(placement) = spanner.placement() {
3292                    direction.set("placement", placement.as_str());
3293                }
3294                if let Some(offset) = offset_element_from(spanner.offset(), offset_in_measure, true)
3295                {
3296                    direction.push(offset);
3297                }
3298                before.push(direction);
3299            }
3300        }
3301    }
3302    (before, after)
3303}
3304
3305/// music21's `setOffsetOptional`: an `<offset>` for a direction at `offset`
3306/// that does not stand where the writer has got to, `offset_in_measure`.
3307fn offset_element_from(
3308    offset: FloatType,
3309    offset_in_measure: FloatType,
3310    sound: bool,
3311) -> Option<Element> {
3312    // music21 counts its place in the measure as a float, and holds an
3313    // offset no float spells exactly -- a triplet's -- as a `Fraction`,
3314    // which compares unequal to every float.
3315    if offset == offset_in_measure && !is_fraction_offset(offset) {
3316        return None;
3317    }
3318    let difference = ((offset - offset_in_measure) * DIVISIONS_PER_QUARTER) as i64;
3319    let mut element = Element::with_text("offset", difference.to_string());
3320    if sound {
3321        element.set("sound", "yes");
3322    }
3323    Some(element)
3324}
3325
3326/// The element a direction spanner writes where it starts or stops,
3327/// numbered, with the attributes [`spanner_parameters`] gives it.
3328fn parameterised(tag: &'static str, spanner: &Spanner, id_local: u32, start: bool) -> Element {
3329    let mut element = Element::new(tag);
3330    element.set("number", id_local.to_string());
3331    let end = if start {
3332        SpannerEnd::Start
3333    } else {
3334        SpannerEnd::Stop
3335    };
3336    for (name, value) in spanner_parameters(spanner, end) {
3337        element.set(name, value.to_string());
3338    }
3339    element
3340}
3341
3342/// Which end of a spanner is written.
3343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3344pub enum SpannerEnd {
3345    /// Where it starts.
3346    Start,
3347    /// Where it stops.
3348    Stop,
3349}
3350
3351/// A value of [`spanner_parameters`]: text, or a number music21 keeps as
3352/// one.
3353#[derive(Clone, Debug, PartialEq)]
3354pub enum SpannerParameter {
3355    /// Text, as `yes` or `crescendo`.
3356    Text(&'static str),
3357    /// A whole number, as an octave line's size.
3358    Whole(i64),
3359    /// A number with a fraction, as a hairpin's spread may be.
3360    Decimal(FloatType),
3361}
3362
3363impl std::fmt::Display for SpannerParameter {
3364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3365        match self {
3366            Self::Text(text) => f.write_str(text),
3367            Self::Whole(number) => write!(f, "{number}"),
3368            Self::Decimal(number) => f.write_str(&num_to_int_or_float(*number)),
3369        }
3370    }
3371}
3372
3373/// music21's `_spannerStartParameters` and `_spannerEndParameters`: the
3374/// attributes an octave line, a bracket line, a hairpin or a pedal mark
3375/// writes where it starts or stops. Every other spanner has only its
3376/// `type`.
3377///
3378/// An `8va` starts `down`: the notes are engraved below where they sound.
3379/// A crescendo opens from nothing and a diminuendo closes to nothing.
3380/// MusicXML has no start for any pedal but the sustaining and sostenuto
3381/// ones, so music21 writes the soft and silent pedals as a plain start.
3382///
3383/// ```
3384/// use music21::{Spanner, SpannerKind};
3385/// use music21::musicxml::{SpannerEnd, SpannerParameter, spanner_parameters};
3386///
3387/// let crescendo = Spanner::new(SpannerKind::Crescendo, vec![0, 1]);
3388/// let start = spanner_parameters(&crescendo, SpannerEnd::Start);
3389/// assert!(start.contains(&("type", SpannerParameter::Text("crescendo"))));
3390/// assert!(start.contains(&("spread", SpannerParameter::Whole(0))));
3391/// ```
3392pub fn spanner_parameters(
3393    spanner: &Spanner,
3394    end: SpannerEnd,
3395) -> Vec<(&'static str, SpannerParameter)> {
3396    use SpannerParameter::{Decimal, Text, Whole};
3397    let start = end == SpannerEnd::Start;
3398    let mut post = vec![("type", Text(if start { "start" } else { "stop" }))];
3399    let mut set = |name: &'static str, value: SpannerParameter| match post
3400        .iter_mut()
3401        .find(|(known, _)| *known == name)
3402    {
3403        Some(held) => held.1 = value,
3404        None => post.push((name, value)),
3405    };
3406    match spanner.kind() {
3407        SpannerKind::Ottava => {
3408            let octave = spanner.shift();
3409            if let Some(octave) = octave {
3410                set("size", Whole(i64::from(octave.magnitude())));
3411            }
3412            if start {
3413                set(
3414                    "type",
3415                    Text(if octave.is_some_and(|o| o.up()) {
3416                        "down"
3417                    } else {
3418                        "up"
3419                    }),
3420                );
3421            }
3422        }
3423        SpannerKind::Line => {
3424            let ends = spanner.ends();
3425            let (tick, height) = if start {
3426                (ends.start, ends.start_height)
3427            } else {
3428                (ends.end, ends.end_height)
3429            };
3430            set("line-end", Text(tick.as_str()));
3431            if let Some(height) = height {
3432                set("end-length", Decimal(height));
3433            }
3434        }
3435        kind if kind.is_wedge() => {
3436            let crescendo = kind == SpannerKind::Crescendo;
3437            if start {
3438                set(
3439                    "type",
3440                    Text(if crescendo { "crescendo" } else { "diminuendo" }),
3441                );
3442            }
3443            if start == crescendo {
3444                set("spread", Whole(0));
3445            } else if let Some(spread) = spanner.spread() {
3446                set("spread", Decimal(spread));
3447            }
3448        }
3449        SpannerKind::PedalMark => {
3450            let pedal = spanner.pedal().unwrap_or_default();
3451            let lined = match end {
3452                SpannerEnd::Start => pedal.form == Some(PedalForm::Line),
3453                SpannerEnd::Stop => pedal.form.is_some_and(PedalForm::has_line),
3454            };
3455            if start && pedal.pedal_type == Some(PedalType::Sostenuto) {
3456                set("type", Text("sostenuto"));
3457            }
3458            set(if lined { "line" } else { "sign" }, Text("yes"));
3459            if start && pedal.abbreviated {
3460                set("abbreviated", Text("yes"));
3461            }
3462        }
3463        _ => {}
3464    }
3465    post
3466}
3467
3468/// music21's `objectAttachedSpannersToNotations`: a slur's start on its
3469/// first note and its stop on its last, and nothing on the notes between.
3470fn spanner_notations(
3471    position: *const StreamElement,
3472    spanners: &[Numbered<'_>],
3473    marks: &Marks<'_>,
3474) -> Vec<Element> {
3475    let mut notations = Vec::new();
3476    // music21's `appendArpeggioMarkSpannersToNotations`: on every note of
3477    // every chord the arpeggio holds, or a bracket on its lowest and highest
3478    // notes alone; numbered when it holds more than one note.
3479    for numbered in spanners {
3480        let spanner = numbered.spanner;
3481        if spanner.kind() != SpannerKind::ArpeggioMark || !numbered.holds(position) {
3482            continue;
3483        }
3484        let mut element = if spanner.arpeggio() == ArpeggioType::NonArpeggio {
3485            let Some(((low, low_ps), (high, high_ps))) = numbered.note_extremes() else {
3486                continue;
3487            };
3488            let is = |at: *const StreamElement, ps: FloatType| {
3489                std::ptr::eq(at, position) && marks.pitch == Some(ps)
3490            };
3491            let side = if is(low, low_ps) {
3492                "bottom"
3493            } else if is(high, high_ps) {
3494                "top"
3495            } else {
3496                continue;
3497            };
3498            let mut element = Element::new("non-arpeggiate");
3499            element.set("type", side);
3500            element
3501        } else {
3502            let mut element = Element::new("arpeggiate");
3503            if spanner.arpeggio() != ArpeggioType::Normal {
3504                element.set("direction", spanner.arpeggio().as_str());
3505            }
3506            element
3507        };
3508        let notes: usize = numbered
3509            .elements
3510            .iter()
3511            .flatten()
3512            .map(|element| match element {
3513                StreamElement::Chord(chord) => chord.notes().len(),
3514                // music21 counts the notes of any `ChordBase`.
3515                StreamElement::PercussionChord(chord) => chord.len(),
3516                _ => 1,
3517            })
3518            .sum();
3519        if numbered.elements.len() > 1 || notes > 1 {
3520            element.set("number", marks.arpeggios.number(spanner).to_string());
3521        }
3522        notations.push(element);
3523    }
3524    if marks.index != 0 {
3525        return notations;
3526    }
3527    for numbered in spanners {
3528        let (spanner, id_local) = (numbered.spanner, numbered.id_local);
3529        if spanner.kind() != SpannerKind::Slur {
3530            continue;
3531        }
3532        let mut slur = Element::new("slur");
3533        if numbered.is_first(position) {
3534            slur.set("type", "start");
3535            if let Some(line_type) = spanner.line_type() {
3536                slur.set("line-type", line_type);
3537            }
3538            if let Some(placement) = spanner.placement() {
3539                slur.set("placement", placement.as_str());
3540            }
3541        } else if numbered.is_last(position) {
3542            slur.set("type", "stop");
3543        } else {
3544            continue;
3545        }
3546        slur.set("number", id_local.to_string());
3547        notations.push(slur);
3548    }
3549    // A glissando, or a slide where it is played without steps, written as
3550    // a slur is; only its start carries its words.
3551    for numbered in spanners {
3552        let (spanner, id_local) = (numbered.spanner, numbered.id_local);
3553        if spanner.kind() != SpannerKind::Glissando {
3554            continue;
3555        }
3556        let details = spanner.glissando_details().cloned().unwrap_or_default();
3557        let mut glissando = Element::new(if details.slide_type == SlideType::Continuous {
3558            "slide"
3559        } else {
3560            "glissando"
3561        });
3562        glissando.set("number", id_local.to_string());
3563        if let Some(line_type) = spanner.line_type() {
3564            glissando.set("line-type", line_type);
3565        }
3566        if numbered.is_first(position) {
3567            if let Some(label) = details.label {
3568                glissando.set_text(label);
3569            }
3570            glissando.set("type", "start");
3571        } else if numbered.is_last(position) {
3572            glissando.set("type", "stop");
3573        } else {
3574            continue;
3575        }
3576        notations.push(glissando);
3577    }
3578    // A tremolo between notes, then a trill's wavy line: where it starts,
3579    // where it stops, and both on a line over one note. These go in an
3580    // `<ornaments>` of their own.
3581    let mut ornaments = Element::new("ornaments");
3582    for numbered in spanners {
3583        let spanner = numbered.spanner;
3584        if spanner.kind() != SpannerKind::TremoloSpanner || !numbered.holds(position) {
3585            continue;
3586        }
3587        let mut tremolo = Element::with_text(
3588            "tremolo",
3589            spanner.number_of_marks().unwrap_or(3).to_string(),
3590        );
3591        if numbered.is_first(position) {
3592            tremolo.set("type", "start");
3593            if let Some(placement) = spanner.placement() {
3594                tremolo.set("placement", placement.as_str());
3595            }
3596        } else if numbered.is_last(position) {
3597            tremolo.set("type", "stop");
3598        }
3599        ornaments.push(tremolo);
3600    }
3601    for numbered in spanners {
3602        let (spanner, id_local) = (numbered.spanner, numbered.id_local);
3603        if spanner.kind() != SpannerKind::TrillExtension {
3604            continue;
3605        }
3606        let first = numbered.is_first(position);
3607        let last = numbered.is_last(position);
3608        if !first && !last {
3609            continue;
3610        }
3611        let mut line = Element::new("wavy-line");
3612        line.set("number", id_local.to_string());
3613        if first {
3614            line.set("type", "start");
3615            if let Some(placement) = spanner.placement() {
3616                line.set("placement", placement.as_str());
3617            }
3618        } else {
3619            line.set("type", "stop");
3620        }
3621        ornaments.push(line);
3622        if first && last {
3623            let mut stop = Element::new("wavy-line");
3624            stop.set("number", id_local.to_string());
3625            stop.set("type", "stop");
3626            ornaments.push(stop);
3627        }
3628    }
3629    if ornaments.len() > 0 {
3630        notations.push(ornaments);
3631    }
3632    notations
3633}
3634
3635/// music21's `expressionToXml` for an ornament.
3636fn ornament_element(ornament: &Ornament) -> Element {
3637    let tag = if ornament.is_a("Turn") {
3638        match (ornament.is_a("InvertedTurn"), ornament.is_delayed()) {
3639            (true, true) => "delayed-inverted-turn",
3640            (true, false) => "inverted-turn",
3641            (false, true) => "delayed-turn",
3642            (false, false) => "turn",
3643        }
3644    } else {
3645        [
3646            ("Trill", "trill-mark"),
3647            ("InvertedMordent", "inverted-mordent"),
3648            ("Mordent", "mordent"),
3649            ("Shake", "shake"),
3650            ("Schleifer", "schleifer"),
3651            ("Tremolo", "tremolo"),
3652        ]
3653        .into_iter()
3654        .find(|(class, _)| ornament.is_a(class))
3655        .map_or("other-ornament", |(_, tag)| tag)
3656    };
3657    let mut element = Element::new(tag);
3658    if let Some(placement) = ornament.placement() {
3659        element.set("placement", placement);
3660    }
3661    if ornament.is_a("Tremolo") {
3662        element.set("type", "single");
3663        element.set_text(ornament.number_of_marks().to_string());
3664    }
3665    element
3666}
3667
3668/// music21's `ornamentToMxAccidentalMarks`: the accidentals an ornament's
3669/// neighbours are shown with, above or below it.
3670fn ornament_accidental_marks(ornament: &Ornament) -> Result<Vec<Element>> {
3671    let shown = |accidental: Option<&Accidental>| {
3672        accidental
3673            .filter(|accidental| accidental.display_status() == Some(true))
3674            .cloned()
3675    };
3676    let mut marks = Vec::new();
3677    let mut mark = |accidental: Accidental, placement: &str| -> Result<()> {
3678        let mut element = accidental_element(&accidental, "accidental-mark")?;
3679        element.set("placement", placement);
3680        marks.push(element);
3681        Ok(())
3682    };
3683    if ornament.is_a("Turn") {
3684        if let Some(upper) = shown(ornament.upper_accidental()) {
3685            mark(upper, "above")?;
3686        }
3687        if let Some(lower) = shown(ornament.lower_accidental()) {
3688            mark(lower, "below")?;
3689        }
3690    } else if (ornament.is_a("GeneralMordent") || ornament.is_a("Trill"))
3691        && let Some(accidental) = shown(ornament.accidental())
3692    {
3693        let below = ornament.direction() == Some(crate::interval::IntervalDirection::Descending);
3694        mark(accidental, if below { "below" } else { "above" })?;
3695    }
3696    Ok(marks)
3697}
3698
3699/// music21's `setBarline`, with `barlineToXml` and `repeatToXml`: a plain
3700/// barline says how it is drawn, a repeat sign only which way it repeats.
3701fn barline_element(
3702    barline: Option<&Barline>,
3703    location: &str,
3704    ending: Option<(&Ending, &str)>,
3705) -> Element {
3706    let mut element = Element::new("barline");
3707    let repeat = barline.and_then(Barline::repeat_direction);
3708    if let Some(barline) = barline
3709        && repeat.is_none()
3710    {
3711        element.sub_text("bar-style", barline.bar_type().musicxml_bar_style());
3712    }
3713    element.set("location", location);
3714    if let Some((ending, kind)) = ending {
3715        let written = element.sub("ending");
3716        written.set("number", ending.number_text());
3717        written.set("type", kind);
3718    }
3719    if let (Some(barline), Some(direction)) = (barline, repeat) {
3720        let written = element.sub("repeat");
3721        written.set(
3722            "direction",
3723            match direction {
3724                RepeatDirection::Start => "forward",
3725                RepeatDirection::End => "backward",
3726            },
3727        );
3728        if let Some(times) = barline.repeat_times() {
3729            written.set("times", times.to_string());
3730        }
3731    }
3732    element
3733}
3734
3735/// The last thing of one sort a stream holds.
3736fn last_of<T>(stream: &Stream, read: impl Fn(&StreamElement) -> Option<T>) -> Option<T> {
3737    stream
3738        .events()
3739        .iter()
3740        .rev()
3741        .find_map(|event| read(event.element()))
3742}
3743
3744/// Whether an element is one of music21's `GeneralNote`s.
3745fn is_general_note(element: &StreamElement) -> bool {
3746    matches!(
3747        element,
3748        StreamElement::Note(_)
3749            | StreamElement::Chord(_)
3750            | StreamElement::Unpitched(_)
3751            | StreamElement::PercussionChord(_)
3752            | StreamElement::Rest(_)
3753            | StreamElement::ChordSymbol(_)
3754    )
3755}
3756
3757/// Whether an element is written as a `<note>`, which a chord symbol is not
3758/// unless it asks to be.
3759fn is_written_as_note(element: &StreamElement) -> bool {
3760    matches!(
3761        element,
3762        StreamElement::Note(_)
3763            | StreamElement::Chord(_)
3764            | StreamElement::Unpitched(_)
3765            | StreamElement::PercussionChord(_)
3766            | StreamElement::Rest(_)
3767    )
3768}
3769
3770/// An octave as MusicXML can say it: music21's
3771/// `moveOctaveIntoMusicxmlRange`, new in v11, which moves an octave
3772/// outside the format's 0 to 9 to the nearest end of that range rather
3773/// than writing a number no reader will take.
3774///
3775/// music21 warns as it moves one; the crate writes no warning, a library
3776/// having no environment to write to, and what reaches the document is
3777/// the same number. Three things carry an octave into a document -- a
3778/// pitch, a rest's displayed place and an unpitched stroke's -- and each
3779/// goes through this.
3780///
3781/// ```
3782/// use music21::musicxml::musicxml_octave;
3783///
3784/// assert_eq!(musicxml_octave(4), 4);
3785/// assert_eq!(musicxml_octave(12), 9);
3786/// ```
3787pub fn musicxml_octave(octave: i32) -> i32 {
3788    octave.clamp(0, 9)
3789}
3790
3791/// The step and octave of a diatonic note number, as music21's
3792/// `diatonicNoteNum` setter reads one: the octave truncated toward nought.
3793fn step_and_octave(number: i32) -> (char, i32) {
3794    let octave = (number - 1) / 7;
3795    let index = (number - 1 - 7 * octave).rem_euclid(7);
3796    (['C', 'D', 'E', 'F', 'G', 'A', 'B'][index as usize], octave)
3797}
3798
3799/// music21's `xmlObjects.fractionToPercent`: a share as a whole percent,
3800/// truncated.
3801///
3802/// ```
3803/// use music21::musicxml::fraction_to_percent;
3804///
3805/// assert_eq!(fraction_to_percent(0.251), "25");
3806/// ```
3807pub fn fraction_to_percent(share: FloatType) -> String {
3808    ((share * 100.0) as i64).to_string()
3809}
3810
3811/// A length in divisions, rounded as Python's `round` rounds.
3812fn divisions(quarter_length: FloatType) -> i64 {
3813    (quarter_length * DIVISIONS_PER_QUARTER).round_ties_even() as i64
3814}
3815
3816fn format_int(value: FloatType) -> String {
3817    (value as i64).to_string()
3818}
3819
3820/// music21's `common.numToIntOrFloat`, written as Python writes the result.
3821fn num_to_int_or_float(value: FloatType) -> String {
3822    let rounded = value.round_ties_even();
3823    if (rounded - value).abs() < 1e-6 {
3824        format!("{}", rounded as i64)
3825    } else {
3826        format!("{value}")
3827    }
3828}
3829
3830/// The MusicXML `<type>` a duration of one written value is written as.
3831fn musicxml_type(duration_type: DurationType) -> Result<&'static str> {
3832    type_to_musicxml(duration_type.music21_name())
3833}
3834
3835/// music21's `typeToMusicXMLType`: the MusicXML `<type>` for a music21
3836/// duration type, which is the type itself but for `longa`, written
3837/// `long`. The types MusicXML has no value for are refused.
3838///
3839/// ```
3840/// use music21::musicxml::type_to_musicxml;
3841///
3842/// assert_eq!(type_to_musicxml("longa")?, "long");
3843/// assert_eq!(type_to_musicxml("16th")?, "16th");
3844/// assert!(type_to_musicxml("duplex-maxima").is_err());
3845/// # Ok::<(), music21::Error>(())
3846/// ```
3847///
3848/// # Errors
3849///
3850/// `2048th`, `duplex-maxima`, `inexpressible`, `complex` and `zero`, each
3851/// with music21's message.
3852pub fn type_to_musicxml(value: &str) -> Result<&str> {
3853    match value {
3854        "longa" => Ok("long"),
3855        "2048th" => Err(export_error(
3856            "Cannot convert \"2048th\" duration to MusicXML (too short).",
3857        )),
3858        "duplex-maxima" => Err(export_error(
3859            "Cannot convert \"duplex-maxima\" duration to MusicXML (too long).",
3860        )),
3861        "inexpressible" => Err(export_error(
3862            "Cannot convert inexpressible durations to MusicXML.",
3863        )),
3864        "complex" => Err(export_error(
3865            "Cannot convert complex durations to MusicXML. Try exporting with \
3866             makeNotation=True or manually running splitAtDurations()",
3867        )),
3868        "zero" => Err(export_error(
3869            "Cannot convert durations without types to MusicXML.",
3870        )),
3871        other => Ok(other),
3872    }
3873}
3874
3875/// The one written value a duration is, as music21's `type` and `dots`
3876/// read it, and the errors `typeToMusicXMLType` raises for the rest.
3877fn written_type(duration: &Duration) -> Result<(&'static str, u32)> {
3878    let components = duration.components();
3879    match components.as_slice() {
3880        [(duration_type, dots)] => Ok((musicxml_type(*duration_type)?, *dots)),
3881        [] if duration.quarter_length() == 0.0 => musicxml_type(DurationType::Zero).map(|t| (t, 0)),
3882        [] => type_to_musicxml("inexpressible").map(|t| (t, 0)),
3883        _ => type_to_musicxml("complex").map(|t| (t, 0)),
3884    }
3885}
3886
3887/// The `<time-modification>` a duration inside tuplets carries.
3888fn time_modification(duration: &Duration) -> Result<Option<Element>> {
3889    let tuplets = duration.tuplets();
3890    match tuplets.as_slice() {
3891        [] => Ok(None),
3892        [tuplet] => tuplet_to_time_modification(tuplet).map(Some),
3893        _ => {
3894            let multiplier = duration.aggregate_tuplet_multiplier();
3895            let (numerator, denominator) = (
3896                *multiplier.numer().unwrap_or(&1),
3897                *multiplier.denom().unwrap_or(&1),
3898            );
3899            let composite = Tuplet::ratio(
3900                u32::try_from(denominator).unwrap_or(1),
3901                u32::try_from(numerator).unwrap_or(1),
3902            );
3903            tuplet_to_time_modification(&composite).map(Some)
3904        }
3905    }
3906}
3907
3908/// music21's `tupletToTimeModification`.
3909fn tuplet_to_time_modification(tuplet: &Tuplet) -> Result<Element> {
3910    let mut element = Element::new("time-modification");
3911    element.sub_text("actual-notes", tuplet.actual().to_string());
3912    element.sub_text("normal-notes", tuplet.normal().to_string());
3913    if let Some((duration_type, dots)) = tuplet.duration_normal() {
3914        element.sub_text("normal-type", musicxml_type(duration_type)?);
3915        for _ in 0..dots {
3916            element.sub("normal-dot");
3917        }
3918    }
3919    Ok(element)
3920}
3921
3922/// Every tuplet bracket a duration's tuplets open or close, numbered from
3923/// the outermost.
3924fn tuplet_notations(duration: &Duration) -> Result<Vec<Element>> {
3925    let mut out = Vec::new();
3926    for (index, tuplet) in duration.tuplets().iter().enumerate() {
3927        out.extend(tuplet_elements(tuplet, index + 1)?);
3928    }
3929    Ok(out)
3930}
3931
3932/// music21's `tupletToXmlTuplet`: a bracket's start, with how it is drawn
3933/// and what it shows, or its stop, or both for a tuplet of one note.
3934fn tuplet_elements(tuplet: &Tuplet, number: usize) -> Result<Vec<Element>> {
3935    use crate::duration::{TupletBracket, TupletShow, TupletType};
3936    let types: &[&str] = match tuplet.tuplet_type() {
3937        None => return Ok(Vec::new()),
3938        Some(TupletType::Start) => &["start"],
3939        Some(TupletType::Stop) => &["stop"],
3940        Some(TupletType::StartStop) => &["start", "stop"],
3941    };
3942    let mut out = Vec::new();
3943    for kind in types {
3944        let mut element = Element::new("tuplet");
3945        element.set("type", *kind);
3946        element.set("number", number.to_string());
3947        if *kind == "start" {
3948            element.set("bracket", yes_no(tuplet.bracket() != TupletBracket::None));
3949            if let Some(placement) = tuplet.placement() {
3950                element.set("placement", placement.as_str());
3951            }
3952            let actual = tuplet.actual_show();
3953            let normal = tuplet.normal_show();
3954            let shows_number = |show: Option<TupletShow>| {
3955                matches!(show, Some(TupletShow::Both | TupletShow::Number))
3956            };
3957            let shows_type = |show: Option<TupletShow>| {
3958                matches!(show, Some(TupletShow::Both | TupletShow::Type))
3959            };
3960            if actual.is_none() {
3961                element.set("show-number", "none");
3962            } else if shows_number(actual) && shows_number(normal) {
3963                element.set("show-number", "both");
3964            } else if actual == Some(TupletShow::Both) {
3965                // music21 asks whether the actual count is shown as `both` or
3966                // as `actual`, which it never is.
3967                element.set("show-number", "actual");
3968            }
3969            if shows_type(actual) && shows_type(normal) {
3970                element.set("show-type", "both");
3971            } else if shows_type(actual) {
3972                element.set("show-type", "actual");
3973            }
3974            if tuplet.bracket() == TupletBracket::Slur {
3975                element.set("line-shape", "curved");
3976            }
3977            for (tag, count, value) in [
3978                ("tuplet-actual", tuplet.actual(), tuplet.duration_actual()),
3979                ("tuplet-normal", tuplet.normal(), tuplet.duration_normal()),
3980            ] {
3981                let side = element.sub(tag);
3982                side.sub_text("tuplet-number", count.to_string());
3983                if let Some((duration_type, dots)) = value {
3984                    side.sub_text("tuplet-type", musicxml_type(duration_type)?);
3985                    for _ in 0..dots {
3986                        side.sub("tuplet-dot");
3987                    }
3988                }
3989            }
3990        }
3991        out.push(element);
3992    }
3993    Ok(out)
3994}
3995
3996/// music21's `pitchToXml`.
3997fn pitch_element(pitch: &Pitch) -> Element {
3998    let mut element = Element::new("pitch");
3999    element.sub_text("step", pitch.step().as_char().to_string());
4000    if let Some(accidental) = pitch.written_accidental() {
4001        element.sub_text("alter", num_to_int_or_float(accidental.alter()));
4002    }
4003    element.sub_text(
4004        "octave",
4005        musicxml_octave(pitch.implicit_octave()).to_string(),
4006    );
4007    element
4008}
4009
4010/// The accidental names music21 writes as they stand: its own names, and the
4011/// MusicXML ones it has no name for.
4012const KNOWN_ACCIDENTALS: [&str; 40] = [
4013    "natural",
4014    "sharp",
4015    "double-sharp",
4016    "triple-sharp",
4017    "quadruple-sharp",
4018    "flat",
4019    "double-flat",
4020    "triple-flat",
4021    "quadruple-flat",
4022    "half-sharp",
4023    "one-and-a-half-sharp",
4024    "half-flat",
4025    "one-and-a-half-flat",
4026    "double-sharp-down",
4027    "double-sharp-up",
4028    "flat-flat-down",
4029    "flat-flat-up",
4030    "arrow-down",
4031    "arrow-up",
4032    "other",
4033    "sharp-down",
4034    "sharp-up",
4035    "natural-down",
4036    "natural-up",
4037    "flat-down",
4038    "flat-up",
4039    "slash-quarter-sharp",
4040    "slash-sharp",
4041    "slash-flat",
4042    "double-slash-flat",
4043    "sharp-1",
4044    "sharp-2",
4045    "sharp-3",
4046    "sharp-5",
4047    "flat-1",
4048    "flat-2",
4049    "flat-3",
4050    "flat-4",
4051    "sori",
4052    "koron",
4053];
4054
4055/// music21's `accidentalToMx`.
4056fn accidental_element(accidental: &Accidental, tag: &'static str) -> Result<Element> {
4057    let name = match accidental.name() {
4058        "half-sharp" => "quarter-sharp",
4059        "one-and-a-half-sharp" => "three-quarters-sharp",
4060        "half-flat" => "quarter-flat",
4061        "one-and-a-half-flat" => "three-quarters-flat",
4062        "double-flat" => "flat-flat",
4063        other if KNOWN_ACCIDENTALS.contains(&other) => other,
4064        _ => "other",
4065    };
4066    let mut element = Element::with_text(tag, name);
4067    let style = accidental.display_style();
4068    if matches!(style, "parentheses" | "both") {
4069        element.set("parentheses", "yes");
4070    }
4071    if matches!(style, "bracket" | "both") {
4072        element.set("bracket", "yes");
4073    }
4074    if let Some(color) = accidental.color() {
4075        element.set("color", normalize_color(color)?);
4076    }
4077    Ok(element)
4078}
4079
4080/// music21's `tieToXmlTie`.
4081fn tie_elements(tie: &Tie) -> Vec<Element> {
4082    tie_like("tie", tie)
4083}
4084
4085fn tie_like(tag: &'static str, tie: &Tie) -> Vec<Element> {
4086    let continues = tie.tie_type() == crate::notation::TieType::Continue;
4087    let mut first = Element::new(tag);
4088    first.set(
4089        "type",
4090        if continues {
4091            "stop"
4092        } else {
4093            tie.tie_type().as_str()
4094        },
4095    );
4096    let mut out = vec![first];
4097    if continues {
4098        let mut second = Element::new(tag);
4099        second.set("type", "start");
4100        out.push(second);
4101    }
4102    out
4103}
4104
4105/// music21's `tieToXmlTied`.
4106fn tied_elements(tie: &Tie) -> Vec<Element> {
4107    use crate::notation::{TieStyle, TieType};
4108    if tie.style() == TieStyle::Hidden {
4109        return Vec::new();
4110    }
4111    let mut out = tie_like("tied", tie);
4112    let last = out.last_mut().expect("a tie writes at least one element");
4113    if tie.style() != TieStyle::Normal && tie.tie_type() != TieType::Stop {
4114        last.set("line-type", tie.style().as_str());
4115    }
4116    if let Some(placement) = tie.placement() {
4117        last.set("placement", placement.as_str());
4118        last.set(
4119            "orientation",
4120            match placement {
4121                Placement::Above => "over",
4122                Placement::Below => "under",
4123            },
4124        );
4125    }
4126    out
4127}
4128
4129/// music21's `dealWithNotehead` and `noteheadToXml`.
4130fn notehead_for(note: &Note, chord: Option<&Chord>) -> Result<Option<Element>> {
4131    let marked =
4132        |notehead: Notehead, parenthesis: bool, fill: Option<bool>, color: Option<&str>| {
4133            notehead != Notehead::Normal || parenthesis || fill.is_some() || color.is_some()
4134        };
4135    let (notehead, parenthesis, fill, color) = if marked(
4136        note.notehead(),
4137        note.notehead_parenthesis(),
4138        note.notehead_fill(),
4139        note.color(),
4140    ) {
4141        (
4142            note.notehead(),
4143            note.notehead_parenthesis(),
4144            note.notehead_fill(),
4145            note.color(),
4146        )
4147    } else if let Some(chord) = chord
4148        && marked(
4149            chord.notehead(),
4150            chord.notehead_parenthesis(),
4151            chord.notehead_fill(),
4152            chord.color(),
4153        )
4154    {
4155        (
4156            chord.notehead(),
4157            chord.notehead_parenthesis(),
4158            chord.notehead_fill(),
4159            chord.color(),
4160        )
4161    } else {
4162        return Ok(None);
4163    };
4164    let mut element = Element::with_text("notehead", notehead.as_str());
4165    if let Some(fill) = fill {
4166        element.set("filled", yes_no(fill));
4167    }
4168    element.set("parentheses", yes_no(parenthesis));
4169    if let Some(color) = color {
4170        element.set("color", normalize_color(color)?);
4171    }
4172    Ok(Some(element))
4173}
4174
4175fn yes_no(value: bool) -> &'static str {
4176    if value { "yes" } else { "no" }
4177}
4178
4179/// music21's `beamsToXml`.
4180fn beam_elements(beams: &Beams) -> Result<Vec<Element>> {
4181    beams.beams().iter().map(beam_element).collect()
4182}
4183
4184/// music21's `beamToXml`.
4185fn beam_element(beam: &Beam) -> Result<Element> {
4186    let text = match beam.beam_type() {
4187        Some(BeamType::Start) => "begin",
4188        Some(BeamType::Continue) => "continue",
4189        Some(BeamType::Stop) => "end",
4190        Some(BeamType::PartialBeam) => match beam.direction() {
4191            Some(BeamDirection::Left) => "backward hook",
4192            Some(BeamDirection::Right) => "forward hook",
4193            None => {
4194                return Err(export_error(
4195                    "partial beam defined without a proper direction set (set to None)",
4196                ));
4197            }
4198        },
4199        None => {
4200            return Err(export_error("unexpected beam type encountered (None)"));
4201        }
4202    };
4203    let mut element = Element::with_text("beam", text);
4204    element.set(
4205        "number",
4206        beam.number()
4207            .map_or_else(|| "None".to_string(), |number| number.to_string()),
4208    );
4209    Ok(element)
4210}
4211
4212/// music21's `lyricToXml`.
4213fn lyric_element(lyric: &Lyric) -> Result<Element> {
4214    let mut element = Element::new("lyric");
4215    let write_syllable = |element: &mut Element, lyric: &Lyric| {
4216        if let Some(syllabic) = lyric.explicit_syllabic() {
4217            element.sub_text("syllabic", syllabic.as_str());
4218        }
4219        element.sub_text("text", lyric.explicit_text().unwrap_or_default());
4220    };
4221    if lyric.is_composite() {
4222        for (index, component) in lyric.components().iter().enumerate() {
4223            if component.is_composite() {
4224                continue;
4225            }
4226            if index >= 1 {
4227                let elision = element.sub("elision");
4228                if !component.elision_before().is_empty() {
4229                    elision.set_text(component.elision_before());
4230                }
4231            }
4232            write_syllable(&mut element, component);
4233        }
4234    } else {
4235        write_syllable(&mut element, lyric);
4236    }
4237    element.set("name", lyric.identifier());
4238    element.set("number", lyric.number().to_string());
4239    if let Some(justify) = lyric.justify() {
4240        element.set("justify", justify.as_str());
4241    }
4242    if let Some(placement) = lyric.placement() {
4243        element.set("placement", placement.as_str());
4244    }
4245    if lyric.is_hidden() {
4246        element.set("print-object", "no");
4247    }
4248    if let Some(color) = lyric.color() {
4249        element.set("color", normalize_color(color)?);
4250    }
4251    Ok(element)
4252}
4253
4254/// The `<key>` for a key or a key signature, and nothing for anything else.
4255fn key_element(element: &StreamElement) -> Option<Result<Element>> {
4256    match element {
4257        StreamElement::KeySignature(signature) => {
4258            Some(key_signature_element(signature, signature.mode()))
4259        }
4260        StreamElement::Key(key) => {
4261            let mut signature = key.key_signature();
4262            signature.set_color(key.color().map(str::to_string));
4263            Some(key_signature_element(&signature, Some(key.mode())))
4264        }
4265        _ => None,
4266    }
4267}
4268
4269/// music21's `keySignatureToXml`, with the mode a `Key` carries.
4270fn key_signature_element(key: &KeySignature, mode: Option<&str>) -> Result<Element> {
4271    let mut element = Element::new("key");
4272    if let Some(color) = key.color() {
4273        element.set("color", normalize_color(color)?);
4274    }
4275    let altered = key.altered_pitches()?;
4276    match (!key.is_non_traditional()).then_some(key.sharps()) {
4277        Some(sharps) => {
4278            element.sub_text("fifths", sharps.to_string());
4279            if let Some(mode) = mode {
4280                element.sub_text("mode", mode);
4281            }
4282        }
4283        None => {
4284            for pitch in &altered {
4285                element.sub_text("key-step", pitch.step().as_char().to_string());
4286                let alter = pitch.written_accidental().map_or(0.0, Accidental::alter);
4287                element.sub_text("key-alter", num_to_int_or_float(alter));
4288            }
4289        }
4290    }
4291    for (index, pitch) in altered.iter().enumerate() {
4292        if let Some(octave) = pitch.octave() {
4293            let mut octave_element = Element::with_text("key-octave", octave.to_string());
4294            octave_element.set("number", (index + 1).to_string());
4295            element.push(octave_element);
4296        }
4297    }
4298    Ok(element)
4299}
4300
4301/// music21's `timeSignatureToXml`.
4302fn time_signature_element(meter: &TimeSignature) -> Result<Element> {
4303    let mut element = Element::new("time");
4304    if let Some(color) = meter.color() {
4305        element.set("color", normalize_color(color)?);
4306    }
4307    let parts: Vec<(String, String)> = meter
4308        .display_sequence()
4309        .flattened()
4310        .iter()
4311        .map(|part| (part.numerator().to_string(), part.denominator().to_string()))
4312        .collect();
4313    let parts = if meter.summed_numerator() {
4314        fraction_to_slash_mixed(parts)
4315    } else {
4316        parts
4317    };
4318    for (beats, beat_type) in parts {
4319        element.sub_text("beats", beats);
4320        element.sub_text("beat-type", beat_type);
4321    }
4322    if meter.symbolize_denominator() {
4323        element.set("symbol", "note");
4324    } else if let Some(symbol) = meter.symbol() {
4325        element.set("symbol", symbol);
4326    }
4327    if meter.is_hidden() {
4328        element.set("print-object", "no");
4329    }
4330    Ok(element)
4331}
4332
4333/// music21's `meter.tools.fractionToSlashMixed`: neighbouring parts over one
4334/// denominator written as one, their numerators summed with `+`.
4335fn fraction_to_slash_mixed(parts: Vec<(String, String)>) -> Vec<(String, String)> {
4336    let mut out: Vec<(String, String)> = Vec::new();
4337    for (numerator, denominator) in parts {
4338        match out.last_mut() {
4339            Some((numerators, last)) if *last == denominator => {
4340                numerators.push('+');
4341                numerators.push_str(&numerator);
4342            }
4343            _ => out.push((numerator, denominator)),
4344        }
4345    }
4346    out
4347}
4348
4349/// music21's `clefToXml`.
4350fn clef_element(clef: &Clef) -> Result<Element> {
4351    let mut element = Element::new("clef");
4352    if let Some(color) = clef.color() {
4353        element.set("color", normalize_color(color)?);
4354    }
4355    element.sub_text("sign", clef.sign().unwrap_or("G"));
4356    if let Some(line) = clef.line() {
4357        element.sub_text("line", line.to_string());
4358    }
4359    if clef.octave_change() != 0 {
4360        element.sub_text("clef-octave-change", clef.octave_change().to_string());
4361    }
4362    Ok(element)
4363}
4364
4365/// music21's `intervalToXmlTranspose`.
4366fn transpose_element(interval: &Interval) -> Element {
4367    let generic = interval.generic().directed();
4368    let steps = generic.abs() - 1;
4369    let (mut octave_shift, mut diatonic) = (steps / 7, steps % 7);
4370    let mut chromatic = (interval.semitones().abs() as i64) % 12;
4371    if generic < 0 {
4372        diatonic = -diatonic;
4373        octave_shift = -octave_shift;
4374        chromatic = -chromatic;
4375    }
4376    let mut element = Element::new("transpose");
4377    element.sub_text("diatonic", diatonic.to_string());
4378    element.sub_text("chromatic", chromatic.to_string());
4379    if octave_shift != 0 {
4380        element.sub_text("octave-change", octave_shift.to_string());
4381    }
4382    element
4383}
4384
4385/// music21's `xmlObjects.DYNAMIC_MARKS`: the marks MusicXML writes as a
4386/// `<dynamics>` element of their own name.
4387pub const DYNAMIC_MARKS: [&str; 27] = [
4388    "p",
4389    "pp",
4390    "ppp",
4391    "pppp",
4392    "ppppp",
4393    "pppppp",
4394    "f",
4395    "ff",
4396    "fff",
4397    "ffff",
4398    "fffff",
4399    "ffffff",
4400    "mp",
4401    "mf",
4402    "sf",
4403    "sfp",
4404    "sfpp",
4405    "fp",
4406    "rf",
4407    "rfz",
4408    "sfz",
4409    "sffz",
4410    "fz",
4411    "n",
4412    "pf",
4413    "sfzp",
4414    "other-dynamics",
4415];
4416
4417/// The tag a dynamic mark is written as, which is the mark itself.
4418fn dynamic_tag(mark: &str) -> &'static str {
4419    DYNAMIC_MARKS
4420        .iter()
4421        .find(|known| **known == mark)
4422        .copied()
4423        .unwrap_or("other-dynamics")
4424}
4425
4426/// Whether music21 holds this offset as a `Fraction` rather than a float:
4427/// `opFrac` keeps a float only where its denominator is a power of two
4428/// below 65535.
4429fn is_fraction_offset(offset: FloatType) -> bool {
4430    let scaled = offset * 32768.0;
4431    scaled.fract() != 0.0
4432}
4433
4434/// music21's `normalizeColor`: a hex colour upper-cased, and a CSS colour
4435/// name written as its hex value.
4436///
4437/// ```
4438/// use music21::musicxml::normalize_color;
4439///
4440/// assert_eq!(normalize_color("red")?, "#FF0000");
4441/// assert_eq!(normalize_color("#00ff00")?, "#00FF00");
4442/// # Ok::<(), music21::Error>(())
4443/// ```
4444///
4445/// # Errors
4446///
4447/// A name that is not a CSS colour's.
4448pub fn normalize_color(color: &str) -> Result<String> {
4449    if color.is_empty() {
4450        return Ok(String::new());
4451    }
4452    if color.contains('#') {
4453        return Ok(color.to_uppercase());
4454    }
4455    crate::style::css_color_hex(color)
4456        .map(str::to_string)
4457        .ok_or_else(|| export_error(format!("{color:?} is not a CSS colour name")))
4458}
4459
4460/// The hex value of a CSS3 colour name: moved to the style module.
4461#[deprecated(since = "0.21.0", note = "use music21::style::css_color_hex")]
4462pub fn css_color_hex(name: &str) -> Option<&'static str> {
4463    crate::style::css_color_hex(name)
4464}
4465
4466/// The CSS3 colour names: moved to the style module.
4467#[deprecated(since = "0.21.0", note = "use music21::style::CSS_COLORS")]
4468pub const CSS_COLORS: [(&str, &str); 147] = crate::style::CSS_COLORS;
4469
4470#[cfg(test)]
4471mod tests {
4472    //! Each expectation is the one music21's own docstring for the method
4473    //! prints, read off `m21ToXml.py`.
4474
4475    use super::*;
4476    use crate::notation::{BeamType, Syllabic, TieStyle, TieType};
4477    use crate::volume::Volume;
4478
4479    static NO_BASES: std::sync::LazyLock<std::collections::HashMap<usize, u32>> =
4480        std::sync::LazyLock::new(std::collections::HashMap::new);
4481
4482    fn with_measure<T>(run: impl FnOnce(&mut MeasureExporter<'_, '_>) -> T) -> T {
4483        let stream = Stream::with_kind(StreamKind::Measure);
4484        let mut context = PartContext {
4485            instruments: &[],
4486            own_instruments: Vec::new(),
4487            own_clefs: Vec::new(),
4488            meter: None,
4489            last_divisions: None,
4490            spanners: Vec::new(),
4491            clef: None,
4492            previous: None,
4493            voice_bases: &NO_BASES,
4494            modulations: Vec::new(),
4495        };
4496        let mut exporter = MeasureExporter::new(&stream, 0.0, &mut context);
4497        run(&mut exporter)
4498    }
4499
4500    #[test]
4501    fn a_segno_and_a_coda_are_signs_and_the_rest_are_words() {
4502        // music21's `segnoToXml` and `codaToXml` docstrings.
4503        let sign = |kind| {
4504            with_measure(|exporter| {
4505                exporter
4506                    .repeat_expression_element(&RepeatExpression::new(kind), 0.0)
4507                    .dump()
4508            })
4509        };
4510        assert_eq!(
4511            sign(RepeatExpressionKind::Segno),
4512            "<direction>
4513  <direction-type>
4514    <segno default-y=\"20\" />
4515  </direction-type>
4516</direction>"
4517        );
4518        assert_eq!(
4519            sign(RepeatExpressionKind::Coda),
4520            "<direction>
4521  <direction-type>
4522    <coda default-y=\"20\" />
4523  </direction-type>
4524</direction>"
4525        );
4526        assert_eq!(
4527            sign(RepeatExpressionKind::Fine),
4528            "<direction>
4529  <direction-type>
4530    <words justify=\"right\">fine</words>
4531  </direction-type>
4532</direction>"
4533        );
4534    }
4535
4536    #[test]
4537    fn a_pedal_goes_down_and_comes_up() {
4538        use crate::spanner::Pedal;
4539        // music21's `_spannerStartParameters` and `_spannerEndParameters`.
4540        let pedal = |pedal_type, form| {
4541            Spanner::pedal_mark(
4542                Pedal {
4543                    pedal_type,
4544                    form,
4545                    abbreviated: false,
4546                },
4547                vec![0, 1],
4548            )
4549        };
4550        let symbol = pedal(Some(PedalType::Sustain), Some(PedalForm::Symbol));
4551        assert_eq!(
4552            parameterised("pedal", &symbol, 1, true).dump(),
4553            "<pedal number=\"1\" sign=\"yes\" type=\"start\" />"
4554        );
4555        assert_eq!(
4556            parameterised("pedal", &symbol, 1, false).dump(),
4557            "<pedal number=\"1\" sign=\"yes\" type=\"stop\" />"
4558        );
4559        let line = pedal(Some(PedalType::Sostenuto), Some(PedalForm::Line));
4560        assert_eq!(
4561            parameterised("pedal", &line, 2, true).dump(),
4562            "<pedal line=\"yes\" number=\"2\" type=\"sostenuto\" />"
4563        );
4564        assert_eq!(
4565            parameterised("pedal", &line, 2, false).dump(),
4566            "<pedal line=\"yes\" number=\"2\" type=\"stop\" />"
4567        );
4568    }
4569
4570    #[test]
4571    fn glissandi_a_tremolo_and_a_pedal_with_a_bounce_are_written_as_music21_writes_them() {
4572        use crate::spanner::{Glissando, Pedal};
4573        // Read off music21's own export of the same two bars.
4574        let bar = |number, names: [&str; 4]| {
4575            let mut measure = Stream::with_kind(StreamKind::Measure);
4576            measure.set_number(number);
4577            for name in names {
4578                measure.push(Note::from_name(name).unwrap());
4579            }
4580            measure
4581        };
4582        let mut first = bar(1, ["C4", "D4", "E4", "F4"]);
4583        first.insert(3.0, PedalObject::new(PedalObjectKind::Bounce));
4584        let mut part = Stream::with_kind(StreamKind::Part);
4585        part.push(first);
4586        part.push(bar(2, ["G4", "A4", "B4", "C5"]));
4587        let mut score = Stream::with_kind(StreamKind::Score);
4588        score.push(part);
4589        // The notes of the first bar stand at 0 to 3, the bounce at 4, and
4590        // the notes of the second at 5 to 8.
4591        let kinds: Vec<bool> = score
4592            .leaves()
4593            .iter()
4594            .map(|(_, element)| matches!(element, StreamElement::PedalObject(_)))
4595            .collect();
4596        assert_eq!(kinds.iter().position(|bounce| *bounce), Some(4));
4597
4598        // A pedal from the second note to the seventh, its bounce joined
4599        // last, so that is where it comes up.
4600        let pedal = Spanner::pedal_mark(
4601            Pedal {
4602                pedal_type: Some(PedalType::Sustain),
4603                form: Some(PedalForm::SymbolLine),
4604                abbreviated: false,
4605            },
4606            vec![1, 7, 4],
4607        );
4608        score.add_spanner(pedal);
4609        score.add_spanner(Spanner::glissando(vec![2, 3]));
4610        let mut slide = Spanner::glissando(vec![5, 6]);
4611        slide.set_glissando_details(Some(Glissando {
4612            slide_type: SlideType::Continuous,
4613            label: Some("gl.".to_string()),
4614        }));
4615        score.add_spanner(slide);
4616        let mut tremolo = Spanner::tremolo(3, vec![7, 8]).unwrap();
4617        tremolo.set_placement(Some(Placement::Above));
4618        score.add_spanner(tremolo);
4619
4620        let written = to_musicxml(&score, &ExportOptions::default()).unwrap();
4621        let direction = |pedal: &str, offset: &str| {
4622            format!(
4623                "      <direction>\n        <direction-type>\n          {pedal}\n        \
4624                 </direction-type>\n{offset}      </direction>\n"
4625            )
4626        };
4627        // The sign, and the line resumed where the pedal mark stands: the
4628        // start of the part, a quarter before the note it goes down on.
4629        assert!(written.contains(&format!(
4630            "{}{}",
4631            direction("<pedal number=\"1\" sign=\"yes\" type=\"start\" />", ""),
4632            direction(
4633                "<pedal line=\"yes\" type=\"resume\" />",
4634                "        <offset sound=\"yes\">-10080</offset>\n"
4635            )
4636        )));
4637        // The bounce, and after it the pedal coming up.
4638        assert!(written.contains(&format!(
4639            "{}{}",
4640            direction("<pedal line=\"yes\" type=\"change\" />", ""),
4641            direction("<pedal line=\"yes\" number=\"1\" type=\"stop\" />", "")
4642        )));
4643        for notation in [
4644            "<glissando line-type=\"wavy\" number=\"1\" type=\"start\" />",
4645            "<glissando line-type=\"wavy\" number=\"1\" type=\"stop\" />",
4646            "<slide line-type=\"wavy\" number=\"2\" type=\"start\">gl.</slide>",
4647            "<slide line-type=\"wavy\" number=\"2\" type=\"stop\" />",
4648            "<tremolo placement=\"above\" type=\"start\">3</tremolo>",
4649            "<tremolo type=\"stop\">3</tremolo>",
4650        ] {
4651            assert!(written.contains(notation), "{notation} in\n{written}");
4652        }
4653    }
4654
4655    #[test]
4656    fn a_bounce_is_written_as_its_pedal_is_drawn() {
4657        use crate::spanner::Pedal;
4658        // music21's `pedalObjectToXml`.
4659        let written = |form, pedal_type, kind| {
4660            let mut measure = Stream::with_kind(StreamKind::Measure);
4661            measure.set_number(1);
4662            measure.push(Note::from_name("C4").unwrap());
4663            measure.insert(1.0, PedalObject::new(kind));
4664            measure.push(Note::from_name("D4").unwrap());
4665            let mut part = Stream::with_kind(StreamKind::Part);
4666            part.push(measure);
4667            part.add_spanner(Spanner::pedal_mark(
4668                Pedal {
4669                    pedal_type,
4670                    form: Some(form),
4671                    abbreviated: false,
4672                },
4673                vec![0, 1, 2],
4674            ));
4675            let mut score = Stream::with_kind(StreamKind::Score);
4676            score.push(part);
4677            let document = to_musicxml(&score, &ExportOptions::default()).unwrap();
4678            document
4679                .lines()
4680                .map(str::trim)
4681                .filter(|line| line.starts_with("<pedal") && !line.contains("number"))
4682                .collect::<Vec<_>>()
4683                .join("")
4684        };
4685        let sustain = Some(PedalType::Sustain);
4686        assert_eq!(
4687            written(PedalForm::Line, sustain, PedalObjectKind::Bounce),
4688            "<pedal line=\"yes\" type=\"change\" />"
4689        );
4690        assert_eq!(
4691            written(PedalForm::Symbol, sustain, PedalObjectKind::Bounce),
4692            "<pedal sign=\"yes\" type=\"stop\" /><pedal sign=\"yes\" type=\"start\" />"
4693        );
4694        assert_eq!(
4695            written(
4696                PedalForm::SymbolAlt,
4697                Some(PedalType::Sostenuto),
4698                PedalObjectKind::Bounce
4699            ),
4700            "<pedal sign=\"yes\" type=\"sostenuto\" />"
4701        );
4702        assert_eq!(
4703            written(
4704                PedalForm::Symbol,
4705                Some(PedalType::Soft),
4706                PedalObjectKind::Bounce
4707            ),
4708            "<pedal sign=\"yes\" type=\"stop\" /><pedal sign=\"yes\" type=\"sustain\" />"
4709        );
4710        assert_eq!(
4711            written(PedalForm::Line, sustain, PedalObjectKind::GapStart),
4712            "<pedal line=\"yes\" type=\"discontinue\" />"
4713        );
4714        assert_eq!(
4715            written(PedalForm::Symbol, sustain, PedalObjectKind::GapEnd),
4716            "<pedal sign=\"yes\" type=\"resume\" />"
4717        );
4718    }
4719
4720    #[test]
4721    fn a_mark_at_a_triplet_offset_always_says_its_offset() {
4722        // music21 holds 8/3 as a Fraction, which equals no float, so the
4723        // offset is written even where it comes to nothing.
4724        with_measure(|exporter| {
4725            exporter.offset_in_measure = 8.0 / 3.0;
4726            let written = exporter.offset_element(8.0 / 3.0, true).unwrap();
4727            assert_eq!(written.dump(), "<offset sound=\"yes\">0</offset>");
4728            exporter.offset_in_measure = 2.5;
4729            assert!(exporter.offset_element(2.5, true).is_none());
4730        });
4731    }
4732
4733    #[test]
4734    fn a_stroke_is_written_where_it_is_displayed() {
4735        // music21's `unpitchedToXml` docstring.
4736        let stroke = crate::percussion::Unpitched::from_display_name("D5")
4737            .unwrap()
4738            .with_duration(Duration::quarter());
4739        let written = with_measure(|exporter| {
4740            exporter
4741                .written_note_element(stroke.written(), 0, None, None, true)
4742                .unwrap()
4743        });
4744        assert_eq!(
4745            written.dump(),
4746            [
4747                "<note>",
4748                "  <unpitched>",
4749                "    <display-step>D</display-step>",
4750                "    <display-octave>5</display-octave>",
4751                "  </unpitched>",
4752                "  <duration>10080</duration>",
4753                "  <type>quarter</type>",
4754                "</note>",
4755            ]
4756            .join(
4757                "
4758"
4759            )
4760        );
4761    }
4762
4763    #[test]
4764    fn a_colour_is_written_in_hex() {
4765        assert_eq!(normalize_color("").unwrap(), "");
4766        assert_eq!(normalize_color("red").unwrap(), "#FF0000");
4767        assert_eq!(normalize_color("#00ff00").unwrap(), "#00FF00");
4768        assert!(normalize_color("reddish").is_err());
4769    }
4770
4771    #[test]
4772    fn a_note_writes_as_music21_writes_it() {
4773        let mut note = Note::from_name("D#5")
4774            .unwrap()
4775            .with_duration(Duration::new(3.0).unwrap());
4776        note.set_volume(Some(Volume::from_velocity_scalar(0.5).unwrap()));
4777        note.set_color(Some("#C0C0C0".to_string()));
4778        let xml =
4779            with_measure(|exporter| exporter.note_element(&note, 0, None, None).unwrap()).dump();
4780        assert_eq!(
4781            xml,
4782            "<note color=\"#C0C0C0\" dynamics=\"70.56\">
4783  <pitch>
4784    <step>D</step>
4785    <alter>1</alter>
4786    <octave>5</octave>
4787  </pitch>
4788  <duration>30240</duration>
4789  <type>half</type>
4790  <dot />
4791  <accidental>sharp</accidental>
4792  <notehead color=\"#C0C0C0\" parentheses=\"no\">normal</notehead>
4793</note>"
4794        );
4795    }
4796
4797    #[test]
4798    fn a_chord_writes_a_note_for_each_of_its_notes() {
4799        let chord = Chord::new("A-2 D3 E4")
4800            .unwrap()
4801            .with_duration(Duration::half());
4802        let root = with_measure(|exporter| {
4803            exporter.chord_elements(&chord, None).unwrap();
4804            exporter.root.clone()
4805        });
4806        assert_eq!(
4807            root.dump(),
4808            "<measure>
4809  <note>
4810    <pitch>
4811      <step>A</step>
4812      <alter>-1</alter>
4813      <octave>2</octave>
4814    </pitch>
4815    <duration>20160</duration>
4816    <type>half</type>
4817    <accidental>flat</accidental>
4818  </note>
4819  <note>
4820    <chord />
4821    <pitch>
4822      <step>D</step>
4823      <octave>3</octave>
4824    </pitch>
4825    <duration>20160</duration>
4826    <type>half</type>
4827  </note>
4828  <note>
4829    <chord />
4830    <pitch>
4831      <step>E</step>
4832      <octave>4</octave>
4833    </pitch>
4834    <duration>20160</duration>
4835    <type>half</type>
4836  </note>
4837</measure>"
4838        );
4839    }
4840
4841    /// music21's `fullMeasure` decides before the bar does: `False` is no
4842    /// measure rest though it fills the bar, `'always'` is one though it
4843    /// does not, and `'auto'` asks the bar.
4844    #[test]
4845    fn a_rest_says_whether_it_is_a_measure_rest() {
4846        let mut measure = Stream::with_kind(StreamKind::Measure);
4847        measure.insert(0.0, TimeSignature::new(4, 4).unwrap());
4848        let mut context = PartContext {
4849            instruments: &[],
4850            own_instruments: Vec::new(),
4851            own_clefs: Vec::new(),
4852            meter: None,
4853            last_divisions: None,
4854            spanners: Vec::new(),
4855            clef: None,
4856            previous: None,
4857            voice_bases: &NO_BASES,
4858            modulations: Vec::new(),
4859        };
4860        let exporter = MeasureExporter::new(&measure, 0.0, &mut context);
4861        let written = |length: Duration, said: FullMeasure| {
4862            let mut rest = Rest::new(length);
4863            rest.set_full_measure(said);
4864            exporter.rest_element(&rest, 0.0, None).unwrap().dump()
4865        };
4866        let whole = || Duration::new(4.0).unwrap();
4867        assert!(!written(whole(), FullMeasure::No).contains("measure=\"yes\""));
4868        assert!(written(whole(), FullMeasure::Auto).contains("measure=\"yes\""));
4869        assert!(written(Duration::half(), FullMeasure::Always).contains("measure=\"yes\""));
4870        assert!(written(Duration::half(), FullMeasure::Yes).contains("measure=\"yes\""));
4871    }
4872
4873    #[test]
4874    fn a_rest_filling_its_bar_is_a_measure_rest() {
4875        let mut measure = Stream::with_kind(StreamKind::Measure);
4876        measure.insert(0.0, TimeSignature::new(4, 4).unwrap());
4877        let rest = Rest::new(Duration::half());
4878        let mut context = PartContext {
4879            instruments: &[],
4880            own_instruments: Vec::new(),
4881            own_clefs: Vec::new(),
4882            meter: None,
4883            last_divisions: None,
4884            spanners: Vec::new(),
4885            clef: None,
4886            previous: None,
4887            voice_bases: &NO_BASES,
4888            modulations: Vec::new(),
4889        };
4890        let exporter = MeasureExporter::new(&measure, 0.0, &mut context);
4891        assert_eq!(
4892            exporter.rest_element(&rest, 0.0, None).unwrap().dump(),
4893            "<note>\n  <rest />\n  <duration>20160</duration>\n  <type>half</type>\n</note>"
4894        );
4895
4896        let mut measure = Stream::with_kind(StreamKind::Measure);
4897        measure.insert(0.0, TimeSignature::new(2, 4).unwrap());
4898        let exporter = MeasureExporter::new(&measure, 0.0, &mut context);
4899        assert_eq!(
4900            exporter.rest_element(&rest, 0.0, None).unwrap().dump(),
4901            "<note>\n  <rest measure=\"yes\" />\n  <duration>20160</duration>\n</note>"
4902        );
4903    }
4904
4905    #[test]
4906    fn a_rests_colour_is_written_on_its_note() {
4907        // As music21 writes it: the colour before what hides it.
4908        let mut rest = Rest::new(Duration::quarter());
4909        rest.set_color(Some("red".to_string()));
4910        rest.set_hidden(true);
4911        let xml = with_measure(|exporter| exporter.rest_element(&rest, 0.0, None).unwrap()).dump();
4912        assert!(
4913            xml.starts_with("<note color=\"#FF0000\" print-object=\"no\" print-spacing=\"yes\">"),
4914            "{xml}"
4915        );
4916    }
4917
4918    #[test]
4919    fn a_triplet_carries_its_time_modification() {
4920        let rest = Rest::new(Duration::new(1.0 / 3.0).unwrap());
4921        let xml = with_measure(|exporter| exporter.rest_element(&rest, 0.0, None).unwrap()).dump();
4922        assert_eq!(
4923            xml,
4924            "<note>
4925  <rest />
4926  <duration>3360</duration>
4927  <type>eighth</type>
4928  <time-modification>
4929    <actual-notes>3</actual-notes>
4930    <normal-notes>2</normal-notes>
4931    <normal-type>eighth</normal-type>
4932  </time-modification>
4933</note>"
4934        );
4935    }
4936
4937    #[test]
4938    fn a_duration_needing_a_tie_is_refused() {
4939        let note = Note::from_name("C4")
4940            .unwrap()
4941            .with_duration(Duration::new(5.0).unwrap());
4942        let error =
4943            with_measure(|exporter| exporter.note_element(&note, 0, None, None).unwrap_err());
4944        assert_eq!(
4945            error,
4946            Error::music_xml(
4947                "Cannot convert complex durations to MusicXML. Try exporting with \
4948                 makeNotation=True or manually running splitAtDurations()"
4949                    .to_string()
4950            )
4951        );
4952    }
4953
4954    #[test]
4955    fn moving_forward_and_back_counts_divisions() {
4956        let root = with_measure(|exporter| {
4957            exporter.move_forward(1.0);
4958            exporter.move_backward(2.0);
4959            exporter.root.clone()
4960        });
4961        assert_eq!(
4962            root.dump(),
4963            "<measure>
4964  <forward>
4965    <duration>10080</duration>
4966  </forward>
4967  <backup>
4968    <duration>20160</duration>
4969  </backup>
4970</measure>"
4971        );
4972    }
4973
4974    #[test]
4975    fn ties_are_written_twice_over() {
4976        let tie = Tie::new(TieType::Continue);
4977        let written: Vec<String> = tie_elements(&tie).iter().map(Element::dump).collect();
4978        assert_eq!(written, ["<tie type=\"stop\" />", "<tie type=\"start\" />"]);
4979        let tied: Vec<String> = tied_elements(&tie).iter().map(Element::dump).collect();
4980        assert_eq!(tied, ["<tied type=\"stop\" />", "<tied type=\"start\" />"]);
4981        let mut hidden = Tie::new(TieType::Continue);
4982        hidden.set_style(TieStyle::Hidden);
4983        assert!(tied_elements(&hidden).is_empty());
4984    }
4985
4986    #[test]
4987    fn beams_name_their_ends() {
4988        let mut beam = Beam::new(BeamType::Start, None);
4989        beam.set_number(Some(1));
4990        assert_eq!(
4991            beam_element(&beam).unwrap().dump(),
4992            "<beam number=\"1\">begin</beam>"
4993        );
4994        beam.set_beam_type(Some(BeamType::Stop));
4995        assert_eq!(
4996            beam_element(&beam).unwrap().dump(),
4997            "<beam number=\"1\">end</beam>"
4998        );
4999        beam.set_beam_type(Some(BeamType::PartialBeam));
5000        beam.set_direction(Some(BeamDirection::Left));
5001        assert_eq!(
5002            beam_element(&beam).unwrap().dump(),
5003            "<beam number=\"1\">backward hook</beam>"
5004        );
5005        beam.set_direction(None);
5006        assert_eq!(
5007            beam_element(&beam).unwrap_err(),
5008            Error::music_xml(
5009                "partial beam defined without a proper direction set (set to None)".to_string()
5010            )
5011        );
5012    }
5013
5014    #[test]
5015    fn key_signatures_traditional_and_not() {
5016        assert_eq!(
5017            key_signature_element(&KeySignature::new(-3), None)
5018                .unwrap()
5019                .dump(),
5020            "<key>\n  <fifths>-3</fifths>\n</key>"
5021        );
5022        let pitches = vec![
5023            Pitch::from_name("C#").unwrap(),
5024            Pitch::from_name("E-4").unwrap(),
5025        ];
5026        assert_eq!(
5027            key_signature_element(&KeySignature::from_altered_pitches(pitches), None)
5028                .unwrap()
5029                .dump(),
5030            "<key>
5031  <key-step>C</key-step>
5032  <key-alter>1</key-alter>
5033  <key-step>E</key-step>
5034  <key-alter>-1</key-alter>
5035  <key-octave number=\"2\">4</key-octave>
5036</key>"
5037        );
5038    }
5039
5040    #[test]
5041    fn a_meter_written_in_parts_writes_each() {
5042        assert_eq!(
5043            time_signature_element(&TimeSignature::new(3, 4).unwrap())
5044                .unwrap()
5045                .dump(),
5046            "<time>\n  <beats>3</beats>\n  <beat-type>4</beat-type>\n</time>"
5047        );
5048        assert_eq!(
5049            time_signature_element(&TimeSignature::from_ratio_string("3/4+2/4").unwrap())
5050                .unwrap()
5051                .dump(),
5052            "<time>
5053  <beats>3</beats>
5054  <beat-type>4</beat-type>
5055  <beats>2</beats>
5056  <beat-type>4</beat-type>
5057</time>"
5058        );
5059    }
5060
5061    #[test]
5062    fn clefs_write_their_sign_line_and_octave() {
5063        assert_eq!(
5064            clef_element(&Clef::of_kind(crate::clef::ClefKind::GClef))
5065                .unwrap()
5066                .dump(),
5067            "<clef>\n  <sign>G</sign>\n</clef>"
5068        );
5069        assert_eq!(
5070            clef_element(&Clef::of_kind(crate::clef::ClefKind::Treble8vbClef))
5071                .unwrap()
5072                .dump(),
5073            "<clef>
5074  <sign>G</sign>
5075  <line>2</line>
5076  <clef-octave-change>-1</clef-octave-change>
5077</clef>"
5078        );
5079        assert_eq!(
5080            clef_element(&Clef::of_kind(crate::clef::ClefKind::PercussionClef))
5081                .unwrap()
5082                .dump(),
5083            "<clef>\n  <sign>percussion</sign>\n</clef>"
5084        );
5085    }
5086
5087    #[test]
5088    fn a_transposition_is_steps_semitones_and_octaves() {
5089        let dump = |name: &str| transpose_element(&Interval::from_name(name).unwrap()).dump();
5090        assert_eq!(
5091            dump("P5"),
5092            "<transpose>\n  <diatonic>4</diatonic>\n  <chromatic>7</chromatic>\n</transpose>"
5093        );
5094        assert_eq!(
5095            dump("A13"),
5096            "<transpose>
5097  <diatonic>5</diatonic>
5098  <chromatic>10</chromatic>
5099  <octave-change>1</octave-change>
5100</transpose>"
5101        );
5102        assert_eq!(
5103            dump("-M9"),
5104            "<transpose>
5105  <diatonic>-1</diatonic>
5106  <chromatic>-2</chromatic>
5107  <octave-change>-1</octave-change>
5108</transpose>"
5109        );
5110    }
5111
5112    #[test]
5113    fn a_dynamic_is_a_direction_with_its_loudness() {
5114        let root = with_measure(|exporter| {
5115            exporter.dynamic_element(&Dynamic::new("ppp"), 1.0).unwrap();
5116            exporter.root.clone()
5117        });
5118        assert_eq!(
5119            root.dump(),
5120            "<measure>
5121  <direction>
5122    <direction-type>
5123      <dynamics default-x=\"-36\" default-y=\"-80\">
5124        <ppp />
5125      </dynamics>
5126    </direction-type>
5127    <offset sound=\"yes\">10080</offset>
5128    <sound dynamics=\"19\" />
5129  </direction>
5130</measure>"
5131        );
5132    }
5133
5134    #[test]
5135    fn a_metronome_mark_writes_its_beat_and_its_word() {
5136        let mark =
5137            MetronomeMark::with_number_and_text(40.0, "slow").with_referent(Duration::half());
5138        let root = with_measure(|exporter| {
5139            exporter.tempo_elements(&mark, 0.0).unwrap();
5140            exporter.root.clone()
5141        });
5142        assert_eq!(
5143            root.dump(),
5144            "<measure>
5145  <direction>
5146    <direction-type>
5147      <metronome parentheses=\"no\">
5148        <beat-unit>half</beat-unit>
5149        <per-minute>40</per-minute>
5150      </metronome>
5151    </direction-type>
5152    <sound tempo=\"80\" />
5153  </direction>
5154  <direction>
5155    <direction-type>
5156      <words default-y=\"45\" font-weight=\"bold\">slow</words>
5157    </direction-type>
5158  </direction>
5159</measure>"
5160        );
5161
5162        let sounding = MetronomeMark::default().with_number_sounding(60.0);
5163        let root = with_measure(|exporter| {
5164            exporter.tempo_elements(&sounding, 0.0).unwrap();
5165            exporter.root.clone()
5166        });
5167        assert_eq!(
5168            root.dump(),
5169            "<measure>
5170  <direction>
5171    <direction-type>
5172      <words />
5173    </direction-type>
5174    <sound tempo=\"60\" />
5175  </direction>
5176</measure>"
5177        );
5178    }
5179
5180    #[test]
5181    fn a_chord_symbol_is_a_harmony() {
5182        let dump = |figure: &str| {
5183            let symbol = ChordSymbol::parse_music21(figure).unwrap();
5184            with_measure(|exporter| exporter.harmony_element(&symbol, 0.0).unwrap()).dump()
5185        };
5186        // MusicXML calls a dominant seventh `dominant`.
5187        assert_eq!(
5188            dump("C7"),
5189            "<harmony>
5190  <root>
5191    <root-step>C</root-step>
5192  </root>
5193  <kind>dominant</kind>
5194</harmony>"
5195        );
5196        assert_eq!(
5197            dump("F sus add 9"),
5198            "<harmony>
5199  <root>
5200    <root-step>F</root-step>
5201  </root>
5202  <kind>suspended-fourth</kind>
5203  <degree>
5204    <degree-value>9</degree-value>
5205    <degree-alter>0</degree-alter>
5206    <degree-type>add</degree-type>
5207  </degree>
5208</harmony>"
5209        );
5210        let no_chord = ChordSymbol::no_chord(None);
5211        assert_eq!(
5212            with_measure(|exporter| exporter.harmony_element(&no_chord, 0.0).unwrap()).dump(),
5213            "<harmony>
5214  <root>
5215    <root-step text=\"\">C</root-step>
5216  </root>
5217  <kind text=\"N.C.\">none</kind>
5218</harmony>"
5219        );
5220    }
5221
5222    #[test]
5223    fn a_lyric_names_its_verse() {
5224        let mut lyric = Lyric::new("hel");
5225        lyric.set_syllabic(Syllabic::Begin);
5226        assert_eq!(
5227            lyric_element(&lyric).unwrap().dump(),
5228            "<lyric name=\"1\" number=\"1\">
5229  <syllabic>begin</syllabic>
5230  <text>hel</text>
5231</lyric>"
5232        );
5233    }
5234
5235    #[test]
5236    fn a_whole_score_writes_as_a_music21_fragment() {
5237        let mut measure = Stream::with_kind(StreamKind::Measure);
5238        measure.set_number(1);
5239        measure.insert(0.0, TimeSignature::new(1, 4).unwrap());
5240        measure.insert(0.0, Clef::treble());
5241        measure.push(Note::from_name("D#4").unwrap());
5242        let mut part = Stream::with_kind(StreamKind::Part);
5243        part.push(measure);
5244        let mut score = Stream::with_kind(StreamKind::Score);
5245        score.push(part);
5246        let options = ExportOptions {
5247            encoding_date: Some("2026-09-28".to_string()),
5248            software: "music21 v.11.0.0".to_string(),
5249            ..ExportOptions::default()
5250        };
5251        assert_eq!(
5252            to_musicxml(&score, &options).unwrap(),
5253            "<?xml version=\"1.0\" encoding=\"utf-8\"?>
5254<!DOCTYPE score-partwise  PUBLIC \"-//Recordare//DTD MusicXML 4.0 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">
5255<score-partwise version=\"4.0\">
5256  <movement-title>Music21 Fragment</movement-title>
5257  <identification>
5258    <creator type=\"composer\">Music21</creator>
5259    <encoding>
5260      <encoding-date>2026-09-28</encoding-date>
5261      <software>music21 v.11.0.0</software>
5262      <supports element=\"beam\" type=\"yes\" />
5263      <supports element=\"stem\" type=\"yes\" />
5264      <supports element=\"accidental\" type=\"yes\" />
5265    </encoding>
5266  </identification>
5267  <defaults>
5268    <scaling>
5269      <millimeters>7</millimeters>
5270      <tenths>40</tenths>
5271    </scaling>
5272  </defaults>
5273  <part-list>
5274    <score-part id=\"P1\">
5275      <part-name />
5276    </score-part>
5277  </part-list>
5278  <!--=========================== Part 1 ===========================-->
5279  <part id=\"P1\">
5280    <!--========================= Measure 1 ==========================-->
5281    <measure implicit=\"no\" number=\"1\">
5282      <attributes>
5283        <divisions>10080</divisions>
5284        <time>
5285          <beats>1</beats>
5286          <beat-type>4</beat-type>
5287        </time>
5288        <clef>
5289          <sign>G</sign>
5290          <line>2</line>
5291        </clef>
5292      </attributes>
5293      <note>
5294        <pitch>
5295          <step>D</step>
5296          <alter>1</alter>
5297          <octave>4</octave>
5298        </pitch>
5299        <duration>10080</duration>
5300        <type>quarter</type>
5301        <accidental>sharp</accidental>
5302      </note>
5303    </measure>
5304  </part>
5305</score-partwise>"
5306        );
5307    }
5308
5309    #[test]
5310    fn a_part_that_changes_instrument_says_who_plays_each_note() {
5311        // music21's `setNoteInstrument`: the last instrument standing at or
5312        // before a note plays it, unless the note keeps one of its own.
5313        let measure = |number, instrument: &str, stored: Option<&str>| {
5314            let mut measure = Stream::with_kind(StreamKind::Measure);
5315            measure.set_number(number);
5316            measure.insert(0.0, Instrument::of_kind(instrument).unwrap());
5317            let mut note = Note::from_name("C4")
5318                .unwrap()
5319                .with_duration(Duration::quarter());
5320            note.set_stored_instrument(stored.map(|kind| Instrument::of_kind(kind).unwrap()));
5321            measure.insert(0.0, note);
5322            measure
5323        };
5324        let mut part = Stream::with_kind(StreamKind::Part);
5325        part.insert(0.0, measure(1, "Violin", None));
5326        part.insert(1.0, measure(2, "Viola", None));
5327        part.insert(2.0, measure(3, "Viola", Some("Violin")));
5328        let mut score = Stream::with_kind(StreamKind::Score);
5329        score.push(part);
5330        let written = to_musicxml(&score, &ExportOptions::default()).unwrap();
5331        let ids: Vec<&str> = written
5332            .lines()
5333            .filter_map(|line| line.trim().strip_prefix("<instrument id=\""))
5334            .map(|rest| rest.trim_end_matches("\" />"))
5335            .collect();
5336        assert_eq!(ids.len(), 3);
5337        assert_ne!(ids[0], ids[1]);
5338        assert_eq!(ids[0], ids[2]);
5339        for id in &ids {
5340            assert!(written.contains(&format!("<score-instrument id=\"{id}\">")));
5341        }
5342    }
5343
5344    #[test]
5345    fn a_part_without_measures_is_refused() {
5346        let mut part = Stream::with_kind(StreamKind::Part);
5347        part.push(Note::from_name("C4").unwrap());
5348        let mut score = Stream::with_kind(StreamKind::Score);
5349        score.push(part);
5350        assert_eq!(
5351            to_musicxml(&score, &ExportOptions::default()).unwrap_err(),
5352            Error::music_xml(
5353                "Cannot export with makeNotation=False if there are no measures".to_string()
5354            )
5355        );
5356    }
5357
5358    #[test]
5359    fn divider_comments_are_centred_in_sixty_signs() {
5360        let mut root = Element::new("score-partwise");
5361        add_divider_comment(&mut root, "second accidental below");
5362        assert_eq!(
5363            root.dump(),
5364            "<score-partwise>\n  <!--================== second accidental below ===================-->\n</score-partwise>"
5365        );
5366    }
5367}