1use crate::defaults::FloatType;
10use crate::dynamics::SHORT_NAMES;
11use crate::error::{Error, Result};
12use crate::pitch::Pitch;
13
14use super::py_range;
15use super::utilities::accidental_label_to_unicode;
16
17pub const STRONG_BARLINES: [&str; 5] = ["heavy", "double", "final", "heavy-light", "heavy-heavy"];
20
21pub fn is_strong_barline(kind: &str) -> bool {
30 STRONG_BARLINES.contains(&kind)
31}
32
33const DEFAULT_MIN: FloatType = 0.0;
35
36const DEFAULT_MAX: FloatType = 10.0;
38
39fn truncate(value: FloatType) -> i64 {
41 value.trunc() as i64
42}
43
44pub fn numeric_ticks(min: Option<FloatType>, max: Option<FloatType>) -> Result<Vec<i64>> {
61 let min = min.unwrap_or(DEFAULT_MIN);
62 let max = max.unwrap_or(DEFAULT_MAX);
63 let difference = max - min;
64 if difference < 0.0 {
65 return Err(Error::Value("math domain error".to_string()));
66 }
67
68 let power = if difference == 0.0 {
71 0
72 } else {
73 truncate(difference.log10())
74 };
75 if power < 0 {
76 return Err(Error::Value(
77 "'float' object cannot be interpreted as an integer".to_string(),
78 ));
79 }
80 let mut step = 10_i64.pow(power as u32);
81 if step > 1 && difference / step as FloatType <= 2.0 {
82 step /= 10;
83 }
84
85 let mut start = (truncate(min / step as FloatType) - 1) * step;
86 if start < 0 && min >= 0.0 {
87 start = 0;
88 }
89 let stop = (truncate(max / step as FloatType) + 2) * step;
90 Ok(py_range(start, stop, step))
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Octaves {
97 Hidden,
99 First,
101 All,
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct PitchLabels {
108 pub octaves: Octaves,
110 pub show_enharmonic: bool,
113 pub blank_label_unused: bool,
116 pub hide_unused: bool,
118}
119
120fn sort_name(name: &str) -> String {
122 match name.strip_prefix('A') {
123 Some(rest) => format!("H{rest}"),
124 None => name.to_string(),
125 }
126}
127
128fn without_digits(label: &str) -> String {
130 label.chars().filter(|c| !c.is_ascii_digit()).collect()
131}
132
133pub fn pitch_ticks(
159 labels: PitchLabels,
160 min: i64,
161 max: i64,
162 counts: &[(String, usize)],
163 value_of: impl Fn(&str) -> Result<FloatType>,
164 unused_label: impl Fn(i64) -> Result<String>,
165) -> Result<Vec<(i64, String)>> {
166 let mut values = Vec::with_capacity(counts.len());
167 for (name, _) in counts {
168 values.push(value_of(name)?);
169 }
170
171 let mut ticks = Vec::new();
172 let mut octaves_seen: Vec<char> = Vec::new();
173 for tick in min..=max {
174 let mut weights: Vec<(usize, &str)> = counts
176 .iter()
177 .zip(&values)
178 .filter(|(_, value)| **value == tick as FloatType)
179 .map(|((name, count), _)| (*count, name.as_str()))
180 .collect();
181 if labels.show_enharmonic {
182 weights.sort_by_key(|(count, name)| (*count as i64, sort_name(name)));
183 } else {
184 weights.sort_by_key(|(count, name)| (-(*count as i64), sort_name(name)));
185 }
186
187 let mut label = if weights.is_empty() {
188 if labels.hide_unused {
189 continue;
190 }
191 if labels.blank_label_unused {
192 String::new()
193 } else {
194 unused_label(tick)?
195 }
196 } else if !labels.show_enharmonic {
197 weights[0].1.to_string()
198 } else {
199 let names: Vec<String> = weights
200 .iter()
201 .map(|(_, name)| accidental_label_to_unicode(name))
202 .collect();
203 names.join("/")
204 };
205
206 match labels.octaves {
208 Octaves::Hidden => label = without_digits(&label),
209 Octaves::First => {
210 if let Some(digit) = label.chars().find(char::is_ascii_digit) {
211 if octaves_seen.contains(&digit) {
212 label = without_digits(&label);
213 } else {
214 octaves_seen.push(digit);
215 }
216 }
217 }
218 Octaves::All => {}
219 }
220 ticks.push((tick, accidental_label_to_unicode(&label)));
221 }
222 Ok(ticks)
223}
224
225pub fn octave_ticks(start: &str, min: FloatType, max: FloatType) -> Result<Vec<(i64, String)>> {
241 let mut pitch = Pitch::from_name(start)?;
242 let mut ticks = Vec::new();
243 while pitch.ps() <= max {
244 if pitch.ps() >= min {
245 let label = accidental_label_to_unicode(&pitch.name_with_octave());
246 ticks.push((truncate(pitch.ps()), label));
247 }
248 let Some(octave) = pitch.octave() else {
249 return Err(Error::Value(format!("{start} names no octave")));
250 };
251 pitch.set_octave(Some(octave + 1));
252 }
253 Ok(ticks)
254}
255
256pub fn offset_ticks(min: FloatType, max: FloatType, step: i64) -> Vec<i64> {
266 py_range(min.floor() as i64, max.ceil() as i64 + 1, step)
267}
268
269#[derive(Clone, Debug, PartialEq)]
272pub struct MeasureMark {
273 pub offset: FloatType,
275 pub number: String,
277 pub strong: bool,
279}
280
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
284pub enum MeasureSpan {
285 Ends,
287 Spaced(i64),
290}
291
292pub fn measure_ticks(
311 marks: &[MeasureMark],
312 min: FloatType,
313 max: FloatType,
314 span: MeasureSpan,
315) -> Result<Vec<(FloatType, String)>> {
316 let used: Vec<&MeasureMark> = marks
317 .iter()
318 .filter(|mark| min <= mark.offset && mark.offset <= max)
319 .collect();
320 if used.is_empty() {
321 return Err(Error::Value("list index out of range".to_string()));
322 }
323 let tick_of = |index: usize| (used[index].offset, used[index].number.clone());
324
325 let most = match span {
326 MeasureSpan::Ends => {
327 let mut ticks = vec![tick_of(0)];
328 let last = tick_of(used.len() - 1);
329 if !ticks.contains(&last) {
330 ticks.push(last);
331 }
332 return Ok(ticks);
333 }
334 MeasureSpan::Spaced(most) => most,
335 };
336
337 let mut chosen: Vec<usize> = Vec::new();
339 let choose = |index: usize, chosen: &mut Vec<usize>| {
340 if !chosen.contains(&index) {
341 chosen.push(index);
342 }
343 };
344 choose(0, &mut chosen);
345 choose(used.len() - 1, &mut chosen);
346 for (index, mark) in used.iter().enumerate().take(used.len() - 1).skip(1) {
347 if mark.strong {
348 choose(index, &mut chosen);
349 }
350 }
351
352 let more = (most - chosen.len() as i64 + 1).min(used.len() as i64);
354 if more == 0 {
355 return Err(Error::Value(
356 "integer division or modulo by zero".to_string(),
357 ));
358 }
359 let step = ((used.len() as FloatType / more as FloatType).floor() as i64).max(1) as usize;
360 let mut index = step;
361 while index < used.len() - 1 {
362 choose(index, &mut chosen);
363 index += step;
364 }
365
366 let mut ticks: Vec<(FloatType, String)> = chosen.into_iter().map(tick_of).collect();
367 ticks.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
368 Ok(ticks)
369}
370
371pub fn dynamics_ticks(min: i64, max: i64) -> Result<Vec<(i64, String)>> {
387 let mut ticks = Vec::new();
388 for index in min..=max {
389 let at = if index < 0 {
390 index + SHORT_NAMES.len() as i64
391 } else {
392 index
393 };
394 let Some(name) = usize::try_from(at).ok().and_then(|at| SHORT_NAMES.get(at)) else {
395 return Err(Error::Value("list index out of range".to_string()));
396 };
397 ticks.push((index, format!("${name}$")));
398 }
399 Ok(ticks)
400}
401
402pub fn dynamics_max() -> i64 {
404 SHORT_NAMES.len() as i64 - 1
405}
406
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409pub enum Scale {
410 Linear,
412 Log2,
414}
415
416pub fn quarter_length_value(ql: FloatType, scale: Scale, grace: FloatType) -> Result<FloatType> {
432 match scale {
433 Scale::Log2 => {
434 let length = if ql == 0.0 { grace } else { ql };
435 if length < 0.0 {
436 return Err(Error::Graph(format!(
437 "cannot take log of x value: {length}"
438 )));
439 }
440 Ok(length.log2())
441 }
442 Scale::Linear if ql > 0.0 => Ok(ql),
443 Scale::Linear => Ok(grace),
444 }
445}
446
447pub fn log_label_tag(base: Option<i64>) -> String {
457 match base {
458 Some(base) => format!(" ($log_{base}$)"),
459 None => String::new(),
460 }
461}
462
463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465pub enum Tied {
466 Onward,
468 Not,
470}
471
472pub fn offset_end(
483 offset: FloatType,
484 length: FloatType,
485 spacing: FloatType,
486 tied: Tied,
487) -> (FloatType, FloatType) {
488 if length < spacing {
489 return (offset, spacing);
490 }
491 if length > spacing * 2.0 && tied == Tied::Not {
492 return (offset, length - spacing);
493 }
494 (offset, length)
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 #[test]
502 fn measure_ticks_space_out_and_keep_strong_bars() {
503 let offsets = [0.0, 1.0, 5.0, 9.0, 13.0, 17.0, 21.0, 25.0, 29.0];
504 let mut marks: Vec<MeasureMark> = offsets
505 .iter()
506 .enumerate()
507 .map(|(number, offset)| MeasureMark {
508 offset: *offset,
509 number: number.to_string(),
510 strong: false,
511 })
512 .collect();
513 let numbers = |ticks: Vec<(FloatType, String)>| -> Vec<String> {
514 ticks.into_iter().map(|(_, label)| label).collect()
515 };
516 let ticks = measure_ticks(&marks, 0.0, 33.0, MeasureSpan::Spaced(4)).unwrap();
517 assert_eq!(numbers(ticks), ["0", "3", "6", "8"]);
518 marks[5].strong = true;
519 let ticks = measure_ticks(&marks, 0.0, 33.0, MeasureSpan::Spaced(4)).unwrap();
520 assert_eq!(numbers(ticks), ["0", "4", "5", "8"]);
521 let ticks = measure_ticks(&marks, 8.0, 12.0, MeasureSpan::Spaced(20)).unwrap();
522 assert_eq!(numbers(ticks), ["3"]);
523 }
524
525 #[test]
526 fn pitch_ticks_write_octaves_once() {
527 let labels = PitchLabels {
528 octaves: Octaves::First,
529 show_enharmonic: true,
530 blank_label_unused: false,
531 hide_unused: false,
532 };
533 let names = ["G#0", "A0", "B-0", "B0", "C1"];
534 let ticks = pitch_ticks(
535 labels,
536 20,
537 24,
538 &[],
539 |_| Ok(0.0),
540 |tick| Ok(names[(tick - 20) as usize].to_string()),
541 )
542 .unwrap();
543 let written: Vec<&str> = ticks.iter().map(|(_, label)| label.as_str()).collect();
544 assert_eq!(written, ["G\u{266f}0", "A", "B\u{266d}", "B", "C1"]);
545 }
546}