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