Skip to main content

sui_text/
style.rs

1//! Font styling primitives: weight, slant, width, and OpenType feature settings.
2//!
3//! These are sui-text-native types. They map to the shaping backend (cosmic-text) only at the
4//! `Attrs` boundary (see `font.rs`), so callers never depend on cosmic-text directly.
5
6/// OpenType weight axis value. Conventional named weights span 100..=900; for variable fonts any
7/// value in the font's `wght` range is valid.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct FontWeight(pub u16);
10
11impl FontWeight {
12    pub const THIN: Self = Self(100);
13    pub const EXTRA_LIGHT: Self = Self(200);
14    pub const LIGHT: Self = Self(300);
15    pub const NORMAL: Self = Self(400);
16    pub const MEDIUM: Self = Self(500);
17    pub const SEMIBOLD: Self = Self(600);
18    pub const BOLD: Self = Self(700);
19    pub const EXTRA_BOLD: Self = Self(800);
20    pub const BLACK: Self = Self(900);
21
22    pub const fn new(value: u16) -> Self {
23        Self(value)
24    }
25
26    pub const fn value(self) -> u16 {
27        self.0
28    }
29}
30
31impl Default for FontWeight {
32    fn default() -> Self {
33        Self::NORMAL
34    }
35}
36
37/// Font slant.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum FontStyle {
40    #[default]
41    Normal,
42    Italic,
43    Oblique,
44}
45
46/// Font width (the standard nine CSS `font-stretch` keywords / OS/2 width classes).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
48pub enum FontStretch {
49    UltraCondensed,
50    ExtraCondensed,
51    Condensed,
52    SemiCondensed,
53    #[default]
54    Normal,
55    SemiExpanded,
56    Expanded,
57    ExtraExpanded,
58    UltraExpanded,
59}
60
61/// A single OpenType feature setting: a 4-byte tag plus a value (`0` disables, `1` enables, and
62/// larger values select an alternate/parameter for features that take one).
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub struct FontFeature {
65    pub tag: [u8; 4],
66    pub value: u32,
67}
68
69impl FontFeature {
70    pub const KERNING: [u8; 4] = *b"kern";
71    pub const STANDARD_LIGATURES: [u8; 4] = *b"liga";
72    pub const CONTEXTUAL_LIGATURES: [u8; 4] = *b"clig";
73    pub const DISCRETIONARY_LIGATURES: [u8; 4] = *b"dlig";
74    pub const SMALL_CAPS: [u8; 4] = *b"smcp";
75    pub const CAPITALS_TO_SMALL_CAPS: [u8; 4] = *b"c2sc";
76    pub const TABULAR_FIGURES: [u8; 4] = *b"tnum";
77    pub const OLDSTYLE_FIGURES: [u8; 4] = *b"onum";
78    pub const FRACTIONS: [u8; 4] = *b"frac";
79    pub const SLASHED_ZERO: [u8; 4] = *b"zero";
80
81    /// Stylistic set `n` (1..=20), e.g. `stylistic_set(1)` -> `ss01`.
82    pub const fn stylistic_set(n: u8) -> [u8; 4] {
83        let tens = b'0' + (n / 10);
84        let ones = b'0' + (n % 10);
85        [b's', b's', tens, ones]
86    }
87
88    pub const fn on(tag: [u8; 4]) -> Self {
89        Self { tag, value: 1 }
90    }
91
92    pub const fn off(tag: [u8; 4]) -> Self {
93        Self { tag, value: 0 }
94    }
95
96    pub const fn set(tag: [u8; 4], value: u32) -> Self {
97        Self { tag, value }
98    }
99}
100
101/// An ordered collection of OpenType feature settings applied to a text run. Later settings for
102/// the same tag take precedence in the shaper.
103#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
104pub struct FontFeatures {
105    features: Vec<FontFeature>,
106}
107
108impl FontFeatures {
109    pub const fn new() -> Self {
110        Self {
111            features: Vec::new(),
112        }
113    }
114
115    /// Enable a feature (`value = 1`).
116    pub fn enable(&mut self, tag: [u8; 4]) -> &mut Self {
117        self.features.push(FontFeature::on(tag));
118        self
119    }
120
121    /// Disable a feature (`value = 0`).
122    pub fn disable(&mut self, tag: [u8; 4]) -> &mut Self {
123        self.features.push(FontFeature::off(tag));
124        self
125    }
126
127    /// Set a feature to an explicit value.
128    pub fn set(&mut self, tag: [u8; 4], value: u32) -> &mut Self {
129        self.features.push(FontFeature::set(tag, value));
130        self
131    }
132
133    pub fn is_empty(&self) -> bool {
134        self.features.is_empty()
135    }
136
137    pub fn len(&self) -> usize {
138        self.features.len()
139    }
140
141    pub fn iter(&self) -> impl Iterator<Item = &FontFeature> {
142        self.features.iter()
143    }
144}
145
146impl FromIterator<FontFeature> for FontFeatures {
147    fn from_iter<I: IntoIterator<Item = FontFeature>>(iter: I) -> Self {
148        Self {
149            features: iter.into_iter().collect(),
150        }
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn weight_named_values_and_default() {
160        assert_eq!(FontWeight::NORMAL.value(), 400);
161        assert_eq!(FontWeight::BOLD.value(), 700);
162        assert_eq!(FontWeight::THIN.value(), 100);
163        assert_eq!(FontWeight::BLACK.value(), 900);
164        assert_eq!(FontWeight::new(550).value(), 550);
165        assert_eq!(FontWeight::default(), FontWeight::NORMAL);
166    }
167
168    #[test]
169    fn style_and_stretch_defaults_are_normal() {
170        assert_eq!(FontStyle::default(), FontStyle::Normal);
171        assert_eq!(FontStretch::default(), FontStretch::Normal);
172    }
173
174    #[test]
175    fn feature_tag_constants_and_constructors() {
176        assert_eq!(FontFeature::STANDARD_LIGATURES, *b"liga");
177        assert_eq!(FontFeature::SMALL_CAPS, *b"smcp");
178        assert_eq!(FontFeature::stylistic_set(1), *b"ss01");
179        assert_eq!(FontFeature::stylistic_set(12), *b"ss12");
180        assert_eq!(
181            FontFeature::on(*b"liga"),
182            FontFeature {
183                tag: *b"liga",
184                value: 1
185            }
186        );
187        assert_eq!(
188            FontFeature::off(*b"liga"),
189            FontFeature {
190                tag: *b"liga",
191                value: 0
192            }
193        );
194        assert_eq!(FontFeature::set(*b"aalt", 3).value, 3);
195    }
196
197    #[test]
198    fn feature_collection_records_settings_in_order() {
199        let mut features = FontFeatures::new();
200        assert!(features.is_empty());
201        features
202            .disable(FontFeature::STANDARD_LIGATURES)
203            .enable(FontFeature::SMALL_CAPS)
204            .set(FontFeature::TABULAR_FIGURES, 1);
205
206        let collected: Vec<_> = features.iter().copied().collect();
207        assert_eq!(
208            collected,
209            vec![
210                FontFeature::off(*b"liga"),
211                FontFeature::on(*b"smcp"),
212                FontFeature::set(*b"tnum", 1),
213            ]
214        );
215        assert_eq!(features.len(), 3);
216        assert!(!features.is_empty());
217    }
218
219    #[test]
220    fn features_equality_is_order_sensitive() {
221        let a: FontFeatures = [FontFeature::on(*b"liga"), FontFeature::on(*b"smcp")]
222            .into_iter()
223            .collect();
224        let b: FontFeatures = [FontFeature::on(*b"smcp"), FontFeature::on(*b"liga")]
225            .into_iter()
226            .collect();
227        assert_ne!(a, b);
228
229        let c: FontFeatures = [FontFeature::on(*b"liga"), FontFeature::on(*b"smcp")]
230            .into_iter()
231            .collect();
232        assert_eq!(a, c);
233    }
234}