1use crate::{
2 color::Color,
3 font_cache::FamilyId,
4 json::{json, ToJson},
5 text_layout::RunStyle,
6 FontCache,
7};
8use anyhow::anyhow;
9pub use font_kit::{
10 metrics::Metrics,
11 properties::{Properties, Stretch, Style, Weight},
12};
13use serde::{de, Deserialize};
14use serde_json::Value;
15use std::{cell::RefCell, sync::Arc};
16
17#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
18pub struct FontId(pub usize);
19
20pub type GlyphId = u32;
21
22#[derive(Clone, Debug)]
23pub struct TextStyle {
24 pub color: Color,
25 pub font_family_name: Arc<str>,
26 pub font_family_id: FamilyId,
27 pub font_id: FontId,
28 pub font_size: f32,
29 pub font_properties: Properties,
30 pub underline: Option<Color>,
31}
32
33#[derive(Clone, Debug, Default)]
34pub struct HighlightStyle {
35 pub color: Color,
36 pub font_properties: Properties,
37 pub underline: Option<Color>,
38}
39
40#[allow(non_camel_case_types)]
41#[derive(Deserialize)]
42enum WeightJson {
43 thin,
44 extra_light,
45 light,
46 normal,
47 medium,
48 semibold,
49 bold,
50 extra_bold,
51 black,
52}
53
54thread_local! {
55 static FONT_CACHE: RefCell<Option<Arc<FontCache>>> = Default::default();
56}
57
58#[derive(Deserialize)]
59struct TextStyleJson {
60 color: Color,
61 family: String,
62 weight: Option<WeightJson>,
63 size: f32,
64 #[serde(default)]
65 italic: bool,
66 #[serde(default)]
67 underline: UnderlineStyleJson,
68}
69
70#[derive(Deserialize)]
71struct HighlightStyleJson {
72 color: Color,
73 weight: Option<WeightJson>,
74 #[serde(default)]
75 italic: bool,
76 #[serde(default)]
77 underline: UnderlineStyleJson,
78}
79
80#[derive(Deserialize)]
81#[serde(untagged)]
82enum UnderlineStyleJson {
83 Underlined(bool),
84 UnderlinedWithColor(Color),
85}
86
87impl TextStyle {
88 pub fn new(
89 font_family_name: impl Into<Arc<str>>,
90 font_size: f32,
91 font_properties: Properties,
92 underline: Option<Color>,
93 color: Color,
94 font_cache: &FontCache,
95 ) -> anyhow::Result<Self> {
96 let font_family_name = font_family_name.into();
97 let font_family_id = font_cache.load_family(&[&font_family_name])?;
98 let font_id = font_cache.select_font(font_family_id, &font_properties)?;
99 Ok(Self {
100 color,
101 font_family_name,
102 font_family_id,
103 font_id,
104 font_size,
105 font_properties,
106 underline,
107 })
108 }
109
110 pub fn to_run(&self) -> RunStyle {
111 RunStyle {
112 font_id: self.font_id,
113 color: self.color,
114 underline: self.underline,
115 }
116 }
117
118 fn from_json(json: TextStyleJson) -> anyhow::Result<Self> {
119 FONT_CACHE.with(|font_cache| {
120 if let Some(font_cache) = font_cache.borrow().as_ref() {
121 let font_properties = properties_from_json(json.weight, json.italic);
122 Self::new(
123 json.family,
124 json.size,
125 font_properties,
126 underline_from_json(json.underline, json.color),
127 json.color,
128 font_cache,
129 )
130 } else {
131 Err(anyhow!(
132 "TextStyle can only be deserialized within a call to with_font_cache"
133 ))
134 }
135 })
136 }
137
138 pub fn line_height(&self, font_cache: &FontCache) -> f32 {
139 font_cache.line_height(self.font_id, self.font_size)
140 }
141
142 pub fn cap_height(&self, font_cache: &FontCache) -> f32 {
143 font_cache.cap_height(self.font_id, self.font_size)
144 }
145
146 pub fn x_height(&self, font_cache: &FontCache) -> f32 {
147 font_cache.x_height(self.font_id, self.font_size)
148 }
149
150 pub fn em_width(&self, font_cache: &FontCache) -> f32 {
151 font_cache.em_width(self.font_id, self.font_size)
152 }
153
154 pub fn descent(&self, font_cache: &FontCache) -> f32 {
155 font_cache.metric(self.font_id, |m| m.descent) * self.em_scale(font_cache)
156 }
157
158 pub fn baseline_offset(&self, font_cache: &FontCache) -> f32 {
159 font_cache.baseline_offset(self.font_id, self.font_size)
160 }
161
162 fn em_scale(&self, font_cache: &FontCache) -> f32 {
163 font_cache.em_scale(self.font_id, self.font_size)
164 }
165}
166
167impl From<TextStyle> for HighlightStyle {
168 fn from(other: TextStyle) -> Self {
169 Self {
170 color: other.color,
171 font_properties: other.font_properties,
172 underline: other.underline,
173 }
174 }
175}
176
177impl Default for UnderlineStyleJson {
178 fn default() -> Self {
179 Self::Underlined(false)
180 }
181}
182
183impl Default for TextStyle {
184 fn default() -> Self {
185 FONT_CACHE.with(|font_cache| {
186 let font_cache = font_cache.borrow();
187 let font_cache = font_cache
188 .as_ref()
189 .expect("TextStyle::default can only be called within a call to with_font_cache");
190
191 let font_family_name = Arc::from("Courier");
192 let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
193 let font_id = font_cache
194 .select_font(font_family_id, &Default::default())
195 .unwrap();
196 Self {
197 color: Default::default(),
198 font_family_name,
199 font_family_id,
200 font_id,
201 font_size: 14.,
202 font_properties: Default::default(),
203 underline: Default::default(),
204 }
205 })
206 }
207}
208
209impl HighlightStyle {
210 fn from_json(json: HighlightStyleJson) -> Self {
211 let font_properties = properties_from_json(json.weight, json.italic);
212 Self {
213 color: json.color,
214 font_properties,
215 underline: underline_from_json(json.underline, json.color),
216 }
217 }
218}
219
220impl From<Color> for HighlightStyle {
221 fn from(color: Color) -> Self {
222 Self {
223 color,
224 font_properties: Default::default(),
225 underline: None,
226 }
227 }
228}
229
230impl<'de> Deserialize<'de> for TextStyle {
231 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
232 where
233 D: serde::Deserializer<'de>,
234 {
235 Ok(Self::from_json(TextStyleJson::deserialize(deserializer)?)
236 .map_err(|e| de::Error::custom(e))?)
237 }
238}
239
240impl ToJson for TextStyle {
241 fn to_json(&self) -> Value {
242 json!({
243 "color": self.color.to_json(),
244 "font_family": self.font_family_name.as_ref(),
245 "font_properties": self.font_properties.to_json(),
246 })
247 }
248}
249
250impl<'de> Deserialize<'de> for HighlightStyle {
251 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
252 where
253 D: serde::Deserializer<'de>,
254 {
255 let json = serde_json::Value::deserialize(deserializer)?;
256 if json.is_object() {
257 Ok(Self::from_json(
258 serde_json::from_value(json).map_err(de::Error::custom)?,
259 ))
260 } else {
261 Ok(Self {
262 color: serde_json::from_value(json).map_err(de::Error::custom)?,
263 font_properties: Properties::new(),
264 underline: None,
265 })
266 }
267 }
268}
269
270fn underline_from_json(json: UnderlineStyleJson, text_color: Color) -> Option<Color> {
271 match json {
272 UnderlineStyleJson::Underlined(false) => None,
273 UnderlineStyleJson::Underlined(true) => Some(text_color),
274 UnderlineStyleJson::UnderlinedWithColor(color) => Some(color),
275 }
276}
277
278fn properties_from_json(weight: Option<WeightJson>, italic: bool) -> Properties {
279 let weight = match weight.unwrap_or(WeightJson::normal) {
280 WeightJson::thin => Weight::THIN,
281 WeightJson::extra_light => Weight::EXTRA_LIGHT,
282 WeightJson::light => Weight::LIGHT,
283 WeightJson::normal => Weight::NORMAL,
284 WeightJson::medium => Weight::MEDIUM,
285 WeightJson::semibold => Weight::SEMIBOLD,
286 WeightJson::bold => Weight::BOLD,
287 WeightJson::extra_bold => Weight::EXTRA_BOLD,
288 WeightJson::black => Weight::BLACK,
289 };
290 let style = if italic { Style::Italic } else { Style::Normal };
291 *Properties::new().weight(weight).style(style)
292}
293
294impl ToJson for Properties {
295 fn to_json(&self) -> crate::json::Value {
296 json!({
297 "style": self.style.to_json(),
298 "weight": self.weight.to_json(),
299 "stretch": self.stretch.to_json(),
300 })
301 }
302}
303
304impl ToJson for Style {
305 fn to_json(&self) -> crate::json::Value {
306 match self {
307 Style::Normal => json!("normal"),
308 Style::Italic => json!("italic"),
309 Style::Oblique => json!("oblique"),
310 }
311 }
312}
313
314impl ToJson for Weight {
315 fn to_json(&self) -> crate::json::Value {
316 if self.0 == Weight::THIN.0 {
317 json!("thin")
318 } else if self.0 == Weight::EXTRA_LIGHT.0 {
319 json!("extra light")
320 } else if self.0 == Weight::LIGHT.0 {
321 json!("light")
322 } else if self.0 == Weight::NORMAL.0 {
323 json!("normal")
324 } else if self.0 == Weight::MEDIUM.0 {
325 json!("medium")
326 } else if self.0 == Weight::SEMIBOLD.0 {
327 json!("semibold")
328 } else if self.0 == Weight::BOLD.0 {
329 json!("bold")
330 } else if self.0 == Weight::EXTRA_BOLD.0 {
331 json!("extra bold")
332 } else if self.0 == Weight::BLACK.0 {
333 json!("black")
334 } else {
335 json!(self.0)
336 }
337 }
338}
339
340impl ToJson for Stretch {
341 fn to_json(&self) -> serde_json::Value {
342 json!(self.0)
343 }
344}
345
346pub fn with_font_cache<F, T>(font_cache: Arc<FontCache>, callback: F) -> T
347where
348 F: FnOnce() -> T,
349{
350 FONT_CACHE.with(|cache| {
351 *cache.borrow_mut() = Some(font_cache);
352 let result = callback();
353 cache.borrow_mut().take();
354 result
355 })
356}