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