Skip to main content

music21/
style.rs

1//! How an object is drawn: music21's `style` objects, as far as the crate
2//! keeps them.
3//!
4//! A [`TextStyle`] says where a piece of text stands, in what font and
5//! colour, and how it is aligned and justified, as MusicXML's print-style,
6//! alignment and justify attributes say it.
7
8use crate::defaults::FloatType;
9use crate::error::{Error, Result};
10
11/// A value of a style as music21 keeps the attribute it read: a whole
12/// number where the text is one, to within a millionth, a number with a
13/// fraction where it is that, and the text itself where it is no number --
14/// music21's `numToIntOrFloat`, which a MusicXML font size written as a CSS
15/// size, `medium`, passes over.
16#[derive(Clone, Debug, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum StyleValue {
19    /// A whole number.
20    Whole(i64),
21    /// A number with a fraction.
22    Decimal(FloatType),
23    /// Text that is no number.
24    Text(String),
25}
26
27impl StyleValue {
28    /// The value an attribute's text gives.
29    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    /// The value as a number, where it is one.
42    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    /// As Python writes the `int`, `float` or string.
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        match self {
55            Self::Whole(whole) => write!(f, "{whole}"),
56            // Python writes a whole float with its point.
57            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/// Where a piece of text stands and how it is drawn: music21's
71/// `TextStyle`, the part of it MusicXML's print style, alignment and
72/// justification say.
73#[derive(Clone, Debug, Default, PartialEq)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
75pub struct TextStyle {
76    /// Across from where it is placed, in tenths: `absoluteX`,
77    /// MusicXML's `default-x`.
78    pub absolute_x: Option<StyleValue>,
79    /// Up from where it is placed: `absoluteY`, `default-y`.
80    pub absolute_y: Option<StyleValue>,
81    /// Across from its default place: `relativeX`, `relative-x`.
82    pub relative_x: Option<StyleValue>,
83    /// Up from its default place: `relativeY`, `relative-y`.
84    pub relative_y: Option<StyleValue>,
85    /// The fonts it may be set in, first choice first: `fontFamily`.
86    pub font_family: Option<Vec<String>>,
87    font_style: Option<String>,
88    /// Its size, in points or as a CSS size: `fontSize`.
89    pub font_size: Option<StyleValue>,
90    font_weight: Option<String>,
91    /// Its colour, as written: `color`.
92    pub color: Option<String>,
93    justify: Option<String>,
94    align_horizontal: Option<String>,
95    align_vertical: Option<String>,
96}
97
98impl TextStyle {
99    /// `italic`, `normal`, `bold` or `bolditalic`: music21's `fontStyle`.
100    pub fn font_style(&self) -> Option<&str> {
101        self.font_style.as_deref()
102    }
103
104    /// Sets the font style, read without regard to case.
105    ///
106    /// # Errors
107    ///
108    /// A style music21 does not name.
109    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    /// `normal` or `bold`: music21's `fontWeight`.
120    pub fn font_weight(&self) -> Option<&str> {
121        self.font_weight.as_deref()
122    }
123
124    /// Sets the font weight, read without regard to case.
125    ///
126    /// # Errors
127    ///
128    /// A weight music21 does not name.
129    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    /// `left`, `center`, `right` or `full`: music21's `justify`.
137    pub fn justify(&self) -> Option<&str> {
138        self.justify.as_deref()
139    }
140
141    /// Sets the justification, read without regard to case.
142    ///
143    /// # Errors
144    ///
145    /// A justification music21 does not name.
146    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    /// `left`, `right` or `center`: music21's `alignHorizontal`, MusicXML's
154    /// `halign`.
155    pub fn align_horizontal(&self) -> Option<&str> {
156        self.align_horizontal.as_deref()
157    }
158
159    /// Sets the horizontal alignment.
160    ///
161    /// # Errors
162    ///
163    /// An alignment music21 does not name.
164    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    /// `top`, `middle`, `bottom` or `baseline`: music21's `alignVertical`,
172    /// MusicXML's `valign`.
173    pub fn align_vertical(&self) -> Option<&str> {
174        self.align_vertical.as_deref()
175    }
176
177    /// Sets the vertical alignment.
178    ///
179    /// # Errors
180    ///
181    /// An alignment music21 does not name.
182    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
193/// A value checked against the ones music21 accepts, lowercased first
194/// where music21 lowercases it.
195fn 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/// How a whole score is drawn, past what its layouts say: music21's
217/// `StreamStyle`, the part MusicXML's `<defaults>` writes.
218#[derive(Clone, Debug, Default, PartialEq)]
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220pub struct StreamStyle {
221    /// Line widths by what they draw, in tenths: `lineWidths`.
222    pub line_widths: Vec<(String, StyleValue)>,
223    /// Note sizes by kind, as percentages: `noteSizes`.
224    pub note_sizes: Vec<(String, StyleValue)>,
225    /// Distances by what they separate, in tenths: `distances`.
226    pub distances: Vec<(String, StyleValue)>,
227    /// Any other appearance by its type: `otherAppearances`.
228    pub other_appearances: Vec<(String, StyleValue)>,
229    /// The font music is set in: `musicFont`.
230    pub music_font: Option<TextStyle>,
231    /// The font words are set in: `wordFont`.
232    pub word_font: Option<TextStyle>,
233    /// A font for the lyrics of each name: `lyricFonts`.
234    pub lyric_fonts: Vec<(Option<String>, Option<TextStyle>)>,
235    /// A language for the lyrics of each name: `lyricLanguages`.
236    pub lyric_languages: Vec<(Option<String>, Option<String>)>,
237}
238
239impl StreamStyle {
240    /// Whether it says anything MusicXML's `<appearance>` writes.
241    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
249/// The hex value of a CSS3 colour name, as `#FF0000` for `red`, whatever
250/// case the name is written in; `None` for a name CSS does not have.
251///
252/// ```
253/// use music21::style::css_color_hex;
254///
255/// assert_eq!(css_color_hex("Red"), Some("#FF0000"));
256/// assert_eq!(css_color_hex("grey"), css_color_hex("gray"));
257/// assert_eq!(css_color_hex("reddish"), None);
258/// ```
259pub 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
267/// The CSS3 colour names and their hex values, sorted by name: the table
268/// music21 reads a colour name out of, through `webcolors`.
269pub 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    /// Python writes a whole `float` with its point: music21's
449    /// `<line-width type="beam">5.0</line-width>`.
450    #[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}