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