text_system.rs

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