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