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