Skip to main content

music21/
bar.rs

1//! Barlines: music21's `bar` module.
2//!
3//! A measure has a barline at each end, and a repeat sign is a barline that
4//! also says which way the music repeats. music21 keeps them as the
5//! measure's `leftBarline` and `rightBarline`, which is where
6//! [`crate::Stream::left_barline`] and [`crate::Stream::right_barline`] keep
7//! them here.
8
9use crate::error::{Error, Result};
10
11/// How a barline is drawn: music21's `bar.barTypeList`.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub enum BarlineType {
15    /// A single thin line.
16    #[default]
17    Regular,
18    /// A dotted line.
19    Dotted,
20    /// A dashed line.
21    Dashed,
22    /// A single thick line.
23    Heavy,
24    /// Two thin lines.
25    Double,
26    /// A thin line and a thick one, which ends a piece.
27    Final,
28    /// A thick line and a thin one.
29    HeavyLight,
30    /// Two thick lines.
31    HeavyHeavy,
32    /// A short stroke through the top line.
33    Tick,
34    /// A line through the middle of the staff only.
35    Short,
36    /// No line at all.
37    None,
38}
39
40impl BarlineType {
41    /// Every type, in music21's order.
42    pub const ALL: [BarlineType; 11] = [
43        Self::Regular,
44        Self::Dotted,
45        Self::Dashed,
46        Self::Heavy,
47        Self::Double,
48        Self::Final,
49        Self::HeavyLight,
50        Self::HeavyHeavy,
51        Self::Tick,
52        Self::Short,
53        Self::None,
54    ];
55
56    /// music21's name for the type.
57    pub fn as_str(self) -> &'static str {
58        match self {
59            Self::Regular => "regular",
60            Self::Dotted => "dotted",
61            Self::Dashed => "dashed",
62            Self::Heavy => "heavy",
63            Self::Double => "double",
64            Self::Final => "final",
65            Self::HeavyLight => "heavy-light",
66            Self::HeavyHeavy => "heavy-heavy",
67            Self::Tick => "tick",
68            Self::Short => "short",
69            Self::None => "none",
70        }
71    }
72
73    /// Reads a type by music21's name or by the MusicXML name music21
74    /// allows for two of them: music21's `standardizeBarType`.
75    pub fn from_name(name: &str) -> Result<Self> {
76        let name = name.to_lowercase();
77        let name = match name.as_str() {
78            "light-light" => "double",
79            "light-heavy" => "final",
80            other => other,
81        };
82        Self::ALL
83            .into_iter()
84            .find(|candidate| candidate.as_str() == name)
85            .ok_or_else(|| Error::Value(format!("cannot process style: {name}")))
86    }
87
88    /// The name MusicXML draws it by: music21's `musicXMLBarStyle`, which
89    /// is the type's own name but for `double` and `final`.
90    pub fn musicxml_bar_style(self) -> &'static str {
91        match self {
92            Self::Double => "light-light",
93            Self::Final => "light-heavy",
94            other => other.as_str(),
95        }
96    }
97}
98
99/// Which way a repeat sign sends the music.
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
102pub enum RepeatDirection {
103    /// The passage to repeat starts here.
104    Start,
105    /// The passage to repeat ends here, and goes back.
106    End,
107}
108
109impl RepeatDirection {
110    /// music21's name for the direction.
111    pub fn as_str(self) -> &'static str {
112        match self {
113            Self::Start => "start",
114            Self::End => "end",
115        }
116    }
117}
118
119/// A barline: music21's `bar.Barline`, or its `bar.Repeat` where it is a
120/// repeat sign.
121#[derive(Clone, Debug, Default, PartialEq, Eq)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
123#[must_use]
124pub struct Barline {
125    bar_type: BarlineType,
126    repeat: Option<(RepeatDirection, Option<u32>)>,
127}
128
129impl Barline {
130    /// A plain barline of a type.
131    pub fn new(bar_type: BarlineType) -> Self {
132        Self {
133            bar_type,
134            repeat: None,
135        }
136    }
137
138    /// A repeat sign, drawn as music21 draws one: `heavy-light` where a
139    /// repeat starts and `final` where it ends. `times` is how many times the
140    /// passage is played, where the score says.
141    pub fn repeat(direction: RepeatDirection, times: Option<u32>) -> Self {
142        Self {
143            bar_type: match direction {
144                RepeatDirection::Start => BarlineType::HeavyLight,
145                RepeatDirection::End => BarlineType::Final,
146            },
147            repeat: Some((direction, times)),
148        }
149    }
150
151    /// How the barline is drawn.
152    pub fn bar_type(&self) -> BarlineType {
153        self.bar_type
154    }
155
156    /// Changes how the barline is drawn.
157    pub fn set_bar_type(&mut self, bar_type: BarlineType) {
158        self.bar_type = bar_type;
159    }
160
161    /// Which way the music repeats, where this is a repeat sign.
162    pub fn repeat_direction(&self) -> Option<RepeatDirection> {
163        self.repeat.map(|(direction, _)| direction)
164    }
165
166    /// How many times the passage is played, where a repeat sign says.
167    pub fn repeat_times(&self) -> Option<u32> {
168        self.repeat.and_then(|(_, times)| times)
169    }
170
171    /// The words a repeat's count is written as, for a caller that wants
172    /// them over the staff: music21's `Repeat.getTextExpression`, which
173    /// writes the times between a prefix and a postfix -- `3x` by
174    /// default.
175    ///
176    /// music21 writes the count whatever it is, so a repeat that says no
177    /// count is written `Nonex`; this answers nothing instead, there
178    /// being nothing to say.
179    pub fn repeat_text_expression(
180        &self,
181        prefix: &str,
182        postfix: &str,
183    ) -> Option<crate::expressions::TextExpression> {
184        let times = self.repeat_times()?;
185        Some(crate::expressions::TextExpression::new(format!(
186            "{prefix}{times}{postfix}"
187        )))
188    }
189}
190
191/// Where a measure stands in an alternative ending: music21's
192/// `RepeatBracket`, the bracket drawn over the measures played the first
193/// time through, or the second.
194///
195/// music21 keeps the bracket as a spanner over the measures; a measure here
196/// says which ending it is in and whether the bracket opens or closes on it.
197#[derive(Clone, Debug, PartialEq, Eq)]
198#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
199#[must_use]
200pub struct Ending {
201    numbers: Vec<u32>,
202    starts: bool,
203    stops: bool,
204    #[cfg_attr(feature = "serde", serde(default))]
205    place: BracketPlace,
206}
207
208/// Where in its part music21 puts the `RepeatBracket` over an ending,
209/// which differs by the reader that made it.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
212pub enum BracketPlace {
213    /// At the part's start, as its MusicXML reader puts it.
214    #[default]
215    PartStart,
216    /// Where the ending's last measure starts, as its NoteWorthy reader
217    /// appends it before that measure.
218    LastMeasure,
219}
220
221impl Ending {
222    /// An ending played the times numbered, opening on this measure where
223    /// `starts` and closing on it where `stops`. Nought as the only number
224    /// is an ending that gives none.
225    pub fn new(numbers: Vec<u32>, starts: bool, stops: bool) -> Self {
226        Self {
227            numbers,
228            starts,
229            stops,
230            place: BracketPlace::default(),
231        }
232    }
233
234    /// The same ending, its bracket put at `place` in the part.
235    pub fn placed(mut self, place: BracketPlace) -> Self {
236        self.place = place;
237        self
238    }
239
240    /// Where music21 puts the bracket over this ending in its part.
241    pub fn place(&self) -> BracketPlace {
242        self.place
243    }
244
245    /// The times through the ending is played: music21's `numberRange`.
246    pub fn numbers(&self) -> &[u32] {
247        &self.numbers
248    }
249
250    /// Whether the bracket opens on this measure.
251    pub fn starts(&self) -> bool {
252        self.starts
253    }
254
255    /// Whether the bracket closes on this measure.
256    pub fn stops(&self) -> bool {
257        self.stops
258    }
259
260    /// The times an ending is numbered for, read from text as music21's
261    /// `RepeatBracket.number` reads it: `1-3` a range, `1, 3` a list,
262    /// empty the ending that gives none (`[0]`).
263    ///
264    /// ```
265    /// use music21::bar::Ending;
266    ///
267    /// assert_eq!(Ending::numbers_from_text("1-3")?, vec![1, 2, 3]);
268    /// assert_eq!(Ending::numbers_from_text("2, 7")?, vec![2, 7]);
269    /// assert_eq!(Ending::numbers_from_text("")?, vec![0]);
270    /// assert!(Ending::numbers_from_text("x").is_err());
271    /// # Ok::<(), music21::Error>(())
272    /// ```
273    pub fn numbers_from_text(text: &str) -> Result<Vec<u32>> {
274        let refused = || {
275            Error::Value(format!(
276                "number for RepeatBracket must be a number, not {text:?}"
277            ))
278        };
279        let number = |piece: &str| piece.trim().parse::<u32>().map_err(|_| refused());
280        if text.is_empty() {
281            return Ok(vec![0]);
282        }
283        if let Some((low, high)) = text.split_once('-') {
284            return Ok((number(low)?..=number(high)?).collect());
285        }
286        if text.contains(',') {
287            return text.split(',').map(number).collect();
288        }
289        if !text.chars().all(|c| c.is_ascii_digit()) {
290            return Err(refused());
291        }
292        Ok(vec![number(text)?])
293    }
294
295    /// The times an ending is numbered for, written as music21's
296    /// `RepeatBracket.number` writes them: `1-3` for a run of three or
297    /// more, `2, 3` for two in a row or numbers with gaps, empty for none.
298    ///
299    /// ```
300    /// use music21::bar::Ending;
301    ///
302    /// assert_eq!(Ending::numbers_label(&[1, 2, 3]), "1-3");
303    /// assert_eq!(Ending::numbers_label(&[2, 3]), "2, 3");
304    /// assert_eq!(Ending::numbers_label(&[1, 2, 3, 7]), "1, 2, 3, 7");
305    /// assert_eq!(Ending::numbers_label(&[0]), "");
306    /// ```
307    pub fn numbers_label(numbers: &[u32]) -> String {
308        if let [only] = numbers {
309            return match only {
310                0 => String::new(),
311                number => number.to_string(),
312            };
313        }
314        let contiguous = numbers.windows(2).all(|pair| pair[1] == pair[0] + 1);
315        match (numbers.first(), numbers.last()) {
316            (Some(first), Some(last)) if contiguous && numbers.len() > 2 => {
317                format!("{first}-{last}")
318            }
319            _ => numbers
320                .iter()
321                .map(u32::to_string)
322                .collect::<Vec<_>>()
323                .join(", "),
324        }
325    }
326
327    /// The numbers as MusicXML writes them, `1,2`; an ending numbered
328    /// nought writes nothing.
329    pub fn number_text(&self) -> String {
330        let mut text = match self.numbers.first() {
331            Some(0) | None => String::new(),
332            Some(first) => first.to_string(),
333        };
334        for number in self.numbers.iter().skip(1) {
335            text.push(',');
336            text.push_str(&number.to_string());
337        }
338        text
339    }
340}
341
342#[cfg(test)]
343mod tests {
344
345    /// music21's own answers: `3x` by default, and what the prefix and
346    /// postfix make of it.
347    #[test]
348    fn a_repeats_count_is_written_as_music21_writes_it() {
349        let twice = Barline::repeat(RepeatDirection::End, Some(3));
350        let said = twice
351            .repeat_text_expression("", "x")
352            .expect("a count to write");
353        assert_eq!(said.content(), "3x");
354        let longer = twice
355            .repeat_text_expression("repeat ", " times")
356            .expect("a count to write");
357        assert_eq!(longer.content(), "repeat 3 times");
358        // A repeat that says no count has nothing to write.
359        assert!(
360            Barline::repeat(RepeatDirection::End, None)
361                .repeat_text_expression("", "x")
362                .is_none()
363        );
364    }
365    use super::*;
366
367    #[test]
368    fn two_types_have_musicxml_names_of_their_own() {
369        assert_eq!(BarlineType::Final.musicxml_bar_style(), "light-heavy");
370        assert_eq!(BarlineType::Double.musicxml_bar_style(), "light-light");
371        assert_eq!(BarlineType::Tick.musicxml_bar_style(), "tick");
372        assert_eq!(
373            BarlineType::from_name("light-heavy").unwrap(),
374            BarlineType::Final
375        );
376        assert_eq!(
377            BarlineType::from_name("Heavy-Light").unwrap(),
378            BarlineType::HeavyLight
379        );
380        assert!(BarlineType::from_name("wiggly").is_err());
381    }
382
383    #[test]
384    fn a_repeat_is_drawn_by_its_direction() {
385        let end = Barline::repeat(RepeatDirection::End, Some(3));
386        assert_eq!(end.bar_type(), BarlineType::Final);
387        assert_eq!(end.repeat_times(), Some(3));
388        let start = Barline::repeat(RepeatDirection::Start, None);
389        assert_eq!(start.bar_type(), BarlineType::HeavyLight);
390        assert_eq!(start.repeat_direction(), Some(RepeatDirection::Start));
391        assert_eq!(Barline::default().repeat_direction(), None);
392    }
393}