text_system.rs

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