Skip to main content

music21/
spanner.rs

1//! Spanners: marks that join several notes, music21's `spanner` module.
2//!
3//! music21 keeps a spanner as an object holding the very notes it joins. A
4//! stream here owns what it holds, so a spanner names its notes by where they
5//! stand instead: by their positions in [`Stream::leaves`] of the stream the
6//! spanner belongs to, first to last.
7//!
8//! [`Stream::leaves`]: crate::Stream::leaves
9
10use crate::defaults::FloatType;
11use crate::display::Drawn;
12use crate::notation::Placement;
13
14/// Which of music21's spanner classes a spanner is.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17#[non_exhaustive]
18pub enum SpannerKind {
19    /// A curve joining notes played in one breath or bow: music21's `Slur`.
20    Slur,
21    /// A hairpin opening out, growing louder: music21's `Crescendo`.
22    Crescendo,
23    /// A hairpin closing, growing softer: music21's `Diminuendo`.
24    Diminuendo,
25    /// An octave line, `8va` or `15mb`: music21's `Ottava`.
26    Ottava,
27    /// A bracket or line over notes, as a *ligatura* or a passage to be
28    /// played together: music21's `Line`.
29    Line,
30    /// How long a pedal is held: music21's `PedalMark`.
31    PedalMark,
32    /// The wavy line carrying a trill on past its note: music21's
33    /// `TrillExtension`.
34    TrillExtension,
35    /// One arpeggio across several chords, as across both hands' staves:
36    /// music21's `ArpeggioMarkSpanner`.
37    ArpeggioMark,
38    /// A glissando or a slide from one note to the next: music21's
39    /// `Glissando`.
40    Glissando,
41    /// A tremolo alternating between two notes: music21's `TremoloSpanner`.
42    TremoloSpanner,
43    /// Notes sung to one syllable as one figure, as chant writes them:
44    /// music21's volpiano `Neume`.
45    Neume,
46    /// Rests of several measures drawn as one: music21's
47    /// `MultiMeasureRest`.
48    MultiMeasureRest,
49    /// The measures of an alternative ending, a first or second time bar:
50    /// music21's `RepeatBracket`. A measure read or written keeps its
51    /// ending as a `bar::Ending`; this is the bracket built by hand.
52    RepeatBracket,
53}
54
55impl SpannerKind {
56    /// music21's class name for the kind.
57    pub fn class_name(self) -> &'static str {
58        match self {
59            Self::Slur => "Slur",
60            Self::Crescendo => "Crescendo",
61            Self::Diminuendo => "Diminuendo",
62            Self::Ottava => "Ottava",
63            Self::Line => "Line",
64            Self::PedalMark => "PedalMark",
65            Self::ArpeggioMark => "ArpeggioMarkSpanner",
66            Self::TrillExtension => "TrillExtension",
67            Self::Glissando => "Glissando",
68            Self::TremoloSpanner => "TremoloSpanner",
69            Self::Neume => "Neume",
70            Self::MultiMeasureRest => "MultiMeasureRest",
71            Self::RepeatBracket => "RepeatBracket",
72        }
73    }
74
75    /// Every kind, in the order music21 lists their classes.
76    pub const ALL: [Self; 13] = [
77        Self::Slur,
78        Self::Crescendo,
79        Self::Diminuendo,
80        Self::Ottava,
81        Self::Line,
82        Self::PedalMark,
83        Self::TrillExtension,
84        Self::ArpeggioMark,
85        Self::Glissando,
86        Self::TremoloSpanner,
87        Self::Neume,
88        Self::MultiMeasureRest,
89        Self::RepeatBracket,
90    ];
91
92    /// The kind music21's class of this name is, where it is one.
93    pub fn from_class_name(name: &str) -> Option<Self> {
94        Self::ALL.into_iter().find(|kind| kind.class_name() == name)
95    }
96
97    /// The class spanners of this kind are counted with where music21 numbers
98    /// them for a score: a crescendo and a diminuendo are both hairpins,
99    /// `DynamicWedge`, and share their numbers.
100    pub fn numbering_class(self) -> &'static str {
101        match self {
102            Self::Crescendo | Self::Diminuendo => "DynamicWedge",
103            other => other.class_name(),
104        }
105    }
106
107    /// Whether this is a hairpin: music21's `DynamicWedge`.
108    pub fn is_wedge(self) -> bool {
109        matches!(self, Self::Crescendo | Self::Diminuendo)
110    }
111}
112
113/// A mark joining several notes: music21's `Spanner`.
114#[derive(Clone, Debug, PartialEq, Eq)]
115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
116#[must_use]
117pub struct Spanner {
118    kind: SpannerKind,
119    /// Each element joined, by position, or nothing for one that stands in
120    /// no stream at all -- which music21 allows, and still counts.
121    spanned: Vec<Option<usize>>,
122    #[cfg_attr(feature = "serde", serde(default))]
123    placement: Drawn<Option<Placement>>,
124    #[cfg_attr(feature = "serde", serde(default))]
125    line_type: Drawn<Option<String>>,
126    #[cfg_attr(feature = "serde", serde(default))]
127    spread: Drawn<Option<FloatType>>,
128    #[cfg_attr(feature = "serde", serde(default))]
129    shift: Option<OctaveShift>,
130    #[cfg_attr(feature = "serde", serde(default))]
131    ends: Drawn<LineEnds>,
132    #[cfg_attr(feature = "serde", serde(default))]
133    pedal: Option<Pedal>,
134    #[cfg_attr(feature = "serde", serde(default))]
135    arpeggio: crate::expressions::ArpeggioType,
136    #[cfg_attr(feature = "serde", serde(default))]
137    glissando: Option<Glissando>,
138    #[cfg_attr(feature = "serde", serde(default))]
139    marks: Option<u8>,
140    #[cfg_attr(feature = "serde", serde(default))]
141    offset: Drawn<FloatType>,
142    #[cfg_attr(feature = "serde", serde(default))]
143    multi_rest: Option<MultiRest>,
144    /// The number a score tells it from others of its kind by: music21's
145    /// `idLocal`, MusicXML's `number`.
146    #[cfg_attr(feature = "serde", serde(default))]
147    id_local: Drawn<Option<String>>,
148    /// Whether the reader that made it saw it to its end: music21's
149    /// `completeStatus`, which only some of its readers set.
150    #[cfg_attr(feature = "serde", serde(default))]
151    complete: Drawn<bool>,
152    /// Whether the reader put it in the score itself rather than in the
153    /// part holding what it joins, as music21's MEI reader does.
154    #[cfg_attr(feature = "serde", serde(default))]
155    in_score: Drawn<bool>,
156    /// What it joins that no stream holds, each by its place among what it
157    /// joins: an ABC slur over a grace note holds the note music21 made
158    /// before copying it as a grace.
159    #[cfg_attr(feature = "serde", serde(default))]
160    unplaced: Drawn<Vec<(usize, crate::stream::StreamElement)>>,
161}
162
163/// How a rest of several measures is drawn and counted: music21's
164/// `MultiMeasureRest.useSymbols`, `maxSymbols` and `numRests`.
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
167pub struct MultiRest {
168    /// Whether it is drawn with rest symbols, a breve or a long, rather
169    /// than a bar with a number over it.
170    pub use_symbols: bool,
171    /// How many measures at most are drawn with symbols.
172    pub max_symbols: u32,
173    /// How many measures it is said to last where that is not how many
174    /// rests it joins.
175    pub count: Option<usize>,
176}
177
178impl Default for MultiRest {
179    /// music21's defaults: symbols, up to eleven of them.
180    fn default() -> Self {
181        Self {
182            use_symbols: true,
183            max_symbols: 11,
184            count: None,
185        }
186    }
187}
188
189/// How a glissando is played: music21's `Glissando.slideType`.
190#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
191#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
192pub enum SlideType {
193    /// Through every semitone between, which is how music21's starts out.
194    #[default]
195    Chromatic,
196    /// With no steps at all, a slide or a smear.
197    Continuous,
198    /// Through the notes of the scale, as a harp plays one.
199    Diatonic,
200    /// Over the white keys.
201    White,
202    /// Over the black keys.
203    Black,
204}
205
206impl SlideType {
207    /// music21's name for it: `chromatic`, `continuous`, `diatonic`,
208    /// `white` or `black`.
209    pub fn as_str(self) -> &'static str {
210        match self {
211            Self::Chromatic => "chromatic",
212            Self::Continuous => "continuous",
213            Self::Diatonic => "diatonic",
214            Self::White => "white",
215            Self::Black => "black",
216        }
217    }
218
219    /// Reads music21's name for a slide, whatever its case.
220    ///
221    /// # Errors
222    ///
223    /// A name that is none of the five, as music21's `SpannerException`.
224    pub fn from_name(name: &str) -> crate::error::Result<Self> {
225        let lower = name.to_lowercase();
226        [
227            Self::Chromatic,
228            Self::Continuous,
229            Self::Diatonic,
230            Self::White,
231            Self::Black,
232        ]
233        .into_iter()
234        .find(|kind| kind.as_str() == lower)
235        .ok_or_else(|| crate::error::Error::Value(format!("not a valid value: {name}")))
236    }
237}
238
239/// What a glissando says beside the notes it joins: how it is played and
240/// the words written along it, music21's `slideType` and `label`.
241#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
242#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
243pub struct Glissando {
244    /// How it is played.
245    pub slide_type: SlideType,
246    /// The words along the line, *gliss.*, where it has any.
247    pub label: Option<String>,
248}
249
250/// Which of music21's pedal objects a [`PedalObject`] is.
251#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
252#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
253pub enum PedalObjectKind {
254    /// The pedal let up and put down again at once: music21's
255    /// `PedalBounce`.
256    Bounce,
257    /// Where the pedal line stops being drawn while the pedalling goes on,
258    /// usually beside *simile*: music21's `PedalGapStart`.
259    GapStart,
260    /// Where the pedal line is drawn again: music21's `PedalGapEnd`.
261    GapEnd,
262}
263
264impl PedalObjectKind {
265    /// music21's class name for it.
266    pub fn class_name(self) -> &'static str {
267        match self {
268            Self::Bounce => "PedalBounce",
269            Self::GapStart => "PedalGapStart",
270            Self::GapEnd => "PedalGapEnd",
271        }
272    }
273
274    /// Reads music21's class name for one.
275    pub fn from_class_name(name: &str) -> Option<Self> {
276        [Self::Bounce, Self::GapStart, Self::GapEnd]
277            .into_iter()
278            .find(|kind| kind.class_name() == name)
279    }
280}
281
282/// A moment inside a held pedal -- a bounce, or a gap in its line -- which
283/// stands in the stream at its own offset and is joined by the pedal mark
284/// it belongs to: music21's `PedalObject`.
285#[derive(Clone, Debug, PartialEq, Eq, Hash)]
286#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
287#[must_use]
288pub struct PedalObject {
289    kind: PedalObjectKind,
290    #[cfg_attr(feature = "serde", serde(default))]
291    placement: Drawn<Option<Placement>>,
292}
293
294impl PedalObject {
295    /// A pedal object of a kind.
296    pub fn new(kind: PedalObjectKind) -> Self {
297        Self {
298            kind,
299            placement: Drawn(None),
300        }
301    }
302
303    /// Which kind it is.
304    pub fn kind(&self) -> PedalObjectKind {
305        self.kind
306    }
307
308    /// Which side of the staff it is drawn on, where the score says.
309    pub fn placement(&self) -> Option<Placement> {
310        self.placement.0
311    }
312
313    /// Says which side of the staff it is drawn on.
314    pub fn set_placement(&mut self, placement: Option<Placement>) {
315        self.placement.0 = placement;
316    }
317}
318
319/// How a line's ends are drawn: music21's `startTick`, `endTick`,
320/// `startHeight` and `endHeight`.
321#[derive(Clone, Copy, Debug, PartialEq, Default)]
322#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
323pub struct LineEnds {
324    /// The tick at the start.
325    pub start: LineEnd,
326    /// The tick at the end.
327    pub end: LineEnd,
328    /// How long the tick at the start is, in tenths of a staff space.
329    pub start_height: Option<FloatType>,
330    /// How long the tick at the end is, in tenths of a staff space.
331    pub end_height: Option<FloatType>,
332}
333
334/// The tick at one end of a line.
335#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
336#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
337pub enum LineEnd {
338    /// A tick up.
339    Up,
340    /// A tick down, which is how music21's lines start out.
341    #[default]
342    Down,
343    /// An arrowhead.
344    Arrow,
345    /// A tick both ways.
346    Both,
347    /// No tick at all.
348    None,
349}
350
351impl LineEnd {
352    /// music21's name for it, which is MusicXML's too: `up`, `down`,
353    /// `arrow`, `both` or `none`.
354    pub fn as_str(self) -> &'static str {
355        match self {
356            Self::Up => "up",
357            Self::Down => "down",
358            Self::Arrow => "arrow",
359            Self::Both => "both",
360            Self::None => "none",
361        }
362    }
363
364    /// Reads music21's name for a tick, whatever its case.
365    pub fn from_name(name: &str) -> crate::error::Result<Self> {
366        Ok(match name.to_lowercase().as_str() {
367            "up" => Self::Up,
368            "down" => Self::Down,
369            "arrow" => Self::Arrow,
370            "both" => Self::Both,
371            "none" => Self::None,
372            other => {
373                return Err(crate::error::Error::Value(format!(
374                    "not a valid value: {other}"
375                )));
376            }
377        })
378    }
379}
380
381/// Which pedal a pedal mark holds down: music21's `PedalType`.
382#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
383#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
384pub enum PedalType {
385    /// The sustaining pedal.
386    Sustain,
387    /// The sostenuto pedal, which holds only the notes already down.
388    Sostenuto,
389    /// The soft pedal.
390    Soft,
391    /// A practice piano's silent pedal.
392    Silent,
393}
394
395/// How a pedal mark is drawn: music21's `PedalForm`.
396#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
397#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
398pub enum PedalForm {
399    /// A bracket under the notes held.
400    Line,
401    /// *Ped.* where it goes down and a star where it comes up.
402    Symbol,
403    /// *Ped.* where it goes down and nothing where it comes up.
404    SymbolAlt,
405    /// *Ped.* where it goes down and a line from there.
406    SymbolLine,
407}
408
409/// A pedal mark's pedal and how it is drawn: music21's `pedalType`,
410/// `pedalForm` and `abbreviated`, the first two of which a score need not
411/// say.
412#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
413#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
414pub struct Pedal {
415    /// Which pedal is held.
416    pub pedal_type: Option<PedalType>,
417    /// How the mark is drawn.
418    pub form: Option<PedalForm>,
419    /// Whether the symbol is shortened, *P.* for *Ped.*
420    pub abbreviated: bool,
421}
422
423impl PedalType {
424    /// music21's name for it: `sustain`, `sostenuto`, `soft` or `silent`.
425    pub fn as_str(self) -> &'static str {
426        match self {
427            Self::Sustain => "sustain",
428            Self::Sostenuto => "sostenuto",
429            Self::Soft => "soft",
430            Self::Silent => "silent",
431        }
432    }
433
434    /// Reads music21's name for a pedal.
435    pub fn from_name(name: &str) -> Option<Self> {
436        [Self::Sustain, Self::Sostenuto, Self::Soft, Self::Silent]
437            .into_iter()
438            .find(|kind| kind.as_str() == name)
439    }
440}
441
442impl PedalForm {
443    /// music21's name for it: `line`, `symbol`, `symbolalt` or
444    /// `symbolline`.
445    pub fn as_str(self) -> &'static str {
446        match self {
447            Self::Line => "line",
448            Self::Symbol => "symbol",
449            Self::SymbolAlt => "symbolalt",
450            Self::SymbolLine => "symbolline",
451        }
452    }
453
454    /// Reads music21's name for a form.
455    pub fn from_name(name: &str) -> Option<Self> {
456        [Self::Line, Self::Symbol, Self::SymbolAlt, Self::SymbolLine]
457            .into_iter()
458            .find(|form| form.as_str() == name)
459    }
460
461    /// Whether a line is drawn from where the pedal goes down.
462    pub fn has_line(self) -> bool {
463        matches!(self, Self::Line | Self::SymbolLine)
464    }
465}
466
467/// How far and which way an octave line moves the notes under it:
468/// music21's `Ottava.type`.
469#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
470#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
471pub struct OctaveShift {
472    size: u8,
473    up: bool,
474    transposing: bool,
475}
476
477impl OctaveShift {
478    /// A shift by music21's name for it: `8va`, `8vb`, `15ma`, `15mb`,
479    /// `22da` or `22db`. `transposing` says whether the notes under it are
480    /// written where they sound, as music21's `transposing` says.
481    pub fn from_name(name: &str, transposing: bool) -> crate::error::Result<Self> {
482        let (size, up) = match name.to_lowercase().as_str() {
483            "8va" => (8, true),
484            "8vb" => (8, false),
485            "15ma" => (15, true),
486            "15mb" => (15, false),
487            "22da" => (22, true),
488            "22db" => (22, false),
489            other => {
490                return Err(crate::error::Error::Value(format!(
491                    "cannot create Ottava of type: {other}"
492                )));
493            }
494        };
495        Ok(Self {
496            size,
497            up,
498            transposing,
499        })
500    }
501
502    /// music21's name for the shift, `8va`.
503    pub fn name(&self) -> &'static str {
504        match (self.size, self.up) {
505            (8, true) => "8va",
506            (8, false) => "8vb",
507            (15, true) => "15ma",
508            (15, false) => "15mb",
509            (_, true) => "22da",
510            (_, false) => "22db",
511        }
512    }
513
514    /// 8, 15 or 22: music21's `shiftMagnitude`.
515    pub fn magnitude(&self) -> u8 {
516        self.size
517    }
518
519    /// Whether the notes sound higher than written: an `8va` does.
520    pub fn up(&self) -> bool {
521        self.up
522    }
523
524    /// Whether the notes under the line are written where they sound:
525    /// music21's `transposing`.
526    pub fn transposing(&self) -> bool {
527        self.transposing
528    }
529
530    /// Says whether the notes under the line are written where they sound.
531    /// This moves no notes; [`crate::Stream::to_sounding_pitch`] and
532    /// [`crate::Stream::to_written_pitch`] move them and say so.
533    pub fn set_transposing(&mut self, transposing: bool) {
534        self.transposing = transposing;
535    }
536
537    /// How far the notes under the line sound from where they are written,
538    /// one, two or three octaves up or down: music21's `interval()`.
539    pub fn interval(&self) -> crate::interval::Interval {
540        let name = if self.up {
541            format!("P{}", self.size)
542        } else {
543            format!("P-{}", self.size)
544        };
545        crate::interval::Interval::from_name(&name)
546            .expect("a perfect octave, fifteenth or twenty-second is an interval")
547    }
548}
549
550impl Spanner {
551    /// A spanner of a kind joining the elements at these positions.
552    ///
553    /// ```
554    /// use music21::{Spanner, SpannerKind};
555    ///
556    /// let line = Spanner::new(SpannerKind::Line, vec![2, 5]);
557    /// assert_eq!(line.len(), 2);
558    /// assert_eq!(line.spanned(), [Some(2), Some(5)]);
559    /// ```
560    pub fn new(kind: SpannerKind, spanned: Vec<usize>) -> Self {
561        Self::with_unplaced(kind, spanned.into_iter().map(Some).collect())
562    }
563
564    /// A spanner of a kind joining elements some of which stand nowhere: a
565    /// score read from a file may leave a spanner holding a note no stream
566    /// holds. It still counts that note among its own, so the ends and the
567    /// length are those of the whole list.
568    pub fn with_unplaced(kind: SpannerKind, spanned: Vec<Option<usize>>) -> Self {
569        Self {
570            kind,
571            spanned,
572            placement: Drawn(None),
573            line_type: Drawn(None),
574            spread: Drawn(None),
575            shift: None,
576            ends: Drawn(LineEnds::default()),
577            pedal: None,
578            arpeggio: crate::expressions::ArpeggioType::Normal,
579            glissando: None,
580            marks: None,
581            offset: Drawn(0.0),
582            multi_rest: None,
583            id_local: Drawn(None),
584            complete: Drawn(false),
585            in_score: Drawn(false),
586            unplaced: Drawn(Vec::new()),
587        }
588    }
589
590    /// One rest of several measures over the rests at these positions,
591    /// drawn with symbols as music21's starts out.
592    pub fn multi_measure_rest(spanned: Vec<usize>) -> Self {
593        let mut rest = Self::new(SpannerKind::MultiMeasureRest, spanned);
594        rest.multi_rest = Some(MultiRest::default());
595        rest
596    }
597
598    /// How a rest of several measures is drawn and counted.
599    pub fn multi_rest(&self) -> Option<MultiRest> {
600        self.multi_rest
601    }
602
603    /// Says how a rest of several measures is drawn and counted.
604    pub fn set_multi_rest(&mut self, multi_rest: Option<MultiRest>) {
605        self.multi_rest = multi_rest;
606    }
607
608    /// How many measures a rest of several lasts: the count it was given,
609    /// or else how many rests it joins. music21's `numRests`.
610    pub fn num_rests(&self) -> usize {
611        self.multi_rest
612            .and_then(|rest| rest.count)
613            .unwrap_or(self.spanned.len())
614    }
615
616    /// A glissando over the elements at these positions, drawn as a wavy
617    /// line and played chromatically, as music21's starts out.
618    pub fn glissando(spanned: Vec<usize>) -> Self {
619        let mut glissando = Self::new(SpannerKind::Glissando, spanned);
620        glissando.line_type = Drawn(Some("wavy".to_string()));
621        glissando.glissando = Some(Glissando::default());
622        glissando
623    }
624
625    /// How a glissando is played and what is written along it.
626    pub fn glissando_details(&self) -> Option<&Glissando> {
627        self.glissando.as_ref()
628    }
629
630    /// Says how a glissando is played and what is written along it.
631    pub fn set_glissando_details(&mut self, glissando: Option<Glissando>) {
632        self.glissando = glissando;
633    }
634
635    /// A tremolo alternating between the elements at these positions, with
636    /// so many strokes through the stems.
637    ///
638    /// # Errors
639    ///
640    /// More than eight strokes, as music21's `TremoloException`.
641    pub fn tremolo(marks: u8, spanned: Vec<usize>) -> crate::error::Result<Self> {
642        let mut tremolo = Self::new(SpannerKind::TremoloSpanner, spanned);
643        tremolo.set_number_of_marks(Some(marks))?;
644        Ok(tremolo)
645    }
646
647    /// How many strokes a tremolo between notes is written with: music21's
648    /// `numberOfMarks`.
649    pub fn number_of_marks(&self) -> Option<u8> {
650        self.marks
651    }
652
653    /// Says how many strokes a tremolo between notes is written with.
654    ///
655    /// # Errors
656    ///
657    /// More than eight, as music21's `TremoloException`.
658    pub fn set_number_of_marks(&mut self, marks: Option<u8>) -> crate::error::Result<()> {
659        if marks.is_some_and(|marks| marks > 8) {
660            return Err(crate::error::Error::Value(
661                "Number of marks must be a number from 0 to 8".to_string(),
662            ));
663        }
664        self.marks = marks;
665        Ok(())
666    }
667
668    /// Where the spanner itself stands in the stream holding it: nought for
669    /// one a score is read with. A pedal mark drawn as a sign and a line
670    /// says where its line resumes by it.
671    pub fn offset(&self) -> FloatType {
672        self.offset.0
673    }
674
675    /// Says where the spanner itself stands in the stream holding it.
676    pub fn set_offset(&mut self, offset: FloatType) {
677        self.offset.0 = offset;
678    }
679
680    /// One arpeggio across the chords at these positions.
681    pub fn arpeggio_mark(arpeggio: crate::expressions::ArpeggioType, spanned: Vec<usize>) -> Self {
682        let mut mark = Self::new(SpannerKind::ArpeggioMark, spanned);
683        mark.arpeggio = arpeggio;
684        mark
685    }
686
687    /// Which way an arpeggio across several chords is spread.
688    pub fn arpeggio(&self) -> crate::expressions::ArpeggioType {
689        self.arpeggio
690    }
691
692    /// Says which way an arpeggio across several chords is spread.
693    pub fn set_arpeggio(&mut self, arpeggio: crate::expressions::ArpeggioType) {
694        self.arpeggio = arpeggio;
695    }
696
697    /// A line over the elements at these positions, solid with a tick down
698    /// at each end, as music21's starts out.
699    pub fn line(spanned: Vec<usize>) -> Self {
700        let mut line = Self::new(SpannerKind::Line, spanned);
701        line.line_type = Drawn(Some("solid".to_string()));
702        line
703    }
704
705    /// How a line's ends are drawn.
706    pub fn ends(&self) -> LineEnds {
707        self.ends.0
708    }
709
710    /// Says how a line's ends are drawn.
711    pub fn set_ends(&mut self, ends: LineEnds) {
712        self.ends.0 = ends;
713    }
714
715    /// A pedal held under the elements at these positions.
716    pub fn pedal_mark(pedal: Pedal, spanned: Vec<usize>) -> Self {
717        let mut mark = Self::new(SpannerKind::PedalMark, spanned);
718        mark.pedal = Some(pedal);
719        mark
720    }
721
722    /// Which pedal a pedal mark holds and how it is drawn.
723    pub fn pedal(&self) -> Option<Pedal> {
724        self.pedal
725    }
726
727    /// Says which pedal a pedal mark holds and how it is drawn.
728    pub fn set_pedal(&mut self, pedal: Option<Pedal>) {
729        self.pedal = pedal;
730    }
731
732    /// An octave line over the elements at these positions, drawn above them
733    /// as music21's starts out.
734    ///
735    /// ```
736    /// use music21::{OctaveShift, Spanner};
737    ///
738    /// let ottava = Spanner::ottava(OctaveShift::from_name("8va", true)?, vec![0, 1]);
739    /// let shift = ottava.shift().expect("an ottava shifts");
740    /// assert_eq!(shift.name(), "8va");
741    /// assert!(shift.up());
742    /// # Ok::<(), music21::Error>(())
743    /// ```
744    pub fn ottava(shift: OctaveShift, spanned: Vec<usize>) -> Self {
745        let mut ottava = Self::new(SpannerKind::Ottava, spanned);
746        ottava.placement = Drawn(Some(Placement::Above));
747        ottava.shift = Some(shift);
748        ottava
749    }
750
751    /// How far and which way an octave line moves its notes.
752    pub fn shift(&self) -> Option<OctaveShift> {
753        self.shift
754    }
755
756    /// Says how far and which way an octave line moves its notes.
757    pub fn set_shift(&mut self, shift: Option<OctaveShift>) {
758        self.shift = shift;
759    }
760
761    /// A slur over the elements at these positions.
762    ///
763    /// ```
764    /// use music21::{Note, Spanner, SpannerKind, Stream};
765    ///
766    /// let mut stream = Stream::new();
767    /// for name in ["C4", "D4", "E4"] {
768    ///     stream.push(Note::from_name(name)?);
769    /// }
770    /// // The slur names its notes by their places in `Stream::leaves`.
771    /// stream.add_spanner(Spanner::slur(vec![0, 1, 2]));
772    /// let slur = &stream.spanners()[0];
773    /// assert_eq!(slur.kind(), SpannerKind::Slur);
774    /// assert!(slur.is_first(0) && slur.is_last(2));
775    /// # Ok::<(), music21::Error>(())
776    /// ```
777    pub fn slur(spanned: Vec<usize>) -> Self {
778        Self::new(SpannerKind::Slur, spanned)
779    }
780
781    /// A hairpin over the elements at these positions, drawn below them and
782    /// opening fifteen tenths wide, as music21's starts out.
783    ///
784    /// ```
785    /// use music21::{Spanner, SpannerKind};
786    ///
787    /// let hairpin = Spanner::wedge(SpannerKind::Crescendo, vec![0, 3]);
788    /// assert!(hairpin.kind().is_wedge());
789    /// assert_eq!(hairpin.kind().class_name(), "Crescendo");
790    /// ```
791    pub fn wedge(kind: SpannerKind, spanned: Vec<usize>) -> Self {
792        let mut wedge = Self::new(kind, spanned);
793        wedge.placement = Drawn(Some(Placement::Below));
794        wedge.spread = Drawn(Some(15.0));
795        wedge
796    }
797
798    /// How wide a hairpin opens, in tenths of a staff space: music21's
799    /// `spread`.
800    pub fn spread(&self) -> Option<FloatType> {
801        self.spread.0
802    }
803
804    /// Says how wide a hairpin opens.
805    pub fn set_spread(&mut self, spread: Option<FloatType>) {
806        self.spread.0 = spread;
807    }
808
809    /// Which kind of spanner this is.
810    pub fn kind(&self) -> SpannerKind {
811        self.kind
812    }
813
814    /// The positions of the elements it joins, first to last, nothing for
815    /// one that stands in no stream.
816    ///
817    /// ```
818    /// use music21::Spanner;
819    ///
820    /// let slur = Spanner::slur(vec![4, 5, 6]);
821    /// assert_eq!(slur.spanned(), [Some(4), Some(5), Some(6)]);
822    /// ```
823    pub fn spanned(&self) -> &[Option<usize>] {
824        &self.spanned
825    }
826
827    /// The positions of the elements it joins, to be moved where an edit
828    /// has moved them.
829    pub(crate) fn spanned_mut(&mut self) -> &mut Vec<Option<usize>> {
830        &mut self.spanned
831    }
832
833    /// Moves each place it names to where `moved` says that element now
834    /// stands, indexed by the old place: nothing for one no longer held.
835    pub(crate) fn move_places(&mut self, moved: &[Option<usize>]) {
836        for place in &mut self.spanned {
837            *place = place.and_then(|old| moved.get(old).copied().flatten());
838        }
839    }
840
841    /// Joins an element once where moving its places has made it join one
842    /// twice, keeping the first.
843    pub(crate) fn drop_repeated_places(&mut self) {
844        let mut seen: Vec<usize> = Vec::new();
845        self.spanned.retain(|place| match place {
846            Some(place) if seen.contains(place) => false,
847            Some(place) => {
848                seen.push(*place);
849                true
850            }
851            None => true,
852        });
853    }
854
855    /// How many elements it joins, those standing nowhere included.
856    pub fn len(&self) -> usize {
857        self.spanned.len()
858    }
859
860    /// Whether it joins nothing at all.
861    pub fn is_empty(&self) -> bool {
862        self.spanned.is_empty()
863    }
864
865    /// Whether the element at a position is the first it joins: music21's
866    /// `isFirst`.
867    pub fn is_first(&self, position: usize) -> bool {
868        self.spanned.first() == Some(&Some(position))
869    }
870
871    /// Whether the element at a position is the last it joins: music21's
872    /// `isLast`.
873    pub fn is_last(&self, position: usize) -> bool {
874        self.spanned.last() == Some(&Some(position))
875    }
876
877    /// Whether the element at a position is among those it joins:
878    /// music21's `hasSpannedElement`.
879    pub fn has_spanned_element(&self, position: usize) -> bool {
880        self.spanned.contains(&Some(position))
881    }
882
883    /// Joins the elements at these positions too, after those it joins
884    /// already, in the order given: music21's `addSpannedElements`, which
885    /// joins an element once however often it is added.
886    ///
887    /// ```
888    /// use music21::Spanner;
889    ///
890    /// let mut slur = Spanner::slur(vec![1]);
891    /// slur.add_spanned_elements([2, 3, 1]);
892    /// assert_eq!(slur.spanned(), [Some(1), Some(2), Some(3)]);
893    /// ```
894    pub fn add_spanned_elements(&mut self, positions: impl IntoIterator<Item = usize>) {
895        for position in positions {
896            if !self.has_spanned_element(position) {
897                self.spanned.push(Some(position));
898            }
899        }
900    }
901
902    /// Joins the element at a position first, before the rest: music21's
903    /// `insertFirstSpannedElement`. One it joins already stays where it
904    /// is.
905    pub fn insert_first_spanned_element(&mut self, position: usize) {
906        if !self.has_spanned_element(position) {
907            self.spanned.insert(0, Some(position));
908        }
909    }
910
911    /// Joins the element at `new` where it joined the one at `old`:
912    /// music21's `replaceSpannedElement`. Where it joins `new` already it
913    /// just lets `old` go, and where it does not join `old` nothing
914    /// changes.
915    ///
916    /// ```
917    /// use music21::Spanner;
918    ///
919    /// let mut slur = Spanner::slur(vec![1, 2, 3]);
920    /// slur.replace_spanned_element(3, 4);
921    /// assert_eq!(slur.spanned(), [Some(1), Some(2), Some(4)]);
922    /// ```
923    pub fn replace_spanned_element(&mut self, old: usize, new: usize) {
924        if self.has_spanned_element(new) {
925            self.spanned.retain(|place| *place != Some(old));
926            return;
927        }
928        for place in &mut self.spanned {
929            if *place == Some(old) {
930                *place = Some(new);
931            }
932        }
933    }
934
935    /// Which side of the notes it is drawn on, where the score says.
936    pub fn placement(&self) -> Option<Placement> {
937        self.placement.0
938    }
939
940    /// Says which side of the notes it is drawn on.
941    pub fn set_placement(&mut self, placement: Option<Placement>) {
942        self.placement.0 = placement;
943    }
944
945    /// The number a score tells it from others of its kind by: music21's
946    /// `idLocal`.
947    pub fn id_local(&self) -> Option<&str> {
948        self.id_local.0.as_deref()
949    }
950
951    /// Sets the number it is told apart by, or clears it.
952    pub fn set_id_local(&mut self, id_local: Option<String>) {
953        self.id_local.0 = id_local;
954    }
955
956    /// What it joins that no stream holds, each by its place among what it
957    /// joins, where [`Spanner::spanned`] says nothing.
958    pub fn unplaced_elements(&self) -> &[(usize, crate::stream::StreamElement)] {
959        &self.unplaced.0
960    }
961
962    /// Says what it joins at `place` that no stream holds.
963    pub fn set_unplaced_element(&mut self, place: usize, element: crate::stream::StreamElement) {
964        self.unplaced.0.retain(|(held, _)| *held != place);
965        self.unplaced.0.push((place, element));
966        self.unplaced.0.sort_by_key(|(held, _)| *held);
967    }
968
969    /// Whether the reader put it in the score itself, after its last
970    /// measure, rather than in the part holding what it joins: music21's
971    /// MEI reader appends its slurs to the score.
972    pub fn stands_in_score(&self) -> bool {
973        self.in_score.0
974    }
975
976    /// Says whether it stands in the score itself.
977    pub fn set_stands_in_score(&mut self, in_score: bool) {
978        self.in_score.0 = in_score;
979    }
980
981    /// Whether the reader that made it saw it to its end: music21's
982    /// `completeStatus`.
983    pub fn complete(&self) -> bool {
984        self.complete.0
985    }
986
987    /// Says whether it was seen to its end.
988    pub fn set_complete(&mut self, complete: bool) {
989        self.complete.0 = complete;
990    }
991
992    /// How its line is drawn where that is not solid, `dashed` or `dotted`:
993    /// music21's `style.lineType`.
994    pub fn line_type(&self) -> Option<&str> {
995        self.line_type.0.as_deref()
996    }
997
998    /// Says how its line is drawn.
999    pub fn set_line_type(&mut self, line_type: Option<String>) {
1000        self.line_type.0 = line_type;
1001    }
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use super::*;
1007
1008    #[test]
1009    fn a_spanner_knows_its_ends() {
1010        let slur = Spanner::slur(vec![3, 4, 5]);
1011        assert!(slur.is_first(3));
1012        assert!(slur.is_last(5));
1013        assert!(!slur.is_first(4) && !slur.is_last(4));
1014        assert_eq!(slur.kind().class_name(), "Slur");
1015    }
1016
1017    #[test]
1018    fn an_element_is_joined_once_in_the_order_added() {
1019        // music21's own example: g, then f# and e, then d- and c.
1020        let mut line = Spanner::new(SpannerKind::Line, vec![]);
1021        line.add_spanned_elements([1]);
1022        line.add_spanned_elements([2, 3]);
1023        line.add_spanned_elements([4, 5, 2]);
1024        assert_eq!(
1025            line.spanned(),
1026            [Some(1), Some(2), Some(3), Some(4), Some(5)]
1027        );
1028        assert!(line.has_spanned_element(4));
1029        assert!(!line.has_spanned_element(6));
1030    }
1031
1032    #[test]
1033    fn an_element_inserted_first_goes_before_the_rest() {
1034        let mut line = Spanner::new(SpannerKind::Line, vec![2, 3, 4, 5]);
1035        line.insert_first_spanned_element(1);
1036        assert_eq!(
1037            line.spanned(),
1038            [Some(1), Some(2), Some(3), Some(4), Some(5)]
1039        );
1040        // One joined already is neither added again nor moved.
1041        line.insert_first_spanned_element(4);
1042        assert_eq!(
1043            line.spanned(),
1044            [Some(1), Some(2), Some(3), Some(4), Some(5)]
1045        );
1046
1047        let mut empty = Spanner::new(SpannerKind::Line, vec![]);
1048        empty.insert_first_spanned_element(7);
1049        assert_eq!(empty.spanned(), [Some(7)]);
1050    }
1051
1052    #[test]
1053    fn a_replaced_element_keeps_its_place() {
1054        let mut slur = Spanner::slur(vec![1, 2, 3]);
1055        slur.replace_spanned_element(1, 9);
1056        assert_eq!(slur.spanned(), [Some(9), Some(2), Some(3)]);
1057        // Nothing joined at the old place changes nothing.
1058        slur.replace_spanned_element(6, 7);
1059        assert_eq!(slur.spanned(), [Some(9), Some(2), Some(3)]);
1060        // A replacement it joins already lets the old one go.
1061        slur.replace_spanned_element(2, 3);
1062        assert_eq!(slur.spanned(), [Some(9), Some(3)]);
1063    }
1064
1065    #[test]
1066    fn a_multi_measure_rest_counts_its_rests() {
1067        let mut rest = Spanner::multi_measure_rest(vec![1, 2, 3]);
1068        assert_eq!(rest.num_rests(), 3);
1069        assert!(rest.multi_rest().is_some_and(|said| said.use_symbols));
1070
1071        rest.set_multi_rest(Some(MultiRest {
1072            count: Some(10),
1073            ..MultiRest::default()
1074        }));
1075        assert_eq!(rest.num_rests(), 10);
1076    }
1077}