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