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