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::*;
 10use schemars::JsonSchema;
 11use serde::{Deserialize, Serialize};
 12
 13use crate::{
 14    px, Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
 15    StrikethroughStyle, UnderlineStyle,
 16};
 17use anyhow::anyhow;
 18use collections::{BTreeSet, FxHashMap};
 19use core::fmt;
 20use derive_more::Deref;
 21use itertools::Itertools;
 22use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
 23use smallvec::{smallvec, SmallVec};
 24use std::{
 25    borrow::Cow,
 26    cmp,
 27    fmt::{Debug, Display, Formatter},
 28    hash::{Hash, Hasher},
 29    ops::{Deref, DerefMut, Range},
 30    sync::Arc,
 31};
 32
 33/// An opaque identifier for a specific font.
 34#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 35#[repr(C)]
 36pub struct FontId(pub usize);
 37
 38/// An opaque identifier for a specific font family.
 39#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 40pub struct FontFamilyId(pub usize);
 41
 42pub(crate) const SUBPIXEL_VARIANTS: u8 = 4;
 43
 44/// The GPUI text rendering sub system.
 45pub struct TextSystem {
 46    platform_text_system: Arc<dyn PlatformTextSystem>,
 47    font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
 48    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
 49    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
 50    wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
 51    font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
 52    fallback_font_stack: SmallVec<[Font; 2]>,
 53}
 54
 55impl TextSystem {
 56    pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
 57        TextSystem {
 58            platform_text_system,
 59            font_metrics: RwLock::default(),
 60            raster_bounds: RwLock::default(),
 61            font_ids_by_font: RwLock::default(),
 62            wrapper_pool: Mutex::default(),
 63            font_runs_pool: Mutex::default(),
 64            fallback_font_stack: smallvec![
 65                // TODO: This is currently Zed-specific.
 66                // We should allow GPUI users to provide their own fallback font stack.
 67                font("Zed Plex Mono"),
 68                font("Helvetica"),
 69                font("Segoe UI"),  // Windows
 70                font("Cantarell"), // Gnome
 71                font("Ubuntu"),    // Gnome (Ubuntu)
 72                font("Noto Sans"), // KDE
 73                font("DejaVu Sans")
 74            ],
 75        }
 76    }
 77
 78    /// Get a list of all available font names from the operating system.
 79    pub fn all_font_names(&self) -> Vec<String> {
 80        let mut names: BTreeSet<_> = self
 81            .platform_text_system
 82            .all_font_names()
 83            .into_iter()
 84            .collect();
 85        names.extend(self.platform_text_system.all_font_families());
 86        names.extend(
 87            self.fallback_font_stack
 88                .iter()
 89                .map(|font| font.family.to_string()),
 90        );
 91        names.into_iter().collect()
 92    }
 93
 94    /// Add a font's data to the text system.
 95    pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 96        self.platform_text_system.add_fonts(fonts)
 97    }
 98
 99    /// Get the FontId for the configure font family and style.
