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