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