Skip to main content

fm_vector/
read.rs

1//! The whole score, system by system: bars and barlines, key and time, every staff's chords in
2//! their voices, ties, slurs, dynamics and marks, and the words; each system compiled after the
3//! ones before it, so what is written always opens.
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use crate::frac::Q;
8use crate::jumps;
9use crate::layout::{self, Kind, Part, System};
10use crate::lyrics;
11use crate::marks;
12use crate::page::{Glyph, Page, Staff};
13use crate::smufl;
14use crate::staff::{read_staff_bar, voices_of, Ev, Res, Untaken};
15use crate::write::write_voice_across;
16
17/// A PDF read whole.
18#[derive(Clone, Debug)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub struct Reading {
21    /// The score as `.fmn` text (docs/transcribing.md).
22    pub fmn: String,
23    /// The score compiled.
24    pub musicxml: String,
25    pub systems: usize,
26    pub bars: usize,
27    pub notes: usize,
28    pub syllables: usize,
29    /// What was read only in part, said for the person (words left off a bar, ...).
30    pub notices: Vec<String>,
31    /// The staves' bars that could not be read: each is written as a bar's rest, for a person
32    /// (or another reader) to fill in.
33    pub unread: Vec<Unread>,
34    /// With `FMV_OPTIONS` set, each unread (or flagged) staff's bar's options, a line of JSON
35    /// each (`options.rs`); else none.
36    pub options: Vec<String>,
37    /// (what each staff's bar was seen as, kept for the options)
38    #[cfg_attr(feature = "serde", serde(skip))]
39    pub(crate) seen: BTreeMap<(i64, String), crate::options::Seen>,
40    /// (where each staff's bar is, the system each bar is in, and, for a review, every note's
41    /// place: `review.rs`)
42    #[cfg_attr(feature = "serde", serde(skip))]
43    pub(crate) places: BTreeMap<(i64, String), Place>,
44    #[cfg_attr(feature = "serde", serde(skip))]
45    pub(crate) bar_systems: BTreeMap<i64, usize>,
46    #[cfg_attr(feature = "serde", serde(skip))]
47    pub(crate) marks: Vec<crate::review::NoteMark>,
48}
49
50/// A staff's bar that could not be read.
51#[derive(Clone, Debug, PartialEq)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub struct Unread {
54    /// The bar's number as written in the score read.
55    pub bar: i64,
56    /// The staff, as the score names it (`P.2`).
57    pub staff: String,
58    pub why: String,
59    /// Where the bar is and what was seen in it, for whoever reads it instead (a person, or a
60    /// reader of its picture). None where the bar was lost before its place was known.
61    pub place: Option<Place>,
62    /// The same bar on the part's other staves (a piano's other hand), read or not, by staff: a
63    /// note set between two staves, or beamed from one to the other, may have been given to
64    /// either.
65    pub beside: Vec<(String, Place)>,
66}
67
68/// A staff's bar on its page, and the notes and rests seen in it. Their pitches are sure (a
69/// notehead's place on its staff); what could not be made out is how they share the bar's time.
70#[derive(Clone, Debug, PartialEq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub struct Place {
73    /// The page, from 1.
74    pub page: usize,
75    /// The bar's left and right edges and the staff's top and bottom lines, in points from the
76    /// page's top left.
77    pub x0: f64,
78    pub x1: f64,
79    pub y0: f64,
80    pub y1: f64,
81    /// The bar's time, as beats and beat unit.
82    pub time: (i64, i64),
83    /// What stands in the bar, left to right: each chord or rest with its place across the bar
84    /// (in staff spaces from its left edge), its noteheads' pitches as written on the staff
85    /// (without their accidentals), its length by head, flags, beams and dots (in quarters), and
86    /// its stem.
87    pub seen: Vec<String>,
88}
89
90/// Why a PDF, or one of its systems, could not be read from its vectors.
91#[derive(Clone, Debug, PartialEq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93pub struct Refusal {
94    /// The system (1-based) and its page (1-based), when one system is the reason.
95    pub system: Option<(usize, usize)>,
96    pub why: String,
97}
98
99impl std::fmt::Display for Refusal {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        match self.system {
102            Some((s, p)) => write!(f, "system {s} (page {p}): {}", self.why),
103            None => f.write_str(&self.why),
104        }
105    }
106}
107
108impl std::error::Error for Refusal {}
109
110fn refuse(why: impl Into<String>) -> Refusal {
111    Refusal {
112        system: None,
113        why: why.into(),
114    }
115}
116
117/// What carries from one system to the next.
118#[derive(Default)]
119struct Carry {
120    fifths: i32,
121    /// staff -> its own key (`None`: a signature that could not be made out).
122    staff_keys: BTreeMap<String, Option<i32>>,
123    /// The key the text so far has said for the score, and for each staff that has its own.
124    said_key: Option<i32>,
125    own_keys: BTreeMap<String, i32>,
126    /// The score prints its key signature at every system's start.
127    reprints: bool,
128    time: (i64, i64),
129    /// staff -> its own time, as the text so far leaves it (`times::Times`).
130    staff_times: BTreeMap<String, (i64, i64)>,
131    /// staff -> the sign its time is printed as (`common`, `cut`); the score's under no name.
132    time_signs: BTreeMap<String, &'static str>,
133    /// The score prints its time signatures on every staff, so a staff with none where
134    /// another has one keeps its time.
135    every_staff_times: bool,
136    /// The score's top staff: its time is the score's.
137    top: String,
138    clef: BTreeMap<String, &'static str>,
139    /// (staff, voice) -> {place: alteration} tied over the system's end.
140    ties: BTreeMap<(String, usize), BTreeMap<i32, i32>>,
141    /// staff -> slurs open over the system's end.
142    slurs: BTreeMap<String, u32>,
143    /// staff -> the stem of the note the last of them leaves (its voice).
144    slur_stems: BTreeMap<String, Option<bool>>,
145    /// A repeat's start at the end of the system before.
146    starts_with: Option<&'static str>,
147    next_bar: i64,
148    /// Words: whether verse 1's last syllable is held on, and the places tied into a voice's next note.
149    held: bool,
150    lyric_ties: BTreeMap<String, BTreeSet<i32>>,
151    /// Hairpins, the pedal and ottava lines open over the system's end.
152    open: marks::Open,
153    /// The ending whose bracket runs on over the system's end.
154    ending: Option<String>,
155    /// staff -> the notes of tuplets read on it in the systems before (the last few): an unmarked
156    /// run shaped like one is that tuplet again ("simile").
157    tupleted: BTreeMap<String, Vec<Ev>>,
158    /// Whether a staff's bar that cannot be read is left as a rest (and listed here) or refuses
159    /// the PDF.
160    partial: bool,
161    unread: Vec<Unread>,
162    /// Every staff's bar read so far, by number and staff: its place.
163    places: BTreeMap<(i64, String), Place>,
164    /// (a system's first bar, staff) -> the alterations in force on the staff's places at the end
165    /// of the bar before it: what a tie into the system from a note not found carries.
166    altered: BTreeMap<(i64, String), BTreeMap<i32, i32>>,
167    /// (a system's first bar, staff) -> the places of each voice's last note in the bar before
168    /// it, where that bar was read with notes: the notes a tie into the system can come from.
169    ended: BTreeMap<(i64, String), BTreeSet<i32>>,
170    /// The bars that run on over a system's end (`longbars.rs`).
171    runs: crate::longbars::RunsOn,
172    /// Every staff's bar as it stood and was read, for the bars that stand again (`repeats.rs`).
173    twins: crate::repeats::Twins,
174    /// With `FMV_OPTIONS` set, what each staff's bar was seen as (`options.rs`).
175    seen: BTreeMap<(i64, String), crate::options::Seen>,
176    /// The system being read (0-based) and its page, the system of each bar, and for a review
177    /// each note read (`review.rs`).
178    system: usize,
179    page: usize,
180    bar_systems: BTreeMap<i64, usize>,
181    marks: Vec<crate::review::NoteMark>,
182}
183
184/// Where a system ends inside a bar: notes or rests stand after its last barline, and the bar
185/// goes on in the next system. The staves' end then closes a bar of its own here, as the
186/// program that set it counts it; without it that music would be lost unseen.
187fn open_end(staff_glyphs: &[Vec<Glyph>], groups: &[Vec<f64>], right: f64, sp: f64) -> Option<f64> {
188    let last = *groups.last()?.last()?;
189    let after = staff_glyphs.iter().flatten().any(|g| {
190        (smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
191            && g.x0 > last + sp
192            && g.x1 < right
193    });
194    (after && right - last > 3.0 * sp).then_some(right)
195}
196
197/// A clef glyph's clef on its staff, by the line it is set on (`smufl::clef_on`).
198fn clef_of(g: &Glyph, st: &Staff) -> Option<&'static str> {
199    smufl::clef_on(g.code, (st.bottom() - g.y) / st.sp() + 1.0)
200}
201
202/// The clef a staff's first note is read in: the last clef before the system's first note or
203/// rest (a clef changed at once is set after the staff's opening clef, before the first note).
204fn opening_clef(gs: &[Glyph], st: &Staff, first_event: f64) -> Option<&'static str> {
205    gs.iter()
206        .filter(|g| g.x0 < first_event)
207        .filter_map(|g| Some((g.x0, clef_of(g, st)?)))
208        .max_by(|a, b| a.0.total_cmp(&b.0))
209        .map(|c| c.1)
210}
211
212/// The clefs before a system's first note or rest, in order, each with where it stands.
213fn clefs_before(gs: &[Glyph], st: &Staff, first_event: f64) -> Vec<(f64, &'static str)> {
214    let mut clefs: Vec<(f64, &'static str)> = gs
215        .iter()
216        .filter(|g| g.x0 < first_event)
217        .filter_map(|g| Some((g.x0, clef_of(g, st)?)))
218        .collect();
219    clefs.sort_by(|a, b| a.0.total_cmp(&b.0));
220    clefs
221}
222
223pub(crate) fn time_of(ts: &[&Glyph]) -> Res<(i64, i64)> {
224    if ts.iter().any(|g| g.code == smufl::COMMON) {
225        return Ok((4, 4));
226    }
227    if ts.iter().any(|g| g.code == smufl::CUT) {
228        return Ok((2, 2));
229    }
230    let mut ys: Vec<i64> = ts
231        .iter()
232        .map(|g| g.y.round() as i64)
233        .collect::<BTreeSet<_>>()
234        .into_iter()
235        .collect();
236    ys.sort();
237    if ys.len() < 2 {
238        return Err(Untaken::new("a time signature it cannot make out"));
239    }
240    let mut sorted: Vec<&&Glyph> = ts.iter().collect();
241    sorted.sort_by(|a, b| a.x0.total_cmp(&b.x0));
242    let digits = |y: i64| -> String {
243        sorted
244            .iter()
245            .filter(|g| g.y.round() as i64 == y)
246            .filter_map(|g| smufl::time_digit(g.code))
247            .map(|d| char::from_digit(d, 10).unwrap())
248            .collect()
249    };
250    let (n, d) = (digits(ys[0]), digits(*ys.last().unwrap()));
251    match (n.parse(), d.parse()) {
252        (Ok(n), Ok(d)) if n > 0 && d > 0 => Ok((n, d)),
253        _ => Err(Untaken::new("a time signature it cannot make out")),
254    }
255}
256
257/// Whether a time signature's digit stands on the staff (from `top` to `bottom`): within half a
258/// space of it. A lead sheet's large time signature, its digits set larger than the noteheads
259/// (`size`: the page's notehead size), reaches under the staff: its lower digit a space further.
260pub(crate) fn on_staff_for_time(g: &Glyph, top: f64, bottom: f64, sp: f64, size: f64) -> bool {
261    let large = g.size > 1.15 * size;
262    top - 0.5 * sp < g.y && g.y < bottom + if large { 1.5 * sp } else { 0.5 * sp }
263}
264
265/// A multi-bar rest's bars on a staff: a thick bar along its middle line, more than four spaces
266/// long (between short strokes at its ends). Their left and right edges.
267fn multi_rests(pg: &Page, st: &Staff, sp: f64) -> Vec<(f64, f64)> {
268    let mid = (st.top() + st.bottom()) / 2.0;
269    pg.polys
270        .iter()
271        .filter(|p| p.len() == 4)
272        .filter_map(|p| {
273            let x0 = p.iter().map(|q| q.0).fold(f64::MAX, f64::min);
274            let x1 = p.iter().map(|q| q.0).fold(f64::MIN, f64::max);
275            let y0 = p.iter().map(|q| q.1).fold(f64::MAX, f64::min);
276            let y1 = p.iter().map(|q| q.1).fold(f64::MIN, f64::max);
277            (x1 - x0 > 4.0 * sp
278                && y1 - y0 > 0.5 * sp
279                && y1 - y0 < 1.5 * sp
280                && ((y0 + y1) / 2.0 - mid).abs() < 0.5 * sp
281                && st.left < x0
282                && x1 < st.right
283                && !stemmed(pg, (x0, y0, x1, y1), sp))
284            .then_some((x0, x1))
285        })
286        .collect()
287}
288
289/// Whether a stem ends at a shape (its box given): an upright line that meets it and runs on well
290/// past it above or below. Such a shape is a beam through the middle of the staff (low notes
291/// stemmed up), not a multi-bar rest, whose end strokes reach a space either side.
292fn stemmed(pg: &Page, (x0, y0, x1, y1): (f64, f64, f64, f64), sp: f64) -> bool {
293    pg.vlines.iter().any(|v| {
294        x0 - 0.2 * sp <= v.x
295            && v.x <= x1 + 0.2 * sp
296            && v.y0 <= y1 + 0.2 * sp
297            && v.y1 >= y0 - 0.2 * sp
298            && (y0 - v.y0).max(v.y1 - y1) > 1.0 * sp
299    })
300}
301
302fn bar_len(t: (i64, i64)) -> Q {
303    Q::new(4 * t.0, t.1)
304}
305
306/// Read a PDF's pages whole, or say why not.
307///
308/// `max_unread`: the share of the staves' bars that may be left unread, each as a bar's rest,
309/// before the PDF is refused for the first of them (0: any bar unread refuses it).
310pub fn read(pages: &[Page], max_unread: f64) -> Result<Reading, Refusal> {
311    // twice, where the first pass left a bar unread that stands again in a bar it read
312    // (`repeats.rs`): the second reads such a bar as its twins were read
313    let twins = crate::repeats::Twins::default();
314    let first = read_pass(pages, max_unread, &twins);
315    if !twins.again() {
316        return first.map(with_options);
317    }
318    match (read_pass(pages, max_unread, &twins), first) {
319        (Ok(second), Ok(first)) if second.unread.len() > first.unread.len() => Ok(first),
320        (Ok(second), _) => Ok(second),
321        (Err(_), first) => first,
322    }
323    .map(with_options)
324}
325
326/// The options of the reading's unread and flagged staves' bars (`options.rs`), where asked for.
327fn with_options(mut r: Reading) -> Reading {
328    // (a review makes its questions of what was seen itself: `review.rs`)
329    if crate::review::on() {
330        return r;
331    }
332    let seen = std::mem::take(&mut r.seen);
333    if !crate::options::on() {
334        return r;
335    }
336    let none = || crate::options::Options {
337        choices: Vec::new(),
338        spot: None,
339        readings: Vec::new(),
340    };
341    for u in &r.unread {
342        let s = seen.get(&(u.bar, u.staff.clone()));
343        let opts = s.map_or_else(none, |s| crate::options::of(s, &u.staff, None));
344        let line = crate::options::json(u.bar, &u.staff, &u.why, u.place.as_ref(), s, &opts);
345        r.options.push(line);
346    }
347    // (a bar flagged as read wrongly: its reading as given is no option)
348    for (bar, staff) in crate::options::flagged() {
349        let s = seen.get(&(bar, staff.clone()));
350        let opts = s.map_or_else(none, |s| {
351            let given =
352                (s.read.as_ref().ok()).and_then(|vs| crate::options::lines_of(vs, &staff, s));
353            let mut opts = crate::options::of(s, &staff, given.as_deref());
354            opts.without("as read");
355            opts
356        });
357        let line = crate::options::json(bar, &staff, "flagged", None, s, &opts);
358        r.options.push(line);
359    }
360    r
361}
362
363/// One pass of [`read`] over the pages.
364fn read_pass(
365    pages: &[Page],
366    max_unread: f64,
367    twins: &crate::repeats::Twins,
368) -> Result<Reading, Refusal> {
369    let systems = layout::systems(pages);
370    if systems.is_empty() {
371        return Err(refuse("it has no staves drawn as lines: it is not a notation program's PDF (a scan, or a picture)"));
372    }
373    if systems.iter().any(|s| pages[s.page].size == 0.0) {
374        return Err(refuse(
375            "its music font is not one whose glyphs this reader knows (its music drawn as pictures or bare outlines, or a font with no table here)",
376        ));
377    }
378    let parts = layout::parts(pages, &systems);
379    let all_names: Vec<String> = parts.iter().flat_map(Part::staff_names).collect();
380    let shown = layout::systems_parts(pages, &systems, &parts);
381    let short = crate::shown::short(pages, &systems, &parts);
382    // the staves' bars of parts a short system does not tell apart: unread, and counted apart
383    // from the bars that could not be read
384    let mut untold: Vec<Unread> = Vec::new();
385    // the staves a tie or slur runs on from, out of the system just read
386    let mut went_on: BTreeSet<String> = BTreeSet::new();
387    let mut header = String::new();
388    let (title, composer) =
389        layout::title_and_composer(&pages[systems[0].page], &systems[0].staves[0]);
390    header.push_str(&format!(
391        "title: {}\n",
392        title.unwrap_or_else(|| "Untitled".into())
393    ));
394    if let Some(c) = composer {
395        header.push_str(&format!("composer: {c}\n"));
396    }
397    header.push('\n');
398    for p in &parts {
399        let opt = match p.kind {
400            Kind::Voice => " voice",
401            Kind::Piano => " piano",
402            Kind::Other => "",
403        };
404        header.push_str(&format!(
405            "part {} \"{}\"{opt}\n",
406            p.id,
407            p.name.replace('"', "'")
408        ));
409    }
410    let mut voice_staves: BTreeSet<String> = parts
411        .iter()
412        .filter(|p| p.kind == Kind::Voice)
413        .map(|p| p.id.clone())
414        .collect();
415    if voice_staves.is_empty() {
416        // no voice part: an easy-piano song sets the words between the piano's staves, under the
417        // tune. Taken when most systems have words there, not the odd "legato"
418        for p in parts.iter().filter(|p| p.kind == Kind::Piano) {
419            let top = &p.staff_names()[0];
420            let Some(at) = all_names.iter().position(|n| n == top) else {
421                continue;
422            };
423            let full: Vec<&System> = systems
424                .iter()
425                .filter(|s| s.staves.len() == all_names.len())
426                .collect();
427            let worded = full
428                .iter()
429                .filter(|s| {
430                    let st = &s.staves[at];
431                    lyrics::band(&pages[s.page], st, s.staves.get(at + 1), st.left, st.right).len()
432                        >= 4
433                })
434                .count();
435            if !full.is_empty() && 2 * worded > full.len() {
436                voice_staves.insert(top.clone());
437            }
438        }
439    }
440
441    // (asks whether the text so far compiles, from where it last stood: `fm_transcribe::Checker`)
442    let mut checker = fm_transcribe::Checker::new();
443    let mut carry = Carry {
444        time: (4, 4),
445        next_bar: 1,
446        partial: max_unread > 0.0,
447        top: all_names.first().cloned().unwrap_or_default(),
448        twins: twins.clone(),
449        ..Carry::default()
450    };
451    let mut staff_bars = 0;
452    // the system (and its page) of the first bar left unread
453    let mut first_unread: Option<(usize, usize)> = None;
454    let mut done = String::new();
455    let mut notices = Vec::new();
456    let mut total_bars = 0;
457    let last_system = systems.len() - 1;
458    for (si, sys) in systems.iter().enumerate() {
459        let at = |why: String| Refusal {
460            system: Some((si + 1, sys.page + 1)),
461            why,
462        };
463        // (fewer staves: what the page says of which parts they are, `shown.rs`)
464        let told = {
465            let before = |name: &str| carry.clef.get(name).copied();
466            let goes_on = |name: &str| went_on.contains(name);
467            short.tell(si, &parts, &before, &goes_on, shown[si].as_ref())
468        };
469        let names: Vec<String> = match all_names.len().checked_sub(sys.staves.len()) {
470            // fewer staves: the top ones left out (a voice not printed while it rests), or the
471            // parts its staves' shapes and printed names say
472            Some(skip) => match told.as_ref().map(|t| &t.parts).or(shown[si].as_ref()) {
473                Some(shown) => (shown.iter())
474                    .flat_map(|&j| parts[j].staff_names())
475                    .collect(),
476                None => all_names[skip..].to_vec(),
477            },
478            None => {
479                return Err(at(format!(
480                    "it has {} staves where the score's parts have {}",
481                    sys.staves.len(),
482                    all_names.len()
483                )))
484            }
485        };
486        let first_piece = si == 0;
487        // the band over the system: from the system above on its page, or the page's top
488        let ceiling = si
489            .checked_sub(1)
490            .map(|p| &systems[p])
491            .filter(|p| p.page == sys.page)
492            .and_then(|p| p.staves.last())
493            .map_or(0.0, |s| s.bottom());
494        let floor = next_system_top(&systems, si);
495        let sung: BTreeSet<usize> = (0..names.len())
496            .filter(|&i| voice_staves.contains(&names[i]))
497            .collect();
498        carry.system = si;
499        carry.page = sys.page;
500        let mut read = read_system(
501            &pages[sys.page],
502            sys,
503            &names,
504            &mut carry,
505            first_piece,
506            si == last_system,
507            ceiling,
508            floor,
509            &sung,
510        )
511        .map_err(|u| at(u.0))?;
512        // the parts the page does not tell apart here: their bars are left as rests
513        // (a short system whose staves fit no choice of the parts at all: which parts it shows
514        // is not known, so none of its bars is told)
515        let fits_none = sys.staves.len() < all_names.len() && told.is_none() && shown[si].is_none();
516        let doubted: Vec<usize> = match fits_none {
517            true => (0..parts.len()).collect(),
518            false => told.map(|t| t.doubted).unwrap_or_default(),
519        };
520        let why = |staff: &str| match fits_none {
521            true => crate::shown::why_unfit(staff),
522            false => crate::shown::why(staff, &doubted, &parts),
523        };
524        let clefs_before = carry.clef.clone();
525        if !doubted.is_empty() {
526            let staves: Vec<String> = (doubted.iter())
527                .flat_map(|&j| parts[j].staff_names())
528                .collect();
529            let bars = read.leave_untold(&staves, &carry.unread);
530            if !carry.partial && !bars.is_empty() {
531                return Err(at(why(&staves[0])));
532            }
533            carry
534                .unread
535                .retain(|u| !(bars.contains(&u.bar) && staves.contains(&u.staff)));
536            for &bar in &bars {
537                untold.extend(staves.iter().map(|staff| Unread {
538                    bar,
539                    staff: staff.clone(),
540                    why: format!("bar {bar}, {}", why(staff)),
541                    place: None,
542                    beside: Vec::new(),
543                }));
544            }
545        }
546        notices.append(&mut read.notices);
547        if first_piece {
548            header.push_str(&format!(
549                "\nkey {} major\ntime {}\n",
550                read.fifths,
551                crate::times::said(read.time, read.time_sign)
552            ));
553            for (name, clef) in names.iter().zip(&read.clefs) {
554                header.push_str(&format!("clef {name} {clef}\n"));
555            }
556            done = header.clone();
557        }
558        // (words at the end of the system before whose line of dashes begins in this one)
559        crate::dashes::open_late(&mut done, &mut carry.open.dashes_late);
560        // the jumps and endings over it, on their bars
561        let edges: Vec<(f64, f64)> = read.bars.iter().map(|b| (b.left, b.right)).collect();
562        let marks = jumps::marks(
563            &pages[sys.page],
564            sys,
565            &edges,
566            ceiling,
567            carry.ending.as_deref(),
568        );
569        carry.ending = marks.runs_on.clone();
570        for (b, name) in marks.jumps {
571            read.bars[b].jumps.push(name);
572        }
573        for (b, nums) in marks.endings {
574            read.bars[b].ending = Some(nums);
575        }
576        // the notes first: a system whose notes compile is kept
577        let notes_text = read.text(&BTreeMap::new());
578        let mut check = |done: &str, text: &str| -> Result<(), String> {
579            match checker.check(done, text) {
580                Ok(()) => Ok(()),
581                Err(msg) => {
582                    // a tie or slur into the next system lands when that system is there
583                    let open = ["never lands", "never ends", "is never closed"]
584                        .iter()
585                        .any(|w| msg.contains(w));
586                    // a hairpin or an ottava line may run on over several systems
587                    let runs_on = msg.contains("is never closed")
588                        && (msg.contains("hairpin")
589                            || msg.contains("ottava")
590                            || msg.contains("line of dashes"));
591                    // a slur the reading has running off the system's end, from whichever of
592                    // its bars (or through the whole of it, from a system before)
593                    let slur_on = msg.contains("never ends")
594                        && (read.slurs_out.iter().chain(&read.slurs_in_left)).any(|(n, k)| {
595                            let staff = match n.contains('.') {
596                                true => n.clone(),
597                                false => format!("{n}.1"),
598                            };
599                            *k > 0 && msg.contains(&format!("a slur in {staff}/"))
600                        });
601                    if open
602                        && si != last_system
603                        && (runs_on || slur_on || msg.contains(&format!("bar {}", read.last_bar)))
604                    {
605                        Ok(())
606                    } else {
607                        Err(msg)
608                    }
609                }
610            }
611        };
612        // a curve run off the system before that its next system does not take up as a tie (no
613        // note there at its place) was a slur's or a mark's: the tie goes
614        // and a slur or tie that pairs with nothing (a curve misread) is taken out, and said
615        let mut tries = 0;
616        let first = read.last_bar - read.bars.len() as i64 + 1;
617        let mut notes_text = notes_text;
618        // (and, reading in part, lines that pair with nothing are left out a system at a time,
619        // and a staff's bar the compiler will not have is left as a rest)
620        let mut blanked: Vec<Unread> = Vec::new();
621        // (as many as the system has staves' bars: a bar as written compiles or goes unread,
622        // and how much of a PDF may go unread is said for the whole of it)
623        let most = (read.bars.len() * names.len()).max(8);
624        while let Err(e) = check(&done, &notes_text) {
625            if tries >= 48 + most {
626                break;
627            }
628            tries += 1;
629            let all = format!("{done}\n{notes_text}");
630            if unties_last(&mut done, &e, first, &all) {
631                continue;
632            }
633            if let Some(what) = crate::dashes::mend(&mut done, &mut notes_text, &e) {
634                notices.push(format!("left out: {what}"));
635                continue;
636            }
637            // (lines the mender does not settle in a few tries go out a system at a time)
638            let stuck =
639                carry.partial && tries > 6 && (e.contains("hairpin") || e.contains("ottava"));
640            if let Some(what) = stuck
641                .then(|| without_lines_or_bars(&mut done, &mut notes_text, &e, &mut blanked))
642                .flatten()
643            {
644                notices.push(format!("left out: {what} (system {})", si + 1));
645            } else if let Some(what) = unpair(&mut done, &mut notes_text, &e) {
646                notices.push(format!("left out: {what}"));
647            } else if !carry.partial {
648                break;
649            } else if let Some(what) =
650                without_lines_or_bars(&mut done, &mut notes_text, &e, &mut blanked)
651            {
652                notices.push(format!("left out: {what} (system {})", si + 1));
653            } else if let Some(u) = blank_bar(&mut notes_text, &e).filter(|_| blanked.len() < most)
654            {
655                blanked.push(u);
656            } else if let Some(mut us) =
657                blank_named(&mut done, &mut notes_text, &e).filter(|_| blanked.len() < most)
658            {
659                blanked.append(&mut us);
660            } else if let Some(u) =
661                blank_line(&done, &mut notes_text, &e).filter(|_| blanked.len() < most)
662            {
663                blanked.push(u);
664            } else {
665                break;
666            }
667        }
668        check(&done, &notes_text).map_err(|e| {
669            #[cfg(not(target_arch = "wasm32"))]
670            if let Ok(p) = std::env::var("FMV_REFUSED") {
671                let _ = std::fs::write(p, format!("{done}\n{notes_text}"));
672            }
673            at(format!(
674                "its bars as read do not compile: {}",
675                e.lines().last().unwrap_or("")
676            ))
677        })?;
678        // then the words, where they fit
679        let words = place_words(
680            &pages[sys.page],
681            sys,
682            &names,
683            &read,
684            &voice_staves,
685            &mut carry,
686        );
687        let mut text = notes_text;
688        if !words.is_empty() {
689            let mut with = read.text(&words);
690            // the bars left as rests in the notes are left so with their words, and the marks
691            // left out of the notes are left out again. Nothing more is left unread for the
692            // words' sake: words that still do not fit are left out, and the notes kept.
693            for u in &blanked {
694                rest_staff_bar(&mut with, &u.bar.to_string(), |base| base == u.staff);
695            }
696            let mut tries = 0;
697            while let Err(e) = check(&done, &with) {
698                tries += 1;
699                // (as the notes were: lines the mender does not settle in a few tries go out)
700                let stuck =
701                    carry.partial && tries > 6 && (e.contains("hairpin") || e.contains("ottava"));
702                let mended = tries <= 48
703                    && (crate::dashes::mend(&mut done, &mut with, &e).is_some()
704                        || (stuck
705                            && without_lines_or_bars(&mut done, &mut with, &e, &mut blanked)
706                                .is_some())
707                        || unpair(&mut done, &mut with, &e).is_some()
708                        || (carry.partial
709                            && without_lines_or_bars(&mut done, &mut with, &e, &mut blanked)
710                                .is_some()));
711                if !mended {
712                    break;
713                }
714            }
715            match check(&done, &with) {
716                Ok(()) => text = with,
717                Err(e) => notices.push(format!(
718                    "the words of system {} were left out: they did not fit its notes ({})",
719                    si + 1,
720                    e.lines().last().unwrap_or("")
721                )),
722            }
723        }
724        carry.unread.append(&mut blanked);
725        done.push('\n');
726        done.push_str(&text);
727        total_bars += read.bars.len();
728        staff_bars += read.bars.len() * names.len();
729        if first_unread.is_none() && !carry.unread.is_empty() {
730            first_unread = Some((si + 1, sys.page + 1));
731        }
732        went_on = (read.ties_out.iter())
733            .filter(|(_, places)| !places.is_empty())
734            .map(|(k, _)| k.0.clone())
735            .chain(
736                read.slurs_out
737                    .iter()
738                    .filter(|(_, &n)| n > 0)
739                    .map(|(k, _)| k.clone()),
740            )
741            .collect();
742        read.commit(&mut carry, &names);
743        // (a doubted part's clef stays the one it was last surely left in)
744        for name in doubted.iter().flat_map(|&j| parts[j].staff_names()) {
745            match clefs_before.get(&name) {
746                Some(c) => carry.clef.insert(name, c),
747                None => carry.clef.remove(&name),
748            };
749        }
750    }
751    // (no barline in any system: they were not found, and the score is not one long bar)
752    if carry.runs.barred == 0 {
753        return Err(Refusal {
754            system: Some((1, systems[0].page + 1)),
755            why: crate::longbars::NO_BARLINES.to_string(),
756        });
757    }
758    let mut unread: Vec<Unread> = Vec::new();
759    for u in std::mem::take(&mut carry.unread) {
760        if !unread.iter().any(|o| o.bar == u.bar && o.staff == u.staff) {
761            unread.push(u);
762        }
763    }
764    carry
765        .twins
766        .close(|bar, staff| unread.iter().any(|u| u.bar == bar && u.staff == staff));
767    notices.extend(carry.twins.said());
768    if unread.len() as f64 > max_unread * staff_bars as f64 {
769        return Err(Refusal {
770            system: first_unread,
771            why: format!(
772                "{} (and {} more of its {} staves' bars)",
773                unread[0].why,
774                unread.len() - 1,
775                staff_bars
776            ),
777        });
778    }
779    unread.retain(|u| !untold.iter().any(|o| o.bar == u.bar && o.staff == u.staff));
780    unread.append(&mut untold);
781    // a bar that ran on over a system's end, read a piece to each system, is one bar
782    let compiles = |text: &str| fm_transcribe::compile(text).is_ok();
783    let places = &mut carry.places;
784    total_bars -= crate::longbars::join(&mut done, &mut carry.runs, &mut unread, places, compiles);
785    for u in unread.iter_mut() {
786        u.place = carry.places.get(&(u.bar, u.staff.clone())).cloned();
787        let part = |s: &str| s.split('.').next().unwrap_or(s).to_string();
788        u.beside = carry
789            .places
790            .range((u.bar, String::new())..(u.bar + 1, String::new()))
791            .filter(|((_, st), _)| *st != u.staff && part(st) == part(&u.staff))
792            .map(|((_, st), p)| (st.clone(), p.clone()))
793            .collect();
794    }
795    for u in &unread {
796        notices.push(format!("not read, left as a rest: {}", u.why));
797    }
798    let compiled = fm_transcribe::compile(&done)
799        .map_err(|e| refuse(format!("the score as read does not compile: {e:#}")))?;
800    Ok(Reading {
801        fmn: done,
802        musicxml: compiled.musicxml,
803        systems: systems.len(),
804        bars: total_bars.max(compiled.bars),
805        notes: compiled.notes,
806        syllables: compiled.syllables,
807        notices,
808        unread,
809        options: Vec::new(),
810        seen: std::mem::take(&mut carry.seen),
811        places: std::mem::take(&mut carry.places),
812        bar_systems: std::mem::take(&mut carry.bar_systems),
813        marks: std::mem::take(&mut carry.marks),
814    })
815}
816
817/// Each staff's key through a system (`key::keys`), from what the system before left.
818#[allow(clippy::too_many_arguments)]
819fn system_keys(
820    staff_glyphs: &[Vec<Glyph>],
821    staves: &[Staff],
822    first_event: f64,
823    edges: &[f64],
824    clef_runs: &[Vec<(f64, &'static str)>],
825    names: &[String],
826    carry: &Carry,
827    first_piece: bool,
828) -> crate::key::Keys {
829    let carried: Vec<Option<i32>> = names
830        .iter()
831        .map(|n| {
832            carry
833                .staff_keys
834                .get(n)
835                .copied()
836                .unwrap_or(Some(carry.fifths))
837        })
838        .collect();
839    // (a clef changed at once stands after the staff's opening clef and its signature, which
840    // is set for the opening clef: up to that second clef the staff is in its first)
841    let openings: Vec<Vec<(f64, &'static str)>> = (staff_glyphs.iter().zip(staves))
842        .map(|(gs, st)| clefs_before(gs, st, first_event))
843        .collect();
844    let clef_bottom = |i: usize, x: f64| {
845        let run = &clef_runs[i];
846        let opening = match &openings[i][..] {
847            [first, second, ..] if x < second.0 => Some(first.1),
848            _ => None,
849        };
850        smufl::clef_bottom(opening.unwrap_or_else(|| {
851            run.iter()
852                .rev()
853                .find(|(cx, _)| *cx < x)
854                .map_or(run[0].1, |c| c.1)
855        }))
856    };
857    crate::key::keys(
858        staff_glyphs,
859        staves,
860        first_event,
861        edges,
862        &clef_bottom,
863        &carried,
864        carry.reprints,
865        first_piece,
866    )
867}
868
869/// The notes tied into a staff's bar, as {place: alteration}, whichever of its voices each was
870/// tied from (the voices are numbered bar by bar, and a tie may land in another); the ties of
871/// voices the bar no longer has are done with.
872fn ties_into(
873    ties: &mut BTreeMap<(String, usize), BTreeMap<i32, i32>>,
874    staff: &str,
875    voices: usize,
876) -> BTreeMap<i32, i32> {
877    let mut into = BTreeMap::new();
878    for ((name, _), tied) in ties.iter().rev() {
879        if name == staff {
880            into.extend(tied.iter().map(|(p, a)| (*p, *a)));
881        }
882    }
883    ties.retain(|(name, voice), _| name != staff || *voice <= voices);
884    into
885}
886
887/// Whether a curve between two heads at one height (its left edge and its top and bottom; `from`
888/// the head it leaves) ends by them, as a tie does: its nearer edge, where its two ends are, is
889/// within 0.8 of a staff space of the heads' middle (a slur over the same two notes stands
890/// further off its heads); it starts at its head, not by a later note; and where it starts over
891/// or under the head it is clear of it. A tie that passes over later notes of its voice is taken
892/// only from such a curve (`ties::settle`).
893fn curve_ends_by((x0, y0, y1): (f64, f64, f64), from: &Glyph, sp: f64) -> bool {
894    let off = (y0 - from.y).abs().min((y1 - from.y).abs());
895    let after = x0 - from.x1;
896    off < 0.8 * sp && after < 0.5 * sp && (after > -0.1 * sp || off > 0.5 * sp)
897}
898
899/// Whether a curve's right end is at a head: just before it, or over its left part.
900fn ends_at(x1: f64, h: &Glyph, sp: f64) -> bool {
901    let d = h.x0 - x1;
902    -1.5 * sp < d && d < 0.8 * sp
903}
904
905/// Whether a curve (its left and right edges, its top and bottom) is a tie that leaves a note
906/// and lands on none, the note left to ring: it starts as a tie does by one of the note's heads
907/// ([`curve_ends_by`]), is flat and of the two staff spaces such a tie is drawn at (a tie to a
908/// note is as long as the way there, a slur rises or falls with its notes), and no head stands
909/// at its height where it ends (`lands`). Not a small note's: its slur to the note it leads to
910/// is as short.
911fn rings_on(
912    (x0, x1, y0, y1): (f64, f64, f64, f64),
913    e: &Ev,
914    lands: &dyn Fn(&Glyph) -> bool,
915    sp: f64,
916) -> bool {
917    let cy = (y0 + y1) / 2.0;
918    let head = (e.heads.iter()).min_by(|p, q| (p.y - cy).abs().total_cmp(&(q.y - cy).abs()));
919    let Some(head) = head.filter(|_| e.grace.is_none()) else {
920        return false;
921    };
922    let (wide, high) = ((x1 - x0) / sp, (y1 - y0) / sp);
923    curve_ends_by((x0, y0, y1), head, sp)
924        && (1.95..2.05).contains(&wide)
925        && high < 0.65
926        && !lands(head)
927}
928
929/// A curve starts by a head of a chord whose heads stand on both sides of the stem (a second in
930/// it): just after a head at its own height, though short of the chord's right edge.
931fn starts_by_a_head(x0: f64, cy: f64, heads: &[Glyph], sp: f64) -> bool {
932    heads.iter().any(|h| {
933        let d = x0 - h.x1;
934        (h.y - cy).abs() < 1.6 * sp && -1.2 * sp < d && d < 1.5 * sp
935    })
936}
937
938/// How far a slur's end at `x` stands from a note across the staff. The end stands over (or
939/// under) the middle of the note's heads or, where the slur is on the side the stem points to
940/// (`over` and stemmed up, or under and stemmed down), anywhere between that and the stem:
941/// nothing there, else the way to the nearer of the two.
942fn slur_end_beside(e: &Ev, x: f64, over: bool) -> f64 {
943    let mid = (e.left() + e.right()) / 2.0;
944    let stem = (e.stem.as_ref())
945        .filter(|_| e.up == Some(over))
946        .map_or(mid, |s| s.x);
947    (mid.min(stem) - x).max(x - mid.max(stem)).max(0.0)
948}
949
950/// How far a slur's end at height `y` is from where the slur meets a note: a slur over its
951/// notes meets a note at its top (its highest head, or its stem's end), one under them at its
952/// foot. Of two voices' notes at one beat the slur's is the one its end is nearer.
953fn slur_end_outside(e: &Ev, y: f64, over: bool) -> f64 {
954    let ys = (e.heads.iter().map(|h| h.y)).chain(e.stem.iter().flat_map(|s| [s.y0, s.y1]));
955    let at = match over {
956        true => ys.fold(f64::MAX, f64::min),
957        false => ys.fold(f64::MIN, f64::max),
958    };
959    (y - at).abs()
960}
961
962/// Whether a head stands on the other side of a curve than a tie's own head does: a tie that
963/// arches upwards stands over its head, one that hangs stands under it.
964fn across_the_curve(c: &crate::page::Curve, h: &Glyph, sp: f64) -> bool {
965    match c.over() {
966        true => h.y < c.ya - 0.2 * sp,
967        false => h.y > c.ya + 0.2 * sp,
968    }
969}
970
971/// A curve ends by a head of such a chord: just before a head at its own height, though past
972/// the chord's left edge.
973fn ends_by_a_head(x1: f64, cy: f64, heads: &[Glyph], sp: f64) -> bool {
974    heads.iter().any(|h| {
975        let d = h.x0 - x1;
976        (h.y - cy).abs() < 1.6 * sp && -1.5 * sp < d && d < 0.8 * sp
977    })
978}
979
980/// The score's key at each bar of a system: the one most of its staves are in, the key before
981/// where none is known.
982fn common_keys(keys: &crate::key::Keys, before: i32) -> Vec<i32> {
983    let mut now = before;
984    (0..keys.at[0].len())
985        .map(|b| {
986            now = keys.common(b).unwrap_or(now);
987            now
988        })
989        .collect()
990}
991
992/// One system read: its bars' heads and staves' lines, ready to be written.
993struct SystemRead {
994    fifths: i32,
995    /// The key from each bar on (the one most staves are in), each staff's key after the system,
996    /// and whether a signature stands at its start after the score's first.
997    bar_keys: Vec<i32>,
998    keys_out: Vec<Option<i32>>,
999    /// What the text before the system has said of the keys: the score's, each staff's own.
1000    key_said: i32,
1001    own_keys: Vec<Option<i32>>,
1002    reprints: bool,
1003    time: (i64, i64),
1004    /// The sign the system's first time is printed as (`common`, `cut`), where it is.
1005    time_sign: crate::times::Sign,
1006    /// Each staff's time before the system, and whether the score prints its time signatures
1007    /// on every staff.
1008    times_before: Vec<(i64, i64)>,
1009    every_staff_times: bool,
1010    names: Vec<String>,
1011    clefs: Vec<&'static str>,
1012    clef_changes: Vec<Option<&'static str>>,
1013    bars: Vec<BarRead>,
1014    last_bar: i64,
1015    ends_with_start: Option<&'static str>,
1016    slurs_out: BTreeMap<String, u32>,
1017    slur_stems: BTreeMap<String, Option<bool>>,
1018    slurs_in_left: BTreeMap<String, u32>,
1019    ties_out: BTreeMap<(String, usize), BTreeMap<i32, i32>>,
1020    /// staff -> the places tied over the system's end, from whichever of its voices.
1021    tied_over: BTreeMap<String, BTreeSet<i32>>,
1022    opens_with: Option<&'static str>,
1023    prev_time: (i64, i64),
1024    /// Each staff's clef at the system's end (a clef changed inside it).
1025    end_clefs: Vec<&'static str>,
1026    notices: Vec<String>,
1027}
1028
1029struct BarRead {
1030    number: i64,
1031    pickup: bool,
1032    short: bool,
1033    /// A piece of a bar that runs on over a system's end, longer than its time's bar.
1034    free: bool,
1035    time: (i64, i64),
1036    /// Each staff's own time; and the signs they are printed as, the score's and each staff's.
1037    times: Vec<(i64, i64)>,
1038    time_sign: crate::times::Sign,
1039    time_signs: Vec<crate::times::Sign>,
1040    /// Each staff's own key as the bar starts (`None`: not made out), and the key a signature
1041    /// inside the bar turns it to.
1042    keys: Vec<Option<i32>>,
1043    key_changes: Vec<Option<i32>>,
1044    end: Option<&'static str>,
1045    start_before: Option<&'static str>,
1046    /// Per staff: its voices' lines (`V: ...`, `V/2: ...`) and the upper voice's events.
1047    staves: Vec<(Vec<String>, Vec<Ev>)>,
1048    left: f64,
1049    right: f64,
1050    /// Its jumps (`segno`, `to-coda`, `ds-al-coda`, ...) and its ending's numbers.
1051    jumps: Vec<&'static str>,
1052    ending: Option<String>,
1053    /// Its tempo mark, as the format's `tempo` line takes it.
1054    tempo: Option<String>,
1055    /// How many bars it stands for: a multi-bar rest's count, else one.
1056    rests: i64,
1057}
1058
1059impl SystemRead {
1060    /// The system's bars as text; `words`: (bar index, staff name) -> its lyric lines.
1061    fn text(&self, words: &BTreeMap<(usize, String), Vec<String>>) -> String {
1062        let mut out = Vec::new();
1063        let mut key_lines = self.key_lines().0;
1064        for (b, bar) in self.bars.iter().enumerate() {
1065            let mut head = format!("bar {}", bar.number);
1066            if bar.pickup {
1067                head.push_str(" pickup");
1068            }
1069            if bar.short {
1070                head.push_str(" short");
1071            }
1072            if bar.free {
1073                head.push_str(" free");
1074            }
1075            if b == 0 {
1076                head.push_str(" system");
1077            }
1078            let mut lines = vec![head];
1079            lines.append(&mut key_lines[b]);
1080            let before = if b > 0 {
1081                self.bars[b - 1].time
1082            } else {
1083                self.prev_time
1084            };
1085            if bar.time != before {
1086                let time = crate::times::said(bar.time, bar.time_sign);
1087                lines.push(format!("time {time}"));
1088            }
1089            let staves_before = match b {
1090                0 => &self.times_before,
1091                _ => &self.bars[b - 1].times,
1092            };
1093            lines.extend(crate::times::own_lines(
1094                &self.names,
1095                (&bar.times, &bar.time_signs),
1096                staves_before,
1097                bar.time,
1098                bar.time != before,
1099            ));
1100            if let Some(t) = &bar.tempo {
1101                lines.push(format!("tempo {t}"));
1102            }
1103            if let Some(s) = bar.start_before {
1104                lines.push(format!("barline {s}"));
1105            }
1106            if let Some(e) = bar.end.filter(|_| bar.rests == 1) {
1107                lines.push(format!("barline {e}"));
1108            }
1109            if !bar.jumps.is_empty() {
1110                lines.push(format!("jump {}", bar.jumps.join(" ")));
1111            }
1112            if let Some(n) = &bar.ending {
1113                lines.push(format!("ending {n}"));
1114            }
1115            if b == 0 {
1116                if let Some(s) = self.opens_with {
1117                    lines.push(format!("barline {s}"));
1118                }
1119            }
1120            for (i, (staff_lines, _)) in bar.staves.iter().enumerate() {
1121                if b == 0 {
1122                    if let Some(c) = self.clef_changes[i] {
1123                        let name = staff_lines[0].split(':').next().unwrap_or("").to_string();
1124                        lines.push(format!("clef {name} {c}"));
1125                    }
1126                }
1127                for l in staff_lines {
1128                    lines.push(l.clone());
1129                    let name = l.split(':').next().unwrap_or("");
1130                    if !name.contains('/') {
1131                        if let Some(ws) = words.get(&(b, name.to_string())) {
1132                            lines.extend(ws.iter().cloned());
1133                        }
1134                    }
1135                }
1136            }
1137            out.push(lines.join("\n"));
1138            // the rest of a multi-bar rest
1139            for k in 1..bar.rests {
1140                let mut lines = vec![format!("bar {}", bar.number + k)];
1141                if let Some(e) = bar.end.filter(|_| k == bar.rests - 1) {
1142                    lines.push(format!("barline {e}"));
1143                }
1144                for (staff_lines, _) in &bar.staves {
1145                    lines.extend(staff_lines.iter().cloned());
1146                }
1147                out.push(lines.join("\n"));
1148            }
1149        }
1150        out.join("\n\n") + "\n"
1151    }
1152
1153    /// The lines that say the keys, bar by bar: the score's (the key most staves are in) where
1154    /// it changes, and a staff's or a part's own beside it (`key P.2 0 major`). Then what the
1155    /// text has said after the system (the score's key, each staff's own), and whether the
1156    /// score's was said in it.
1157    fn key_lines(&self) -> (Vec<Vec<String>>, i32, Vec<Option<i32>>, bool) {
1158        let say = |who: Option<&str>, k: i32| match who {
1159            Some(name) => format!("key {name} {k} major"),
1160            None => format!("key {k} major"),
1161        };
1162        let (mut score, mut own) = (self.key_said, self.own_keys.clone());
1163        let mut said = false;
1164        let mut out = Vec::new();
1165        for (b, bar) in self.bars.iter().enumerate() {
1166            let before = score;
1167            // (a staff whose key is not made out keeps its own, or goes with the score: its bar
1168            // is not read)
1169            let common = self.bar_keys.get(b).copied().unwrap_or(score);
1170            let want: Vec<i32> = (0..own.len())
1171                .map(|i| (bar.keys.get(i).copied().flatten()).unwrap_or(own[i].unwrap_or(common)))
1172                .collect();
1173            out.push(crate::times::lines_for(
1174                &self.names,
1175                &want,
1176                common,
1177                (&mut score, &mut own),
1178                &say,
1179            ));
1180            said |= score != before;
1181            for (i, k) in bar.key_changes.iter().enumerate() {
1182                own[i] = k.or(own[i]);
1183            }
1184        }
1185        (out, score, own, said)
1186    }
1187
1188    /// The bars of `staves` left as bars' rests, with nothing carried out of them: staves the
1189    /// page does not tell apart in this system (`shown.rs`). A bar in which each of them that is
1190    /// shown rests throughout (as read, and not listed in `unread`) is kept: there every part
1191    /// they may be rests, shown or not. The numbers of the bars left.
1192    fn leave_untold(&mut self, staves: &[String], unread: &[Unread]) -> Vec<i64> {
1193        let mut numbers = Vec::new();
1194        for bar in self.bars.iter_mut() {
1195            let span = bar.number..bar.number + bar.rests.max(1);
1196            let sounds = self.names.iter().enumerate().any(|(i, name)| {
1197                staves.contains(name)
1198                    && (bar.staves[i].1.iter().any(|e| !e.heads.is_empty())
1199                        || (unread.iter()).any(|u| &u.staff == name && span.contains(&u.bar)))
1200            });
1201            if !sounds {
1202                continue;
1203            }
1204            numbers.extend(span);
1205            for (i, name) in self.names.iter().enumerate() {
1206                if staves.contains(name) {
1207                    let (n, d) = bar.times[i];
1208                    let rest = bar_rest(Q::new(4 * n, d), bar.left);
1209                    bar.staves[i] = (vec![format!("{name}: R")], vec![rest]);
1210                }
1211            }
1212        }
1213        self.slurs_out.retain(|k, _| !staves.contains(k));
1214        self.slur_stems.retain(|k, _| !staves.contains(k));
1215        self.slurs_in_left.retain(|k, _| !staves.contains(k));
1216        self.ties_out.retain(|k, _| !staves.contains(&k.0));
1217        self.tied_over.retain(|k, _| !staves.contains(k));
1218        numbers
1219    }
1220
1221    fn commit(&self, carry: &mut Carry, names: &[String]) {
1222        let (_, score, own, said) = self.key_lines();
1223        carry.said_key = Some(score);
1224        if said {
1225            carry.own_keys.clear();
1226        }
1227        for (n, k) in names.iter().zip(own) {
1228            match k {
1229                Some(k) => carry.own_keys.insert(n.clone(), k),
1230                None => carry.own_keys.remove(n),
1231            };
1232        }
1233        carry.fifths = self.bar_keys.last().copied().unwrap_or(self.fifths);
1234        for (n, k) in names.iter().zip(&self.keys_out) {
1235            carry.staff_keys.insert(n.clone(), *k);
1236        }
1237        carry.reprints |= self.reprints;
1238        // (the score's time said anew is every staff's again, those not printed here too)
1239        let said = (self.bars.iter()).fold((false, self.prev_time), |(said, was), b| {
1240            (said || b.time != was, b.time)
1241        });
1242        if said.0 {
1243            carry.staff_times.clear();
1244            carry.time_signs.clear();
1245        }
1246        carry.time = self.bars.last().map(|b| b.time).unwrap_or(carry.time);
1247        if let Some(last) = self.bars.last() {
1248            for (n, t) in names.iter().zip(&last.times) {
1249                carry.staff_times.insert(n.clone(), *t);
1250            }
1251            let signs = (names.iter().cloned()).zip(last.time_signs.iter().copied());
1252            for (n, sign) in signs.chain([(String::new(), last.time_sign)]) {
1253                match sign {
1254                    Some(sign) => carry.time_signs.insert(n, sign),
1255                    None => carry.time_signs.remove(&n),
1256                };
1257            }
1258        }
1259        carry.every_staff_times = self.every_staff_times;
1260        for (n, c) in names.iter().zip(&self.end_clefs) {
1261            carry.clef.insert(n.clone(), c);
1262        }
1263        carry.ties = self.ties_out.clone();
1264        let mut slurs = self.slurs_in_left.clone();
1265        for (k, v) in &self.slurs_out {
1266            *slurs.entry(k.clone()).or_default() += v;
1267        }
1268        carry.slurs = slurs;
1269        for (k, v) in &self.slur_stems {
1270            carry.slur_stems.insert(k.clone(), *v);
1271        }
1272        carry.starts_with = self.ends_with_start;
1273        carry.next_bar = self.last_bar + 1;
1274    }
1275}
1276
1277/// Dynamics' letters, in order of place, as words: each letter joins the word it follows close
1278/// on at its height (two dynamics one over the other, as two staves' are, are two words).
1279fn dynamic_words(letters: Vec<&Glyph>, sp: f64) -> Vec<Vec<&Glyph>> {
1280    let mut words: Vec<Vec<&Glyph>> = Vec::new();
1281    for g in letters {
1282        match words.iter_mut().rev().find(|w| {
1283            g.x0 - w.last().unwrap().x1 < 0.3 * sp && (g.y - w.last().unwrap().y).abs() < 0.5 * sp
1284        }) {
1285            Some(w) => w.push(g),
1286            None => words.push(vec![g]),
1287        }
1288    }
1289    words
1290}
1291
1292/// A bar's events with its duplets (a 2, read as 2 in the time of 3) read as plain notes: in
1293/// simple time a 2 after triplets marks notes no longer in threes. None when it has none.
1294fn without_duplets(evs: &[Ev]) -> Option<Vec<Ev>> {
1295    if !evs
1296        .iter()
1297        .any(|e| e.tuplets.iter().any(|t| (t.0, t.1) == (2, 3)))
1298    {
1299        return None;
1300    }
1301    Some(
1302        evs.iter()
1303            .cloned()
1304            .map(|mut e| {
1305                let n = e.tuplets.len();
1306                e.tuplets.retain(|t| (t.0, t.1) != (2, 3));
1307                for _ in e.tuplets.len()..n {
1308                    e.dur = e.dur * Q::new(2, 3);
1309                }
1310                e
1311            })
1312            .collect(),
1313    )
1314}
1315
1316/// Barlines drawn as thin as the stems: at one place across the system, lines that each run from
1317/// a staff's top line to a staff's bottom line, end to end, and between them cross every staff
1318/// (one line through the system, or one for the voice's staff and one for the piano's two). A
1319/// stem ends where its notes are. The system's last barline, at its staves' right end, must be
1320/// among them: where it is not, these are not its barlines.
1321fn full_height_lines(pg: &Page, staves: &[Staff], sp: f64, left: f64, right: f64) -> Vec<f64> {
1322    let near = 0.15 * sp;
1323    let at_top = |y: f64| staves.iter().any(|s| (s.top() - y).abs() <= near);
1324    let at_bottom = |y: f64| staves.iter().any(|s| (s.bottom() - y).abs() <= near);
1325    let mut by_x: BTreeMap<i64, Vec<&crate::page::VLine>> = BTreeMap::new();
1326    for v in pg.vlines.iter().filter(|v| {
1327        // (the closing barline may stand a little past the staff lines' end)
1328        at_top(v.y0) && at_bottom(v.y1) && left - 0.2 * sp <= v.x && v.x <= right + 0.4 * sp
1329    }) {
1330        by_x.entry((v.x * 10.0).round() as i64).or_default().push(v);
1331    }
1332    let xs: Vec<f64> = by_x
1333        .into_iter()
1334        .filter(|(_, vs)| {
1335            staves.iter().all(|s| {
1336                vs.iter()
1337                    .any(|v| v.y0 <= s.top() + near && s.bottom() - near <= v.y1)
1338            })
1339        })
1340        .map(|(x, _)| x as f64 / 10.0)
1341        .collect();
1342    // (or, where the staff runs on a little past its last barline, nothing but a change of key,
1343    // time or clef announced for the next system stands after it: no note, no rest)
1344    let announces = |last: f64| {
1345        let (top, bottom) = (staves[0].top(), staves[staves.len() - 1].bottom());
1346        right - last < 10.0 * sp
1347            && !pg.glyphs.iter().any(|g| {
1348                g.x0 > last
1349                    && g.x0 < right
1350                    && top - 4.0 * sp < g.y
1351                    && g.y < bottom + 4.0 * sp
1352                    && (smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
1353            })
1354            && pg.glyphs.iter().any(|g| {
1355                g.x0 > last
1356                    && g.x0 < right
1357                    && top - sp < g.y
1358                    && g.y < bottom + sp
1359                    && (smufl::accidental(g.code).is_some()
1360                        || smufl::is_time(g.code)
1361                        || smufl::clef(g.code).is_some())
1362            })
1363    };
1364    if xs.iter().any(|x| (x - right).abs() <= 0.5 * sp)
1365        || xs
1366            .last()
1367            .is_some_and(|&last| xs.len() >= 2 && announces(last))
1368    {
1369        xs
1370    } else {
1371        Vec::new()
1372    }
1373}
1374
1375/// Barlines drawn thinner than the stems (capella's): the lines thinner than the page's stems that
1376/// run from a staff's top line to a staff's bottom line through every staff of the system. No stem
1377/// is thinner than the stems, so these are told from them where `full_height_lines` cannot be
1378/// (a thick closing barline is there too, and the width test finds only that).
1379fn thinner_than_stems(pg: &Page, staves: &[Staff], sp: f64, left: f64, right: f64) -> Vec<f64> {
1380    let stem = pg.stem_width(sp);
1381    let near = 0.15 * sp;
1382    let at_top = |y: f64| staves.iter().any(|s| (s.top() - y).abs() <= near);
1383    let at_bottom = |y: f64| staves.iter().any(|s| (s.bottom() - y).abs() <= near);
1384    let mut by_x: BTreeMap<i64, Vec<&crate::page::VLine>> = BTreeMap::new();
1385    for v in pg.vlines.iter().filter(|v| {
1386        v.w < stem - 0.04
1387            && at_top(v.y0)
1388            && at_bottom(v.y1)
1389            && left - 0.2 * sp <= v.x
1390            && v.x <= right + 0.4 * sp
1391    }) {
1392        by_x.entry((v.x * 10.0).round() as i64).or_default().push(v);
1393    }
1394    by_x.into_iter()
1395        .filter(|(_, vs)| {
1396            staves.iter().all(|s| {
1397                vs.iter()
1398                    .any(|v| v.y0 <= s.top() + near && s.bottom() - near <= v.y1)
1399            })
1400        })
1401        .map(|(x, _)| x as f64 / 10.0)
1402        .collect()
1403}
1404
1405/// Whether a glyph is a notehead well out past a staff's outer line `edge` (`dir` -1 above, 1
1406/// below), further than the staff's ledger lines there reach: it is not that staff's.
1407fn other_systems_head(pg: &Page, h: &Glyph, edge: f64, dir: f64, sp: f64) -> bool {
1408    if smufl::head(h.code).is_none() || (h.y - edge) * dir < 3.0 * sp {
1409        return false;
1410    }
1411    // its ledger lines, each about a space past the one before (some programs set them off the
1412    // staff's spacing)
1413    let mut at = edge;
1414    while let Some(l) = pg.hlines.iter().find(|l| {
1415        let past = (l.y - at) * dir;
1416        0.5 * sp < past
1417            && past < 1.5 * sp
1418            && l.x0 <= h.x0 + 0.3 * sp
1419            && l.x1 >= h.x1 - 0.3 * sp
1420            && l.x1 - l.x0 < 6.0 * sp
1421    }) {
1422        at = l.y;
1423    }
1424    // the last ledger, or the staff's edge: its own head is on it or just past it
1425    (h.y - at) * dir >= 0.75 * sp
1426}
1427
1428/// The top of the system after `si` on its page, or 0 when it is the page's last.
1429fn next_system_top(systems: &[System], si: usize) -> f64 {
1430    systems
1431        .get(si + 1)
1432        .filter(|n| n.page == systems[si].page)
1433        .and_then(|n| n.staves.first())
1434        .map_or(0.0, |s| s.top())
1435}
1436
1437/// The bottom of the last staff's band: six spaces under it, but no lower than halfway to the
1438/// system below on the page (a high note of that system's first staff is that staff's).
1439fn last_staff_ceiling(bottom: f64, sp: f64, floor: f64) -> f64 {
1440    let hi = bottom + 6.0 * sp;
1441    if floor > bottom {
1442        hi.min((bottom + floor) / 2.0)
1443    } else {
1444        hi
1445    }
1446}
1447
1448/// The top of the first staff's band: six spaces over it, but no higher than halfway to the
1449/// system above on the page (a low note of that system's last staff, on ledger lines, is
1450/// that staff's).
1451fn first_staff_floor(top: f64, sp: f64, ceiling: f64) -> f64 {
1452    let lo = top - 6.0 * sp;
1453    if ceiling > 0.0 && ceiling < top {
1454        lo.max((ceiling + top) / 2.0)
1455    } else {
1456        lo
1457    }
1458}
1459
1460/// The foot of a system's last staff's band: 6 spaces under it, or halfway to the next staff
1461/// down the page when that is nearer (a system set close above the next one: a note over the
1462/// next system's top staff is that staff's).
1463fn band_floor(pg: &Page, last: &Staff, sp: f64) -> f64 {
1464    let below = pg
1465        .staves()
1466        .iter()
1467        .map(|s| s.top())
1468        .filter(|&t| t > last.bottom() + 0.5 * sp)
1469        .fold(f64::MAX, f64::min);
1470    (last.bottom() + 6.0 * sp).min((last.bottom() + below) / 2.0)
1471}
1472
1473/// What a staff's voices hold of a bar: its longest voice's time; none where it only rests
1474/// through the bar.
1475fn held_by(voices: &[Vec<Ev>]) -> Option<Q> {
1476    voices
1477        .iter()
1478        .filter(|v| v.iter().any(|e| e.rest != crate::staff::Rest::Bar))
1479        .map(|v| v.iter().map(|e| e.takes()).sum::<Q>())
1480        .max()
1481}
1482
1483/// A bar that may be short (a score's first or last), read so: where one staff's notes fill the
1484/// whole bar, the bar is not short, and each staff read as shorter (some of its rests hidden) is
1485/// read again as in any other bar: its voices fill the bar or it is left unread. Where the bar is
1486/// short and the staves with notes agree how long it is (and one staff more, of notes or rests),
1487/// a staff of rests alone that rests for less has rests hidden too: it rests through the bar.
1488fn not_short_where_filled(voices: &mut BarVoices, evs: &[Vec<Ev>], sp: f64, len: Q, right: f64) {
1489    let noted = |vs: &Vec<Vec<Ev>>| vs.iter().flatten().any(|e| e.is_note());
1490    let lengths: BTreeSet<Q> = voices
1491        .iter()
1492        .filter_map(|v| v.as_ref().ok())
1493        .filter(|vs| noted(vs))
1494        .filter_map(|vs| held_by(vs))
1495        .collect();
1496    let Some(&longest) = lengths.iter().next_back() else {
1497        return;
1498    };
1499    // (agreed: by every staff with notes, and by two staves at least)
1500    let as_long =
1501        |v: &Result<Vec<Vec<Ev>>, String>| v.as_ref().is_ok_and(|vs| held_by(vs) == Some(longest));
1502    let agreed = lengths.len() == 1 && voices.iter().filter(|v| as_long(v)).count() >= 2;
1503    for (v, ev) in voices.iter_mut().zip(evs) {
1504        let shorter = v.as_ref().is_ok_and(|vs| {
1505            held_by(vs).is_some_and(|h| h < longest) && (longest == len || !noted(vs))
1506        });
1507        if shorter && (longest == len || agreed) {
1508            *v = voices_of(ev.clone(), sp, longest, Some(right), false).map_err(|e| e.0);
1509        }
1510    }
1511}
1512
1513/// Whether a staff's voices were filled out with blank time (rests the program hid).
1514fn padded(voices: &[Vec<Ev>]) -> bool {
1515    let blank = |e: &Ev| e.rest == crate::staff::Rest::Blank;
1516    voices.iter().flatten().any(blank)
1517}
1518
1519/// A bar shorter than its time where some staff has two voices, one with rests hidden: the bar's
1520/// length is what two staves at least, each a single line of notes and rests, both hold; and it
1521/// is the bar's if every staff then reads as a whole bar of that length with nothing over. The
1522/// staves' voices so read.
1523fn short_as_its_lines_say(
1524    evs: &[Vec<Ev>],
1525    sp: f64,
1526    len: Q,
1527    right: f64,
1528) -> Option<Vec<Vec<Vec<Ev>>>> {
1529    let lines: Vec<Q> = evs
1530        .iter()
1531        .filter_map(|ev| voices_of(ev.clone(), sp, len, Some(right), true).ok())
1532        .filter(|vs| vs.len() == 1 && vs[0].iter().any(|e| e.is_note()) && !padded(vs))
1533        .filter_map(|vs| held_by(&vs))
1534        .collect();
1535    let short = *lines.first()?;
1536    if lines.len() < 2 || lines.iter().any(|&l| l != short) || short >= len {
1537        return None;
1538    }
1539    let read: Vec<Vec<Vec<Ev>>> = evs
1540        .iter()
1541        .map(|ev| voices_of(ev.clone(), sp, short, Some(right), false).ok())
1542        .collect::<Option<_>>()?;
1543    let whole = read.iter().all(|vs| held_by(vs).is_none_or(|h| h == short));
1544    whole.then_some(read)
1545}
1546
1547/// A note whose head another voice shares is printed without its dot by some programs (the
1548/// other voice's note has none). Where such a note is beamed to the next note of its voice and
1549/// the voice was given blank time between the two, half the note's length, the time is the
1550/// note's dot: no rest hides inside a beam. So too where the blank time was put after the second
1551/// note, and that note stands well right of what the staff's other voice has at the time it was
1552/// given, and nowhere else than what it has half the first note's length later.
1553fn dots_hidden_under_a_beam(voices: &mut [Vec<Ev>], sp: f64) {
1554    let blank = |e: &Ev| e.rest == crate::staff::Rest::Blank;
1555    let same = |a: &Glyph, b: &Glyph| a.x0 == b.x0 && a.y == b.y;
1556    // where the other voices have something printed at a time
1557    let others_at = |vs: &[Vec<Ev>], vi: usize, at: Q| -> Vec<f64> {
1558        let mut xs = Vec::new();
1559        for v in (vs.iter().enumerate()).filter(|(vj, _)| *vj != vi) {
1560            let mut t = Q::ZERO;
1561            for e in v.1 {
1562                if t == at && !blank(e) && e.grace.is_none() {
1563                    xs.push(e.x);
1564                }
1565                t += e.takes();
1566            }
1567        }
1568        xs
1569    };
1570    for vi in 0..voices.len() {
1571        let (mut k, mut t) = (0, Q::ZERO);
1572        while k + 2 < voices[vi].len() {
1573            let a = &voices[vi][k];
1574            let half = a.dur / Q::int(2);
1575            let dotless =
1576                a.is_note() && a.grace.is_none() && a.tuplets.is_empty() && a.dur.is_power_of_two();
1577            let shared = (voices.iter().enumerate())
1578                .filter(|(vj, _)| *vj != vi)
1579                .flat_map(|(_, v)| v.iter())
1580                .any(|o| o.heads.iter().any(|h| a.heads.iter().any(|g| same(g, h))));
1581            let beamed =
1582                |b: &Ev| b.is_note() && a.beam_polys.intersection(&b.beam_polys).next().is_some();
1583            let (m, n) = (&voices[vi][k + 1], &voices[vi][k + 2]);
1584            // the note, blank time, the note beamed to it
1585            let between = blank(m) && m.dur == half && beamed(n);
1586            // the note, the note beamed to it, blank time: the second note's place says when
1587            let after = beamed(m) && blank(n) && n.dur == half && {
1588                let now = others_at(voices, vi, t + a.dur);
1589                let then = others_at(voices, vi, t + a.dur + half);
1590                now.iter().any(|x| m.x - x > 0.8 * sp)
1591                    && then.iter().all(|x| (m.x - x).abs() < 0.8 * sp)
1592            };
1593            t += a.takes();
1594            if dotless && shared && (between || after) {
1595                voices[vi][k].dur += half;
1596                voices[vi].remove(if between { k + 1 } else { k + 2 });
1597                t += half;
1598            }
1599            k += 1;
1600        }
1601    }
1602}
1603
1604/// A bar's rest standing for a staff's bar: one left unread, or with nothing in it.
1605fn bar_rest(len: Q, x: f64) -> Ev {
1606    let mut rest = Ev::spacer(len, x);
1607    rest.rest = crate::staff::Rest::Bar;
1608    rest
1609}
1610
1611/// Staff `i`'s band of the page, top and bottom: halfway to the staves either side, and for a
1612/// system's outer staves six spaces out or halfway to the system beside.
1613fn staff_band(
1614    pg: &Page,
1615    mine: &[Staff],
1616    i: usize,
1617    sp: f64,
1618    ceiling: f64,
1619    floor: f64,
1620) -> (f64, f64) {
1621    let lo = if i == 0 {
1622        first_staff_floor(mine[0].top(), sp, ceiling)
1623    } else {
1624        (mine[i - 1].bottom() + mine[i].top()) / 2.0
1625    };
1626    let hi = if i + 1 == mine.len() {
1627        last_staff_ceiling(mine[i].bottom(), sp, floor).min(band_floor(pg, &mine[i], sp))
1628    } else {
1629        (mine[i].bottom() + mine[i + 1].top()) / 2.0
1630    };
1631    (lo, hi)
1632}
1633
1634/// The heads out past a system's outer staff's band (`band` its limit, `dir` -1 above the staff's
1635/// top line `edge`, 1 below its bottom line) that the staff's ledger lines reach, a line to each
1636/// space all the way: they are the staff's however far out (a low bass note seven lines under),
1637/// and are added to its glyphs with their accidentals and dots.
1638fn past_band(
1639    pg: &Page,
1640    edge: f64,
1641    dir: f64,
1642    band: f64,
1643    sides: (f64, f64),
1644    sp: f64,
1645    glyphs: &mut Vec<Glyph>,
1646) {
1647    let heads: Vec<Glyph> = pg
1648        .glyphs
1649        .iter()
1650        .filter(|h| {
1651            smufl::head(h.code).is_some()
1652                && sides.0 <= h.x0
1653                && h.x0 <= sides.1
1654                && (h.y - band) * dir > 0.0
1655                && (h.y - edge) * dir >= 3.0 * sp
1656                && (h.y - edge) * dir < 16.0 * sp
1657                && !other_systems_head(pg, h, edge, dir, sp)
1658        })
1659        .copied()
1660        .collect();
1661    for h in heads {
1662        let goes = |g: &Glyph| {
1663            let off = if g.code == smufl::DOT { 0.7 } else { 0.3 };
1664            (g.y - h.y).abs() < off * sp
1665                && g.x0 > h.x0 - 4.0 * sp
1666                && g.x0 < h.x1 + 2.0 * sp
1667                && (g.x0 == h.x0 && g.code == h.code
1668                    || smufl::accidental(g.code).is_some()
1669                    || g.code == smufl::DOT)
1670        };
1671        for g in pg.glyphs.iter().filter(|g| goes(g)) {
1672            if !glyphs
1673                .iter()
1674                .any(|o| o.code == g.code && o.x0 == g.x0 && o.y == g.y)
1675            {
1676                glyphs.push(*g);
1677            }
1678        }
1679    }
1680}
1681
1682/// What stands in a staff's bar that was read as holding nothing, if anything does: a notehead
1683/// or a rest in the staff's `band` between the bar's two `sides` that no other staff's bar
1684/// (`theirs`) took, or a stem through the staff's lines that is none of theirs. A bar with any of
1685/// these is not empty: something of it was passed over (a head out past the ledger lines, a rest
1686/// far off the staff, a head of a shape not known).
1687fn left_in_empty_bar(
1688    pg: &Page,
1689    staff: &Staff,
1690    band: (f64, f64),
1691    sides: (f64, f64),
1692    sp: f64,
1693    theirs: &[&Ev],
1694) -> Option<&'static str> {
1695    let (l, r) = sides;
1696    // any notehead, note or rest of the music font, known or not
1697    let of_a_note = |c: u32| {
1698        smufl::head(c).is_some()
1699            || smufl::rest(c).is_some()
1700            || (0xE0A0..=0xE21F).contains(&c)
1701            || (0xE4E0..=0xE4FF).contains(&c)
1702    };
1703    let taken = |g: &Glyph| {
1704        theirs.iter().any(|e| {
1705            e.heads.iter().any(|h| h.x0 == g.x0 && h.y == g.y)
1706                || matches!(&e.rest, crate::staff::Rest::Printed(p) if p.x0 == g.x0 && p.y == g.y)
1707        })
1708    };
1709    let inside = |g: &&Glyph| l < g.x0 && g.x0 < r && band.0 <= g.y && g.y <= band.1;
1710    if pg
1711        .glyphs
1712        .iter()
1713        .filter(inside)
1714        .any(|g| of_a_note(g.code) && !taken(g))
1715    {
1716        return Some("a notehead or a rest stands in it");
1717    }
1718    let line_w = pg.barline_width(sp);
1719    let stem = pg.vlines.iter().any(|v| {
1720        l + 0.3 * sp < v.x
1721            && v.x < r - 0.3 * sp
1722            && v.w < line_w
1723            && v.y1 - v.y0 > 1.2 * sp
1724            && v.y0 < staff.bottom()
1725            && v.y1 > staff.top()
1726            && !pg.in_frame(v.x, (v.y0 + v.y1) / 2.0)
1727            && !theirs
1728                .iter()
1729                .any(|e| e.stem.is_some_and(|s| s.x == v.x && s.y0 == v.y0))
1730    });
1731    stem.then_some("a stem stands in it")
1732}
1733
1734/// Whether nothing of a note is printed on a staff where a voice of it was read as having
1735/// blank time: no beam that is none of the bar's notes', and no accidental standing clear of
1736/// the note after it. (A beam or a sharp with no note under it is a note that was not read.)
1737fn nothing_where_blank(
1738    pg: &Page,
1739    staff: &Staff,
1740    voice: &[Ev],
1741    sides: (f64, f64),
1742    sp: f64,
1743    theirs: &[&Ev],
1744) -> bool {
1745    let (top, bottom) = (staff.top() - 3.0 * sp, staff.bottom() + 3.0 * sp);
1746    let blank = |e: &Ev| e.rest == crate::staff::Rest::Blank;
1747    (0..voice.len()).filter(|&k| blank(&voice[k])).all(|k| {
1748        let before = voice[..k]
1749            .iter()
1750            .rev()
1751            .find(|e| !blank(e) && e.grace.is_none());
1752        let after = voice[k + 1..].iter().find(|e| !blank(e));
1753        let x0 = before.map_or(sides.0, |e| e.x + 1.5 * sp);
1754        let x1 = after.map_or(sides.1, |e| e.x);
1755        let beam = pg.polys.iter().enumerate().any(|(n, poly)| {
1756            let xs = poly.iter().map(|p| p.0);
1757            let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |a, x| (a.0.min(x), a.1.max(x)));
1758            let y = poly.iter().map(|p| p.1).sum::<f64>() / poly.len().max(1) as f64;
1759            lo.max(x0) + 0.5 * sp < hi.min(x1)
1760                && top < y
1761                && y < bottom
1762                && !theirs.iter().any(|e| e.beam_polys.contains(&n))
1763        });
1764        let sign = pg.glyphs.iter().any(|g| {
1765            smufl::accidental(g.code).is_some()
1766                && x0 < g.x0
1767                && g.x1 < x1 - 4.5 * sp
1768                && top < g.y
1769                && g.y < bottom
1770        });
1771        !beam && !sign
1772    })
1773}
1774
1775/// Whether a notehead or a rest of the music font stands in a staff's `band` between the bar's
1776/// `sides` that none of the bar's events (`theirs`) took: a note the solver was not given. (An
1777/// augmentation dot is no note's head: a solved bar's dotted notes have them.)
1778fn head_passed_over(pg: &Page, band: (f64, f64), sides: (f64, f64), theirs: &[&Ev]) -> bool {
1779    let of_a_note = |c: u32| {
1780        c != 0xE1E7
1781            && (smufl::head(c).is_some()
1782                || smufl::rest(c).is_some()
1783                || (0xE0A0..=0xE21F).contains(&c)
1784                || (0xE4E0..=0xE4FF).contains(&c))
1785    };
1786    let taken = |g: &Glyph| {
1787        theirs.iter().any(|e| {
1788            e.heads.iter().any(|h| h.x0 == g.x0 && h.y == g.y)
1789                || matches!(&e.rest, crate::staff::Rest::Printed(p) if p.x0 == g.x0 && p.y == g.y)
1790        })
1791    };
1792    let inside = |g: &&Glyph| sides.0 < g.x0 && g.x0 < sides.1 && band.0 <= g.y && g.y <= band.1;
1793    (pg.glyphs.iter())
1794        .filter(inside)
1795        .any(|g| of_a_note(g.code) && !taken(g))
1796}
1797
1798/// A bar's unread staves solved by `spacing::solve`, where a read staff's notes fill the bar (its
1799/// length is then sure), every staff is in the score's time, and nothing printed in a solved
1800/// staff's bar was passed over. One entry a staff: its voices if solved.
1801#[allow(clippy::too_many_arguments, clippy::type_complexity)]
1802fn spaced(
1803    pg: &Page,
1804    mine: &[Staff],
1805    names: &[String],
1806    events: &[Vec<Ev>],
1807    voices: &BarVoices,
1808    own: &[Option<(i64, i64)>],
1809    sp: f64,
1810    (len, sides, (ceiling, floor)): (Q, (f64, f64), (f64, f64)),
1811) -> Vec<Option<Vec<Vec<Ev>>>> {
1812    let none = vec![None; voices.len()];
1813    let full = voices.iter().any(|v| {
1814        v.as_ref()
1815            .is_ok_and(|vs| vs.iter().flatten().any(|e| e.is_note()) && !padded(vs))
1816    });
1817    if !full || voices.iter().all(|v| v.is_ok()) || own.iter().any(|t| t.is_some()) {
1818        return none;
1819    }
1820    let parts: Vec<&str> = (names.iter())
1821        .map(|n| n.split('.').next().unwrap_or(n))
1822        .collect();
1823    let staves: Vec<crate::spacing::StaffIn> = (0..voices.len())
1824        .map(|i| crate::spacing::StaffIn {
1825            part: parts[i],
1826            events: &events[i],
1827            read: voices[i].as_ref().ok().map(|v| &v[..]),
1828        })
1829        .collect();
1830    let mut solved = crate::spacing::solve(&staves, sp, len, sides.1);
1831    // (a dot two voices' notes share: solved once for each way it may be given out)
1832    if matches!(solved, Err(e) if e == crate::spacing::UNSURE) {
1833        if let Some(one) = crate::dotways::solve(&staves, sp, len, sides.1) {
1834            solved = Ok(one);
1835        }
1836    }
1837    let Ok(mut solved) = solved else {
1838        return none;
1839    };
1840    let theirs: Vec<&Ev> = events.iter().flatten().collect();
1841    for (i, vs) in solved.iter_mut().enumerate() {
1842        let band = staff_band(pg, mine, i, sp, ceiling, floor);
1843        let clean = |vs: &Vec<Vec<Ev>>| {
1844            !head_passed_over(pg, band, sides, &theirs)
1845                && (vs.iter()).all(|v| nothing_where_blank(pg, &mine[i], v, sides, sp, &theirs))
1846        };
1847        if vs.as_ref().is_some_and(|vs| !clean(vs)) {
1848            return none;
1849        }
1850    }
1851    solved
1852}
1853
1854/// An empty staff's bar, held so far as a bar's rest, made blank time of the bar's length
1855/// (where the format has lengths for it).
1856fn blank_if_bar_rest(voices: &mut [Vec<Ev>], len: Q) {
1857    let [v] = voices else { return };
1858    let [e] = &mut v[..] else { return };
1859    if e.rest == crate::staff::Rest::Bar && crate::write::plain_lengths(len).is_ok() {
1860        e.rest = crate::staff::Rest::Blank;
1861        e.dur = len;
1862    }
1863}
1864
1865#[allow(clippy::too_many_arguments)]
1866fn read_system(
1867    pg: &Page,
1868    sys: &System,
1869    names: &[String],
1870    carry: &mut Carry,
1871    first_piece: bool,
1872    last_piece: bool,
1873    ceiling: f64,
1874    floor: f64,
1875    sung: &BTreeSet<usize>,
1876) -> Res<SystemRead> {
1877    let mine = &sys.staves;
1878    let sp = mine[0].sp();
1879    let left = mine.iter().map(|s| s.left).fold(f64::MAX, f64::min);
1880    let right = mine.iter().map(|s| s.right).fold(f64::MIN, f64::max);
1881    let top0 = mine[0].top();
1882    let bot0 = mine[0].bottom();
1883    // each staff's glyphs: its own band, halfway to the staves either side
1884    let staff_glyphs: Vec<Vec<Glyph>> = (0..mine.len())
1885        .map(|i| {
1886            let lo = if i == 0 {
1887                first_staff_floor(mine[0].top(), sp, ceiling)
1888            } else {
1889                (mine[i - 1].bottom() + mine[i].top()) / 2.0
1890            };
1891            let hi = if i + 1 == mine.len() {
1892                last_staff_ceiling(mine[i].bottom(), sp, floor).min(band_floor(pg, &mine[i], sp))
1893            } else {
1894                (mine[i].bottom() + mine[i + 1].top()) / 2.0
1895            };
1896            pg.glyphs
1897                .iter()
1898                .filter(|g| lo <= g.y && g.y <= hi && left - 2.0 * sp <= g.x0 && g.x0 <= right + sp)
1899                .copied()
1900                .collect()
1901        })
1902        .collect();
1903    // a note between two staves is the staff's whose ledger lines reach it (halfway is only a
1904    // guess): it goes there with its accidentals and dots
1905    let mut staff_glyphs = staff_glyphs;
1906    // a head out past the system's outer staves that no ledger line of theirs reaches, toward
1907    // the system beside on the page, is that system's
1908    let last = mine.len() - 1;
1909    if ceiling > 0.0 {
1910        staff_glyphs[0].retain(|g| !other_systems_head(pg, g, mine[0].top(), -1.0, sp));
1911    }
1912    if floor > 0.0 {
1913        staff_glyphs[last].retain(|g| !other_systems_head(pg, g, mine[last].bottom(), 1.0, sp));
1914    }
1915    for i in 0..mine.len().saturating_sub(1) {
1916        let (above, below) = (mine[i].bottom(), mine[i + 1].top());
1917        let ledgers_reach = |h: &Glyph, from: f64, dir: f64| -> bool {
1918            let mut k = 1;
1919            loop {
1920                let y = from + dir * k as f64 * sp;
1921                let found = pg.hlines.iter().any(|l| {
1922                    (l.y - y).abs() < 0.15 * sp
1923                        && l.x0 <= h.x0 + 0.3 * sp
1924                        && l.x1 >= h.x1 - 0.3 * sp
1925                        && l.x1 - l.x0 < 4.0 * sp
1926                });
1927                if !found {
1928                    break;
1929                }
1930                k += 1;
1931            }
1932            // the last ledger, or the staff's edge: the head on it or just past it
1933            let edge = from + dir * (k - 1) as f64 * sp;
1934            (h.y - edge) * dir < 0.75 * sp && ledgers_end_at_a_head(pg, h, edge, k, sp)
1935        };
1936        let gap = |h: &Glyph| above + 0.6 * sp < h.y && h.y < below - 0.6 * sp;
1937        let heads: Vec<(usize, Glyph)> = [i, i + 1]
1938            .iter()
1939            .flat_map(|&s| {
1940                staff_glyphs[s]
1941                    .iter()
1942                    .filter(|g| smufl::head(g.code).is_some() && gap(g))
1943                    .map(move |g| (s, *g))
1944            })
1945            .collect();
1946        for (from_staff, h) in heads {
1947            let up = ledgers_reach(&h, above, 1.0);
1948            let down = ledgers_reach(&h, below, -1.0);
1949            let to = match (up, down) {
1950                (true, false) => i,
1951                (false, true) => i + 1,
1952                _ => continue,
1953            };
1954            if to == from_staff {
1955                continue;
1956            }
1957            // (a dot a half space off: its head is on a line)
1958            let goes = |g: &Glyph| {
1959                let off = if g.code == smufl::DOT { 0.7 } else { 0.3 };
1960                (g.y - h.y).abs() < off * sp
1961                    && g.x0 > h.x0 - 4.0 * sp
1962                    && g.x0 < h.x1 + 2.0 * sp
1963                    && (g.x0 == h.x0 && g.code == h.code
1964                        || smufl::accidental(g.code).is_some()
1965                        || g.code == smufl::DOT)
1966            };
1967            let moved: Vec<Glyph> = staff_glyphs[from_staff]
1968                .iter()
1969                .filter(|g| goes(g))
1970                .copied()
1971                .collect();
1972            staff_glyphs[from_staff].retain(|g| !goes(g));
1973            staff_glyphs[to].extend(moved);
1974        }
1975    }
1976    above_system(pg, &mine[0], ceiling, &mut staff_glyphs[0]);
1977    // a head out past an outer staff's band on ledger lines that reach it from the staff
1978    let band = staff_band(pg, mine, 0, sp, ceiling, floor).0;
1979    let sides = (left - 2.0 * sp, right + sp);
1980    past_band(
1981        pg,
1982        mine[0].top(),
1983        -1.0,
1984        band,
1985        sides,
1986        sp,
1987        &mut staff_glyphs[0],
1988    );
1989    let band = staff_band(pg, mine, last, sp, ceiling, floor).1;
1990    past_band(
1991        pg,
1992        mine[last].bottom(),
1993        1.0,
1994        band,
1995        sides,
1996        sp,
1997        &mut staff_glyphs[last],
1998    );
1999    let first_event = staff_glyphs
2000        .iter()
2001        .flatten()
2002        .filter(|g| smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
2003        .map(|g| g.x0)
2004        .chain(multi_rests(pg, &mine[0], sp).into_iter().map(|m| m.0))
2005        .fold(right, f64::min);
2006    // barlines: thick or thin lines through the top staff
2007    let line_w = pg.barline_width(sp);
2008    let mut xs: Vec<f64> = pg
2009        .vlines
2010        .iter()
2011        .filter(|v| {
2012            v.w >= line_w
2013                && v.y0 <= top0 + 0.4 * sp
2014                && v.y1 >= bot0 - 0.4 * sp
2015                && left - 0.2 * sp <= v.x
2016                && v.x <= right + 0.2 * sp
2017        })
2018        .map(|v| (v.x * 10.0).round() / 10.0)
2019        .collect();
2020    // (none past the first note: the only wide line is the system's opening repeat sign)
2021    if !xs.iter().any(|&x| x - left > 3.0 * sp && x >= first_event) {
2022        xs.extend(full_height_lines(pg, mine, sp, left, right));
2023    }
2024    xs.extend(thinner_than_stems(pg, mine, sp, left, right));
2025    xs.sort_by(f64::total_cmp);
2026    xs.dedup();
2027    let mut groups: Vec<Vec<f64>> = Vec::new();
2028    for x in xs {
2029        match groups.last_mut() {
2030            Some(g) if x - g.last().unwrap() < 2.5 * sp => g.push(x),
2031            _ => groups.push(vec![x]),
2032        }
2033    }
2034    // a barline before the first note is the system's opening (a repeat's start after the key)
2035    let opening: Vec<Vec<f64>> = groups
2036        .iter()
2037        .filter(|g| g.last().unwrap() - left > 3.0 * sp && *g.last().unwrap() < first_event)
2038        .cloned()
2039        .collect();
2040    let groups: Vec<Vec<f64>> = groups
2041        .into_iter()
2042        .filter(|g| g.last().unwrap() - left > 3.0 * sp && *g.last().unwrap() >= first_event)
2043        .collect();
2044    // a barline that only closes a break in the lines (the coda's start, set apart) ends no bar
2045    let mut groups = groups;
2046    let mut k = 1;
2047    while k < groups.len() {
2048        let (from, to) = (*groups[k - 1].last().unwrap(), groups[k][0]);
2049        if mine[0]
2050            .breaks
2051            .iter()
2052            .any(|&(a, b)| a < from + 1.0 * sp && b > to - 1.0 * sp)
2053        {
2054            groups.remove(k);
2055        } else {
2056            k += 1;
2057        }
2058    }
2059    // (a system with no barline at all is a piece of a bar that runs on over its end)
2060    let continues = carry.runs.open;
2061    if !crate::longbars::all_one_piece(&mut carry.runs, groups.len(), sys.page, &staff_glyphs)
2062        && groups.is_empty()
2063    {
2064        return Err(Untaken::new(crate::longbars::NO_BARLINES));
2065    }
2066    carry.runs.open = match groups.is_empty() {
2067        true => Some(right),
2068        false => open_end(&staff_glyphs, &groups, right, sp),
2069    }
2070    .map(|end| groups.push(vec![end]))
2071    .is_some();
2072    let mut edges = vec![left];
2073    edges.extend(groups.iter().map(|g| g[0]));
2074    let mut styles: Vec<(Option<&'static str>, Option<&'static str>)> = Vec::new();
2075    for g in opening.iter().chain(groups.iter()) {
2076        let ws: Vec<(f64, f64)> = pg
2077            .vlines
2078            .iter()
2079            .filter(|v| {
2080                g.contains(&((v.x * 10.0).round() / 10.0)) && (v.y0 - top0).abs() <= 0.4 * sp
2081            })
2082            .map(|v| (v.w, v.x))
2083            .collect();
2084        let thick: Vec<f64> = ws
2085            .iter()
2086            .filter(|(w, _)| *w > 0.3 * sp)
2087            .map(|(_, x)| *x)
2088            .collect();
2089        let thin: Vec<f64> = ws
2090            .iter()
2091            .filter(|(w, _)| *w <= 0.3 * sp)
2092            .map(|(_, x)| *x)
2093            .collect();
2094        let dots: Vec<f64> = pg
2095            .glyphs
2096            .iter()
2097            .filter(|d| {
2098                smufl::is_repeat_dot(d.code)
2099                    && (d.x0 - g[0]).abs() < 2.5 * sp
2100                    && top0 - sp < d.y
2101                    && d.y < bot0 + sp
2102            })
2103            .map(|d| d.x0)
2104            .collect();
2105        let max = |v: &[f64]| v.iter().cloned().fold(f64::MIN, f64::max);
2106        let min = |v: &[f64]| v.iter().cloned().fold(f64::MAX, f64::min);
2107        let (mut end, mut start) = (None, None);
2108        if !thick.is_empty() && !dots.is_empty() && min(&dots) < min(&thick) {
2109            end = Some("repeat-end");
2110        }
2111        if !thick.is_empty() && !dots.is_empty() && max(&dots) > max(&thick) {
2112            start = Some("repeat-start");
2113        }
2114        if end.is_none() {
2115            if !thick.is_empty() && !thin.is_empty() && max(&thick) > max(&thin) {
2116                if dots.is_empty() {
2117                    end = Some("final");
2118                }
2119            } else if thin.len() >= 2 && thick.is_empty() {
2120                end = Some("double");
2121            }
2122        }
2123        styles.push((end, start));
2124    }
2125    let opens_with = if opening.is_empty() {
2126        None
2127    } else {
2128        styles[0].1
2129    };
2130    let styles = styles[opening.len()..].to_vec();
2131
2132    // clefs, key and time at the system's start
2133    let mut clefs = Vec::new();
2134    let mut clef_changes = Vec::new();
2135    for (i, gs) in staff_glyphs.iter().enumerate() {
2136        let clef = match (
2137            opening_clef(gs, &mine[i], first_event),
2138            carry.clef.get(&names[i]),
2139        ) {
2140            (Some(c), _) => c,
2141            (None, Some(c)) => c,
2142            (None, None) => return Err(Untaken::new("a staff with no clef at the start")),
2143        };
2144        // a clef other than the one before, or a staff's first that is not the format's default
2145        let before = carry.clef.get(&names[i]).copied();
2146        let change = match before {
2147            Some(b) => (b != clef).then_some(clef),
2148            None if !first_piece => Some(clef),
2149            None => None,
2150        };
2151        clefs.push(clef);
2152        clef_changes.push(change);
2153    }
2154    let g0 = &staff_glyphs[0];
2155    // the key signature: the accidentals before the first note, set evenly one after another;
2156    // one after a wider gap is the first note's own. A lone one beside a note at its height is
2157    // the note's.
2158    let mut before: Vec<&Glyph> = g0
2159        .iter()
2160        .filter(|g| smufl::accidental(g.code).is_some() && g.x0 < first_event && g.y < bot0 + sp)
2161        .collect();
2162    before.sort_by(|a, b| a.x0.total_cmp(&b.x0));
2163    let beside_note = |g: &Glyph| crate::key::beside_note(g, g0, 3.0, sp);
2164    let mut sig: Vec<&Glyph> = Vec::new();
2165    for g in before {
2166        let gap = sig.last().map(|p| g.x0 - p.x0);
2167        let step = if sig.len() >= 2 {
2168            Some(sig[1].x0 - sig[0].x0)
2169        } else {
2170            None
2171        };
2172        let fits = match (gap, step) {
2173            (None, _) => true,
2174            (Some(d), Some(s)) => d < 1.5 * s && d < 2.0 * sp,
2175            (Some(d), None) => d < 1.6 * sp,
2176        };
2177        if !fits {
2178            break;
2179        }
2180        sig.push(g);
2181    }
2182    if sig.len() == 1 && beside_note(sig[0]) {
2183        sig.clear();
2184    }
2185    // where the system's clefs, key and time end
2186    let opening_end = staff_glyphs
2187        .iter()
2188        .flatten()
2189        .filter(|g| {
2190            g.x0 < first_event
2191                && (smufl::clef(g.code).is_some()
2192                    || smufl::is_time(g.code)
2193                    || sig.iter().any(|s| (s.x0 - g.x0).abs() < 0.3 * sp))
2194        })
2195        .map(|g| g.x1 + 0.1)
2196        .fold(f64::MIN, f64::max)
2197        .max(left);
2198    let ev_x: Vec<f64> = staff_glyphs
2199        .iter()
2200        .flatten()
2201        .filter(|g| smufl::head(g.code).is_some() || smufl::rest(g.code).is_some())
2202        .map(|g| g.x1)
2203        .collect();
2204    // each staff's own time, bar by bar, and the score's
2205    let times = crate::times::read(
2206        &crate::times::Seen {
2207            staff_glyphs: &staff_glyphs,
2208            staves: mine,
2209            names,
2210            first_event,
2211            edges: &edges,
2212            ev_x: &ev_x,
2213            sp,
2214            size: pg.size,
2215        },
2216        &crate::times::Before {
2217            score: carry.time,
2218            staves: &carry.staff_times,
2219            signs: &carry.time_signs,
2220            every: carry.every_staff_times,
2221            top: &carry.top,
2222        },
2223    )?;
2224    let bar_times = &times.score;
2225    let len_of = |i: usize, b: usize| bar_len(times.at[i][b]);
2226    // (each staff's own time where it is not the bar's: the unnumbered tuplets leave it be)
2227    let own: Vec<Vec<Option<(i64, i64)>>> = (0..groups.len())
2228        .map(|b| {
2229            (times.at.iter())
2230                .map(|t| Some(t[b]).filter(|t| *t != bar_times[b]))
2231                .collect()
2232        })
2233        .collect();
2234    let first_number = if first_piece { 1 } else { carry.next_bar };
2235    if continues {
2236        carry.runs.joins.push(first_number);
2237    }
2238
2239    // clefs changed inside the system: each staff's clef from where it stands on
2240    let mut clef_runs: Vec<Vec<(f64, &'static str)>> = Vec::new();
2241    let mut clef_marks: Vec<(usize, f64, &'static str)> = Vec::new();
2242    for (i, gs) in staff_glyphs.iter().enumerate() {
2243        let mut run = vec![(f64::MIN, clefs[i])];
2244        let mut inner: Vec<&Glyph> = gs
2245            .iter()
2246            .filter(|g| clef_of(g, &mine[i]).is_some() && g.x0 > first_event)
2247            .collect();
2248        inner.sort_by(|a, b| a.x0.total_cmp(&b.x0));
2249        for g in inner {
2250            let c = clef_of(g, &mine[i]).unwrap();
2251            if c != run.last().unwrap().1 {
2252                run.push((g.x0, c));
2253                clef_marks.push((i, g.x1, c));
2254            }
2255        }
2256        clef_runs.push(run);
2257    }
2258    let end_clefs: Vec<&'static str> = clef_runs.iter().map(|r| r.last().unwrap().1).collect();
2259    // each staff's own key, bar by bar; a signature inside the system is no note's accidentals
2260    let keys = system_keys(
2261        &staff_glyphs,
2262        mine,
2263        first_event,
2264        &edges,
2265        &clef_runs,
2266        names,
2267        carry,
2268        first_piece,
2269    );
2270    for (gs, sig) in staff_glyphs.iter_mut().zip(&keys.inner) {
2271        gs.retain(|g| {
2272            !sig.iter()
2273                .any(|s| s.code == g.code && s.x0 == g.x0 && s.y == g.y)
2274        });
2275    }
2276    let opening_end = opening_end.max(keys.opening_end);
2277    let bar_keys = common_keys(&keys, carry.fifths);
2278    let fifths = bar_keys[0];
2279    // every staff's every bar
2280    let mut per_bar: Vec<Vec<Vec<Ev>>> = vec![Vec::new(); groups.len()];
2281    // how many bars each bar stands for: a multi-bar rest's count, else one
2282    let mut rests_of: Vec<i64> = vec![1; groups.len()];
2283    let multis: Vec<Vec<(f64, f64)>> = mine.iter().map(|st| multi_rests(pg, st, sp)).collect();
2284    // the staves' bars with nothing read in them, each with its left and right
2285    let mut empties: BTreeMap<(usize, usize), (f64, f64)> = BTreeMap::new();
2286    for b in 0..groups.len() {
2287        let l = if b > 0 {
2288            edges[b]
2289        } else {
2290            // after the clef, key and time: the first note's own accidental is the bar's
2291            first_event - 0.5 * sp
2292        }
2293        .min(if b == 0 { opening_end } else { f64::MAX });
2294        let r = edges[b + 1];
2295        // a multi-bar rest across every staff: that many bars' rests, its count in the
2296        // time signature's digits over or under it
2297        let multi: Vec<(f64, f64)> = multis
2298            .iter()
2299            .filter_map(|ms| ms.iter().find(|m| l < m.0 && m.1 < r).copied())
2300            .collect();
2301        if multi.len() == mine.len() {
2302            let (x0, x1) = multi[0];
2303            let mut digits: Vec<&Glyph> = staff_glyphs
2304                .iter()
2305                .flatten()
2306                .filter(|g| smufl::time_digit(g.code).is_some() && x0 < g.x0 && g.x1 < x1)
2307                .collect();
2308            digits.sort_by(|a, b| a.x0.total_cmp(&b.x0));
2309            digits.dedup_by(|a, b| (a.x0 - b.x0).abs() < 0.3 * sp);
2310            let count: String = digits
2311                .iter()
2312                .filter_map(|g| smufl::time_digit(g.code))
2313                .filter_map(|d| char::from_digit(d, 10))
2314                .collect();
2315            let n: i64 = count.parse().map_err(|_| {
2316                Untaken(format!(
2317                    "bar {}: a multi-bar rest without its count",
2318                    first_number + b as i64
2319                ))
2320            })?;
2321            if n < 1 {
2322                return Err(Untaken(format!(
2323                    "bar {}: a multi-bar rest of no bars",
2324                    first_number + b as i64
2325                )));
2326            }
2327            rests_of[b] = n;
2328            for i in 0..mine.len() {
2329                let mut rest = Ev::spacer(len_of(i, b), x0);
2330                rest.rest = crate::staff::Rest::Bar;
2331                per_bar[b].push(vec![rest]);
2332            }
2333            continue;
2334        }
2335        for (i, st) in mine.iter().enumerate() {
2336            let bar_name = |e: Untaken| {
2337                Untaken(format!(
2338                    "bar {}, {}: {}",
2339                    first_number + b as i64,
2340                    names[i],
2341                    e.0
2342                ))
2343            };
2344            // (by its own staff space: a system may set a small staff, a cue's or an
2345            // instrument's, above full-sized ones; the system's, when they differ only by the
2346            // rounding of where the lines were drawn)
2347            let sp = match (st.sp() / mine[0].sp() - 1.0).abs() > 0.1 {
2348                true => st.sp(),
2349                false => mine[0].sp(),
2350            };
2351            let ev = read_staff_bar(pg, &staff_glyphs[i], st, l, r, sp, &clef_runs[i])
2352                .and_then(|ev| match ev.is_empty() {
2353                    true => Err(Untaken::new("a staff with nothing on it")),
2354                    false => Ok(ev),
2355                })
2356                .map_err(bar_name);
2357            // (whether it is empty is settled below, when the other staves' bars are read)
2358            let ev = match ev {
2359                Err(e) if e.0.ends_with("a staff with nothing on it") => {
2360                    empties.insert((b, i), (l, r));
2361                    Ok(vec![bar_rest(bar_len(bar_times[b]), l)])
2362                }
2363                ev => ev,
2364            };
2365            match ev {
2366                Ok(ev) => per_bar[b].push(ev),
2367                Err(e) if carry.partial => {
2368                    carry.unread.push(Unread {
2369                        bar: first_number + b as i64,
2370                        staff: names[i].clone(),
2371                        why: e.0,
2372                        place: None,
2373                        beside: Vec::new(),
2374                    });
2375                    let mut rest = Ev::spacer(len_of(i, b), l);
2376                    rest.rest = crate::staff::Rest::Bar;
2377                    per_bar[b].push(vec![rest]);
2378                }
2379                Err(e) => return Err(e),
2380            }
2381        }
2382    }
2383
2384    // a staff with nothing in a bar (its rest hidden: a piano's hands on one staff, a part that
2385    // waits) has an empty bar, if nothing of its own was passed over there
2386    for (&(b, i), &(l, r)) in empties.clone().iter() {
2387        let band = staff_band(pg, mine, i, sp, ceiling, floor);
2388        let others = (0..mine.len()).filter(|&j| j != i);
2389        let theirs: Vec<&Ev> = others.flat_map(|j| per_bar[b][j].iter()).collect();
2390        if let Some(what) = left_in_empty_bar(pg, &mine[i], band, (l, r), sp, &theirs) {
2391            empties.remove(&(b, i));
2392            let why = format!(
2393                "bar {}, {}: a staff with nothing read on it ({what})",
2394                first_number + b as i64,
2395                names[i]
2396            );
2397            if !carry.partial {
2398                return Err(Untaken(why));
2399            }
2400            carry.unread.push(Unread {
2401                bar: first_number + b as i64,
2402                staff: names[i].clone(),
2403                why,
2404                place: None,
2405                beside: Vec::new(),
2406            });
2407        }
2408    }
2409
2410    cross_staff(&mut per_bar, names);
2411
2412    // ties and slurs: the filled curves
2413    let mut slurs_in = BTreeMap::new();
2414    for n in names {
2415        if let Some(&k) = carry.slurs.get(n) {
2416            slurs_in.insert(n.clone(), k);
2417        }
2418    }
2419    let mut slurs_out: BTreeMap<String, u32> = BTreeMap::new();
2420    let mut slur_stems: BTreeMap<String, Option<bool>> = BTreeMap::new();
2421    let bot_last = mine.last().unwrap().bottom();
2422    let mut curve_doubts: Vec<(usize, usize, usize, &'static str)> = Vec::new();
2423    let mut curve_no = 0u32;
2424    let mut ties_found: Vec<(String, i32, i32)> = Vec::new();
2425    #[allow(clippy::type_complexity)]
2426    let mut ties_failed: Vec<((usize, usize), (usize, usize), usize)> = Vec::new();
2427    // the flat curves from the system before that end at a note: (staff, note, right end, top
2428    // and bottom)
2429    #[allow(clippy::type_complexity)]
2430    let mut ties_in: Vec<(usize, (usize, usize), (f64, f64, f64))> = Vec::new();
2431    for c in &pg.curves {
2432        if !(left - sp < c.x0
2433            && c.x0 < right + sp
2434            && top0 - 6.0 * sp < c.y0
2435            && c.y0 < bot_last + 6.0 * sp)
2436        {
2437            continue;
2438        }
2439        let cy = (c.y0 + c.y1) / 2.0;
2440        if pg.in_frame((c.x0 + c.x1) / 2.0, cy) {
2441            continue; // a guitar frame's dot
2442        }
2443        // the staff whose noteheads stand nearest the curve's two ends
2444        let reach = |i: usize| -> f64 {
2445            let hs: Vec<&Glyph> = per_bar
2446                .iter()
2447                .flat_map(|bar| bar[i].iter())
2448                .filter(|e| e.is_note())
2449                .flat_map(|e| e.heads.iter())
2450                .collect();
2451            if hs.is_empty() {
2452                return 1e18;
2453            }
2454            // (each end at its own height; an end at the system's edge is by no note: the
2455            // curve runs on over it)
2456            [
2457                (c.x0, c.ya, c.x0 < first_event - sp),
2458                (c.x1, c.yb, c.x1 > right - sp),
2459            ]
2460            .iter()
2461            .filter(|e| !e.2)
2462            .map(|&(x, y, _)| {
2463                hs.iter()
2464                    .map(|h| (h.x0 - x).abs() + (h.y - y).abs())
2465                    .fold(f64::MAX, f64::min)
2466            })
2467            .sum()
2468        };
2469        let si = (0..mine.len())
2470            .min_by(|&a, &b| reach(a).total_cmp(&reach(b)))
2471            .unwrap();
2472        // the staff's notes as (bar, index), in order
2473        let notes: Vec<(usize, usize)> = (0..groups.len())
2474            .flat_map(|b| (0..per_bar[b][si].len()).map(move |k| (b, k)))
2475            .filter(|&(b, k)| per_bar[b][si][k].is_note())
2476            .collect();
2477        if notes.is_empty() {
2478            continue;
2479        }
2480        let ev = |t: (usize, usize)| -> &Ev { &per_bar[t.0][si][t.1] };
2481        let near_y = |e: &Ev| e.heads.iter().any(|h| (h.y - cy).abs() < 2.2 * sp);
2482        // of two voices' notes at one end (stemmed up and down at one beat), the one with a head
2483        // nearer the curve's height
2484        // (a tie that arches upwards stands over its head, one that hangs under it: a head on
2485        // the curve's other side is not the one it ties)
2486        let aside = |h: &Glyph| {
2487            (h.y - cy).abs()
2488                + if across_the_curve(c, h, sp) {
2489                    3.0 * sp
2490                } else {
2491                    0.0
2492                }
2493        };
2494        let dy = |t: (usize, usize)| ev(t).heads.iter().map(aside).fold(f64::MAX, f64::min);
2495        let a_all: Vec<(usize, usize)> = notes
2496            .iter()
2497            .copied()
2498            .filter(|&t| {
2499                let d = c.x0 - ev(t).right();
2500                (-1.2 * sp < d && d < 1.5 * sp && near_y(ev(t)))
2501                    || starts_by_a_head(c.x0, cy, &ev(t).heads, sp)
2502            })
2503            .collect();
2504        let a_x = a_all.iter().map(|&t| ev(t).x).fold(f64::MIN, f64::max);
2505        // (of two at one height, two voices' unison set side by side: the one it starts by)
2506        // (and of those, one with a head by the curve that no tie has left yet: the ties of
2507        // two voices' notes a third apart stand over their heads, the lower by the upper head)
2508        let free = |t: (usize, usize)| {
2509            let e = ev(t);
2510            (e.heads.iter().zip(&e.place_of))
2511                .any(|(h, p)| !e.tied.contains(p) && (h.y - cy).abs() < 1.6 * sp)
2512        };
2513        // (or a chord's tie that reaches past another voice's notes set after it)
2514        let tied_from =
2515            crate::ties::start_of_a_tie(&a_all, &notes, ev, (c.x0, c.x1, cy, c.y1 - c.y0), sp);
2516        let a = a_all
2517            .iter()
2518            .copied()
2519            .filter(|&t| match tied_from {
2520                Some(x) => (ev(t).x - x).abs() < 1.0 * sp,
2521                None => ev(t).x > a_x - 1.0 * sp,
2522            })
2523            .min_by(|&p, &q| {
2524                free(q).cmp(&free(p)).then(dy(p).total_cmp(&dy(q))).then(
2525                    (c.x0 - ev(p).right())
2526                        .abs()
2527                        .total_cmp(&(c.x0 - ev(q).right()).abs()),
2528                )
2529            });
2530        let b_all: Vec<(usize, usize)> = notes
2531            .iter()
2532            .copied()
2533            .filter(|&t| {
2534                let d = ev(t).left() - c.x1;
2535                (-1.5 * sp < d && d < 0.8 * sp && near_y(ev(t)))
2536                    || ends_by_a_head(c.x1, cy, &ev(t).heads, sp)
2537            })
2538            .collect();
2539        let b_x = b_all.iter().map(|&t| ev(t).x).fold(f64::MAX, f64::min);
2540        let bnext = b_all
2541            .iter()
2542            .copied()
2543            // (within a head's width: the other voice's note of a second is set beside)
2544            .filter(|&t| ev(t).x < b_x + 1.3 * sp)
2545            .min_by(|&p, &q| dy(p).total_cmp(&dy(q)));
2546        // a slur: from the note at its left end to the note at its right. Its end stands over
2547        // (or under) the middle of its note's heads or, on the side its stem is, between
2548        // that and the stem: the note is the one the end is by across the staff
2549        let over = c.over();
2550        let beside = |p: (usize, usize), x: f64| slur_end_beside(ev(p), x, over);
2551        // of two voices' notes at one end, the one the end is nearer in height: a slur over its
2552        // notes meets a note at its top (its highest head, or its stem's end), one under them at
2553        // its foot
2554        let outside = |p: (usize, usize), y: f64| slur_end_outside(ev(p), y, over);
2555        // (one from the system before: the voice it left, by its note's stem, where that is known)
2556        let name = names[si].clone();
2557        let incoming = c.x0 < first_event - sp;
2558        let from_stem = carry.slur_stems.get(&name).copied().flatten();
2559        let unlike_from =
2560            |p: (usize, usize)| incoming && from_stem.is_some() && ev(p).up != from_stem;
2561        let best_r = (notes.iter().map(|&p| beside(p, c.x1))).fold(f64::MAX, f64::min);
2562        let rights = notes
2563            .iter()
2564            .copied()
2565            .filter(|&p| beside(p, c.x1) < best_r + 0.5 * sp)
2566            .min_by(|&p, &q| {
2567                unlike_from(p)
2568                    .cmp(&unlike_from(q))
2569                    .then(outside(p, c.yb).total_cmp(&outside(q, c.yb)))
2570                    .then(beside(p, c.x1).total_cmp(&beside(q, c.x1)))
2571            })
2572            .unwrap();
2573        let best = (notes.iter().map(|&p| beside(p, c.x0))).fold(f64::MAX, f64::min);
2574        let lefts = notes
2575            .iter()
2576            .copied()
2577            .filter(|&p| beside(p, c.x0) < best + 0.5 * sp)
2578            .min_by(|&p, &q| {
2579                outside(p, c.ya)
2580                    .total_cmp(&outside(q, c.ya))
2581                    .then(beside(p, c.x0).total_cmp(&beside(q, c.x0)))
2582            })
2583            .unwrap();
2584        // a tie that lands on no note (laissez vibrer): the note is left to ring (`-lv`)
2585        if let Some(a) = a {
2586            let later = notes.iter().any(|&u| ev(u).x > ev(a).x + 0.5 * sp);
2587            let lands = |h: &Glyph| {
2588                (notes.iter().filter(|&&u| u != a))
2589                    .flat_map(|&u| ev(u).heads.iter())
2590                    .any(|o| (o.y - h.y).abs() < 0.2 * sp && ends_at(c.x1, o, sp))
2591            };
2592            let within = c.x1 < right - 2.0 * sp && later;
2593            if within && rings_on((c.x0, c.x1, c.y0, c.y1), ev(a), &lands, sp) {
2594                let marks = &mut per_bar[a.0][si][a.1].marks;
2595                if !marks.contains(&"-lv") {
2596                    marks.push("-lv");
2597                }
2598                continue;
2599            }
2600        }
2601        // a tie: to the next note on that staff, at the same place
2602        if let Some(a) = a {
2603            // one running off the system's end is a tie only if its two ends stand at one
2604            // height (a slur's first half rises or falls to the system's end; a long tie
2605            // arches as high as a slur) and it passes over no other note of its voice (one
2606            // stemmed the other way is the other voice's, and so is any with a stem where
2607            // the tied note has none: a whole note's voice has no other note in its bar)
2608            let other_voice = |u: (usize, usize)| {
2609                matches!((ev(a).up, ev(u).up), (Some(p), Some(q)) if p != q)
2610                    || (ev(a).up.is_none() && ev(u).up.is_some())
2611            };
2612            let runs_off = c.x1 > right - 2.0 * sp
2613                && c.level(sp)
2614                && !notes.iter().any(|&u| {
2615                    let x = ev(u).x;
2616                    x > ev(a).x + 0.5 * sp && x < c.x1 - sp && !other_voice(u)
2617                });
2618            if bnext.is_some() || runs_off {
2619                // the head nearest its height not tied already (a chord's ties lie close); one
2620                // running on into the next system takes the nearest (the voices there unknown)
2621                let tied_already =
2622                    |k: usize| bnext.is_some() && ev(a).tied.contains(&ev(a).place_of[k]);
2623                // (a flat curve to a chord that has not the nearest head's note, but has the
2624                // note of a head little further from it: that head's tie, drawn past its
2625                // neighbour's)
2626                let flat = c.y1 - c.y0 < 1.5 * sp;
2627                let goes_on = |h: &Glyph| {
2628                    flat && (h.y - cy).abs() < 1.4 * sp
2629                        && bnext.is_some_and(|bn| {
2630                            bn != a && ev(bn).heads.iter().any(|o| (o.y - h.y).abs() < 0.2 * sp)
2631                        })
2632                };
2633                let (hk, ha) = ev(a)
2634                    .heads
2635                    .iter()
2636                    .enumerate()
2637                    .min_by(|p, q| {
2638                        tied_already(p.0)
2639                            .cmp(&tied_already(q.0))
2640                            .then(goes_on(q.1).cmp(&goes_on(p.1)))
2641                            .then(aside(p.1).total_cmp(&aside(q.1)))
2642                    })
2643                    .unwrap();
2644                let hy = ha.y;
2645                let next = notes
2646                    .iter()
2647                    .copied()
2648                    .filter(|&u| {
2649                        (u.0, ev(u).x) > (a.0, ev(a).x)
2650                            && u != a
2651                            && ev(u).heads.iter().any(|h| (h.y - hy).abs() < 0.2 * sp)
2652                    })
2653                    .min_by(|&p, &q| {
2654                        (p.0, ev(p).x)
2655                            .partial_cmp(&(q.0, ev(q).x))
2656                            .unwrap()
2657                            .then((Some(p) != bnext).cmp(&(Some(q) != bnext)))
2658                    });
2659                let is_tie = match bnext {
2660                    None => true,
2661                    // (a tie's two ends stand at one height: a curve that slants is a slur's)
2662                    Some(bn) => {
2663                        bn != a
2664                            && ev(bn).heads.iter().any(|h| (h.y - hy).abs() < 0.2 * sp)
2665                            && next == Some(bn)
2666                            && c.level(sp)
2667                    }
2668                };
2669                if is_tie {
2670                    if let Some(bn) = bnext.filter(|bn| bn.0 > a.0) {
2671                        curve_doubts.push((bn.0, si, bn.1, crate::doubt::TIE_ENDS));
2672                    }
2673                    let place = ev(a).place_of[hk];
2674                    // (its ends lie by the heads, as a tie's do: a slur's stand off them)
2675                    if curve_ends_by((c.x0, c.y0, c.y1), ha, sp) {
2676                        per_bar[a.0][si][a.1].tie_close.insert(place);
2677                    }
2678                    per_bar[a.0][si][a.1].tied.insert(place);
2679                    // (should the tie land on no note, the curve is a slur's to the note it
2680                    // ends by)
2681                    if let Some(bn) = bnext.filter(|_| c.x1 - c.x0 >= 1.2 * sp) {
2682                        curve_no += 1;
2683                        (per_bar[a.0][si][a.1].tie_curves).insert(place, curve_no);
2684                        per_bar[bn.0][si][bn.1].curve_ends.push(curve_no);
2685                    }
2686                    continue;
2687                }
2688            }
2689        }
2690        // (a flat curve that ends at a head and is no tie as read: was it one?)
2691        if let Some(bn) = bnext.filter(|_| c.y1 - c.y0 < 1.5 * sp) {
2692            let carried = |p: i32| {
2693                (carry.ties.iter()).any(|((n, _), t)| *n == names[si] && t.contains_key(&p))
2694            };
2695            // (a tie into the system whose note the system before did not leave tied: its place
2696            // as the bar before left it)
2697            // (a tie's end lies by its head, at its height and before it: a slur's over it)
2698            let by_head = |k: &usize| {
2699                let h = &ev(bn).heads[*k];
2700                (h.y - cy).abs() < 1.3 * sp && (c.x1 < h.x0 + 0.3 * sp || c.y1 - c.y0 < 0.8 * sp)
2701            };
2702            // (the curves into one chord are held against its heads together, after the loop;
2703            // before a system's first chord a tie's stub may be short)
2704            if c.x0 < first_event - sp || (a.is_none() && c.x0 < first_event - 0.5 * sp) {
2705                ties_in.push((si, bn, (c.x1, c.y0, c.y1)));
2706            }
2707            let why = crate::doubt::of_curve(
2708                (c.x0 < first_event - sp).then_some(&carried),
2709                a.map(ev),
2710                ev(bn),
2711                cy,
2712                sp,
2713            );
2714            curve_doubts.extend(why.map(|w| (bn.0, si, bn.1, w)));
2715            // (from a chord with other notes tied: one of its ties was not read)
2716            if let (Some(a), Some(crate::doubt::TIE_FAILED)) = (a, why) {
2717                ties_failed.push((a, bn, si));
2718            }
2719            // (a tie's end by its head: its note's pitch is the note's before it)
2720            let k = crate::doubt::ends_by(ev(bn), cy, sp).filter(by_head);
2721            if k.is_some() && a.is_none_or(|a| a.0 < bn.0) {
2722                curve_doubts.push((bn.0, si, bn.1, crate::doubt::TIE_ENDS));
2723            }
2724        }
2725        // a small note's curve to a note of full size is the slur of a grace note to the note
2726        // it leads to, never a tie: the note at the curve's right end or, where the curve is too
2727        // short to reach one, the next (small notes all through are a part printed small)
2728        if ev(lefts).grace.is_some() && !incoming && c.x1 < right - sp {
2729            let at = notes.iter().position(|&p| p == lefts).unwrap();
2730            let next = (notes.get(at + 1).copied())
2731                .filter(|&p| p.0 == lefts.0 && ev(p).left() - c.x1 < 2.0 * sp);
2732            let to = Some(rights).filter(|&r| r != lefts).or(next);
2733            if let Some(to) = to.filter(|&t| ev(t).grace.is_none()) {
2734                per_bar[lefts.0][si][lefts.1].slur_open += 1;
2735                per_bar[to.0][si][to.1].slur_close += 1;
2736                continue;
2737            }
2738        }
2739        if c.x1 - c.x0 < 1.2 * sp {
2740            continue; // a mark too small to be a slur
2741        }
2742        if incoming {
2743            // (a level curve to a note the system before left tied is that tie's second half)
2744            let e = ev(rights);
2745            let tied_in = c.level(sp)
2746                && (e.heads.iter().zip(&e.place_of)).any(|(h, p)| {
2747                    (h.y - cy).abs() < 1.6 * sp
2748                        && (carry.ties.iter())
2749                            .any(|((n, _), t)| *n == names[si] && t.contains_key(p))
2750                });
2751            if tied_in {
2752                continue;
2753            }
2754            // it comes from the system before (else it is a tie's second half)
2755            if let Some(k) = slurs_in.get_mut(&name).filter(|k| **k > 0) {
2756                *k -= 1;
2757                per_bar[rights.0][si][rights.1].slur_close += 1;
2758            }
2759            continue;
2760        }
2761        if c.x1 > right - sp {
2762            slur_stems.insert(name.clone(), ev(lefts).up);
2763            per_bar[lefts.0][si][lefts.1].slur_open += 1;
2764            *slurs_out.entry(name).or_default() += 1; // it goes on into the next system
2765            continue;
2766        }
2767        // an end that stands by a note of the part's other staff, and by no note of its own
2768        // or much nearer the other's in height, is that note's: a slur from one staff of a
2769        // piano to the other
2770        let part_of = |n: &str| n.split('.').next().unwrap_or(n).to_string();
2771        let all = &per_bar;
2772        let across = |(x, y): (f64, f64), own: (usize, usize)| -> (usize, (usize, usize)) {
2773            let own_off = match beside(own, x) < 0.75 * sp {
2774                true => outside(own, y),
2775                false => f64::MAX,
2776            };
2777            let by = |&(j, (b, k)): &(usize, (usize, usize))| {
2778                let e = &all[b][j][k];
2779                (slur_end_beside(e, x, over), slur_end_outside(e, y, over))
2780            };
2781            (0..mine.len())
2782                .filter(|&j| j != si && part_of(&names[j]) == part_of(&names[si]))
2783                .flat_map(|j| {
2784                    (0..groups.len())
2785                        .flat_map(move |b| (0..all[b][j].len()).map(move |k| (j, (b, k))))
2786                })
2787                .filter(|&(j, (b, k))| all[b][j][k].is_note())
2788                .filter(|t| by(t).0 < 0.25 * sp && by(t).1 < 2.5 * sp)
2789                .filter(|t| by(t).1 + 1.0 * sp < own_off)
2790                .min_by(|p, q| by(p).1.total_cmp(&by(q).1))
2791                .unwrap_or((si, own))
2792        };
2793        let (sl, lefts) = across((c.x0, c.ya), lefts);
2794        let (sr, rights) = across((c.x1, c.yb), rights);
2795        if (sl, lefts) == (sr, rights) {
2796            continue;
2797        }
2798        per_bar[lefts.0][sl][lefts.1].slur_open += 1;
2799        per_bar[rights.0][sr][rights.1].slur_close += 1;
2800    }
2801    // a tie into the system whose note the system before did not leave tied: its place as the
2802    // bar before left it. The curves into one chord take its heads in order of height (the
2803    // ties of a close chord stand off their heads, each nearer its neighbour's than its own)
2804    for (n, &(si, bn, _)) in ties_in.iter().enumerate() {
2805        if ties_in[..n].iter().any(|t| (t.0, t.1) == (si, bn)) {
2806            continue;
2807        }
2808        let into: Vec<(f64, f64, f64)> = (ties_in.iter())
2809            .filter(|t| (t.0, t.1) == (si, bn))
2810            .map(|t| t.2)
2811            .collect();
2812        let e = &per_bar[bn.0][si][bn.1];
2813        let cys: Vec<f64> = into.iter().map(|c| (c.1 + c.2) / 2.0).collect();
2814        let ys: Vec<f64> = e.heads.iter().map(|h| h.y).collect();
2815        let before = carry.altered.get(&(first_number, names[si].clone()));
2816        let ended = carry.ended.get(&(first_number, names[si].clone()));
2817        for (c, k) in into
2818            .iter()
2819            .zip(crate::ties::heads_in_order(&cys, &ys, 1.5 * sp))
2820        {
2821            let Some(k) = k.filter(|k| !e.accs.contains_key(&e.place_of[*k])) else {
2822                continue;
2823            };
2824            // (a tie's end lies by its head, at its height and before it: a slur's over it)
2825            let (h, cy) = (&e.heads[k], (c.1 + c.2) / 2.0);
2826            let by_head =
2827                (h.y - cy).abs() < 1.3 * sp && (c.0 < h.x0 + 0.3 * sp || c.2 - c.1 < 0.8 * sp);
2828            let p = e.place_of[k];
2829            let carried =
2830                (carry.ties.iter()).any(|((n, _), t)| *n == names[si] && t.contains_key(&p));
2831            // (a tie joins two notes of one pitch: where no voice of the bar before ended on
2832            // this one, the curve is a slur's)
2833            let from = ended.is_none_or(|s| s.contains(&p));
2834            if let Some(a) = before
2835                .and_then(|b| b.get(&p))
2836                .filter(|_| by_head && !carried && from)
2837            {
2838                ties_found.push((names[si].clone(), p, *a));
2839            }
2840        }
2841    }
2842    for (b, i, k, why) in curve_doubts {
2843        per_bar[b][i][k].doubts.push(why);
2844    }
2845    for (a, bn, i) in ties_failed {
2846        if !per_bar[a.0][i][a.1].tied.is_empty() {
2847            per_bar[bn.0][i][bn.1]
2848                .doubts
2849                .push(crate::doubt::TIE_PARTIAL);
2850        }
2851    }
2852
2853    // dynamics: on the nearest chord of the staff above them
2854    let left_out: Vec<String> = Vec::new();
2855    let dyn_glyphs: Vec<Glyph> = {
2856        let mut v: Vec<Glyph> = staff_glyphs
2857            .iter()
2858            .flatten()
2859            .filter(|g| smufl::dynamic_text(g.code).is_some())
2860            .copied()
2861            .collect();
2862        v.sort_by(|a, b| a.x0.total_cmp(&b.x0).then(a.y.total_cmp(&b.y)));
2863        v.dedup();
2864        v
2865    };
2866    for i in 0..mine.len() {
2867        let mine_dyn: Vec<&Glyph> = dyn_glyphs
2868            .iter()
2869            .filter(|g| {
2870                (0..mine.len())
2871                    .filter(|&j| mine[j].top() < g.y)
2872                    .max()
2873                    .unwrap_or(0)
2874                    == i
2875            })
2876            .collect();
2877        for w in dynamic_words(mine_dyn, sp) {
2878            let text: String = w
2879                .iter()
2880                .filter_map(|g| smufl::dynamic_text(g.code))
2881                .collect();
2882            let x = (w[0].x0 + w.last().unwrap().x1) / 2.0;
2883            // (whatever its letters: the format writes any run of p m f s z r n)
2884            if let Some((b, k)) = (0..groups.len())
2885                .flat_map(|b| (0..per_bar[b][i].len()).map(move |k| (b, k)))
2886                .min_by(|&(b, k), &(c, l)| {
2887                    (per_bar[b][i][k].x + 0.6 * sp - x)
2888                        .abs()
2889                        .total_cmp(&(per_bar[c][i][l].x + 0.6 * sp - x).abs())
2890                })
2891            {
2892                per_bar[b][i][k].dynamic = Some(text);
2893            }
2894        }
2895        // fermatas and articulations: on the staff's nearest note
2896        for g in &staff_glyphs[i] {
2897            let mark = if let Some(f) = smufl::fermata(g.code) {
2898                f
2899            } else if let Some(a) = smufl::articulation(g.code).or(smufl::ornament(g.code)) {
2900                a
2901            } else {
2902                continue;
2903            };
2904            let cx = (g.x0 + g.x1) / 2.0;
2905            let all: Vec<(usize, usize)> = (0..groups.len())
2906                .flat_map(|b| (0..per_bar[b][i].len()).map(move |k| (b, k)))
2907                .collect();
2908            let notes: Vec<(usize, usize)> = all
2909                .iter()
2910                .copied()
2911                .filter(|&(b, k)| per_bar[b][i][k].is_note() && per_bar[b][i][k].grace.is_none())
2912                .collect();
2913            // (a staff of rests alone keeps a fermata, on a rest; an articulation or an ornament
2914            // is a note's, and one read over rests alone is a misreading: the compiler now
2915            // writes what a whole bar's rest carries, so it is left out here)
2916            if notes.is_empty() && smufl::fermata(g.code).is_none() {
2917                continue;
2918            }
2919            let pool = if notes.is_empty() { &all } else { &notes };
2920            // (an arpeggio's line stands before its chord, past the chord's accidentals: the
2921            // first notes right of it, never the note before)
2922            let arpeggio = smufl::is_arpeggio(g.code);
2923            let after: Vec<(usize, usize)> = pool
2924                .iter()
2925                .copied()
2926                .filter(|&(b, k)| {
2927                    let x = per_bar[b][i][k].x;
2928                    arpeggio && x > cx - 0.3 * sp && x < cx + 5.0 * sp
2929                })
2930                .collect();
2931            if arpeggio && after.is_empty() {
2932                continue;
2933            }
2934            let pool = if arpeggio { &after } else { pool };
2935            if let Some(&(b, k)) = pool.iter().min_by(|&&(b, k), &&(c, l)| {
2936                (per_bar[b][i][k].x + 0.6 * sp - cx)
2937                    .abs()
2938                    .total_cmp(&(per_bar[c][i][l].x + 0.6 * sp - cx).abs())
2939            }) {
2940                // one mark of a kind (an arpeggio is drawn as a chain of wiggles)
2941                if !per_bar[b][i][k].marks.contains(&mark) {
2942                    per_bar[b][i][k].marks.push(mark);
2943                }
2944            }
2945        }
2946    }
2947
2948    // the marks that are not notes: clefs changed, hairpins, words, chord symbols, the pedal, ...
2949    let bar_edges: Vec<(f64, f64)> = (0..groups.len())
2950        .map(|b| (if b > 0 { edges[b] } else { left }, edges[b + 1]))
2951        .collect();
2952    let msys = marks::Sys {
2953        pg,
2954        staves: mine,
2955        names,
2956        bars: &bar_edges,
2957        sp,
2958        right,
2959        first_event,
2960        ceiling,
2961        floor,
2962        sung,
2963    };
2964    for &(i, x, c) in &clef_marks {
2965        marks::put(&mut per_bar, &msys, i, x, format!("\\clef:{c}"));
2966    }
2967    crate::cues::mark_sung(pg, mine, sung, &mut per_bar, left, right);
2968    let placed = marks::place(&msys, &mut per_bar, &mut carry.open);
2969    let notices = left_out;
2970
2971    // the voices, and the bars as text
2972    let mut bars = Vec::new();
2973    // (each staff's bar as it stands now: what a bar that stands again is known by)
2974    let snaps: Vec<Vec<crate::repeats::Snap>> = (0..groups.len())
2975        .map(|b| {
2976            let of = |(i, evs): (usize, &Vec<Ev>)| {
2977                let top = mine.get(i).map_or(0.0, |st| st.top());
2978                crate::repeats::snap(evs, sp, top, len_of(i, b))
2979            };
2980            per_bar[b].iter().enumerate().map(of).collect()
2981        })
2982        .collect();
2983    // every bar's voices first: a tie is kept only where its voice's next note has its place
2984    let mut all_voices: Vec<BarVoices> = (0..groups.len())
2985        .map(|b| {
2986            let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
2987            per_bar[b]
2988                .iter()
2989                .enumerate()
2990                .map(|(i, ev)| {
2991                    let len = len_of(i, b);
2992                    voices_of(ev.clone(), sp, len, Some(edges[b + 1]), may_be_short)
2993                        .map_err(|e| e.0)
2994                })
2995                .collect()
2996        })
2997        .collect();
2998    let judged_first = crate::judge::stamps(&all_voices);
2999    // a first or last bar that a staff's notes fill is not short: a staff read as shorter there
3000    // (its rests hidden) is read as any bar's
3001    for b in 0..groups.len() {
3002        if (first_piece && b == 0) || (last_piece && b == groups.len() - 1) {
3003            let (len, right) = (bar_len(bar_times[b]), edges[b + 1]);
3004            not_short_where_filled(&mut all_voices[b], &per_bar[b], sp, len, right);
3005        }
3006    }
3007    // a staff whose notes beamed with the other staff's are read there
3008    for b in 0..groups.len() {
3009        let len = bar_len(bar_times[b]);
3010        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3011        for i in 0..mine.len() {
3012            if all_voices[b][i].is_err() {
3013                let read = |evs| voices_of(evs, sp, len, Some(edges[b + 1]), may_be_short);
3014                if let Some((evs, voices)) = without_the_notes_gone(&per_bar[b][i], read, len) {
3015                    per_bar[b][i] = evs;
3016                    all_voices[b][i] = Ok(voices);
3017                }
3018            }
3019        }
3020    }
3021    // a rest out between two staves of one part may be either's: where a staff's bar does not
3022    // add up, its rests in the gap go to the staff beside, if both then do
3023    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
3024    for b in 0..groups.len() {
3025        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3026        for i in 0..mine.len() {
3027            if all_voices[b][i].is_ok() {
3028                continue;
3029            }
3030            let len = len_of(i, b);
3031            for j in [i.wrapping_sub(1), i + 1] {
3032                if j >= mine.len() || part(&names[i]) != part(&names[j]) {
3033                    continue;
3034                }
3035                if len_of(j, b) != len {
3036                    continue; // (each staff in its own time: a rest of one is not the other's)
3037                }
3038                let toward_j = |y: f64| {
3039                    if j < i {
3040                        y < mine[i].top() - 2.0 * sp && y > mine[j].bottom()
3041                    } else {
3042                        y > mine[i].bottom() + 2.0 * sp && y < mine[j].top()
3043                    }
3044                };
3045                let (gone, kept): (Vec<Ev>, Vec<Ev>) =
3046                    per_bar[b][i].iter().cloned().partition(|e| {
3047                        matches!(e.rest, crate::staff::Rest::Printed(_)) && toward_j(e.y())
3048                    });
3049                if gone.is_empty() || kept.is_empty() {
3050                    continue;
3051                }
3052                let mut there = per_bar[b][j].clone();
3053                there.extend(gone);
3054                there.sort_by(|a, b| a.x.total_cmp(&b.x));
3055                let here_v = voices_of(kept.clone(), sp, len, Some(edges[b + 1]), may_be_short);
3056                let there_v = voices_of(there.clone(), sp, len, Some(edges[b + 1]), may_be_short);
3057                if let (Ok(h), Ok(t)) = (here_v, there_v) {
3058                    per_bar[b][i] = kept;
3059                    per_bar[b][j] = there;
3060                    all_voices[b][i] = Ok(h);
3061                    all_voices[b][j] = Ok(t);
3062                    break;
3063                }
3064            }
3065        }
3066    }
3067    // tuplets with no number where the reader looks for one: a bare number over notes no one
3068    // beam joins, a beam of three, a run set as a tuplet marked before on the staff was
3069    // ("simile"), or one the other staves' columns show
3070    for b in 0..groups.len() {
3071        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3072        if all_voices[b].iter().all(|v| v.is_ok()) {
3073            continue;
3074        }
3075        let len = bar_len(bar_times[b]);
3076        let seen: Vec<Vec<Ev>> = (0..mine.len())
3077            .map(|i| {
3078                let before = carry.tupleted.get(&names[i]).into_iter().flatten();
3079                let here = (0..=b).flat_map(|c| per_bar[c][i].iter());
3080                before
3081                    .chain(here)
3082                    .filter(|e| !e.tuplets.is_empty())
3083                    .cloned()
3084                    .collect()
3085            })
3086            .collect();
3087        let bar = crate::tuplets::Bar {
3088            names,
3089            own_time: &own[b],
3090            seen: &seen,
3091            sp,
3092            len,
3093            right: Some(edges[b + 1]),
3094            short: may_be_short,
3095        };
3096        crate::tuplets::unnumbered_in_bar(&mut per_bar[b], &mut all_voices[b], &bar);
3097    }
3098    // (the blank time a note beamed with the part's other staff left on its own, as long as
3099    // the note is in the tuplet since found for it)
3100    for b in 0..groups.len() {
3101        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3102        let lens: Vec<Q> = (0..mine.len()).map(|i| len_of(i, b)).collect();
3103        let (bar, read) = (&mut per_bar[b], &mut all_voices[b]);
3104        let right = Some(edges[b + 1]);
3105        crate::between::blanks_as_their_notes(bar, read, names, sp, &lens, right, may_be_short);
3106    }
3107    // a 2 over notes in simple time, after triplets, that says they are plain again
3108    for b in 0..groups.len() {
3109        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3110        for i in 0..mine.len() {
3111            let len = len_of(i, b);
3112            let simple = times.at[i][b].0 % 3 != 0 || times.at[i][b].1 < 8;
3113            if simple && all_voices[b][i].is_err() {
3114                if let Some(plain) = without_duplets(&per_bar[b][i]) {
3115                    if let Ok(v) =
3116                        voices_of(plain.clone(), sp, len, Some(edges[b + 1]), may_be_short)
3117                    {
3118                        per_bar[b][i] = plain;
3119                        all_voices[b][i] = Ok(v);
3120                    }
3121                }
3122            }
3123        }
3124    }
3125    // a dot two voices' notes at one place share may be one's alone
3126    for b in 0..groups.len() {
3127        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3128        for i in 0..mine.len() {
3129            let len = len_of(i, b);
3130            if all_voices[b][i].is_err() {
3131                if let Some((evs, voices)) = crate::staff::dots_of_one_voice(
3132                    &per_bar[b][i],
3133                    sp,
3134                    len,
3135                    Some(edges[b + 1]),
3136                    may_be_short,
3137                ) {
3138                    per_bar[b][i] = evs;
3139                    all_voices[b][i] = Ok(voices);
3140                }
3141            }
3142        }
3143    }
3144    // one figure passing between a part's two staves, one of which at least does not read alone
3145    for b in 0..groups.len() {
3146        let len = bar_len(bar_times[b]);
3147        for i in 0..mine.len().saturating_sub(1) {
3148            let j = i + 1;
3149            if part(&names[i]) != part(&names[j])
3150                || (all_voices[b][i].is_ok() && all_voices[b][j].is_ok())
3151            {
3152                continue;
3153            }
3154            let both = crate::staff::passed_between_staves(&per_bar[b][i], &per_bar[b][j], sp, len);
3155            if let Some([upper, lower]) = both {
3156                all_voices[b][i] = Ok(upper);
3157                all_voices[b][j] = Ok(lower);
3158            }
3159        }
3160    }
3161    // a voice passing between a part's two staves beside their own voices
3162    for b in 0..groups.len() {
3163        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3164        // (a first or last bar only where a staff's notes fill it: it is then not short)
3165        let full = all_voices[b].iter().any(|v| {
3166            v.as_ref()
3167                .is_ok_and(|vs| vs.iter().flatten().any(|e| e.is_note()) && !padded(vs))
3168        });
3169        if !may_be_short || full {
3170            let lens: Vec<Q> = (0..mine.len()).map(|i| len_of(i, b)).collect();
3171            let (len, right) = (&lens, Some(edges[b + 1]));
3172            crate::passing::between_staves(&per_bar[b], &mut all_voices[b], names, sp, len, right);
3173        }
3174        // (and one in tuplets shared between the two staves: in a bar that may be short, only
3175        // where nothing is made up to fill it)
3176        let lens: Vec<Q> = (0..mine.len()).map(|i| len_of(i, b)).collect();
3177        let how = (Some(edges[b + 1]), may_be_short && !full);
3178        let (bar, read) = (&mut per_bar[b], &mut all_voices[b]);
3179        crate::between::tuplets_between(bar, read, names, sp, &lens, how);
3180    }
3181    // a staff's one voice whose rests the program hid, timed by the other staves' columns,
3182    // where nothing printed in its bar was passed over
3183    for b in 0..groups.len() {
3184        let full = all_voices[b].iter().any(|v| {
3185            v.as_ref()
3186                .is_ok_and(|vs| vs.iter().flatten().any(|e| e.is_note()) && !padded(vs))
3187        });
3188        // (the bar's length is sure where a staff's notes fill it)
3189        if !full {
3190            continue;
3191        }
3192        for i in 0..mine.len() {
3193            if all_voices[b][i].is_ok() || own[b][i].is_some() {
3194                continue;
3195            }
3196            let others: Vec<crate::columns::Mark> = (0..mine.len())
3197                .filter(|&j| j != i)
3198                .filter_map(|j| all_voices[b][j].as_ref().ok())
3199                .flat_map(|vs| crate::columns::columns(&crate::columns::marks(vs)))
3200                .collect();
3201            let len = bar_len(bar_times[b]);
3202            let Some(vs) = crate::passing::hidden_rests(&per_bar[b][i], &others, sp, len) else {
3203                continue;
3204            };
3205            let band = staff_band(pg, mine, i, sp, ceiling, floor);
3206            let sides = (if b > 0 { edges[b] } else { opening_end }, edges[b + 1]);
3207            let theirs: Vec<&Ev> = per_bar[b].iter().flatten().collect();
3208            if left_in_empty_bar(pg, &mine[i], band, sides, sp, &theirs).is_none()
3209                && nothing_where_blank(pg, &mine[i], &vs[0], sides, sp, &theirs)
3210            {
3211                all_voices[b][i] = Ok(vs);
3212            }
3213        }
3214    }
3215    // a voice of rests alone, as printed, beside one that fills the bar
3216    for (b, voices) in all_voices.iter_mut().enumerate() {
3217        for (i, v) in voices.iter_mut().enumerate().filter(|(_, v)| v.is_err()) {
3218            // (a pickup or a last bar may be short: its first voice then says how long)
3219            let short = (first_piece && b == 0) || (last_piece && b + 1 == groups.len());
3220            if let Some(read) = crate::staff::rests_apart(&per_bar[b][i], sp, len_of(i, b), short) {
3221                *v = Ok(read);
3222            }
3223        }
3224    }
3225    // a bar shorter than its time with no new time signature printed (a 2/4 bar in 4/4): where
3226    // a staff's bar does not add up, the bar is short if every staff then fills one shorter
3227    // length, two of them at least, one with notes (a staff of printed rests alone holds them)
3228    let mut short_bars: BTreeSet<usize> = BTreeSet::new();
3229    for b in 0..groups.len() {
3230        if all_voices[b].iter().all(|v| v.is_ok()) {
3231            continue;
3232        }
3233        // a staff whose notes fill the whole bar says the bar is not short
3234        // (one filled out with time that is not printed says nothing)
3235        let full = all_voices[b].iter().any(|v| {
3236            v.as_ref()
3237                .is_ok_and(|vs| vs.iter().flatten().any(|e| e.is_note()) && !padded(vs))
3238        });
3239        if full {
3240            continue;
3241        }
3242        let tried: Vec<Res<Vec<Vec<Ev>>>> = per_bar[b]
3243            .iter()
3244            .enumerate()
3245            .map(|(i, ev)| voices_of(ev.clone(), sp, len_of(i, b), Some(edges[b + 1]), true))
3246            .collect();
3247        let Ok(tried) = tried.into_iter().collect::<Res<Vec<_>>>() else {
3248            continue;
3249        };
3250        // (where a staff was read as full only by time that is not printed, the short reading
3251        // must need none)
3252        let noted_ok = |v: &Result<Vec<Vec<Ev>>, String>| {
3253            v.as_ref()
3254                .is_ok_and(|vs| vs.iter().flatten().any(|e| e.is_note()))
3255        };
3256        if all_voices[b].iter().any(noted_ok) && tried.iter().any(|vs| padded(vs)) {
3257            continue;
3258        }
3259        // each staff's length: its longest voice's, a bar's rest none (as a share of its own
3260        // time's bar: staves in different times agree in proportion)
3261        let lengths: Vec<Option<Q>> = tried
3262            .iter()
3263            .enumerate()
3264            .map(|(i, vs)| {
3265                vs.iter()
3266                    .filter(|v| v.iter().any(|e| e.is_note()))
3267                    .map(|v| v.iter().map(|e| e.takes()).sum::<Q>())
3268                    .max()
3269                    .or_else(|| rests_held(vs))
3270                    .map(|h| h / len_of(i, b))
3271            })
3272            .collect();
3273        // a staff's voices sound together from the bar's start: two read one after the other
3274        // (a run, then a held chord) are one voice misread, not a short bar
3275        let together = tried.iter().all(|vs| {
3276            let starts: Vec<f64> = vs
3277                .iter()
3278                .filter(|v| v.iter().any(|e| e.is_note()))
3279                .filter_map(|v| v.first().map(|e| e.x))
3280                .collect();
3281            let lo = starts.iter().copied().fold(f64::MAX, f64::min);
3282            starts.iter().all(|&x| x - lo < 2.0 * sp)
3283        });
3284        let held: Vec<Q> = lengths.iter().flatten().copied().collect();
3285        let noted = tried
3286            .iter()
3287            .filter(|vs| vs.iter().flatten().any(|e| e.is_note()))
3288            .count();
3289        if together
3290            && noted >= 1
3291            && held.len() >= 2
3292            && held
3293                .iter()
3294                .all(|&h| h == held[0] && h < Q::ONE && !h.is_zero())
3295        {
3296            short_bars.insert(b);
3297            for (i, v) in tried.into_iter().enumerate() {
3298                all_voices[b][i] = Ok(v);
3299            }
3300        } else if let Some(read) = (own[b].iter().all(|t| t.is_none()))
3301            // (staves each in its own time have no one length to fall short of)
3302            .then(|| bar_len(bar_times[b]))
3303            .and_then(|len| short_as_its_lines_say(&per_bar[b], sp, len, edges[b + 1]))
3304        {
3305            short_bars.insert(b);
3306            all_voices[b] = read.into_iter().map(Ok).collect();
3307        }
3308    }
3309    // a piece of a bar that runs on over a system's end holds what its staves agree it holds
3310    for b in crate::longbars::pieces(continues, carry.runs.open, groups.len()) {
3311        let lens: Vec<Q> = (0..mine.len()).map(|i| len_of(i, b)).collect();
3312        let (read, evs) = (&mut all_voices[b], &per_bar[b]);
3313        crate::longbars::as_its_staves_agree(read, evs, sp, &lens, edges[b + 1]);
3314        short_bars.insert(b);
3315    }
3316    for i in 0..mine.len() {
3317        let kept = carry.tupleted.entry(names[i].clone()).or_default();
3318        kept.extend(
3319            (0..groups.len())
3320                .flat_map(|b| per_bar[b][i].iter())
3321                .filter(|e| !e.tuplets.is_empty())
3322                .cloned(),
3323        );
3324        let over = kept.len().saturating_sub(64);
3325        kept.drain(..over);
3326    }
3327    let judged_mid = crate::judge::stamps(&all_voices);
3328    // (with `FMV_OPTIONS`: each staff's reading before the columns set it aside)
3329    let options_on = crate::options::on();
3330    let before_columns = match options_on {
3331        true => all_voices.clone(),
3332        false => Vec::new(),
3333    };
3334    // a staff's bar whose notes do not stand in the columns its starts say is misread: it is
3335    // timed again by the other staves' columns, or left unread
3336    // (and a staff's bar not read that stands again in bars that were is read as they were,
3337    // where the columns then say nothing against it: `repeats.rs`)
3338    let mut twinned: BTreeMap<(usize, usize), i64> = BTreeMap::new();
3339    for (b, voices) in all_voices.iter_mut().enumerate() {
3340        let now: Vec<crate::times::Time> = times.at.iter().map(|t| t[b]).collect();
3341        let scales = crate::times::scales(&now);
3342        let read =
3343            crate::repeats::held_by_columns(&carry.twins, names, &snaps[b], voices, sp, &scales);
3344        twinned.extend(read.into_iter().map(|(i, twin)| ((b, i), twin)));
3345    }
3346    // (a staff the columns left unread: a voice passing between it and the part's other staff)
3347    for b in 0..groups.len() {
3348        let may_be_short = (first_piece && b == 0) || (last_piece && b == groups.len() - 1);
3349        let misread = |v: &Result<Vec<Vec<Ev>>, String>| {
3350            v.as_ref()
3351                .is_err_and(|e| e.starts_with(crate::columns::MISREAD))
3352        };
3353        if !may_be_short && all_voices[b].iter().any(misread) {
3354            let lens: Vec<Q> = (0..mine.len()).map(|i| len_of(i, b)).collect();
3355            let (len, right) = (&lens, Some(edges[b + 1]));
3356            crate::passing::between_staves(&per_bar[b], &mut all_voices[b], names, sp, len, right);
3357            let (bar, read) = (&mut per_bar[b], &mut all_voices[b]);
3358            crate::between::tuplets_between(bar, read, names, sp, len, (right, false));
3359        }
3360    }
3361    // a bar still unread, solved from where its notes stand among the read staves' columns
3362    for b in 0..groups.len() {
3363        let solved = spaced(pg, mine, names, &per_bar[b], &all_voices[b], &own[b], sp, {
3364            let sides = (if b > 0 { edges[b] } else { opening_end }, edges[b + 1]);
3365            (bar_len(bar_times[b]), sides, (ceiling, floor))
3366        });
3367        for (i, vs) in solved.into_iter().enumerate() {
3368            if let Some(vs) = vs {
3369                all_voices[b][i] = Ok(vs);
3370            }
3371        }
3372    }
3373    crate::ties::settle(&mut all_voices, names);
3374    for voices in all_voices.iter_mut().flatten().flatten() {
3375        dots_hidden_under_a_beam(voices, sp);
3376    }
3377    let mut ties = carry.ties.clone();
3378    for (name, place, alter) in ties_found {
3379        ties.entry((name, 1))
3380            .or_default()
3381            .entry(place)
3382            .or_insert(alter);
3383    }
3384    // the pitches the ties held over what follows (`~~`) carry out of the bar before, by staff
3385    let mut held_over: BTreeMap<String, BTreeMap<i32, i32>> = BTreeMap::new();
3386    let mut tied_over: BTreeMap<String, BTreeSet<i32>> = BTreeMap::new();
3387    let mut number = first_number;
3388    let nb = groups.len();
3389    for b in 0..nb {
3390        let may_be_short =
3391            (first_piece && b == 0) || (last_piece && b == nb - 1) || short_bars.contains(&b);
3392        let r = edges[b + 1];
3393        let mut voices_per_staff = Vec::new();
3394        // (a staff with no key known is not read either)
3395        let readable: BarVoices = (0..all_voices[b].len())
3396            .map(|i| crate::key::known(keys.at[i][b], all_voices[b][i].clone()))
3397            .collect();
3398        let lost_with = lost_with_the_other_staff(&readable, &per_bar[b], names);
3399        crate::spacing::trace(number, names, &per_bar[b], &readable, sp, len_of(0, b), r);
3400        let mut bar_doubts = crate::doubt::of_bar(&per_bar[b], &readable, sp);
3401        for (i, ds) in bar_doubts.iter_mut().enumerate() {
3402            // (a tie into the bar from a bar that was not read)
3403            let before = |u: &Unread| u.bar == number - 1 && u.staff == names[i];
3404            let tied_in = |e: &&Ev| e.doubts.contains(&crate::doubt::TIE_ENDS);
3405            let into: Vec<i32> = (per_bar[b][i].iter().filter(tied_in))
3406                .flat_map(|e| e.places.iter().filter(|p| !e.accs.contains_key(p)).copied())
3407                .collect();
3408            if !into.is_empty() && carry.unread.iter().any(before) {
3409                ds.push(crate::doubt::TIE_FROM_UNREAD);
3410                // (and the bar not read has an accidental on the tied note's place)
3411                let signed = |p: &i32| per_bar[b - 1][i].iter().any(|e| e.accs.contains_key(p));
3412                if b > 0 && into.iter().any(signed) {
3413                    ds.push(crate::doubt::TIE_FROM_UNREAD_SIGNED);
3414                }
3415            }
3416        }
3417        let mut judged = Vec::new();
3418        let mut first_read: Vec<Result<Vec<Vec<Ev>>, String>> = Vec::new();
3419        for (i, v) in std::mem::take(&mut all_voices[b]).into_iter().enumerate() {
3420            let len = len_of(i, b);
3421            if options_on {
3422                first_read.push(match (&v, &before_columns[b][i]) {
3423                    (Err(_), Ok(was)) => Ok(was.clone()),
3424                    _ => v.clone(),
3425                });
3426            }
3427            let v = crate::key::known(keys.at[i][b], v);
3428            let v = crate::doubt::sure(&per_bar[b][i], &bar_doubts[i], v);
3429            // (a piece that goes on with the bar before the system's end)
3430            let v = match continues && b == 0 {
3431                true => crate::longbars::sure(
3432                    &per_bar[b][i],
3433                    carry.altered.get(&(number, names[i].clone())),
3434                    &(ties.iter().filter(|((n, _), _)| *n == names[i]))
3435                        .flat_map(|(_, t)| t.keys().copied())
3436                        .collect(),
3437                    keys.at[i][b].unwrap_or(fifths),
3438                    v,
3439                ),
3440                false => v,
3441            };
3442            if let (true, Ok(vs)) = (crate::judge::traced(), &v) {
3443                let before = |u: &Unread| u.bar == number - 1 && u.staff == names[i];
3444                let after = all_voices.get(b + 1).is_some_and(|n| n[i].is_err());
3445                let bar = crate::judge::Bar {
3446                    evs: &per_bar[b][i],
3447                    of_bar: &bar_doubts[i],
3448                    read: &readable,
3449                    staff: i,
3450                    names,
3451                    sp,
3452                    len,
3453                    edges: (edges[b], r),
3454                    at: (b, nb),
3455                    may_be_short,
3456                    unread_about: (carry.unread.iter().any(before), after),
3457                    first: &judged_first[b][i],
3458                    mid: &judged_mid[b][i],
3459                };
3460                judged.push((i, crate::judge::features(&bar, vs)));
3461            }
3462            let v = rests_only(&per_bar[b][i], v, len, edges[b]);
3463            let v = v.map_err(|e| Untaken(format!("bar {number}, {}: {}", names[i], e)));
3464            let v = match lost_with.contains(&i) {
3465                true => v.and(Err(Untaken(format!(
3466                    "bar {number}, {}: its notes are beamed with the part's other staff's, whose bar could not be read",
3467                    names[i]
3468                )))),
3469                false => v,
3470            };
3471            let v = match v {
3472                Ok(v) => v,
3473                Err(e) if carry.partial => {
3474                    carry.unread.push(Unread {
3475                        bar: number,
3476                        staff: names[i].clone(),
3477                        why: e.0,
3478                        place: None,
3479                        beside: Vec::new(),
3480                    });
3481                    let mut rest = Ev::spacer(len, edges[b]);
3482                    rest.rest = crate::staff::Rest::Bar;
3483                    // (an ottava line that starts or ends in it still does)
3484                    let marks = per_bar[b][i]
3485                        .iter()
3486                        .flat_map(|e| e.before.iter().chain(&e.after));
3487                    rest.before = ottava_marks_kept(marks.map(String::as_str));
3488                    vec![vec![rest]]
3489                }
3490                Err(e) => return Err(e),
3491            };
3492            voices_per_staff.push(v);
3493        }
3494        // what the bar holds, as a share of each staff's own time's bar
3495        let held: Q = voices_per_staff
3496            .iter()
3497            .enumerate()
3498            .flat_map(|(i, vs)| vs.iter().map(move |v| (i, v)))
3499            .filter(|(_, v)| v.iter().all(|e| e.rest != crate::staff::Rest::Bar))
3500            // (a grace note takes no time of the bar)
3501            .map(|(i, v)| v.iter().map(|e| e.takes()).sum::<Q>() / len_of(i, b))
3502            .max()
3503            .unwrap_or(Q::ONE);
3504        let len = Q::ONE;
3505        let pickup = first_piece && b == 0 && held < len;
3506        if pickup {
3507            number = 0;
3508            // (the staves' bars left unread so far, all of this first system, were listed as
3509            // numbered from 1)
3510            for u in carry.unread.iter_mut() {
3511                u.bar -= 1;
3512            }
3513        }
3514        for (i, f) in &judged {
3515            crate::judge::trace(number, &names[*i], f);
3516        }
3517        let short = !pickup && may_be_short && held < len;
3518        // an empty staff's bar is blank time, as long as the bar
3519        for (i, vs) in voices_per_staff.iter_mut().enumerate() {
3520            let listed = |u: &Unread| u.bar == number && u.staff == names[i];
3521            if empties.contains_key(&(b, i)) && !carry.unread.iter().any(listed) {
3522                let whole = len_of(i, b);
3523                blank_if_bar_rest(vs, if pickup || short { held * whole } else { whole });
3524            }
3525        }
3526        // the pedal's marks, into the voices as read
3527        let pedals: Vec<&marks::PedalMark> = placed.pedals.iter().filter(|m| m.bar == b).collect();
3528        let unread_here =
3529            |i: usize| (carry.unread.iter()).any(|u| u.bar == number && u.staff == names[i]);
3530        marks::write_pedals(&mut voices_per_staff, &pedals, &unread_here, 0.8 * sp);
3531        let mut staves = Vec::new();
3532        let printed_by_staff = printed_on_each_staff(&voices_per_staff, names);
3533        for (i, vs) in voices_per_staff.into_iter().enumerate() {
3534            let name = &names[i];
3535            let len = len_of(i, b);
3536            let beat = if times.at[i][b].1 == 8 && times.at[i][b].0 % 3 == 0 {
3537                Q::new(3, 2)
3538            } else {
3539                Q::ONE
3540            };
3541            let (printed, printed_on) = &printed_by_staff[i];
3542            // a bar the format cannot write (a length it has no note for) is left unread
3543            let unwritable = vs.iter().enumerate().find_map(|(vi, v)| {
3544                let tied = ties.get(&(name.clone(), vi + 1));
3545                let none = BTreeMap::new();
3546                write_voice_across(
3547                    v,
3548                    fifths,
3549                    printed,
3550                    printed_on,
3551                    tied.unwrap_or(&none),
3552                    beat,
3553                    None,
3554                )
3555                .err()
3556            });
3557            let vs = match unwritable {
3558                Some(e) if carry.partial => {
3559                    carry.unread.push(Unread {
3560                        bar: number,
3561                        staff: name.clone(),
3562                        why: format!("bar {number}, {name}: {}", e.0),
3563                        place: None,
3564                        beside: Vec::new(),
3565                    });
3566                    let mut rest = Ev::spacer(len, edges[b]);
3567                    rest.rest = crate::staff::Rest::Bar;
3568                    let marks = vs
3569                        .iter()
3570                        .flatten()
3571                        .flat_map(|e| e.before.iter().chain(&e.after));
3572                    rest.before = ottava_marks_kept(marks.map(String::as_str));
3573                    vec![vec![rest]]
3574                }
3575                _ => vs,
3576            };
3577            if b + 1 == nb {
3578                tied_over.insert(name.clone(), crate::ties::over_the_end(&vs));
3579            }
3580            carry.twins.note(name, number, &snaps[b][i], &vs);
3581            let listed = |u: &Unread| u.bar == number && u.staff == *name;
3582            if let Some(twin) = twinned
3583                .get(&(b, i))
3584                .filter(|_| !carry.unread.iter().any(listed))
3585            {
3586                carry.twins.say(format!(
3587                    "bar {number}, {name}: read as bar {twin}, where the same notes stand the same way"
3588                ));
3589            }
3590            if options_on {
3591                let seen = crate::options::Seen {
3592                    events: per_bar[b][i].clone(),
3593                    read: first_read[i].clone(),
3594                    part: name.split('.').next().unwrap_or(name).to_string(),
3595                    others: (0..per_bar[b].len())
3596                        .filter(|&j| j != i)
3597                        .map(|j| {
3598                            let part = names[j].split('.').next().unwrap_or(&names[j]);
3599                            let read = readable[j].as_ref().ok().cloned();
3600                            (part.to_string(), per_bar[b][j].clone(), read)
3601                        })
3602                        .collect(),
3603                    sp,
3604                    len,
3605                    right: r,
3606                    fifths: keys.at[i][b].unwrap_or(fifths),
3607                    beat,
3608                    ties_in: (1..=4)
3609                        .filter_map(|k| ties.get(&(name.clone(), k)))
3610                        .flat_map(|t| t.iter().map(|(&p, &a)| (p, a)))
3611                        .collect(),
3612                    signs_before: match b {
3613                        0 => BTreeMap::new(),
3614                        _ => (per_bar[b - 1][i].iter())
3615                            .flat_map(|e| e.accs.iter().map(|(&p, &(a, _))| (p, a)))
3616                            .collect(),
3617                    },
3618                };
3619                carry.seen.insert((number, name.clone()), seen);
3620                if crate::review::on() {
3621                    let fifths = keys.at[i][b].unwrap_or(fifths);
3622                    let marks = crate::review::marks_of(&vs, number, name, carry.page, fifths);
3623                    carry.marks.extend(marks);
3624                }
3625            }
3626            let mut lines = Vec::new();
3627            let tied_in = ties_into(&mut ties, name, vs.len());
3628            let held_in = held_over.remove(name).unwrap_or_default();
3629            // a key signature inside the bar: from the note after it on, in each voice
3630            let change = keys.mid[i][b].map(|(x, k)| (crate::write::key_change_at(&vs, x), k));
3631            for (vi, v) in vs.iter().enumerate() {
3632                let key = (name.clone(), vi + 1);
3633                let change = change.map(|((at, voice), fifths)| crate::write::KeyChange {
3634                    at,
3635                    fifths,
3636                    say: voice == vi,
3637                });
3638                let (line, tied_on, held_on) = crate::write::write_voice_held(
3639                    v,
3640                    keys.at[i][b].unwrap_or(fifths),
3641                    printed,
3642                    printed_on,
3643                    &tied_in,
3644                    &held_in,
3645                    beat,
3646                    change,
3647                )?;
3648                held_over.entry(name.clone()).or_default().extend(held_on);
3649                lines.push(format!(
3650                    "{name}{}: {line}",
3651                    if vi == 0 {
3652                        String::new()
3653                    } else {
3654                        format!("/{}", vi + 1)
3655                    }
3656                ));
3657                ties.insert(key, tied_on);
3658            }
3659            if b + 1 == nb {
3660                let left = crate::doubt::in_force(printed, &tied_in);
3661                carry.altered.insert((number + 1, name.clone()), left);
3662                match crate::ties::last_places(&vs) {
3663                    Some(s) => carry.ended.insert((number + 1, name.clone()), s),
3664                    None => carry.ended.remove(&(number + 1, name.clone())),
3665                };
3666            }
3667            staves.push((lines, vs.into_iter().next().unwrap_or_default()));
3668        }
3669        for (i, name) in names.iter().enumerate().take(mine.len()) {
3670            let place = Place {
3671                page: sys.page + 1,
3672                x0: if b > 0 { edges[b] } else { left },
3673                x1: r,
3674                y0: mine[i].top(),
3675                y1: mine[i].bottom(),
3676                time: times.at[i][b],
3677                seen: seen_in(&per_bar[b][i], edges[b], sp),
3678            };
3679            carry.places.insert((number, name.clone()), place);
3680            carry.bar_systems.insert(number, carry.system);
3681        }
3682        let whole = bar_len(bar_times[b]);
3683        carry.runs.lens.insert(number, (held * whole, whole));
3684        bars.push(BarRead {
3685            number,
3686            pickup,
3687            short,
3688            free: held > len
3689                && crate::longbars::pieces(continues, carry.runs.open, nb).contains(&b),
3690            time: bar_times[b],
3691            times: times.at.iter().map(|t| t[b]).collect(),
3692            time_sign: times.score_signs[b],
3693            time_signs: times.signs.iter().map(|t| t[b]).collect(),
3694            keys: keys.at.iter().map(|k| k[b]).collect(),
3695            key_changes: (keys.mid.iter()).map(|m| m[b].map(|(_, k)| k)).collect(),
3696            end: styles[b].0,
3697            start_before: if b > 0 { styles[b - 1].1 } else { None },
3698            staves,
3699            left: if b > 0 { edges[b] } else { left },
3700            right: r,
3701            jumps: Vec::new(),
3702            ending: None,
3703            tempo: placed.tempos.iter().find(|t| t.0 == b).map(|t| t.1.clone()),
3704            rests: rests_of[b],
3705        });
3706        number += rests_of[b];
3707    }
3708    let mut slurs_in_left = BTreeMap::new();
3709    for (k, v) in slurs_in {
3710        if v > 0 {
3711            slurs_in_left.insert(k, v);
3712        }
3713    }
3714    let first_bar_start = if bars.is_empty() {
3715        None
3716    } else {
3717        carry.starts_with
3718    };
3719    Ok(SystemRead {
3720        fifths,
3721        bar_keys,
3722        keys_out: keys.out,
3723        // (the score's first system has its key in the header)
3724        key_said: match first_piece {
3725            true => fifths,
3726            false => carry.said_key.unwrap_or(carry.fifths),
3727        },
3728        own_keys: match first_piece {
3729            true => vec![None; names.len()],
3730            false => (names.iter())
3731                .map(|n| carry.own_keys.get(n).copied())
3732                .collect(),
3733        },
3734        reprints: !first_piece && keys.at_start,
3735        time: bar_times[0],
3736        time_sign: times.score_signs[0],
3737        prev_time: if first_piece {
3738            bar_times[0]
3739        } else {
3740            carry.time
3741        },
3742        // (the score's first system says its times in its first bar)
3743        times_before: match first_piece {
3744            true => vec![bar_times[0]; names.len()],
3745            false => times.before.clone(),
3746        },
3747        every_staff_times: times.every,
3748        names: names.to_vec(),
3749        clefs,
3750        clef_changes,
3751        end_clefs,
3752        notices,
3753        last_bar: number - 1,
3754        ends_with_start: styles.last().and_then(|s| s.1),
3755        slurs_out,
3756        slur_stems,
3757        slurs_in_left,
3758        ties_out: ties,
3759        tied_over,
3760        opens_with: opens_with.or(first_bar_start),
3761        bars,
3762    })
3763}
3764
3765/// The words under each voice's staff, as lyric lines by (bar, staff name).
3766fn place_words(
3767    pg: &Page,
3768    sys: &System,
3769    names: &[String],
3770    read: &SystemRead,
3771    voices: &BTreeSet<String>,
3772    carry: &mut Carry,
3773) -> BTreeMap<(usize, String), Vec<String>> {
3774    let mut out: BTreeMap<(usize, String), Vec<String>> = BTreeMap::new();
3775    for (i, name) in names.iter().enumerate() {
3776        if !voices.contains(name) {
3777            continue;
3778        }
3779        let staff: &Staff = &sys.staves[i];
3780        let sp = staff.sp();
3781        let (x0, x1) = (read.bars[0].left, read.bars.last().unwrap().right);
3782        let lines = lyrics::verse_lines(lyrics::band(pg, staff, sys.staves.get(i + 1), x0, x1), sp);
3783        // the sung notes: the upper voice's notes not reached by a tie
3784        #[derive(Clone, Copy, PartialEq)]
3785        enum K {
3786            Sung,
3787            Tied,
3788            Rest,
3789        }
3790        let mut kinds: Vec<(usize, K)> = Vec::new();
3791        let mut sung_x = Vec::new();
3792        // (a note a tie lands on takes none, whichever voice the tie came from: `ties::settle`
3793        // marked them; into the system's first note, the ties the system before left)
3794        let mut tie_in = carry.lyric_ties.get(name).cloned().unwrap_or_default();
3795        for (b, bar) in read.bars.iter().enumerate() {
3796            for e in &bar.staves[i].1 {
3797                if e.grace.is_some() {
3798                    continue; // a grace note takes no syllable
3799                }
3800                if !e.is_note() {
3801                    kinds.push((b, K::Rest));
3802                    tie_in.clear();
3803                    continue;
3804                }
3805                if crate::ties::tied_into(e, &tie_in) {
3806                    kinds.push((b, K::Tied));
3807                } else {
3808                    kinds.push((b, K::Sung));
3809                    sung_x.push((e.left() + e.right()) / 2.0);
3810                }
3811                tie_in.clear();
3812            }
3813        }
3814        let over = read.tied_over.get(name).cloned().unwrap_or_default();
3815        carry.lyric_ties.insert(name.clone(), over);
3816        // verse lines with words on few notes are stray marks, when there are others
3817        let syl_lines: Vec<Vec<lyrics::Syl>> = lines
3818            .iter()
3819            .map(|l| lyrics::syllables(l, sp))
3820            .filter(|s| !s.is_empty())
3821            .collect();
3822        let keep: Vec<&Vec<lyrics::Syl>> = syl_lines
3823            .iter()
3824            .filter(|s| s.len() > 2 || syl_lines.len() == 1)
3825            .collect();
3826        for (vi, syls) in keep.iter().enumerate() {
3827            let at = lyrics::align(syls, &sung_x, sp);
3828            let by_note: BTreeMap<usize, &lyrics::Syl> = syls
3829                .iter()
3830                .zip(&at)
3831                .filter_map(|(s, a)| a.map(|a| (a, s)))
3832                .collect();
3833            let mut held = if vi == 0 { carry.held } else { false };
3834            let mut j = 0;
3835            let mut per_bar: BTreeMap<usize, Vec<String>> = BTreeMap::new();
3836            let mut prev_bar: Option<usize> = None;
3837            for &(b, k) in &kinds {
3838                // the words go back to a repeat's start: nothing is held over its end
3839                if let Some(pb) = prev_bar.filter(|&pb| pb != b) {
3840                    if read.bars[pb]
3841                        .end
3842                        .is_some_and(|e| e == "repeat-end" || e == "final")
3843                    {
3844                        held = false;
3845                    }
3846                }
3847                prev_bar = Some(b);
3848                match k {
3849                    K::Rest => held = false,
3850                    K::Tied => {}
3851                    K::Sung => {
3852                        let tok = match by_note.get(&j) {
3853                            Some(s) => {
3854                                held = true;
3855                                lyrics::clean(&s.text) + if s.cont { "-" } else { "" }
3856                            }
3857                            None if held => "_".into(),
3858                            None => "*".into(),
3859                        };
3860                        per_bar.entry(b).or_default().push(tok);
3861                        j += 1;
3862                    }
3863                }
3864            }
3865            if vi == 0 {
3866                carry.held = held;
3867            }
3868            let label = if vi == 0 {
3869                format!("{name} lyrics")
3870            } else {
3871                format!("{name} lyrics{}", vi + 1)
3872            };
3873            for (b, toks) in per_bar {
3874                if toks.iter().any(|t| t != "_" && t != "*") {
3875                    out.entry((b, name.clone()))
3876                        .or_default()
3877                        .push(format!("{label}: {}", toks.join(" ")));
3878                }
3879            }
3880        }
3881    }
3882    out
3883}
3884
3885/// Notes beamed with a part's other staff (a run passing from one hand's staff to the other's):
3886/// they are the voice's of the staff where most of the beam's notes stand, drawn on the other.
3887/// Where they stand, the other staff has time with nothing written.
3888fn cross_staff(per_bar: &mut [Vec<Vec<Ev>>], names: &[String]) {
3889    let part_of = |n: &str| n.split('.').next().unwrap_or(n).to_string();
3890    let number_of = |n: &str| n.split('.').nth(1).and_then(|k| k.parse::<u8>().ok());
3891    for bar in per_bar.iter_mut() {
3892        for a in 0..names.len() {
3893            for b in a + 1..names.len() {
3894                if part_of(&names[a]) != part_of(&names[b]) {
3895                    continue;
3896                }
3897                let (Some(na), Some(nb)) = (number_of(&names[a]), number_of(&names[b])) else {
3898                    continue;
3899                };
3900                // the beams the two staves' notes share
3901                let beams_a: BTreeSet<usize> = bar[a]
3902                    .iter()
3903                    .flat_map(|e| e.beam_polys.iter().copied())
3904                    .collect();
3905                let shared: BTreeSet<usize> = bar[b]
3906                    .iter()
3907                    .flat_map(|e| e.beam_polys.iter().copied())
3908                    .filter(|p| beams_a.contains(p))
3909                    .collect();
3910                if shared.is_empty() {
3911                    continue;
3912                }
3913                let on = |e: &Ev| e.is_note() && !e.beam_polys.is_disjoint(&shared);
3914                let in_a = bar[a].iter().filter(|e| on(e)).count();
3915                let in_b = bar[b].iter().filter(|e| on(e)).count();
3916                // home: the staff with more of the beam's notes (the upper on a tie)
3917                let (home, away, away_no) = if in_a >= in_b { (a, b, nb) } else { (b, a, na) };
3918                let mut moved = Vec::new();
3919                for e in bar[away].iter_mut() {
3920                    if on(e) {
3921                        let blank = Ev::spacer(e.dur, e.x);
3922                        let mut m = std::mem::replace(e, blank);
3923                        m.on_staff = Some(away_no);
3924                        moved.push(m);
3925                    }
3926                }
3927                stemmed_as_their_beam(&bar[home], &mut moved);
3928                bar[home].extend(moved);
3929                bar[home].sort_by(|p, q| p.x.total_cmp(&q.x));
3930            }
3931        }
3932    }
3933}
3934
3935/// The accidentals printed in a bar, as (onset, place, alteration) in order of onset: for each
3936/// staff, those on the staff itself, and those on each of its part's staves by number. A note
3937/// drawn on its part's other staff (`Ev::on_staff`) is printed there, whichever staff's voice
3938/// it is read in.
3939#[allow(clippy::type_complexity)]
3940fn printed_on_each_staff(
3941    voices: &[Vec<Vec<Ev>>],
3942    names: &[String],
3943) -> Vec<(Vec<(Q, i32, i32)>, BTreeMap<u8, Vec<(Q, i32, i32)>>)> {
3944    let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
3945    let number = |n: &str| n.split('.').nth(1).and_then(|k| k.parse::<u8>().ok());
3946    let mut on: Vec<Vec<(Q, i32, i32)>> = vec![Vec::new(); voices.len()];
3947    for (i, vs) in voices.iter().enumerate() {
3948        for v in vs {
3949            let mut t = Q::ZERO;
3950            for e in v {
3951                let drawn = e
3952                    .on_staff
3953                    .and_then(|n| {
3954                        let name = format!("{}.{n}", part(&names[i]));
3955                        names.iter().take(voices.len()).position(|m| *m == name)
3956                    })
3957                    .unwrap_or(i);
3958                on[drawn].extend(e.accs.iter().map(|(&p, &(a, _))| (t, p, a)));
3959                t += e.takes();
3960            }
3961        }
3962    }
3963    for list in on.iter_mut() {
3964        list.sort_by_key(|a| a.0);
3965    }
3966    (0..voices.len())
3967        .map(|i| {
3968            let others: BTreeMap<u8, Vec<(Q, i32, i32)>> = (0..voices.len())
3969                .filter(|&j| j != i && part(&names[j]) == part(&names[i]))
3970                .filter_map(|j| number(&names[j]).map(|n| (n, on[j].clone())))
3971                .collect();
3972            (on[i].clone(), others)
3973        })
3974        .collect()
3975}
3976
3977/// Ledger lines run from a staff out to the furthest head of a chord and no further: a run of
3978/// `k - 1` of them that ends at `edge` with no head of `h`'s chord there (staves a whole number
3979/// of spaces apart: the other staff's ledger lines stand where this one's would) is not this
3980/// staff's.
3981fn ledgers_end_at_a_head(pg: &Page, h: &Glyph, edge: f64, k: usize, sp: f64) -> bool {
3982    k == 1
3983        || pg.glyphs.iter().any(|g| {
3984            smufl::head(g.code).is_some()
3985                && (g.x0 - h.x0).abs() < 1.5 * sp
3986                && (g.y - edge).abs() < 0.75 * sp
3987        })
3988}
3989
3990/// Notes drawn on a part's other staff (`moved`), beamed with notes of this one (`home`): a
3991/// beam between two staves has the lower staff's stems up to it and the upper's down, so their
3992/// stems do not say their voice. They are of the voice of the notes they are beamed with, and
3993/// are given those notes' stems' way where those agree (the stem kept at the head's same edge,
3994/// so the note's column is where it was).
3995fn stemmed_as_their_beam(home: &[Ev], moved: &mut [Ev]) {
3996    for m in moved.iter_mut() {
3997        let ways: BTreeSet<bool> = home
3998            .iter()
3999            .filter(|e| e.is_note() && !e.beam_polys.is_disjoint(&m.beam_polys))
4000            .filter_map(|e| e.up)
4001            .collect();
4002        let (Some(&way), 1) = (ways.first(), ways.len()) else {
4003            continue;
4004        };
4005        if m.up.is_some_and(|u| u != way) {
4006            let w = m.heads.iter().map(|h| h.x1 - h.x0).fold(0.0, f64::max);
4007            if let Some(s) = m.stem.as_mut() {
4008                s.x += if way { w } else { -w };
4009            }
4010            m.up = Some(way);
4011        }
4012    }
4013}
4014
4015/// A staff's bar some of whose notes are read on the part's other staff (`cross_staff`), which
4016/// left blank time where they stand: where the bar does not read so, what is left of it read
4017/// alone, if that fills it with nothing unseen (the notes taken away were another voice's
4018/// passing through); with nothing left, the staff has the bar blank.
4019fn without_the_notes_gone(
4020    evs: &[Ev],
4021    read: impl Fn(Vec<Ev>) -> Res<Vec<Vec<Ev>>>,
4022    len: Q,
4023) -> Option<(Vec<Ev>, Vec<Vec<Ev>>)> {
4024    let blank = |e: &Ev| e.rest == crate::staff::Rest::Blank;
4025    if !evs.iter().any(blank) {
4026        return None;
4027    }
4028    let kept: Vec<Ev> = evs.iter().filter(|e| !blank(e)).cloned().collect();
4029    if kept.is_empty() {
4030        let all = vec![Ev::spacer(len, evs[0].x)];
4031        return Some((all.clone(), vec![all]));
4032    }
4033    let voices = read(kept.clone()).ok()?;
4034    // (with time unseen in what is left, the notes gone may have been its own voice's)
4035    if voices.iter().flatten().any(blank) {
4036        return None;
4037    }
4038    Some((kept, voices))
4039}
4040
4041/// Takes out the tie that a compile error says finds no note in the next bar, where that bar is
4042/// `first` (a new system's first) and the tie is in the text before it.
4043fn unties_last(done: &mut String, msg: &str, first: i64, all: &str) -> bool {
4044    let Some(at) = msg.find("the tie from bar ") else {
4045        return false;
4046    };
4047    let rest = &msg[at + "the tie from bar ".len()..];
4048    let Some((from, rest)) = rest.split_once(" wants ") else {
4049        return false;
4050    };
4051    let Some((pitch, _)) = rest.split_once(" next") else {
4052        return false;
4053    };
4054    if from.parse::<i64>().ok() != Some(first - 1) {
4055        return false;
4056    }
4057    // the voice: the label of the line the error names
4058    let Some(line_no) = msg
4059        .split("line ")
4060        .nth(1)
4061        .and_then(|t| t.split(':').next())
4062        .and_then(|t| t.trim().parse::<usize>().ok())
4063    else {
4064        return false;
4065    };
4066    let Some(label) = all
4067        .lines()
4068        .nth(line_no.saturating_sub(1))
4069        .and_then(|l| l.split_once(':'))
4070        .map(|(a, _)| a.trim().to_string())
4071    else {
4072        return false;
4073    };
4074    // the bar's block, the voice's line in it, and the last tie on that pitch there
4075    let mut in_bar = false;
4076    let mut offset = 0;
4077    let mut target: Option<(usize, String)> = None;
4078    for line in done.split_inclusive('\n') {
4079        let t = line.trim_end();
4080        if let Some(n) = t.strip_prefix("bar ") {
4081            in_bar = n.split_whitespace().next() == Some(from);
4082        } else if in_bar && t.split_once(':').is_some_and(|(a, _)| a.trim() == label) {
4083            target = Some((offset, line.to_string()));
4084        }
4085        offset += line.len();
4086    }
4087    let Some((start, line)) = target else {
4088        return false;
4089    };
4090    let mut cut = None;
4091    for (i, _) in line.match_indices(pitch) {
4092        // the pitch whole (not the end of another), then its tie in the same token
4093        let before = line[..i].chars().last();
4094        if before.is_some_and(|c| c.is_ascii_alphanumeric()) {
4095            continue;
4096        }
4097        let tail = &line[i + pitch.len()..];
4098        let token_end = tail.find([' ', '>']).unwrap_or(tail.len());
4099        if let Some(k) = tail[..token_end.max(tail.find(' ').unwrap_or(tail.len()))]
4100            .find('~')
4101            .filter(|&k| !tail[..k].contains(' '))
4102        {
4103            cut = Some(i + pitch.len() + k);
4104        }
4105    }
4106    let Some(k) = cut else {
4107        return false;
4108    };
4109    done.replace_range(start + k..start + k + 1, "");
4110    true
4111}
4112
4113/// The byte ranges of a text's lines, without their line ends.
4114fn line_spans(s: &str) -> Vec<(usize, usize)> {
4115    let mut out = Vec::new();
4116    let mut at = 0;
4117    for l in s.split_inclusive('\n') {
4118        out.push((at, at + l.trim_end_matches(['\n', '\r']).len()));
4119        at += l.len();
4120    }
4121    out
4122}
4123
4124/// A system's hairpins, or its ottava lines, taken out where the compiler says one of them
4125/// pairs with nothing and nothing nearer mends it; from the bar the message names in the text
4126/// before, where this system has none. What was taken out, for the notice.
4127fn without_lines(done: &mut String, text: &mut String, msg: &str) -> Option<&'static str> {
4128    let (what, marks): (_, &[&str]) = if msg.contains("hairpin") {
4129        ("its hairpins", &["\\<", "\\>", "\\!"])
4130    } else if msg.contains("ottava") {
4131        ("its ottava lines", &OTTAVA_MARKS)
4132    } else {
4133        return None;
4134    };
4135    let hairpin = msg.contains("hairpin");
4136    // (a mark is a token of its own on a voice's line)
4137    let strip = |s: &mut String, from_bar: Option<&str>| -> bool {
4138        let mut out = String::with_capacity(s.len());
4139        let mut cut = false;
4140        let mut on = from_bar.is_none();
4141        for line in s.split_inclusive('\n') {
4142            if let Some(n) = line.strip_prefix("bar ") {
4143                if Some(n.split_whitespace().next().unwrap_or("")) == from_bar {
4144                    on = true;
4145                }
4146            }
4147            if !on || !line.contains('\\') {
4148                out.push_str(line);
4149                continue;
4150            }
4151            let body = line.trim_end_matches(['\n', '\r']);
4152            // (not inside quoted words)
4153            let mut quoted = false;
4154            let kept: Vec<&str> = body
4155                .split(' ')
4156                .filter(|t| {
4157                    // (a hairpin's mark may have its number: `\\<2`, `\\!2`)
4158                    let plain = t.trim_end_matches(|c: char| hairpin && c.is_ascii_digit());
4159                    let is = !quoted && marks.contains(&plain);
4160                    if t.matches('"').count() % 2 == 1 {
4161                        quoted = !quoted;
4162                    }
4163                    cut |= is;
4164                    !is
4165                })
4166                .collect();
4167            out.push_str(&kept.join(" "));
4168            out.push_str(&line[body.len()..]);
4169        }
4170        *s = out;
4171        cut
4172    };
4173    if strip(text, None) {
4174        return Some(what);
4175    }
4176    let from: String = msg
4177        .split("from bar ")
4178        .nth(1)?
4179        .chars()
4180        .take_while(|c| c.is_ascii_digit() || *c == '-')
4181        .collect();
4182    strip(done, Some(&from)).then_some(what)
4183}
4184
4185const OTTAVA_MARKS: [&str; 5] = ["\\8va", "\\8vb", "\\15ma", "\\15mb", "\\loco"];
4186
4187/// The ottava marks among a bar's marks that a bar left as a rest keeps, so that a line over
4188/// the bars before it still ends in it and one over the bars after it still starts: all of them
4189/// in order, but for a line that both starts and ends in the bar.
4190fn ottava_marks_kept<'a>(marks: impl Iterator<Item = &'a str>) -> Vec<String> {
4191    let mut kept: Vec<String> = Vec::new();
4192    for m in marks.filter(|m| OTTAVA_MARKS.contains(m)) {
4193        if m == "\\loco" && kept.last().is_some_and(|l| l != "\\loco") {
4194            kept.pop();
4195        } else {
4196            kept.push(m.to_string());
4197        }
4198    }
4199    kept
4200}
4201
4202/// The staff's bar the compiler will not have (a voice of it longer or shorter than the bar),
4203/// left as a bar's rest: its first voice's line rests, its other voices' and its words' lines go.
4204fn blank_bar(text: &mut String, msg: &str) -> Option<Unread> {
4205    // "bar 12 (line 40): P.1/2 lasts ...", "bar 12: V.1/1 lasts ..."
4206    let at = msg.find(" lasts ")?;
4207    let voice = msg[..at].rsplit(' ').next()?;
4208    let (part_staff, _) = voice.rsplit_once('/')?;
4209    let (part, staff) = part_staff.rsplit_once('.')?;
4210    let bar: String = msg[..at]
4211        .rsplit("bar ")
4212        .next()?
4213        .chars()
4214        .take_while(|c| c.is_ascii_digit() || *c == '-')
4215        .collect();
4216    let number: i64 = bar.parse().ok()?;
4217    let staff = rest_staff_bar(text, &bar, |base| {
4218        base == part_staff || (staff == "1" && base == part)
4219    })?;
4220    Some(Unread {
4221        bar: number,
4222        staff,
4223        why: format!("bar {number}, {}: {}", part_staff, &msg[at + 1..]),
4224        place: None,
4225        beside: Vec::new(),
4226    })
4227}
4228
4229/// The last mending of a system the compiler will not have: the bar its message names (the bar
4230/// a tie or a slur that pairs with nothing is from) left as a rest, in the staff the message
4231/// names or, if it names none, in every staff; in this system's text, or in the text before.
4232/// The staves' bars left so, or None if the message names no bar that is there.
4233fn blank_named(done: &mut String, text: &mut String, msg: &str) -> Option<Vec<Unread>> {
4234    let number = |key: &str| -> Option<String> {
4235        let at = msg.rfind(key)? + key.len();
4236        let n: String = msg[at..]
4237            .chars()
4238            .take_while(|c| c.is_ascii_digit() || *c == '-')
4239            .collect();
4240        (!n.is_empty()).then_some(n)
4241    };
4242    let bar = number("from bar ").or_else(|| number("bar "))?;
4243    // the voice as the compiler names it: `P.2/2`, or `V.1/1` for a part of one staff
4244    let voice = msg
4245        .split(|c: char| c.is_whitespace() || c == ',' || c == ':')
4246        .find(|w| {
4247            w.contains('/')
4248                && w.rsplit('/')
4249                    .next()
4250                    .is_some_and(|v| v.parse::<u8>().is_ok())
4251        });
4252    let staff: Option<(&str, &str)> = voice.and_then(|v| v.rsplit_once('/')).and_then(|(ps, _)| {
4253        ps.rsplit_once('.')
4254            .map(|(p, st)| (ps, if st == "1" { p } else { ps }))
4255    });
4256    let why = msg.lines().last().unwrap_or(msg);
4257    for target in [text, done] {
4258        let before = target.clone();
4259        // (every staff of the bar, one at a time, when the message names none)
4260        let staves: Vec<String> = match staff {
4261            Some((a, b)) if a == b => vec![a.to_string()],
4262            Some((a, b)) => vec![a.to_string(), b.to_string()],
4263            None => staves_of_bar(target, &bar),
4264        };
4265        let mut lost: Vec<Unread> = Vec::new();
4266        for st in staves {
4267            if let Some(name) = rest_staff_bar(target, &bar, |base| base == st) {
4268                lost.push(Unread {
4269                    bar: bar.parse().unwrap_or(0),
4270                    why: format!("bar {bar}, {name}: {why}"),
4271                    staff: name,
4272                    place: None,
4273                    beside: Vec::new(),
4274                });
4275            }
4276        }
4277        if *target != before {
4278            return Some(lost);
4279        }
4280    }
4281    None
4282}
4283
4284/// The staff's bar on the line the compiler names where it names no bar ("line 144: P.2: ...:
4285/// a tremolo's second note is a note, not a rest"), left as a bar's rest: whatever the compiler
4286/// will not have of a bar as written, the bar goes unread rather than the score. Only a line of
4287/// this system's text (`done` is the text before it, a line break between them).
4288fn blank_line(done: &str, text: &mut String, msg: &str) -> Option<Unread> {
4289    let last = msg.lines().last().unwrap_or(msg);
4290    let at = last.find("line ")? + 5;
4291    let n: usize = (last[at..].chars())
4292        .take_while(|c| c.is_ascii_digit())
4293        .collect::<String>()
4294        .parse()
4295        .ok()?;
4296    let k = n.checked_sub(done.split('\n').count() + 1)?;
4297    let lines: Vec<&str> = text.split('\n').collect();
4298    let (label, _) = lines.get(k)?.split_once(':')?;
4299    let base = label
4300        .split_whitespace()
4301        .next()?
4302        .split('/')
4303        .next()?
4304        .to_string();
4305    let bar = (lines[..k].iter().rev())
4306        .find_map(|l| l.strip_prefix("bar "))?
4307        .split_whitespace()
4308        .next()?
4309        .to_string();
4310    let staff = rest_staff_bar(text, &bar, |b| b == base)?;
4311    Some(Unread {
4312        bar: bar.parse().ok()?,
4313        why: format!("bar {bar}, {staff}: {last}"),
4314        staff,
4315        place: None,
4316        beside: Vec::new(),
4317    })
4318}
4319
4320/// A staff's bar that holds printed rests alone and could not be timed (rests that do not add
4321/// up to the bar: the others are hidden, or the bar is short) is read as what it is, a bar with
4322/// no note: a bar's rest. Where its rests stand in the bar is not said; nothing sounds in it.
4323fn rests_only(
4324    events: &[Ev],
4325    read: Result<Vec<Vec<Ev>>, String>,
4326    len: Q,
4327    x: f64,
4328) -> Result<Vec<Vec<Ev>>, String> {
4329    let printed = |e: &Ev| matches!(e.rest, crate::staff::Rest::Printed(_)) && e.heads.is_empty();
4330    if read.is_ok() || events.is_empty() || !events.iter().all(printed) {
4331        return read;
4332    }
4333    let mut rest = Ev::spacer(len, x);
4334    rest.rest = crate::staff::Rest::Bar;
4335    let marks = events.iter().flat_map(|e| e.before.iter().chain(&e.after));
4336    rest.before = ottava_marks_kept(marks.map(String::as_str));
4337    Ok(vec![vec![rest]])
4338}
4339
4340/// The staves that have a line in bar `bar` of `text`, by their names, in order.
4341fn staves_of_bar(text: &str, bar: &str) -> Vec<String> {
4342    let mut out: Vec<String> = Vec::new();
4343    let mut in_bar = false;
4344    for line in text.lines() {
4345        if let Some(n) = line.strip_prefix("bar ") {
4346            in_bar = n.split_whitespace().next() == Some(bar);
4347            continue;
4348        }
4349        let Some((label, _)) = line.split_once(':').filter(|_| in_bar) else {
4350            continue;
4351        };
4352        let base = label.split('/').next().unwrap_or("");
4353        if !label.contains(' ') && !out.iter().any(|o| o == base) {
4354            out.push(base.to_string());
4355        }
4356    }
4357    out
4358}
4359
4360/// Bar `bar`'s lines of the staff `mine` knows (by the name before the voice's number) left as a
4361/// bar's rest: its first voice's line rests, its other voices' and its words' lines go. The
4362/// staff's name as written, or None if the bar has none of it.
4363fn rest_staff_bar(text: &mut String, bar: &str, mine: impl Fn(&str) -> bool) -> Option<String> {
4364    let mut out = String::with_capacity(text.len());
4365    let mut in_bar = false;
4366    let mut rested = false;
4367    let mut name = None;
4368    // (its first voice's ottava marks stay: a line that starts or ends in the bar still does)
4369    let mut kept_at: Option<(usize, Vec<String>)> = None;
4370    for line in text.split_inclusive('\n') {
4371        if let Some(n) = line.strip_prefix("bar ") {
4372            in_bar = n.split_whitespace().next() == Some(bar);
4373            out.push_str(line);
4374            continue;
4375        }
4376        let Some((label, body)) = line.split_once(':').filter(|_| in_bar) else {
4377            out.push_str(line);
4378            continue;
4379        };
4380        // "P.1", "P.1/2", "P.1 lyrics", "V/2 lyrics[2]"
4381        let voice_label = label.split_whitespace().next().unwrap_or("");
4382        let base = voice_label.split('/').next().unwrap_or("");
4383        if !mine(base) {
4384            out.push_str(line);
4385        } else if !rested && !label.contains("lyrics") {
4386            rested = true;
4387            name = Some(base.to_string());
4388            out.push_str(&format!("{base}: "));
4389            kept_at = Some((out.len(), ottava_marks_kept(body.split_whitespace())));
4390            out.push_str("R\n");
4391        }
4392    }
4393    let staff = name?;
4394    if let Some((at, kept)) = kept_at.filter(|k| !k.1.is_empty()) {
4395        out.insert_str(at, &format!("{} ", kept.join(" ")));
4396    }
4397    *text = out;
4398    Some(staff)
4399}
4400
4401/// The staves' bars that stand under an ottava line in `text` (from bar `from` on, if given), as
4402/// (bar, staff): from each line's start to its end, a line that only ends there from the text's
4403/// start, one that does not end there to the text's end.
4404fn bars_under_ottavas(text: &str, from: Option<&str>) -> Vec<(String, String)> {
4405    let mut out: Vec<(String, String)> = Vec::new();
4406    let mut bars: Vec<&str> = Vec::new();
4407    let mut open: BTreeSet<&str> = BTreeSet::new();
4408    let mut on = from.is_none();
4409    for line in text.lines() {
4410        if let Some(n) = line.strip_prefix("bar ") {
4411            let n = n.split_whitespace().next().unwrap_or("");
4412            on |= Some(n) == from;
4413            if on {
4414                bars.push(n);
4415            }
4416            continue;
4417        }
4418        let Some((label, body)) = line.split_once(':').filter(|_| on && !bars.is_empty()) else {
4419            continue;
4420        };
4421        if label.contains(' ') {
4422            continue; // (a line of words)
4423        }
4424        let base = label.split('/').next().unwrap_or("");
4425        let bar = bars[bars.len() - 1];
4426        let mut under = open.contains(base);
4427        for t in body.split(' ').filter(|t| OTTAVA_MARKS.contains(t)) {
4428            if t == "\\loco" {
4429                if !open.remove(base) && !under {
4430                    // (it began in the text before)
4431                    out.extend(bars.iter().map(|b| (b.to_string(), base.to_string())));
4432                }
4433            } else {
4434                open.insert(base);
4435            }
4436            under = true;
4437        }
4438        if under {
4439            out.push((bar.to_string(), base.to_string()));
4440        }
4441    }
4442    out.sort();
4443    out.dedup();
4444    out
4445}
4446
4447/// [`without_lines`], and where what goes are ottava lines, the staves' bars under them left as
4448/// rests and listed in `lost`: their notes are printed an octave or two from where they sound,
4449/// and without the line they would be written at the wrong pitch.
4450fn without_lines_or_bars(
4451    done: &mut String,
4452    text: &mut String,
4453    msg: &str,
4454    lost: &mut Vec<Unread>,
4455) -> Option<&'static str> {
4456    let ottava = msg.contains("ottava") && !msg.contains("hairpin");
4457    let before = text.clone();
4458    let from: String = msg
4459        .split("from bar ")
4460        .nth(1)
4461        .unwrap_or("")
4462        .chars()
4463        .take_while(|c| c.is_ascii_digit() || *c == '-')
4464        .collect();
4465    let under = |t: &str, from: Option<&str>| match ottava {
4466        true => bars_under_ottavas(t, from),
4467        false => Vec::new(),
4468    };
4469    let (in_text, in_done) = (under(text, None), under(done, Some(&from)));
4470    let what = without_lines(done, text, msg)?;
4471    let (target, bars) = if *text != before {
4472        (text, in_text)
4473    } else {
4474        (done, in_done)
4475    };
4476    for (bar, staff) in bars {
4477        if let Some(name) = rest_staff_bar(target, &bar, |base| base == staff) {
4478            lost.push(Unread {
4479                bar: bar.parse().unwrap_or(0),
4480                why: format!("bar {bar}, {name}: under an ottava line that pairs with no other"),
4481                staff: name,
4482                place: None,
4483                beside: Vec::new(),
4484            });
4485        }
4486    }
4487    Some(what)
4488}
4489
4490/// What stands in a staff's bar, left to right, in words (`Place::seen`).
4491fn seen_in(evs: &[Ev], left: f64, sp: f64) -> Vec<String> {
4492    let mut order: Vec<&Ev> = evs
4493        .iter()
4494        .filter(|e| e.rest != crate::staff::Rest::Blank)
4495        .collect();
4496    order.sort_by(|a, b| a.x.total_cmp(&b.x));
4497    order
4498        .iter()
4499        .map(|e| {
4500            let at = (e.x - left) / sp;
4501            let what = match &e.rest {
4502                crate::staff::Rest::None => {
4503                    let names: Vec<String> = e
4504                        .places
4505                        .iter()
4506                        .map(|&p| crate::write::pitch_name(p, 0))
4507                        .collect();
4508                    let stem = match e.up {
4509                        Some(true) => "stem up",
4510                        Some(false) => "stem down",
4511                        None => "no stem",
4512                    };
4513                    let small = if e.grace.is_some() { ", small" } else { "" };
4514                    let tup = if e.tuplets.is_empty() {
4515                        String::new()
4516                    } else {
4517                        format!(", under a {}", e.tuplets[0].0)
4518                    };
4519                    format!("{} {stem}{small}{tup}", names.join(" "))
4520                }
4521                crate::staff::Rest::Bar => "a bar's rest".to_string(),
4522                _ => "rest".to_string(),
4523            };
4524            format!("{at:.1}: {what}, {} quarter(s)", e.written())
4525        })
4526        .collect()
4527}
4528
4529/// The span of the line of voice `voice` (as the compiler names it: `P.1/2`) in bar `bar`.
4530fn voice_line(s: &str, bar: &str, voice: &str) -> Option<(usize, usize)> {
4531    let (part_staff, v) = voice.rsplit_once('/')?;
4532    let (part, staff) = part_staff.rsplit_once('.')?;
4533    let tail = if v == "1" {
4534        String::new()
4535    } else {
4536        format!("/{v}")
4537    };
4538    let mut labels = vec![format!("{part}.{staff}{tail}")];
4539    if staff == "1" {
4540        labels.push(format!("{part}{tail}"));
4541    }
4542    let mut in_bar = false;
4543    for (a, b) in line_spans(s) {
4544        let t = &s[a..b];
4545        if let Some(n) = t.strip_prefix("bar ") {
4546            in_bar = n.split_whitespace().next() == Some(bar);
4547        } else if in_bar
4548            && t.split_once(':')
4549                .is_some_and(|(l, _)| labels.iter().any(|w| w == l.trim()))
4550        {
4551            return Some((a, b));
4552        }
4553    }
4554    None
4555}
4556
4557/// Where in bar `bar` the marks starting with one of `pats` stand on a staff's lines (the
4558/// compiler names a staff `P.1`; a part of one staff is written `P`).
4559fn staff_marks(s: &str, bar: &str, staff: &str, pats: &[&str]) -> Vec<usize> {
4560    let (part, st) = staff.rsplit_once('.').unwrap_or((staff, "1"));
4561    let mut out = Vec::new();
4562    let mut in_bar = false;
4563    for (a, b) in line_spans(s) {
4564        let t = &s[a..b];
4565        if let Some(n) = t.strip_prefix("bar ") {
4566            in_bar = n.split_whitespace().next() == Some(bar);
4567            continue;
4568        }
4569        let Some((label, _)) = t.split_once(':') else {
4570            continue;
4571        };
4572        let base = label.trim().split('/').next().unwrap_or("");
4573        if in_bar && (base == staff || (st == "1" && base == part)) {
4574            for q in marks_in(t, '\\') {
4575                if pats.iter().any(|p| t[q..].starts_with(p)) {
4576                    out.push(a + q);
4577                }
4578            }
4579        }
4580    }
4581    out
4582}
4583
4584/// The byte offsets of a char in a voice line's notes, outside quoted words.
4585fn marks_in(line: &str, c: char) -> Vec<usize> {
4586    let start = line.find(':').map_or(0, |k| k + 1);
4587    let mut quoted = false;
4588    let mut out = Vec::new();
4589    for (i, ch) in line.char_indices().skip_while(|&(i, _)| i < start) {
4590        if ch == '"' {
4591            quoted = !quoted;
4592        } else if ch == c && !quoted {
4593            out.push(i);
4594        }
4595    }
4596    out
4597}
4598
4599/// The last tie in a voice line on `pitch` (or on any pitch, `None`), taken out: the edited line.
4600fn untie_in(line: &str, pitch: Option<&str>) -> Option<String> {
4601    let start = line.find(':').map_or(0, |k| k + 1);
4602    let mut best: Option<String> = None;
4603    // the tokens, a chord's spaces inside one: (start, token)
4604    let mut toks: Vec<(usize, &str)> = Vec::new();
4605    let (mut chord, mut from) = (false, start);
4606    let bytes = line.as_bytes();
4607    for i in start..=line.len() {
4608        let c = bytes.get(i).copied().unwrap_or(b' ');
4609        if c == b'<' && (i == 0 || bytes[i - 1] != b'\\') {
4610            chord = true;
4611        } else if c == b'>' && chord {
4612            chord = false;
4613        } else if c == b' ' && !chord {
4614            if i > from {
4615                toks.push((from, &line[from..i]));
4616            }
4617            from = i + 1;
4618        }
4619    }
4620    for (a, tok) in toks {
4621        if !tok.contains('~') || tok.starts_with('"') {
4622            continue;
4623        }
4624        // the token's pitches: (offset in the token, name, its own tie)
4625        // (a chord's pitches run to its '>'; an accent `->` after the length is no chord's end)
4626        let slash = tok.find('/').unwrap_or(tok.len());
4627        let notes_end = match tok.find('<') {
4628            Some(c) if c < slash => tok[c..].find('>').map_or(slash, |k| c + k + 1),
4629            _ => slash,
4630        };
4631        let body = &tok[..notes_end];
4632        let mut pitches: Vec<(usize, &str, bool)> = Vec::new();
4633        let mut k = 0;
4634        for part in body.split([' ', '<', '>']) {
4635            let off = body[k..].find(part).map_or(k, |f| k + f);
4636            k = off + part.len();
4637            let part = part.rsplit(':').next().unwrap_or(part);
4638            let name = part.trim_end_matches(['~', '!', '?']);
4639            if !name.is_empty()
4640                && name
4641                    .chars()
4642                    .next()
4643                    .is_some_and(|c| ('a'..='g').contains(&c))
4644            {
4645                let off = off + body[off..].find(name).unwrap_or(0);
4646                pitches.push((off, name, part.contains('~')));
4647            }
4648        }
4649        let whole = tok[notes_end..].find('~').map(|k| notes_end + k);
4650        let hit = match pitch {
4651            None => !pitches.is_empty(),
4652            Some(p) => pitches.iter().any(|q| q.1 == p && (q.2 || whole.is_some())),
4653        };
4654        if !hit {
4655            continue;
4656        }
4657        let mut t = tok.to_string();
4658        // (a tie held over what follows is `~~`: both go, or stay, together)
4659        let run = |t: &str, k: usize| t[k..].chars().take_while(|c| *c == '~').count();
4660        match pitch {
4661            None => t = t.replace('~', ""),
4662            Some(p) => {
4663                if let Some(w) = whole {
4664                    // the chord's tie: its other pitches keep theirs
4665                    let mark = "~".repeat(run(&t, w));
4666                    t.replace_range(w..w + mark.len(), "");
4667                    for q in pitches.iter().rev().filter(|q| q.1 != p && !q.2) {
4668                        t.insert_str(q.0 + q.1.len(), &mark);
4669                    }
4670                } else if let Some(q) = pitches.iter().find(|q| q.1 == p && q.2) {
4671                    // (its tie after the mark of a printed accidental: `bf2!~`)
4672                    let k = q.0 + q.1.len();
4673                    let k = k + t[k..].chars().take_while(|c| "!?".contains(*c)).count();
4674                    let n = run(&t, k);
4675                    t.replace_range(k..k + n, "");
4676                }
4677            }
4678        }
4679        if t == tok {
4680            continue;
4681        }
4682        best = Some(format!(
4683            "{}{}{}",
4684            &line[..a],
4685            t,
4686            &line[(a + tok.len()).min(line.len())..]
4687        ));
4688    }
4689    best
4690}
4691
4692/// The number written after a hairpin's mark at `k` (`\<2`, `\!2`: "2"; plain: none).
4693fn mark_number(s: &str, k: usize) -> String {
4694    (s[k + 2..].chars())
4695        .take_while(|c| c.is_ascii_digit())
4696        .collect()
4697}
4698
4699/// A compile error naming a slur or a tie that does not pair: that mark taken out of the
4700/// system's text, or of the text before it. What was taken out, or None.
4701fn unpair(done: &mut String, text: &mut String, msg: &str) -> Option<String> {
4702    let num_after = |key: &str| -> Option<String> {
4703        let k = msg.find(key)? + key.len();
4704        Some(
4705            msg[k..]
4706                .chars()
4707                .take_while(|c| c.is_ascii_digit())
4708                .collect(),
4709        )
4710    };
4711    let line_no: Option<usize> = msg
4712        .split(", line ")
4713        .nth(1)
4714        .and_then(|t| t.split(':').next())
4715        .and_then(|t| t.trim().parse().ok());
4716    // the line the error names, as (in the text before, start, end)
4717    let named = |done: &str, text: &str| -> Option<(bool, usize, usize)> {
4718        let all = format!("{done}\n{text}");
4719        let spans = line_spans(&all);
4720        let (a, b) = *spans.get(line_no?.checked_sub(1)?)?;
4721        let split = done.len() + 1;
4722        if a >= split {
4723            Some((false, a - split, b - split))
4724        } else if b <= done.len() {
4725            Some((true, a, b))
4726        } else {
4727            None
4728        }
4729    };
4730    let label_of = |done: &str, text: &str| -> Option<String> {
4731        let (d, a, b) = named(done, text)?;
4732        let s = if d { done } else { text };
4733        Some(s[a..b].split_once(':')?.0.trim().to_string())
4734    };
4735    // a voice named by its line's label, as the compiler names voices
4736    let voice_of = |label: &str| -> String {
4737        let (staff, v) = label.split_once('/').unwrap_or((label, "1"));
4738        if staff.contains('.') {
4739            format!("{staff}/{v}")
4740        } else {
4741            format!("{staff}.1/{v}")
4742        }
4743    };
4744    let edit = |s: &mut String, span: (usize, usize), f: &dyn Fn(&str) -> Option<String>| -> bool {
4745        match f(&s[span.0..span.1]) {
4746            Some(new) => {
4747                s.replace_range(span.0..span.1, &new);
4748                true
4749            }
4750            None => false,
4751        }
4752    };
4753    let in_either = |done: &mut String,
4754                     text: &mut String,
4755                     bar: &str,
4756                     voice: &str,
4757                     f: &dyn Fn(&str) -> Option<String>|
4758     -> bool {
4759        if let Some(sp) = voice_line(text, bar, voice) {
4760            return edit(text, sp, f);
4761        }
4762        if let Some(sp) = voice_line(done, bar, voice) {
4763            return edit(done, sp, f);
4764        }
4765        false
4766    };
4767    if let Some(k) = msg.find(": a hairpin opens on ") {
4768        // the hairpin before is closed where the new one opens
4769        let bar: String = msg[..k].rsplit(' ').next()?.to_string();
4770        let rest = &msg[k + ": a hairpin opens on ".len()..];
4771        let (staff, rest) = rest.split_once(" while one from bar ")?;
4772        let from: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
4773        // (of the hairpins of the number the message names: `close it with \!2`)
4774        let nth: String = (msg.split("close it with \\!").nth(1).unwrap_or(""))
4775            .chars()
4776            .take_while(|c| c.is_ascii_digit())
4777            .collect();
4778        let pick = |s: &str, v: Vec<usize>| -> Option<usize> {
4779            let v: Vec<usize> = (v.into_iter())
4780                .filter(|&k| mark_number(s, k) == nth)
4781                .collect();
4782            if from == bar {
4783                v.get(1).copied()
4784            } else {
4785                v.first().copied()
4786            }
4787        };
4788        let opens = ["\\<", "\\>"];
4789        let close = format!("\\!{nth} ");
4790        if let Some(k) = pick(text, staff_marks(text, &bar, staff, &opens)) {
4791            text.insert_str(k, &close);
4792        } else {
4793            let k = pick(done, staff_marks(done, &bar, staff, &opens))?;
4794            done.insert_str(k, &close);
4795        }
4796        return Some(format!("a hairpin's end (bar {bar})"));
4797    }
4798    if let Some(at) = msg.find(" closes no hairpin on ") {
4799        // "bar 12: \! closes no hairpin on P.1", or `\!2` for a second hairpin's end
4800        let k = msg[..at].rfind(": \\!")?;
4801        let nth = &msg[k + 4..at];
4802        let bar: String = msg[..k].rsplit(' ').next()?.to_string();
4803        let staff = msg[at + " closes no hairpin on ".len()..].trim();
4804        let cut = |s: &mut String| -> bool {
4805            let ends = staff_marks(s, &bar, staff, &["\\!"]);
4806            match ends.into_iter().find(|&k| mark_number(s, k) == nth) {
4807                Some(k) => {
4808                    // (with its number, and the space after it)
4809                    let end = k + 2 + nth.len();
4810                    let end = end + usize::from(s[end..].starts_with(' '));
4811                    s.replace_range(k..end, "");
4812                    true
4813                }
4814                None => false,
4815            }
4816        };
4817        return (cut(text) || cut(done))
4818            .then(|| format!("a hairpin's end with no start (bar {bar})"));
4819    }
4820    if msg.contains("a slur ends that never began") {
4821        let (d, a, b) = named(done, text)?;
4822        let s = if d { &mut *done } else { &mut *text };
4823        let k = *marks_in(&s[a..b], ')').first()?;
4824        s.replace_range(a + k..a + k + 1, "");
4825        return Some(format!(
4826            "a slur's end with no start (bar {})",
4827            num_after("bar ")?
4828        ));
4829    }
4830    if let Some(k) = msg.find("a slur in ") {
4831        let rest = &msg[k + "a slur in ".len()..];
4832        let (voice, rest) = rest.split_once(" from bar ")?;
4833        let bar: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
4834        let f = |l: &str| -> Option<String> {
4835            let k = *marks_in(l, '(').last()?;
4836            let mut l = l.to_string();
4837            l.replace_range(k..k + 1, "");
4838            Some(l)
4839        };
4840        return in_either(done, text, &bar, voice, &f)
4841            .then(|| format!("a slur with no end (bar {bar})"));
4842    }
4843    if let Some(k) = msg.find("a tie on ") {
4844        let rest = &msg[k + "a tie on ".len()..];
4845        let (pitch, rest) = rest.split_once(" in ")?;
4846        let (voice, rest) = rest.split_once(" from bar ")?;
4847        let bar: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
4848        let pitch = pitch.to_string();
4849        let f = move |l: &str| untie_in(l, Some(&pitch));
4850        return in_either(done, text, &bar, voice, &f)
4851            .then(|| format!("a tie that lands nowhere (bar {bar})"));
4852    }
4853    if let Some(from) = num_after("the tie from bar ") {
4854        let pitch = msg
4855            .split(" wants ")
4856            .nth(1)?
4857            .split(" next")
4858            .next()?
4859            .to_string();
4860        let voice = voice_of(&label_of(done, text)?);
4861        let f = move |l: &str| untie_in(l, Some(&pitch));
4862        return in_either(done, text, &from, &voice, &f)
4863            .then(|| format!("a tie to another note (bar {from})"));
4864    }
4865    if let Some(from) = num_after("a tie from bar ") {
4866        let voice = voice_of(&label_of(done, text)?);
4867        let f = |l: &str| untie_in(l, None);
4868        return in_either(done, text, &from, &voice, &f)
4869            .then(|| format!("a tie to a rest (bar {from})"));
4870    }
4871    None
4872}
4873
4874/// The staves whose bar is lost with another's: a staff's notes beamed with its part's other
4875/// staff are read there (`cross_staff`), and when that staff's bar cannot be read, this one's
4876/// is not the rests left behind either.
4877fn lost_with_the_other_staff(
4878    voices: &BarVoices,
4879    evs: &[Vec<Ev>],
4880    names: &[String],
4881) -> BTreeSet<usize> {
4882    let mut lost = BTreeSet::new();
4883    for (i, v) in voices.iter().enumerate() {
4884        if v.is_ok() {
4885            continue;
4886        }
4887        let part = names[i].split('.').next().unwrap_or("");
4888        for n in evs[i].iter().filter_map(|e| e.on_staff) {
4889            let from = format!("{part}.{n}");
4890            lost.extend(names.iter().position(|name| *name == from));
4891        }
4892    }
4893    lost
4894}
4895
4896use crate::ties::BarVoices;
4897
4898/// Whether ledger lines from a staff's edge at `from`, going `dir` (1 down, -1 up), reach a
4899/// head: it is on the last of them or just past it.
4900fn ledgers_reach(pg: &Page, h: &Glyph, from: f64, dir: f64, sp: f64) -> bool {
4901    let mut k = 1;
4902    while pg.hlines.iter().any(|l| {
4903        (l.y - (from + dir * k as f64 * sp)).abs() < 0.15 * sp
4904            && l.x0 <= h.x0 + 0.3 * sp
4905            && l.x1 >= h.x1 - 0.3 * sp
4906            && l.x1 - l.x0 < 4.0 * sp
4907    }) {
4908        k += 1;
4909    }
4910    (h.y - (from + dir * (k - 1) as f64 * sp)) * dir < 0.75 * sp
4911}
4912
4913/// Notes over a system's first staff that are the system above's: low notes of its last staff
4914/// (at `ceiling`), on ledger lines hanging from it that do not reach this staff. They are left
4915/// out with their dots and accidentals.
4916fn above_system(pg: &Page, staff: &Staff, ceiling: f64, glyphs: &mut Vec<Glyph>) {
4917    let sp = staff.sp();
4918    let top = staff.top();
4919    if ceiling <= 0.0 {
4920        return;
4921    }
4922    let theirs: Vec<Glyph> = glyphs
4923        .iter()
4924        .filter(|h| {
4925            smufl::head(h.code).is_some()
4926                && h.y < top - 0.6 * sp
4927                && h.y > ceiling + 0.6 * sp
4928                && ledgers_reach(pg, h, ceiling, 1.0, sp)
4929                && !ledgers_reach(pg, h, top, -1.0, sp)
4930        })
4931        .copied()
4932        .collect();
4933    glyphs.retain(|g| {
4934        !theirs.iter().any(|h| {
4935            let off = if g.code == smufl::DOT { 0.7 } else { 0.3 };
4936            (g.y - h.y).abs() < off * sp
4937                && g.x0 > h.x0 - 4.0 * sp
4938                && g.x0 < h.x1 + 2.0 * sp
4939                && (g.x0 == h.x0 && g.code == h.code
4940                    || smufl::accidental(g.code).is_some()
4941                    || g.code == smufl::DOT)
4942        })
4943    });
4944}
4945
4946/// A staff of printed rests alone (a half rest in a short bar): what they hold, its longest
4947/// voice's; none where a rest stands for the whole bar or time is unprinted.
4948fn rests_held(vs: &[Vec<Ev>]) -> Option<Q> {
4949    let printed = |e: &Ev| matches!(e.rest, crate::staff::Rest::Printed(_));
4950    (!vs.is_empty() && vs.iter().flatten().all(printed))
4951        .then(|| {
4952            vs.iter()
4953                .map(|v| v.iter().map(|e| e.takes()).sum::<Q>())
4954                .max()
4955        })
4956        .flatten()
4957}
4958
4959#[cfg(test)]
4960mod tests {
4961    use super::*;
4962
4963    fn staff(top: f64) -> Staff {
4964        Staff {
4965            lines: [top, top + 1.0, top + 2.0, top + 3.0, top + 4.0],
4966            left: 0.0,
4967            right: 100.0,
4968            breaks: Vec::new(),
4969        }
4970    }
4971
4972    #[test]
4973    fn a_short_flat_tie_that_reaches_no_head_leaves_its_note_to_ring() {
4974        let head = |x: f64, y: f64| Glyph {
4975            code: 0xE0A4,
4976            x0: x,
4977            x1: x + 1.2,
4978            y,
4979            size: 4.0,
4980        };
4981        let note = Ev::new(vec![head(10.0, 20.0)], None, Some(true));
4982        let nothing = |_: &Glyph| false;
4983        // two spaces long from the head's middle, 0.73 under it and 0.54 deep
4984        let curve = (10.6, 12.6, 20.73, 21.27);
4985        assert!(rings_on(curve, &note, &nothing, 1.0));
4986        // one that reaches a head at its height is a tie to it; a longer one, or one that
4987        // rises, is a slur; a small note's is its slur to its note
4988        assert!(!rings_on(curve, &note, &|_| true, 1.0));
4989        assert!(!rings_on((10.6, 14.0, 20.73, 21.27), &note, &nothing, 1.0));
4990        assert!(!rings_on((10.6, 12.6, 19.9, 21.27), &note, &nothing, 1.0));
4991        let mut small = note.clone();
4992        small.grace = Some(false);
4993        assert!(!rings_on(curve, &small, &nothing, 1.0));
4994        // where the curve ends: just before a head, or over its left part
4995        assert!(ends_at(12.6, &head(12.9, 20.0), 1.0) && !ends_at(12.6, &head(14.5, 20.0), 1.0));
4996    }
4997
4998    #[test]
4999    fn a_ties_curve_ends_by_its_heads_and_a_slurs_stands_off_them() {
5000        // a head 1.2 wide at x 10, y 20 (a staff space of 1)
5001        let head = Glyph {
5002            code: 0xE0A4,
5003            x0: 10.0,
5004            x1: 11.2,
5005            y: 20.0,
5006            size: 4.0,
5007        };
5008        // a tie over the head: from its middle, 0.73 above; one inside a chord: from just
5009        // after the head, at its height
5010        assert!(curve_ends_by((10.6, 18.3, 19.27), &head, 1.0));
5011        assert!(curve_ends_by((11.4, 19.9, 20.6), &head, 1.0));
5012        // a slur stands 0.9 off; a curve that starts by the next note is not this head's; one
5013        // drawn through the head is no tie
5014        assert!(!curve_ends_by((10.6, 17.5, 19.1), &head, 1.0));
5015        assert!(!curve_ends_by((12.4, 18.3, 19.27), &head, 1.0));
5016        assert!(!curve_ends_by((10.6, 18.7, 19.98), &head, 1.0));
5017    }
5018
5019    #[test]
5020    fn a_slurs_end_is_by_the_note_whose_middle_or_stem_it_stands_at() {
5021        // two notes set close (sixteenths), both stemmed up, the stem at the head's right edge
5022        let note = |x: f64, stem: Option<crate::page::VLine>, up: Option<bool>| {
5023            let head = Glyph {
5024                code: 0xE0A4,
5025                x0: x,
5026                x1: x + 1.2,
5027                y: 20.0,
5028                size: 4.0,
5029            };
5030            Ev::new(vec![head], stem, up)
5031        };
5032        let stem = |x: f64| {
5033            Some(crate::page::VLine {
5034                x,
5035                y0: 16.5,
5036                y1: 20.0,
5037                w: 0.1,
5038            })
5039        };
5040        let first = note(10.0, stem(11.2), Some(true));
5041        let second = note(11.8, stem(13.0), Some(true));
5042        // a slur over them that starts just past the first's stem is nearer the first
5043        let (a, b) = (
5044            slur_end_beside(&first, 11.3, true),
5045            slur_end_beside(&second, 11.3, true),
5046        );
5047        assert!((a - 0.1).abs() < 1e-9 && (b - 1.1).abs() < 1e-9 && a < b);
5048        // between the middle (10.6) and the stem: right at the note
5049        assert_eq!(slur_end_beside(&first, 10.9, true), 0.0);
5050        // a slur under an up stem has only the middle to stand at
5051        assert!((slur_end_beside(&first, 11.2, false) - 0.6).abs() < 1e-9);
5052        // a note with no stem: the middle only
5053        let bare = note(10.0, None, None);
5054        assert!((slur_end_beside(&bare, 11.2, true) - 0.6).abs() < 1e-9);
5055        assert_eq!(slur_end_beside(&bare, 10.6, false), 0.0);
5056    }
5057
5058    #[test]
5059    fn of_two_voices_notes_a_slurs_end_takes_the_one_it_is_nearer_in_height() {
5060        let head = |y: f64| Glyph {
5061            code: 0xE0A4,
5062            x0: 10.0,
5063            x1: 11.2,
5064            y,
5065            size: 4.0,
5066        };
5067        let stem = |y0: f64, y1: f64| {
5068            Some(crate::page::VLine {
5069                x: 11.2,
5070                y0,
5071                y1,
5072                w: 0.1,
5073            })
5074        };
5075        let up = Ev::new(vec![head(20.0)], stem(16.5, 20.0), Some(true));
5076        let down = Ev::new(vec![head(22.0)], stem(22.0, 25.5), Some(false));
5077        // over: the end at 16.0 meets the up-stem note's stem end, 0.5 off, not the other's head
5078        let (a, b) = (
5079            slur_end_outside(&up, 16.0, true),
5080            slur_end_outside(&down, 16.0, true),
5081        );
5082        assert!((a - 0.5).abs() < 1e-9 && (b - 6.0).abs() < 1e-9);
5083        // under: the end at 26.0 meets the down-stem note's stem end
5084        let (a, b) = (
5085            slur_end_outside(&down, 26.0, false),
5086            slur_end_outside(&up, 26.0, false),
5087        );
5088        assert!((a - 0.5).abs() < 1e-9 && (b - 6.0).abs() < 1e-9);
5089    }
5090
5091    #[test]
5092    fn a_ties_head_is_on_the_curves_own_side() {
5093        let head = |y: f64| Glyph {
5094            code: 0xE0A4,
5095            x0: 10.0,
5096            x1: 11.2,
5097            y,
5098            size: 4.0,
5099        };
5100        // a curve that arches up stands over its head: one above its end is across it
5101        let over = crate::page::Curve {
5102            x0: 10.0,
5103            y0: 17.0,
5104            x1: 20.0,
5105            y1: 18.0,
5106            ya: 18.0,
5107            yb: 18.0,
5108        };
5109        assert!(over.over());
5110        assert!(!across_the_curve(&over, &head(18.7), 1.0));
5111        assert!(across_the_curve(&over, &head(17.0), 1.0));
5112        // one that hangs stands under its head
5113        let hung = crate::page::Curve {
5114            x0: 10.0,
5115            y0: 22.0,
5116            x1: 20.0,
5117            y1: 23.0,
5118            ya: 22.0,
5119            yb: 22.0,
5120        };
5121        assert!(!hung.over());
5122        assert!(!across_the_curve(&hung, &head(21.3), 1.0));
5123        assert!(across_the_curve(&hung, &head(23.0), 1.0));
5124    }
5125
5126    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<(f64, f64)> {
5127        vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
5128    }
5129
5130    #[test]
5131    fn a_slur_or_tie_that_pairs_with_nothing_is_taken_out() {
5132        let mut done = "title: t".to_string();
5133        // a slur's end with no start: the line the error names (the text's lines follow the
5134        // text before)
5135        let mut text = "bar 1\nP: c4/4 d4/4) e4/2\n".to_string();
5136        let what = unpair(
5137            &mut done,
5138            &mut text,
5139            "bar 1, line 3: a slur ends that never began",
5140        );
5141        assert!(what.is_some());
5142        assert_eq!(text, "bar 1\nP: c4/4 d4/4 e4/2\n");
5143        // a slur with no end: the last start in the voice's line of its bar
5144        let mut text = "bar 2\nP.1: c4/4( d4/4( e4/2)\nP.1/2: c4/1\n".to_string();
5145        unpair(
5146            &mut done,
5147            &mut text,
5148            "a slur in P.1/1 from bar 2 never ends",
5149        )
5150        .unwrap();
5151        assert_eq!(text, "bar 2\nP.1: c4/4( d4/4 e4/2)\nP.1/2: c4/1\n");
5152        // a chord's tie on one pitch: the others keep theirs
5153        let mut text = "bar 3\nP.1: r/2 <a3 cs4>/2~\n".to_string();
5154        unpair(
5155            &mut done,
5156            &mut text,
5157            "a tie on a3 in P.1/1 from bar 3 never lands",
5158        )
5159        .unwrap();
5160        assert_eq!(text, "bar 3\nP.1: r/2 <a3 cs4~>/2\n");
5161        // an accent after the length is no chord's end
5162        let mut text = "bar 4\nP.1/2: gs4/2-> a4!/2~->\n".to_string();
5163        unpair(
5164            &mut done,
5165            &mut text,
5166            "a tie on a4 in P.1/2 from bar 4 never lands",
5167        )
5168        .unwrap();
5169        assert_eq!(text, "bar 4\nP.1/2: gs4/2-> a4!/2->\n");
5170        // a tie into another voice, from the system before
5171        let mut before = "bar 5\nP: <c4 e4~>/1\n".to_string();
5172        let mut text = "bar 6 system\nP: d4/1\n".to_string();
5173        let msg = "bar 6, line 5: the tie from bar 5 wants e4 next, and this note is d4";
5174        unpair(&mut before, &mut text, msg).unwrap();
5175        assert_eq!(before, "bar 5\nP: <c4 e4>/1\n");
5176        // a hairpin opened over one still open: the first is closed where the second opens
5177        let mut text = "bar 7\nP.1: \\< c4/2 \\> d4/2\n".to_string();
5178        let msg = "bar 7: a hairpin opens on P.1 while one from bar 7 is open (close it with \\!)";
5179        unpair(&mut done, &mut text, msg).unwrap();
5180        assert_eq!(text, "bar 7\nP.1: \\< c4/2 \\! \\> d4/2\n");
5181        let mut text = "bar 8\nP.1: c4/2 \\! d4/2\n".to_string();
5182        unpair(&mut done, &mut text, "bar 8: \\! closes no hairpin on P.1").unwrap();
5183        assert_eq!(text, "bar 8\nP.1: c4/2 d4/2\n");
5184        // what it cannot place it leaves
5185        let mut text = "bar 9\nP: c4/1\n".to_string();
5186        assert!(unpair(
5187            &mut done,
5188            &mut text,
5189            "a slur in Q.1/1 from bar 9 never ends"
5190        )
5191        .is_none());
5192    }
5193
5194    #[test]
5195    fn a_system_set_close_over_the_next_ends_its_band_halfway() {
5196        // staves at 10 and 24 (a space apart): the first's band would reach 6 under its foot (20),
5197        // past the next one's top; it stops halfway (19)
5198        let line = |y: f64| crate::page::HLine {
5199            x0: 0.0,
5200            x1: 90.0,
5201            y,
5202            w: 0.1,
5203        };
5204        let pg = Page {
5205            width: 100.0,
5206            hlines: [10.0, 24.0]
5207                .iter()
5208                .flat_map(|&t| (0..5).map(move |k| line(t + k as f64)))
5209                .collect(),
5210            ..Page::default()
5211        };
5212        assert_eq!(band_floor(&pg, &staff(10.0), 1.0), 19.0);
5213        // alone on its page: six spaces
5214        let alone = Page {
5215            hlines: pg.hlines[..5].to_vec(),
5216            ..pg.clone()
5217        };
5218        assert_eq!(band_floor(&alone, &staff(10.0), 1.0), 20.0);
5219    }
5220
5221    #[test]
5222    fn a_page_with_thick_stems_parts_barlines_by_them() {
5223        let v = |w: f64, len: f64| crate::page::VLine {
5224            x: 0.0,
5225            y0: 0.0,
5226            y1: len,
5227            w,
5228        };
5229        // stems 0.14 spaces wide, barlines 0.16: the stems are the commonest stem-long lines
5230        let mut lines: Vec<_> = (0..20).map(|_| v(0.7, 17.0)).collect();
5231        lines.extend((0..6).map(|_| v(0.8, 20.0)));
5232        let pg = Page {
5233            vlines: lines,
5234            ..Page::default()
5235        };
5236        assert!((pg.barline_width(5.0) - 0.75).abs() < 1e-9);
5237        // thin stems: a thirteenth of a space
5238        let pg = Page {
5239            vlines: (0..20).map(|_| v(0.4, 17.0)).collect(),
5240            ..Page::default()
5241        };
5242        assert!((pg.barline_width(5.0) - 0.65).abs() < 1e-9);
5243    }
5244
5245    #[test]
5246    fn a_bar_the_compiler_will_not_have_is_left_as_a_rest() {
5247        let mut text =
5248            "bar 4\nV: c5/4 d5 e5\nV lyrics: la la la\nP.1: c4/1\nP.1/2: e3/2 g3\nP.2: c3/1\nbar 5\nP.1: d4/1\n"
5249                .to_string();
5250        let msg = "bar 4 (line 9): P.1/2 lasts 3 quarter(s), the bar 4 quarter(s) (4/4)";
5251        let u = blank_bar(&mut text, msg).unwrap();
5252        assert_eq!((u.bar, u.staff.as_str()), (4, "P.1"));
5253        assert_eq!(
5254            text,
5255            "bar 4\nV: c5/4 d5 e5\nV lyrics: la la la\nP.1: R\nP.2: c3/1\nbar 5\nP.1: d4/1\n"
5256        );
5257        // a part of one staff, its words with it
5258        let msg = "bar 4: V.1/1 lasts 3 quarter(s), other voices 4 quarter(s)";
5259        let u = blank_bar(&mut text, msg).unwrap();
5260        assert_eq!((u.bar, u.staff.as_str()), (4, "V"));
5261        assert!(text.starts_with("bar 4\nV: R\nP.1: R\n"));
5262        assert!(blank_bar(&mut text, "bar 9: a slur ends that never began").is_none());
5263    }
5264
5265    #[test]
5266    fn a_line_the_compiler_will_not_have_and_names_no_bar_for_is_left_as_a_rest() {
5267        let done = "title x\nbar 3\nP.1: c4/1";
5268        let mut text = "bar 4\nP.1: c4/1\nP.2: c3/2-trem1= s/2\nbar 5\nP.1: d4/1\n".to_string();
5269        let msg = "line 6: P.2: c3/2-trem1= s/2: a tremolo's second note is a note, not a rest";
5270        let u = blank_line(done, &mut text, msg).unwrap();
5271        assert_eq!((u.bar, u.staff.as_str()), (4, "P.2"));
5272        assert_eq!(text, "bar 4\nP.1: c4/1\nP.2: R\nbar 5\nP.1: d4/1\n");
5273        // (a line of the text before is not this system's to rest)
5274        assert!(blank_line(done, &mut text, "line 3: P.1: c4/1: no").is_none());
5275    }
5276
5277    #[test]
5278    fn a_bar_of_rests_alone_that_do_not_add_up_is_a_bar_s_rest() {
5279        let rest = |x: f64| {
5280            let mut e = Ev::spacer(Q::new(1, 2), x);
5281            e.rest = crate::staff::Rest::Printed(Glyph {
5282                code: 0xE4E6,
5283                x0: x,
5284                x1: x + 1.0,
5285                y: 0.0,
5286                size: 4.0,
5287            });
5288            e
5289        };
5290        let evs = vec![rest(0.0), rest(12.0)];
5291        let read = rests_only(&evs, Err("no".to_string()), Q::int(3), 0.0).unwrap();
5292        assert_eq!((read.len(), read[0].len()), (1, 1));
5293        assert_eq!(read[0][0].rest, crate::staff::Rest::Bar);
5294        // (not a bar with a note in it, nor one with nothing at all)
5295        let mut with = evs.clone();
5296        with.push(Ev::new(
5297            vec![Glyph {
5298                code: 0xE0A4,
5299                x0: 6.0,
5300                x1: 7.2,
5301                y: 0.0,
5302                size: 4.0,
5303            }],
5304            None,
5305            Some(true),
5306        ));
5307        assert!(rests_only(&with, Err("no".to_string()), Q::int(3), 0.0).is_err());
5308        assert!(rests_only(&[], Err("no".to_string()), Q::int(3), 0.0).is_err());
5309    }
5310
5311    #[test]
5312    fn a_staff_whose_notes_went_to_one_that_cannot_be_read_is_not_read_either() {
5313        let names = ["V".to_string(), "P.1".to_string(), "P.2".to_string()];
5314        // the upper staff's note was read on the lower (beamed with its notes), which fails
5315        let mut moved = Ev::spacer(Q::ONE, 5.0);
5316        moved.on_staff = Some(1);
5317        let evs = vec![Vec::new(), vec![Ev::spacer(Q::ONE, 5.0)], vec![moved]];
5318        let voices: BarVoices = vec![Ok(Vec::new()), Ok(Vec::new()), Err("no".into())];
5319        let lost = lost_with_the_other_staff(&voices, &evs, &names);
5320        assert_eq!(lost.into_iter().collect::<Vec<_>>(), [1]);
5321        // read, it takes nothing with it
5322        let voices: BarVoices = vec![Ok(Vec::new()), Ok(Vec::new()), Ok(Vec::new())];
5323        assert!(lost_with_the_other_staff(&voices, &evs, &names).is_empty());
5324    }
5325
5326    #[test]
5327    fn notes_after_a_system_s_last_barline_are_a_bar_that_ends_with_the_staves() {
5328        let g = |code: u32, x0: f64| Glyph {
5329            code,
5330            x0,
5331            x1: x0 + 1.2,
5332            y: 22.0,
5333            size: 4.0,
5334        };
5335        // barlines at 40 and 70, the staves end at 100: a note at 80 is in a bar with no
5336        // barline of its own
5337        let groups = vec![vec![40.0], vec![70.0]];
5338        let open = vec![vec![g(0xE0A4, 20.0), g(0xE0A4, 50.0), g(0xE0A4, 80.0)]];
5339        assert_eq!(open_end(&open, &groups, 100.0, 1.0), Some(100.0));
5340        // the last barline at the staves' end, or only a clef after it: no bar more
5341        let closed = vec![vec![g(0xE0A4, 20.0), g(0xE0A4, 50.0), g(0xE050, 72.0)]];
5342        assert_eq!(open_end(&closed, &groups, 100.0, 1.0), None);
5343        let groups = vec![vec![40.0], vec![99.5, 100.0]];
5344        assert_eq!(open_end(&open, &groups, 100.0, 1.0), None);
5345    }
5346
5347    #[test]
5348    fn a_staff_opens_in_the_last_clef_before_its_first_note() {
5349        let g = |code: u32, x0: f64, y: f64| Glyph {
5350            code,
5351            x0,
5352            x1: x0 + 2.0,
5353            y,
5354            size: 4.0,
5355        };
5356        // the staff's lines at 20 to 24: a bass clef on its fourth line, then a treble clef on
5357        // its second, both before the first note at 12; a clef after it is a change inside
5358        let st = staff(20.0);
5359        let gs = [
5360            g(0xE062, 1.0, 21.0),
5361            g(0xE050, 6.0, 23.0),
5362            g(0xE0A4, 12.0, 22.0),
5363            g(0xE062, 30.0, 21.0),
5364        ];
5365        assert_eq!(opening_clef(&gs, &st, 12.0), Some("treble"));
5366        assert_eq!(opening_clef(&gs[..1], &st, 12.0), Some("bass"));
5367        assert_eq!(opening_clef(&gs[2..], &st, 12.0), None);
5368        // (the signature between the two is set for the first)
5369        let both = clefs_before(&gs, &st, 12.0);
5370        assert_eq!((both[0].1, both[1].1, both.len()), ("bass", "treble", 2));
5371        // a C clef is the clef of the line it is set on
5372        assert_eq!(clef_of(&g(0xE05C, 1.0, 22.0), &st), Some("alto"));
5373        assert_eq!(clef_of(&g(0xE05C, 1.0, 21.0), &st), Some("tenor"));
5374        assert_eq!(clef_of(&g(0xE05C, 1.0, 24.0), &st), Some("soprano"));
5375    }
5376
5377    #[test]
5378    fn a_bar_left_as_a_rest_keeps_the_ottava_lines_that_start_or_end_in_it() {
5379        let kept = |t: &str| ottava_marks_kept(t.split(' ')).join(" ");
5380        assert_eq!(kept("c4/4 \\loco d4/2."), "\\loco");
5381        assert_eq!(kept("\\loco c4/2 \\8va d4/2"), "\\loco \\8va");
5382        // one that starts and ends in the bar is over nothing now
5383        assert_eq!(kept("c4/4 \\8va d4/4 \\loco e4/2"), "");
5384        assert_eq!(kept("\\p c4/1 ^\"a\""), "");
5385        let mut text = "bar 4\nP.1: c4/2 \\loco d4/4\nP.1/2: e3/2 g3\nP.2: c3/1\n".to_string();
5386        let msg = "bar 4 (line 9): P.1/1 lasts 3 quarter(s), the bar 4 quarter(s) (4/4)";
5387        assert!(blank_bar(&mut text, msg).is_some());
5388        assert_eq!(text, "bar 4\nP.1: \\loco R\nP.2: c3/1\n");
5389    }
5390
5391    #[test]
5392    fn the_bars_under_ottava_lines_left_out_are_left_as_rests() {
5393        // the line from bar 1 never ends: its mark goes, and the bars it was over are not read
5394        let mut done =
5395            "bar 1\nV: c5/1\nP.1: c5/2 \\8va d5/2\nP.2: c3/1\nbar 2\nV: c5/1\nP.1: e5/1\nP.2: c3/1\n"
5396                .to_string();
5397        let mut text = "bar 3\nV: c5/1\nP.1: \\8va c5/1\nP.2: c3/1\n".to_string();
5398        let msg =
5399            "bar 3: an ottava opens on P.1 while the one from bar 1 is open (close it with \\loco)";
5400        let mut lost = Vec::new();
5401        assert!(without_lines_or_bars(&mut done, &mut text, msg, &mut lost).is_some());
5402        assert_eq!(text, "bar 3\nV: c5/1\nP.1: R\nP.2: c3/1\n");
5403        assert_eq!(lost.len(), 1);
5404        assert_eq!((lost[0].bar, lost[0].staff.as_str()), (3, "P.1"));
5405        let msg = "an ottava on P.1 from bar 1 is never closed (\\loco)";
5406        assert!(without_lines_or_bars(&mut done, &mut text, msg, &mut lost).is_some());
5407        assert_eq!(
5408            done,
5409            "bar 1\nV: c5/1\nP.1: R\nP.2: c3/1\nbar 2\nV: c5/1\nP.1: R\nP.2: c3/1\n"
5410        );
5411        assert_eq!(lost.len(), 3);
5412        // a line that only ends here began in the text before: every bar up to its end
5413        let text = "bar 7\nP.1: c5/1\nP.2: c3/1\nbar 8\nP.1: c5/2 \\loco d5/2\nP.2: \\8vb c3/2 \\loco d3\nbar 9\nP.1: c5/1\n";
5414        let under = bars_under_ottavas(text, None);
5415        let pairs: Vec<(&str, &str)> = under
5416            .iter()
5417            .map(|(b, s)| (b.as_str(), s.as_str()))
5418            .collect();
5419        assert_eq!(pairs, [("7", "P.1"), ("8", "P.1"), ("8", "P.2")]);
5420        // hairpins left out take no bars with them
5421        let mut done = "bar 1\nP.1: \\< c4/1\n".to_string();
5422        let mut text = "bar 2\nP.1: c4/2 \\> d4/2 \\!\n".to_string();
5423        let msg = "bar 2: a hairpin opens on P.1 while one from bar 1 is open (close it with \\!)";
5424        let mut lost = Vec::new();
5425        assert!(without_lines_or_bars(&mut done, &mut text, msg, &mut lost).is_some());
5426        assert!(lost.is_empty());
5427        assert_eq!(text, "bar 2\nP.1: c4/2 d4/2\n");
5428    }
5429
5430    #[test]
5431    fn a_tie_after_a_printed_accidental_s_mark_is_taken_out_too() {
5432        let line = "P.2/2: cs4/4 \\sf <bf2!~ f3!~ d4>/8";
5433        assert_eq!(
5434            untie_in(line, Some("bf2")).as_deref(),
5435            Some("P.2/2: cs4/4 \\sf <bf2! f3!~ d4>/8")
5436        );
5437        // none on that pitch: nothing to take out
5438        assert_eq!(untie_in(line, Some("d4")), None);
5439    }
5440
5441    #[test]
5442    fn a_bar_whose_tie_the_format_cannot_carry_is_left_as_a_rest() {
5443        // a tie from a staff's second voice that lands in no voice: its bar, in the text before
5444        let mut done = "bar 63\nP.1: c5/1\nP.2: c3/1\nP.2/2: e3/2 g3~\n".to_string();
5445        let mut text = "bar 64\nP.1: c5/1\nP.2: <c3 g3>/1\n".to_string();
5446        let msg = "a tie on g3 in P.2/2 from bar 63 never lands";
5447        let lost = blank_named(&mut done, &mut text, msg).unwrap();
5448        assert_eq!(done, "bar 63\nP.1: c5/1\nP.2: R\n");
5449        assert_eq!(text, "bar 64\nP.1: c5/1\nP.2: <c3 g3>/1\n");
5450        assert_eq!(lost.len(), 1);
5451        assert_eq!((lost[0].bar, lost[0].staff.as_str()), (63, "P.2"));
5452        // already a rest: nothing more to leave out
5453        assert!(blank_named(&mut done, &mut text, msg).is_none());
5454        // a message that names a bar and no staff: every staff of the bar
5455        let lost = blank_named(
5456            &mut done,
5457            &mut text,
5458            "bar 64: internal: a mark out of place",
5459        )
5460        .unwrap();
5461        assert_eq!(text, "bar 64\nP.1: R\nP.2: R\n");
5462        assert_eq!(lost.len(), 2);
5463        // one that names no bar: nothing
5464        assert!(blank_named(&mut done, &mut text, "internal: a mark out of place").is_none());
5465    }
5466
5467    #[test]
5468    fn a_numbered_hairpin_is_mended_whole() {
5469        // an end with no start goes with its number
5470        let mut done = String::new();
5471        let mut text = "bar 3\nP.1: c5/2 \\!2 d5/2\n".to_string();
5472        let msg = "bar 3: \\!2 closes no hairpin on P.1";
5473        assert!(unpair(&mut done, &mut text, msg).is_some());
5474        assert_eq!(text, "bar 3\nP.1: c5/2 d5/2\n");
5475        // (the plain one's end is not the numbered one's)
5476        let mut text = "bar 3\nP.1: \\< c5/2 \\! \\!2 d5/2\n".to_string();
5477        let msg = "bar 3: \\!2 closes no hairpin on P.1";
5478        assert!(unpair(&mut done, &mut text, msg).is_some());
5479        assert_eq!(text, "bar 3\nP.1: \\< c5/2 \\! d5/2\n");
5480        // and one opened over another of its number is closed by that number first
5481        let mut text = "bar 3\nP.1: \\< \\<2 c5/2 \\<2 d5/2 \\!2 \\!\n".to_string();
5482        let msg = "bar 3: a hairpin opens on P.1 while one from bar 3 is open (close it with \\!2)";
5483        assert!(unpair(&mut done, &mut text, msg).is_some());
5484        assert_eq!(text, "bar 3\nP.1: \\< \\<2 c5/2 \\!2 \\<2 d5/2 \\!2 \\!\n");
5485    }
5486
5487    #[test]
5488    fn hairpins_that_pair_with_nothing_are_left_out_of_their_system() {
5489        let mut done = "bar 1\nP.1: \\< c4/1\n".to_string();
5490        let mut text = "bar 2\nP.1: c4/2 \\> d4/2 \\!\nP.2: ^\"a \\< b\" c3/1\n".to_string();
5491        let msg = "bar 2: a hairpin opens on P.1 while one from bar 1 is open (close it with \\!)";
5492        assert_eq!(
5493            without_lines(&mut done, &mut text, msg),
5494            Some("its hairpins")
5495        );
5496        // (words are left as they are)
5497        assert_eq!(text, "bar 2\nP.1: c4/2 d4/2\nP.2: ^\"a \\< b\" c3/1\n");
5498        // none in this system: from the bar named, in the text before
5499        let msg = "a hairpin on P.1 from bar 1 is never closed (\\!)";
5500        assert_eq!(
5501            without_lines(&mut done, &mut text, msg),
5502            Some("its hairpins")
5503        );
5504        assert_eq!(done, "bar 1\nP.1: c4/1\n");
5505        assert!(without_lines(&mut done, &mut text, msg).is_none());
5506        assert!(without_lines(&mut done, &mut text, "bar 2: a slur ends").is_none());
5507    }
5508
5509    #[test]
5510    fn a_multi_bar_rest_is_a_thick_bar_on_the_middle_line() {
5511        let pg = Page {
5512            polys: vec![
5513                rect(20.0, 11.5, 40.0, 12.5), // on the middle line: a multi-bar rest
5514                rect(50.0, 9.5, 60.0, 10.5),  // on the top line
5515                rect(62.0, 11.6, 64.0, 12.4), // too short: a half or whole rest
5516                vec![(70.0, 11.5), (80.0, 12.0), (70.0, 12.5)], // no rectangle
5517            ],
5518            ..Page::default()
5519        };
5520        assert_eq!(multi_rests(&pg, &staff(10.0), 1.0), vec![(20.0, 40.0)]);
5521        // a beam is thinner and stands off the middle line
5522        let pg = Page {
5523            polys: vec![rect(20.0, 4.0, 40.0, 4.5)],
5524            ..Page::default()
5525        };
5526        assert!(multi_rests(&pg, &staff(10.0), 1.0).is_empty());
5527    }
5528
5529    #[test]
5530    fn a_multi_bar_rest_writes_its_bars() {
5531        let mut rest = Ev::spacer(Q::int(4), 20.0);
5532        rest.rest = crate::staff::Rest::Bar;
5533        let bar = BarRead {
5534            number: 3,
5535            pickup: false,
5536            short: false,
5537            free: false,
5538            time: (4, 4),
5539            times: vec![(4, 4)],
5540            time_sign: None,
5541            time_signs: vec![None],
5542            keys: vec![Some(0)],
5543            key_changes: vec![None],
5544            end: Some("double"),
5545            start_before: None,
5546            staves: vec![(vec!["P: R".to_string()], vec![rest])],
5547            left: 0.0,
5548            right: 100.0,
5549            jumps: Vec::new(),
5550            ending: None,
5551            tempo: None,
5552            rests: 3,
5553        };
5554        let sys = SystemRead {
5555            fifths: 0,
5556            bar_keys: Vec::new(),
5557            keys_out: Vec::new(),
5558            key_said: 0,
5559            own_keys: vec![None],
5560            reprints: false,
5561            time: (4, 4),
5562            time_sign: None,
5563            prev_time: (4, 4),
5564            times_before: vec![(4, 4)],
5565            every_staff_times: false,
5566            names: vec!["P".to_string()],
5567            clefs: vec!["treble"],
5568            clef_changes: vec![None],
5569            end_clefs: vec!["treble"],
5570            notices: Vec::new(),
5571            last_bar: 5,
5572            ends_with_start: None,
5573            slurs_out: BTreeMap::new(),
5574            slur_stems: BTreeMap::new(),
5575            slurs_in_left: BTreeMap::new(),
5576            ties_out: BTreeMap::new(),
5577            tied_over: BTreeMap::new(),
5578            opens_with: None,
5579            bars: vec![bar],
5580        };
5581        assert_eq!(
5582            sys.text(&BTreeMap::new()),
5583            "bar 3 system\nP: R\n\nbar 4\nP: R\n\nbar 5\nbarline double\nP: R\n"
5584        );
5585    }
5586
5587    #[test]
5588    fn a_doubted_staff_s_bars_are_left_where_it_sounds() {
5589        // a voice the page does not tell from another: its bars with notes are left as rests,
5590        // a bar it rests through is kept (both voices rest there), and so is the piano's
5591        let mut note = Ev::spacer(Q::int(4), 20.0);
5592        note.heads.push(glyph(0xE0A2, 19.0, 21.0, 5.0));
5593        let rest = Ev::spacer(Q::int(4), 20.0);
5594        let bar = |number: i64, v: Ev| BarRead {
5595            number,
5596            pickup: false,
5597            short: false,
5598            free: false,
5599            time: (4, 4),
5600            times: vec![(4, 4); 2],
5601            time_sign: None,
5602            time_signs: vec![None; 2],
5603            keys: vec![Some(0); 2],
5604            key_changes: vec![None; 2],
5605            end: None,
5606            start_before: None,
5607            staves: vec![
5608                (vec!["V: c5/1".to_string()], vec![v]),
5609                (vec!["P.1: c5/1".to_string()], vec![note.clone()]),
5610            ],
5611            left: 0.0,
5612            right: 100.0,
5613            jumps: Vec::new(),
5614            ending: None,
5615            tempo: None,
5616            rests: 1,
5617        };
5618        let mut sys = SystemRead {
5619            fifths: 0,
5620            bar_keys: Vec::new(),
5621            keys_out: Vec::new(),
5622            key_said: 0,
5623            own_keys: vec![None; 2],
5624            reprints: false,
5625            time: (4, 4),
5626            time_sign: None,
5627            prev_time: (4, 4),
5628            times_before: vec![(4, 4); 2],
5629            every_staff_times: false,
5630            names: ["V", "P.1"].map(String::from).to_vec(),
5631            clefs: vec!["treble"; 2],
5632            clef_changes: vec![None; 2],
5633            end_clefs: vec!["treble"; 2],
5634            notices: Vec::new(),
5635            last_bar: 3,
5636            ends_with_start: None,
5637            slurs_out: BTreeMap::from([("V".to_string(), 1)]),
5638            slur_stems: BTreeMap::new(),
5639            slurs_in_left: BTreeMap::new(),
5640            ties_out: BTreeMap::new(),
5641            tied_over: BTreeMap::new(),
5642            opens_with: None,
5643            bars: vec![bar(1, note.clone()), bar(2, rest.clone()), bar(3, rest)],
5644        };
5645        // bar 3's rest stands for notes that could not be read
5646        let unread = vec![Unread {
5647            bar: 3,
5648            staff: "V".to_string(),
5649            why: String::new(),
5650            place: None,
5651            beside: Vec::new(),
5652        }];
5653        assert_eq!(sys.leave_untold(&["V".to_string()], &unread), [1, 3]);
5654        assert_eq!(sys.bars[0].staves[0].0, ["V: R"]);
5655        assert_eq!(sys.bars[1].staves[0].0, ["V: c5/1"]);
5656        assert_eq!(sys.bars[0].staves[1].0, ["P.1: c5/1"]);
5657        assert!(sys.slurs_out.is_empty());
5658    }
5659
5660    #[test]
5661    fn a_staff_in_its_own_time_says_so_and_again_after_the_scores() {
5662        // a piano in 6/8 under a voice that turns from 6/8 to 2/4 in the system's second bar
5663        let bar = |number: i64, time: (i64, i64)| BarRead {
5664            number,
5665            pickup: false,
5666            short: false,
5667            free: false,
5668            time,
5669            times: vec![time, (6, 8), (6, 8)],
5670            time_sign: None,
5671            time_signs: vec![None; 3],
5672            keys: vec![Some(0); 3],
5673            key_changes: vec![None; 3],
5674            end: None,
5675            start_before: None,
5676            staves: ["V: R", "P.1: R", "P.2: R"]
5677                .iter()
5678                .map(|l| (vec![l.to_string()], Vec::new()))
5679                .collect(),
5680            left: 0.0,
5681            right: 100.0,
5682            jumps: Vec::new(),
5683            ending: None,
5684            tempo: None,
5685            rests: 1,
5686        };
5687        let sys = SystemRead {
5688            fifths: 0,
5689            bar_keys: Vec::new(),
5690            keys_out: Vec::new(),
5691            key_said: 0,
5692            own_keys: vec![None; 3],
5693            reprints: false,
5694            time: (6, 8),
5695            time_sign: None,
5696            prev_time: (6, 8),
5697            times_before: vec![(6, 8); 3],
5698            every_staff_times: true,
5699            names: ["V", "P.1", "P.2"].map(String::from).to_vec(),
5700            clefs: vec!["treble"; 3],
5701            clef_changes: vec![None; 3],
5702            end_clefs: vec!["treble"; 3],
5703            notices: Vec::new(),
5704            last_bar: 3,
5705            ends_with_start: None,
5706            slurs_out: BTreeMap::new(),
5707            slur_stems: BTreeMap::new(),
5708            slurs_in_left: BTreeMap::new(),
5709            ties_out: BTreeMap::new(),
5710            tied_over: BTreeMap::new(),
5711            opens_with: None,
5712            bars: vec![bar(1, (6, 8)), bar(2, (2, 4)), bar(3, (2, 4))],
5713        };
5714        let text = sys.text(&BTreeMap::new());
5715        assert_eq!(
5716            text,
5717            "bar 1 system\nV: R\nP.1: R\nP.2: R\n\nbar 2\ntime 2/4\ntime P 6/8\nV: R\nP.1: R\nP.2: R\n\n\
5718             bar 3\nV: R\nP.1: R\nP.2: R\n"
5719        );
5720        // and the compiler takes each staff's bars at their own length
5721        let head = "part V \"Voice\" voice\npart P \"Piano\" piano\n\nkey 0 major\ntime 6/8\n";
5722        let notes = text.replace("P 6/8\nV: R\nP.1: R", "P 6/8\nV: c5/2\nP.1: c5/2.");
5723        fm_transcribe::compile(&format!("{head}\n{notes}")).unwrap();
5724        // the systems after know what each staff is in
5725        let mut carry = Carry::default();
5726        sys.commit(&mut carry, &sys.names);
5727        assert_eq!(carry.time, (2, 4));
5728        assert_eq!(carry.staff_times["P.2"], (6, 8));
5729        assert!(carry.every_staff_times);
5730    }
5731
5732    #[test]
5733    fn a_tie_the_next_system_does_not_take_up_is_taken_out() {
5734        let mut done = "bar 31\nP.1: c5/4 a4/2.~\nP.1/2: a4/8 c4/8~ c4/4 <a3 c4>/4\n".to_string();
5735        let all = format!("{done}\nbar 32 system\nP.1: f4/2 a4/8 g4/8 f4/4\n");
5736        let msg = "bar 32, line 6: the tie from bar 31 wants a4 next, and this note is f4";
5737        assert!(unties_last(&mut done, msg, 32, &all));
5738        assert_eq!(
5739            done,
5740            "bar 31\nP.1: c5/4 a4/2.\nP.1/2: a4/8 c4/8~ c4/4 <a3 c4>/4\n"
5741        );
5742        // a tie from further back is not the new system's to take out
5743        assert!(!unties_last(&mut done, msg, 33, &all));
5744    }
5745
5746    fn glyph(code: u32, x0: f64, x1: f64, y: f64) -> Glyph {
5747        Glyph {
5748            code,
5749            x0,
5750            x1,
5751            y,
5752            size: 4.0,
5753        }
5754    }
5755
5756    #[test]
5757    fn a_staffs_band_stops_halfway_to_the_system_beside() {
5758        // six spaces out, or halfway to the next system on the page when that is nearer
5759        assert_eq!(first_staff_floor(100.0, 1.0, 0.0), 94.0);
5760        assert_eq!(first_staff_floor(100.0, 1.0, 92.0), 96.0);
5761        assert_eq!(first_staff_floor(100.0, 1.0, 80.0), 94.0);
5762        assert_eq!(last_staff_ceiling(104.0, 1.0, 0.0), 110.0);
5763        assert_eq!(last_staff_ceiling(104.0, 1.0, 112.0), 108.0);
5764    }
5765
5766    #[test]
5767    fn a_head_past_the_ledgers_toward_another_system_is_not_the_staffs() {
5768        // a staff's top line at 100: a head 4 spaces over it on ledger lines is its own, one
5769        // with none (the low note of the system above) is not
5770        let ledger = |y: f64| crate::page::HLine {
5771            x0: 9.5,
5772            x1: 12.0,
5773            y,
5774            w: 0.1,
5775        };
5776        let pg = Page {
5777            // set off the staff's spacing a little, as some programs draw them
5778            hlines: vec![ledger(98.8), ledger(97.8), ledger(96.8), ledger(95.8)],
5779            ..Page::default()
5780        };
5781        let high = glyph(0xE0A4, 10.0, 11.2, 95.9);
5782        assert!(!other_systems_head(&pg, &high, 100.0, -1.0, 1.0));
5783        let stray = glyph(0xE0A4, 20.0, 21.2, 95.9);
5784        assert!(other_systems_head(&pg, &stray, 100.0, -1.0, 1.0));
5785        // near the staff it is the staff's: its ledgers may be drawn some other way
5786        let near = glyph(0xE0A4, 20.0, 21.2, 98.0);
5787        assert!(!other_systems_head(&pg, &near, 100.0, -1.0, 1.0));
5788        // below a staff whose bottom line is at 104
5789        let low = glyph(0xE0A4, 20.0, 21.2, 109.0);
5790        assert!(other_systems_head(&pg, &low, 104.0, 1.0, 1.0));
5791    }
5792
5793    #[test]
5794    fn two_dynamics_one_over_the_other_are_two_words() {
5795        // mf over mf, their letters sorted by place: m, m, f, f
5796        let gs = [
5797            glyph(0xE521, 10.0, 11.0, 50.0),
5798            glyph(0xE521, 10.1, 11.1, 40.0),
5799            glyph(0xE522, 11.0, 12.0, 50.0),
5800            glyph(0xE522, 11.1, 12.1, 40.0),
5801        ];
5802        let words = dynamic_words(gs.iter().collect(), 1.0);
5803        assert_eq!(words.len(), 2);
5804        assert!(words.iter().all(|w| w.len() == 2 && w[0].y == w[1].y));
5805        // apart, two words
5806        let gs = [
5807            glyph(0xE520, 10.0, 11.0, 50.0),
5808            glyph(0xE522, 13.0, 14.0, 50.0),
5809        ];
5810        assert_eq!(dynamic_words(gs.iter().collect(), 1.0).len(), 2);
5811    }
5812
5813    #[test]
5814    fn thin_barlines_are_the_lines_from_the_top_staff_to_the_bottom() {
5815        // a piano's two staves at 10 and 20, ending at 100; a stem ends where its notes are
5816        let v = |x: f64, y0: f64, y1: f64| crate::page::VLine { x, y0, y1, w: 0.1 };
5817        let mut pg = Page {
5818            vlines: vec![
5819                v(30.0, 10.0, 24.0),
5820                v(40.0, 8.0, 13.5),
5821                v(50.0, 12.0, 24.0),
5822                v(100.0, 10.0, 24.0),
5823            ],
5824            ..Page::default()
5825        };
5826        let staves = [staff(10.0), staff(20.0)];
5827        assert_eq!(
5828            full_height_lines(&pg, &staves, 1.0, 0.0, 100.0),
5829            vec![30.0, 100.0]
5830        );
5831        // a line for each staff at one place is a barline too (a voice's staff over a piano's)
5832        pg.vlines.extend([v(70.0, 10.0, 14.0), v(70.0, 20.0, 24.0)]);
5833        assert_eq!(
5834            full_height_lines(&pg, &staves, 1.0, 0.0, 100.0),
5835            vec![30.0, 70.0, 100.0]
5836        );
5837        // with no line at the staves' end, these are not the barlines
5838        assert!(full_height_lines(&pg, &staves, 1.0, 0.0, 90.0).is_empty());
5839    }
5840
5841    #[test]
5842    fn a_staff_may_run_on_past_its_last_barline_to_announce_a_key() {
5843        // barlines at 30 and 92, the staff's lines on to 100: three sharps for the next system
5844        // stand after the last barline
5845        let v = |x: f64, y0: f64, y1: f64| crate::page::VLine { x, y0, y1, w: 0.1 };
5846        let mut pg = Page {
5847            vlines: vec![v(30.0, 10.0, 24.0), v(92.0, 10.0, 24.0)],
5848            glyphs: vec![glyph(0xE262, 94.0, 95.0, 10.0)],
5849            ..Page::default()
5850        };
5851        let staves = [staff(10.0), staff(20.0)];
5852        assert_eq!(
5853            full_height_lines(&pg, &staves, 1.0, 0.0, 100.0),
5854            vec![30.0, 92.0]
5855        );
5856        // a note after the last line: these are stems, or the barline is not found
5857        pg.glyphs.push(glyph(0xE0A4, 96.0, 97.2, 12.0));
5858        assert!(full_height_lines(&pg, &staves, 1.0, 0.0, 100.0).is_empty());
5859        // nothing after it: no reason for the staff to run on
5860        pg.glyphs.clear();
5861        assert!(full_height_lines(&pg, &staves, 1.0, 0.0, 100.0).is_empty());
5862    }
5863
5864    #[test]
5865    fn a_large_time_signature_reaches_under_the_staff() {
5866        // a staff from 10 to 14, noteheads of size 4: digits of size 5 at 11 and 15
5867        let mut low = glyph(0xE084, 3.0, 4.0, 15.0);
5868        assert!(!on_staff_for_time(&low, 10.0, 14.0, 1.0, 4.0));
5869        low.size = 5.0;
5870        assert!(on_staff_for_time(&low, 10.0, 14.0, 1.0, 4.0));
5871        low.y = 16.0;
5872        assert!(!on_staff_for_time(&low, 10.0, 14.0, 1.0, 4.0));
5873        let ts = [glyph(0xE083, 3.0, 4.0, 11.0), glyph(0xE084, 3.0, 4.0, 15.0)];
5874        assert_eq!(time_of(&ts.iter().collect::<Vec<_>>()).unwrap(), (3, 4));
5875    }
5876
5877    #[test]
5878    fn lines_thinner_than_the_stems_are_barlines() {
5879        // stems 0.24 wide, barlines 0.12 (a voice's staff at 10, a piano's at 20 and 30), and a
5880        // thick closing line: the width test finds only that one
5881        let v = |x: f64, y0: f64, y1: f64, w: f64| crate::page::VLine { x, y0, y1, w };
5882        let pg = Page {
5883            vlines: vec![
5884                v(22.0, 7.0, 10.5, 0.24),
5885                v(26.0, 13.0, 16.5, 0.24),
5886                v(28.0, 21.0, 24.5, 0.24),
5887                // a stem as long as the staff is high is no barline: it is as wide as the stems
5888                v(34.0, 10.0, 14.0, 0.24),
5889                v(40.0, 10.0, 14.0, 0.12),
5890                v(40.0, 20.0, 34.0, 0.12),
5891                // through the piano only: a line of its own
5892                v(60.0, 20.0, 34.0, 0.12),
5893                v(100.3, 10.0, 34.0, 0.12),
5894            ],
5895            ..Page::default()
5896        };
5897        let staves = [staff(10.0), staff(20.0), staff(30.0)];
5898        assert_eq!(
5899            thinner_than_stems(&pg, &staves, 1.0, 0.0, 100.0),
5900            vec![40.0, 100.3]
5901        );
5902    }
5903
5904    #[test]
5905    fn a_beam_through_the_middle_of_the_staff_is_no_multi_bar_rest() {
5906        // low notes stemmed up: their beam lies on the middle line, a stem at each end running
5907        // on down to its note
5908        let v = |x: f64, y0: f64, y1: f64| crate::page::VLine { x, y0, y1, w: 0.1 };
5909        let mut pg = Page {
5910            polys: vec![rect(20.0, 11.6, 25.0, 12.4)],
5911            vlines: vec![v(20.0, 11.6, 15.0), v(25.0, 11.6, 14.5)],
5912            ..Page::default()
5913        };
5914        assert!(multi_rests(&pg, &staff(10.0), 1.0).is_empty());
5915        // a multi-bar rest's end strokes reach a space over and under the middle line
5916        pg.vlines = vec![v(20.0, 11.0, 13.0), v(25.0, 11.0, 13.0)];
5917        assert_eq!(multi_rests(&pg, &staff(10.0), 1.0), vec![(20.0, 25.0)]);
5918    }
5919
5920    fn ev(x: f64, dur: Q, grace: bool) -> Ev {
5921        let mut e = Ev::new(vec![glyph(0xE0A4, x, x + 1.2, 12.0)], None, Some(true));
5922        e.dur = dur;
5923        if grace {
5924            e.grace = Some(false);
5925        }
5926        e
5927    }
5928
5929    #[test]
5930    fn an_unread_bar_says_what_was_seen_in_it() {
5931        // a chord, a small note and a rest, as set: said left to right, pitches as written
5932        let mut chord = ev(6.0, Q::int(2), false);
5933        chord.places = vec![28, 30];
5934        let mut small = ev(3.0, Q::new(1, 2), true);
5935        small.places = vec![32];
5936        let mut rest = printed_rest(9.0, Q::ONE);
5937        rest.x = 9.0;
5938        let seen = seen_in(&[chord, small, rest], 2.0, 1.0);
5939        assert_eq!(
5940            seen,
5941            vec![
5942                "1.0: g4 stem up, small, 1/2 quarter(s)",
5943                "4.0: c4 e4 stem up, 2 quarter(s)",
5944                "7.0: rest, 1 quarter(s)",
5945            ]
5946        );
5947    }
5948
5949    #[test]
5950    fn a_two_after_triplets_in_simple_time_is_plain_notes() {
5951        // two sixteenths under a 2, read as 2 in the time of 3
5952        let mut a = ev(0.0, Q::new(3, 8), false);
5953        a.tuplets.push((2, 3, 7));
5954        let mut b = ev(2.0, Q::new(3, 8), false);
5955        b.tuplets.push((2, 3, 7));
5956        let plain = without_duplets(&[a, b]).unwrap();
5957        assert!(plain
5958            .iter()
5959            .all(|e| e.dur == Q::new(1, 4) && e.tuplets.is_empty()));
5960        assert!(without_duplets(&[ev(0.0, Q::ONE, false)]).is_none());
5961    }
5962
5963    fn printed_rest(x: f64, dur: Q) -> Ev {
5964        let g = Glyph {
5965            code: 0xE4E4,
5966            x0: x,
5967            x1: x + 1.0,
5968            y: 2.0,
5969            size: 1.0,
5970        };
5971        let mut e = Ev::new(Vec::new(), None, None);
5972        e.rest = crate::staff::Rest::Printed(g);
5973        e.dur = dur;
5974        e
5975    }
5976
5977    #[test]
5978    fn a_staff_of_printed_rests_holds_their_length() {
5979        // a half rest alone says the bar is two beats long; a bar's rest says nothing
5980        assert_eq!(
5981            rests_held(&[vec![printed_rest(5.0, Q::int(2))]]),
5982            Some(Q::int(2))
5983        );
5984        let mut bar = printed_rest(5.0, Q::int(4));
5985        bar.rest = crate::staff::Rest::Bar;
5986        assert_eq!(rests_held(&[vec![bar]]), None);
5987    }
5988
5989    #[test]
5990    fn a_low_note_of_the_system_above_is_not_this_one_s() {
5991        // the system above's last staff ends at 100; this one's first begins at 108. A dotted
5992        // head on the second ledger line under the one above is its; a head over this staff,
5993        // with no ledgers, is this one's
5994        let ledger = |y: f64| crate::page::HLine {
5995            x0: 9.7,
5996            x1: 11.5,
5997            y,
5998            w: 0.1,
5999        };
6000        let head = |x: f64, y: f64| Glyph {
6001            code: 0xE0A4,
6002            x0: x,
6003            x1: x + 1.2,
6004            y,
6005            size: 4.0,
6006        };
6007        let dot = Glyph {
6008            code: smufl::DOT,
6009            x0: 11.6,
6010            x1: 11.9,
6011            y: 101.8,
6012            size: 4.0,
6013        };
6014        let pg = Page {
6015            width: 600.0,
6016            hlines: vec![ledger(101.0), ledger(102.0)],
6017            ..Page::default()
6018        };
6019        let mut glyphs = vec![head(10.0, 102.0), dot, head(20.0, 107.0)];
6020        above_system(&pg, &staff(108.0), 100.0, &mut glyphs);
6021        assert_eq!(glyphs.len(), 1);
6022        assert_eq!(glyphs[0].x0, 20.0);
6023    }
6024
6025    #[test]
6026    fn a_tie_lands_in_whichever_voice_and_a_voice_gone_leaves_none() {
6027        let mut ties: BTreeMap<(String, usize), BTreeMap<i32, i32>> = BTreeMap::new();
6028        ties.insert(("P.1".into(), 1), [(30, 0)].into_iter().collect());
6029        ties.insert(("P.1".into(), 2), [(28, -1)].into_iter().collect());
6030        ties.insert(("P.2".into(), 1), [(20, 1)].into_iter().collect());
6031        // the staff's bar has one voice now: both ties land in it, and the second voice's is done
6032        let into = ties_into(&mut ties, "P.1", 1);
6033        assert_eq!(into, [(28, -1), (30, 0)].into_iter().collect());
6034        assert!(!ties.contains_key(&("P.1".to_string(), 2)));
6035        assert!(ties.contains_key(&("P.2".to_string(), 1)));
6036    }
6037
6038    #[test]
6039    fn a_staff_with_nothing_in_its_bar_is_empty_unless_something_was_passed_over() {
6040        // a staff at 100 to 104, its band 94 to 110, the bar from x 10 to 40
6041        let st = staff(100.0);
6042        let empty = |pg: &Page, theirs: &[&Ev]| {
6043            left_in_empty_bar(pg, &st, (94.0, 110.0), (10.0, 40.0), 1.0, theirs)
6044        };
6045        assert_eq!(empty(&Page::default(), &[]), None);
6046        // an accidental, a dynamic or a clef is no note; a head in the next bar is not here
6047        let pg = Page {
6048            glyphs: vec![
6049                glyph(0xE262, 20.0, 21.0, 102.0),
6050                glyph(0xE0A4, 50.0, 51.2, 102.0),
6051            ],
6052            ..Page::default()
6053        };
6054        assert_eq!(empty(&pg, &[]), None);
6055        // a head no staff took (out past where the staff reads), or one of a shape not known
6056        let low = glyph(0xE0A4, 20.0, 21.2, 109.5);
6057        let pg = Page {
6058            glyphs: vec![low],
6059            ..Page::default()
6060        };
6061        assert!(empty(&pg, &[]).is_some());
6062        let pg_odd = Page {
6063            glyphs: vec![glyph(0xE0DB, 20.0, 21.2, 102.0)],
6064            ..Page::default()
6065        };
6066        assert!(empty(&pg_odd, &[]).is_some());
6067        // the same head read by the staff below (its ledger lines reach it) is that staff's
6068        let stem = crate::page::VLine {
6069            x: 21.2,
6070            y0: 103.0,
6071            y1: 109.5,
6072            w: 0.05,
6073        };
6074        let theirs = Ev::new(vec![low], Some(stem), Some(true));
6075        assert_eq!(empty(&pg, &[&theirs]), None);
6076        // a stem through the staff's lines that is no other staff's note's
6077        let pg = Page {
6078            glyphs: vec![low],
6079            vlines: vec![stem],
6080            ..Page::default()
6081        };
6082        assert!(empty(&pg, &[]).is_some());
6083        assert_eq!(empty(&pg, &[&theirs]), None);
6084        // a rest hung far off the staff
6085        let pg = Page {
6086            glyphs: vec![glyph(0xE4E5, 20.0, 21.0, 109.0)],
6087            ..Page::default()
6088        };
6089        assert!(empty(&pg, &[]).is_some());
6090    }
6091
6092    #[test]
6093    fn an_empty_staffs_bar_is_blank_time_of_the_bars_length() {
6094        let mut voices = vec![vec![bar_rest(Q::int(4), 10.0)]];
6095        // a pickup of a quarter: blank for a quarter
6096        blank_if_bar_rest(&mut voices, Q::ONE);
6097        assert_eq!(voices[0][0].rest, crate::staff::Rest::Blank);
6098        assert_eq!(voices[0][0].dur, Q::ONE);
6099        // a length with no notes to write it stays a bar's rest
6100        let mut voices = vec![vec![bar_rest(Q::int(4), 10.0)]];
6101        blank_if_bar_rest(&mut voices, Q::new(1, 3));
6102        assert_eq!(voices[0][0].rest, crate::staff::Rest::Bar);
6103    }
6104
6105    #[test]
6106    fn a_head_past_the_band_on_the_staffs_ledger_lines_is_the_staffs() {
6107        // a staff's bottom line at 104, its band to 108 (a system close below): a head on the
6108        // seventh ledger line under it, a flat before it, and a head as far out with no lines
6109        let ledger = |y: f64| crate::page::HLine {
6110            x0: 19.5,
6111            x1: 22.0,
6112            y,
6113            w: 0.1,
6114        };
6115        let low = glyph(0xE0A3, 20.0, 21.2, 111.0);
6116        let flat = glyph(0xE260, 18.5, 19.4, 111.0);
6117        let stray = glyph(0xE0A4, 40.0, 41.2, 111.0);
6118        let pg = Page {
6119            glyphs: vec![low, flat, stray],
6120            hlines: (1..=7).map(|k| ledger(104.0 + k as f64)).collect(),
6121            ..Page::default()
6122        };
6123        let mut glyphs = Vec::new();
6124        past_band(&pg, 104.0, 1.0, 108.0, (0.0, 100.0), 1.0, &mut glyphs);
6125        assert_eq!(glyphs.len(), 2);
6126        assert!(glyphs.iter().any(|g| g.code == 0xE0A3));
6127        assert!(glyphs.iter().any(|g| g.code == 0xE260));
6128        // and none twice
6129        past_band(&pg, 104.0, 1.0, 108.0, (0.0, 100.0), 1.0, &mut glyphs);
6130        assert_eq!(glyphs.len(), 2);
6131        // over the top staff the same
6132        let mut glyphs = Vec::new();
6133        past_band(&pg, 118.0, -1.0, 114.0, (0.0, 100.0), 1.0, &mut glyphs);
6134        assert!(glyphs.is_empty());
6135    }
6136
6137    fn note_at(x: f64, dur: Q, up: bool) -> Ev {
6138        let mut e = Ev::new(vec![glyph(0xE0A4, x, x + 1.2, 10.0)], None, Some(up));
6139        e.dur = dur;
6140        e
6141    }
6142
6143    fn rest_at(x: f64, dur: Q) -> Ev {
6144        let mut e = Ev::new(Vec::new(), None, None);
6145        e.rest = crate::staff::Rest::Printed(glyph(0xE4E5, x, x + 1.0, 10.0));
6146        e.dur = dur;
6147        e.x = x;
6148        e
6149    }
6150
6151    fn read_short(evs: &[Vec<Ev>], len: Q) -> BarVoices {
6152        evs.iter()
6153            .map(|ev| voices_of(ev.clone(), 1.0, len, Some(40.0), true).map_err(|e| e.0))
6154            .collect()
6155    }
6156
6157    #[test]
6158    fn a_last_bar_one_staff_fills_is_not_short_for_the_others() {
6159        // 4/4: the right hand's four quarters fill the bar; the left has a half rest at the
6160        // third beat and nothing printed before it
6161        let full: Vec<Ev> = (0..4)
6162            .map(|k| note_at(10.0 * k as f64, Q::ONE, true))
6163            .collect();
6164        let evs = vec![full, vec![rest_at(20.0, Q::int(2))]];
6165        let mut voices = read_short(&evs, Q::int(4));
6166        assert_eq!(held_by(voices[1].as_ref().unwrap()), Some(Q::int(2)));
6167        not_short_where_filled(&mut voices, &evs, 1.0, Q::int(4), 40.0);
6168        // it rests through the bar
6169        assert_eq!(held_by(voices[1].as_ref().unwrap()), None);
6170        assert_eq!(held_by(voices[0].as_ref().unwrap()), Some(Q::int(4)));
6171    }
6172
6173    #[test]
6174    fn a_short_bars_staff_of_fewer_rests_rests_through_it() {
6175        // a last bar of one quarter in 4/4: the voice's quarter rest, the left hand's eighth
6176        // chord and eighth rest, and the right hand's eighth rest alone under the second eighth
6177        let half = Q::new(1, 2);
6178        let evs = vec![
6179            vec![rest_at(0.0, Q::ONE)],
6180            vec![rest_at(5.0, half)],
6181            vec![note_at(0.0, half, false), rest_at(5.0, half)],
6182        ];
6183        let mut voices = read_short(&evs, Q::int(4));
6184        not_short_where_filled(&mut voices, &evs, 1.0, Q::int(4), 40.0);
6185        assert_eq!(held_by(voices[0].as_ref().unwrap()), Some(Q::ONE));
6186        assert_eq!(held_by(voices[1].as_ref().unwrap()), None);
6187        assert_eq!(held_by(voices[2].as_ref().unwrap()), Some(Q::ONE));
6188        // with no second staff as long as the notes', nothing says which is right
6189        let evs = vec![evs[1].clone(), evs[2].clone()];
6190        let mut voices = read_short(&evs, Q::int(4));
6191        not_short_where_filled(&mut voices, &evs, 1.0, Q::int(4), 40.0);
6192        assert_eq!(held_by(voices[0].as_ref().unwrap()), Some(half));
6193    }
6194
6195    #[test]
6196    fn a_bar_two_single_lines_make_short_is_short_for_two_voices_too() {
6197        // 3/4 with no 2/4 printed: the voice sings two quarters, the left hand plays a quarter
6198        // and rests one, the right hand has a half note under two quarters
6199        let line = vec![note_at(0.0, Q::ONE, true), note_at(10.0, Q::ONE, true)];
6200        let left = vec![note_at(0.0, Q::ONE, false), rest_at(10.0, Q::ONE)];
6201        let two = vec![
6202            note_at(0.0, Q::int(2), false),
6203            note_at(0.0, Q::ONE, true),
6204            note_at(10.0, Q::ONE, true),
6205        ];
6206        let evs = vec![line.clone(), two.clone(), left];
6207        let read = short_as_its_lines_say(&evs, 1.0, Q::int(3), 40.0).unwrap();
6208        assert!(read.iter().all(|vs| held_by(vs) == Some(Q::int(2))));
6209        assert_eq!(read[1].len(), 2);
6210        // one line alone does not say so, nor do lines that fill the bar
6211        assert!(short_as_its_lines_say(&[line.clone(), two], 1.0, Q::int(3), 40.0).is_none());
6212        let evs = vec![line.clone(), line];
6213        assert!(short_as_its_lines_say(&evs, 1.0, Q::int(2), 40.0).is_none());
6214    }
6215
6216    #[test]
6217    fn a_shared_heads_dot_is_the_blank_time_under_its_beam() {
6218        let (e8, s16) = (Q::new(1, 2), Q::new(1, 4));
6219        let beamed = |x: f64, y: f64, dur: Q, up: bool, beam: usize| {
6220            let mut e = Ev::new(vec![glyph(0xE0A4, x, x + 1.2, y)], None, Some(up));
6221            e.dur = dur;
6222            e.beam_polys.insert(beam);
6223            e
6224        };
6225        // one head at x 0 for both voices: a sixteenth of the lower (beam 1), an eighth of the
6226        // upper, beamed (beam 2) to a sixteenth at x 9, three sixteenths on; no dot is printed
6227        let lower = vec![
6228            beamed(0.0, 10.0, s16, false, 1),
6229            beamed(3.0, 12.0, s16, false, 1),
6230            beamed(6.0, 13.0, s16, false, 1),
6231            beamed(9.0, 14.0, s16, false, 1),
6232        ];
6233        let upper = |gap_first: bool| {
6234            let (a, b) = (
6235                beamed(0.0, 10.0, e8, true, 2),
6236                beamed(9.0, 8.0, s16, true, 2),
6237            );
6238            match gap_first {
6239                true => vec![a, Ev::spacer(s16, 8.9), b],
6240                false => vec![a, b, Ev::spacer(s16, 9.1)],
6241            }
6242        };
6243        // blank time between the two beamed notes: the first's dot
6244        let mut voices = vec![upper(true), lower.clone()];
6245        dots_hidden_under_a_beam(&mut voices, 1.0);
6246        assert_eq!(voices[0].len(), 2);
6247        assert_eq!(voices[0][0].dur, Q::new(3, 4));
6248        // blank time after the second, which stands over the lower voice's fourth sixteenth and
6249        // three spaces right of its third: the dot again
6250        let mut voices = vec![upper(false), lower.clone()];
6251        dots_hidden_under_a_beam(&mut voices, 1.0);
6252        assert_eq!(voices[0].len(), 2);
6253        assert_eq!(voices[0][0].dur, Q::new(3, 4));
6254        // set over the third sixteenth, it is where it was read, and a rest is hidden after it
6255        let mut voices = vec![upper(false), lower.clone()];
6256        voices[0][1].x = 6.0;
6257        voices[0][1].heads[0].x0 = 6.0;
6258        dots_hidden_under_a_beam(&mut voices, 1.0);
6259        assert_eq!(voices[0].len(), 3);
6260        // a head of its own (not the other voice's too) has its dot printed if it has one
6261        let mut voices = vec![upper(true), lower];
6262        voices[0][0].heads[0].y = 6.0;
6263        dots_hidden_under_a_beam(&mut voices, 1.0);
6264        assert_eq!(voices[0].len(), 3);
6265    }
6266
6267    #[test]
6268    fn a_tie_starts_by_its_own_head_of_a_chord_with_a_second() {
6269        // heads on both sides of the stem: c4 at 0 to 1.2, d4 at 1.2 to 2.4; the c's tie starts
6270        // just past its head, well short of the chord's right edge, 1.4 spaces under it
6271        let heads = [glyph(0xE0A4, 0.0, 1.2, 10.0), glyph(0xE0A4, 1.2, 2.4, 9.5)];
6272        assert!(starts_by_a_head(0.7, 11.4, &heads, 1.0));
6273        assert!(!starts_by_a_head(0.7, 13.0, &heads, 1.0));
6274        assert!(ends_by_a_head(0.9, 9.5, &heads, 1.0));
6275        assert!(!ends_by_a_head(4.0, 9.5, &heads, 1.0));
6276    }
6277
6278    #[test]
6279    fn a_note_beamed_from_the_other_staff_is_stemmed_as_its_beam_s_notes() {
6280        let mut home = ev(0.0, Q::new(1, 2), false);
6281        home.up = Some(false);
6282        home.beam_polys.insert(3);
6283        let mut moved = ev(4.0, Q::new(1, 2), false);
6284        moved.stem = Some(crate::page::VLine {
6285            x: 5.2,
6286            y0: 0.0,
6287            y1: 12.0,
6288            w: 0.1,
6289        });
6290        moved.beam_polys.insert(3);
6291        moved.on_staff = Some(2);
6292        let mut all = vec![moved.clone()];
6293        stemmed_as_their_beam(std::slice::from_ref(&home), &mut all);
6294        assert_eq!(all[0].up, Some(false));
6295        // (its column where it was: the head's left edge)
6296        let column = crate::columns::column_x;
6297        assert!((column(&all[0]) - column(&moved)).abs() < 1e-9);
6298        // beamed with notes stemmed both ways, it keeps its own
6299        let mut other = home.clone();
6300        other.up = Some(true);
6301        let mut all = vec![moved];
6302        stemmed_as_their_beam(&[home, other], &mut all);
6303        assert_eq!(all[0].up, Some(true));
6304    }
6305
6306    #[test]
6307    fn a_staff_whose_beamed_notes_are_read_on_the_other_is_read_without_them() {
6308        let alone = |evs: Vec<Ev>| -> Res<Vec<Vec<Ev>>> { Ok(vec![evs]) };
6309        let evs = vec![
6310            ev(0.0, Q::int(2), false),
6311            Ev::spacer(Q::new(1, 2), 1.0),
6312            ev(4.0, Q::int(2), false),
6313        ];
6314        let (kept, voices) = without_the_notes_gone(&evs, alone, Q::int(4)).unwrap();
6315        assert_eq!((kept.len(), voices[0].len()), (2, 2));
6316        // nothing of its own: the bar blank
6317        let gone = vec![Ev::spacer(Q::new(1, 2), 1.0), Ev::spacer(Q::new(1, 2), 3.0)];
6318        let (kept, _) = without_the_notes_gone(&gone, alone, Q::int(4)).unwrap();
6319        assert_eq!(kept.len(), 1);
6320        assert_eq!(kept[0].dur, Q::int(4));
6321        // what is left read only with time unseen: not told
6322        let padded = |mut evs: Vec<Ev>| -> Res<Vec<Vec<Ev>>> {
6323            evs.push(Ev::spacer(Q::ONE, 9.0));
6324            Ok(vec![evs])
6325        };
6326        assert!(without_the_notes_gone(&evs, padded, Q::int(4)).is_none());
6327        // and a staff none of whose notes went has nothing to leave out
6328        assert!(without_the_notes_gone(&evs[..1], alone, Q::int(4)).is_none());
6329    }
6330
6331    #[test]
6332    fn ledger_lines_that_run_on_past_a_chord_are_the_other_staff_s() {
6333        let pg = Page {
6334            glyphs: vec![glyph(0xE0A4, 5.0, 6.2, 13.0)],
6335            ..Page::default()
6336        };
6337        let h = pg.glyphs[0];
6338        // three ledger lines down to the head at 13
6339        assert!(ledgers_end_at_a_head(&pg, &h, 13.0, 4, 1.0));
6340        // from the other side they would run on two lines past it, to 11
6341        assert!(!ledgers_end_at_a_head(&pg, &h, 11.0, 3, 1.0));
6342        // a head by the staff's edge with no ledger line
6343        assert!(ledgers_end_at_a_head(&pg, &h, 20.0, 1, 1.0));
6344    }
6345
6346    #[test]
6347    fn an_accidental_holds_on_the_staff_it_is_printed_on() {
6348        let names = ["V".to_string(), "P.1".to_string(), "P.2".to_string()];
6349        // the upper staff's voice: a sharp on a note drawn on the lower staff, then a flat
6350        let mut drawn_below = ev(0.0, Q::ONE, false);
6351        drawn_below.accs.insert(30, (1, false));
6352        drawn_below.on_staff = Some(2);
6353        let mut own = ev(4.0, Q::ONE, false);
6354        own.accs.insert(32, (-1, false));
6355        let mut lower = ev(0.0, Q::ONE, false);
6356        lower.accs.insert(20, (1, false));
6357        let voices = vec![
6358            vec![Vec::new()],
6359            vec![vec![drawn_below, own]],
6360            vec![vec![lower]],
6361        ];
6362        let by_staff = printed_on_each_staff(&voices, &names);
6363        assert_eq!(by_staff[1].0, vec![(Q::ONE, 32, -1)]);
6364        assert_eq!(by_staff[2].0, vec![(Q::ZERO, 30, 1), (Q::ZERO, 20, 1)]);
6365        assert_eq!(by_staff[1].1[&2], by_staff[2].0);
6366        assert_eq!(by_staff[2].1[&1], by_staff[1].0);
6367        assert!(by_staff[0].1.is_empty());
6368    }
6369
6370    #[test]
6371    fn a_solved_bar_with_a_head_no_event_took_is_not_taken() {
6372        let glyph = |code: u32, x0: f64| Glyph {
6373            code,
6374            x0,
6375            x1: x0 + 1.2,
6376            y: 12.0,
6377            size: 4.0,
6378        };
6379        let note = Ev::new(vec![glyph(0xE0A4, 5.0)], None, Some(true));
6380        let theirs = [&note];
6381        let (band, sides) = ((8.0, 16.0), (0.0, 40.0));
6382        // the note's head and its dot: nothing passed over
6383        let pg = Page {
6384            glyphs: vec![glyph(0xE0A4, 5.0), glyph(0xE1E7, 6.6)],
6385            ..Page::default()
6386        };
6387        assert!(!head_passed_over(&pg, band, sides, &theirs));
6388        // a second head no event took
6389        let pg = Page {
6390            glyphs: vec![glyph(0xE0A4, 5.0), glyph(0xE0A4, 20.0)],
6391            ..Page::default()
6392        };
6393        assert!(head_passed_over(&pg, band, sides, &theirs));
6394        // (past the bar's side it is another bar's)
6395        assert!(!head_passed_over(&pg, band, (0.0, 15.0), &theirs));
6396    }
6397}