Skip to main content

quickgui/
font.rs

1use std::{
2    fmt,
3    hash::{Hash, Hasher},
4    mem::size_of,
5    sync::{Arc, LazyLock},
6};
7
8use glyphon::{
9    Style as GlyphStyle, Weight,
10    cosmic_text::{
11        Family as GlyphFamily, FamilyOwned as GlyphFamilyOwned, FeatureTag as GlyphFeatureTag,
12        FontFeatures as GlyphFontFeatures,
13    },
14};
15
16/// Maximum UTF-8 size accepted for one named font family.
17pub const MAX_FONT_FAMILY_BYTES: usize = 1_024;
18/// Maximum number of ordered custom fallback families retained by one font style.
19pub const MAX_FONT_FALLBACKS: usize = 8;
20/// Maximum number of explicit OpenType feature values retained by one font style.
21pub const MAX_FONT_FEATURES: usize = 32;
22
23/// A generic or explicitly named font family.
24#[derive(Clone, Debug, Eq, Hash, PartialEq)]
25pub enum FontFamily {
26    SansSerif,
27    Serif,
28    Monospace,
29    Named(Arc<str>),
30}
31
32impl FontFamily {
33    /// Create a named family after enforcing QuickGUI's retained-string bound.
34    pub fn named(name: impl Into<Arc<str>>) -> Self {
35        let name = name.into();
36        assert_valid_family_name(&name);
37        Self::Named(name)
38    }
39}
40
41impl From<&str> for FontFamily {
42    fn from(value: &str) -> Self {
43        Self::named(value)
44    }
45}
46
47impl From<String> for FontFamily {
48    fn from(value: String) -> Self {
49        Self::named(value)
50    }
51}
52
53impl From<Arc<str>> for FontFamily {
54    fn from(value: Arc<str>) -> Self {
55        Self::named(value)
56    }
57}
58
59/// Ordered named families tried after the primary family and before platform fallbacks.
60///
61/// Clones share both the public family table and the precomputed Cosmic Text representation.
62#[derive(Clone)]
63pub struct FontFallbacks(Arc<FontFallbackData>);
64
65struct FontFallbackData {
66    families: Vec<Arc<str>>,
67    cosmic: Arc<[GlyphFamilyOwned]>,
68}
69
70static EMPTY_FONT_FALLBACKS: LazyLock<Arc<FontFallbackData>> = LazyLock::new(|| {
71    Arc::new(FontFallbackData {
72        families: Vec::new(),
73        cosmic: Arc::from([]),
74    })
75});
76
77impl FontFallbacks {
78    pub fn new() -> Self {
79        Self(Arc::clone(&EMPTY_FONT_FALLBACKS))
80    }
81
82    /// Build a canonical fallback stack. Duplicate names are removed in declaration order.
83    ///
84    /// # Panics
85    ///
86    /// Panics when a name is empty or above [`MAX_FONT_FAMILY_BYTES`], or when more than
87    /// [`MAX_FONT_FALLBACKS`] distinct families are supplied.
88    pub fn from_fonts<I, S>(fonts: I) -> Self
89    where
90        I: IntoIterator<Item = S>,
91        S: Into<Arc<str>>,
92    {
93        let fonts = fonts.into_iter();
94        let mut families = Vec::with_capacity(fonts.size_hint().0.min(MAX_FONT_FALLBACKS));
95        for family in fonts {
96            let family = family.into();
97            assert_valid_family_name(&family);
98            if families.iter().any(|current| current == &family) {
99                continue;
100            }
101            assert!(
102                families.len() < MAX_FONT_FALLBACKS,
103                "a font supports at most {MAX_FONT_FALLBACKS} custom fallback families"
104            );
105            families.push(family);
106        }
107        if families.is_empty() {
108            return Self::new();
109        }
110        let cosmic = families
111            .iter()
112            .map(|family| GlyphFamilyOwned::new(GlyphFamily::Name(family)))
113            .collect::<Vec<_>>()
114            .into();
115        Self(Arc::new(FontFallbackData { families, cosmic }))
116    }
117
118    pub fn fallback_list(&self) -> &[Arc<str>] {
119        &self.0.families
120    }
121
122    pub fn is_empty(&self) -> bool {
123        self.0.families.is_empty()
124    }
125
126    pub fn len(&self) -> usize {
127        self.0.families.len()
128    }
129
130    pub(crate) fn cosmic(&self) -> Arc<[GlyphFamilyOwned]> {
131        Arc::clone(&self.0.cosmic)
132    }
133
134    pub(crate) fn retained_bytes(&self) -> usize {
135        let names = self
136            .0
137            .families
138            .iter()
139            .fold(0_usize, |bytes, family| bytes.saturating_add(family.len()));
140        size_of::<FontFallbackData>()
141            .saturating_add(2 * size_of::<usize>())
142            .saturating_add(
143                self.0
144                    .families
145                    .capacity()
146                    .saturating_mul(size_of::<Arc<str>>()),
147            )
148            .saturating_add(
149                self.0
150                    .cosmic
151                    .len()
152                    .saturating_mul(size_of::<GlyphFamilyOwned>()),
153            )
154            .saturating_add(self.0.families.len().saturating_mul(2 * size_of::<usize>()))
155            .saturating_add(names.saturating_mul(2))
156    }
157}
158
159impl PartialEq for FontFallbacks {
160    fn eq(&self, other: &Self) -> bool {
161        self.0.families == other.0.families
162    }
163}
164
165impl Eq for FontFallbacks {}
166
167impl Hash for FontFallbacks {
168    fn hash<H: Hasher>(&self, state: &mut H) {
169        self.0.families.hash(state);
170    }
171}
172
173impl Default for FontFallbacks {
174    fn default() -> Self {
175        Self::new()
176    }
177}
178
179impl fmt::Debug for FontFallbacks {
180    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
181        formatter
182            .debug_tuple("FontFallbacks")
183            .field(&self.0.families)
184            .finish()
185    }
186}
187
188/// A validated four-byte OpenType feature tag.
189#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
190pub struct FontFeatureTag([u8; 4]);
191
192impl FontFeatureTag {
193    pub const KERNING: Self = Self(*b"kern");
194    pub const STANDARD_LIGATURES: Self = Self(*b"liga");
195    pub const CONTEXTUAL_LIGATURES: Self = Self(*b"clig");
196    pub const CONTEXTUAL_ALTERNATES: Self = Self(*b"calt");
197    pub const DISCRETIONARY_LIGATURES: Self = Self(*b"dlig");
198    pub const SMALL_CAPS: Self = Self(*b"smcp");
199    pub const ALL_SMALL_CAPS: Self = Self(*b"c2sc");
200    pub const TABULAR_NUMBERS: Self = Self(*b"tnum");
201    pub const PROPORTIONAL_NUMBERS: Self = Self(*b"pnum");
202    pub const OLDSTYLE_NUMBERS: Self = Self(*b"onum");
203    pub const LINING_NUMBERS: Self = Self(*b"lnum");
204    pub const SLASHED_ZERO: Self = Self(*b"zero");
205    pub const FRACTIONS: Self = Self(*b"frac");
206    pub const ORDINALS: Self = Self(*b"ordn");
207    pub const STYLISTIC_SET_1: Self = Self(*b"ss01");
208    pub const STYLISTIC_SET_2: Self = Self(*b"ss02");
209
210    pub const fn as_bytes(self) -> [u8; 4] {
211        self.0
212    }
213
214    pub fn as_str(&self) -> &str {
215        std::str::from_utf8(&self.0).expect("validated OpenType tags are ASCII")
216    }
217}
218
219impl fmt::Debug for FontFeatureTag {
220    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
221        formatter
222            .debug_tuple("FontFeatureTag")
223            .field(&self.as_str())
224            .finish()
225    }
226}
227
228impl fmt::Display for FontFeatureTag {
229    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
230        formatter.write_str(self.as_str())
231    }
232}
233
234/// Error returned when an OpenType feature tag is not four ASCII alphanumeric bytes.
235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
236pub struct FontFeatureTagError;
237
238impl fmt::Display for FontFeatureTagError {
239    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
240        formatter.write_str("an OpenType feature tag must contain four ASCII letters or digits")
241    }
242}
243
244impl std::error::Error for FontFeatureTagError {}
245
246impl TryFrom<&str> for FontFeatureTag {
247    type Error = FontFeatureTagError;
248
249    fn try_from(value: &str) -> Result<Self, Self::Error> {
250        let bytes: [u8; 4] = value
251            .as_bytes()
252            .try_into()
253            .map_err(|_| FontFeatureTagError)?;
254        if bytes.iter().all(u8::is_ascii_alphanumeric) {
255            Ok(Self(bytes))
256        } else {
257            Err(FontFeatureTagError)
258        }
259    }
260}
261
262impl TryFrom<String> for FontFeatureTag {
263    type Error = FontFeatureTagError;
264
265    fn try_from(value: String) -> Result<Self, Self::Error> {
266        Self::try_from(value.as_str())
267    }
268}
269
270/// One explicit OpenType feature value.
271#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
272pub struct FontFeature {
273    pub tag: FontFeatureTag,
274    pub value: u32,
275}
276
277/// Canonical, shared, and hard-bounded OpenType feature configuration.
278#[derive(Clone, Default, Eq, Hash, PartialEq)]
279pub struct FontFeatures(Option<Arc<Vec<FontFeature>>>);
280
281impl FontFeatures {
282    pub fn new() -> Self {
283        Self::default()
284    }
285
286    /// Set a feature value. Repeated tags replace their previous value and the retained table is
287    /// sorted by tag so equivalent declarations share the same text-layout cache key.
288    ///
289    /// # Panics
290    ///
291    /// Panics when more than [`MAX_FONT_FEATURES`] distinct tags are supplied.
292    pub fn set(self, tag: FontFeatureTag, value: u32) -> Self {
293        let mut features = self.0.unwrap_or_else(|| Arc::new(Vec::new()));
294        if let Some(index) = features.iter().position(|feature| feature.tag == tag) {
295            if features[index].value == value {
296                return Self(Some(features));
297            }
298            Arc::make_mut(&mut features)[index].value = value;
299        } else {
300            assert!(
301                features.len() < MAX_FONT_FEATURES,
302                "a font supports at most {MAX_FONT_FEATURES} explicit OpenType features"
303            );
304            let features = Arc::make_mut(&mut features);
305            features.push(FontFeature { tag, value });
306            features.sort_unstable_by_key(|feature| feature.tag);
307        }
308        Self(Some(features))
309    }
310
311    pub fn enable(self, tag: FontFeatureTag) -> Self {
312        self.set(tag, 1)
313    }
314
315    pub fn disable(self, tag: FontFeatureTag) -> Self {
316        self.set(tag, 0)
317    }
318
319    /// Match GPUI's convenience behavior by disabling contextual alternates (`calt`).
320    pub fn disable_ligatures() -> Self {
321        Self::new().disable(FontFeatureTag::CONTEXTUAL_ALTERNATES)
322    }
323
324    pub fn tag_value_list(&self) -> &[FontFeature] {
325        self.0.as_deref().map(Vec::as_slice).unwrap_or_default()
326    }
327
328    pub fn value(&self, tag: FontFeatureTag) -> Option<u32> {
329        self.tag_value_list()
330            .binary_search_by_key(&tag, |feature| feature.tag)
331            .ok()
332            .map(|index| self.tag_value_list()[index].value)
333    }
334
335    pub fn is_calt_enabled(&self) -> Option<bool> {
336        self.value(FontFeatureTag::CONTEXTUAL_ALTERNATES)
337            .map(|value| value == 1)
338    }
339
340    pub fn is_empty(&self) -> bool {
341        self.0.is_none()
342    }
343
344    pub fn len(&self) -> usize {
345        self.tag_value_list().len()
346    }
347
348    pub(crate) fn cosmic(&self) -> GlyphFontFeatures {
349        let mut features = GlyphFontFeatures::new();
350        features.features.reserve(self.len());
351        for feature in self.tag_value_list() {
352            let tag = feature.tag.as_bytes();
353            features.set(GlyphFeatureTag::new(&tag), feature.value);
354        }
355        features
356    }
357
358    pub(crate) fn retained_bytes(&self) -> usize {
359        self.0.as_ref().map_or(0, |features| {
360            size_of::<Vec<FontFeature>>()
361                .saturating_add(2 * size_of::<usize>())
362                .saturating_add(features.capacity().saturating_mul(size_of::<FontFeature>()))
363        })
364    }
365}
366
367impl fmt::Debug for FontFeatures {
368    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
369        formatter
370            .debug_tuple("FontFeatures")
371            .field(&self.tag_value_list())
372            .finish()
373    }
374}
375
376impl FromIterator<(FontFeatureTag, u32)> for FontFeatures {
377    fn from_iter<T: IntoIterator<Item = (FontFeatureTag, u32)>>(iter: T) -> Self {
378        iter.into_iter()
379            .fold(Self::new(), |features, (tag, value)| {
380                features.set(tag, value)
381            })
382    }
383}
384
385/// Complete inherited font configuration used by [`crate::Element::font`].
386#[derive(Clone, Debug, Eq, Hash, PartialEq)]
387pub struct Font {
388    pub family: FontFamily,
389    pub features: FontFeatures,
390    pub fallbacks: Option<FontFallbacks>,
391    pub weight: Weight,
392    pub style: GlyphStyle,
393}
394
395impl Font {
396    pub fn new(family: impl Into<FontFamily>) -> Self {
397        let family = family.into();
398        assert_valid_font_family(&family);
399        Self {
400            family,
401            features: FontFeatures::new(),
402            fallbacks: None,
403            weight: Weight::NORMAL,
404            style: GlyphStyle::Normal,
405        }
406    }
407
408    pub fn features(mut self, features: FontFeatures) -> Self {
409        self.features = features;
410        self
411    }
412
413    pub fn fallbacks(mut self, fallbacks: FontFallbacks) -> Self {
414        self.fallbacks = (!fallbacks.is_empty()).then_some(fallbacks);
415        self
416    }
417
418    pub fn weight(mut self, weight: Weight) -> Self {
419        self.weight = weight;
420        self
421    }
422
423    pub fn style(mut self, style: GlyphStyle) -> Self {
424        self.style = style;
425        self
426    }
427
428    pub fn bold(mut self) -> Self {
429        self.weight = Weight::BOLD;
430        self
431    }
432
433    pub fn italic(mut self) -> Self {
434        self.style = GlyphStyle::Italic;
435        self
436    }
437}
438
439impl Default for Font {
440    fn default() -> Self {
441        Self::new(FontFamily::SansSerif)
442    }
443}
444
445/// Construct a complete font configuration from a family name or generic [`FontFamily`].
446pub fn font(family: impl Into<FontFamily>) -> Font {
447    Font::new(family)
448}
449
450pub(crate) fn glyph_family(family: &FontFamily) -> GlyphFamily<'_> {
451    match family {
452        FontFamily::SansSerif => GlyphFamily::SansSerif,
453        FontFamily::Serif => GlyphFamily::Serif,
454        FontFamily::Monospace => GlyphFamily::Monospace,
455        FontFamily::Named(name) => GlyphFamily::Name(name),
456    }
457}
458
459pub(crate) fn assert_valid_font_family(family: &FontFamily) {
460    if let FontFamily::Named(name) = family {
461        assert_valid_family_name(name);
462    }
463}
464
465pub(crate) fn normalize_fallbacks(fallbacks: Option<FontFallbacks>) -> Option<FontFallbacks> {
466    fallbacks.filter(|fallbacks| !fallbacks.is_empty())
467}
468
469fn assert_valid_family_name(name: &str) {
470    assert!(!name.is_empty(), "font family names cannot be empty");
471    assert!(
472        name.len() <= MAX_FONT_FAMILY_BYTES,
473        "font family names support at most {MAX_FONT_FAMILY_BYTES} UTF-8 bytes"
474    );
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn features_are_validated_canonical_and_bounded() {
483        assert_eq!(
484            FontFeatureTag::try_from("calt").unwrap(),
485            FontFeatureTag::CONTEXTUAL_ALTERNATES
486        );
487        assert!(FontFeatureTag::try_from("abc").is_err());
488        assert!(FontFeatureTag::try_from("ab-c").is_err());
489
490        let features = FontFeatures::new()
491            .enable(FontFeatureTag::STANDARD_LIGATURES)
492            .disable(FontFeatureTag::CONTEXTUAL_ALTERNATES)
493            .disable(FontFeatureTag::STANDARD_LIGATURES);
494        assert_eq!(features.len(), 2);
495        assert_eq!(features.value(FontFeatureTag::STANDARD_LIGATURES), Some(0));
496        assert_eq!(features.is_calt_enabled(), Some(false));
497        assert_eq!(features, features.clone());
498        let unchanged = features.clone().disable(FontFeatureTag::STANDARD_LIGATURES);
499        assert!(Arc::ptr_eq(
500            features.0.as_ref().unwrap(),
501            unchanged.0.as_ref().unwrap()
502        ));
503        assert_eq!(
504            FontFeatures::new()
505                .enable(FontFeatureTag::STANDARD_LIGATURES)
506                .disable(FontFeatureTag::CONTEXTUAL_ALTERNATES),
507            FontFeatures::new()
508                .disable(FontFeatureTag::CONTEXTUAL_ALTERNATES)
509                .enable(FontFeatureTag::STANDARD_LIGATURES)
510        );
511    }
512
513    #[test]
514    fn fallback_stacks_deduplicate_and_precompute_cosmic_families() {
515        let fallbacks = FontFallbacks::from_fonts([
516            "Symbols Nerd Font",
517            "Apple Color Emoji",
518            "Symbols Nerd Font",
519        ]);
520        assert_eq!(fallbacks.len(), 2);
521        assert_eq!(fallbacks.fallback_list()[0].as_ref(), "Symbols Nerd Font");
522        assert_eq!(fallbacks.cosmic().len(), 2);
523    }
524
525    #[test]
526    fn shared_font_tables_keep_thin_handles_in_every_text_style() {
527        assert_eq!(size_of::<FontFeatures>(), size_of::<usize>());
528        assert_eq!(size_of::<FontFallbacks>(), size_of::<usize>());
529        assert!(FontFeatures::new().is_empty());
530    }
531
532    #[test]
533    #[should_panic(expected = "at most 8 custom fallback families")]
534    fn fallback_stacks_have_a_hard_count_bound() {
535        let _ = FontFallbacks::from_fonts(
536            (0..=MAX_FONT_FALLBACKS).map(|index| format!("Font {index}")),
537        );
538    }
539
540    #[test]
541    #[should_panic(expected = "at most 32 explicit OpenType features")]
542    fn feature_tables_have_a_hard_count_bound() {
543        let mut features = FontFeatures::new();
544        for index in 0..=MAX_FONT_FEATURES {
545            let tag = format!("x{index:03}");
546            features = features.set(FontFeatureTag::try_from(tag).unwrap(), 1);
547        }
548    }
549}