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, 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 global_line_layout_cache: Arc<GlobalLineLayoutCache>,
57 font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
58 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
59 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
60 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
61 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
62 fallback_font_stack: SmallVec<[Font; 2]>,
63}
64
65impl TextSystem {
66 pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
67 TextSystem {
68 platform_text_system,
69 global_line_layout_cache: Arc::new(GlobalLineLayoutCache::new()),
70 font_metrics: RwLock::default(),
71 raster_bounds: RwLock::default(),
72 font_ids_by_font: RwLock::default(),
73 wrapper_pool: Mutex::default(),
74 font_runs_pool: Mutex::default(),
75 fallback_font_stack: smallvec![
76 font(".ZedMono"),
78 font(".ZedSans"),
79 font("Helvetica"),
80 font("Segoe UI"), font("Cantarell"), font("Ubuntu"), font("Noto Sans"), font("DejaVu Sans")
85 ],
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
331#[derive(Deref)]
333pub struct WindowTextSystem {
334 line_layout_cache: LineLayoutCache,
335 #[deref]
336 text_system: Arc<TextSystem>,
337}
338
339impl WindowTextSystem {
340 pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
341 Self {
342 line_layout_cache: LineLayoutCache::new(
343 text_system.platform_text_system.clone(),
344 text_system.global_line_layout_cache.clone(),
345 ),
346 text_system,
347 }
348 }
349
350 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
351 self.line_layout_cache.layout_index()
352 }
353
354 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
355 self.line_layout_cache.reuse_layouts(index)
356 }
357
358 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
359 self.line_layout_cache.truncate_layouts(index)
360 }
361
362 pub fn shape_line(
369 &self,
370 text: SharedString,
371 font_size: Pixels,
372 runs: &[TextRun],
373 force_width: Option<Pixels>,
374 ) -> ShapedLine {
375 self.shape_line_with_spacing(text, font_size, runs, force_width, None)
376 }
377
378 pub fn shape_line_with_spacing(
380 &self,
381 text: SharedString,
382 font_size: Pixels,
383 runs: &[TextRun],
384 force_width: Option<Pixels>,
385 letter_spacing: Option<Pixels>,
386 ) -> ShapedLine {
387 debug_assert!(
388 text.find('\n').is_none(),
389 "text argument should not contain newlines"
390 );
391
392 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
393 for run in runs {
394 if let Some(last_run) = decoration_runs.last_mut()
395 && last_run.color == run.color
396 && last_run.underline == run.underline
397 && last_run.strikethrough == run.strikethrough
398 && last_run.background_color == run.background_color
399 {
400 last_run.len += run.len as u32;
401 continue;
402 }
403 decoration_runs.push(DecorationRun {
404 len: run.len as u32,
405 color: run.color,
406 background_color: run.background_color,
407 underline: run.underline,
408 strikethrough: run.strikethrough,
409 });
410 }
411
412 let layout =
413 self.layout_line_with_spacing(&text, font_size, runs, force_width, letter_spacing);
414
415 ShapedLine {
416 layout,
417 text,
418 decoration_runs,
419 }
420 }
421
422 pub fn shape_text(
426 &self,
427 text: SharedString,
428 font_size: Pixels,
429 runs: &[TextRun],
430 wrap_width: Option<Pixels>,
431 line_clamp: Option<usize>,
432 ) -> Result<SmallVec<[WrappedLine; 1]>> {
433 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
434 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
435
436 let mut lines = SmallVec::new();
437 let mut line_start = 0;
438 let mut max_wrap_lines = line_clamp.unwrap_or(usize::MAX);
439 let mut wrapped_lines = 0;
440
441 let mut process_line = |line_text: SharedString| {
442 font_runs.clear();
443 let line_end = line_start + line_text.len();
444
445 let mut last_font: Option<FontId> = None;
446 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
447 let mut run_start = line_start;
448 while run_start < line_end {
449 let Some(run) = runs.peek_mut() else {
450 break;
451 };
452
453 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
454
455 let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
456 && last_run.color == run.color
457 && last_run.underline == run.underline
458 && last_run.strikethrough == run.strikethrough
459 && last_run.background_color == run.background_color
460 {
461 last_run.len += run_len_within_line as u32;
462 false
463 } else {
464 decoration_runs.push(DecorationRun {
465 len: run_len_within_line as u32,
466 color: run.color,
467 background_color: run.background_color,
468 underline: run.underline,
469 strikethrough: run.strikethrough,
470 });
471 true
472 };
473
474 if let Some(font_run) = font_runs.last_mut()
475 && Some(font_run.font_id) == last_font
476 && !decoration_changed
477 {
478 font_run.len += run_len_within_line;
479 } else {
480 let font_id = self.resolve_font(&run.font);
481 last_font = Some(font_id);
482 font_runs.push(FontRun {
483 len: run_len_within_line,
484 font_id,
485 });
486 }
487
488 if run_len_within_line == run.len {
489 runs.next();
490 } else {
491 run.len -= run_len_within_line;
493 }
494 run_start += run_len_within_line;
495 }
496
497 let layout = self.line_layout_cache.layout_wrapped_line(
498 &line_text,
499 font_size,
500 &font_runs,
501 wrap_width,
502 Some(max_wrap_lines - wrapped_lines),
503 );
504 wrapped_lines += layout.wrap_boundaries.len();
505
506 lines.push(WrappedLine {
507 layout,
508 decoration_runs,
509 text: line_text,
510 });
511
512 line_start = line_end + 1;
514 if let Some(run) = runs.peek_mut() {
515 run.len -= 1;
516 if run.len == 0 {
517 runs.next();
518 }
519 }
520 };
521
522 let mut split_lines = text.split('\n');
523 let mut processed = false;
524
525 if let Some(first_line) = split_lines.next()
526 && let Some(second_line) = split_lines.next()
527 {
528 processed = true;
529 process_line(first_line.to_string().into());
530 process_line(second_line.to_string().into());
531 for line_text in split_lines {
532 process_line(line_text.to_string().into());
533 }
534 }
535
536 if !processed {
537 process_line(text);
538 }
539
540 self.font_runs_pool.lock().push(font_runs);
541
542 Ok(lines)
543 }
544
545 pub(crate) fn finish_frame(&self) {
546 self.line_layout_cache.finish_frame()
547 }
548
549 pub fn layout_line(
554 &self,
555 text: &str,
556 font_size: Pixels,
557 runs: &[TextRun],
558 force_width: Option<Pixels>,
559 ) -> Arc<LineLayout> {
560 self.layout_line_with_spacing(text, font_size, runs, force_width, None)
561 }
562
563 pub fn layout_line_with_spacing(
565 &self,
566 text: &str,
567 font_size: Pixels,
568 runs: &[TextRun],
569 force_width: Option<Pixels>,
570 letter_spacing: Option<Pixels>,
571 ) -> Arc<LineLayout> {
572 let mut last_run = None::<&TextRun>;
573 let mut last_font: Option<FontId> = None;
574 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
575 font_runs.clear();
576
577 for run in runs.iter() {
578 let decoration_changed = if let Some(last_run) = last_run
579 && last_run.color == run.color
580 && last_run.underline == run.underline
581 && last_run.strikethrough == run.strikethrough
582 {
583 false
584 } else {
585 last_run = Some(run);
586 true
587 };
588
589 if let Some(font_run) = font_runs.last_mut()
590 && Some(font_run.font_id) == last_font
591 && !decoration_changed
592 {
593 font_run.len += run.len;
594 } else {
595 let font_id = self.resolve_font(&run.font);
596 last_font = Some(font_id);
597 font_runs.push(FontRun {
598 len: run.len,
599 font_id,
600 });
601 }
602 }
603
604 let layout = self.line_layout_cache.layout_line_with_spacing(
605 &SharedString::new(text),
606 font_size,
607 &font_runs,
608 force_width,
609 letter_spacing,
610 );
611
612 self.font_runs_pool.lock().push(font_runs);
613
614 layout
615 }
616}
617
618#[derive(Hash, Eq, PartialEq)]
619struct FontIdWithSize {
620 font_id: FontId,
621 font_size: Pixels,
622}
623
624pub struct LineWrapperHandle {
626 wrapper: Option<LineWrapper>,
627 text_system: Arc<TextSystem>,
628}
629
630impl Drop for LineWrapperHandle {
631 fn drop(&mut self) {
632 let mut state = self.text_system.wrapper_pool.lock();
633 let wrapper = self.wrapper.take().unwrap();
634 state
635 .get_mut(&FontIdWithSize {
636 font_id: wrapper.font_id,
637 font_size: wrapper.font_size,
638 })
639 .unwrap()
640 .push(wrapper);
641 }
642}
643
644impl Deref for LineWrapperHandle {
645 type Target = LineWrapper;
646
647 fn deref(&self) -> &Self::Target {
648 self.wrapper.as_ref().unwrap()
649 }
650}
651
652impl DerefMut for LineWrapperHandle {
653 fn deref_mut(&mut self) -> &mut Self::Target {
654 self.wrapper.as_mut().unwrap()
655 }
656}
657
658#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
661#[serde(transparent)]
662pub struct FontWeight(pub f32);
663
664impl Display for FontWeight {
665 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
666 write!(f, "{}", self.0)
667 }
668}
669
670impl From<f32> for FontWeight {
671 fn from(weight: f32) -> Self {
672 FontWeight(weight)
673 }
674}
675
676impl Default for FontWeight {
677 #[inline]
678 fn default() -> FontWeight {
679 FontWeight::NORMAL
680 }
681}
682
683impl Hash for FontWeight {
684 fn hash<H: Hasher>(&self, state: &mut H) {
685 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
686 }
687}
688
689impl Eq for FontWeight {}
690
691impl FontWeight {
692 pub const THIN: FontWeight = FontWeight(100.0);
694 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
696 pub const LIGHT: FontWeight = FontWeight(300.0);
698 pub const NORMAL: FontWeight = FontWeight(400.0);
700 pub const MEDIUM: FontWeight = FontWeight(500.0);
702 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
704 pub const BOLD: FontWeight = FontWeight(700.0);
706 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
708 pub const BLACK: FontWeight = FontWeight(900.0);
710
711 pub const ALL: [FontWeight; 9] = [
713 Self::THIN,
714 Self::EXTRA_LIGHT,
715 Self::LIGHT,
716 Self::NORMAL,
717 Self::MEDIUM,
718 Self::SEMIBOLD,
719 Self::BOLD,
720 Self::EXTRA_BOLD,
721 Self::BLACK,
722 ];
723}
724
725impl schemars::JsonSchema for FontWeight {
726 fn schema_name() -> std::borrow::Cow<'static, str> {
727 "FontWeight".into()
728 }
729
730 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
731 use schemars::json_schema;
732 json_schema!({
733 "type": "number",
734 "minimum": Self::THIN,
735 "maximum": Self::BLACK,
736 "default": Self::default(),
737 "description": "Font weight value between 100 (thin) and 900 (black)"
738 })
739 }
740}
741
742#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
744pub enum FontStyle {
745 #[default]
747 Normal,
748 Italic,
750 Oblique,
752}
753
754impl Display for FontStyle {
755 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
756 Debug::fmt(self, f)
757 }
758}
759
760#[derive(Clone, Debug, PartialEq, Eq)]
762pub struct TextRun {
763 pub len: usize,
765 pub font: Font,
767 pub color: Hsla,
769 pub background_color: Option<Hsla>,
771 pub underline: Option<UnderlineStyle>,
773 pub strikethrough: Option<StrikethroughStyle>,
775}
776
777#[cfg(all(target_os = "macos", test))]
778impl TextRun {
779 fn with_len(&self, len: usize) -> Self {
780 let mut this = self.clone();
781 this.len = len;
782 this
783 }
784}
785
786#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
788#[repr(C)]
789pub struct GlyphId(pub(crate) u32);
790
791#[derive(Clone, Debug, PartialEq)]
792pub(crate) struct RenderGlyphParams {
793 pub(crate) font_id: FontId,
794 pub(crate) glyph_id: GlyphId,
795 pub(crate) font_size: Pixels,
796 pub(crate) subpixel_variant: Point<u8>,
797 pub(crate) scale_factor: f32,
798 pub(crate) is_emoji: bool,
799}
800
801impl Eq for RenderGlyphParams {}
802
803impl Hash for RenderGlyphParams {
804 fn hash<H: Hasher>(&self, state: &mut H) {
805 self.font_id.0.hash(state);
806 self.glyph_id.0.hash(state);
807 self.font_size.0.to_bits().hash(state);
808 self.subpixel_variant.hash(state);
809 self.scale_factor.to_bits().hash(state);
810 self.is_emoji.hash(state);
811 }
812}
813
814#[derive(Clone, Debug, Eq, PartialEq, Hash)]
816pub struct Font {
817 pub family: SharedString,
821
822 pub features: FontFeatures,
824
825 pub fallbacks: Option<FontFallbacks>,
827
828 pub weight: FontWeight,
830
831 pub style: FontStyle,
833}
834
835pub fn font(family: impl Into<SharedString>) -> Font {
837 Font {
838 family: family.into(),
839 features: FontFeatures::default(),
840 weight: FontWeight::default(),
841 style: FontStyle::default(),
842 fallbacks: None,
843 }
844}
845
846impl Font {
847 pub fn bold(mut self) -> Self {
849 self.weight = FontWeight::BOLD;
850 self
851 }
852
853 pub fn italic(mut self) -> Self {
855 self.style = FontStyle::Italic;
856 self
857 }
858}
859
860#[derive(Clone, Copy, Debug)]
863pub struct FontMetrics {
864 pub(crate) units_per_em: u32,
867
868 pub(crate) ascent: f32,
870
871 pub(crate) descent: f32,
873
874 pub(crate) line_gap: f32,
876
877 pub(crate) underline_position: f32,
879
880 pub(crate) underline_thickness: f32,
882
883 pub(crate) cap_height: f32,
885
886 pub(crate) x_height: f32,
888
889 pub(crate) bounding_box: Bounds<f32>,
892}
893
894impl FontMetrics {
895 pub fn ascent(&self, font_size: Pixels) -> Pixels {
897 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
898 }
899
900 pub fn descent(&self, font_size: Pixels) -> Pixels {
902 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
903 }
904
905 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
907 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
908 }
909
910 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
912 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
913 }
914
915 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
917 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
918 }
919
920 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
922 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
923 }
924
925 pub fn x_height(&self, font_size: Pixels) -> Pixels {
927 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
928 }
929
930 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
932 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
933 }
934}
935
936#[allow(unused)]
937pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
938 match name {
942 ".SystemUIFont" => system,
943 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
944 ".ZedMono" | "Zed Plex Mono" => "Lilex",
945 _ => name,
946 }
947}