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