Skip to main content

music21/musicxml/
partstaff.rs

1//! Several staves written as one part: music21's `PartStaffExporterMixin`.
2//!
3//! A piano's two staves are two `PartStaff` streams in music21 and one
4//! `<part>` in MusicXML. Each staff is written as a part of its own first;
5//! then every note, direction and forward is told which staff it is on, the
6//! later staves' measures are moved into the first's behind a `<backup>`,
7//! and the first measure's `<attributes>` is given the number of staves and
8//! a clef for each.
9//!
10//! The steps work on any tree that is an [`XmlTree`]: the crate's own, as
11//! its writer joins staves, and Python's `ElementTree`, as music21's mixin
12//! is called on one.
13
14use super::tree::{Element, Node};
15use crate::error::{Error, Result};
16
17fn export_error(message: impl Into<String>) -> Error {
18    Error::music_xml(message.into())
19}
20
21/// An XML element the joining steps can read and change: its tag,
22/// attributes, text and children, counted as ElementTree counts them,
23/// comments included.
24///
25/// [`XmlTree::child`] hands back a child to read. What it hands back may be
26/// a copy, so a child is changed through [`XmlTree::with_child`].
27pub trait XmlTree: Sized {
28    /// The tag, or nothing for a comment.
29    fn tag(&self) -> Option<String>;
30    /// An attribute, where it is set.
31    fn attribute(&self, name: &str) -> Option<String>;
32    /// Sets an attribute.
33    fn set_attribute(&mut self, name: &str, value: &str) -> Result<()>;
34    /// The text, where there is some.
35    fn text(&self) -> Option<String>;
36    /// Sets the text.
37    fn set_text(&mut self, text: &str) -> Result<()>;
38    /// How many children, comments included.
39    fn len(&self) -> usize;
40    /// Whether it has no children.
41    fn is_empty(&self) -> bool {
42        self.len() == 0
43    }
44    /// The child at an index, to read.
45    fn child(&self, index: usize) -> Option<Self>;
46    /// Runs `change` on the child at an index, where it is an element.
47    fn with_child<R>(&mut self, index: usize, change: impl FnOnce(&mut Self) -> R) -> Option<R>;
48    /// Puts a node in at an index.
49    fn insert(&mut self, index: usize, child: Self) -> Result<()>;
50    /// Takes away the child at an index.
51    fn remove(&mut self, index: usize) -> Result<()>;
52    /// A new element of this tag, of the same kind of tree.
53    fn element(&self, tag: &str) -> Result<Self>;
54    /// A new comment, of the same kind of tree.
55    fn comment(&self, text: &str) -> Result<Self>;
56    /// A copy of the whole element, unconnected to this one.
57    fn deep_copy(&self) -> Result<Self>;
58}
59
60impl XmlTree for Element {
61    fn tag(&self) -> Option<String> {
62        Some(Element::tag(self).to_string())
63    }
64
65    fn attribute(&self, name: &str) -> Option<String> {
66        self.get(name).map(str::to_string)
67    }
68
69    fn set_attribute(&mut self, name: &str, value: &str) -> Result<()> {
70        self.set(name.to_string(), value);
71        Ok(())
72    }
73
74    fn text(&self) -> Option<String> {
75        Element::text(self).map(str::to_string)
76    }
77
78    fn set_text(&mut self, text: &str) -> Result<()> {
79        Element::set_text(self, text);
80        Ok(())
81    }
82
83    fn len(&self) -> usize {
84        self.children().len()
85    }
86
87    fn child(&self, index: usize) -> Option<Self> {
88        match self.children().get(index)? {
89            Node::Element(element) => Some(element.clone()),
90            Node::Comment(text) => Some(comment_carrier(text)),
91        }
92    }
93
94    fn with_child<R>(&mut self, index: usize, change: impl FnOnce(&mut Self) -> R) -> Option<R> {
95        match self.children_mut().get_mut(index)? {
96            Node::Element(element) => Some(change(element)),
97            Node::Comment(_) => None,
98        }
99    }
100
101    fn insert(&mut self, index: usize, child: Self) -> Result<()> {
102        let node = match carried_comment(&child) {
103            Some(text) => Node::Comment(text),
104            None => Node::Element(child),
105        };
106        self.children_mut().insert(index, node);
107        Ok(())
108    }
109
110    fn remove(&mut self, index: usize) -> Result<()> {
111        self.children_mut().remove(index);
112        Ok(())
113    }
114
115    fn element(&self, tag: &str) -> Result<Self> {
116        Ok(Element::new(tag.to_string()))
117    }
118
119    fn comment(&self, text: &str) -> Result<Self> {
120        Ok(comment_carrier(text))
121    }
122
123    fn deep_copy(&self) -> Result<Self> {
124        Ok(self.clone())
125    }
126}
127
128/// The tag a comment of the crate's tree travels under while it is handed
129/// about as an element: no XML tag can start with `!`.
130const COMMENT_TAG: &str = "!--";
131
132/// A comment, carried as an element.
133fn comment_carrier(text: &str) -> Element {
134    Element::with_text(COMMENT_TAG, text)
135}
136
137/// The text of a carried comment.
138fn carried_comment(element: &Element) -> Option<String> {
139    (Element::tag(element) == COMMENT_TAG).then(|| Element::text(element).unwrap_or("").to_string())
140}
141
142/// The child elements of a tree with their indices, comments passed over.
143fn elements_of<T: XmlTree>(tree: &T) -> Vec<(usize, T)> {
144    (0..tree.len())
145        .filter_map(|index| tree.child(index).map(|child| (index, child)))
146        .filter(|(_, child)| is_element(child))
147        .collect()
148}
149
150/// Whether a node is an element rather than a comment.
151fn is_element<T: XmlTree>(node: &T) -> bool {
152    node.tag().is_some_and(|tag| tag != COMMENT_TAG)
153}
154
155/// Whether a node is an element of this tag.
156fn tagged<T: XmlTree>(node: &T, tag: &str) -> bool {
157    node.tag().as_deref() == Some(tag)
158}
159
160/// The first child of a tag, with its index: ElementTree's `find`.
161fn find_in<T: XmlTree>(tree: &T, tag: &str) -> Option<(usize, T)> {
162    elements_of(tree)
163        .into_iter()
164        .find(|(_, child)| tagged(child, tag))
165}
166
167/// A new element of a tag holding text.
168fn with_text_of<T: XmlTree>(tree: &T, tag: &str, text: &str) -> Result<T> {
169    let mut element = tree.element(tag)?;
170    element.set_text(text)?;
171    Ok(element)
172}
173
174/// music21's `helpers.insertBeforeElements`: `child` put in before the
175/// first child tagged one of `tags`, or at the end.
176fn insert_before<T: XmlTree>(tree: &mut T, child: T, tags: &[&str]) -> Result<()> {
177    let at = elements_of(tree)
178        .into_iter()
179        .find(|(_, element)| {
180            element
181                .tag()
182                .is_some_and(|tag| tags.contains(&tag.as_str()))
183        })
184        .map_or(tree.len(), |(index, _)| index);
185    tree.insert(at, child)
186}
187
188/// Whether the staves of a group start in the same key, or meter.
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum Across {
191    /// Every staff starts the same.
192    Same,
193    /// Some staff starts differently, so each staff's is written.
194    Different,
195}
196
197/// Which marks the staves of a group start with differently: music21's
198/// `isMultiAttribute` for keys and meters.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub struct StaffDifferences {
201    /// The keys.
202    pub keys: Across,
203    /// The meters.
204    pub meters: Across,
205}
206
207/// The tags a `<staff>` goes before inside a note, direction or forward.
208const BEFORE_STAFF: [&str; 5] = ["beam", "notations", "lyric", "play", "sound"];
209
210/// The children of a measure told their staff when staves are joined.
211pub const STAFF_TAGGED: [&str; 4] = ["note", "direction", "forward", "harmony"];
212
213/// music21's `addStaffTags`: a `<staff>` in each child of a measure whose
214/// tag is one of `tags`, before its beams, notations, lyrics and sound.
215///
216/// # Errors
217///
218/// A tree that is no `<measure>`, and a child that has a `<staff>` already.
219pub fn add_staff_tags<T: XmlTree>(measure: &mut T, staff: usize, tags: &[&str]) -> Result<()> {
220    if !tagged(measure, "measure") {
221        return Err(export_error("addStaffTags() only accepts <measure> tags"));
222    }
223    let number = measure.attribute("number").unwrap_or_default();
224    for (index, child) in elements_of(measure) {
225        if !child.tag().is_some_and(|tag| tags.contains(&tag.as_str())) {
226            continue;
227        }
228        if find_in(&child, "staff").is_some() {
229            return Err(export_error(format!(
230                "In part (), measure ({number}): Attempted to create a second <staff> tag"
231            )));
232        }
233        let tag = with_text_of(&child, "staff", &staff.to_string())?;
234        measure
235            .with_child(index, |child| insert_before(child, tag, &BEFORE_STAFF))
236            .transpose()?;
237    }
238    Ok(())
239}
240
241/// music21's `addStaffTagsMultiStaffParts`: [`add_staff_tags`] over every
242/// measure of each staff, the first staff numbered one.
243///
244/// # Errors
245///
246/// A child that has a `<staff>` already.
247pub fn add_staff_tags_to_staves<T: XmlTree>(parts: &mut [T]) -> Result<()> {
248    for (position, part) in parts.iter_mut().enumerate() {
249        for (index, _) in elements_of(part)
250            .into_iter()
251            .filter(|(_, child)| tagged(child, "measure"))
252        {
253            part.with_child(index, |measure| {
254                add_staff_tags(measure, position + 1, &STAFF_TAGGED)
255            })
256            .transpose()?;
257        }
258    }
259    Ok(())
260}
261
262/// music21's `movePartStaffMeasureContents`, `setEarliestAttributesAndClefs`
263/// and the staff tags before them: the staves of `parts`, first to last,
264/// joined into the first.
265///
266/// # Errors
267///
268/// A child that has a `<staff>` already, measures whose numbers cannot be
269/// put in order, more clefs than staves.
270pub fn join<T: XmlTree>(parts: &mut [T], differences: StaffDifferences) -> Result<()> {
271    add_staff_tags_to_staves(parts)?;
272    move_part_staff_contents(parts)?;
273    set_earliest_attributes_and_clefs(parts, differences)
274}
275
276/// music21's `movePartStaffMeasureContents`: every later staff's measures
277/// moved into the first's, a measure the first lacks put in where it falls.
278///
279/// # Errors
280///
281/// Measures whose numbers cannot be put in order.
282pub fn move_part_staff_contents<T: XmlTree>(parts: &mut [T]) -> Result<()> {
283    let Some((target, sources)) = parts.split_first_mut() else {
284        return Ok(());
285    };
286    for (index, source) in sources.iter().enumerate() {
287        let staff = index + 2;
288        let insertions = process_subsequent_part_staff(target, source, staff)?;
289        let mut inserted = 0;
290        for (at, nodes) in insertions {
291            for node in nodes {
292                target.insert(at + inserted, node)?;
293                inserted += 1;
294            }
295        }
296    }
297    Ok(())
298}
299
300/// music21's `measureNumberComesBefore`: whether one measure number comes
301/// strictly before another, suffixes and all.
302///
303/// ```
304/// use music21::musicxml::measure_number_comes_before;
305///
306/// assert!(measure_number_comes_before("23", "23a"));
307/// assert!(measure_number_comes_before("23b", "24a"));
308/// assert!(!measure_number_comes_before("23b", "23a"));
309/// ```
310pub fn measure_number_comes_before(first: &str, second: &str) -> bool {
311    if first == second {
312        return false;
313    }
314    let split = |number: &str| {
315        let digits: String = number.chars().take_while(char::is_ascii_digit).collect();
316        let suffix = number[digits.len()..].to_string();
317        (digits.parse::<i64>().unwrap_or(0), suffix)
318    };
319    let (first_number, first_suffix) = split(first);
320    let (second_number, second_suffix) = split(second);
321    if first_number != second_number {
322        return first_number < second_number;
323    }
324    first_suffix <= second_suffix
325}
326
327/// music21's `processSubsequentPartStaff`: each measure of `source` moved
328/// into the measure of `target` with the same number, and the measures
329/// `target` has no number for gathered, with their divider comments, to be
330/// inserted where they fall.
331///
332/// # Errors
333///
334/// Measures whose numbers cannot be put in order.
335pub fn process_subsequent_part_staff<T: XmlTree>(
336    target: &mut T,
337    source: &T,
338    staff: usize,
339) -> Result<Vec<(usize, Vec<T>)>> {
340    let divider = |number: &str| {
341        source.comment(&format!(
342            "========================= Measure {number} =========================="
343        ))
344    };
345    let mut insertions: Vec<(usize, Vec<T>)> = Vec::new();
346    let mut add =
347        |at: usize, nodes: Vec<T>| match insertions.iter_mut().find(|(index, _)| *index == at) {
348            Some((_, existing)) => existing.extend(nodes),
349            None => insertions.push((at, nodes)),
350        };
351    let source_measures: Vec<T> = elements_of(source)
352        .into_iter()
353        .filter(|(_, child)| tagged(child, "measure"))
354        .map(|(_, child)| child)
355        .collect();
356    let mut next = 0;
357    let before = |first: &Option<String>, second: &Option<String>| match (first, second) {
358        (Some(first), Some(second)) => measure_number_comes_before(first, second),
359        _ => false,
360    };
361    for (index, target_measure) in elements_of(target) {
362        if !tagged(&target_measure, "measure") {
363            continue;
364        }
365        let Some(mut source_measure) = source_measures.get(next) else {
366            return Ok(insertions);
367        };
368        let target_number = target_measure.attribute("number");
369        let mut source_number = source_measure.attribute("number");
370        if target_number == source_number {
371            move_measure_into(target, index, source_measure, staff)?;
372            next += 1;
373            continue;
374        }
375        // A measure the later staff lacks: wait for it with the same source
376        // measure.
377        if before(&target_number, &source_number) {
378            continue;
379        }
380        // Measures the first staff lacks go in on their own, until the
381        // numbers meet again.
382        while before(&source_number, &target_number) {
383            let number = source_number.clone().unwrap_or_default();
384            add(index, vec![divider(&number)?, source_measure.deep_copy()?]);
385            next += 1;
386            let Some(following) = source_measures.get(next) else {
387                return Ok(insertions);
388            };
389            source_measure = following;
390            source_number = source_measure.attribute("number");
391        }
392        if target_number == source_number {
393            move_measure_into(target, index, source_measure, staff)?;
394            next += 1;
395            continue;
396        }
397        if before(&target_number, &source_number) {
398            continue;
399        }
400        return Err(export_error(format!(
401            "joinPartStaffs() was unable to order the measures {}, {}",
402            target_number.as_deref().unwrap_or("None"),
403            source_number.as_deref().unwrap_or("None")
404        )));
405    }
406    let end = target.len();
407    for remaining in &source_measures[next..] {
408        let Some(number) = remaining.attribute("number") else {
409            continue;
410        };
411        add(end, vec![divider(&number)?, remaining.deep_copy()?]);
412    }
413    Ok(insertions)
414}
415
416/// [`move_measure_contents`] into the target's child at an index.
417fn move_measure_into<T: XmlTree>(
418    target: &mut T,
419    index: usize,
420    source: &T,
421    staff: usize,
422) -> Result<()> {
423    target
424        .with_child(index, |measure| {
425            move_measure_contents(source, measure, staff)
426        })
427        .transpose()
428        .map(|_| ())
429}
430
431/// The tags a `<voice>` goes before inside a `<note>`.
432const BEFORE_VOICE: [&str; 8] = [
433    "type",
434    "dot",
435    "accidental",
436    "time-modification",
437    "stem",
438    "notehead",
439    "notehead-text",
440    "staff",
441];
442
443/// A duration's text as a whole number, nought where it is none.
444fn duration_of<T: XmlTree>(element: &T) -> i64 {
445    find_in(element, "duration")
446        .and_then(|(_, duration)| duration.text())
447        .and_then(|text| text.trim().parse().ok())
448        .unwrap_or(0)
449}
450
451/// music21's `moveMeasureContents`: the contents of `measure` moved into
452/// `other` behind a `<backup>` to the start, with voices numbered on from
453/// `other`'s, mid-measure clefs told their staff, and a barline replacing
454/// the one at the same end.
455///
456/// # Errors
457///
458/// Either tree no `<measure>`, and a voice that is no number.
459pub fn move_measure_contents<T: XmlTree>(measure: &T, other: &mut T, staff: usize) -> Result<()> {
460    if !tagged(measure, "measure") || !tagged(other, "measure") {
461        return Err(export_error(format!(
462            "moveMeasureContents() called on <{}> and <{}> (not measures).",
463            measure.tag().unwrap_or_default(),
464            other.tag().unwrap_or_default()
465        )));
466    }
467
468    // The voices `other` has, or a first one for each of its notes.
469    let mut max_voices: i64 = 0;
470    for (_, child) in elements_of(other) {
471        for (_, voice) in elements_of(&child)
472            .into_iter()
473            .filter(|(_, v)| tagged(v, "voice"))
474        {
475            if let Some(text) = voice.text() {
476                let number: i64 = text.parse().map_err(|_| {
477                    export_error(format!("invalid literal for int() with base 10: '{text}'"))
478                })?;
479                max_voices = max_voices.max(number);
480            }
481        }
482    }
483    let lacked_voice = max_voices == 0;
484    if lacked_voice {
485        for (index, note) in elements_of(other) {
486            if !tagged(&note, "note") {
487                continue;
488            }
489            let voice = with_text_of(&note, "voice", "1")?;
490            other
491                .with_child(index, |note| insert_before(note, voice, &BEFORE_VOICE))
492                .transpose()?;
493        }
494        max_voices = 1;
495    }
496
497    // Back to the start of the measure.
498    let mut backup: i64 = 0;
499    for (_, child) in elements_of(other) {
500        match child.tag().as_deref() {
501            Some("note") if find_in(&child, "chord").is_none() => backup += duration_of(&child),
502            Some("forward") => backup += duration_of(&child),
503            Some("backup") => backup -= duration_of(&child),
504            _ => {}
505        }
506    }
507    if backup != 0 {
508        let mut written = other.element("backup")?;
509        written.insert(0, with_text_of(other, "duration", &backup.to_string())?)?;
510        let end = other.len();
511        other.insert(end, written)?;
512    }
513
514    // What `measure` holds, moved over.
515    for (_, element) in elements_of(measure) {
516        let mut element = element.deep_copy()?;
517        match element.tag().as_deref() {
518            Some("print") => continue,
519            Some("attributes") => {
520                if find_in(&element, "divisions").is_some() {
521                    continue;
522                }
523                for (index, _) in elements_of(&element)
524                    .into_iter()
525                    .filter(|(_, child)| tagged(child, "clef"))
526                {
527                    element
528                        .with_child(index, |clef| {
529                            clef.set_attribute("number", &staff.to_string())
530                        })
531                        .transpose()?;
532                }
533            }
534            Some("barline") => {
535                let location = element.attribute("location");
536                let existing: Vec<usize> = elements_of(other)
537                    .into_iter()
538                    .filter(|(_, child)| {
539                        tagged(child, "barline") && child.attribute("location") == location
540                    })
541                    .map(|(index, _)| index)
542                    .collect();
543                for index in existing.into_iter().rev() {
544                    other.remove(index)?;
545                }
546            }
547            Some("note") => match find_in(&element, "voice") {
548                Some((index, voice)) => {
549                    if lacked_voice && let Some(text) = voice.text() {
550                        let number: i64 = text.parse().unwrap_or(0);
551                        element
552                            .with_child(index, |voice| voice.set_text(&(number + 1).to_string()))
553                            .transpose()?;
554                    }
555                }
556                None => {
557                    let voice = with_text_of(&element, "voice", &(max_voices + 1).to_string())?;
558                    insert_before(&mut element, voice, &BEFORE_VOICE)?;
559                }
560            },
561            _ => {}
562        }
563        let end = other.len();
564        other.insert(end, element)?;
565    }
566    Ok(())
567}
568
569/// The index of the first `<attributes>` of any measure of a part, where
570/// ElementTree's `find('measure/attributes')` finds it: the measure's
571/// index and the attributes' index in it.
572fn first_attributes<T: XmlTree>(part: &T) -> Option<(usize, usize)> {
573    elements_of(part)
574        .into_iter()
575        .filter(|(_, child)| tagged(child, "measure"))
576        .find_map(|(index, measure)| find_in(&measure, "attributes").map(|(at, _)| (index, at)))
577}
578
579/// The first child of a tag inside the first `<attributes>` that has one:
580/// `find('measure/attributes/<tag>')`.
581fn first_in_attributes<T: XmlTree>(part: &T, tag: &str) -> Option<T> {
582    elements_of(part)
583        .into_iter()
584        .filter(|(_, child)| tagged(child, "measure"))
585        .flat_map(|(_, measure)| elements_of(&measure))
586        .filter(|(_, child)| tagged(child, "attributes"))
587        .find_map(|(_, attributes)| find_in(&attributes, tag).map(|(_, found)| found))
588}
589
590/// The tags `<staves>` goes before in `<attributes>`.
591const BEFORE_STAVES: [&str; 7] = [
592    "part-symbol",
593    "instruments",
594    "clef",
595    "staff-details",
596    "transpose",
597    "directive",
598    "measure-style",
599];
600
601/// music21's `setEarliestAttributesAndClefsPartStaff`: the first staff's
602/// first `<attributes>` told how many staves there are, given a clef for
603/// each, and, where they differ across the staves, a key and a meter for
604/// each.
605///
606/// # Errors
607///
608/// More clefs than staves.
609pub fn set_earliest_attributes_and_clefs<T: XmlTree>(
610    parts: &mut [T],
611    differences: StaffDifferences,
612) -> Result<()> {
613    let Some((target, sources)) = parts.split_first_mut() else {
614        return Ok(());
615    };
616    let Some((measure, at)) = first_attributes(target) else {
617        return Ok(());
618    };
619    let staves = sources.len() + 1;
620    target
621        .with_child(measure, |measure| {
622            measure
623                .with_child(at, |attributes| {
624                    earliest_attributes(attributes, sources, staves, differences)
625                })
626                .transpose()
627        })
628        .transpose()?;
629    Ok(())
630}
631
632/// [`set_earliest_attributes_and_clefs`] on the first `<attributes>`.
633fn earliest_attributes<T: XmlTree>(
634    attributes: &mut T,
635    sources: &[T],
636    staves: usize,
637    differences: StaffDifferences,
638) -> Result<()> {
639    let multi_key = differences.keys == Across::Different;
640    let multi_meter = differences.meters == Across::Different;
641    let number_first = |attributes: &mut T, tag: &str| -> Result<()> {
642        if let Some((index, _)) = find_in(attributes, tag) {
643            attributes
644                .with_child(index, |found| found.set_attribute("number", "1"))
645                .transpose()?;
646        }
647        Ok(())
648    };
649    number_first(attributes, "clef")?;
650    let count = with_text_of(attributes, "staves", &staves.to_string())?;
651    insert_before(attributes, count, &BEFORE_STAVES)?;
652    if multi_key {
653        number_first(attributes, "key")?;
654    }
655    if multi_meter {
656        number_first(attributes, "time")?;
657    }
658
659    for (index, source) in sources.iter().enumerate() {
660        let staff = index + 2;
661        if let Some(old_clef) = first_in_attributes(source, "clef") {
662            let clefs = elements_of(attributes)
663                .into_iter()
664                .filter(|(_, child)| tagged(child, "clef"))
665                .count();
666            if clefs >= staff {
667                return Err(export_error("Attempted to add more clefs than staffs"));
668            }
669            let mut clef = attributes.element("clef")?;
670            clef.set_attribute("number", &staff.to_string())?;
671            let sign = find_in(&old_clef, "sign").and_then(|(_, sign)| sign.text());
672            let mut written = attributes.element("sign")?;
673            if let Some(sign) = sign {
674                written.set_text(&sign)?;
675            }
676            clef.insert(0, written)?;
677            let line = find_in(&old_clef, "line")
678                .and_then(|(_, line)| line.text())
679                .unwrap_or_default();
680            clef.insert(1, with_text_of(attributes, "line", &line)?)?;
681            if let Some((_, change)) = find_in(&old_clef, "clef-octave-change") {
682                clef.insert(2, change.deep_copy()?)?;
683            }
684            insert_before(
685                attributes,
686                clef,
687                &["staff-details", "transpose", "directive", "measure-style"],
688            )?;
689        }
690        if multi_meter && let Some(old_meter) = first_in_attributes(source, "time") {
691            let mut meter = old_meter.deep_copy()?;
692            meter.set_attribute("number", &staff.to_string())?;
693            insert_before(attributes, meter, &["staves"])?;
694        }
695        if multi_key && let Some(old_key) = first_in_attributes(source, "key") {
696            let mut key = old_key.deep_copy()?;
697            key.set_attribute("number", &staff.to_string())?;
698            insert_before(attributes, key, &["time", "staves"])?;
699        }
700    }
701    Ok(())
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    #[test]
709    fn measure_numbers_order_by_number_then_suffix() {
710        assert!(measure_number_comes_before("23", "24"));
711        assert!(!measure_number_comes_before("23", "23"));
712        assert!(measure_number_comes_before("23", "23a"));
713        assert!(measure_number_comes_before("23a", "23b"));
714        assert!(!measure_number_comes_before("23b", "23a"));
715        assert!(measure_number_comes_before("23b", "24a"));
716    }
717
718    #[test]
719    fn a_staff_tag_goes_before_beams_and_notations() {
720        let mut part = Element::new("part");
721        let measure = part.sub("measure");
722        measure.set("number", "1");
723        let note = measure.sub("note");
724        note.sub_text("duration", "8");
725        note.sub_text("beam", "begin");
726        add_staff_tags_to_staves(std::slice::from_mut(&mut part)).unwrap();
727        assert_eq!(
728            part.dump(),
729            "<part>\n  <measure number=\"1\">\n    <note>\n      <duration>8</duration>\n      \
730             <staff>1</staff>\n      <beam>begin</beam>\n    </note>\n  </measure>\n</part>"
731        );
732        let error = add_staff_tags_to_staves(std::slice::from_mut(&mut part)).unwrap_err();
733        assert!(
734            error
735                .to_string()
736                .contains("In part (), measure (1): Attempted to create a second <staff> tag"),
737            "{error}"
738        );
739    }
740
741    #[test]
742    fn moving_a_measure_numbers_its_voices_on() {
743        let mut measure = Element::new("measure");
744        measure.sub("note");
745        let mut other = Element::new("measure");
746        other.sub("note");
747        move_measure_contents(&measure, &mut other, 2).unwrap();
748        assert_eq!(
749            other.dump(),
750            "<measure>\n  <note>\n    <voice>1</voice>\n  </note>\n  <note>\n    \
751             <voice>2</voice>\n  </note>\n</measure>"
752        );
753    }
754}