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, StrikethroughStyle, UnderlineStyle,
14};
15use anyhow::anyhow;
16use collections::{BTreeSet, FxHashMap, FxHashSet};
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<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 ],
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.strikethrough == run.strikethrough
321 && last_run.background_color == run.background_color
322 {
323 last_run.len += run.len as u32;
324 continue;
325 }
326 }
327 decoration_runs.push(DecorationRun {
328 len: run.len as u32,
329 color: run.color,
330 background_color: run.background_color,
331 underline: run.underline,
332 strikethrough: run.strikethrough,
333 });
334 }
335
336 let layout = self.layout_line(text.as_ref(), font_size, runs)?;
337
338 Ok(ShapedLine {
339 layout,
340 text,
341 decoration_runs,
342 })
343 }
344
345 /// Shape a multi line string of text, at the given font_size, for painting to the screen.
346 /// Subsets of the text can be styled independently with the `runs` parameter.
347 /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
348 pub fn shape_text(
349 &self,
350 text: SharedString,
351 font_size: Pixels,
352 runs: &[TextRun],
353 wrap_width: Option<Pixels>,
354 ) -> Result<SmallVec<[WrappedLine; 1]>> {
355 let mut runs = runs.iter().cloned().peekable();
356 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
357
358 let mut lines = SmallVec::new();
359 let mut line_start = 0;
360
361 let mut process_line = |line_text: SharedString| {
362 let line_end = line_start + line_text.len();
363
364 let mut last_font: Option<Font> = None;
365 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
366 let mut run_start = line_start;
367 while run_start < line_end {
368 let Some(run) = runs.peek_mut() else {
369 break;
370 };
371
372 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
373
374 if last_font == Some(run.font.clone()) {
375 font_runs.last_mut().unwrap().len += run_len_within_line;
376 } else {
377 last_font = Some(run.font.clone());
378 font_runs.push(FontRun {
379 len: run_len_within_line,
380 font_id: self.resolve_font(&run.font),
381 });
382 }
383
384 if decoration_runs.last().map_or(false, |last_run| {
385 last_run.color == run.color
386 && last_run.underline == run.underline
387 && last_run.strikethrough == run.strikethrough
388 && last_run.background_color == run.background_color
389 }) {
390 decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
391 } else {
392 decoration_runs.push(DecorationRun {
393 len: run_len_within_line as u32,
394 color: run.color,
395 background_color: run.background_color,
396 underline: run.underline,
397 strikethrough: run.strikethrough,
398 });
399 }
400
401 if run_len_within_line == run.len {
402 runs.next();
403 } else {
404 // Preserve the remainder of the run for the next line
405 run.len -= run_len_within_line;
406 }
407 run_start += run_len_within_line;
408 }
409
410 let layout = self
411 .line_layout_cache
412 .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
413
414 lines.push(WrappedLine {
415 layout,
416 decoration_runs,
417 text: line_text,
418 });
419
420 // Skip `\n` character.
421 line_start = line_end + 1;
422 if let Some(run) = runs.peek_mut() {
423 run.len = run.len.saturating_sub(1);
424 if run.len == 0 {
425 runs.next();
426 }
427 }
428
429 font_runs.clear();
430 };
431
432 let mut split_lines = text.split('\n');
433 let mut processed = false;
434
435 if let Some(first_line) = split_lines.next() {
436 if let Some(second_line) = split_lines.next() {
437 processed = true;
438 process_line(first_line.to_string().into());
439 process_line(second_line.to_string().into());
440 for line_text in split_lines {
441 process_line(line_text.to_string().into());
442 }
443 }
444 }
445
446 if !processed {
447 process_line(text);
448 }
449
450 self.font_runs_pool.lock().push(font_runs);
451
452 Ok(lines)
453 }
454
455 pub(crate) fn finish_frame(&self, reused_views: &FxHashSet<EntityId>) {
456 self.line_layout_cache.finish_frame(reused_views)
457 }
458
459 /// Layout the given line of text, at the given font_size.
460 /// Subsets of the line can be styled independently with the `runs` parameter.
461 /// Generally, you should prefer to use `TextLayout::shape_line` instead, which
462 /// can be painted directly.
463 pub fn layout_line(
464 &self,
465 text: &str,
466 font_size: Pixels,
467 runs: &[TextRun],
468 ) -> Result<Arc<LineLayout>> {
469 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
470 for run in runs.iter() {
471 let font_id = self.resolve_font(&run.font);
472 if let Some(last_run) = font_runs.last_mut() {
473 if last_run.font_id == font_id {
474 last_run.len += run.len;
475 continue;
476 }
477 }
478 font_runs.push(FontRun {
479 len: run.len,
480 font_id,
481 });
482 }
483
484 let layout = self
485 .line_layout_cache
486 .layout_line(text, font_size, &font_runs);
487
488 font_runs.clear();
489 self.font_runs_pool.lock().push(font_runs);
490
491 Ok(layout)
492 }
493}
494
495#[derive(Hash, Eq, PartialEq)]
496struct FontIdWithSize {
497 font_id: FontId,
498 font_size: Pixels,
499}
500
501/// A handle into the text system, which can be used to compute the wrapped layout of text
502pub struct LineWrapperHandle {
503 wrapper: Option<LineWrapper>,
504 text_system: Arc<TextSystem>,
505}
506
507impl Drop for LineWrapperHandle {
508 fn drop(&mut self) {
509 let mut state = self.text_system.wrapper_pool.lock();
510 let wrapper = self.wrapper.take().unwrap();
511 state
512 .get_mut(&FontIdWithSize {
513 font_id: wrapper.font_id,
514 font_size: wrapper.font_size,
515 })
516 .unwrap()
517 .push(wrapper);
518 }
519}
520
521impl Deref for LineWrapperHandle {
522 type Target = LineWrapper;
523
524 fn deref(&self) -> &Self::Target {
525 self.wrapper.as_ref().unwrap()
526 }
527}
528
529impl DerefMut for LineWrapperHandle {
530 fn deref_mut(&mut self) -> &mut Self::Target {
531 self.wrapper.as_mut().unwrap()
532 }
533}
534
535/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
536/// with 400.0 as normal.
537#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
538pub struct FontWeight(pub f32);
539
540impl Default for FontWeight {
541 #[inline]
542 fn default() -> FontWeight {
543 FontWeight::NORMAL
544 }
545}
546
547impl Hash for FontWeight {
548 fn hash<H: Hasher>(&self, state: &mut H) {
549 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
550 }
551}
552
553impl Eq for FontWeight {}
554
555impl FontWeight {
556 /// Thin weight (100), the thinnest value.
557 pub const THIN: FontWeight = FontWeight(100.0);
558 /// Extra light weight (200).
559 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
560 /// Light weight (300).
561 pub const LIGHT: FontWeight = FontWeight(300.0);
562 /// Normal (400).
563 pub const NORMAL: FontWeight = FontWeight(400.0);
564 /// Medium weight (500, higher than normal).
565 pub const MEDIUM: FontWeight = FontWeight(500.0);
566 /// Semibold weight (600).
567 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
568 /// Bold weight (700).
569 pub const BOLD: FontWeight = FontWeight(700.0);
570 /// Extra-bold weight (800).
571 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
572 /// Black weight (900), the thickest value.
573 pub const BLACK: FontWeight = FontWeight(900.0);
574}
575
576/// Allows italic or oblique faces to be selected.
577#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default)]
578pub enum FontStyle {
579 /// A face that is neither italic not obliqued.
580 #[default]
581 Normal,
582 /// A form that is generally cursive in nature.
583 Italic,
584 /// A typically-sloped version of the regular face.
585 Oblique,
586}
587
588impl Display for FontStyle {
589 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
590 Debug::fmt(self, f)
591 }
592}
593
594/// A styled run of text, for use in [`TextLayout`].
595#[derive(Clone, Debug, PartialEq, Eq)]
596pub struct TextRun {
597 /// A number of utf8 bytes
598 pub len: usize,
599 /// The font to use for this run.
600 pub font: Font,
601 /// The color
602 pub color: Hsla,
603 /// The background color (if any)
604 pub background_color: Option<Hsla>,
605 /// The underline style (if any)
606 pub underline: Option<UnderlineStyle>,
607 /// The strikethrough style (if any)
608 pub strikethrough: Option<StrikethroughStyle>,
609}
610
611/// An identifier for a specific glyph, as returned by [`TextSystem::layout_line`].
612#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
613#[repr(C)]
614pub struct GlyphId(pub(crate) u32);
615
616#[derive(Clone, Debug, PartialEq)]
617pub(crate) struct RenderGlyphParams {
618 pub(crate) font_id: FontId,
619 pub(crate) glyph_id: GlyphId,
620 pub(crate) font_size: Pixels,
621 pub(crate) subpixel_variant: Point<u8>,
622 pub(crate) scale_factor: f32,
623 pub(crate) is_emoji: bool,
624}
625
626impl Eq for RenderGlyphParams {}
627
628impl Hash for RenderGlyphParams {
629 fn hash<H: Hasher>(&self, state: &mut H) {
630 self.font_id.0.hash(state);
631 self.glyph_id.0.hash(state);
632 self.font_size.0.to_bits().hash(state);
633 self.subpixel_variant.hash(state);
634 self.scale_factor.to_bits().hash(state);
635 }
636}
637
638/// The parameters for rendering an emoji glyph.
639#[derive(Clone, Debug, PartialEq)]
640pub struct RenderEmojiParams {
641 pub(crate) font_id: FontId,
642 pub(crate) glyph_id: GlyphId,
643 pub(crate) font_size: Pixels,
644 pub(crate) scale_factor: f32,
645}
646
647impl Eq for RenderEmojiParams {}
648
649impl Hash for RenderEmojiParams {
650 fn hash<H: Hasher>(&self, state: &mut H) {
651 self.font_id.0.hash(state);
652 self.glyph_id.0.hash(state);
653 self.font_size.0.to_bits().hash(state);
654 self.scale_factor.to_bits().hash(state);
655 }
656}
657
658/// The configuration details for identifying a specific font.
659#[derive(Clone, Debug, Eq, PartialEq, Hash)]
660pub struct Font {
661 /// The font family name.
662 pub family: SharedString,
663
664 /// The font features to use.
665 pub features: FontFeatures,
666
667 /// The font weight.
668 pub weight: FontWeight,
669
670 /// The font style.
671 pub style: FontStyle,
672}
673
674/// Get a [`Font`] for a given name.
675pub fn font(family: impl Into<SharedString>) -> Font {
676 Font {
677 family: family.into(),
678 features: FontFeatures::default(),
679 weight: FontWeight::default(),
680 style: FontStyle::default(),
681 }
682}
683
684impl Font {
685 /// Set this Font to be bold
686 pub fn bold(mut self) -> Self {
687 self.weight = FontWeight::BOLD;
688 self
689 }
690
691 /// Set this Font to be italic
692 pub fn italic(mut self) -> Self {
693 self.style = FontStyle::Italic;
694 self
695 }
696}
697
698/// A struct for storing font metrics.
699/// It is used to define the measurements of a typeface.
700#[derive(Clone, Copy, Debug)]
701pub struct FontMetrics {
702 /// The number of font units that make up the "em square",
703 /// a scalable grid for determining the size of a typeface.
704 pub(crate) units_per_em: u32,
705
706 /// The vertical distance from the baseline of the font to the top of the glyph covers.
707 pub(crate) ascent: f32,
708
709 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
710 pub(crate) descent: f32,
711
712 /// The recommended additional space to add between lines of type.
713 pub(crate) line_gap: f32,
714
715 /// The suggested position of the underline.
716 pub(crate) underline_position: f32,
717
718 /// The suggested thickness of the underline.
719 pub(crate) underline_thickness: f32,
720
721 /// The height of a capital letter measured from the baseline of the font.
722 pub(crate) cap_height: f32,
723
724 /// The height of a lowercase x.
725 pub(crate) x_height: f32,
726
727 /// The outer limits of the area that the font covers.
728 pub(crate) bounding_box: Bounds<f32>,
729}
730
731impl FontMetrics {
732 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
733 pub fn ascent(&self, font_size: Pixels) -> Pixels {
734 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
735 }
736
737 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
738 pub fn descent(&self, font_size: Pixels) -> Pixels {
739 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
740 }
741
742 /// Returns the recommended additional space to add between lines of type in pixels.
743 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
744 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
745 }
746
747 /// Returns the suggested position of the underline in pixels.
748 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
749 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
750 }
751
752 /// Returns the suggested thickness of the underline in pixels.
753 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
754 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
755 }
756
757 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
758 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
759 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
760 }
761
762 /// Returns the height of a lowercase x in pixels.
763 pub fn x_height(&self, font_size: Pixels) -> Pixels {
764 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
765 }
766
767 /// Returns the outer limits of the area that the font covers in pixels.
768 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
769 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
770 }
771}