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, Result};
  9pub use font_kit::{
 10    metrics::Metrics,
 11    properties::{Properties, Stretch, Style, Weight},
 12};
 13use ordered_float::OrderedFloat;
 14use refineable::Refineable;
 15use schemars::JsonSchema;
 16use serde::{de, Deserialize, Serialize};
 17use serde_json::Value;
 18use std::{cell::RefCell, sync::Arc};
 19
 20#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, JsonSchema)]
 21pub struct FontId(pub usize);
 22
 23pub type GlyphId = u32;
 24
 25#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
 26pub struct Features {
 27    pub calt: Option<bool>,
 28    pub case: Option<bool>,
 29    pub cpsp: Option<bool>,
 30    pub frac: Option<bool>,
 31    pub liga: Option<bool>,
 32    pub onum: Option<bool>,
 33    pub ordn: Option<bool>,
 34    pub pnum: Option<bool>,
 35    pub ss01: Option<bool>,
 36    pub ss02: Option<bool>,
 37    pub ss03: Option<bool>,
 38    pub ss04: Option<bool>,
 39    pub ss05: Option<bool>,
 40    pub ss06: Option<bool>,
 41    pub ss07: Option<bool>,
 42    pub ss08: Option<bool>,
 43    pub ss09: Option<bool>,
 44    pub ss10: Option<bool>,
 45    pub ss11: Option<bool>,
 46    pub ss12: Option<bool>,
 47    pub ss13: Option<bool>,
 48    pub ss14: Option<bool>,
 49    pub ss15: Option<bool>,
 50    pub ss16: Option<bool>,
 51    pub ss17: Option<bool>,
 52    pub ss18: Option<bool>,
 53    pub ss19: Option<bool>,
 54    pub ss20: Option<bool>,
 55    pub subs: Option<bool>,
 56    pub sups: Option<bool>,
 57    pub swsh: Option<bool>,
 58    pub titl: Option<bool>,
 59    pub tnum: Option<bool>,
 60    pub zero: Option<bool>,
 61}
 62
 63#[derive(Clone, Debug, JsonSchema)]
 64pub struct TextStyle {
 65    pub color: Color,
 66    pub font_family_name: Arc<str>,
 67    pub font_family_id: FamilyId,
 68    pub font_id: FontId,
 69    pub font_size: f32,
 70    #[schemars(with = "PropertiesDef")]
 71    pub font_properties: Properties,
 72    pub underline: Underline,
 73    pub soft_wrap: bool,
 74}
 75
 76impl TextStyle {
 77    pub fn for_color(color: Color) -> Self {
 78        Self {
 79            color,
 80            ..Default::default()
 81        }
 82    }
 83}
 84
 85impl TextStyle {
 86    pub fn refine(
 87        &mut self,
 88        refinement: &TextStyleRefinement,
 89        font_cache: &FontCache,
 90    ) -> Result<()> {
 91        if let Some(font_size) = refinement.font_size {
 92            self.font_size = font_size;
 93        }
 94        if let Some(color) = refinement.color {
 95            self.color = color;
 96        }
 97        if let Some(underline) = refinement.underline {
 98            self.underline = underline;
 99        }
100
101        let mut update_font_id = false;
102        if let Some(font_family) = refinement.font_family.clone() {
103            self.font_family_id = font_cache.load_family(&[&font_family], &Default::default())?;
104            self.font_family_name = font_family;
105            update_font_id = true;
106        }
107        if let Some(font_weight) = refinement.font_weight {
108            self.font_properties.weight = font_weight;
109            update_font_id = true;
110        }
111        if let Some(font_style) = refinement.font_style {
112            self.font_properties.style = font_style;
113            update_font_id = true;
114        }
115
116        if update_font_id {
117            self.font_id = font_cache.select_font(self.font_family_id, &self.font_properties)?;
118        }
119
120        Ok(())
121    }
122}
123
124#[derive(Clone, Debug, Default)]
125pub struct TextStyleRefinement {
126    pub color: Option<Color>,
127    pub font_family: Option<Arc<str>>,
128    pub font_size: Option<f32>,
129    pub font_weight: Option<Weight>,
130    pub font_style: Option<Style>,
131    pub underline: Option<Underline>,
132}
133
134impl Refineable for TextStyleRefinement {
135    type Refinement = Self;
136
137    fn refine(&mut self, refinement: &Self::Refinement) {
138        if refinement.color.is_some() {
139            self.color = refinement.color;
140        }
141        if refinement.font_family.is_some() {
142            self.font_family = refinement.font_family.clone();
143        }
144        if refinement.font_size.is_some() {
145            self.font_size = refinement.font_size;
146        }
147        if refinement.font_weight.is_some() {
148            self.font_weight = refinement.font_weight;
149        }
150        if refinement.font_style.is_some() {
151            self.font_style = refinement.font_style;
152        }
153        if refinement.underline.is_some() {
154            self.underline = refinement.underline;
155        }
156    }
157
158    fn refined(self, refinement: Self::Refinement) -> Self {
159        todo!()
160    }
161}
162
163#[derive(JsonSchema)]
164#[serde(remote = "Properties")]
165pub struct PropertiesDef {
166    /// The font style, as defined in CSS.
167    pub style: StyleDef,
168    /// The font weight, as defined in CSS.
169    pub weight: f32,
170    /// The font stretchiness, as defined in CSS.
171    pub stretch: f32,
172}
173
174#[derive(JsonSchema)]
175#[schemars(remote = "Style")]
176pub enum StyleDef {
177    /// A face that is neither italic not obliqued.
178    Normal,
179    /// A form that is generally cursive in nature.
180    Italic,
181    /// A typically-sloped version of the regular face.
182    Oblique,
183}
184
185#[derive(Copy, Clone, Debug, Default, PartialEq, JsonSchema)]
186pub struct HighlightStyle {
187    pub color: Option<Color>,
188    #[schemars(with = "Option::<f32>")]
189    pub weight: Option<Weight>,
190    pub italic: Option<bool>,
191    pub underline: Option<Underline>,
192    pub fade_out: Option<f32>,
193}
194
195impl Eq for HighlightStyle {}
196
197#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, JsonSchema)]
198pub struct Underline {
199    pub color: Option<Color>,
200    #[schemars(with = "f32")]
201    pub thickness: OrderedFloat<f32>,
202    pub squiggly: bool,
203}
204
205#[allow(non_camel_case_types)]
206#[derive(Deserialize)]
207enum WeightJson {
208    thin,
209    extra_light,
210    light,
211    normal,
212    medium,
213    semibold,
214    bold,
215    extra_bold,
216    black,
217}
218
219thread_local! {
220    static FONT_CACHE: RefCell<Option<Arc<FontCache>>> = Default::default();
221}
222
223#[derive(Deserialize)]
224struct TextStyleJson {
225    color: Color,
226    family: String,
227    #[serde(default)]
228    features: Features,
229    weight: Option<WeightJson>,
230    size: f32,
231    #[serde(default)]
232    italic: bool,
233    #[serde(default)]
234    underline: UnderlineStyleJson,
235}
236
237#[derive(Deserialize)]
238struct HighlightStyleJson {
239    color: Option<Color>,
240    weight: Option<WeightJson>,
241    italic: Option<bool>,
242    underline: Option<UnderlineStyleJson>,
243    fade_out: Option<f32>,
244}
245
246#[derive(Deserialize)]
247#[serde(untagged)]
248enum UnderlineStyleJson {
249    Underlined(bool),
250    UnderlinedWithProperties {
251        #[serde(default)]
252        color: Option<Color>,
253        #[serde(default)]
254        thickness: Option<f32>,
255        #[serde(default)]
256        squiggly: bool,
257    },
258}
259
260impl TextStyle {
261    pub fn new(
262        font_family_name: impl Into<Arc<str>>,
263        font_size: f32,
264        font_properties: Properties,
265        font_features: Features,
266        underline: Underline,
267        color: Color,
268        font_cache: &FontCache,
269    ) -> Result<Self> {
270        let font_family_name = font_family_name.into();
271        let font_family_id = font_cache.load_family(&[&font_family_name], &font_features)?;
272        let font_id = font_cache.select_font(font_family_id, &font_properties)?;
273        Ok(Self {
274            color,
275            font_family_name,
276            font_family_id,
277            font_id,
278            font_size,
279            font_properties,
280            underline,
281            soft_wrap: false,
282        })
283    }
284
285    pub fn default(font_cache: &FontCache) -> Self {
286        let font_family_id = font_cache.known_existing_family();
287        let font_id = font_cache
288            .select_font(font_family_id, &Default::default())
289            .expect("did not have any font in system-provided family");
290        let font_family_name = font_cache
291            .family_name(font_family_id)
292            .expect("we loaded this family from the font cache, so this should work");
293
294        Self {
295            color: Color::default(),
296            font_family_name,
297            font_family_id,
298            font_id,
299            font_size: 14.,
300            font_properties: Default::default(),
301            underline: Default::default(),
302            soft_wrap: true,
303        }
304    }
305
306    pub fn with_font_size(mut self, font_size: f32) -> Self {
307        self.font_size = font_size;
308        self
309    }
310
311    pub fn highlight(mut self, style: HighlightStyle, font_cache: &FontCache) -> Result<Self> {
312        let mut font_properties = self.font_properties;
313        if let Some(weight) = style.weight {
314            font_properties.weight(weight);
315        }
316        if let Some(italic) = style.italic {
317            if italic {
318                font_properties.style(Style::Italic);
319            } else {
320                font_properties.style(Style::Normal);
321            }
322        }
323
324        if self.font_properties != font_properties {
325            self.font_id = font_cache.select_font(self.font_family_id, &font_properties)?;
326        }
327        if let Some(color) = style.color {
328            self.color = Color::blend(color, self.color);
329        }
330        if let Some(factor) = style.fade_out {
331            self.color.fade_out(factor);
332        }
333        if let Some(underline) = style.underline {
334            self.underline = underline;
335        }
336
337        Ok(self)
338    }
339
340    pub fn to_run(&self) -> RunStyle {
341        RunStyle {
342            font_id: self.font_id,
343            color: self.color,
344            underline: self.underline,
345        }
346    }
347
348    fn from_json(json: TextStyleJson) -> Result<Self> {
349        FONT_CACHE.with(|font_cache| {
350            if let Some(font_cache) = font_cache.borrow().as_ref() {
351                let font_properties = properties_from_json(json.weight, json.italic);
352                Self::new(
353                    json.family,
354                    json.size,
355                    font_properties,
356                    json.features,
357                    underline_from_json(json.underline),
358                    json.color,
359                    font_cache,
360                )
361            } else {
362                Err(anyhow!(
363                    "TextStyle can only be deserialized within a call to with_font_cache"
364                ))
365            }
366        })
367    }
368
369    pub fn line_height(&self, font_cache: &FontCache) -> f32 {
370        font_cache.line_height(self.font_size)
371    }
372
373    pub fn cap_height(&self, font_cache: &FontCache) -> f32 {
374        font_cache.cap_height(self.font_id, self.font_size)
375    }
376
377    pub fn x_height(&self, font_cache: &FontCache) -> f32 {
378        font_cache.x_height(self.font_id, self.font_size)
379    }
380
381    pub fn em_width(&self, font_cache: &FontCache) -> f32 {
382        font_cache.em_width(self.font_id, self.font_size)
383    }
384
385    pub fn em_advance(&self, font_cache: &FontCache) -> f32 {
386        font_cache.em_advance(self.font_id, self.font_size)
387    }
388
389    pub fn descent(&self, font_cache: &FontCache) -> f32 {
390        font_cache.metric(self.font_id, |m| m.descent) * self.em_scale(font_cache)
391    }
392
393    pub fn baseline_offset(&self, font_cache: &FontCache) -> f32 {
394        font_cache.baseline_offset(self.font_id, self.font_size)
395    }
396
397    fn em_scale(&self, font_cache: &FontCache) -> f32 {
398        font_cache.em_scale(self.font_id, self.font_size)
399    }
400}
401
402impl From<TextStyle> for HighlightStyle {
403    fn from(other: TextStyle) -> Self {
404        Self::from(&other)
405    }
406}
407
408impl From<&TextStyle> for HighlightStyle {
409    fn from(other: &TextStyle) -> Self {
410        Self {
411            color: Some(other.color),
412            weight: Some(other.font_properties.weight),
413            italic: Some(other.font_properties.style == Style::Italic),
414            underline: Some(other.underline),
415            fade_out: None,
416        }
417    }
418}
419
420impl Default for UnderlineStyleJson {
421    fn default() -> Self {
422        Self::Underlined(false)
423    }
424}
425
426impl Default for TextStyle {
427    fn default() -> Self {
428        FONT_CACHE.with(|font_cache| {
429            let font_cache = font_cache.borrow();
430            let font_cache = font_cache
431                .as_ref()
432                .expect("TextStyle::default can only be called within a call to with_font_cache");
433            Self::default(font_cache)
434        })
435    }
436}
437
438impl HighlightStyle {
439    fn from_json(json: HighlightStyleJson) -> Self {
440        Self {
441            color: json.color,
442            weight: json.weight.map(weight_from_json),
443            italic: json.italic,
444            underline: json.underline.map(underline_from_json),
445            fade_out: json.fade_out,
446        }
447    }
448
449    pub fn highlight(&mut self, other: HighlightStyle) {
450        match (self.color, other.color) {
451            (Some(self_color), Some(other_color)) => {
452                self.color = Some(Color::blend(other_color, self_color));
453            }
454            (None, Some(other_color)) => {
455                self.color = Some(other_color);
456            }
457            _ => {}
458        }
459
460        if other.weight.is_some() {
461            self.weight = other.weight;
462        }
463
464        if other.italic.is_some() {
465            self.italic = other.italic;
466        }
467
468        if other.underline.is_some() {
469            self.underline = other.underline;
470        }
471
472        match (other.fade_out, self.fade_out) {
473            (Some(source_fade), None) => self.fade_out = Some(source_fade),
474            (Some(source_fade), Some(dest_fade)) => {
475                let source_alpha = 1. - source_fade;
476                let dest_alpha = 1. - dest_fade;
477                let blended_alpha = source_alpha + (dest_alpha * source_fade);
478                let blended_fade = 1. - blended_alpha;
479                self.fade_out = Some(blended_fade);
480            }
481            _ => {}
482        }
483    }
484}
485
486impl From<Color> for HighlightStyle {
487    fn from(color: Color) -> Self {
488        Self {
489            color: Some(color),
490            ..Default::default()
491        }
492    }
493}
494
495impl<'de> Deserialize<'de> for TextStyle {
496    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
497    where
498        D: serde::Deserializer<'de>,
499    {
500        Self::from_json(TextStyleJson::deserialize(deserializer)?).map_err(de::Error::custom)
501    }
502}
503
504impl ToJson for TextStyle {
505    fn to_json(&self) -> Value {
506        json!({
507            "color": self.color.to_json(),
508            "font_family": self.font_family_name.as_ref(),
509            "font_properties": self.font_properties.to_json(),
510        })
511    }
512}
513
514impl<'de> Deserialize<'de> for HighlightStyle {
515    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
516    where
517        D: serde::Deserializer<'de>,
518    {
519        let json = serde_json::Value::deserialize(deserializer)?;
520        if json.is_object() {
521            Ok(Self::from_json(
522                serde_json::from_value(json).map_err(de::Error::custom)?,
523            ))
524        } else {
525            Ok(Self {
526                color: serde_json::from_value(json).map_err(de::Error::custom)?,
527                ..Default::default()
528            })
529        }
530    }
531}
532
533fn underline_from_json(json: UnderlineStyleJson) -> Underline {
534    match json {
535        UnderlineStyleJson::Underlined(false) => Underline::default(),
536        UnderlineStyleJson::Underlined(true) => Underline {
537            color: None,
538            thickness: 1.0.into(),
539            squiggly: false,
540        },
541        UnderlineStyleJson::UnderlinedWithProperties {
542            color,
543            thickness,
544            squiggly,
545        } => Underline {
546            color,
547            thickness: thickness.unwrap_or(1.).into(),
548            squiggly,
549        },
550    }
551}
552
553fn properties_from_json(weight: Option<WeightJson>, italic: bool) -> Properties {
554    let weight = weight.map(weight_from_json).unwrap_or_default();
555    let style = if italic { Style::Italic } else { Style::Normal };
556    *Properties::new().weight(weight).style(style)
557}
558
559fn weight_from_json(weight: WeightJson) -> Weight {
560    match weight {
561        WeightJson::thin => Weight::THIN,
562        WeightJson::extra_light => Weight::EXTRA_LIGHT,
563        WeightJson::light => Weight::LIGHT,
564        WeightJson::normal => Weight::NORMAL,
565        WeightJson::medium => Weight::MEDIUM,
566        WeightJson::semibold => Weight::SEMIBOLD,
567        WeightJson::bold => Weight::BOLD,
568        WeightJson::extra_bold => Weight::EXTRA_BOLD,
569        WeightJson::black => Weight::BLACK,
570    }
571}
572
573impl ToJson for Properties {
574    fn to_json(&self) -> crate::json::Value {
575        json!({
576            "style": self.style.to_json(),
577            "weight": self.weight.to_json(),
578            "stretch": self.stretch.to_json(),
579        })
580    }
581}
582
583impl ToJson for Style {
584    fn to_json(&self) -> crate::json::Value {
585        match self {
586            Style::Normal => json!("normal"),
587            Style::Italic => json!("italic"),
588            Style::Oblique => json!("oblique"),
589        }
590    }
591}
592
593impl ToJson for Weight {
594    fn to_json(&self) -> crate::json::Value {
595        if self.0 == Weight::THIN.0 {
596            json!("thin")
597        } else if self.0 == Weight::EXTRA_LIGHT.0 {
598            json!("extra light")
599        } else if self.0 == Weight::LIGHT.0 {
600            json!("light")
601        } else if self.0 == Weight::NORMAL.0 {
602            json!("normal")
603        } else if self.0 == Weight::MEDIUM.0 {
604            json!("medium")
605        } else if self.0 == Weight::SEMIBOLD.0 {
606            json!("semibold")
607        } else if self.0 == Weight::BOLD.0 {
608            json!("bold")
609        } else if self.0 == Weight::EXTRA_BOLD.0 {
610            json!("extra bold")
611        } else if self.0 == Weight::BLACK.0 {
612            json!("black")
613        } else {
614            json!(self.0)
615        }
616    }
617}
618
619impl ToJson for Stretch {
620    fn to_json(&self) -> serde_json::Value {
621        json!(self.0)
622    }
623}
624
625pub fn with_font_cache<F, T>(font_cache: Arc<FontCache>, callback: F) -> T
626where
627    F: FnOnce() -> T,
628{
629    FONT_CACHE.with(|cache| {
630        *cache.borrow_mut() = Some(font_cache);
631        let result = callback();
632        cache.borrow_mut().take();
633        result
634    })
635}