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