Skip to main content

music21/graph/
utilities.rs

1//! music21's `graph.utilities`: colours as matplotlib takes them, and
2//! accidentals as its fonts can draw them.
3
4use crate::defaults::FloatType;
5use crate::error::{Error, Result};
6use crate::style::css_color_hex;
7
8/// matplotlib's one-letter colours and the names they stand for.
9const ABBREVIATIONS: [(&str, &str); 8] = [
10    ("b", "blue"),
11    ("g", "green"),
12    ("r", "red"),
13    ("c", "cyan"),
14    ("m", "magenta"),
15    ("y", "yellow"),
16    ("k", "black"),
17    ("w", "white"),
18];
19
20/// The accidentals matplotlib's default fonts draw, in the order music21
21/// tries them: `pitch.unicodeFromModifier`'s order.
22const DRAWN_ACCIDENTALS: [(&str, &str); 2] = [("#", "\u{266f}"), ("-", "\u{266d}")];
23
24/// The most an RGB channel takes.
25const CHANNEL_MAX: i64 = 255;
26
27/// A label with its sharps or its flats drawn as music symbols: only one
28/// of the two, the first music21's table has that the label holds.
29///
30/// ```
31/// use music21::graph::utilities::accidental_label_to_unicode;
32///
33/// assert_eq!(accidental_label_to_unicode("B-4"), "B\u{266d}4");
34/// assert_eq!(accidental_label_to_unicode("B--4"), "B\u{266d}\u{266d}4");
35/// assert_eq!(accidental_label_to_unicode("C4"), "C4");
36/// ```
37pub fn accidental_label_to_unicode(label: &str) -> String {
38    for (modifier, drawn) in DRAWN_ACCIDENTALS {
39        if label.contains(modifier) {
40            return label.replace(modifier, drawn);
41        }
42    }
43    label.to_string()
44}
45
46/// One channel of a colour given as numbers: Python's int or float, which
47/// music21 tells apart when it writes the colour as hex.
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum Level {
50    /// A whole number.
51    Whole(i64),
52    /// A number with a fraction.
53    Real(FloatType),
54}
55
56impl Level {
57    fn value(self) -> FloatType {
58        match self {
59            Level::Whole(whole) => whole as FloatType,
60            Level::Real(real) => real,
61        }
62    }
63}
64
65/// A colour as music21's `getColor` takes one.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub enum Color<'a> {
68    /// A name, a matplotlib letter or a hex code.
69    Text(&'a str),
70    /// One number for a grey, or one per channel: fractions of one where
71    /// any is below one, else values up to 255.
72    Levels(&'a [Level]),
73}
74
75/// A colour as the lowercase hex code matplotlib takes: music21's
76/// `getColor`.
77///
78/// ```
79/// use music21::graph::utilities::{Color, Level, color_hex};
80///
81/// assert_eq!(color_hex(Color::Text("r"))?, "#ff0000");
82/// assert_eq!(color_hex(Color::Text("Steel Blue"))?, "#4682b4");
83/// assert_eq!(color_hex(Color::Text("#f50"))?, "#ff5500");
84/// assert_eq!(color_hex(Color::Levels(&[Level::Real(0.8)]))?, "#cccccc");
85/// assert_eq!(color_hex(Color::Levels(&[Level::Whole(255); 3]))?, "#ffffff");
86/// # Ok::<(), music21::Error>(())
87/// ```
88///
89/// # Errors
90///
91/// An unknown letter or name, a malformed hex code, or numbers that make
92/// no colour.
93pub fn color_hex(color: Color<'_>) -> Result<String> {
94    match color {
95        Color::Text(text) => text_hex(text),
96        Color::Levels(levels) => levels_hex(levels),
97    }
98}
99
100fn text_hex(text: &str) -> Result<String> {
101    if text.starts_with('#') {
102        return normalize_hex(text);
103    }
104
105    // A letter of matplotlib's, or a name.
106    let mut name = text.to_lowercase().replace(' ', "");
107    if name.chars().count() == 1 {
108        let Some((_, full)) = ABBREVIATIONS.iter().find(|(letter, _)| *letter == name) else {
109            return Err(Error::Graph(format!("invalid color abbreviation: {name}")));
110        };
111        name = (*full).to_string();
112    }
113    css_color_hex(&name)
114        .map(str::to_lowercase)
115        .ok_or_else(|| Error::Graph(format!("invalid color name: {name}")))
116}
117
118/// `#rgb` or `#rrggbb` as six lowercase digits: webcolors' `normalize_hex`.
119fn normalize_hex(text: &str) -> Result<String> {
120    let digits = &text[1..];
121    let valid = matches!(digits.len(), 3 | 6) && digits.chars().all(|c| c.is_ascii_hexdigit());
122    if !valid {
123        return Err(Error::Value(format!(
124            "'{text}' is not a valid hexadecimal color value."
125        )));
126    }
127    let digits = digits.to_lowercase();
128    if digits.len() == 3 {
129        let doubled: String = digits.chars().flat_map(|c| [c, c]).collect();
130        return Ok(format!("#{doubled}"));
131    }
132    Ok(format!("#{digits}"))
133}
134
135fn levels_hex(levels: &[Level]) -> Result<String> {
136    // A single number is a grey.
137    let tripled;
138    let levels = if levels.len() == 1 {
139        tripled = [levels[0]; 3];
140        &tripled[..]
141    } else {
142        levels
143    };
144    if levels.len() != 3 {
145        return Err(Error::Value(format!(
146            "a colour takes three channels, not {}",
147            levels.len()
148        )));
149    }
150
151    // Fractions where any is below one, as webcolors reads percentages.
152    if levels.iter().any(|level| level.value() < 1.0) {
153        let channels: Vec<i64> = levels
154            .iter()
155            .map(|level| {
156                let percent = (level.value() * 100.0).clamp(0.0, 100.0);
157                (percent / 100.0 * CHANNEL_MAX as FloatType).round_ties_even() as i64
158            })
159            .collect();
160        return Ok(hex_of(&channels));
161    }
162    let mut channels = Vec::new();
163    for level in levels {
164        match level {
165            Level::Whole(whole) => channels.push((*whole).clamp(0, CHANNEL_MAX)),
166            Level::Real(real) if *real > CHANNEL_MAX as FloatType => channels.push(CHANNEL_MAX),
167            Level::Real(_) => {
168                return Err(Error::Value(
169                    "Unknown format code 'x' for object of type 'float'".to_string(),
170                ));
171            }
172        }
173    }
174    Ok(hex_of(&channels))
175}
176
177fn hex_of(channels: &[i64]) -> String {
178    let digits: String = channels.iter().map(|c| format!("{c:02x}")).collect();
179    format!("#{digits}")
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn colors_read_as_music21_reads_them() {
188        let grey = [Level::Real(0.5); 3];
189        assert_eq!(color_hex(Color::Levels(&grey)).unwrap(), "#808080");
190        assert_eq!(
191            color_hex(Color::Levels(&[Level::Real(0.5)])).unwrap(),
192            "#808080"
193        );
194        assert_eq!(
195            color_hex(Color::Levels(&[Level::Whole(255)])).unwrap(),
196            "#ffffff"
197        );
198        assert_eq!(color_hex(Color::Text("red")).unwrap(), "#ff0000");
199    }
200
201    #[test]
202    fn bad_colors_are_refused() {
203        let error = color_hex(Color::Text("l")).unwrap_err();
204        assert_eq!(
205            error.to_string(),
206            "Graph error: invalid color abbreviation: l"
207        );
208        let error = color_hex(Color::Text("chalky white")).unwrap_err();
209        assert_eq!(
210            error.to_string(),
211            "Graph error: invalid color name: chalkywhite"
212        );
213        assert!(color_hex(Color::Text("#ff")).is_err());
214    }
215}