Skip to main content

gpui/text_system/
font_features.rs

1use std::borrow::Cow;
2use std::sync::Arc;
3
4use schemars::{JsonSchema, json_schema};
5
6/// The OpenType features that can be configured for a given font.
7#[derive(Clone, Eq, PartialEq, Hash)]
8pub struct FontFeatures(pub Arc<Vec<(String, u32)>>);
9
10impl Default for FontFeatures {
11    /// Shares one empty list, since a default `TextStyle` is built many times per frame.
12    fn default() -> Self {
13        static EMPTY: std::sync::LazyLock<Arc<Vec<(String, u32)>>> =
14            std::sync::LazyLock::new(|| Arc::new(Vec::new()));
15        Self(EMPTY.clone())
16    }
17}
18
19impl FontFeatures {
20    /// Disables `calt`.
21    pub fn disable_ligatures() -> Self {
22        Self(Arc::new(vec![("calt".into(), 0)]))
23    }
24
25    /// Get the tag name list of the font OpenType features
26    /// only enabled or disabled features are returned
27    pub fn tag_value_list(&self) -> &[(String, u32)] {
28        self.0.as_slice()
29    }
30
31    /// Returns whether the `calt` feature is enabled.
32    ///
33    /// Returns `None` if the feature is not present.
34    pub fn is_calt_enabled(&self) -> Option<bool> {
35        self.0
36            .iter()
37            .find(|(feature, _)| feature == "calt")
38            .map(|(_, value)| *value == 1)
39    }
40}
41
42impl std::fmt::Debug for FontFeatures {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        let mut debug = f.debug_struct("FontFeatures");
45        for (tag, value) in self.tag_value_list() {
46            debug.field(tag, value);
47        }
48
49        debug.finish()
50    }
51}
52
53#[derive(Debug, serde::Serialize, serde::Deserialize)]
54#[serde(untagged)]
55enum FeatureValue {
56    Bool(bool),
57    Number(serde_json::Number),
58}
59
60impl<'de> serde::Deserialize<'de> for FontFeatures {
61    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62    where
63        D: serde::Deserializer<'de>,
64    {
65        use serde::de::{MapAccess, Visitor};
66        use std::fmt;
67
68        struct FontFeaturesVisitor;
69
70        impl<'de> Visitor<'de> for FontFeaturesVisitor {
71            type Value = FontFeatures;
72
73            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
74                formatter.write_str("a map of font features")
75            }
76
77            fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
78            where
79                M: MapAccess<'de>,
80            {
81                let mut feature_list = Vec::new();
82
83                while let Some((key, value)) =
84                    access.next_entry::<String, Option<FeatureValue>>()?
85                {
86                    if !is_valid_feature_tag(&key) {
87                        log::error!("Incorrect font feature tag: {}", key);
88                        continue;
89                    }
90                    if let Some(value) = value {
91                        match value {
92                            FeatureValue::Bool(enable) => {
93                                if enable {
94                                    feature_list.push((key, 1));
95                                } else {
96                                    feature_list.push((key, 0));
97                                }
98                            }
99                            FeatureValue::Number(value) => {
100                                if value.is_u64() {
101                                    feature_list.push((key, value.as_u64().unwrap() as u32));
102                                } else {
103                                    log::error!(
104                                        "Incorrect font feature value {} for feature tag {}",
105                                        value,
106                                        key
107                                    );
108                                    continue;
109                                }
110                            }
111                        }
112                    }
113                }
114
115                Ok(FontFeatures(Arc::new(feature_list)))
116            }
117        }
118
119        let features = deserializer.deserialize_map(FontFeaturesVisitor)?;
120        Ok(features)
121    }
122}
123
124impl serde::Serialize for FontFeatures {
125    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
126    where
127        S: serde::Serializer,
128    {
129        use serde::ser::SerializeMap;
130
131        let mut map = serializer.serialize_map(None)?;
132
133        for (tag, value) in self.tag_value_list() {
134            map.serialize_entry(tag, value)?;
135        }
136
137        map.end()
138    }
139}
140
141impl JsonSchema for FontFeatures {
142    fn schema_name() -> Cow<'static, str> {
143        "FontFeatures".into()
144    }
145
146    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
147        json_schema!({
148            "type": "object",
149            "patternProperties": {
150                "[0-9a-zA-Z]{4}$": {
151                    "type": ["boolean", "integer"],
152                    "minimum": 0,
153                    "multipleOf": 1
154                }
155            },
156            "additionalProperties": false
157        })
158    }
159}
160
161fn is_valid_feature_tag(tag: &str) -> bool {
162    tag.len() == 4 && tag.chars().all(|c| c.is_ascii_alphanumeric())
163}