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