font_cache.rs

  1use crate::{
  2    fonts::{FontId, Metrics, Properties},
  3    geometry::vector::{vec2f, Vector2F},
  4    platform,
  5    text_layout::LineWrapper,
  6};
  7use anyhow::{anyhow, Result};
  8use ordered_float::OrderedFloat;
  9use parking_lot::{RwLock, RwLockUpgradableReadGuard};
 10use std::{
 11    collections::HashMap,
 12    ops::{Deref, DerefMut},
 13    sync::Arc,
 14};
 15
 16#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
 17pub struct FamilyId(usize);
 18
 19struct Family {
 20    name: Arc<str>,
 21    font_ids: Vec<FontId>,
 22}
 23
 24pub struct FontCache(RwLock<FontCacheState>);
 25
 26pub struct FontCacheState {
 27    fonts: Arc<dyn platform::FontSystem>,
 28    families: Vec<Family>,
 29    font_selections: HashMap<FamilyId, HashMap<Properties, FontId>>,
 30    metrics: HashMap<FontId, Metrics>,
 31    wrapper_pool: HashMap<(FontId, OrderedFloat<f32>), Vec<LineWrapper>>,
 32}
 33
 34pub struct LineWrapperHandle {
 35    wrapper: Option<LineWrapper>,
 36    font_cache: Arc<FontCache>,
 37}
 38
 39unsafe impl Send for FontCache {}
 40
 41impl FontCache {
 42    pub fn new(fonts: Arc<dyn platform::FontSystem>) -> Self {
 43        Self(RwLock::new(FontCacheState {
 44            fonts,
 45            families: Default::default(),
 46            font_selections: Default::default(),
 47            metrics: Default::default(),
 48            wrapper_pool: Default::default(),
 49        }))
 50    }
 51
 52    pub fn family_name(&self, family_id: FamilyId) -> Result<Arc<str>> {
 53        self.0
 54            .read()
 55            .families
 56            .get(family_id.0)
 57            .ok_or_else(|| anyhow!("invalid family id"))
 58            .map(|family| family.name.clone())
 59    }
 60
 61    pub fn load_family(&self, names: &[&str]) -> Result<FamilyId> {
 62        for name in names {
 63            let state = self.0.upgradable_read();
 64
 65            if let Some(ix) = state.families.iter().position(|f| f.name.as_ref() == *name) {
 66                return Ok(FamilyId(ix));
 67            }
 68
 69            let mut state = RwLockUpgradableReadGuard::upgrade(state);
 70
 71            if let Ok(font_ids) = state.fonts.load_family(name) {
 72                if font_ids.is_empty() {
 73                    continue;
 74                }
 75
 76                let family_id = FamilyId(state.families.len());
 77                for font_id in &font_ids {
 78                    if state.fonts.glyph_for_char(*font_id, 'm').is_none() {
 79                        return Err(anyhow!("font must contain a glyph for the 'm' character"));
 80                    }
 81                }
 82
 83                state.families.push(Family {
 84                    name: Arc::from(*name),
 85                    font_ids,
 86                });
 87                return Ok(family_id);
 88            }
 89        }
 90
 91        Err(anyhow!(
 92            "could not find a non-empty font family matching one of the given names"
 93        ))
 94    }
 95
 96    pub fn default_font(&self, family_id: FamilyId) -> FontId {
 97        self.select_font(family_id, &Properties::default()).unwrap()
 98    }
 99
100    pub fn select_font(&self, family_id: FamilyId, properties: &Properties) -> Result<FontId> {
101        let inner = self.0.upgradable_read();
102        if let Some(font_id) = inner
103            .font_selections
104            .get(&family_id)
105            .and_then(|f| f.get(properties))
106        {
107            Ok(*font_id)
108        } else {
109            let mut inner = RwLockUpgradableReadGuard::upgrade(inner);
110            let family = &inner.families[family_id.0];
111            let font_id = inner
112                .fonts
113                .select_font(&family.font_ids, properties)
114                .unwrap_or(family.font_ids[0]);
115
116            inner
117                .font_selections
118                .entry(family_id)
119                .or_default()
120                .insert(properties.clone(), font_id);
121            Ok(font_id)
122        }
123    }
124
125    pub fn metric<F, T>(&self, font_id: FontId, f: F) -> T
126    where
127        F: FnOnce(&Metrics) -> T,
128        T: 'static,
129    {
130        let state = self.0.upgradable_read();
131        if let Some(metrics) = state.metrics.get(&font_id) {
132            f(metrics)
133        } else {
134            let metrics = state.fonts.font_metrics(font_id);
135            let metric = f(&metrics);
136            let mut state = RwLockUpgradableReadGuard::upgrade(state);
137            state.metrics.insert(font_id, metrics);
138            metric
139        }
140    }
141
142    pub fn bounding_box(&self, font_id: FontId, font_size: f32) -> Vector2F {
143        let bounding_box = self.metric(font_id, |m| m.bounding_box);
144        let width = bounding_box.width() * self.em_scale(font_id, font_size);
145        let height = bounding_box.height() * self.em_scale(font_id, font_size);
146        vec2f(width, height)
147    }
148
149    pub fn em_width(&self, font_id: FontId, font_size: f32) -> f32 {
150        let glyph_id;
151        let bounds;
152        {
153            let state = self.0.read();
154            glyph_id = state.fonts.glyph_for_char(font_id, 'm').unwrap();
155            bounds = state.fonts.typographic_bounds(font_id, glyph_id).unwrap();
156        }
157        bounds.width() * self.em_scale(font_id, font_size)
158    }
159
160    pub fn line_height(&self, font_id: FontId, font_size: f32) -> f32 {
161        let height = self.metric(font_id, |m| m.bounding_box.height());
162        (height * self.em_scale(font_id, font_size)).ceil()
163    }
164
165    pub fn cap_height(&self, font_id: FontId, font_size: f32) -> f32 {
166        self.metric(font_id, |m| m.cap_height) * self.em_scale(font_id, font_size)
167    }
168
169    pub fn x_height(&self, font_id: FontId, font_size: f32) -> f32 {
170        self.metric(font_id, |m| m.x_height) * self.em_scale(font_id, font_size)
171    }
172
173    pub fn ascent(&self, font_id: FontId, font_size: f32) -> f32 {
174        self.metric(font_id, |m| m.ascent) * self.em_scale(font_id, font_size)
175    }
176
177    pub fn descent(&self, font_id: FontId, font_size: f32) -> f32 {
178        self.metric(font_id, |m| -m.descent) * self.em_scale(font_id, font_size)
179    }
180
181    pub fn em_scale(&self, font_id: FontId, font_size: f32) -> f32 {
182        font_size / self.metric(font_id, |m| m.units_per_em as f32)
183    }
184
185    pub fn baseline_offset(&self, font_id: FontId, font_size: f32) -> f32 {
186        let line_height = self.line_height(font_id, font_size);
187        let ascent = self.ascent(font_id, font_size);
188        let descent = self.descent(font_id, font_size);
189        let padding_top = (line_height - ascent - descent) / 2.;
190        padding_top + ascent
191    }
192
193    pub fn line_wrapper(self: &Arc<Self>, font_id: FontId, font_size: f32) -> LineWrapperHandle {
194        let mut state = self.0.write();
195        let wrappers = state
196            .wrapper_pool
197            .entry((font_id, OrderedFloat(font_size)))
198            .or_default();
199        let wrapper = wrappers
200            .pop()
201            .unwrap_or_else(|| LineWrapper::new(font_id, font_size, state.fonts.clone()));
202        LineWrapperHandle {
203            wrapper: Some(wrapper),
204            font_cache: self.clone(),
205        }
206    }
207}
208
209impl Drop for LineWrapperHandle {
210    fn drop(&mut self) {
211        let mut state = self.font_cache.0.write();
212        let wrapper = self.wrapper.take().unwrap();
213        state
214            .wrapper_pool
215            .get_mut(&(wrapper.font_id, OrderedFloat(wrapper.font_size)))
216            .unwrap()
217            .push(wrapper);
218    }
219}
220
221impl Deref for LineWrapperHandle {
222    type Target = LineWrapper;
223
224    fn deref(&self) -> &Self::Target {
225        self.wrapper.as_ref().unwrap()
226    }
227}
228
229impl DerefMut for LineWrapperHandle {
230    fn deref_mut(&mut self) -> &mut Self::Target {
231        self.wrapper.as_mut().unwrap()
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use crate::{
239        fonts::{Style, Weight},
240        platform::{test, Platform as _},
241    };
242
243    #[test]
244    fn test_select_font() {
245        let platform = test::platform();
246        let fonts = FontCache::new(platform.fonts());
247        let arial = fonts.load_family(&["Arial"]).unwrap();
248        let arial_regular = fonts.select_font(arial, &Properties::new()).unwrap();
249        let arial_italic = fonts
250            .select_font(arial, &Properties::new().style(Style::Italic))
251            .unwrap();
252        let arial_bold = fonts
253            .select_font(arial, &Properties::new().weight(Weight::BOLD))
254            .unwrap();
255        assert_ne!(arial_regular, arial_italic);
256        assert_ne!(arial_regular, arial_bold);
257        assert_ne!(arial_italic, arial_bold);
258    }
259}