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 `TextLayout::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 if 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 }
379 decoration_runs.push(DecorationRun {
380 len: run.len as u32,
381 color: run.color,
382 background_color: run.background_color,
383 underline: run.underline,
384 strikethrough: run.strikethrough,
385 });
386 }
387
388 let layout = self.layout_line(&text, font_size, runs, force_width);
389
390 ShapedLine {
391 layout,
392 text,
393 decoration_runs,
394 }
395 }
396
397 /// Shape a multi line string of text, at the given font_size, for painting to the screen.
398 /// Subsets of the text can be styled independently with the `runs` parameter.
399 /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
400 pub fn shape_text(
401 &self,
402 text: SharedString,
403 font_size: Pixels,
404 runs: &[TextRun],
405 wrap_width: Option<Pixels>,
406 line_clamp: Option<usize>,
407 ) -> Result<SmallVec<[WrappedLine; 1]>> {
408 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
409 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
410
411 let mut lines = SmallVec::new();
412 let mut line_start = 0;
413 let mut max_wrap_lines = line_clamp.unwrap_or(usize::MAX);
414 let mut wrapped_lines = 0;
415
416 let mut process_line = |line_text: SharedString| {
417 let line_end = line_start + line_text.len();
418
419 let mut last_font: Option<Font> = None;
420 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
421 let mut run_start = line_start;
422 while run_start < line_end {
423 let Some(run) = runs.peek_mut() else {
424 break;
425 };
426
427 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
428
429 if last_font == Some(run.font.clone()) {
430 font_runs.last_mut().unwrap().len += run_len_within_line;
431 } else {
432 last_font = Some(run.font.clone());
433 font_runs.push(FontRun {
434 len: run_len_within_line,
435 font_id: self.resolve_font(&run.font),
436 });
437 }
438
439 if decoration_runs.last().map_or(false, |last_run| {
440 last_run.color == run.color
441 && last_run.underline == run.underline
442 && last_run.strikethrough == run.strikethrough
443 && last_run.background_color == run.background_color
444 }) {
445 decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
446 } else {
447 decoration_runs.push(DecorationRun {
448 len: run_len_within_line as u32,
449 color: run.color,
450 background_color: run.background_color,
451 underline: run.underline,
452 strikethrough: run.strikethrough,
453 });
454 }
455
456 if run_len_within_line == run.len {
457 runs.next();
458 } else {
459 // Preserve the remainder of the run for the next line
460 run.len -= run_len_within_line;
461 }
462 run_start += run_len_within_line;
463 }
464
465 let layout = self.line_layout_cache.layout_wrapped_line(
466 &line_text,
467 font_size,
468 &font_runs,
469 wrap_width,
470 Some(max_wrap_lines - wrapped_lines),
471 );
472 wrapped_lines += layout.wrap_boundaries.len();
473
474 lines.push(WrappedLine {
475 layout,
476 decoration_runs,
477 text: line_text,
478 });
479
480 // Skip `\n` character.
481 line_start = line_end + 1;
482 if let Some(run) = runs.peek_mut() {
483 run.len -= 1;
484 if run.len == 0 {
485 runs.next();
486 }
487 }
488
489 font_runs.clear();
490 };
491
492 let mut split_lines = text.split('\n');
493 let mut processed = false;
494
495 if let Some(first_line) = split_lines.next() {
496 if let Some(second_line) = split_lines.next() {
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
506 if !processed {
507 process_line(text);
508 }
509
510 self.font_runs_pool.lock().push(font_runs);
511
512 Ok(lines)
513 }
514
515 pub(crate) fn finish_frame(&self) {
516 self.line_layout_cache.finish_frame()
517 }
518
519 /// Layout the given line of text, at the given font_size.
520 /// Subsets of the line can be styled independently with the `runs` parameter.
521 /// Generally, you should prefer to use `TextLayout::shape_line` instead, which
522 /// can be painted directly.
523 pub fn layout_line<Text>(
524 &self,
525 text: Text,
526 font_size: Pixels,
527 runs: &[TextRun],
528 force_width: Option<Pixels>,
529 ) -> Arc<LineLayout>
530 where
531 Text: AsRef<str>,
532 SharedString: From<Text>,
533 {
534 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
535 for run in runs.iter() {
536 let font_id = self.resolve_font(&run.font);
537 if let Some(last_run) = font_runs.last_mut() {
538 if last_run.font_id == font_id {
539 last_run.len += run.len;
540 continue;
541 }
542 }
543 font_runs.push(FontRun {
544 len: run.len,
545 font_id,
546 });
547 }
548
549 let layout =
550 self.line_layout_cache
551 .layout_line_internal(text, font_size, &font_runs, force_width);
552
553 font_runs.clear();
554 self.font_runs_pool.lock().push(font_runs);
555
556 layout
557 }
558}
559
560#[derive(Hash, Eq, PartialEq)]
561struct FontIdWithSize {
562 font_id: FontId,
563 font_size: Pixels,
564}
565
566/// A handle into the text system, which can be used to compute the wrapped layout of text
567pub struct LineWrapperHandle {
568 wrapper: Option<LineWrapper>,
569 text_system: Arc<TextSystem>,
570}
571
572impl Drop for LineWrapperHandle {
573 fn drop(&mut self) {
574 let mut state = self.text_system.wrapper_pool.lock();
575 let wrapper = self.wrapper.take().unwrap();
576 state
577 .get_mut(&FontIdWithSize {
578 font_id: wrapper.font_id,
579 font_size: wrapper.font_size,
580 })
581 .unwrap()
582 .push(wrapper);
583 }
584}
585
586impl Deref for LineWrapperHandle {
587 type Target = LineWrapper;
588
589 fn deref(&self) -> &Self::Target {
590 self.wrapper.as_ref().unwrap()
591 }
592}
593
594impl DerefMut for LineWrapperHandle {
595 fn deref_mut(&mut self) -> &mut Self::Target {
596 self.wrapper.as_mut().unwrap()
597 }
598}
599
600/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
601/// with 400.0 as normal.
602#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, JsonSchema)]
603pub struct FontWeight(pub f32);
604
605impl Default for FontWeight {
606 #[inline]
607 fn default() -> FontWeight {
608 FontWeight::NORMAL
609 }
610}
611
612impl Hash for FontWeight {
613 fn hash<H: Hasher>(&self, state: &mut H) {
614 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
615 }
616}
617
618impl Eq for FontWeight {}
619
620impl FontWeight {
621 /// Thin weight (100), the thinnest value.
622 pub const THIN: FontWeight = FontWeight(100.0);
623 /// Extra light weight (200).
624 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
625 /// Light weight (300).
626 pub const LIGHT: FontWeight = FontWeight(300.0);
627 /// Normal (400).
628 pub const NORMAL: FontWeight = FontWeight(400.0);
629 /// Medium weight (500, higher than normal).
630 pub const MEDIUM: FontWeight = FontWeight(500.0);
631 /// Semibold weight (600).
632 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
633 /// Bold weight (700).
634 pub const BOLD: FontWeight = FontWeight(700.0);
635 /// Extra-bold weight (800).
636 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
637 /// Black weight (900), the thickest value.
638 pub const BLACK: FontWeight = FontWeight(900.0);
639
640 /// All of the font weights, in order from thinnest to thickest.
641 pub const ALL: [FontWeight; 9] = [
642 Self::THIN,
643 Self::EXTRA_LIGHT,
644 Self::LIGHT,
645 Self::NORMAL,
646 Self::MEDIUM,
647 Self::SEMIBOLD,
648 Self::BOLD,
649 Self::EXTRA_BOLD,
650 Self::BLACK,
651 ];
652}
653
654/// Allows italic or oblique faces to be selected.
655#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
656pub enum FontStyle {
657 /// A face that is neither italic not obliqued.
658 #[default]
659 Normal,
660 /// A form that is generally cursive in nature.
661 Italic,
662 /// A typically-sloped version of the regular face.
663 Oblique,
664}
665
666impl Display for FontStyle {
667 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
668 Debug::fmt(self, f)
669 }
670}
671
672/// A styled run of text, for use in [`TextLayout`].
673#[derive(Clone, Debug, PartialEq, Eq)]
674pub struct TextRun {
675 /// A number of utf8 bytes
676 pub len: usize,
677 /// The font to use for this run.
678 pub font: Font,
679 /// The color
680 pub color: Hsla,
681 /// The background color (if any)
682 pub background_color: Option<Hsla>,
683 /// The underline style (if any)
684 pub underline: Option<UnderlineStyle>,
685 /// The strikethrough style (if any)
686 pub strikethrough: Option<StrikethroughStyle>,
687}
688
689#[cfg(all(target_os = "macos", test))]
690impl TextRun {
691 fn with_len(&self, len: usize) -> Self {
692 let mut this = self.clone();
693 this.len = len;
694 this
695 }
696}
697
698/// An identifier for a specific glyph, as returned by [`TextSystem::layout_line`].
699#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
700#[repr(C)]
701pub struct GlyphId(pub(crate) u32);
702
703#[derive(Clone, Debug, PartialEq)]
704pub(crate) struct RenderGlyphParams {
705 pub(crate) font_id: FontId,
706 pub(crate) glyph_id: GlyphId,
707 pub(crate) font_size: Pixels,
708 pub(crate) subpixel_variant: Point<u8>,
709 pub(crate) scale_factor: f32,
710 pub(crate) is_emoji: bool,
711}
712
713impl Eq for RenderGlyphParams {}
714
715impl Hash for RenderGlyphParams {
716 fn hash<H: Hasher>(&self, state: &mut H) {
717 self.font_id.0.hash(state);
718 self.glyph_id.0.hash(state);
719 self.font_size.0.to_bits().hash(state);
720 self.subpixel_variant.hash(state);
721 self.scale_factor.to_bits().hash(state);
722 self.is_emoji.hash(state);
723 }
724}
725
726/// The configuration details for identifying a specific font.
727#[derive(Clone, Debug, Eq, PartialEq, Hash)]
728pub struct Font {
729 /// The font family name.
730 ///
731 /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
732 pub family: SharedString,
733
734 /// The font features to use.
735 pub features: FontFeatures,
736
737 /// The fallbacks fonts to use.
738 pub fallbacks: Option<FontFallbacks>,
739
740 /// The font weight.
741 pub weight: FontWeight,
742
743 /// The font style.
744 pub style: FontStyle,
745}
746
747/// Get a [`Font`] for a given name.
748pub fn font(family: impl Into<SharedString>) -> Font {
749 Font {
750 family: family.into(),
751 features: FontFeatures::default(),
752 weight: FontWeight::default(),
753 style: FontStyle::default(),
754 fallbacks: None,
755 }
756}
757
758impl Font {
759 /// Set this Font to be bold
760 pub fn bold(mut self) -> Self {
761 self.weight = FontWeight::BOLD;
762 self
763 }
764
765 /// Set this Font to be italic
766 pub fn italic(mut self) -> Self {
767 self.style = FontStyle::Italic;
768 self
769 }
770}
771
772/// A struct for storing font metrics.
773/// It is used to define the measurements of a typeface.
774#[derive(Clone, Copy, Debug)]
775pub struct FontMetrics {
776 /// The number of font units that make up the "em square",
777 /// a scalable grid for determining the size of a typeface.
778 pub(crate) units_per_em: u32,
779
780 /// The vertical distance from the baseline of the font to the top of the glyph covers.
781 pub(crate) ascent: f32,
782
783 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
784 pub(crate) descent: f32,
785
786 /// The recommended additional space to add between lines of type.
787 pub(crate) line_gap: f32,
788
789 /// The suggested position of the underline.
790 pub(crate) underline_position: f32,
791
792 /// The suggested thickness of the underline.
793 pub(crate) underline_thickness: f32,
794
795 /// The height of a capital letter measured from the baseline of the font.
796 pub(crate) cap_height: f32,
797
798 /// The height of a lowercase x.
799 pub(crate) x_height: f32,
800
801 /// The outer limits of the area that the font covers.
802 /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
803 pub(crate) bounding_box: Bounds<f32>,
804}
805
806impl FontMetrics {
807 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
808 pub fn ascent(&self, font_size: Pixels) -> Pixels {
809 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
810 }
811
812 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
813 pub fn descent(&self, font_size: Pixels) -> Pixels {
814 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
815 }
816
817 /// Returns the recommended additional space to add between lines of type in pixels.
818 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
819 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
820 }
821
822 /// Returns the suggested position of the underline in pixels.
823 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
824 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
825 }
826
827 /// Returns the suggested thickness of the underline in pixels.
828 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
829 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
830 }
831
832 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
833 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
834 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
835 }
836
837 /// Returns the height of a lowercase x in pixels.
838 pub fn x_height(&self, font_size: Pixels) -> Pixels {
839 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
840 }
841
842 /// Returns the outer limits of the area that the font covers in pixels.
843 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
844 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
845 }
846}
847
848#[allow(unused)]
849pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
850 // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
851 // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
852 // and so retained here for backward compatibility.
853 match name {
854 ".SystemUIFont" => system,
855 ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
856 ".ZedMono" | "Zed Plex Mono" => "Lilex",
857 _ => name,
858 }
859}