1use crate::error::{Error, Result};
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub enum BarlineType {
15 #[default]
17 Regular,
18 Dotted,
20 Dashed,
22 Heavy,
24 Double,
26 Final,
28 HeavyLight,
30 HeavyHeavy,
32 Tick,
34 Short,
36 None,
38}
39
40impl BarlineType {
41 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
102pub enum RepeatDirection {
103 Start,
105 End,
107}
108
109impl RepeatDirection {
110 pub fn as_str(self) -> &'static str {
112 match self {
113 Self::Start => "start",
114 Self::End => "end",
115 }
116 }
117}
118
119#[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 pub fn new(bar_type: BarlineType) -> Self {
132 Self {
133 bar_type,
134 repeat: None,
135 }
136 }
137
138 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 pub fn bar_type(&self) -> BarlineType {
153 self.bar_type
154 }
155
156 pub fn set_bar_type(&mut self, bar_type: BarlineType) {
158 self.bar_type = bar_type;
159 }
160
161 pub fn repeat_direction(&self) -> Option<RepeatDirection> {
163 self.repeat.map(|(direction, _)| direction)
164 }
165
166 pub fn repeat_times(&self) -> Option<u32> {
168 self.repeat.and_then(|(_, times)| times)
169 }
170
171 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
212pub enum BracketPlace {
213 #[default]
215 PartStart,
216 LastMeasure,
219}
220
221impl Ending {
222 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 pub fn placed(mut self, place: BracketPlace) -> Self {
236 self.place = place;
237 self
238 }
239
240 pub fn place(&self) -> BracketPlace {
242 self.place
243 }
244
245 pub fn numbers(&self) -> &[u32] {
247 &self.numbers
248 }
249
250 pub fn starts(&self) -> bool {
252 self.starts
253 }
254
255 pub fn stops(&self) -> bool {
257 self.stops
258 }
259
260 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 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 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 #[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 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}