1mod font_fallbacks;
2mod font_features;
3mod line;
4mod line_layout;
5mod line_wrapper;
6
7pub use font_fallbacks::*;
8pub use font_features::*;
9pub use line::*;
10pub use line_layout::*;
11pub use line_wrapper::*;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
17 StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
18};
19use anyhow::{Context as _, anyhow};
20use collections::FxHashMap;
21use core::fmt;
22use derive_more::{Add, Deref, FromStr, Sub};
23use itertools::Itertools;
24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
25use smallvec::{SmallVec, smallvec};
26use std::{
27 borrow::Cow,
28 cmp,
29 fmt::{Debug, Display, Formatter},
30 hash::{Hash, Hasher},
31 ops::{Deref, DerefMut, Range},
32 sync::Arc,
33};
34
35#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
37#[repr(C)]
38pub struct FontId(pub usize);
39
40#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
42pub struct FontFamilyId(pub usize);
43
44pub(crate) const SUBPIXEL_VARIANTS_X: u8 = 4;
45
46pub(crate) const SUBPIXEL_VARIANTS_Y: u8 =
47 if cfg!(target_os = "windows") || cfg!(target_os = "linux") {
48 1
49 } else {
50 SUBPIXEL_VARIANTS_X
51 };
52
53pub struct TextSystem {
55 platform_text_system: Arc<dyn PlatformTextSystem>,
56 font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
57 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
58 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
59 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
60 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
61 fallback_font_stack: SmallVec<[Font; 2]>,
62}
63
64impl TextSystem {
65 pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
66 TextSystem {
67 platform_text_system,
68 font_metrics: RwLock::default(),
69 raster_bounds: RwLock::default(),
70 font_ids_by_font: RwLock::default(),
71 wrapper_pool: Mutex::default(),
72 font_runs_pool: Mutex::default(),
73 fallback_font_stack: smallvec![
74 font(".ZedMono"),
76 font(".ZedSans"),
77 font("Helvetica"),
78 font("Segoe UI"), font("Ubuntu"), font("Adwaita Sans"), font("Cantarell"), font("Noto Sans"), font("DejaVu Sans"),
84 font("Arial"), ],
86 }
87 }
88
89 pub fn all_font_names(&self) -> Vec<String> {
91 let mut names = self.platform_text_system.all_font_names();
92 names.extend(
93 self.fallback_font_stack
94 .iter()
95 .map(|font| font.family.to_string()),
96 );
97 names.push(".SystemUIFont".to_string());
98 names.sort();
99 names.dedup();
100 names
101 }
102
103 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
105 self.platform_text_system.add_fonts(fonts)
106 }
107
108 fn font_id(&self, font: &Font) -> Result<FontId> {
110 fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
111 match font_id {
112 Ok(font_id) => Ok(*font_id),
113 Err(err) => Err(anyhow!("{err}")),
114 }
115 }
116
117 let font_id = self
118 .font_ids_by_font
119 .read()
120 .get(font)
121 .map(clone_font_id_result);
122 if let Some(font_id) = font_id {
123 font_id
124 } else {
125 let font_id = self.platform_text_system.font_id(font);
126 self.font_ids_by_font
127 .write()
128 .insert(font.clone(), clone_font_id_result(&font_id));
129 font_id
130 }
131 }
132
133 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
135 let lock = self.font_ids_by_font.read();
136 lock.iter()
137 .filter_map(|(font, result)| match result {
138 Ok(font_id) if *font_id == id => Some(font.clone()),
139 _ => None,
140 })
141 .next()
142 }
143
144 pub fn resolve_font(&self, font: &Font) -> FontId {
151 if let Ok(font_id) = self.font_id(font) {
152 return font_id;
153 }
154 for fallback in &self.fallback_font_stack {
155 if let Ok(font_id) = self.font_id(fallback) {
156 return font_id;
157 }
158 }
159
160 panic!(
161 "failed to resolve font '{}' or any of the fallbacks: {}",
162 font.family,
163 self.fallback_font_stack
164 .iter()
165 .map(|fallback| &fallback.family)
166 .join(", ")
167 );
168 }
169
170 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
174 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
175 }
176
177 pub fn typographic_bounds(
179 &self,
180 font_id: FontId,
181 font_size: Pixels,
182 character: char,
183 ) -> Result<Bounds<Pixels>> {
184 let glyph_id = self
185 .platform_text_system
186 .glyph_for_char(font_id, character)
187 .with_context(|| format!("glyph not found for character '{character}'"))?;
188 let bounds = self
189 .platform_text_system
190 .typographic_bounds(font_id, glyph_id)?;
191 Ok(self.read_metrics(font_id, |metrics| {
192 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
193 }))
194 }
195
196 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
198 let glyph_id = self
199 .platform_text_system
200 .glyph_for_char(font_id, ch)
201 .with_context(|| format!("glyph not found for character '{ch}'"))?;
202 let result = self.platform_text_system.advance(font_id, glyph_id)?
203 / self.units_per_em(font_id) as f32;
204
205 Ok(result * font_size)
206 }
207
208 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
212 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
213 }
214
215 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
219 Ok(self.advance(font_id, font_size, 'm')?.width)
220 }
221
222 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
226 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
227 }
228
229 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
233 Ok(self.advance(font_id, font_size, '0')?.width)
234 }
235
236 pub fn units_per_em(&self, font_id: FontId) -> u32 {
240 self.read_metrics(font_id, |metrics| metrics.units_per_em)
241 }
242
243 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
245 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
246 }
247
248 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
250 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
251 }
252
253 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
255 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
256 }
257
258 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
261 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
262 }
263
264 pub fn baseline_offset(
266 &self,
267 font_id: FontId,
268 font_size: Pixels,
269 line_height: Pixels,
270 ) -> Pixels {
271 let ascent = self.ascent(font_id, font_size);
272 let descent = self.descent(font_id, font_size);
273 let padding_top = (line_height - ascent - descent) / 2.;
274 padding_top + ascent
275 }
276
277 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
278 let lock = self.font_metrics.upgradable_read();
279
280 if let Some(metrics) = lock.get(&font_id) {
281 read(metrics)
282 } else {
283 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
284 let metrics = lock
285 .entry(font_id)
286 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
287 read(metrics)
288 }
289 }
290
291 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
293 let lock = &mut self.wrapper_pool.lock();
294 let font_id = self.resolve_font(&font);
295 let wrappers = lock
296 .entry(FontIdWithSize { font_id, font_size })
297 .or_default();
298 let wrapper = wrappers.pop().unwrap_or_else(|| {
299 LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
300 });
301
302 LineWrapperHandle {
303 wrapper: Some(wrapper),
304 text_system: self.clone(),
305 }
306 }
307
308 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
310 let raster_bounds = self.raster_bounds.upgradable_read();
311 if let Some(bounds) = raster_bounds.get(params) {
312 Ok(*bounds)
313 } else {
314 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
315 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
316 raster_bounds.insert(params.clone(), bounds);
317 Ok(bounds)
318 }
319 }
320
321 pub(crate) fn rasterize_glyph(
322 &self,
323 params: &RenderGlyphParams,
324 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
325 let raster_bounds = self.raster_bounds(params)?;
326 self.platform_text_system
327 .rasterize_glyph(params, raster_bounds)
328 }
329
330 pub(crate) fn recommended_rendering_mode(
333 &self,
334 font_id: FontId,
335 font_size: Pixels,
336 ) -> TextRenderingMode {
337 self.platform_text_system
338 .recommended_rendering_mode(font_id, font_size)
339 }
340}
341
342#[derive(Deref)]
344pub struct WindowTextSystem {
345 line_layout_cache: LineLayoutCache,
346 #[deref]
347 text_system: Arc<TextSystem>,
348}
349
350impl WindowTextSystem {
351 pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
352 Self {
353 line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
354 text_system,
355 }
356 }
357
358 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
359 self.line_layout_cache.layout_index()
360 }
361
362 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
363 self.line_layout_cache.reuse_layouts(index)
364 }
365
366 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
367 self.line_layout_cache.truncate_layouts(index)
368 }
369
370 pub fn shape_line(
377 &self,
378 text: SharedString,
379 font_size: Pixels,
380 runs: &[TextRun],
381 force_width: Option<Pixels>,
382 ) -> ShapedLine {
383 debug_assert!(
384 text.find('\n').is_none(),
385 "text argument should not contain newlines"
386 );
387
388 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
389 for run in runs {
390 if let Some(last_run) = decoration_runs.last_mut()
391 && last_run.color == run.color
392 && last_run.underline == run.underline
393 && last_run.strikethrough == run.strikethrough
394 && last_run.background_color == run.background_color
395 {
396 last_run.len += run.len as u32;
397 continue;
398 }
399 decoration_runs.push(DecorationRun {
400 len: run.len as u32,
401 color: run.color,
402 background_color: run.background_color,
403 underline: run.underline,
404 strikethrough: run.strikethrough,
405 });
406 }
407
408 let layout = self.layout_line(&text, font_size, runs, force_width);
409
410 ShapedLine {
411 layout,
412 text,
413 decoration_runs,
414 }
415 }
416
417 pub fn shape_text(
421 &self,
422 text: SharedString,
423 font_size: Pixels,
424 runs: &[TextRun],
425 wrap_width: Option<Pixels>,
426 line_clamp: Option<usize>,
427 ) -> Result<SmallVec<[WrappedLine; 1]>> {
428 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
429 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
430
431 let mut lines = SmallVec::new();
432 let mut max_wrap_lines = line_clamp;
433 let mut wrapped_lines = 0;
434
435 let mut process_line = |line_text: SharedString, line_start, line_end| {
436 font_runs.clear();
437
438 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
439 let mut run_start = line_start;
440 while run_start < line_end {
441 let Some(run) = runs.peek_mut() else {
442 log::warn!("`TextRun`s do not cover the entire to be shaped text");
443 break;
444 };
445
446 let run_len_within_line = cmp::min(line_end - run_start, run.len);
447
448 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
449 && last_run.color == run.color
450 && last_run.underline == run.underline
451 && last_run.strikethrough == run.strikethrough
452 && last_run.background_color == run.background_color
453 {
454 last_run.len += run_len_within_line as u32;
455 false
456 } else {
457 decoration_runs.push(DecorationRun {
458 len: run_len_within_line as u32,
459 color: run.color,
460 background_color: run.background_color,
461 underline: run.underline,
462 strikethrough: run.strikethrough,
463 });
464 true
465 };
466
467 let font_id = self.resolve_font(&run.font);
468 if let Some(font_run) = font_runs.last_mut()
469 && font_id == font_run.font_id
470 && !decoration_changed
471 {
472 font_run.len += run_len_within_line;
473 } else {
474 font_runs.push(FontRun {
475 len: run_len_within_line,
476 font_id,
477 });
478 }
479
480 run.len -= run_len_within_line;
482 if run.len == 0 {
483 runs.next();
484 }
485 run_start += run_len_within_line;
486 }
487
488 let layout = self.line_layout_cache.layout_wrapped_line(
489 &line_text,
490 font_size,
491 &font_runs,
492 wrap_width,
493 max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
494 );
495 wrapped_lines += layout.wrap_boundaries.len();
496
497 lines.push(WrappedLine {
498 layout,
499 decoration_runs,
500 text: line_text,
501 });
502
503 if let Some(run) = runs.peek_mut() {
505 run.len -= 1;
506 if run.len == 0 {
507 runs.next();
508 }
509 }
510 };
511
512 let mut split_lines = text.split('\n');
513
514 if let Some(first_line) = split_lines.next()
516 && let Some(second_line) = split_lines.next()
517 {
518 let mut line_start = 0;
519 process_line(
520 SharedString::new(first_line),
521 line_start,
522 line_start + first_line.len(),
523 );
524 line_start += first_line.len() + '\n'.len_utf8();
525 process_line(
526 SharedString::new(second_line),
527 line_start,
528 line_start + second_line.len(),
529 );
530 for line_text in split_lines {
531 line_start += line_text.len() + '\n'.len_utf8();
532 process_line(
533 SharedString::new(line_text),
534 line_start,
535 line_start + line_text.len(),
536 );
537 }
538 } else {
539 let end = text.len();
540 process_line(text, 0, end);
541 }
542
543 self.font_runs_pool.lock().push(font_runs);
544
545 Ok(lines)
546 }
547
548 pub(crate) fn finish_frame(&self) {
549 self.line_layout_cache.finish_frame()
550 }
551
552 pub fn layout_line(
557 &self,
558 text: &str,
559 font_size: Pixels,
560 runs: &[TextRun],
561 force_width: Option<Pixels>,
562 ) -> Arc<LineLayout> {
563 let mut last_run = None::<&TextRun>;
564 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
565 font_runs.clear();
566
567 for run in runs.iter() {
568 let decoration_changed = if let Some(last_run) = last_run
569 && last_run.color == run.color
570 && last_run.underline == run.underline
571 && last_run.strikethrough == run.strikethrough
572 {
575 false
576 } else {
577 last_run = Some(run);
578 true
579 };
580
581 let font_id = self.resolve_font(&run.font);
582 if let Some(font_run) = font_runs.last_mut()
583 && font_id == font_run.font_id
584 && !decoration_changed
585 {
586 font_run.len += run.len;
587 } else {
588 font_runs.push(FontRun {
589 len: run.len,
590 font_id,
591 });
592 }
593 }
594
595 let layout = self.line_layout_cache.layout_line(
596 &SharedString::new(text),
597 font_size,
598 &font_runs,
599 force_width,
600 );
601
602 self.font_runs_pool.lock().push(font_runs);
603
604 layout
605 }
606}
607
608#[derive(Hash, Eq, PartialEq)]
609struct FontIdWithSize {
610 font_id: FontId,
611 font_size: Pixels,
612}
613
614pub struct LineWrapperHandle {
616 wrapper: Option<LineWrapper>,
617 text_system: Arc<TextSystem>,
618}
619
620impl Drop for LineWrapperHandle {
621 fn drop(&mut self) {
622 let mut state = self.text_system.wrapper_pool.lock();
623 let wrapper = self.wrapper.take().unwrap();
624 state
625 .get_mut(&FontIdWithSize {
626 font_id: wrapper.font_id,
627 font_size: wrapper.font_size,
628 })
629 .unwrap()
630 .push(wrapper);
631 }
632}
633
634impl Deref for LineWrapperHandle {
635 type Target = LineWrapper;
636
637 fn deref(&self) -> &Self::Target {
638 self.wrapper.as_ref().unwrap()
639 }
640}
641
642impl DerefMut for LineWrapperHandle {
643 fn deref_mut(&mut self) -> &mut Self::Target {
644 self.wrapper.as_mut().unwrap()
645 }
646}
647
648#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
651#[serde(transparent)]
652pub struct FontWeight(pub f32);
653
654impl Display for FontWeight {
655 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
656 write!(f, "{}", self.0)
657 }
658}
659
660impl From<f32> for FontWeight {
661 fn from(weight: f32) -> Self {
662 FontWeight(weight)
663 }
664}
665
666impl Default for FontWeight {
667 #[inline]
668 fn default() -> FontWeight {
669 FontWeight::NORMAL
670 }
671}
672
673impl Hash for FontWeight {
674 fn hash<H: Hasher>(&self, state: &mut H) {
675 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
676 }
677}
678
679impl Eq for FontWeight {}
680
681impl FontWeight {
682 pub const THIN: FontWeight = FontWeight(100.0);
684 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
686 pub const LIGHT: FontWeight = FontWeight(300.0);
688 pub const NORMAL: FontWeight = FontWeight(400.0);
690 pub const MEDIUM: FontWeight = FontWeight(500.0);
692 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
694 pub const BOLD: FontWeight = FontWeight(700.0);
696 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
698 pub const BLACK: FontWeight = FontWeight(900.0);
700
701 pub const ALL: [FontWeight; 9] = [
703 Self::THIN,
704 Self::EXTRA_LIGHT,
705 Self::LIGHT,
706 Self::NORMAL,
707 Self::MEDIUM,
708 Self::SEMIBOLD,
709 Self::BOLD,
710 Self::EXTRA_BOLD,
711 Self::BLACK,
712 ];
713}
714
715impl schemars::JsonSchema for FontWeight {
716 fn schema_name() -> std::borrow::Cow<'static, str> {
717 "FontWeight".into()
718 }
719
720 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
721 use schemars::json_schema;
722 json_schema!({
723 "type": "number",
724 "minimum": Self::THIN,
725 "maximum": Self::BLACK,
726 "default": Self::default(),
727 "description": "Font weight value between 100 (thin) and 900 (black)"
728 })
729 }
730}
731
732#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
734pub enum FontStyle {
735 #[default]
737 Normal,
738 Italic,
740 Oblique,
742}
743
744impl Display for FontStyle {
745 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
746 Debug::fmt(self, f)
747 }
748}
749
750#[derive(Clone, Debug, PartialEq, Eq, Default)]
752pub struct TextRun {
753 pub len: usize,
755 pub font: Font,
757 pub color: Hsla,
759 pub background_color: Option<Hsla>,
761 pub underline: Option<UnderlineStyle>,
763 pub strikethrough: Option<StrikethroughStyle>,
765}
766
767#[cfg(all(target_os = "macos", test))]
768impl TextRun {
769 fn with_len(&self, len: usize) -> Self {
770 let mut this = self.clone();
771 this.len = len;
772 this
773 }
774}
775
776#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
778#[repr(C)]
779pub struct GlyphId(pub(crate) u32);
780
781#[derive(Clone, Debug, PartialEq)]
782pub(crate) struct RenderGlyphParams {
783 pub(crate) font_id: FontId,
784 pub(crate) glyph_id: GlyphId,
785 pub(crate) font_size: Pixels,
786 pub(crate) subpixel_variant: Point<u8>,
787 pub(crate) scale_factor: f32,
788 pub(crate) is_emoji: bool,
789 pub(crate) subpixel_rendering: bool,
790}
791
792impl Eq for RenderGlyphParams {}
793
794impl Hash for RenderGlyphParams {
795 fn hash<H: Hasher>(&self, state: &mut H) {
796 self.font_id.0.hash(state);
797 self.glyph_id.0.hash(state);
798 self.font_size.0.to_bits().hash(state);
799 self.subpixel_variant.hash(state);
800 self.scale_factor.to_bits().hash(state);
801 self.is_emoji.hash(state);
802 self.subpixel_rendering.hash(state);
803 }
804}
805
806#[derive(Clone, Debug, Eq, PartialEq, Hash)]
808pub struct Font {
809 pub family: SharedString,
813
814 pub features: FontFeatures,
816
817 pub fallbacks: Option<FontFallbacks>,
819
820 pub weight: FontWeight,
822
823 pub style: FontStyle,
825}
826
827impl Default for Font {
828 fn default() -> Self {
829 font(".SystemUIFont")
830 }
831}
832
833pub fn font(family: impl Into<SharedString>) -> Font {
835 Font {
836 family: family.into(),
837 features: FontFeatures::default(),
838 weight: FontWeight::default(),
839 style: FontStyle::default(),
840 fallbacks: None,
841 }
842}
843
844impl Font {
845 pub fn bold(mut self) -> Self {
847 self.weight = FontWeight::BOLD;
848 self
849 }
850
851 pub fn italic(mut self) -> Self {
853 self.style = FontStyle::Italic;
854 self
855 }
856}
857
858#[derive(Clone, Copy, Debug)]
861pub struct FontMetrics {
862 pub(crate) units_per_em: u32,
865
866 pub(crate) ascent: f32,
868
869 pub(crate) descent: f32,
871
872 pub(crate) line_gap: f32,
874
875 pub(crate) underline_position: f32,
877
878 pub(crate) underline_thickness: f32,
880
881 pub(crate) cap_height: f32,
883
884 pub(crate) x_height: f32,
886
887 pub(crate) bounding_box: Bounds<f32>,
890}
891
892impl FontMetrics {
893 pub fn ascent(&self, font_size: Pixels) -> Pixels {
895 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
896 }
897
898 pub fn descent(&self, font_size: Pixels) -> Pixels {
900 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
901 }
902
903 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
905 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
906 }
907
908 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
910 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
911 }
912
913 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
915 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
916 }
917
918 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
920 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
921 }
922
923 pub fn x_height(&self, font_size: Pixels) -> Pixels {
925 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
926 }
927
928 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
930 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
931 }
932}
933
934#[allow(unused)]
935pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
936 match name {
940 ".SystemUIFont" => system,
941 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
942 ".ZedMono" | "Zed Plex Mono" => "Lilex",
943 _ => name,
944 }
945}