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