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::Deref;
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/// An opaque identifier for a specific font.
36#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
37#[repr(C)]
38pub struct FontId(pub usize);
39
40/// An opaque identifier for a specific font family.
41#[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 = if cfg!(target_os = "windows") {
47 1
48} else {
49 SUBPIXEL_VARIANTS_X
50};
51
52/// The GPUI text rendering sub system.
53pub struct TextSystem {
54 platform_text_system: Arc<dyn PlatformTextSystem>,
55 font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
56 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
57 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
58 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
59 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
60 fallback_font_stack: SmallVec<[Font; 2]>,
61}
62
63impl TextSystem {
64 pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
65 TextSystem {
66 platform_text_system,
67 font_metrics: RwLock::default(),
68 raster_bounds: RwLock::default(),
69 font_ids_by_font: RwLock::default(),
70 wrapper_pool: Mutex::default(),
71 font_runs_pool: Mutex::default(),
72 fallback_font_stack: smallvec![
73 // TODO: Remove this when Linux have implemented setting fallbacks.
74 font(".ZedMono"),
75 font("Helvetica"),
76 font("Segoe UI"), // Windows
77 font("Cantarell"), // Gnome
78 font("Ubuntu"), // Gnome (Ubuntu)
79 font("Noto Sans"), // KDE
80 font("DejaVu Sans")
81 ],
82 }
83 }
84
85 /// Get a list of all available font names from the operating system.
86 pub fn all_font_names(&self) -> Vec<String> {
87 let mut names = self.platform_text_system.all_font_names();
88 names.extend(
89 self.fallback_font_stack
90 .iter()
91 .map(|font| font.family.to_string()),
92 );
93 names.push(".SystemUIFont".to_string());
94 names.sort();
95 names.dedup();
96 names
97 }
98
99 /// Add a font's data to the text system.
100 pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
101 self.platform_text_system.add_fonts(fonts)
102 }
103
104 /// Get the FontId for the configure font family and style.
105 fn font_id(&self, font: &Font) -> Result<FontId> {
106 fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
107 match font_id {
108 Ok(font_id) => Ok(*font_id),
109 Err(err) => Err(anyhow!("{err}")),
110 }
111 }
112
113 let font_id = self
114 .font_ids_by_font
115 .read()
116 .get(font)
117 .map(clone_font_id_result);
118 if let Some(font_id) = font_id {
119 font_id
120 } else {
121 let font_id = self.platform_text_system.font_id(font);
122 self.font_ids_by_font
123 .write()
124 .insert(font.clone(), clone_font_id_result(&font_id));
125 font_id
126 }
127 }
128
129 /// Get the Font for the Font Id.
130 pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
131 let lock = self.font_ids_by_font.read();
132 lock.iter()
133 .filter_map(|(font, result)| match result {
134 Ok(font_id) if *font_id == id => Some(font.clone()),
135 _ => None,
136 })
137 .next()
138 }
139
140 /// Resolves the specified font, falling back to the default font stack if
141 /// the font fails to load.
142 ///
143 /// # Panics
144 ///
145 /// Panics if the font and none of the fallbacks can be resolved.
146 pub fn resolve_font(&self, font: &Font) -> FontId {
147 if let Ok(font_id) = self.font_id(font) {
148 return font_id;
149 }
150 for fallback in &self.fallback_font_stack {
151 if let Ok(font_id) = self.font_id(fallback) {
152 return font_id;
153 }
154 }
155
156 panic!(
157 "failed to resolve font '{}' or any of the fallbacks: {}",
158 font.family,
159 self.fallback_font_stack
160 .iter()
161 .map(|fallback| &fallback.family)
162 .join(", ")
163 );
164 }
165
166 /// Get the bounding box for the given font and font size.
167 /// A font's bounding box is the smallest rectangle that could enclose all glyphs
168 /// in the font. superimposed over one another.
169 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
170 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
171 }
172
173 /// Get the typographic bounds for the given character, in the given font and size.
174 pub fn typographic_bounds(
175 &self,
176 font_id: FontId,
177 font_size: Pixels,
178 character: char,
179 ) -> Result<Bounds<Pixels>> {
180 let glyph_id = self
181 .platform_text_system
182 .glyph_for_char(font_id, character)
183 .with_context(|| format!("glyph not found for character '{character}'"))?;
184 let bounds = self
185 .platform_text_system
186 .typographic_bounds(font_id, glyph_id)?;
187 Ok(self.read_metrics(font_id, |metrics| {
188 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
189 }))
190 }
191
192 /// Get the advance width for the given character, in the given font and size.
193 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
194 let glyph_id = self
195 .platform_text_system
196 .glyph_for_char(font_id, ch)
197 .with_context(|| format!("glyph not found for character '{ch}'"))?;
198 let result = self.platform_text_system.advance(font_id, glyph_id)?
199 / self.units_per_em(font_id) as f32;
200
201 Ok(result * font_size)
202 }
203
204 /// Returns the width of an `em`.
205 ///
206 /// Uses the width of the `m` character in the given font and size.
207 pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
208 Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
209 }
210
211 /// Returns the advance width of an `em`.
212 ///
213 /// Uses the advance width of the `m` character in the given font and size.
214 pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
215 Ok(self.advance(font_id, font_size, 'm')?.width)
216 }
217
218 /// Returns the width of an `ch`.
219 ///
220 /// Uses the width of the `0` character in the given font and size.
221 pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
222 Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
223 }
224
225 /// Returns the advance width of an `ch`.
226 ///
227 /// Uses the advance width of the `0` character in the given font and size.
228 pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
229 Ok(self.advance(font_id, font_size, '0')?.width)
230 }
231
232 /// Get the number of font size units per 'em square',
233 /// Per MDN: "an abstract square whose height is the intended distance between
234 /// lines of type in the same type size"
235 pub fn units_per_em(&self, font_id: FontId) -> u32 {
236 self.read_metrics(font_id, |metrics| metrics.units_per_em)
237 }
238
239 /// Get the height of a capital letter in the given font and size.
240 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
241 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
242 }
243
244 /// Get the height of the x character in the given font and size.
245 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
246 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
247 }
248
249 /// Get the recommended distance from the baseline for the given font
250 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
251 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
252 }
253
254 /// Get the recommended distance below the baseline for the given font,
255 /// in single spaced text.
256 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
257 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
258 }
259
260 /// Get the recommended baseline offset for the given font and line height.
261 pub fn baseline_offset(
262 &self,
263 font_id: FontId,
264 font_size: Pixels,
265 line_height: Pixels,
266 ) -> Pixels {
267 let ascent = self.ascent(font_id, font_size);
268 let descent = self.descent(font_id, font_size);
269 let padding_top = (line_height - ascent - descent) / 2.;
270 padding_top + ascent
271 }
272
273 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
274 let lock = self.font_metrics.upgradable_read();
275
276 if let Some(metrics) = lock.get(&font_id) {
277 read(metrics)
278 } else {
279 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
280 let metrics = lock
281 .entry(font_id)
282 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
283 read(metrics)
284 }
285 }
286
287 /// Returns a handle to a line wrapper, for the given font and font size.
288 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
289 let lock = &mut self.wrapper_pool.lock();
290 let font_id = self.resolve_font(&font);
291 let wrappers = lock
292 .entry(FontIdWithSize { font_id, font_size })
293 .or_default();
294 let wrapper = wrappers.pop().unwrap_or_else(|| {
295 LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
296 });
297
298 LineWrapperHandle {
299 wrapper: Some(wrapper),
300 text_system: self.clone(),
301 }
302 }
303
304 /// Get the rasterized size and location of a specific, rendered glyph.
305 pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
306 let raster_bounds = self.raster_bounds.upgradable_read();
307 if let Some(bounds) = raster_bounds.get(params) {
308 Ok(*bounds)
309 } else {
310 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
311 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
312 raster_bounds.insert(params.clone(), bounds);
313 Ok(bounds)
314 }
315 }
316
317 pub(crate) fn rasterize_glyph(
318 &self,
319 params: &RenderGlyphParams,
320 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
321 let raster_bounds = self.raster_bounds(params)?;
322 self.platform_text_system
323 .rasterize_glyph(params, raster_bounds)
324 }
325}
326
327/// The GPUI text layout subsystem.
328#[derive(Deref)]
329pub struct WindowTextSystem {
330 line_layout_cache: LineLayoutCache,
331 #[deref]
332 text_system: Arc<TextSystem>,
333}
334
335impl WindowTextSystem {
336 pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
337 Self {
338 line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
339 text_system,
340 }
341 }
342
343 pub(crate) fn layout_index(&self) -> LineLayoutIndex {
344 self.line_layout_cache.layout_index()
345 }
346
347 pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
348 self.line_layout_cache.reuse_layouts(index)
349 }
350
351 pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
352 self.line_layout_cache.truncate_layouts(index)
353 }
354
355 /// Shape the given line, at the given font_size, for painting to the screen.
356 /// Subsets of the line can be styled independently with the `runs` parameter.
357 ///
358 /// Note that this method can only shape a single line of text. It will panic
359 /// if the text contains newlines. If you need to shape multiple lines of text,
360 /// use [`Self::shape_text`] instead.
361 pub fn shape_line(
362 &self,
363 text: SharedString,
364 font_size: Pixels,
365 runs: &[TextRun],
366 force_width: Option<Pixels>,
367 ) -> ShapedLine {
368 debug_assert!(
369 text.find('\n').is_none(),
370 "text argument should not contain newlines"
371 );
372
373 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
374 for run in runs {
375 if let Some(last_run) = decoration_runs.last_mut()
376 && last_run.color == run.color
377 && last_run.underline == run.underline
378 && last_run.strikethrough == run.strikethrough
379 && last_run.background_color == run.background_color
380 {
381 last_run.len += run.len as u32;
382 continue;
383 }
384 decoration_runs.push(DecorationRun {
385 len: run.len as u32,
386 color: run.color,
387 background_color: run.background_color,
388 underline: run.underline,
389 strikethrough: run.strikethrough,
390 });
391 }
392
393 let layout = self.layout_line(&text, font_size, runs, force_width);
394
395 ShapedLine {
396 layout,
397 text,
398 decoration_runs,
399 }
400 }
401
402 /// Shape a multi line string of text, at the given font_size, for painting to the screen.
403 /// Subsets of the text can be styled independently with the `runs` parameter.
404 /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
405 pub fn shape_text(
406 &self,
407 text: SharedString,
408 font_size: Pixels,
409 runs: &[TextRun],
410 wrap_width: Option<Pixels>,
411 line_clamp: Option<usize>,
412 ) -> Result<SmallVec<[WrappedLine; 1]>> {
413 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
414 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
415
416 let mut lines = SmallVec::new();
417 let mut line_start = 0;
418 let mut max_wrap_lines = line_clamp.unwrap_or(usize::MAX);
419 let mut wrapped_lines = 0;
420
421 let mut process_line = |line_text: SharedString| {
422 let line_end = line_start + line_text.len();
423
424 let mut last_font: Option<Font> = None;
425 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
426 let mut run_start = line_start;
427 while run_start < line_end {
428 let Some(run) = runs.peek_mut() else {
429 break;
430 };
431
432 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
433
434 if last_font == Some(run.font.clone()) {
435 font_runs.last_mut().unwrap().len += run_len_within_line;
436 } else {
437 last_font = Some(run.font.clone());
438 font_runs.push(FontRun {
439 len: run_len_within_line,
440 font_id: self.resolve_font(&run.font),
441 });
442 }
443
444 if decoration_runs.last().is_some_and(|last_run| {
445 last_run.color == run.color
446 && last_run.underline == run.underline
447 && last_run.strikethrough == run.strikethrough
448 && last_run.background_color == run.background_color
449 }) {
450 decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
451 } else {
452 decoration_runs.push(DecorationRun {
453 len: run_len_within_line as u32,
454 color: run.color,
455 background_color: run.background_color,
456 underline: run.underline,
457 strikethrough: run.strikethrough,
458 });
459 }
460
461 if run_len_within_line == run.len {
462 runs.next();
463 } else {
464 // Preserve the remainder of the run for the next line
465 run.len -= run_len_within_line;
466 }
467 run_start += run_len_within_line;
468 }
469
470 let layout = self.line_layout_cache.layout_wrapped_line(
471 &line_text,
472 font_size,
473 &font_runs,
474 wrap_width,
475 Some(max_wrap_lines - wrapped_lines),
476 );
477 wrapped_lines += layout.wrap_boundaries.len();
478
479 lines.push(WrappedLine {
480 layout,
481 decoration_runs,
482 text: line_text,
483 });
484
485 // Skip `\n` character.
486 line_start = line_end + 1;
487 if let Some(run) = runs.peek_mut() {
488 run.len -= 1;
489 if run.len == 0 {
490 runs.next();
491 }
492 }
493
494 font_runs.clear();
495 };
496
497 let mut split_lines = text.split('\n');
498 let mut processed = false;
499
500 if let Some(first_line) = split_lines.next()
501 && let Some(second_line) = split_lines.next()
502 {
503 processed = true;
504 process_line(first_line.to_string().into());
505 process_line(second_line.to_string().into());
506 for line_text in split_lines {
507 process_line(line_text.to_string().into());
508 }
509 }
510
511 if !processed {
512 process_line(text);
513 }
514
515 self.font_runs_pool.lock().push(font_runs);
516
517 Ok(lines)
518 }
519
520 pub(crate) fn finish_frame(&self) {
521 self.line_layout_cache.finish_frame()
522 }
523
524 /// Layout the given line of text, at the given font_size.
525 /// Subsets of the line can be styled independently with the `runs` parameter.
526 /// Generally, you should prefer to use [`Self::shape_line`] instead, which
527 /// can be painted directly.
528 pub fn layout_line<Text>(
529 &self,
530 text: Text,
531 font_size: Pixels,
532 runs: &[TextRun],
533 force_width: Option<Pixels>,
534 ) -> Arc<LineLayout>
535 where
536 Text: AsRef<str>,
537 SharedString: From<Text>,
538 {
539 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
540 for run in runs.iter() {
541 let font_id = self.resolve_font(&run.font);
542 if let Some(last_run) = font_runs.last_mut()
543 && last_run.font_id == font_id
544 {
545 last_run.len += run.len;
546 continue;
547 }
548 font_runs.push(FontRun {
549 len: run.len,
550 font_id,
551 });
552 }
553
554 let layout =
555 self.line_layout_cache
556 .layout_line_internal(text, font_size, &font_runs, force_width);
557
558 font_runs.clear();
559 self.font_runs_pool.lock().push(font_runs);
560
561 layout
562 }
563}
564
565#[derive(Hash, Eq, PartialEq)]
566struct FontIdWithSize {
567 font_id: FontId,
568 font_size: Pixels,
569}
570
571/// A handle into the text system, which can be used to compute the wrapped layout of text
572pub struct LineWrapperHandle {
573 wrapper: Option<LineWrapper>,
574 text_system: Arc<TextSystem>,
575}
576
577impl Drop for LineWrapperHandle {
578 fn drop(&mut self) {
579 let mut state = self.text_system.wrapper_pool.lock();
580 let wrapper = self.wrapper.take().unwrap();
581 state
582 .get_mut(&FontIdWithSize {
583 font_id: wrapper.font_id,
584 font_size: wrapper.font_size,
585 })
586 .unwrap()
587 .push(wrapper);
588 }
589}
590
591impl Deref for LineWrapperHandle {
592 type Target = LineWrapper;
593
594 fn deref(&self) -> &Self::Target {
595 self.wrapper.as_ref().unwrap()
596 }
597}
598
599impl DerefMut for LineWrapperHandle {
600 fn deref_mut(&mut self) -> &mut Self::Target {
601 self.wrapper.as_mut().unwrap()
602 }
603}
604
605/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
606/// with 400.0 as normal.
607#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, JsonSchema)]
608pub struct FontWeight(pub f32);
609
610impl Default for FontWeight {
611 #[inline]
612 fn default() -> FontWeight {
613 FontWeight::NORMAL
614 }
615}
616
617impl Hash for FontWeight {
618 fn hash<H: Hasher>(&self, state: &mut H) {
619 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
620 }
621}
622
623impl Eq for FontWeight {}
624
625impl FontWeight {
626 /// Thin weight (100), the thinnest value.
627 pub const THIN: FontWeight = FontWeight(100.0);
628 /// Extra light weight (200).
629 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
630 /// Light weight (300).
631 pub const LIGHT: FontWeight = FontWeight(300.0);
632 /// Normal (400).
633 pub const NORMAL: FontWeight = FontWeight(400.0);
634 /// Medium weight (500, higher than normal).
635 pub const MEDIUM: FontWeight = FontWeight(500.0);
636 /// Semibold weight (600).
637 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
638 /// Bold weight (700).
639 pub const BOLD: FontWeight = FontWeight(700.0);
640 /// Extra-bold weight (800).
641 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
642 /// Black weight (900), the thickest value.
643 pub const BLACK: FontWeight = FontWeight(900.0);
644
645 /// All of the font weights, in order from thinnest to thickest.
646 pub const ALL: [FontWeight; 9] = [
647 Self::THIN,
648 Self::EXTRA_LIGHT,
649 Self::LIGHT,
650 Self::NORMAL,
651 Self::MEDIUM,
652 Self::SEMIBOLD,
653 Self::BOLD,
654 Self::EXTRA_BOLD,
655 Self::BLACK,
656 ];
657}
658
659/// Allows italic or oblique faces to be selected.
660#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
661pub enum FontStyle {
662 /// A face that is neither italic not obliqued.
663 #[default]
664 Normal,
665 /// A form that is generally cursive in nature.
666 Italic,
667 /// A typically-sloped version of the regular face.
668 Oblique,
669}
670
671impl Display for FontStyle {
672 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
673 Debug::fmt(self, f)
674 }
675}
676
677/// A styled run of text, for use in [`crate::TextLayout`].
678#[derive(Clone, Debug, PartialEq, Eq)]
679pub struct TextRun {
680 /// A number of utf8 bytes
681 pub len: usize,
682 /// The font to use for this run.
683 pub font: Font,
684 /// The color
685 pub color: Hsla,
686 /// The background color (if any)
687 pub background_color: Option<Hsla>,
688 /// The underline style (if any)
689 pub underline: Option<UnderlineStyle>,
690 /// The strikethrough style (if any)
691 pub strikethrough: Option<StrikethroughStyle>,
692}
693
694#[cfg(all(target_os = "macos", test))]
695impl TextRun {
696 fn with_len(&self, len: usize) -> Self {
697 let mut this = self.clone();
698 this.len = len;
699 this
700 }
701}
702
703/// An identifier for a specific glyph, as returned by [`WindowTextSystem::layout_line`].
704#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
705#[repr(C)]
706pub struct GlyphId(pub(crate) u32);
707
708#[derive(Clone, Debug, PartialEq)]
709pub(crate) struct RenderGlyphParams {
710 pub(crate) font_id: FontId,
711 pub(crate) glyph_id: GlyphId,
712 pub(crate) font_size: Pixels,
713 pub(crate) subpixel_variant: Point<u8>,
714 pub(crate) scale_factor: f32,
715 pub(crate) is_emoji: bool,
716}
717
718impl Eq for RenderGlyphParams {}
719
720impl Hash for RenderGlyphParams {
721 fn hash<H: Hasher>(&self, state: &mut H) {
722 self.font_id.0.hash(state);
723 self.glyph_id.0.hash(state);
724 self.font_size.0.to_bits().hash(state);
725 self.subpixel_variant.hash(state);
726 self.scale_factor.to_bits().hash(state);
727 self.is_emoji.hash(state);
728 }
729}
730
731/// The configuration details for identifying a specific font.
732#[derive(Clone, Debug, Eq, PartialEq, Hash)]
733pub struct Font {
734 /// The font family name.
735 ///
736 /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
737 pub family: SharedString,
738
739 /// The font features to use.
740 pub features: FontFeatures,
741
742 /// The fallbacks fonts to use.
743 pub fallbacks: Option<FontFallbacks>,
744
745 /// The font weight.
746 pub weight: FontWeight,
747
748 /// The font style.
749 pub style: FontStyle,
750}
751
752/// Get a [`Font`] for a given name.
753pub fn font(family: impl Into<SharedString>) -> Font {
754 Font {
755 family: family.into(),
756 features: FontFeatures::default(),
757 weight: FontWeight::default(),
758 style: FontStyle::default(),
759 fallbacks: None,
760 }
761}
762
763impl Font {
764 /// Set this Font to be bold
765 pub fn bold(mut self) -> Self {
766 self.weight = FontWeight::BOLD;
767 self
768 }
769
770 /// Set this Font to be italic
771 pub fn italic(mut self) -> Self {
772 self.style = FontStyle::Italic;
773 self
774 }
775}
776
777/// A struct for storing font metrics.
778/// It is used to define the measurements of a typeface.
779#[derive(Clone, Copy, Debug)]
780pub struct FontMetrics {
781 /// The number of font units that make up the "em square",
782 /// a scalable grid for determining the size of a typeface.
783 pub(crate) units_per_em: u32,
784
785 /// The vertical distance from the baseline of the font to the top of the glyph covers.
786 pub(crate) ascent: f32,
787
788 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
789 pub(crate) descent: f32,
790
791 /// The recommended additional space to add between lines of type.
792 pub(crate) line_gap: f32,
793
794 /// The suggested position of the underline.
795 pub(crate) underline_position: f32,
796
797 /// The suggested thickness of the underline.
798 pub(crate) underline_thickness: f32,
799
800 /// The height of a capital letter measured from the baseline of the font.
801 pub(crate) cap_height: f32,
802
803 /// The height of a lowercase x.
804 pub(crate) x_height: f32,
805
806 /// The outer limits of the area that the font covers.
807 /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
808 pub(crate) bounding_box: Bounds<f32>,
809}
810
811impl FontMetrics {
812 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
813 pub fn ascent(&self, font_size: Pixels) -> Pixels {
814 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
815 }
816
817 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
818 pub fn descent(&self, font_size: Pixels) -> Pixels {
819 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
820 }
821
822 /// Returns the recommended additional space to add between lines of type in pixels.
823 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
824 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
825 }
826
827 /// Returns the suggested position of the underline in pixels.
828 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
829 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
830 }
831
832 /// Returns the suggested thickness of the underline in pixels.
833 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
834 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
835 }
836
837 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
838 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
839 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
840 }
841
842 /// Returns the height of a lowercase x in pixels.
843 pub fn x_height(&self, font_size: Pixels) -> Pixels {
844 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
845 }
846
847 /// Returns the outer limits of the area that the font covers in pixels.
848 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
849 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
850 }
851}
852
853#[allow(unused)]
854pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
855 // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
856 // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
857 // and so retained here for backward compatibility.
858 match name {
859 ".SystemUIFont" => system,
860 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
861 ".ZedMono" | "Zed Plex Mono" => "Lilex",
862 _ => name,
863 }
864}