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