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