text_system.rs

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