100    pub fn font_id(&self, font: &Font) -> Result<FontId> {
101        fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
102            match font_id {
103                Ok(font_id) => Ok(*font_id),
104                Err(err) => Err(anyhow!("{}", err)),
105            }
106        }
107
108        let font_id = self
109            .font_ids_by_font
110            .read()
111            .get(font)
112            .map(clone_font_id_result);
113        if let Some(font_id) = font_id {
114            font_id
115        } else {
116            let font_id = self.platform_text_system.font_id(font);
117            self.font_ids_by_font
118                .write()
119                .insert(font.clone(), clone_font_id_result(&font_id));
120            font_id
121        }
122    }
123
124    /// Get the Font for the Font Id.
125    pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
126        let lock = self.font_ids_by_font.read();
127        lock.iter()
128            .filter_map(|(font, result)| match result {
129                Ok(font_id) if *font_id == id => Some(font.clone()),
130                _ => None,
131            })
132            .next()
133    }
134
135    /// Resolves the specified font, falling back to the default font stack if
136    /// the font fails to load.
137    ///
138    /// # Panics
139    ///
140    /// Panics if the font and none of the fallbacks can be resolved.
141    pub fn resolve_font(&self, font: &Font) -> FontId {
142        if let Ok(font_id) = self.font_id(font) {
143            return font_id;
144        }
145        for fallback in &self.fallback_font_stack {
146            if let Ok(font_id) = self.font_id(fallback) {
147                return font_id;
148            }
149        }
150
151        panic!(
152            "failed to resolve font '{}' or any of the fallbacks: {}",
153            font.family,
154            self.fallback_font_stack
155                .iter()
156                .map(|fallback| &fallback.family)
157                .join(", ")
158        );
159    }
160
161    /// Get the bounding box for the given font and font size.
162    /// A font's bounding box is the smallest rectangle that could enclose all glyphs
163    /// in the font. superimposed over one another.
164    pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
165        self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
166    }
167
168    /// Get the typographic bounds for the given character, in the given font and size.
169    pub fn typographic_bounds(
170        &self,
171        font_id: FontId,
172        font_size: Pixels,
173        character: char,
174    ) -> Result<Bounds<Pixels>> {
175        let glyph_id = self
176            .platform_text_system
177            .glyph_for_char(font_id, character)
178            .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
179        let bounds = self
180            .platform_text_system
181            .typographic_bounds(font_id, glyph_id)?;
182        Ok(self.read_metrics(font_id, |metrics| {
183            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
184        }))
185    }
186
187    /// Get the advance width for the given character, in the given font and size.
188    pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
189        let glyph_id = self
190            .platform_text_system
191            .glyph_for_char(font_id, ch)
192            .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
193        let result = self.platform_text_system.advance(font_id, glyph_id)?
194            / self.units_per_em(font_id) as f32;
195
196        Ok(result * font_size)
197    }
198
199    /// Get the number of font size units per 'em square',
200    /// Per MDN: "an abstract square whose height is the intended distance between
201    /// lines of type in the same type size"
202    pub fn units_per_em(&self, font_id: FontId) -> u32 {
203        self.read_metrics(font_id, |metrics| metrics.units_per_em)
204    }
205
206    /// Get the height of a capital letter in the given font and size.
207    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
208        self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
209    }
210
211    /// Get the height of the x character in the given font and size.
212    pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
213        self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
214    }
215
216    /// Get the recommended distance from the baseline for the given font
217    pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
218        self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
219    }
220
221    /// Get the recommended distance below the baseline for the given font,
222    /// in single spaced text.
223    pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
224        self.read_metrics(font_id, |metrics| metrics.descent(font_size))
225    }
226
227    /// Get the recommended baseline offset for the given font and line height.
228    pub fn baseline_offset(
229        &self,
230        font_id: FontId,
231        font_size: Pixels,
232        line_height: Pixels,
233    ) -> Pixels {
234        let ascent = self.ascent(font_id, font_size);
235        let descent = self.descent(font_id, font_size);
236        let padding_top = (line_height - ascent - descent) / 2.;
237        padding_top + ascent
238    }
239
240    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
241        let lock = self.font_metrics.upgradable_read();
242
243        if let Some(metrics) = lock.get(&font_id) {
244            read(metrics)
245        } else {
246            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
247            let metrics = lock
248                .entry(font_id)
249                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
250            read(metrics)
251        }
252    }
253
254    /// Returns a handle to a line wrapper, for the given font and font size.
255    pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
256        let lock = &mut self.wrapper_pool.lock();
257        let font_id = self.resolve_font(&font);
258        let wrappers = lock
259            .entry(FontIdWithSize { font_id, font_size })
260            .or_default();
261        let wrapper = wrappers.pop().unwrap_or_else(|| {
262            LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
263        });
264
265        LineWrapperHandle {
266            wrapper: Some(wrapper),
267            text_system: self.clone(),
268        }
269    }
270
271    /// Get the rasterized size and location of a specific, rendered glyph.
272    pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
273        let raster_bounds = self.raster_bounds.upgradable_read();
274        if let Some(bounds) = raster_bounds.get(params) {
275            Ok(*bounds)
276        } else {
277            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
278            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
279            raster_bounds.insert(params.clone(), bounds);
280            Ok(bounds)
281        }
282    }
283
284    pub(crate) fn rasterize_glyph(
285        &self,
286        params: &RenderGlyphParams,
287    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
288        let raster_bounds = self.raster_bounds(params)?;
289        self.platform_text_system
290            .rasterize_glyph(params, raster_bounds)
291    }
292}
293
294/// The GPUI text layout subsystem.
295#[derive(Deref)]
296pub struct WindowTextSystem {
297    line_layout_cache: LineLayoutCache,
298    #[deref]
299    text_system: Arc<TextSystem>,
300}
301
302impl WindowTextSystem {
303    pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
304        Self {
305            line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
306            text_system,
307        }
308    }
309
310    pub(crate) fn layout_index(&self) -> LineLayoutIndex {
311        self.line_layout_cache.layout_index()
312    }
313
314    pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
315        self.line_layout_cache.reuse_layouts(index)
316    }
317
318    pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
319        self.line_layout_cache.truncate_layouts(index)
320    }
321
322    /// Shape the given line, at the given font_size, for painting to the screen.
323    /// Subsets of the line can be styled independently with the `runs` parameter.
324    ///
325    /// Note that this method can only shape a single line of text. It will panic
326    /// if the text contains newlines. If you need to shape multiple lines of text,
327    /// use `TextLayout::shape_text` instead.
328    pub fn shape_line(
329        &self,
330        text: SharedString,
331        font_size: Pixels,
332        runs: &[TextRun],
333    ) -> Result<ShapedLine> {
334        debug_assert!(
335            text.find('\n').is_none(),
336            "text argument should not contain newlines"
337        );
338
339        let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
340        for run in runs {
341            if let Some(last_run) = decoration_runs.last_mut() {
342                if last_run.color == run.color
343                    && last_run.underline == run.underline
344                    && last_run.strikethrough == run.strikethrough
345                    && last_run.background_color == run.background_color
346                {
347                    last_run.len += run.len as u32;
348                    continue;
349                }
350            }
351            decoration_runs.push(DecorationRun {
352                len: run.len as u32,
353                color: run.color,
354                background_color: run.background_color,
355                underline: run.underline,
356                strikethrough: run.strikethrough,
357            });
358        }
359
360        let layout = self.layout_line(text.as_ref(), font_size, runs)?;
361
362        Ok(ShapedLine {
363            layout,
364            text,
365            decoration_runs,
366        })
367    }
368
369    /// Shape a multi line string of text, at the given font_size, for painting to the screen.
370    /// Subsets of the text can be styled independently with the `runs` parameter.
371    /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
372    pub fn shape_text(
373        &self,
374        text: SharedString,
375        font_size: Pixels,
376        runs: &[TextRun],
377        wrap_width: Option<Pixels>,
378    ) -> Result<SmallVec<[WrappedLine; 1]>> {
379        let mut runs = runs.iter().cloned().peekable();
380        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
381
382        let mut lines = SmallVec::new();
383        let mut line_start = 0;
384
385        let mut process_line = |line_text: SharedString| {
386            let line_end = line_start + line_text.len();
387
388            let mut last_font: Option<Font> = None;
389            let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
390            let mut run_start = line_start;
391            while run_start < line_end {
392                let Some(run) = runs.peek_mut() else {
393                    break;
394                };
395
396                let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
397
398                if last_font == Some(run.font.clone()) {
399                    font_runs.last_mut().unwrap().len += run_len_within_line;
400                } else {
401                    last_font = Some(run.font.clone());
402                    font_runs.push(FontRun {
403                        len: run_len_within_line,
404                        font_id: self.resolve_font(&run.font),
405                    });
406                }
407
408                if decoration_runs.last().map_or(false, |last_run| {
409                    last_run.color == run.color
410                        && last_run.underline == run.underline
411                        && last_run.strikethrough == run.strikethrough
412                        && last_run.background_color == run.background_color
413                }) {
414                    decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
415                } else {
416                    decoration_runs.push(DecorationRun {
417                        len: run_len_within_line as u32,
418                        color: run.color,
419                        background_color: run.background_color,
420                        underline: run.underline,
421                        strikethrough: run.strikethrough,
422                    });
423                }
424
425                if run_len_within_line == run.len {
426                    runs.next();
427                } else {
428                    // Preserve the remainder of the run for the next line
429                    run.len -= run_len_within_line;
430                }
431                run_start += run_len_within_line;
432            }
433
434            let layout = self
435                .line_layout_cache
436                .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
437
438            lines.push(WrappedLine {
439                layout,
440                decoration_runs,
441                text: line_text,
442            });
443
444            // Skip `\n` character.
445            line_start = line_end + 1;
446            if let Some(run) = runs.peek_mut() {
447                run.len = run.len.saturating_sub(1);
448                if run.len == 0 {
449                    runs.next();
450                }
451            }
452
453            font_runs.clear();
454        };
455
456        let mut split_lines = text.split('\n');
457        let mut processed = false;
458
459        if let Some(first_line) = split_lines.next() {
460            if let Some(second_line) = split_lines.next() {
461                processed = true;
462                process_line(first_line.to_string().into());
463                process_line(second_line.to_string().into());
464                for line_text in split_lines {
465                    process_line(line_text.to_string().into());
466                }
467            }
468        }
469
470        if !processed {
471            process_line(text);
472        }
473
474        self.font_runs_pool.lock().push(font_runs);
475
476        Ok(lines)
477    }
478
479    pub(crate) fn finish_frame(&self) {
480        self.line_layout_cache.finish_frame()
481    }
482
483    /// Layout the given line of text, at the given font_size.
484    /// Subsets of the line can be styled independently with the `runs` parameter.
485    /// Generally, you should prefer to use `TextLayout::shape_line` instead, which
486    /// can be painted directly.
487    pub fn layout_line(
488        &self,
489        text: &str,
490        font_size: Pixels,
491        runs: &[TextRun],
492    ) -> Result<Arc<LineLayout>> {
493        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
494        for run in runs.iter() {
495            let font_id = self.resolve_font(&run.font);
496            if let Some(last_run) = font_runs.last_mut() {
497                if last_run.font_id == font_id {
498                    last_run.len += run.len;
499                    continue;
500                }
501            }
502            font_runs.push(FontRun {
503                len: run.len,
504                font_id,
505            });
506        }
507
508        let layout = self
509            .line_layout_cache
510            .layout_line(text, font_size, &font_runs);
511
512        font_runs.clear();
513        self.font_runs_pool.lock().push(font_runs);
514
515        Ok(layout)
516    }
517}
518
519#[derive(Hash, Eq, PartialEq)]
520struct FontIdWithSize {
521    font_id: FontId,
522    font_size: Pixels,
523}
524
525/// A handle into the text system, which can be used to compute the wrapped layout of text
526pub struct LineWrapperHandle {
527    wrapper: Option<LineWrapper>,
528    text_system: Arc<TextSystem>,
529}
530
531impl Drop for LineWrapperHandle {
532    fn drop(&mut self) {
533        let mut state = self.text_system.wrapper_pool.lock();
534        let wrapper = self.wrapper.take().unwrap();
535        state
536            .get_mut(&FontIdWithSize {
537                font_id: wrapper.font_id,
538                font_size: wrapper.font_size,
539            })
540            .unwrap()
541            .push(wrapper);
542    }
543}
544
545impl Deref for LineWrapperHandle {
546    type Target = LineWrapper;
547
548    fn deref(&self) -> &Self::Target {
549        self.wrapper.as_ref().unwrap()
550    }
551}
552
553impl DerefMut for LineWrapperHandle {
554    fn deref_mut(&mut self) -> &mut Self::Target {
555        self.wrapper.as_mut().unwrap()
556    }
557}
558
559/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
560/// with 400.0 as normal.
561#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Deserialize, Serialize, JsonSchema)]
562pub struct FontWeight(pub f32);
563
564impl Default for FontWeight {
565    #[inline]
566    fn default() -> FontWeight {
567        FontWeight::NORMAL
568    }
569}
570
571impl Hash for FontWeight {
572    fn hash<H: Hasher>(&self, state: &mut H) {
573        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
574    }
575}
576
577impl Eq for FontWeight {}
578
579impl FontWeight {
580    /// Thin weight (100), the thinnest value.
581    pub const THIN: FontWeight = FontWeight(100.0);
582    /// Extra light weight (200).
583    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
584    /// Light weight (300).
585    pub const LIGHT: FontWeight = FontWeight(300.0);
586    /// Normal (400).
587    pub const NORMAL: FontWeight = FontWeight(400.0);
588    /// Medium weight (500, higher than normal).
589    pub const MEDIUM: FontWeight = FontWeight(500.0);
590    /// Semibold weight (600).
591    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
592    /// Bold weight (700).
593    pub const BOLD: FontWeight = FontWeight(700.0);
594    /// Extra-bold weight (800).
595    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
596    /// Black weight (900), the thickest value.
597    pub const BLACK: FontWeight = FontWeight(900.0);
598}
599
600/// Allows italic or oblique faces to be selected.
601#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default)]
602pub enum FontStyle {
603    /// A face that is neither italic not obliqued.
604    #[default]
605    Normal,
606    /// A form that is generally cursive in nature.
607    Italic,
608    /// A typically-sloped version of the regular face.
609    Oblique,
610}
611
612impl Display for FontStyle {
613    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
614        Debug::fmt(self, f)
615    }
616}
617
618/// A styled run of text, for use in [`TextLayout`].
619#[derive(Clone, Debug, PartialEq, Eq)]
620pub struct TextRun {
621    /// A number of utf8 bytes
622    pub len: usize,
623    /// The font to use for this run.
624    pub font: Font,
625    /// The color
626    pub color: Hsla,
627    /// The background color (if any)
628    pub background_color: Option<Hsla>,
629    /// The underline style (if any)
630    pub underline: Option<UnderlineStyle>,
631    /// The strikethrough style (if any)
632    pub strikethrough: Option<StrikethroughStyle>,
633}
634
635/// An identifier for a specific glyph, as returned by [`TextSystem::layout_line`].
636#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
637#[repr(C)]
638pub struct GlyphId(pub(crate) u32);
639
640#[derive(Clone, Debug, PartialEq)]
641pub(crate) struct RenderGlyphParams {
642    pub(crate) font_id: FontId,
643    pub(crate) glyph_id: GlyphId,
644    pub(crate) font_size: Pixels,
645    pub(crate) subpixel_variant: Point<u8>,
646    pub(crate) scale_factor: f32,
647    pub(crate) is_emoji: bool,
648}
649
650impl Eq for RenderGlyphParams {}
651
652impl Hash for RenderGlyphParams {
653    fn hash<H: Hasher>(&self, state: &mut H) {
654        self.font_id.0.hash(state);
655        self.glyph_id.0.hash(state);
656        self.font_size.0.to_bits().hash(state);
657        self.subpixel_variant.hash(state);
658        self.scale_factor.to_bits().hash(state);
659    }
660}
661
662/// The configuration details for identifying a specific font.
663#[derive(Clone, Debug, Eq, PartialEq, Hash)]
664pub struct Font {
665    /// The font family name.
666    ///
667    /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
668    pub family: SharedString,
669
670    /// The font features to use.
671    pub features: FontFeatures,
672
673    /// The font weight.
674    pub weight: FontWeight,
675
676    /// The font style.
677    pub style: FontStyle,
678}
679
680/// Get a [`Font`] for a given name.
681pub fn font(family: impl Into<SharedString>) -> Font {
682    Font {
683        family: family.into(),
684        features: FontFeatures::default(),
685        weight: FontWeight::default(),
686        style: FontStyle::default(),
687    }
688}
689
690impl Font {
691    /// Set this Font to be bold
692    pub fn bold(mut self) -> Self {
693        self.weight = FontWeight::BOLD;
694        self
695    }
696
697    /// Set this Font to be italic
698    pub fn italic(mut self) -> Self {
699        self.style = FontStyle::Italic;
700        self
701    }
702}
703
704/// A struct for storing font metrics.
705/// It is used to define the measurements of a typeface.
706#[derive(Clone, Copy, Debug)]
707pub struct FontMetrics {
708    /// The number of font units that make up the "em square",
709    /// a scalable grid for determining the size of a typeface.
710    pub(crate) units_per_em: u32,
711
712    /// The vertical distance from the baseline of the font to the top of the glyph covers.
713    pub(crate) ascent: f32,
714
715    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
716    pub(crate) descent: f32,
717
718    /// The recommended additional space to add between lines of type.
719    pub(crate) line_gap: f32,
720
721    /// The suggested position of the underline.
722    pub(crate) underline_position: f32,
723
724    /// The suggested thickness of the underline.
725    pub(crate) underline_thickness: f32,
726
727    /// The height of a capital letter measured from the baseline of the font.
728    pub(crate) cap_height: f32,
729
730    /// The height of a lowercase x.
731    pub(crate) x_height: f32,
732
733    /// The outer limits of the area that the font covers.
734    /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
735    pub(crate) bounding_box: Bounds<f32>,
736}
737
738impl FontMetrics {
739    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
740    pub fn ascent(&self, font_size: Pixels) -> Pixels {
741        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
742    }
743
744    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
745    pub fn descent(&self, font_size: Pixels) -> Pixels {
746        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
747    }
748
749    /// Returns the recommended additional space to add between lines of type in pixels.
750    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
751        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
752    }
753
754    /// Returns the suggested position of the underline in pixels.
755    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
756        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
757    }
758
759    /// Returns the suggested thickness of the underline in pixels.
760    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
761        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
762    }
763
764    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
765    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
766        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
767    }
768
769    /// Returns the height of a lowercase x in pixels.
770    pub fn x_height(&self, font_size: Pixels) -> Pixels {
771        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
772    }
773
774    /// Returns the outer limits of the area that the font covers in pixels.
775    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
776        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
777    }
778}