1use crate::defaults::FloatType;
9use crate::error::{Error, Result};
10
11#[derive(Clone, Debug, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum StyleValue {
19 Whole(i64),
21 Decimal(FloatType),
23 Text(String),
25}
26
27impl StyleValue {
28 pub fn read(text: &str) -> Self {
30 let Ok(value) = text.trim().parse::<FloatType>() else {
31 return Self::Text(text.to_string());
32 };
33 let whole = value.round();
34 if value.is_finite() && (whole - value).abs() <= 1e-6 && whole.abs() < 9.0e15 {
35 Self::Whole(whole as i64)
36 } else {
37 Self::Decimal(value)
38 }
39 }
40
41 pub fn number(&self) -> Option<FloatType> {
43 match self {
44 Self::Whole(whole) => Some(*whole as FloatType),
45 Self::Decimal(value) => Some(*value),
46 Self::Text(_) => None,
47 }
48 }
49}
50
51impl std::fmt::Display for StyleValue {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 match self {
55 Self::Whole(whole) => write!(f, "{whole}"),
56 Self::Decimal(value) if value.is_finite() && value.fract() == 0.0 => {
58 write!(f, "{value:.1}")
59 }
60 Self::Decimal(value) => write!(f, "{value}"),
61 Self::Text(text) => f.write_str(text),
62 }
63 }
64}
65
66fn format_error(message: impl Into<String>) -> Error {
67 Error::Text(message.into())
68}
69
70#[derive(Clone, Debug, Default, PartialEq)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
75pub struct TextStyle {
76 pub absolute_x: Option<StyleValue>,
79 pub absolute_y: Option<StyleValue>,
81 pub relative_x: Option<StyleValue>,
83 pub relative_y: Option<StyleValue>,
85 pub font_family: Option<Vec<String>>,
87 font_style: Option<String>,
88 pub font_size: Option<StyleValue>,
90 font_weight: Option<String>,
91 pub color: Option<String>,
93 justify: Option<String>,
94 align_horizontal: Option<String>,
95 align_vertical: Option<String>,
96}
97
98impl TextStyle {
99 pub fn font_style(&self) -> Option<&str> {
101 self.font_style.as_deref()
102 }
103
104 pub fn set_font_style(&mut self, value: Option<&str>) -> Result<()> {
110 self.font_style = checked(
111 value,
112 &["italic", "normal", "bold", "bolditalic"],
113 true,
114 |value| format!("Not a supported fontStyle: {value:?}"),
115 )?;
116 Ok(())
117 }
118
119 pub fn font_weight(&self) -> Option<&str> {
121 self.font_weight.as_deref()
122 }
123
124 pub fn set_font_weight(&mut self, value: Option<&str>) -> Result<()> {
130 self.font_weight = checked(value, &["normal", "bold"], true, |value| {
131 format!("Not a supported fontWeight: {value}")
132 })?;
133 Ok(())
134 }
135
136 pub fn justify(&self) -> Option<&str> {
138 self.justify.as_deref()
139 }
140
141 pub fn set_justify(&mut self, value: Option<&str>) -> Result<()> {
147 self.justify = checked(value, &["left", "center", "right", "full"], true, |value| {
148 format!("Not a supported justification: {value:?}")
149 })?;
150 Ok(())
151 }
152
153 pub fn align_horizontal(&self) -> Option<&str> {
156 self.align_horizontal.as_deref()
157 }
158
159 pub fn set_align_horizontal(&mut self, value: Option<&str>) -> Result<()> {
165 self.align_horizontal = checked(value, &["left", "right", "center"], false, |value| {
166 format!("Invalid horizontal align: {value:?}")
167 })?;
168 Ok(())
169 }
170
171 pub fn align_vertical(&self) -> Option<&str> {
174 self.align_vertical.as_deref()
175 }
176
177 pub fn set_align_vertical(&mut self, value: Option<&str>) -> Result<()> {
183 self.align_vertical = checked(
184 value,
185 &["top", "middle", "bottom", "baseline"],
186 false,
187 |value| format!("Invalid vertical align: {value:?}"),
188 )?;
189 Ok(())
190 }
191}
192
193fn checked(
196 value: Option<&str>,
197 allowed: &[&str],
198 lowercase: bool,
199 message: impl Fn(&str) -> String,
200) -> Result<Option<String>> {
201 let Some(value) = value else {
202 return Ok(None);
203 };
204 let read = if lowercase {
205 value.to_lowercase()
206 } else {
207 value.to_string()
208 };
209 if allowed.contains(&read.as_str()) {
210 Ok(Some(read))
211 } else {
212 Err(format_error(message(value)))
213 }
214}
215
216#[derive(Clone, Debug, Default, PartialEq)]
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220pub struct StreamStyle {
221 pub line_widths: Vec<(String, StyleValue)>,
223 pub note_sizes: Vec<(String, StyleValue)>,
225 pub distances: Vec<(String, StyleValue)>,
227 pub other_appearances: Vec<(String, StyleValue)>,
229 pub music_font: Option<TextStyle>,
231 pub word_font: Option<TextStyle>,
233 pub lyric_fonts: Vec<(Option<String>, Option<TextStyle>)>,
235 pub lyric_languages: Vec<(Option<String>, Option<String>)>,
237}
238
239impl StreamStyle {
240 pub fn has_appearance(&self) -> bool {
242 !(self.line_widths.is_empty()
243 && self.note_sizes.is_empty()
244 && self.distances.is_empty()
245 && self.other_appearances.is_empty())
246 }
247}
248
249pub fn css_color_hex(name: &str) -> Option<&'static str> {
260 let name = name.to_ascii_lowercase();
261 CSS_COLORS
262 .binary_search_by(|(known, _)| known.cmp(&name.as_str()))
263 .ok()
264 .map(|index| CSS_COLORS[index].1)
265}
266
267pub const CSS_COLORS: [(&str, &str); 147] = [
270 ("aliceblue", "#F0F8FF"),
271 ("antiquewhite", "#FAEBD7"),
272 ("aqua", "#00FFFF"),
273 ("aquamarine", "#7FFFD4"),
274 ("azure", "#F0FFFF"),
275 ("beige", "#F5F5DC"),
276 ("bisque", "#FFE4C4"),
277 ("black", "#000000"),
278 ("blanchedalmond", "#FFEBCD"),
279 ("blue", "#0000FF"),
280 ("blueviolet", "#8A2BE2"),
281 ("brown", "#A52A2A"),
282 ("burlywood", "#DEB887"),
283 ("cadetblue", "#5F9EA0"),
284 ("chartreuse", "#7FFF00"),
285 ("chocolate", "#D2691E"),
286 ("coral", "#FF7F50"),
287 ("cornflowerblue", "#6495ED"),
288 ("cornsilk", "#FFF8DC"),
289 ("crimson", "#DC143C"),
290 ("cyan", "#00FFFF"),
291 ("darkblue", "#00008B"),
292 ("darkcyan", "#008B8B"),
293 ("darkgoldenrod", "#B8860B"),
294 ("darkgray", "#A9A9A9"),
295 ("darkgreen", "#006400"),
296 ("darkgrey", "#A9A9A9"),
297 ("darkkhaki", "#BDB76B"),
298 ("darkmagenta", "#8B008B"),
299 ("darkolivegreen", "#556B2F"),
300 ("darkorange", "#FF8C00"),
301 ("darkorchid", "#9932CC"),
302 ("darkred", "#8B0000"),
303 ("darksalmon", "#E9967A"),
304 ("darkseagreen", "#8FBC8F"),
305 ("darkslateblue", "#483D8B"),
306 ("darkslategray", "#2F4F4F"),
307 ("darkslategrey", "#2F4F4F"),
308 ("darkturquoise", "#00CED1"),
309 ("darkviolet", "#9400D3"),
310 ("deeppink", "#FF1493"),
311 ("deepskyblue", "#00BFFF"),
312 ("dimgray", "#696969"),
313 ("dimgrey", "#696969"),
314 ("dodgerblue", "#1E90FF"),
315 ("firebrick", "#B22222"),
316 ("floralwhite", "#FFFAF0"),
317 ("forestgreen", "#228B22"),
318 ("fuchsia", "#FF00FF"),
319 ("gainsboro", "#DCDCDC"),
320 ("ghostwhite", "#F8F8FF"),
321 ("gold", "#FFD700"),
322 ("goldenrod", "#DAA520"),
323 ("gray", "#808080"),
324 ("green", "#008000"),
325 ("greenyellow", "#ADFF2F"),
326 ("grey", "#808080"),
327 ("honeydew", "#F0FFF0"),
328 ("hotpink", "#FF69B4"),
329 ("indianred", "#CD5C5C"),
330 ("indigo", "#4B0082"),
331 ("ivory", "#FFFFF0"),
332 ("khaki", "#F0E68C"),
333 ("lavender", "#E6E6FA"),
334 ("lavenderblush", "#FFF0F5"),
335 ("lawngreen", "#7CFC00"),
336 ("lemonchiffon", "#FFFACD"),
337 ("lightblue", "#ADD8E6"),
338 ("lightcoral", "#F08080"),
339 ("lightcyan", "#E0FFFF"),
340 ("lightgoldenrodyellow", "#FAFAD2"),
341 ("lightgray", "#D3D3D3"),
342 ("lightgreen", "#90EE90"),
343 ("lightgrey", "#D3D3D3"),
344 ("lightpink", "#FFB6C1"),
345 ("lightsalmon", "#FFA07A"),
346 ("lightseagreen", "#20B2AA"),
347 ("lightskyblue", "#87CEFA"),
348 ("lightslategray", "#778899"),
349 ("lightslategrey", "#778899"),
350 ("lightsteelblue", "#B0C4DE"),
351 ("lightyellow", "#FFFFE0"),
352 ("lime", "#00FF00"),
353 ("limegreen", "#32CD32"),
354 ("linen", "#FAF0E6"),
355 ("magenta", "#FF00FF"),
356 ("maroon", "#800000"),
357 ("mediumaquamarine", "#66CDAA"),
358 ("mediumblue", "#0000CD"),
359 ("mediumorchid", "#BA55D3"),
360 ("mediumpurple", "#9370DB"),
361 ("mediumseagreen", "#3CB371"),
362 ("mediumslateblue", "#7B68EE"),
363 ("mediumspringgreen", "#00FA9A"),
364 ("mediumturquoise", "#48D1CC"),
365 ("mediumvioletred", "#C71585"),
366 ("midnightblue", "#191970"),
367 ("mintcream", "#F5FFFA"),
368 ("mistyrose", "#FFE4E1"),
369 ("moccasin", "#FFE4B5"),
370 ("navajowhite", "#FFDEAD"),
371 ("navy", "#000080"),
372 ("oldlace", "#FDF5E6"),
373 ("olive", "#808000"),
374 ("olivedrab", "#6B8E23"),
375 ("orange", "#FFA500"),
376 ("orangered", "#FF4500"),
377 ("orchid", "#DA70D6"),
378 ("palegoldenrod", "#EEE8AA"),
379 ("palegreen", "#98FB98"),
380 ("paleturquoise", "#AFEEEE"),
381 ("palevioletred", "#DB7093"),
382 ("papayawhip", "#FFEFD5"),
383 ("peachpuff", "#FFDAB9"),
384 ("peru", "#CD853F"),
385 ("pink", "#FFC0CB"),
386 ("plum", "#DDA0DD"),
387 ("powderblue", "#B0E0E6"),
388 ("purple", "#800080"),
389 ("red", "#FF0000"),
390 ("rosybrown", "#BC8F8F"),
391 ("royalblue", "#4169E1"),
392 ("saddlebrown", "#8B4513"),
393 ("salmon", "#FA8072"),
394 ("sandybrown", "#F4A460"),
395 ("seagreen", "#2E8B57"),
396 ("seashell", "#FFF5EE"),
397 ("sienna", "#A0522D"),
398 ("silver", "#C0C0C0"),
399 ("skyblue", "#87CEEB"),
400 ("slateblue", "#6A5ACD"),
401 ("slategray", "#708090"),
402 ("slategrey", "#708090"),
403 ("snow", "#FFFAFA"),
404 ("springgreen", "#00FF7F"),
405 ("steelblue", "#4682B4"),
406 ("tan", "#D2B48C"),
407 ("teal", "#008080"),
408 ("thistle", "#D8BFD8"),
409 ("tomato", "#FF6347"),
410 ("turquoise", "#40E0D0"),
411 ("violet", "#EE82EE"),
412 ("wheat", "#F5DEB3"),
413 ("white", "#FFFFFF"),
414 ("whitesmoke", "#F5F5F5"),
415 ("yellow", "#FFFF00"),
416 ("yellowgreen", "#9ACD32"),
417];
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422
423 #[test]
424 fn a_value_is_read_as_music21_reads_it() {
425 assert_eq!(StyleValue::read("12"), StyleValue::Whole(12));
426 assert_eq!(StyleValue::read("12.0000001"), StyleValue::Whole(12));
427 assert_eq!(StyleValue::read("12.5"), StyleValue::Decimal(12.5));
428 assert_eq!(
429 StyleValue::read("medium"),
430 StyleValue::Text("medium".to_string())
431 );
432 assert_eq!(StyleValue::Decimal(12.5).to_string(), "12.5");
433 }
434
435 #[test]
436 fn styles_music21_does_not_name_are_refused() {
437 let mut style = TextStyle::default();
438 style.set_justify(Some("Center")).unwrap();
439 assert_eq!(style.justify(), Some("center"));
440 assert!(style.set_justify(Some("middle")).is_err());
441 assert!(style.set_align_horizontal(Some("Center")).is_err());
442 style.set_align_vertical(Some("baseline")).unwrap();
443 assert!(style.set_font_style(Some("oblique")).is_err());
444 style.set_font_weight(Some("BOLD")).unwrap();
445 assert_eq!(style.font_weight(), Some("bold"));
446 }
447
448 #[test]
451 fn a_whole_decimal_is_written_with_its_point() {
452 assert_eq!(StyleValue::Decimal(5.0).to_string(), "5.0");
453 assert_eq!(StyleValue::Decimal(0.1).to_string(), "0.1");
454 assert_eq!(StyleValue::Whole(75).to_string(), "75");
455 }
456}