text_system.rs

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