Skip to main content

music21/musicxml/
fragment.rs

1//! One element written alone: what music21's `MeasureExporter` methods
2//! (`noteToXml`, `chordToXml`, `clefToXml`, `dynamicToXml` and the rest)
3//! hand back for an element given to them outside any score.
4
5use std::collections::HashMap;
6
7use super::tree::Element;
8use super::{
9    ExportOptions, MeasureExporter, Numbered, PartContext, barline_element, clef_element,
10    credit_element, frame_element, frame_note_element, key_element, midi_instrument,
11    page_layout_element, score_element, score_instrument, staff_details_element,
12    staff_group_element, staff_layout_element, system_layout_element, time_signature_element,
13    transpose_element,
14};
15use crate::defaults::FloatType;
16use crate::error::Result;
17use crate::instrument::Instrument;
18use crate::interval::Interval;
19use crate::layout::Layout;
20use crate::spanner::Spanner;
21use crate::stream::{Stream, StreamElement, StreamKind};
22
23/// The MusicXML music21's `MeasureExporter` writes for one element, each
24/// top-level element as a document of its own.
25///
26/// The element stands at `offset` in `measure`, whose meter and clefs are
27/// what decide, as they do for music21, whether a rest fills its bar and
28/// where it is displayed; with no measure it stands alone in one of its
29/// own. The writer has written nothing of the measure before it.
30///
31/// A note is one `<note>`, a chord a `<note>` for each of its pitches, a
32/// dynamic or a text mark a `<direction>`; a clef, a key or a meter is the
33/// `<clef>`, `<key>` or `<time>` that goes in a measure's `<attributes>`,
34/// a barline is its `<barline>` with no location, and a text box the
35/// `<credit>` a score writes for it. What a measure
36/// writes nothing for, such as an instrument, writes nothing here.
37///
38/// ```
39/// use music21::{Duration, Note, StreamElement};
40/// use music21::musicxml::{Surroundings, element_xml};
41///
42/// let note = Note::from_name("D#4")?.with_duration(Duration::half());
43/// let written = element_xml(&StreamElement::from(note), &Surroundings::default())?;
44/// assert_eq!(written.len(), 1);
45/// assert!(written[0].starts_with("<note>"));
46/// assert!(written[0].contains("<type>half</type>"));
47/// # Ok::<(), music21::Error>(())
48/// ```
49///
50/// # Errors
51///
52/// What the measure writer refuses for the element: a duration no single
53/// note value writes, a stream, a colour CSS has no name for.
54pub fn element_xml(element: &StreamElement, around: &Surroundings<'_>) -> Result<Vec<String>> {
55    Ok(written_elements(element, around)?
56        .iter()
57        .map(Element::dump)
58        .collect())
59}
60
61/// Where an element written alone stands: the measure holding it, its
62/// offset there, and the spanners joining it, which mark the element as
63/// they mark it in a score (a slur's end on a note, a pedal's change at a
64/// bounce); the directions a spanner opens and closes with are not the
65/// element's and are left out. By default it stands at the start of a
66/// measure of its own, joined by none.
67#[derive(Clone, Copy, Debug, Default)]
68pub struct Surroundings<'a> {
69    /// The measure it stands in.
70    pub measure: Option<&'a Stream>,
71    /// Where in the measure it stands.
72    pub offset: FloatType,
73    /// The spanners joining it, numbered from one in this order.
74    pub spanners: &'a [Joined<'a>],
75}
76
77/// A spanner joining an element written alone, and where among the
78/// spanner's elements the element stands.
79#[derive(Clone, Copy, Debug)]
80pub struct Joined<'a> {
81    /// The spanner.
82    pub spanner: &'a Spanner,
83    /// Where the element stands among the spanner's elements.
84    pub index: usize,
85    /// How many elements the spanner joins.
86    pub count: usize,
87}
88
89/// The elements [`element_xml`] writes, as the crate's tree.
90fn written_elements(element: &StreamElement, around: &Surroundings<'_>) -> Result<Vec<Element>> {
91    // The marks a measure writes into its `<attributes>`, alone.
92    match element {
93        StreamElement::Clef(clef) => return Ok(vec![clef_element(clef)?]),
94        StreamElement::TimeSignature(meter) => return Ok(vec![time_signature_element(meter)?]),
95        StreamElement::Key(_) | StreamElement::KeySignature(_) => {
96            return key_element(element)
97                .transpose()
98                .map(|key| key.into_iter().collect());
99        }
100        StreamElement::TextBox(text) => return Ok(vec![credit_element(text)?]),
101        StreamElement::Barline(barline) => {
102            let mut written = barline_element(Some(barline), "", None);
103            written.remove_attribute("location");
104            return Ok(vec![written]);
105        }
106        _ => {}
107    }
108
109    // Everything else, as a measure with nothing else in it writes it.
110    let alone = Stream::with_kind(StreamKind::Measure);
111    let measure = around.measure.unwrap_or(&alone);
112    let own_clefs = measure
113        .events()
114        .iter()
115        .filter_map(|event| match event.element() {
116            StreamElement::Clef(clef) => Some((event.offset(), clef)),
117            _ => None,
118        })
119        .collect();
120    let spanners = around
121        .spanners
122        .iter()
123        .enumerate()
124        .map(|(number, joined)| Numbered {
125            spanner: joined.spanner,
126            id_local: number as u32 + 1,
127            elements: (0..joined.count)
128                .map(|index| (index == joined.index).then_some(element))
129                .collect(),
130        })
131        .collect();
132    let voice_bases = HashMap::new();
133    let mut context = PartContext {
134        instruments: &[],
135        own_instruments: Vec::new(),
136        own_clefs,
137        meter: None,
138        last_divisions: None,
139        spanners,
140        clef: None,
141        previous: None,
142        voice_bases: &voice_bases,
143        modulations: Vec::new(),
144    };
145    let mut exporter = MeasureExporter::new(measure, 0.0, &mut context);
146    exporter.write_element(around.offset, element, element as *const StreamElement)?;
147    Ok(exporter.root.elements().cloned().collect())
148}
149
150/// What music21's `ScoreExporter` writes before a score's parts, element
151/// by element: the work and movement titles, `<identification>`,
152/// `<defaults>`, a `<credit>` for each text box and the `<part-list>`.
153///
154/// A score with nothing in it is written as a part of one empty measure,
155/// rather than as the blank page [`super::to_musicxml`] writes for it, so
156/// that what is written is what the score and `options` say.
157///
158/// ```
159/// use music21::{Stream, StreamKind};
160/// use music21::musicxml::{ExportOptions, score_header_xml};
161///
162/// let header = score_header_xml(&Stream::with_kind(StreamKind::Score), &ExportOptions::default())?;
163/// assert!(header.iter().any(|element| element.starts_with("<identification>")));
164/// assert!(header.last().unwrap().starts_with("<part-list>"));
165/// # Ok::<(), music21::Error>(())
166/// ```
167///
168/// # Errors
169///
170/// What writing the score refuses.
171pub fn score_header_xml(score: &Stream, options: &ExportOptions) -> Result<Vec<String>> {
172    let placeholder;
173    let score = if score.is_empty() {
174        let mut measure = Stream::with_kind(StreamKind::Measure);
175        measure.set_number(1);
176        let mut part = Stream::with_kind(StreamKind::Part);
177        part.push(measure);
178        let mut filled = Stream::with_kind(score.kind());
179        filled.set_metadata(score.metadata().cloned());
180        filled.set_stream_style(score.stream_style().cloned());
181        filled.push(part);
182        placeholder = filled;
183        &placeholder
184    } else {
185        score
186    };
187    let root = score_element(score, options)?;
188    Ok(root
189        .elements()
190        .filter(|element| element.tag() != "part")
191        .map(Element::dump)
192        .collect())
193}
194
195/// What music21's `instrumentToXmlScoreInstrument` and
196/// `instrumentToXmlMidiInstrument` write for an instrument: its
197/// `<score-instrument>` and its `<midi-instrument>`.
198///
199/// ```
200/// use music21::Instrument;
201/// use music21::musicxml::instrument_xml;
202///
203/// let (score, midi) = instrument_xml(&Instrument::new());
204/// assert!(score.starts_with("<score-instrument"));
205/// assert!(midi.starts_with("<midi-instrument"));
206/// ```
207pub fn instrument_xml(instrument: &Instrument) -> (String, String) {
208    (
209        score_instrument(instrument).dump(),
210        midi_instrument(instrument).dump(),
211    )
212}
213
214/// What music21's `intervalToXmlTranspose` writes for an interval a part
215/// is transposed by: its `<transpose>`.
216///
217/// ```
218/// use music21::Interval;
219/// use music21::musicxml::transpose_xml;
220///
221/// let written = transpose_xml(&Interval::from_name("-M2")?);
222/// assert!(written.contains("<diatonic>-1</diatonic>"));
223/// assert!(written.contains("<chromatic>-2</chromatic>"));
224/// # Ok::<(), music21::Error>(())
225/// ```
226pub fn transpose_xml(interval: &Interval) -> String {
227    transpose_element(interval).dump()
228}
229
230/// The element music21 writes a page, system or staff layout as:
231/// `<page-layout>`, `<system-layout>` or `<staff-layout>`, as
232/// `pageLayoutToXmlPageLayout` and its neighbours write them. `None` for
233/// a score layout, which is written as the parts of `<defaults>`.
234///
235/// ```
236/// use music21::layout::{Layout, StaffLayout};
237/// use music21::musicxml::layout_xml;
238///
239/// let written = layout_xml(&Layout::Staff(StaffLayout::default()));
240/// assert_eq!(written.as_deref(), Some("<staff-layout />"));
241/// ```
242pub fn layout_xml(layout: &Layout) -> Option<String> {
243    let element = match layout {
244        Layout::Page(page) => page_layout_element(page),
245        Layout::System(system) => system_layout_element(system),
246        Layout::Staff(staff) => staff_layout_element(staff),
247        Layout::Score(_) => return None,
248    };
249    Some(element.dump())
250}
251
252/// What music21's `staffLayoutToXmlStaffDetails` writes for a staff
253/// layout: its `<staff-details>`.
254///
255/// ```
256/// use music21::layout::StaffLayout;
257/// use music21::musicxml::staff_details_xml;
258///
259/// assert!(staff_details_xml(&StaffLayout::default()).starts_with("<staff-details"));
260/// ```
261pub fn staff_details_xml(staff: &crate::layout::StaffLayout) -> String {
262    staff_details_element(staff).dump()
263}
264
265/// What music21's `staffGroupToXmlPartGroup` writes for a staff group:
266/// the `<part-group type="start">`, its number left for the part list to
267/// give it.
268///
269/// ```
270/// use music21::stream::StaffGroup;
271/// use music21::musicxml::part_group_xml;
272///
273/// assert!(part_group_xml(&StaffGroup::new(vec![0, 1])).starts_with("<part-group type=\"start\">"));
274/// ```
275pub fn part_group_xml(group: &crate::stream::StaffGroup) -> String {
276    staff_group_element(group).dump()
277}
278
279/// What music21's `fretBoardToXml` writes for a chord diagram: its
280/// `<frame>`, the notes lowest string first; `None` for a board with no
281/// notes.
282pub fn frame_xml(board: &crate::tablature::FretBoard) -> Option<String> {
283    frame_element(board).map(|frame| frame.dump())
284}
285
286/// What music21's `fretNoteToXml` writes for one stopped string: its
287/// `<frame-note>`.
288pub fn frame_note_xml(note: &crate::tablature::FretNote) -> String {
289    frame_note_element(note).dump()
290}
291
292/// What music21's `chordWithFretBoardToXml` writes for a chord symbol with
293/// a diagram: the symbol's `<harmony>` with the `<frame>` at its end.
294///
295/// # Errors
296///
297/// What writing the symbol refuses.
298pub fn chord_with_fret_board_xml(chord: &crate::tablature::ChordWithFretBoard) -> Result<String> {
299    let symbol = StreamElement::ChordSymbol(chord.chord_symbol.clone());
300    let mut written = written_elements(&symbol, &Surroundings::default())?;
301    let mut harmony = written.remove(0);
302    if let Some(frame) = frame_element(&chord.fret_board) {
303        harmony.push(frame);
304    }
305    Ok(harmony.dump())
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::chord::Chord;
312    use crate::clef::Clef;
313    use crate::duration::Duration;
314    use crate::instrument::Instrument;
315
316    #[test]
317    fn a_chord_is_a_note_for_each_pitch() {
318        let chord = Chord::new("C4 E4 G4").unwrap();
319        let written = element_xml(&StreamElement::from(chord), &Surroundings::default()).unwrap();
320        assert_eq!(written.len(), 3);
321        assert!(written[1].contains("<chord />"));
322    }
323
324    #[test]
325    fn a_clef_is_the_clef_alone() {
326        let written = element_xml(
327            &StreamElement::from(Clef::treble()),
328            &Surroundings::default(),
329        )
330        .unwrap();
331        assert_eq!(
332            written,
333            ["<clef>\n  <sign>G</sign>\n  <line>2</line>\n</clef>"]
334        );
335    }
336
337    /// music21's `restToXml` docstring: the measure's meter decides.
338    #[test]
339    fn a_rest_filling_its_measure_is_a_measure_rest() {
340        let mut measure = Stream::with_kind(StreamKind::Measure);
341        measure.insert(0.0, crate::meter::TimeSignature::new(2, 4).unwrap());
342        let rest = StreamElement::from(crate::rest::Rest::new(Duration::half()));
343        let written = element_xml(
344            &rest,
345            &Surroundings {
346                measure: Some(&measure),
347                ..Surroundings::default()
348            },
349        )
350        .unwrap();
351        assert!(
352            written[0].contains("<rest measure=\"yes\" />"),
353            "{}",
354            written[0]
355        );
356    }
357
358    /// music21's `dynamicToXml` docstring: the style moves the mark.
359    #[test]
360    fn a_dynamic_is_written_where_its_style_puts_it() {
361        let mut dynamic = crate::dynamics::Dynamic::new("ppp");
362        let mut style = dynamic.style().clone();
363        style.relative_y = Some(crate::style::StyleValue::Whole(-10));
364        dynamic.set_style(style);
365        let written = element_xml(&StreamElement::from(dynamic), &Surroundings::default()).unwrap();
366        assert!(
367            written[0]
368                .contains("<dynamics default-x=\"-36\" default-y=\"-80\" relative-y=\"-10\">"),
369            "{}",
370            written[0]
371        );
372    }
373
374    /// music21's `keySignatureToXml` docstring: a mode set by hand.
375    #[test]
376    fn a_signature_given_a_mode_writes_it() {
377        let mut signature = crate::key::KeySignature::new(-3);
378        signature.set_mode(Some("major".to_string()));
379        let written =
380            element_xml(&StreamElement::from(signature), &Surroundings::default()).unwrap();
381        assert_eq!(
382            written,
383            ["<key>\n  <fifths>-3</fifths>\n  <mode>major</mode>\n</key>"]
384        );
385    }
386
387    /// music21's `fretNoteToXml` docstring.
388    #[test]
389    fn a_fret_note_is_a_frame_note() {
390        use crate::tablature::FretNote;
391        assert_eq!(
392            frame_note_xml(&FretNote::new(Some(3), Some(1), Some(2))),
393            "<frame-note>\n  <string>3</string>\n  <fret>1</fret>\n  <fingering>2</fingering>\n</frame-note>"
394        );
395        assert_eq!(
396            frame_note_xml(&FretNote::new(Some(5), Some(2), None)),
397            "<frame-note>\n  <string>5</string>\n  <fret>2</fret>\n</frame-note>"
398        );
399    }
400
401    /// music21's `fretBoardToXml` docstring: a D major chord on a guitar.
402    #[test]
403    fn a_fret_board_is_a_frame() {
404        use crate::tablature::{FretBoard, FretNote};
405        let board = FretBoard::new(
406            6,
407            vec![
408                FretNote::new(Some(1), Some(2), Some(2)),
409                FretNote::new(Some(2), Some(3), Some(3)),
410                FretNote::new(Some(3), Some(2), Some(1)),
411            ],
412            4,
413        );
414        let note = |string, fret, finger| {
415            format!(
416                "  <frame-note>\n    <string>{string}</string>\n    <fret>{fret}</fret>\n    \
417                 <fingering>{finger}</fingering>\n  </frame-note>\n"
418            )
419        };
420        assert_eq!(
421            frame_xml(&board).unwrap(),
422            format!(
423                "<frame>\n  <frame-strings>6</frame-strings>\n  <frame-frets>4</frame-frets>\n{}{}{}</frame>",
424                note(3, 2, 1),
425                note(2, 3, 3),
426                note(1, 2, 2)
427            )
428        );
429        assert_eq!(frame_xml(&FretBoard::new(6, Vec::new(), 4)), None);
430    }
431
432    #[test]
433    fn an_instrument_writes_nothing() {
434        let written = element_xml(
435            &StreamElement::from(Instrument::new()),
436            &Surroundings::default(),
437        )
438        .unwrap();
439        assert!(written.is_empty());
440    }
441
442    #[test]
443    fn a_length_no_value_writes_is_refused() {
444        let note = crate::note::Note::from_name("C4")
445            .unwrap()
446            .with_duration(Duration::new(2.5).unwrap());
447        assert!(element_xml(&StreamElement::from(note), &Surroundings::default()).is_err());
448    }
449}