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