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 finish_frame(&self, reused_views: &FxHashSet<EntityId>) {
368        self.line_layout_cache.finish_frame(reused_views)
369    }
370
371    pub fn line_wrapper(
372        self: &Arc<Self>,
373        font: Font,
374        font_size: Pixels,
375    ) -> Result<LineWrapperHandle> {
376        let lock = &mut self.wrapper_pool.lock();
377        let font_id = self.font_id(&font)?;
378        let wrappers = lock
379            .entry(FontIdWithSize { font_id, font_size })
380            .or_default();
381        let wrapper = wrappers.pop().map(anyhow::Ok).unwrap_or_else(|| {
382            Ok(LineWrapper::new(
383                font_id,
384                font_size,
385                self.platform_text_system.clone(),
386            ))
387        })?;
388
389        Ok(LineWrapperHandle {
390            wrapper: Some(wrapper),
391            text_system: self.clone(),
392        })
393    }
394
395    pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
396        let raster_bounds = self.raster_bounds.upgradable_read();
397        if let Some(bounds) = raster_bounds.get(params) {
398            Ok(*bounds)
399        } else {
400            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
401            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
402            raster_bounds.insert(params.clone(), bounds);
403            Ok(bounds)
404        }
405    }
406
407    pub fn rasterize_glyph(
408        &self,
409        params: &RenderGlyphParams,
410    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
411        let raster_bounds = self.raster_bounds(params)?;
412        self.platform_text_system
413            .rasterize_glyph(params, raster_bounds)
414    }
415}
416
417#[derive(Hash, Eq, PartialEq)]
418struct FontIdWithSize {
419    font_id: FontId,
420    font_size: Pixels,
421}
422
423pub struct LineWrapperHandle {
424    wrapper: Option<LineWrapper>,
425    text_system: Arc<TextSystem>,
426}
427
428impl Drop for LineWrapperHandle {
429    fn drop(&mut self) {
430        let mut state = self.text_system.wrapper_pool.lock();
431        let wrapper = self.wrapper.take().unwrap();
432        state
433            .get_mut(&FontIdWithSize {
434                font_id: wrapper.font_id,
435                font_size: wrapper.font_size,
436            })
437            .unwrap()
438            .push(wrapper);
439    }
440}
441
442impl Deref for LineWrapperHandle {
443    type Target = LineWrapper;
444
445    fn deref(&self) -> &Self::Target {
446        self.wrapper.as_ref().unwrap()
447    }
448}
449
450impl DerefMut for LineWrapperHandle {
451    fn deref_mut(&mut self) -> &mut Self::Target {
452        self.wrapper.as_mut().unwrap()
453    }
454}
455
456/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
457/// with 400.0 as normal.
458#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
459pub struct FontWeight(pub f32);
460
461impl Default for FontWeight {
462    #[inline]
463    fn default() -> FontWeight {
464        FontWeight::NORMAL
465    }
466}
467
468impl Hash for FontWeight {
469    fn hash<H: Hasher>(&self, state: &mut H) {
470        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
471    }
472}
473
474impl Eq for FontWeight {}
475
476impl FontWeight {
477    /// Thin weight (100), the thinnest value.
478    pub const THIN: FontWeight = FontWeight(100.0);
479    /// Extra light weight (200).
480    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
481    /// Light weight (300).
482    pub const LIGHT: FontWeight = FontWeight(300.0);
483    /// Normal (400).
484    pub const NORMAL: FontWeight = FontWeight(400.0);
485    /// Medium weight (500, higher than normal).
486    pub const MEDIUM: FontWeight = FontWeight(500.0);
487    /// Semibold weight (600).
488    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
489    /// Bold weight (700).
490    pub const BOLD: FontWeight = FontWeight(700.0);
491    /// Extra-bold weight (800).
492    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
493    /// Black weight (900), the thickest value.
494    pub const BLACK: FontWeight = FontWeight(900.0);
495}
496
497/// Allows italic or oblique faces to be selected.
498#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default)]
499pub enum FontStyle {
500    /// A face that is neither italic not obliqued.
501    #[default]
502    Normal,
503    /// A form that is generally cursive in nature.
504    Italic,
505    /// A typically-sloped version of the regular face.
506    Oblique,
507}
508
509impl Display for FontStyle {
510    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
511        Debug::fmt(self, f)
512    }
513}
514
515#[derive(Clone, Debug, PartialEq, Eq)]
516pub struct TextRun {
517    // number of utf8 bytes
518    pub len: usize,
519    pub font: Font,
520    pub color: Hsla,
521    pub background_color: Option<Hsla>,
522    pub underline: Option<UnderlineStyle>,
523}
524
525#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
526#[repr(C)]
527pub struct GlyphId(u32);
528
529impl From<GlyphId> for u32 {
530    fn from(value: GlyphId) -> Self {
531        value.0
532    }
533}
534
535impl From<u16> for GlyphId {
536    fn from(num: u16) -> Self {
537        GlyphId(num as u32)
538    }
539}
540
541impl From<u32> for GlyphId {
542    fn from(num: u32) -> Self {
543        GlyphId(num)
544    }
545}
546
547#[derive(Clone, Debug, PartialEq)]
548pub struct RenderGlyphParams {
549    pub(crate) font_id: FontId,
550    pub(crate) glyph_id: GlyphId,
551    pub(crate) font_size: Pixels,
552    pub(crate) subpixel_variant: Point<u8>,
553    pub(crate) scale_factor: f32,
554    pub(crate) is_emoji: bool,
555}
556
557impl Eq for RenderGlyphParams {}
558
559impl Hash for RenderGlyphParams {
560    fn hash<H: Hasher>(&self, state: &mut H) {
561        self.font_id.0.hash(state);
562        self.glyph_id.0.hash(state);
563        self.font_size.0.to_bits().hash(state);
564        self.subpixel_variant.hash(state);
565        self.scale_factor.to_bits().hash(state);
566    }
567}
568
569#[derive(Clone, Debug, PartialEq)]
570pub struct RenderEmojiParams {
571    pub(crate) font_id: FontId,
572    pub(crate) glyph_id: GlyphId,
573    pub(crate) font_size: Pixels,
574    pub(crate) scale_factor: f32,
575}
576
577impl Eq for RenderEmojiParams {}
578
579impl Hash for RenderEmojiParams {
580    fn hash<H: Hasher>(&self, state: &mut H) {
581        self.font_id.0.hash(state);
582        self.glyph_id.0.hash(state);
583        self.font_size.0.to_bits().hash(state);
584        self.scale_factor.to_bits().hash(state);
585    }
586}
587
588#[derive(Clone, Debug, Eq, PartialEq, Hash)]
589pub struct Font {
590    pub family: SharedString,
591    pub features: FontFeatures,
592    pub weight: FontWeight,
593    pub style: FontStyle,
594}
595
596pub fn font(family: impl Into<SharedString>) -> Font {
597    Font {
598        family: family.into(),
599        features: FontFeatures::default(),
600        weight: FontWeight::default(),
601        style: FontStyle::default(),
602    }
603}
604
605impl Font {
606    pub fn bold(mut self) -> Self {
607        self.weight = FontWeight::BOLD;
608        self
609    }
610}
611
612/// A struct for storing font metrics.
613/// It is used to define the measurements of a typeface.
614#[derive(Clone, Copy, Debug)]
615pub struct FontMetrics {
616    /// The number of font units that make up the "em square",
617    /// a scalable grid for determining the size of a typeface.
618    pub(crate) units_per_em: u32,
619
620    /// The vertical distance from the baseline of the font to the top of the glyph covers.
621    pub(crate) ascent: f32,
622
623    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
624    pub(crate) descent: f32,
625
626    /// The recommended additional space to add between lines of type.
627    pub(crate) line_gap: f32,
628
629    /// The suggested position of the underline.
630    pub(crate) underline_position: f32,
631
632    /// The suggested thickness of the underline.
633    pub(crate) underline_thickness: f32,
634
635    /// The height of a capital letter measured from the baseline of the font.
636    pub(crate) cap_height: f32,
637
638    /// The height of a lowercase x.
639    pub(crate) x_height: f32,
640
641    /// The outer limits of the area that the font covers.
642    pub(crate) bounding_box: Bounds<f32>,
643}
644
645impl FontMetrics {
646    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
647    pub fn ascent(&self, font_size: Pixels) -> Pixels {
648        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
649    }
650
651    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
652    pub fn descent(&self, font_size: Pixels) -> Pixels {
653        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
654    }
655
656    /// Returns the recommended additional space to add between lines of type in pixels.
657    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
658        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
659    }
660
661    /// Returns the suggested position of the underline in pixels.
662    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
663        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
664    }
665
666    /// Returns the suggested thickness of the underline in pixels.
667    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
668        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
669    }
670
671    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
672    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
673        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
674    }
675
676    /// Returns the height of a lowercase x in pixels.
677    pub fn x_height(&self, font_size: Pixels) -> Pixels {
678        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
679    }
680
681    /// Returns the outer limits of the area that the font covers in pixels.
682    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
683        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
684    }
685}