text_system.rs

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