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