music21/graph/
utilities.rs1use crate::defaults::FloatType;
5use crate::error::{Error, Result};
6use crate::style::css_color_hex;
7
8const 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
20const DRAWN_ACCIDENTALS: [(&str, &str); 2] = [("#", "\u{266f}"), ("-", "\u{266d}")];
23
24const CHANNEL_MAX: i64 = 255;
26
27pub 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#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum Level {
50 Whole(i64),
52 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#[derive(Clone, Copy, Debug, PartialEq)]
67pub enum Color<'a> {
68 Text(&'a str),
70 Levels(&'a [Level]),
73}
74
75pub 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 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
118fn 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 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 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}