text_system.rs

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