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