fonts.rs

  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: bool,
 31}
 32
 33#[derive(Clone, Debug, Default)]
 34pub struct HighlightStyle {
 35    pub color: Color,
 36    pub font_properties: Properties,
 37    pub underline: bool,
 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: bool,
 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: bool,
 78}
 79
 80impl TextStyle {
 81    pub fn new(
 82        font_family_name: impl Into<Arc<str>>,
 83        font_size: f32,
 84        font_properties: Properties,
 85        underline: bool,
 86        color: Color,
 87        font_cache: &FontCache,
 88    ) -> anyhow::Result<Self> {
 89        let font_family_name = font_family_name.into();
 90        let font_family_id = font_cache.load_family(&[&font_family_name])?;
 91        let font_id = font_cache.select_font(font_family_id, &font_properties)?;
 92        Ok(Self {
 93            color,
 94            font_family_name,
 95            font_family_id,
 96            font_id,
 97            font_size,
 98            font_properties,
 99            underline,
100        })
101    }
102
103    pub fn to_run(&self) -> RunStyle {
104        RunStyle {
105            font_id: self.font_id,
106            color: self.color,
107            underline: self.underline,
108        }
109    }
110
111    fn from_json(json: TextStyleJson) -> anyhow::Result<Self> {
112        FONT_CACHE.with(|font_cache| {
113            if let Some(font_cache) = font_cache.borrow().as_ref() {
114                let font_properties = properties_from_json(json.weight, json.italic);
115                Self::new(
116                    json.family,
117                    json.size,
118                    font_properties,
119                    json.underline,
120                    json.color,
121                    font_cache,
122                )
123            } else {
124                Err(anyhow!(
125                    "TextStyle can only be deserialized within a call to with_font_cache"
126                ))
127            }
128        })
129    }
130
131    pub fn line_height(&self, font_cache: &FontCache) -> f32 {
132        font_cache.line_height(self.font_id, self.font_size)
133    }
134
135    pub fn em_width(&self, font_cache: &FontCache) -> f32 {
136        font_cache.em_width(self.font_id, self.font_size)
137    }
138
139    pub fn descent(&self, font_cache: &FontCache) -> f32 {
140        font_cache.metric(self.font_id, |m| m.descent) * self.em_scale(font_cache)
141    }
142
143    fn em_scale(&self, font_cache: &FontCache) -> f32 {
144        font_cache.em_scale(self.font_id, self.font_size)
145    }
146}
147
148impl From<TextStyle> for HighlightStyle {
149    fn from(other: TextStyle) -> Self {
150        Self {
151            color: other.color,
152            font_properties: other.font_properties,
153            underline: other.underline,
154        }
155    }
156}
157
158impl HighlightStyle {
159    fn from_json(json: HighlightStyleJson) -> Self {
160        let font_properties = properties_from_json(json.weight, json.italic);
161        Self {
162            color: json.color,
163            font_properties,
164            underline: json.underline,
165        }
166    }
167}
168
169impl From<Color> for HighlightStyle {
170    fn from(color: Color) -> Self {
171        Self {
172            color,
173            font_properties: Default::default(),
174            underline: false,
175        }
176    }
177}
178
179impl<'de> Deserialize<'de> for TextStyle {
180    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181    where
182        D: serde::Deserializer<'de>,
183    {
184        Ok(Self::from_json(TextStyleJson::deserialize(deserializer)?)
185            .map_err(|e| de::Error::custom(e))?)
186    }
187}
188
189impl ToJson for TextStyle {
190    fn to_json(&self) -> Value {
191        json!({
192            "color": self.color.to_json(),
193            "font_family": self.font_family_name.as_ref(),
194            "font_properties": self.font_properties.to_json(),
195        })
196    }
197}
198
199impl<'de> Deserialize<'de> for HighlightStyle {
200    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
201    where
202        D: serde::Deserializer<'de>,
203    {
204        let json = serde_json::Value::deserialize(deserializer)?;
205        if json.is_object() {
206            Ok(Self::from_json(
207                serde_json::from_value(json).map_err(de::Error::custom)?,
208            ))
209        } else {
210            Ok(Self {
211                color: serde_json::from_value(json).map_err(de::Error::custom)?,
212                font_properties: Properties::new(),
213                underline: false,
214            })
215        }
216    }
217}
218
219fn properties_from_json(weight: Option<WeightJson>, italic: bool) -> Properties {
220    let weight = match weight.unwrap_or(WeightJson::normal) {
221        WeightJson::thin => Weight::THIN,
222        WeightJson::extra_light => Weight::EXTRA_LIGHT,
223        WeightJson::light => Weight::LIGHT,
224        WeightJson::normal => Weight::NORMAL,
225        WeightJson::medium => Weight::MEDIUM,
226        WeightJson::semibold => Weight::SEMIBOLD,
227        WeightJson::bold => Weight::BOLD,
228        WeightJson::extra_bold => Weight::EXTRA_BOLD,
229        WeightJson::black => Weight::BLACK,
230    };
231    let style = if italic { Style::Italic } else { Style::Normal };
232    *Properties::new().weight(weight).style(style)
233}
234
235impl ToJson for Properties {
236    fn to_json(&self) -> crate::json::Value {
237        json!({
238            "style": self.style.to_json(),
239            "weight": self.weight.to_json(),
240            "stretch": self.stretch.to_json(),
241        })
242    }
243}
244
245impl ToJson for Style {
246    fn to_json(&self) -> crate::json::Value {
247        match self {
248            Style::Normal => json!("normal"),
249            Style::Italic => json!("italic"),
250            Style::Oblique => json!("oblique"),
251        }
252    }
253}
254
255impl ToJson for Weight {
256    fn to_json(&self) -> crate::json::Value {
257        if self.0 == Weight::THIN.0 {
258            json!("thin")
259        } else if self.0 == Weight::EXTRA_LIGHT.0 {
260            json!("extra light")
261        } else if self.0 == Weight::LIGHT.0 {
262            json!("light")
263        } else if self.0 == Weight::NORMAL.0 {
264            json!("normal")
265        } else if self.0 == Weight::MEDIUM.0 {
266            json!("medium")
267        } else if self.0 == Weight::SEMIBOLD.0 {
268            json!("semibold")
269        } else if self.0 == Weight::BOLD.0 {
270            json!("bold")
271        } else if self.0 == Weight::EXTRA_BOLD.0 {
272            json!("extra bold")
273        } else if self.0 == Weight::BLACK.0 {
274            json!("black")
275        } else {
276            json!(self.0)
277        }
278    }
279}
280
281impl ToJson for Stretch {
282    fn to_json(&self) -> serde_json::Value {
283        json!(self.0)
284    }
285}
286
287pub fn with_font_cache<F, T>(font_cache: Arc<FontCache>, callback: F) -> T
288where
289    F: FnOnce() -> T,
290{
291    FONT_CACHE.with(|cache| {
292        *cache.borrow_mut() = Some(font_cache);
293        let result = callback();
294        cache.borrow_mut().take();
295        result
296    })
297}