Skip to main content

music21/noteworthy/
placement.rs

1//! Where music21's NoteWorthy translator places notes, rests and marks in
2//! a measure, and how it joins slurs and ties: the one implementation,
3//! generic over what the measures are.
4//!
5//! The crate's reader places into measures of its own; the wheel's
6//! translator places into Python streams a caller may hand it. Both
7//! implement [`Placing`], and [`Placement`] keeps the state between lines:
8//! the position in the measure, the slurs left open and the ties begun.
9
10use crate::defaults::{FloatType, IntegerType};
11use crate::notation::TieType;
12
13/// What a measure of either kind does for the translator.
14pub trait Placing {
15    /// A measure, compared by identity.
16    type Measure;
17    /// A voice of a measure.
18    type Voice;
19    /// A note, chord or rest about to be placed.
20    type Element;
21    /// What a placed note is remembered by, for a slur to reach it.
22    type Handle;
23    /// What goes wrong.
24    type Error;
25
26    /// Another reference to the same measure.
27    fn copy_measure(&self, measure: &Self::Measure) -> Self::Measure;
28    /// Another reference to the same placed note.
29    fn copy_handle(&self, handle: &Self::Handle) -> Self::Handle;
30    /// Whether two measures are the same one.
31    fn same_measure(&self, first: &Self::Measure, second: &Self::Measure) -> bool;
32    /// Whether two placed notes are the same one.
33    fn same_handle(&self, first: &Self::Handle, second: &Self::Handle) -> bool;
34    /// What `element` will be remembered by.
35    fn handle(&self, element: &Self::Element) -> Result<Self::Handle, Self::Error>;
36    /// Where the last thing in the measure ends: music21's `highestTime`.
37    fn highest_time(&self, measure: &Self::Measure) -> Result<FloatType, Self::Error>;
38    /// How long an element lasts.
39    fn length(&self, element: &Self::Element) -> Result<FloatType, Self::Error>;
40    /// The measure's voices, in order.
41    fn voices(&self, measure: &Self::Measure) -> Result<Vec<Self::Voice>, Self::Error>;
42    /// Where the last thing in a voice ends.
43    fn voice_end(&self, voice: &Self::Voice) -> Result<FloatType, Self::Error>;
44    /// The notes, chords and rests the measure holds moved into a voice
45    /// numbered nought, each where it stood, and the voice put at the
46    /// start of the measure.
47    fn gather_voice(&mut self, measure: &Self::Measure) -> Result<Self::Voice, Self::Error>;
48    /// A new empty voice numbered `id` at the start of the measure.
49    fn new_voice(&mut self, measure: &Self::Measure, id: usize)
50    -> Result<Self::Voice, Self::Error>;
51    /// An element put in the measure at an offset.
52    fn insert(
53        &mut self,
54        measure: &Self::Measure,
55        offset: FloatType,
56        element: Self::Element,
57    ) -> Result<(), Self::Error>;
58    /// An element put in a voice at an offset.
59    fn insert_in(
60        &mut self,
61        voice: &Self::Voice,
62        offset: FloatType,
63        element: Self::Element,
64    ) -> Result<(), Self::Error>;
65    /// The ties of an element's notes, in order, set where given.
66    fn set_ties(
67        &mut self,
68        element: &mut Self::Element,
69        ties: &[Option<TieType>],
70    ) -> Result<(), Self::Error>;
71    /// A slur from one placed note to another, kept in the measure.
72    fn slur(
73        &mut self,
74        measure: &Self::Measure,
75        start: &Self::Handle,
76        end: &Self::Handle,
77    ) -> Result<(), Self::Error>;
78}
79
80/// A slur begun and not yet joined: where it starts, the measure it
81/// starts in, where that note ends and its place in its group.
82#[derive(Clone, Debug)]
83pub struct OpenSlur<M, H> {
84    /// The note it starts at.
85    pub start: H,
86    /// The measure that note is in.
87    pub measure: M,
88    /// Where that note ends.
89    pub end: FloatType,
90    /// Its place among the notes placed with it.
91    pub group: usize,
92}
93
94/// A tie begun on a staff step: the measure it was begun in, none where
95/// carried over a barline, and where the tied note ends.
96#[derive(Clone, Debug)]
97pub struct TiedStep<M> {
98    /// The staff step: a step and octave under the clef in force.
99    pub step: (char, IntegerType),
100    /// The measure, where not carried over a barline.
101    pub measure: Option<M>,
102    /// Where the tied note ends.
103    pub end: FloatType,
104}
105
106/// The translator's placing state: music21's `positionMeasure` and
107/// `measurePosition`, `openSlurs` and `tiedSteps`.
108#[derive(Clone, Debug)]
109pub struct Placement<M, H> {
110    /// The measure placed in last: music21's `positionMeasure`.
111    pub position_measure: Option<M>,
112    /// Where the next object goes in it: music21's `measurePosition`.
113    /// Read only while the measure placed in is `position_measure`.
114    pub measure_position: FloatType,
115    /// Slurs begun and not yet joined.
116    pub open_slurs: Vec<OpenSlur<M, H>>,
117    /// Ties begun.
118    pub tied_steps: Vec<TiedStep<M>>,
119}
120
121impl<M, H> Default for Placement<M, H> {
122    fn default() -> Self {
123        Self {
124            position_measure: None,
125            measure_position: 0.0,
126            open_slurs: Vec::new(),
127            tied_steps: Vec::new(),
128        }
129    }
130}
131
132impl<M, H> Placement<M, H> {
133    /// music21's `currentPosition`: the end of what the measure holds the
134    /// first time it is asked in a measure, then where the notes placed
135    /// last moved it on to.
136    ///
137    /// # Errors
138    ///
139    /// What the measure's `highest_time` raises.
140    pub fn position<T>(&mut self, music: &T, measure: &M) -> Result<FloatType, T::Error>
141    where
142        T: Placing<Measure = M, Handle = H>,
143    {
144        if let Some(placed) = &self.position_measure
145            && music.same_measure(placed, measure)
146        {
147            return Ok(self.measure_position);
148        }
149        self.measure_position = music.highest_time(measure)?;
150        self.position_measure = Some(music.copy_measure(measure));
151        Ok(self.measure_position)
152    }
153
154    /// music21's `insertAtPosition`: a mark where the next note goes.
155    ///
156    /// # Errors
157    ///
158    /// What placing it raises.
159    pub fn mark<T>(
160        &mut self,
161        music: &mut T,
162        measure: &M,
163        element: T::Element,
164    ) -> Result<(), T::Error>
165    where
166        T: Placing<Measure = M, Handle = H>,
167    {
168        let offset = self.position(music, measure)?;
169        music.insert(measure, offset, element)
170    }
171
172    /// music21's `setTieFromPitchInfo`: the ties of an element about to go
173    /// at the current position, from the staff step of each of its notes
174    /// and whether the note is tied on. A note is tied from one on the
175    /// same step that ends where it starts.
176    ///
177    /// # Errors
178    ///
179    /// What the measure or the element raises.
180    pub fn tie<T>(
181        &mut self,
182        music: &mut T,
183        measure: &M,
184        element: &mut T::Element,
185        steps: &[((char, IntegerType), bool)],
186    ) -> Result<(), T::Error>
187    where
188        T: Placing<Measure = M, Handle = H>,
189    {
190        let offset = self.position(music, measure)?;
191        let end = offset + music.length(element)?;
192        let mut ties = Vec::with_capacity(steps.len());
193        for (step, tied_on) in steps {
194            let mut tied_from = false;
195            if let Some(at) = self.tied_steps.iter().position(|tied| tied.step == *step) {
196                let tied = self.tied_steps.remove(at);
197                let here = tied
198                    .measure
199                    .as_ref()
200                    .is_none_or(|tied_measure| music.same_measure(tied_measure, measure));
201                tied_from = here && tied.end == offset;
202            }
203            ties.push(match (tied_from, *tied_on) {
204                (true, true) => Some(TieType::Continue),
205                (false, true) => Some(TieType::Start),
206                (true, false) => Some(TieType::Stop),
207                (false, false) => None,
208            });
209            if *tied_on {
210                self.tied_steps.push(TiedStep {
211                    step: *step,
212                    measure: Some(music.copy_measure(measure)),
213                    end,
214                });
215            }
216        }
217        music.set_ties(element, &ties)
218    }
219
220    /// music21's `appendSimultaneous`: notes, chords or rests, each with
221    /// whether it is slurred, starting together at the current position,
222    /// which then moves on by the shortest of them. Where several start
223    /// together, or the measure has voices, each goes in a voice free
224    /// there, the longest of them first, or a new one; the notes the
225    /// measure holds become its first voice where it has none.
226    ///
227    /// # Errors
228    ///
229    /// What the measure raises.
230    pub fn place<T>(
231        &mut self,
232        music: &mut T,
233        measure: &M,
234        elements: Vec<(T::Element, bool)>,
235    ) -> Result<(), T::Error>
236    where
237        T: Placing<Measure = M, Handle = H>,
238    {
239        let offset = self.position(music, measure)?;
240        let mut voices = music.voices(measure)?;
241        if voices.is_empty() && elements.len() > 1 {
242            voices.push(music.gather_voice(measure)?);
243        }
244
245        // The voices free here, the one ending latest first.
246        let mut free = Vec::new();
247        for (index, voice) in voices.iter().enumerate() {
248            let end = music.voice_end(voice)?;
249            if end <= offset {
250                free.push((end, index));
251            }
252        }
253        free.sort_by(|left, right| right.0.total_cmp(&left.0));
254        let mut free: std::collections::VecDeque<usize> =
255            free.into_iter().map(|(_, index)| index).collect();
256
257        let had_voices = !voices.is_empty();
258        let mut group = Vec::with_capacity(elements.len());
259        for (element, slurred) in elements {
260            group.push((music.handle(&element)?, slurred, music.length(&element)?));
261            if !had_voices {
262                music.insert(measure, offset, element)?;
263                continue;
264            }
265            let index = match free.pop_front() {
266                Some(index) => index,
267                None => {
268                    let id = voices.len();
269                    voices.push(music.new_voice(measure, id)?);
270                    id
271                }
272            };
273            music.insert_in(&voices[index], offset, element)?;
274        }
275
276        self.slurs(music, measure, &group)?;
277        let shortest = group
278            .iter()
279            .map(|(_, _, length)| *length)
280            .fold(FloatType::INFINITY, FloatType::min);
281        if shortest.is_finite() {
282            self.measure_position = offset + shortest;
283        }
284        Ok(())
285    }
286
287    /// music21's `setSlurs`, for notes just placed together at the current
288    /// position, each with whether it is slurred and how long it lasts: a
289    /// slurred note is slurred to the next note starting once it has
290    /// ended, the one in the same place in its group if there is one, else
291    /// the first slurred one, else the first. Slurred notes in a row make
292    /// one slur.
293    ///
294    /// # Errors
295    ///
296    /// What the measure raises.
297    pub fn slurs<T>(
298        &mut self,
299        music: &mut T,
300        measure: &M,
301        group: &[(H, bool, FloatType)],
302    ) -> Result<(), T::Error>
303    where
304        T: Placing<Measure = M, Handle = H>,
305    {
306        let offset = self.position(music, measure)?;
307        let ended: Vec<OpenSlur<M, H>> = self
308            .open_slurs
309            .iter()
310            .filter(|open| !music.same_measure(&open.measure, measure) || open.end <= offset)
311            .map(|open| OpenSlur {
312                start: music.copy_handle(&open.start),
313                measure: music.copy_measure(&open.measure),
314                end: open.end,
315                group: open.group,
316            })
317            .collect();
318        let first_slurred = group
319            .iter()
320            .position(|(_, slurred, _)| *slurred)
321            .unwrap_or(0);
322        for (index, (handle, slurred, length)) in group.iter().enumerate() {
323            let mut arriving: Vec<&OpenSlur<M, H>> = ended
324                .iter()
325                .filter(|open| {
326                    let lands = if open.group < group.len() {
327                        open.group
328                    } else {
329                        first_slurred
330                    };
331                    lands == index
332                })
333                .collect();
334            let end = offset + length;
335            if *slurred && !arriving.is_empty() {
336                let start = music.copy_handle(&arriving.remove(0).start);
337                self.forget(music, &start);
338                self.open_slurs.push(OpenSlur {
339                    start,
340                    measure: music.copy_measure(measure),
341                    end,
342                    group: index,
343                });
344            } else if *slurred {
345                self.open_slurs.push(OpenSlur {
346                    start: music.copy_handle(handle),
347                    measure: music.copy_measure(measure),
348                    end,
349                    group: index,
350                });
351            }
352            for open in arriving {
353                music.slur(measure, &open.start, handle)?;
354                self.forget(music, &open.start);
355            }
356        }
357        Ok(())
358    }
359
360    /// Every open slur begun at `start` dropped.
361    fn forget<T>(&mut self, music: &T, start: &H)
362    where
363        T: Placing<Measure = M, Handle = H>,
364    {
365        self.open_slurs
366            .retain(|open| !music.same_handle(&open.start, start));
367    }
368
369    /// music21's `createBarlines` for ties: a tie running to the end of
370    /// the measure goes on into the next; any other is dropped.
371    ///
372    /// # Errors
373    ///
374    /// What the measure's `highest_time` raises.
375    pub fn barline<T>(&mut self, music: &T, measure: &M) -> Result<(), T::Error>
376    where
377        T: Placing<Measure = M, Handle = H>,
378    {
379        let end = music.highest_time(measure)?;
380        self.tied_steps.retain(|tied| {
381            tied.measure
382                .as_ref()
383                .is_some_and(|tied_measure| music.same_measure(tied_measure, measure))
384                && tied.end == end
385        });
386        for tied in &mut self.tied_steps {
387            tied.measure = None;
388            tied.end = 0.0;
389        }
390        Ok(())
391    }
392
393    /// music21's `createStaff`: nothing left open from the staff before.
394    pub fn new_staff(&mut self) {
395        self.open_slurs.clear();
396        self.tied_steps.clear();
397    }
398}