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