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