text_system.rs

  1mod font_features;
  2mod line_wrapper;
  3mod text_layout_cache;
  4
  5use anyhow::anyhow;
  6pub use font_features::*;
  7use line_wrapper::*;
  8pub use text_layout_cache::*;
  9
 10use crate::{
 11    px, Bounds, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size, UnderlineStyle,
 12};
 13use collections::HashMap;
 14use core::fmt;
 15use parking_lot::{Mutex, RwLock};
 16use std::{
 17    fmt::{Debug, Display, Formatter},
 18    hash::{Hash, Hasher},
 19    ops::{Deref, DerefMut},
 20    sync::Arc,
 21};
 22
 23#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 24pub struct FontId(pub usize);
 25
 26#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 27pub struct FontFamilyId(pub usize);
 28
 29pub struct TextSystem {
 30    text_layout_cache: Arc<TextLayoutCache>,
 31    platform_text_system: Arc<dyn PlatformTextSystem>,
 32    font_ids_by_font: RwLock<HashMap<Font, FontId>>,
 33    fonts_by_font_id: RwLock<HashMap<FontId, Font>>,
 34    font_metrics: RwLock<HashMap<Font, FontMetrics>>,
 35    wrapper_pool: Mutex<HashMap<FontIdWithSize, Vec<LineWrapper>>>,
 36    font_runs_pool: Mutex<Vec<Vec<(usize, FontId)>>>,
 37}
 38
 39impl TextSystem {
 40    pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
 41        TextSystem {
 42            text_layout_cache: Arc::new(TextLayoutCache::new(platform_text_system.clone())),
 43            platform_text_system,
 44            font_metrics: RwLock::new(HashMap::default()),
 45            font_ids_by_font: RwLock::new(HashMap::default()),
 46            fonts_by_font_id: RwLock::new(HashMap::default()),
 47            wrapper_pool: Mutex::new(HashMap::default()),
 48            font_runs_pool: Default::default(),
 49        }
 50    }
 51
 52    pub fn font_id(&self, font: &Font) -> Result<FontId> {
 53        if let Some(font_id) = self.font_ids_by_font.read().get(font) {
 54            Ok(*font_id)
 55        } else {
 56            let font_id = self.platform_text_system.font_id(font)?;
 57            self.font_ids_by_font.write().insert(font.clone(), font_id);
 58            self.fonts_by_font_id.write().insert(font_id, font.clone());
 59
 60            Ok(font_id)
 61        }
 62    }
 63
 64    pub fn with_font<T>(&self, font_id: FontId, f: impl FnOnce(&Self, &Font) -> T) -> Result<T> {
 65        self.fonts_by_font_id
 66            .read()
 67            .get(&font_id)
 68            .ok_or_else(|| anyhow!("font not found"))
 69            .map(|font| f(self, font))
 70    }
 71
 72    pub fn bounding_box(&self, font: &Font, font_size: Pixels) -> Result<Bounds<Pixels>> {
 73        self.read_metrics(&font, |metrics| metrics.bounding_box(font_size))
 74    }
 75
 76    pub fn typographic_bounds(
 77        &self,
 78        font: &Font,
 79        font_size: Pixels,
 80        character: char,
 81    ) -> Result<Bounds<Pixels>> {
 82        let font_id = self.font_id(font)?;
 83        let glyph_id = self
 84            .platform_text_system
 85            .glyph_for_char(font_id, character)
 86            .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
 87        let bounds = self
 88            .platform_text_system
 89            .typographic_bounds(font_id, glyph_id)?;
 90        self.read_metrics(font, |metrics| {
 91            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
 92        })
 93    }
 94
 95    pub fn advance(&self, font: &Font, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
 96        let font_id = self.font_id(font)?;
 97        let glyph_id = self
 98            .platform_text_system
 99            .glyph_for_char(font_id, ch)
100            .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
101        let result =
102            self.platform_text_system.advance(font_id, glyph_id)? / self.units_per_em(font)? as f32;
103
104        Ok(result * font_size)
105    }
106
107    pub fn units_per_em(&self, font: &Font) -> Result<u32> {
108        self.read_metrics(font, |metrics| metrics.units_per_em as u32)
109    }
110
111    pub fn cap_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
112        self.read_metrics(font, |metrics| metrics.cap_height(font_size))
113    }
114
115    pub fn x_height(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
116        self.read_metrics(font, |metrics| metrics.x_height(font_size))
117    }
118
119    pub fn ascent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
120        self.read_metrics(font, |metrics| metrics.ascent(font_size))
121    }
122
123    pub fn descent(&self, font: &Font, font_size: Pixels) -> Result<Pixels> {
124        self.read_metrics(font, |metrics| metrics.descent(font_size))
125    }
126
127    pub fn baseline_offset(
128        &self,
129        font: &Font,
130        font_size: Pixels,
131        line_height: Pixels,
132    ) -> Result<Pixels> {
133        let ascent = self.ascent(font, font_size)?;
134        let descent = self.descent(font, font_size)?;
135        let padding_top = (line_height - ascent - descent) / 2.;
136        Ok(padding_top + ascent)
137    }
138
139    fn read_metrics<T>(&self, font: &Font, read: impl FnOnce(&FontMetrics) -> T) -> Result<T> {
140        if let Some(metrics) = self.font_metrics.read().get(font) {
141            Ok(read(metrics))
142        } else {
143            let font_id = self.platform_text_system.font_id(&font)?;
144            let mut lock = self.font_metrics.write();
145            let metrics = lock
146                .entry(font.clone())
147                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
148            Ok(read(metrics))
149        }
150    }
151
152    pub fn layout_line(
153        &self,
154        text: &str,
155        font_size: Pixels,
156        runs: &[(usize, RunStyle)],
157    ) -> Result<Line> {
158        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
159        let mut last_font: Option<&Font> = None;
160        for (len, style) in runs {
161            if let Some(last_font) = last_font.as_ref() {
162                if **last_font == style.font {
163                    font_runs.last_mut().unwrap().0 += len;
164                    continue;
165                }
166            }
167            last_font = Some(&style.font);
168            font_runs.push((*len, self.font_id(&style.font)?));
169        }
170
171        let layout = self
172            .text_layout_cache
173            .layout_line(text, font_size, &font_runs);
174
175        font_runs.clear();
176        self.font_runs_pool.lock().push(font_runs);
177
178        Ok(Line::new(layout.clone(), runs))
179    }
180
181    pub fn finish_frame(&self) {
182        self.text_layout_cache.finish_frame()
183    }
184
185    pub fn line_wrapper(
186        self: &Arc<Self>,
187        font: Font,
188        font_size: Pixels,
189    ) -> Result<LineWrapperHandle> {
190        let lock = &mut self.wrapper_pool.lock();
191        let font_id = self.font_id(&font)?;
192        let wrappers = lock
193            .entry(FontIdWithSize { font_id, font_size })
194            .or_default();
195        let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
196            Ok(LineWrapper::new(
197                font_id,
198                font_size,
199                self.platform_text_system.clone(),
200            ))
201        })?;
202
203        Ok(LineWrapperHandle {
204            wrapper: Some(wrapper),
205            text_system: self.clone(),
206        })
207    }
208}
209
210#[derive(Hash, Eq, PartialEq)]
211struct FontIdWithSize {
212    font_id: FontId,
213    font_size: Pixels,
214}
215
216pub struct LineWrapperHandle {
217    wrapper: Option<LineWrapper>,
218    text_system: Arc<TextSystem>,
219}
220
221impl Drop for LineWrapperHandle {
222    fn drop(&mut self) {
223        let mut state = self.text_system.wrapper_pool.lock();
224        let wrapper = self.wrapper.take().unwrap();
225        state
226            .get_mut(&FontIdWithSize {
227                font_id: wrapper.font_id.clone(),
228                font_size: wrapper.font_size,
229            })
230            .unwrap()
231            .push(wrapper);
232    }
233}
234
235impl Deref for LineWrapperHandle {
236    type Target = LineWrapper;
237
238    fn deref(&self) -> &Self::Target {
239        self.wrapper.as_ref().unwrap()
240    }
241}
242
243impl DerefMut for LineWrapperHandle {
244    fn deref_mut(&mut self) -> &mut Self::Target {
245        self.wrapper.as_mut().unwrap()
246    }
247}
248
249/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
250/// with 400.0 as normal.
251#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
252pub struct FontWeight(pub f32);
253
254impl Default for FontWeight {
255    #[inline]
256    fn default() -> FontWeight {
257        FontWeight::NORMAL
258    }
259}
260
261impl Hash for FontWeight {
262    fn hash<H: Hasher>(&self, state: &mut H) {
263        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
264    }
265}
266
267impl Eq for FontWeight {}
268
269impl FontWeight {
270    /// Thin weight (100), the thinnest value.
271    pub const THIN: FontWeight = FontWeight(100.0);
272    /// Extra light weight (200).
273    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
274    /// Light weight (300).
275    pub const LIGHT: FontWeight = FontWeight(300.0);
276    /// Normal (400).
277    pub const NORMAL: FontWeight = FontWeight(400.0);
278    /// Medium weight (500, higher than normal).
279    pub const MEDIUM: FontWeight = FontWeight(500.0);
280    /// Semibold weight (600).
281    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
282    /// Bold weight (700).
283    pub const BOLD: FontWeight = FontWeight(700.0);
284    /// Extra-bold weight (800).
285    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
286    /// Black weight (900), the thickest value.
287    pub const BLACK: FontWeight = FontWeight(900.0);
288}
289
290/// Allows italic or oblique faces to be selected.
291#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
292pub enum FontStyle {
293    /// A face that is neither italic not obliqued.
294    Normal,
295    /// A form that is generally cursive in nature.
296    Italic,
297    /// A typically-sloped version of the regular face.
298    Oblique,
299}
300
301impl Default for FontStyle {
302    fn default() -> FontStyle {
303        FontStyle::Normal
304    }
305}
306
307impl Display for FontStyle {
308    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
309        Debug::fmt(self, f)
310    }
311}
312
313#[derive(Clone, Debug, PartialEq, Eq)]
314pub struct RunStyle {
315    pub font: Font,
316    pub color: Hsla,
317    pub underline: Option<UnderlineStyle>,
318}
319
320#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
321pub struct GlyphId(u32);
322
323impl From<GlyphId> for u32 {
324    fn from(value: GlyphId) -> Self {
325        value.0
326    }
327}
328
329impl From<u16> for GlyphId {
330    fn from(num: u16) -> Self {
331        GlyphId(num as u32)
332    }
333}
334
335impl From<u32> for GlyphId {
336    fn from(num: u32) -> Self {
337        GlyphId(num)
338    }
339}
340
341#[derive(Clone, Debug)]
342pub struct Glyph {
343    pub id: GlyphId,
344    pub position: Point<Pixels>,
345    pub index: usize,
346    pub is_emoji: bool,
347}
348
349#[derive(Default, Debug)]
350pub struct LineLayout {
351    pub font_size: Pixels,
352    pub width: Pixels,
353    pub ascent: Pixels,
354    pub descent: Pixels,
355    pub runs: Vec<Run>,
356    pub len: usize,
357}
358
359#[derive(Debug)]
360pub struct Run {
361    pub font_id: FontId,
362    pub glyphs: Vec<Glyph>,
363}
364
365#[derive(Clone, Debug, Eq, PartialEq, Hash)]
366pub struct Font {
367    pub family: SharedString,
368    pub features: FontFeatures,
369    pub weight: FontWeight,
370    pub style: FontStyle,
371}
372
373pub fn font(family: impl Into<SharedString>) -> Font {
374    Font {
375        family: family.into(),
376        features: FontFeatures::default(),
377        weight: FontWeight::default(),
378        style: FontStyle::default(),
379    }
380}
381
382impl Font {
383    pub fn bold(mut self) -> Self {
384        self.weight = FontWeight::BOLD;
385        self
386    }
387}
388
389/// A struct for storing font metrics.
390/// It is used to define the measurements of a typeface.
391#[derive(Clone, Copy, Debug)]
392pub struct FontMetrics {
393    /// The number of font units that make up the "em square",
394    /// a scalable grid for determining the size of a typeface.
395    pub(crate) units_per_em: u32,
396
397    /// The vertical distance from the baseline of the font to the top of the glyph covers.
398    pub(crate) ascent: f32,
399
400    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
401    pub(crate) descent: f32,
402
403    /// The recommended additional space to add between lines of type.
404    pub(crate) line_gap: f32,
405
406    /// The suggested position of the underline.
407    pub(crate) underline_position: f32,
408
409    /// The suggested thickness of the underline.
410    pub(crate) underline_thickness: f32,
411
412    /// The height of a capital letter measured from the baseline of the font.
413    pub(crate) cap_height: f32,
414
415    /// The height of a lowercase x.
416    pub(crate) x_height: f32,
417
418    /// The outer limits of the area that the font covers.
419    pub(crate) bounding_box: Bounds<f32>,
420}
421
422impl FontMetrics {
423    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
424    pub fn ascent(&self, font_size: Pixels) -> Pixels {
425        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
426    }
427
428    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
429    pub fn descent(&self, font_size: Pixels) -> Pixels {
430        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
431    }
432
433    /// Returns the recommended additional space to add between lines of type in pixels.
434    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
435        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
436    }
437
438    /// Returns the suggested position of the underline in pixels.
439    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
440        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
441    }
442
443    /// Returns the suggested thickness of the underline in pixels.
444    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
445        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
446    }
447
448    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
449    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
450        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
451    }
452
453    /// Returns the height of a lowercase x in pixels.
454    pub fn x_height(&self, font_size: Pixels) -> Pixels {
455        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
456    }
457
458    /// Returns the outer limits of the area that the font covers in pixels.
459    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
460        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
461    }
462}