text_system.rs

  1mod font_features;
  2mod line;
  3mod line_layout;
  4mod line_wrapper;
  5
  6pub use font_features::*;
  7pub use line::*;
  8pub use line_layout::*;
  9pub use line_wrapper::*;
 10
 11use crate::{
 12    px, Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
 13    UnderlineStyle,
 14};
 15use anyhow::anyhow;
 16use collections::FxHashMap;
 17use core::fmt;
 18use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
 19use smallvec::SmallVec;
 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<FxHashMap<Font, FontId>>,
 41    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
 42    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
 43    wrapper_pool: Mutex<FxHashMap<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) -> 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        Ok(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) -> u32 {
109        self.read_metrics(font_id, |metrics| metrics.units_per_em)
110    }
111
112    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> 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) -> 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) -> 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) -> 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    ) -> 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        padding_top + ascent
138    }
139
140    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
141        let lock = self.font_metrics.upgradable_read();
142
143        if let Some(metrics) = lock.get(&font_id) {
144            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            read(metrics)
151        }
152    }
153
154    pub fn layout_line(
155        &self,
156        text: &str,
157        font_size: Pixels,
158        runs: &[TextRun],
159    ) -> Result<Arc<LineLayout>> {
160        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
161        for run in runs.iter() {
162            let font_id = self.font_id(&run.font)?;
163            if let Some(last_run) = font_runs.last_mut() {
164                if last_run.font_id == font_id {
165                    last_run.len += run.len;
166                    continue;
167                }
168            }
169            font_runs.push(FontRun {
170                len: run.len,
171                font_id,
172            });
173        }
174
175        let layout = self
176            .line_layout_cache
177            .layout_line(text, font_size, &font_runs);
178
179        font_runs.clear();
180        self.font_runs_pool.lock().push(font_runs);
181
182        Ok(layout)
183    }
184
185    pub fn shape_line(
186        &self,
187        text: SharedString,
188        font_size: Pixels,
189        runs: &[TextRun],
190    ) -> Result<ShapedLine> {
191        debug_assert!(
192            text.find('\n').is_none(),
193            "text argument should not contain newlines"
194        );
195
196        let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
197        for run in runs {
198            if let Some(last_run) = decoration_runs.last_mut() {
199                if last_run.color == run.color
200                    && last_run.underline == run.underline
201                    && last_run.background_color == run.background_color
202                {
203                    last_run.len += run.len as u32;
204                    continue;
205                }
206            }
207            decoration_runs.push(DecorationRun {
208                len: run.len as u32,
209                color: run.color,
210                background_color: run.background_color,
211                underline: run.underline,
212            });
213        }
214
215        let layout = self.layout_line(text.as_ref(), font_size, runs)?;
216
217        Ok(ShapedLine {
218            layout,
219            text,
220            decoration_runs,
221        })
222    }
223
224    pub fn shape_text(
225        &self,
226        text: &str, // todo!("pass a SharedString and preserve it when passed a single line?")
227        font_size: Pixels,
228        runs: &[TextRun],
229        wrap_width: Option<Pixels>,
230    ) -> Result<SmallVec<[WrappedLine; 1]>> {
231        let mut runs = runs.iter().cloned().peekable();
232        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
233
234        let mut lines = SmallVec::new();
235        let mut line_start = 0;
236        for line_text in text.split('\n') {
237            let line_text = SharedString::from(line_text.to_string());
238            let line_end = line_start + line_text.len();
239
240            let mut last_font: Option<Font> = None;
241            let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
242            let mut run_start = line_start;
243            while run_start < line_end {
244                let Some(run) = runs.peek_mut() else {
245                    break;
246                };
247
248                let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
249
250                if last_font == Some(run.font.clone()) {
251                    font_runs.last_mut().unwrap().len += run_len_within_line;
252                } else {
253                    last_font = Some(run.font.clone());
254                    font_runs.push(FontRun {
255                        len: run_len_within_line,
256                        font_id: self.platform_text_system.font_id(&run.font)?,
257                    });
258                }
259
260                if decoration_runs.last().map_or(false, |last_run| {
261                    last_run.color == run.color
262                        && last_run.underline == run.underline
263                        && last_run.background_color == run.background_color
264                }) {
265                    decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
266                } else {
267                    decoration_runs.push(DecorationRun {
268                        len: run_len_within_line as u32,
269                        color: run.color,
270                        background_color: run.background_color,
271                        underline: run.underline,
272                    });
273                }
274
275                if run_len_within_line == run.len {
276                    runs.next();
277                } else {
278                    // Preserve the remainder of the run for the next line
279                    run.len -= run_len_within_line;
280                }
281                run_start += run_len_within_line;
282            }
283
284            let layout = self
285                .line_layout_cache
286                .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
287            lines.push(WrappedLine {
288                layout,
289                decoration_runs,
290                text: line_text,
291            });
292
293            // Skip `\n` character.
294            line_start = line_end + 1;
295            if let Some(run) = runs.peek_mut() {
296                run.len = run.len.saturating_sub(1);
297                if run.len == 0 {
298                    runs.next();
299                }
300            }
301
302            font_runs.clear();
303        }
304
305        self.font_runs_pool.lock().push(font_runs);
306
307        Ok(lines)
308    }
309
310    pub fn start_frame(&self) {
311        self.line_layout_cache.start_frame()
312    }
313
314    pub fn line_wrapper(
315        self: &Arc<Self>,
316        font: Font,
317        font_size: Pixels,
318    ) -> Result<LineWrapperHandle> {
319        let lock = &mut self.wrapper_pool.lock();
320        let font_id = self.font_id(&font)?;
321        let wrappers = lock
322            .entry(FontIdWithSize { font_id, font_size })
323            .or_default();
324        let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
325            Ok(LineWrapper::new(
326                font_id,
327                font_size,
328                self.platform_text_system.clone(),
329            ))
330        })?;
331
332        Ok(LineWrapperHandle {
333            wrapper: Some(wrapper),
334            text_system: self.clone(),
335        })
336    }
337
338    pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
339        let raster_bounds = self.raster_bounds.upgradable_read();
340        if let Some(bounds) = raster_bounds.get(params) {
341            Ok(*bounds)
342        } else {
343            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
344            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
345            raster_bounds.insert(params.clone(), bounds);
346            Ok(bounds)
347        }
348    }
349
350    pub fn rasterize_glyph(
351        &self,
352        params: &RenderGlyphParams,
353    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
354        let raster_bounds = self.raster_bounds(params)?;
355        self.platform_text_system
356            .rasterize_glyph(params, raster_bounds)
357    }
358}
359
360#[derive(Hash, Eq, PartialEq)]
361struct FontIdWithSize {
362    font_id: FontId,
363    font_size: Pixels,
364}
365
366pub struct LineWrapperHandle {
367    wrapper: Option<LineWrapper>,
368    text_system: Arc<TextSystem>,
369}
370
371impl Drop for LineWrapperHandle {
372    fn drop(&mut self) {
373        let mut state = self.text_system.wrapper_pool.lock();
374        let wrapper = self.wrapper.take().unwrap();
375        state
376            .get_mut(&FontIdWithSize {
377                font_id: wrapper.font_id,
378                font_size: wrapper.font_size,
379            })
380            .unwrap()
381            .push(wrapper);
382    }
383}
384
385impl Deref for LineWrapperHandle {
386    type Target = LineWrapper;
387
388    fn deref(&self) -> &Self::Target {
389        self.wrapper.as_ref().unwrap()
390    }
391}
392
393impl DerefMut for LineWrapperHandle {
394    fn deref_mut(&mut self) -> &mut Self::Target {
395        self.wrapper.as_mut().unwrap()
396    }
397}
398
399/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
400/// with 400.0 as normal.
401#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
402pub struct FontWeight(pub f32);
403
404impl Default for FontWeight {
405    #[inline]
406    fn default() -> FontWeight {
407        FontWeight::NORMAL
408    }
409}
410
411impl Hash for FontWeight {
412    fn hash<H: Hasher>(&self, state: &mut H) {
413        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
414    }
415}
416
417impl Eq for FontWeight {}
418
419impl FontWeight {
420    /// Thin weight (100), the thinnest value.
421    pub const THIN: FontWeight = FontWeight(100.0);
422    /// Extra light weight (200).
423    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
424    /// Light weight (300).
425    pub const LIGHT: FontWeight = FontWeight(300.0);
426    /// Normal (400).
427    pub const NORMAL: FontWeight = FontWeight(400.0);
428    /// Medium weight (500, higher than normal).
429    pub const MEDIUM: FontWeight = FontWeight(500.0);
430    /// Semibold weight (600).
431    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
432    /// Bold weight (700).
433    pub const BOLD: FontWeight = FontWeight(700.0);
434    /// Extra-bold weight (800).
435    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
436    /// Black weight (900), the thickest value.
437    pub const BLACK: FontWeight = FontWeight(900.0);
438}
439
440/// Allows italic or oblique faces to be selected.
441#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
442#[derive(Default)]
443pub enum FontStyle {
444    /// A face that is neither italic not obliqued.
445    #[default]
446    Normal,
447    /// A form that is generally cursive in nature.
448    Italic,
449    /// A typically-sloped version of the regular face.
450    Oblique,
451}
452
453
454
455impl Display for FontStyle {
456    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
457        Debug::fmt(self, f)
458    }
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
462pub struct TextRun {
463    // number of utf8 bytes
464    pub len: usize,
465    pub font: Font,
466    pub color: Hsla,
467    pub background_color: Option<Hsla>,
468    pub underline: Option<UnderlineStyle>,
469}
470
471#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
472#[repr(C)]
473pub struct GlyphId(u32);
474
475impl From<GlyphId> for u32 {
476    fn from(value: GlyphId) -> Self {
477        value.0
478    }
479}
480
481impl From<u16> for GlyphId {
482    fn from(num: u16) -> Self {
483        GlyphId(num as u32)
484    }
485}
486
487impl From<u32> for GlyphId {
488    fn from(num: u32) -> Self {
489        GlyphId(num)
490    }
491}
492
493#[derive(Clone, Debug, PartialEq)]
494pub struct RenderGlyphParams {
495    pub(crate) font_id: FontId,
496    pub(crate) glyph_id: GlyphId,
497    pub(crate) font_size: Pixels,
498    pub(crate) subpixel_variant: Point<u8>,
499    pub(crate) scale_factor: f32,
500    pub(crate) is_emoji: bool,
501}
502
503impl Eq for RenderGlyphParams {}
504
505impl Hash for RenderGlyphParams {
506    fn hash<H: Hasher>(&self, state: &mut H) {
507        self.font_id.0.hash(state);
508        self.glyph_id.0.hash(state);
509        self.font_size.0.to_bits().hash(state);
510        self.subpixel_variant.hash(state);
511        self.scale_factor.to_bits().hash(state);
512    }
513}
514
515#[derive(Clone, Debug, PartialEq)]
516pub struct RenderEmojiParams {
517    pub(crate) font_id: FontId,
518    pub(crate) glyph_id: GlyphId,
519    pub(crate) font_size: Pixels,
520    pub(crate) scale_factor: f32,
521}
522
523impl Eq for RenderEmojiParams {}
524
525impl Hash for RenderEmojiParams {
526    fn hash<H: Hasher>(&self, state: &mut H) {
527        self.font_id.0.hash(state);
528        self.glyph_id.0.hash(state);
529        self.font_size.0.to_bits().hash(state);
530        self.scale_factor.to_bits().hash(state);
531    }
532}
533
534#[derive(Clone, Debug, Eq, PartialEq, Hash)]
535pub struct Font {
536    pub family: SharedString,
537    pub features: FontFeatures,
538    pub weight: FontWeight,
539    pub style: FontStyle,
540}
541
542pub fn font(family: impl Into<SharedString>) -> Font {
543    Font {
544        family: family.into(),
545        features: FontFeatures::default(),
546        weight: FontWeight::default(),
547        style: FontStyle::default(),
548    }
549}
550
551impl Font {
552    pub fn bold(mut self) -> Self {
553        self.weight = FontWeight::BOLD;
554        self
555    }
556}
557
558/// A struct for storing font metrics.
559/// It is used to define the measurements of a typeface.
560#[derive(Clone, Copy, Debug)]
561pub struct FontMetrics {
562    /// The number of font units that make up the "em square",
563    /// a scalable grid for determining the size of a typeface.
564    pub(crate) units_per_em: u32,
565
566    /// The vertical distance from the baseline of the font to the top of the glyph covers.
567    pub(crate) ascent: f32,
568
569    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
570    pub(crate) descent: f32,
571
572    /// The recommended additional space to add between lines of type.
573    pub(crate) line_gap: f32,
574
575    /// The suggested position of the underline.
576    pub(crate) underline_position: f32,
577
578    /// The suggested thickness of the underline.
579    pub(crate) underline_thickness: f32,
580
581    /// The height of a capital letter measured from the baseline of the font.
582    pub(crate) cap_height: f32,
583
584    /// The height of a lowercase x.
585    pub(crate) x_height: f32,
586
587    /// The outer limits of the area that the font covers.
588    pub(crate) bounding_box: Bounds<f32>,
589}
590
591impl FontMetrics {
592    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
593    pub fn ascent(&self, font_size: Pixels) -> Pixels {
594        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
595    }
596
597    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
598    pub fn descent(&self, font_size: Pixels) -> Pixels {
599        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
600    }
601
602    /// Returns the recommended additional space to add between lines of type in pixels.
603    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
604        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
605    }
606
607    /// Returns the suggested position of the underline in pixels.
608    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
609        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
610    }
611
612    /// Returns the suggested thickness of the underline in pixels.
613    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
614        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
615    }
616
617    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
618    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
619        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
620    }
621
622    /// Returns the height of a lowercase x in pixels.
623    pub fn x_height(&self, font_size: Pixels) -> Pixels {
624        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
625    }
626
627    /// Returns the outer limits of the area that the font covers in pixels.
628    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
629        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
630    }
631}