1mod font_features;
2mod line;
3mod line_layout;
4mod line_wrapper;
5
6pub use font_features::*;
7pub use line::*;
8pub use line_layout::*;
9pub use line_wrapper::*;
10
11use crate::{
12 px, Bounds, DevicePixels, EntityId, Hsla, Pixels, PlatformTextSystem, Point, Result,
13 SharedString, Size, UnderlineStyle,
14};
15use anyhow::anyhow;
16use collections::{FxHashMap, FxHashSet};
17use core::fmt;
18use itertools::Itertools;
19use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
20use smallvec::{smallvec, SmallVec};
21use std::{
22 cmp,
23 fmt::{Debug, Display, Formatter},
24 hash::{Hash, Hasher},
25 ops::{Deref, DerefMut},
26 sync::Arc,
27};
28
29#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
30#[repr(C)]
31pub struct FontId(pub usize);
32
33#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
34pub struct FontFamilyId(pub usize);
35
36pub(crate) const SUBPIXEL_VARIANTS: u8 = 4;
37
38pub struct TextSystem {
39 line_layout_cache: Arc<LineLayoutCache>,
40 platform_text_system: Arc<dyn PlatformTextSystem>,
41 font_ids_by_font: RwLock<FxHashMap<Font, FontId>>,
42 font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
43 raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
44 wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
45 font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
46 fallback_font_stack: SmallVec<[Font; 2]>,
47}
48
49impl TextSystem {
50 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
51 TextSystem {
52 line_layout_cache: Arc::new(LineLayoutCache::new(platform_text_system.clone())),
53 platform_text_system,
54 font_metrics: RwLock::default(),
55 raster_bounds: RwLock::default(),
56 font_ids_by_font: RwLock::default(),
57 wrapper_pool: Mutex::default(),
58 font_runs_pool: Mutex::default(),
59 fallback_font_stack: smallvec![
60 // TODO: This is currently Zed-specific.
61 // We should allow GPUI users to provide their own fallback font stack.
62 font("Zed Mono"),
63 font("Helvetica")
64 ],
65 }
66 }
67
68 pub fn all_font_families(&self) -> Vec<String> {
69 let mut families = self.platform_text_system.all_font_families();
70 families.append(
71 &mut self
72 .fallback_font_stack
73 .iter()
74 .map(|font| font.family.to_string())
75 .collect(),
76 );
77 families
78 }
79 pub fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
80 self.platform_text_system.add_fonts(fonts)
81 }
82
83 pub fn font_id(&self, font: &Font) -> Result<FontId> {
84 let font_id = self.font_ids_by_font.read().get(font).copied();
85 if let Some(font_id) = font_id {
86 Ok(font_id)
87 } else {
88 let font_id = self.platform_text_system.font_id(font)?;
89 self.font_ids_by_font.write().insert(font.clone(), font_id);
90 Ok(font_id)
91 }
92 }
93
94 /// Resolves the specified font, falling back to the default font stack if
95 /// the font fails to load.
96 ///
97 /// # Panics
98 ///
99 /// Panics if the font and none of the fallbacks can be resolved.
100 pub fn resolve_font(&self, font: &Font) -> FontId {
101 if let Ok(font_id) = self.font_id(font) {
102 return font_id;
103 }
104
105 for fallback in &self.fallback_font_stack {
106 if let Ok(font_id) = self.font_id(fallback) {
107 return font_id;
108 }
109 }
110
111 panic!(
112 "failed to resolve font '{}' or any of the fallbacks: {}",
113 font.family,
114 self.fallback_font_stack
115 .iter()
116 .map(|fallback| &fallback.family)
117 .join(", ")
118 );
119 }
120
121 pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
122 self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
123 }
124
125 pub fn typographic_bounds(
126 &self,
127 font_id: FontId,
128 font_size: Pixels,
129 character: char,
130 ) -> Result<Bounds<Pixels>> {
131 let glyph_id = self
132 .platform_text_system
133 .glyph_for_char(font_id, character)
134 .ok_or_else(|| anyhow!("glyph not found for character '{}'", character))?;
135 let bounds = self
136 .platform_text_system
137 .typographic_bounds(font_id, glyph_id)?;
138 Ok(self.read_metrics(font_id, |metrics| {
139 (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
140 }))
141 }
142
143 pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
144 let glyph_id = self
145 .platform_text_system
146 .glyph_for_char(font_id, ch)
147 .ok_or_else(|| anyhow!("glyph not found for character '{}'", ch))?;
148 let result = self.platform_text_system.advance(font_id, glyph_id)?
149 / self.units_per_em(font_id) as f32;
150
151 Ok(result * font_size)
152 }
153
154 pub fn units_per_em(&self, font_id: FontId) -> u32 {
155 self.read_metrics(font_id, |metrics| metrics.units_per_em)
156 }
157
158 pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
159 self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
160 }
161
162 pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
163 self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
164 }
165
166 pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
167 self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
168 }
169
170 pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
171 self.read_metrics(font_id, |metrics| metrics.descent(font_size))
172 }
173
174 pub fn baseline_offset(
175 &self,
176 font_id: FontId,
177 font_size: Pixels,
178 line_height: Pixels,
179 ) -> Pixels {
180 let ascent = self.ascent(font_id, font_size);
181 let descent = self.descent(font_id, font_size);
182 let padding_top = (line_height - ascent - descent) / 2.;
183 padding_top + ascent
184 }
185
186 fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
187 let lock = self.font_metrics.upgradable_read();
188
189 if let Some(metrics) = lock.get(&font_id) {
190 read(metrics)
191 } else {
192 let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
193 let metrics = lock
194 .entry(font_id)
195 .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
196 read(metrics)
197 }
198 }
199
200 pub fn with_view<R>(&self, view_id: EntityId, f: impl FnOnce() -> R) -> R {
201 self.line_layout_cache.with_view(view_id, f)
202 }
203
204 pub fn layout_line(
205 &self,
206 text: &str,
207 font_size: Pixels,
208 runs: &[TextRun],
209 ) -> Result<Arc<LineLayout>> {
210 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
211 for run in runs.iter() {
212 let font_id = self.resolve_font(&run.font);
213 if let Some(last_run) = font_runs.last_mut() {
214 if last_run.font_id == font_id {
215 last_run.len += run.len;
216 continue;
217 }
218 }
219 font_runs.push(FontRun {
220 len: run.len,
221 font_id,
222 });
223 }
224
225 let layout = self
226 .line_layout_cache
227 .layout_line(text, font_size, &font_runs);
228
229 font_runs.clear();
230 self.font_runs_pool.lock().push(font_runs);
231
232 Ok(layout)
233 }
234
235 pub fn shape_line(
236 &self,
237 text: SharedString,
238 font_size: Pixels,
239 runs: &[TextRun],
240 ) -> Result<ShapedLine> {
241 debug_assert!(
242 text.find('\n').is_none(),
243 "text argument should not contain newlines"
244 );
245
246 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
247 for run in runs {
248 if let Some(last_run) = decoration_runs.last_mut() {
249 if last_run.color == run.color
250 && last_run.underline == run.underline
251 && last_run.background_color == run.background_color
252 {
253 last_run.len += run.len as u32;
254 continue;
255 }
256 }
257 decoration_runs.push(DecorationRun {
258 len: run.len as u32,
259 color: run.color,
260 background_color: run.background_color,
261 underline: run.underline,
262 });
263 }
264
265 let layout = self.layout_line(text.as_ref(), font_size, runs)?;
266
267 Ok(ShapedLine {
268 layout,
269 text,
270 decoration_runs,
271 })
272 }
273
274 pub fn shape_text(
275 &self,
276 text: SharedString,
277 font_size: Pixels,
278 runs: &[TextRun],
279 wrap_width: Option<Pixels>,
280 ) -> Result<SmallVec<[WrappedLine; 1]>> {
281 let mut runs = runs.iter().cloned().peekable();
282 let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
283
284 let mut lines = SmallVec::new();
285 let mut line_start = 0;
286
287 let mut process_line = |line_text: SharedString| {
288 let line_end = line_start + line_text.len();
289
290 let mut last_font: Option<Font> = None;
291 let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
292 let mut run_start = line_start;
293 while run_start < line_end {
294 let Some(run) = runs.peek_mut() else {
295 break;
296 };
297
298 let run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
299
300 if last_font == Some(run.font.clone()) {
301 font_runs.last_mut().unwrap().len += run_len_within_line;
302 } else {
303 last_font = Some(run.font.clone());
304 font_runs.push(FontRun {
305 len: run_len_within_line,
306 font_id: self.resolve_font(&run.font),
307 });
308 }
309
310 if decoration_runs.last().map_or(false, |last_run| {
311 last_run.color == run.color
312 && last_run.underline == run.underline
313 && last_run.background_color == run.background_color
314 }) {
315 decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
316 } else {
317 decoration_runs.push(DecorationRun {
318 len: run_len_within_line as u32,
319 color: run.color,
320 background_color: run.background_color,
321 underline: run.underline,
322 });
323 }
324
325 if run_len_within_line == run.len {
326 runs.next();
327 } else {
328 // Preserve the remainder of the run for the next line
329 run.len -= run_len_within_line;
330 }
331 run_start += run_len_within_line;
332 }
333
334 let layout = self
335 .line_layout_cache
336 .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
337 lines.push(WrappedLine {
338 layout,
339 decoration_runs,
340 text: line_text,
341 });
342
343 // Skip `\n` character.
344 line_start = line_end + 1;
345 if let Some(run) = runs.peek_mut() {
346 run.len = run.len.saturating_sub(1);
347 if run.len == 0 {
348 runs.next();
349 }
350 }
351
352 font_runs.clear();
353 };
354
355 let mut split_lines = text.split('\n');
356 let mut processed = false;
357
358 if let Some(first_line) = split_lines.next() {
359 if let Some(second_line) = split_lines.next() {
360 processed = true;
361 process_line(first_line.to_string().into());
362 process_line(second_line.to_string().into());
363 for line_text in split_lines {
364 process_line(line_text.to_string().into());
365 }
366 }
367 }
368
369 if !processed {
370 process_line(text);
371 }
372
373 self.font_runs_pool.lock().push(font_runs);
374
375 Ok(lines)
376 }
377
378 pub fn finish_frame(&self, reused_views: &FxHashSet<EntityId>) {
379 self.line_layout_cache.finish_frame(reused_views)
380 }
381
382 pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
383 let lock = &mut self.wrapper_pool.lock();
384 let font_id = self.resolve_font(&font);
385 let wrappers = lock
386 .entry(FontIdWithSize { font_id, font_size })
387 .or_default();
388 let wrapper = wrappers.pop().unwrap_or_else(|| {
389 LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
390 });
391
392 LineWrapperHandle {
393 wrapper: Some(wrapper),
394 text_system: self.clone(),
395 }
396 }
397
398 pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
399 let raster_bounds = self.raster_bounds.upgradable_read();
400 if let Some(bounds) = raster_bounds.get(params) {
401 Ok(*bounds)
402 } else {
403 let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
404 let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
405 raster_bounds.insert(params.clone(), bounds);
406 Ok(bounds)
407 }
408 }
409
410 pub fn rasterize_glyph(
411 &self,
412 params: &RenderGlyphParams,
413 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
414 let raster_bounds = self.raster_bounds(params)?;
415 self.platform_text_system
416 .rasterize_glyph(params, raster_bounds)
417 }
418}
419
420#[derive(Hash, Eq, PartialEq)]
421struct FontIdWithSize {
422 font_id: FontId,
423 font_size: Pixels,
424}
425
426pub struct LineWrapperHandle {
427 wrapper: Option<LineWrapper>,
428 text_system: Arc<TextSystem>,
429}
430
431impl Drop for LineWrapperHandle {
432 fn drop(&mut self) {
433 let mut state = self.text_system.wrapper_pool.lock();
434 let wrapper = self.wrapper.take().unwrap();
435 state
436 .get_mut(&FontIdWithSize {
437 font_id: wrapper.font_id,
438 font_size: wrapper.font_size,
439 })
440 .unwrap()
441 .push(wrapper);
442 }
443}
444
445impl Deref for LineWrapperHandle {
446 type Target = LineWrapper;
447
448 fn deref(&self) -> &Self::Target {
449 self.wrapper.as_ref().unwrap()
450 }
451}
452
453impl DerefMut for LineWrapperHandle {
454 fn deref_mut(&mut self) -> &mut Self::Target {
455 self.wrapper.as_mut().unwrap()
456 }
457}
458
459/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
460/// with 400.0 as normal.
461#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
462pub struct FontWeight(pub f32);
463
464impl Default for FontWeight {
465 #[inline]
466 fn default() -> FontWeight {
467 FontWeight::NORMAL
468 }
469}
470
471impl Hash for FontWeight {
472 fn hash<H: Hasher>(&self, state: &mut H) {
473 state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
474 }
475}
476
477impl Eq for FontWeight {}
478
479impl FontWeight {
480 /// Thin weight (100), the thinnest value.
481 pub const THIN: FontWeight = FontWeight(100.0);
482 /// Extra light weight (200).
483 pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
484 /// Light weight (300).
485 pub const LIGHT: FontWeight = FontWeight(300.0);
486 /// Normal (400).
487 pub const NORMAL: FontWeight = FontWeight(400.0);
488 /// Medium weight (500, higher than normal).
489 pub const MEDIUM: FontWeight = FontWeight(500.0);
490 /// Semibold weight (600).
491 pub const SEMIBOLD: FontWeight = FontWeight(600.0);
492 /// Bold weight (700).
493 pub const BOLD: FontWeight = FontWeight(700.0);
494 /// Extra-bold weight (800).
495 pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
496 /// Black weight (900), the thickest value.
497 pub const BLACK: FontWeight = FontWeight(900.0);
498}
499
500/// Allows italic or oblique faces to be selected.
501#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default)]
502pub enum FontStyle {
503 /// A face that is neither italic not obliqued.
504 #[default]
505 Normal,
506 /// A form that is generally cursive in nature.
507 Italic,
508 /// A typically-sloped version of the regular face.
509 Oblique,
510}
511
512impl Display for FontStyle {
513 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
514 Debug::fmt(self, f)
515 }
516}
517
518#[derive(Clone, Debug, PartialEq, Eq)]
519pub struct TextRun {
520 // number of utf8 bytes
521 pub len: usize,
522 pub font: Font,
523 pub color: Hsla,
524 pub background_color: Option<Hsla>,
525 pub underline: Option<UnderlineStyle>,
526}
527
528#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
529#[repr(C)]
530pub struct GlyphId(u32);
531
532impl From<GlyphId> for u32 {
533 fn from(value: GlyphId) -> Self {
534 value.0
535 }
536}
537
538impl From<u16> for GlyphId {
539 fn from(num: u16) -> Self {
540 GlyphId(num as u32)
541 }
542}
543
544impl From<u32> for GlyphId {
545 fn from(num: u32) -> Self {
546 GlyphId(num)
547 }
548}
549
550#[derive(Clone, Debug, PartialEq)]
551pub struct RenderGlyphParams {
552 pub(crate) font_id: FontId,
553 pub(crate) glyph_id: GlyphId,
554 pub(crate) font_size: Pixels,
555 pub(crate) subpixel_variant: Point<u8>,
556 pub(crate) scale_factor: f32,
557 pub(crate) is_emoji: bool,
558}
559
560impl Eq for RenderGlyphParams {}
561
562impl Hash for RenderGlyphParams {
563 fn hash<H: Hasher>(&self, state: &mut H) {
564 self.font_id.0.hash(state);
565 self.glyph_id.0.hash(state);
566 self.font_size.0.to_bits().hash(state);
567 self.subpixel_variant.hash(state);
568 self.scale_factor.to_bits().hash(state);
569 }
570}
571
572#[derive(Clone, Debug, PartialEq)]
573pub struct RenderEmojiParams {
574 pub(crate) font_id: FontId,
575 pub(crate) glyph_id: GlyphId,
576 pub(crate) font_size: Pixels,
577 pub(crate) scale_factor: f32,
578}
579
580impl Eq for RenderEmojiParams {}
581
582impl Hash for RenderEmojiParams {
583 fn hash<H: Hasher>(&self, state: &mut H) {
584 self.font_id.0.hash(state);
585 self.glyph_id.0.hash(state);
586 self.font_size.0.to_bits().hash(state);
587 self.scale_factor.to_bits().hash(state);
588 }
589}
590
591#[derive(Clone, Debug, Eq, PartialEq, Hash)]
592pub struct Font {
593 pub family: SharedString,
594 pub features: FontFeatures,
595 pub weight: FontWeight,
596 pub style: FontStyle,
597}
598
599pub fn font(family: impl Into<SharedString>) -> Font {
600 Font {
601 family: family.into(),
602 features: FontFeatures::default(),
603 weight: FontWeight::default(),
604 style: FontStyle::default(),
605 }
606}
607
608impl Font {
609 pub fn bold(mut self) -> Self {
610 self.weight = FontWeight::BOLD;
611 self
612 }
613}
614
615/// A struct for storing font metrics.
616/// It is used to define the measurements of a typeface.
617#[derive(Clone, Copy, Debug)]
618pub struct FontMetrics {
619 /// The number of font units that make up the "em square",
620 /// a scalable grid for determining the size of a typeface.
621 pub(crate) units_per_em: u32,
622
623 /// The vertical distance from the baseline of the font to the top of the glyph covers.
624 pub(crate) ascent: f32,
625
626 /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
627 pub(crate) descent: f32,
628
629 /// The recommended additional space to add between lines of type.
630 pub(crate) line_gap: f32,
631
632 /// The suggested position of the underline.
633 pub(crate) underline_position: f32,
634
635 /// The suggested thickness of the underline.
636 pub(crate) underline_thickness: f32,
637
638 /// The height of a capital letter measured from the baseline of the font.
639 pub(crate) cap_height: f32,
640
641 /// The height of a lowercase x.
642 pub(crate) x_height: f32,
643
644 /// The outer limits of the area that the font covers.
645 pub(crate) bounding_box: Bounds<f32>,
646}
647
648impl FontMetrics {
649 /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
650 pub fn ascent(&self, font_size: Pixels) -> Pixels {
651 Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
652 }
653
654 /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
655 pub fn descent(&self, font_size: Pixels) -> Pixels {
656 Pixels((self.descent / self.units_per_em as f32) * font_size.0)
657 }
658
659 /// Returns the recommended additional space to add between lines of type in pixels.
660 pub fn line_gap(&self, font_size: Pixels) -> Pixels {
661 Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
662 }
663
664 /// Returns the suggested position of the underline in pixels.
665 pub fn underline_position(&self, font_size: Pixels) -> Pixels {
666 Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
667 }
668
669 /// Returns the suggested thickness of the underline in pixels.
670 pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
671 Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
672 }
673
674 /// Returns the height of a capital letter measured from the baseline of the font in pixels.
675 pub fn cap_height(&self, font_size: Pixels) -> Pixels {
676 Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
677 }
678
679 /// Returns the height of a lowercase x in pixels.
680 pub fn x_height(&self, font_size: Pixels) -> Pixels {
681 Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
682 }
683
684 /// Returns the outer limits of the area that the font covers in pixels.
685 pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
686 (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
687 }
688}