1use std::sync::{Arc, OnceLock};
4
5use skrifa::{Font, GlyphId, HintOptions, ScalerFont};
6
7use crate::text::glyph::{FontData, Glyph, GlyphID};
8
9pub(crate) const SDF_FONT_SIZE: i32 = 24;
11
12#[derive(Clone)]
13pub(crate) struct Face {
14 font: Option<Font>,
18 scaler: Arc<OnceLock<ScalerFont>>,
20}
21
22impl Face {
23 pub(crate) fn new(font_data: impl Into<FontData>, weight: f32) -> Self {
33 let font = crate::text::woff::to_sfnt(font_data.into())
34 .ok()
35 .and_then(|data| Font::new(data.shared(), data.face_index()))
36 .filter(|font| font.charmap().has_unicode())
37 .map(|font| crate::text::weight::at_weight(font, weight));
38 Face { font, scaler: Arc::default() }
39 }
40
41 #[must_use]
42 pub(crate) fn is_valid(&self) -> bool {
43 self.font.is_some()
44 }
45
46 #[must_use]
48 pub(crate) fn font(&self) -> Option<&Font> {
49 self.font.as_ref()
50 }
51
52 pub(crate) fn scaler(&self) -> Option<&ScalerFont> {
55 let font = self.font.as_ref()?;
56 Some(
57 self.scaler
58 .get_or_init(|| ScalerFont::hinted(font.clone(), SDF_FONT_SIZE as f32, HintOptions::auto_fallback())),
59 )
60 }
61
62 pub(crate) fn glyph_of(&self, c: char) -> Option<u16> {
66 let glyph = self.font()?.charmap().map_unicode(c)?;
67 let index = u16::try_from(glyph.to_u32()).ok().filter(|&index| index != 0)?;
68 self.scaler()?.outline(GlyphId::new(u32::from(index)))?;
69 Some(index)
70 }
71
72 #[must_use]
73 pub(crate) fn rasterize_glyph(&self, glyph: GlyphID) -> Glyph {
74 crate::text::rasterize::rasterize_glyph(self, glyph)
75 }
76}
77
78#[cfg(all(feature = "system-fonts", not(target_family = "wasm")))]
80#[derive(Clone)]
81pub(crate) struct FontFile {
82 face: Face,
83}
84
85#[cfg(all(feature = "system-fonts", not(target_family = "wasm")))]
86impl FontFile {
87 #[must_use]
90 pub(crate) fn new(data: FontData) -> Option<Self> {
91 let face = Face::new(data, crate::text::weight::REGULAR_WEIGHT);
93 face.is_valid().then_some(FontFile { face })
94 }
95
96 #[must_use]
100 pub(crate) fn has_char(&self, c: char) -> bool {
101 self.face.glyph_of(c).is_some()
102 }
103}
104
105#[cfg(all(feature = "system-fonts", not(target_family = "wasm")))]
106impl std::fmt::Debug for FontFile {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.debug_struct("FontFile").finish_non_exhaustive()
109 }
110}