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