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