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