text_system.rs

  1mod font_fallbacks;
  2mod font_features;
  3mod line;
  4mod line_layout;
  5mod line_wrapper;
  6
  7pub use font_fallbacks::*;
  8pub use font_features::*;
  9pub use line::*;
 10pub use line_layout::*;
 11pub use line_wrapper::*;
 12use schemars::JsonSchema;
 13use serde::{Deserialize, Serialize};
 14
 15use crate::{
 16    Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
 17    StrikethroughStyle, UnderlineStyle, px,
 18};
 19use anyhow::{Context as _, anyhow};
 20use collections::FxHashMap;
 21use core::fmt;
 22use derive_more::Deref;
 23use itertools::Itertools;
 24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
 25use smallvec::{SmallVec, smallvec};
 26use std::{
 27    borrow::Cow,
 28    cmp,
 29    fmt::{Debug, Display, Formatter},
 30    hash::{Hash, Hasher},
 31    ops::{Deref, DerefMut, Range},
 32    sync::Arc,
 33};
 34
 35/// An opaque identifier for a specific font.
 36#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 37#[repr(C)]
 38pub struct FontId(pub usize);
 39
 40/// An opaque identifier for a specific font family.
 41#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
 42pub struct FontFamilyId(pub usize);
 43
 44pub(crate) const SUBPIXEL_VARIANTS_X: u8 = 4;
 45
 46pub(crate) const SUBPIXEL_VARIANTS_Y: u8 = if cfg!(target_os = "windows") {
 47    1
 48} else {
 49    SUBPIXEL_VARIANTS_X
 50};
 51
 52/// The GPUI text rendering sub system.
 53pub struct TextSystem {
 54    platform_text_system: Arc<dyn PlatformTextSystem>,
 55    font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
 56    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
 57    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
 58    wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
 59    font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
 60    fallback_font_stack: SmallVec<[Font; 2]>,
 61}
 62
 63impl TextSystem {
 64    pub(crate) fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
 65        TextSystem {
 66            platform_text_system,
 67            font_metrics: RwLock::default(),
 68            raster_bounds: RwLock::default(),
 69            font_ids_by_font: RwLock::default(),
 70            wrapper_pool: Mutex::default(),
 71            font_runs_pool: Mutex::default(),
 72            fallback_font_stack: smallvec![
 73                // TODO: Remove this when Linux have implemented setting fallbacks.
 74                font(".ZedMono"),
 75                font("Helvetica"),
 76                font("Segoe UI"),  // Windows
 77                font("Cantarell"), // Gnome
 78                font("Ubuntu"),    // Gnome (Ubuntu)
 79                font("Noto Sans"), // KDE
 80                font("DejaVu Sans")
 81            ],
 82        }
 83    }
 84
 85    /// Get a list of all available font names from the operating system.
 86    pub fn all_font_names(&self) -> Vec<String> {
 87        let mut names = self.platform_text_system.all_font_names();
 88        names.extend(
 89            self.fallback_font_stack
 90                .iter()
 91                .map(|font| font.family.to_string()),
 92        );
 93        names.push(".SystemUIFont".to_string());
 94        names.sort();
 95        names.dedup();
 96        names
 97    }
 98
 99    /// Add a font's data to the text system.
100    pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
101        self.platform_text_system.add_fonts(fonts)
102    }
103
104    /// Get the FontId for the configure font family and style.
105    fn font_id(&self, font: &Font) -> Result<FontId> {
106        fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
107            match font_id {
108                Ok(font_id) => Ok(*font_id),
109                Err(err) => Err(anyhow!("{err}")),
110            }
111        }
112
113        let font_id = self
114            .font_ids_by_font
115            .read()
116            .get(font)
117            .map(clone_font_id_result);
118        if let Some(font_id) = font_id {
119            font_id
120        } else {
121            let font_id = self.platform_text_system.font_id(font);
122            self.font_ids_by_font
123                .write()
124                .insert(font.clone(), clone_font_id_result(&font_id));
125            font_id
126        }
127    }
128
129    /// Get the Font for the Font Id.
130    pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
131        let lock = self.font_ids_by_font.read();
132        lock.iter()
133            .filter_map(|(font, result)| match result {
134                Ok(font_id) if *font_id == id => Some(font.clone()),
135                _ => None,
136            })
137            .next()
138    }
139
140    /// Resolves the specified font, falling back to the default font stack if
141    /// the font fails to load.
142    ///
143    /// # Panics
144    ///
145    /// Panics if the font and none of the fallbacks can be resolved.
146    pub fn resolve_font(&self, font: &Font) -> FontId {
147        if let Ok(font_id) = self.font_id(font) {
148            return font_id;
149        }
150        for fallback in &self.fallback_font_stack {
151            if let Ok(font_id) = self.font_id(fallback) {
152                return font_id;
153            }
154        }
155
156        panic!(
157            "failed to resolve font '{}' or any of the fallbacks: {}",
158            font.family,
159            self.fallback_font_stack
160                .iter()
161                .map(|fallback| &fallback.family)
162                .join(", ")
163        );
164    }
165
166    /// Get the bounding box for the given font and font size.
167    /// A font's bounding box is the smallest rectangle that could enclose all glyphs
168    /// in the font. superimposed over one another.
169    pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
170        self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
171    }
172
173    /// Get the typographic bounds for the given character, in the given font and size.
174    pub fn typographic_bounds(
175        &self,
176        font_id: FontId,
177        font_size: Pixels,
178        character: char,
179    ) -> Result<Bounds<Pixels>> {
180        let glyph_id = self
181            .platform_text_system
182            .glyph_for_char(font_id, character)
183            .with_context(|| format!("glyph not found for character '{character}'"))?;
184        let bounds = self
185            .platform_text_system
186            .typographic_bounds(font_id, glyph_id)?;
187        Ok(self.read_metrics(font_id, |metrics| {
188            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
189        }))
190    }
191
192    /// Get the advance width for the given character, in the given font and size.
193    pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
194        let glyph_id = self
195            .platform_text_system
196            .glyph_for_char(font_id, ch)
197            .with_context(|| format!("glyph not found for character '{ch}'"))?;
198        let result = self.platform_text_system.advance(font_id, glyph_id)?
199            / self.units_per_em(font_id) as f32;
200
201        Ok(result * font_size)
202    }
203
204    /// Returns the width of an `em`.
205    ///
206    /// Uses the width of the `m` character in the given font and size.
207    pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
208        Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
209    }
210
211    /// Returns the advance width of an `em`.
212    ///
213    /// Uses the advance width of the `m` character in the given font and size.
214    pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
215        Ok(self.advance(font_id, font_size, 'm')?.width)
216    }
217
218    /// Returns the width of an `ch`.
219    ///
220    /// Uses the width of the `0` character in the given font and size.
221    pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
222        Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
223    }
224
225    /// Returns the advance width of an `ch`.
226    ///
227    /// Uses the advance width of the `0` character in the given font and size.
228    pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
229        Ok(self.advance(font_id, font_size, '0')?.width)
230    }
231
232    /// Get the number of font size units per 'em square',
233    /// Per MDN: "an abstract square whose height is the intended distance between
234    /// lines of type in the same type size"
235    pub fn units_per_em(&self, font_id: FontId) -> u32 {
236        self.read_metrics(font_id, |metrics| metrics.units_per_em)
237    }
238
239    /// Get the height of a capital letter in the given font and size.
240    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
241        self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
242    }
243
244    /// Get the height of the x character in the given font and size.
245    pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
246        self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
247    }
248
249    /// Get the recommended distance from the baseline for the given font
250    pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
251        self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
252    }
253
254    /// Get the recommended distance below the baseline for the given font,
255    /// in single spaced text.
256    pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
257        self.read_metrics(font_id, |metrics| metrics.descent(font_size))
258    }
259
260    /// Get the recommended baseline offset for the given font and line height.
261    pub fn baseline_offset(
262        &self,
263        font_id: FontId,
264        font_size: Pixels,
265        line_height: Pixels,
266    ) -> Pixels {
267        let ascent = self.ascent(font_id, font_size);
268        let descent = self.descent(font_id, font_size);
269        let padding_top = (line_height - ascent - descent) / 2.;
270        padding_top + ascent
271    }
272
273    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
274        let lock = self.font_metrics.upgradable_read();
275
276        if let Some(metrics) = lock.get(&font_id) {
277            read(metrics)
278        } else {
279            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
280            let metrics = lock
281                .entry(font_id)
282                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
283            read(metrics)
284        }
285    }
286
287    /// Returns a handle to a line wrapper, for the given font and font size.
288    pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
289        let lock = &mut self.wrapper_pool.lock();
290        let font_id = self.resolve_font(&font);
291        let wrappers = lock
292            .entry(FontIdWithSize { font_id, font_size })
293            .or_default();
294        let wrapper = wrappers.pop().unwrap_or_else(|| {
295            LineWrapper::new(font_id, font_size, self.platform_text_system.clone())
296        });
297
298        LineWrapperHandle {
299            wrapper: Some(wrapper),
300            text_system: self.clone(),
301        }
302    }
303
304    /// Get the rasterized size and location of a specific, rendered glyph.
305    pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
306        let raster_bounds = self.raster_bounds.upgradable_read();
307        if let Some(bounds) = raster_bounds.get(params) {
308            Ok(*bounds)
309        } else {
310            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
311            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
312            raster_bounds.insert(params.clone(), bounds);
313            Ok(bounds)
314        }
315    }
316
317    pub(crate) fn rasterize_glyph(
318        &self,
319        params: &RenderGlyphParams,
320    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
321        let raster_bounds = self.raster_bounds(params)?;
322        self.platform_text_system
323            .rasterize_glyph(params, raster_bounds)
324    }
325}
326
327/// The GPUI text layout subsystem.
328#[derive(Deref)]
329pub struct WindowTextSystem {
330    line_layout_cache: LineLayoutCache,
331    #[deref]
332    text_system: Arc<TextSystem>,
333}
334
335impl WindowTextSystem {
336    pub(crate) fn new(text_system: Arc<TextSystem>) -> Self {
337        Self {
338            line_layout_cache: LineLayoutCache::new(text_system.platform_text_system.clone()),
339            text_system,
340        }
341    }
342
343    pub(crate) fn layout_index(&self) -> LineLayoutIndex {
344        self.line_layout_cache.layout_index()
345    }
346
347    pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
348        self.line_layout_cache.reuse_layouts(index)
349    }
350
351    pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
352        self.line_layout_cache.truncate_layouts(index)
353    }
354
355    /// Shape the given line, at the given font_size, for painting to the screen.
356    /// Subsets of the line can be styled independently with the `runs` parameter.
357    ///
358    /// Note that this method can only shape a single line of text. It will panic
359    /// if the text contains newlines. If you need to shape multiple lines of text,
360    /// use [`Self::shape_text`] instead.
361    pub fn shape_line(
362        &self,
363        text: SharedString,
364        font_size: Pixels,
365        runs: &[TextRun],
366        force_width: Option<Pixels>,
367    ) -> ShapedLine {
368        debug_assert!(
369            text.find('\n').is_none(),
370            "text argument should not contain newlines"
371        );
372
373        let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
374        for run in runs {
375            if let Some(last_run) = decoration_runs.last_mut()
376                && last_run.color == run.color
377                && last_run.underline == run.underline
378                && last_run.strikethrough == run.strikethrough
379                && last_run.background_color == run.background_color
380            {
381                last_run.len += run.len as u32;
382                continue;
383            }
384            decoration_runs.push(DecorationRun {
385                len: run.len as u32,
386                color: run.color,
387                background_color: run.background_color,
388                underline: run.underline,
389                strikethrough: run.strikethrough,
390            });
391        }
392
393        let layout = self.layout_line(&text, font_size, runs, force_width);
394
395        ShapedLine {
396            layout,
397            text,
398            decoration_runs,
399        }
400    }
401
402    /// Shape a multi line string of text, at the given font_size, for painting to the screen.
403    /// Subsets of the text can be styled independently with the `runs` parameter.
404    /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
405    pub fn shape_text(
406        &self,
407        text: SharedString,
408        font_size: Pixels,
409        runs: &[TextRun],
410        wrap_width: Option<Pixels>,
411        line_clamp: Option<usize>,
412    ) -> Result<SmallVec<[WrappedLine; 1]>> {
413        let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
414        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
415
416        let mut lines = SmallVec::new();
417        let mut line_start = 0;
418        let mut max_wrap_lines = line_clamp.unwrap_or(usize::MAX);
419        let mut wrapped_lines = 0;
420
421        let mut process_line = |line_text: SharedString| {
422            let line_end = line_start + line_text.len();
423
424            let mut last_font: Option<Font> = None;
425            let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
426            let mut run_start = line_start;
427            while run_start < line_end {
428                let Some(run) = runs.peek_mut() else {
429                    break;
430                };
431
432                let mut run_len_within_line = cmp::min(line_end, run_start + run.len) - run_start;
433
434                // Ensure the run length respects UTF-8 character boundaries
435                if run_len_within_line > 0 {
436                    let text_slice = &line_text[run_start - line_start..];
437                    if run_len_within_line < text_slice.len()
438                        && !text_slice.is_char_boundary(run_len_within_line)
439                    {
440                        // Find the previous character boundary using efficient bit-level checking
441                        // UTF-8 characters are at most 4 bytes, so we only need to check up to 3 bytes back
442                        let lower_bound = run_len_within_line.saturating_sub(3);
443                        let search_range =
444                            &text_slice.as_bytes()[lower_bound..=run_len_within_line];
445
446                        // SAFETY: A valid character boundary must exist in this range because:
447                        // 1. run_len_within_line is a valid position in the string slice
448                        // 2. UTF-8 characters are at most 4 bytes, so some boundary exists in [run_len_within_line-3..=run_len_within_line]
449                        let pos_from_lower = unsafe {
450                            search_range
451                                .iter()
452                                .rposition(|&b| (b as i8) >= -0x40)
453                                .unwrap_unchecked()
454                        };
455
456                        run_len_within_line = lower_bound + pos_from_lower;
457                    }
458                }
459
460                if last_font == Some(run.font.clone()) {
461                    font_runs.last_mut().unwrap().len += run_len_within_line;
462                } else {
463                    last_font = Some(run.font.clone());
464                    font_runs.push(FontRun {
465                        len: run_len_within_line,
466                        font_id: self.resolve_font(&run.font),
467                    });
468                }
469
470                if decoration_runs.last().is_some_and(|last_run| {
471                    last_run.color == run.color
472                        && last_run.underline == run.underline
473                        && last_run.strikethrough == run.strikethrough
474                        && last_run.background_color == run.background_color
475                }) {
476                    decoration_runs.last_mut().unwrap().len += run_len_within_line as u32;
477                } else {
478                    decoration_runs.push(DecorationRun {
479                        len: run_len_within_line as u32,
480                        color: run.color,
481                        background_color: run.background_color,
482                        underline: run.underline,
483                        strikethrough: run.strikethrough,
484                    });
485                }
486
487                if run_len_within_line == run.len {
488                    runs.next();
489                } else {
490                    // Preserve the remainder of the run for the next line
491                    run.len -= run_len_within_line;
492                }
493                run_start += run_len_within_line;
494            }
495
496            let layout = self.line_layout_cache.layout_wrapped_line(
497                &line_text,
498                font_size,
499                &font_runs,
500                wrap_width,
501                Some(max_wrap_lines - wrapped_lines),
502            );
503            wrapped_lines += layout.wrap_boundaries.len();
504
505            lines.push(WrappedLine {
506                layout,
507                decoration_runs,
508                text: line_text,
509            });
510
511            // Skip `\n` character.
512            line_start = line_end + 1;
513            if let Some(run) = runs.peek_mut() {
514                run.len -= 1;
515                if run.len == 0 {
516                    runs.next();
517                }
518            }
519
520            font_runs.clear();
521        };
522
523        let mut split_lines = text.split('\n');
524        let mut processed = false;
525
526        if let Some(first_line) = split_lines.next()
527            && let Some(second_line) = split_lines.next()
528        {
529            processed = true;
530            process_line(first_line.to_string().into());
531            process_line(second_line.to_string().into());
532            for line_text in split_lines {
533                process_line(line_text.to_string().into());
534            }
535        }
536
537        if !processed {
538            process_line(text);
539        }
540
541        self.font_runs_pool.lock().push(font_runs);
542
543        Ok(lines)
544    }
545
546    pub(crate) fn finish_frame(&self) {
547        self.line_layout_cache.finish_frame()
548    }
549
550    /// Layout the given line of text, at the given font_size.
551    /// Subsets of the line can be styled independently with the `runs` parameter.
552    /// Generally, you should prefer to use [`Self::shape_line`] instead, which
553    /// can be painted directly.
554    pub fn layout_line<Text>(
555        &self,
556        text: Text,
557        font_size: Pixels,
558        runs: &[TextRun],
559        force_width: Option<Pixels>,
560    ) -> Arc<LineLayout>
561    where
562        Text: AsRef<str>,
563        SharedString: From<Text>,
564    {
565        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
566        for run in runs.iter() {
567            let font_id = self.resolve_font(&run.font);
568            if let Some(last_run) = font_runs.last_mut()
569                && last_run.font_id == font_id
570            {
571                last_run.len += run.len;
572                continue;
573            }
574            font_runs.push(FontRun {
575                len: run.len,
576                font_id,
577            });
578        }
579
580        let layout =
581            self.line_layout_cache
582                .layout_line_internal(text, font_size, &font_runs, force_width);
583
584        font_runs.clear();
585        self.font_runs_pool.lock().push(font_runs);
586
587        layout
588    }
589}
590
591#[derive(Hash, Eq, PartialEq)]
592struct FontIdWithSize {
593    font_id: FontId,
594    font_size: Pixels,
595}
596
597/// A handle into the text system, which can be used to compute the wrapped layout of text
598pub struct LineWrapperHandle {
599    wrapper: Option<LineWrapper>,
600    text_system: Arc<TextSystem>,
601}
602
603impl Drop for LineWrapperHandle {
604    fn drop(&mut self) {
605        let mut state = self.text_system.wrapper_pool.lock();
606        let wrapper = self.wrapper.take().unwrap();
607        state
608            .get_mut(&FontIdWithSize {
609                font_id: wrapper.font_id,
610                font_size: wrapper.font_size,
611            })
612            .unwrap()
613            .push(wrapper);
614    }
615}
616
617impl Deref for LineWrapperHandle {
618    type Target = LineWrapper;
619
620    fn deref(&self) -> &Self::Target {
621        self.wrapper.as_ref().unwrap()
622    }
623}
624
625impl DerefMut for LineWrapperHandle {
626    fn deref_mut(&mut self) -> &mut Self::Target {
627        self.wrapper.as_mut().unwrap()
628    }
629}
630
631/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
632/// with 400.0 as normal.
633#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, JsonSchema)]
634pub struct FontWeight(pub f32);
635
636impl Default for FontWeight {
637    #[inline]
638    fn default() -> FontWeight {
639        FontWeight::NORMAL
640    }
641}
642
643impl Hash for FontWeight {
644    fn hash<H: Hasher>(&self, state: &mut H) {
645        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
646    }
647}
648
649impl Eq for FontWeight {}
650
651impl FontWeight {
652    /// Thin weight (100), the thinnest value.
653    pub const THIN: FontWeight = FontWeight(100.0);
654    /// Extra light weight (200).
655    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
656    /// Light weight (300).
657    pub const LIGHT: FontWeight = FontWeight(300.0);
658    /// Normal (400).
659    pub const NORMAL: FontWeight = FontWeight(400.0);
660    /// Medium weight (500, higher than normal).
661    pub const MEDIUM: FontWeight = FontWeight(500.0);
662    /// Semibold weight (600).
663    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
664    /// Bold weight (700).
665    pub const BOLD: FontWeight = FontWeight(700.0);
666    /// Extra-bold weight (800).
667    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
668    /// Black weight (900), the thickest value.
669    pub const BLACK: FontWeight = FontWeight(900.0);
670
671    /// All of the font weights, in order from thinnest to thickest.
672    pub const ALL: [FontWeight; 9] = [
673        Self::THIN,
674        Self::EXTRA_LIGHT,
675        Self::LIGHT,
676        Self::NORMAL,
677        Self::MEDIUM,
678        Self::SEMIBOLD,
679        Self::BOLD,
680        Self::EXTRA_BOLD,
681        Self::BLACK,
682    ];
683}
684
685/// Allows italic or oblique faces to be selected.
686#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
687pub enum FontStyle {
688    /// A face that is neither italic not obliqued.
689    #[default]
690    Normal,
691    /// A form that is generally cursive in nature.
692    Italic,
693    /// A typically-sloped version of the regular face.
694    Oblique,
695}
696
697impl Display for FontStyle {
698    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
699        Debug::fmt(self, f)
700    }
701}
702
703/// A styled run of text, for use in [`crate::TextLayout`].
704#[derive(Clone, Debug, PartialEq, Eq)]
705pub struct TextRun {
706    /// A number of utf8 bytes
707    pub len: usize,
708    /// The font to use for this run.
709    pub font: Font,
710    /// The color
711    pub color: Hsla,
712    /// The background color (if any)
713    pub background_color: Option<Hsla>,
714    /// The underline style (if any)
715    pub underline: Option<UnderlineStyle>,
716    /// The strikethrough style (if any)
717    pub strikethrough: Option<StrikethroughStyle>,
718}
719
720#[cfg(all(target_os = "macos", test))]
721impl TextRun {
722    fn with_len(&self, len: usize) -> Self {
723        let mut this = self.clone();
724        this.len = len;
725        this
726    }
727}
728
729/// An identifier for a specific glyph, as returned by [`WindowTextSystem::layout_line`].
730#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
731#[repr(C)]
732pub struct GlyphId(pub(crate) u32);
733
734#[derive(Clone, Debug, PartialEq)]
735pub(crate) struct RenderGlyphParams {
736    pub(crate) font_id: FontId,
737    pub(crate) glyph_id: GlyphId,
738    pub(crate) font_size: Pixels,
739    pub(crate) subpixel_variant: Point<u8>,
740    pub(crate) scale_factor: f32,
741    pub(crate) is_emoji: bool,
742}
743
744impl Eq for RenderGlyphParams {}
745
746impl Hash for RenderGlyphParams {
747    fn hash<H: Hasher>(&self, state: &mut H) {
748        self.font_id.0.hash(state);
749        self.glyph_id.0.hash(state);
750        self.font_size.0.to_bits().hash(state);
751        self.subpixel_variant.hash(state);
752        self.scale_factor.to_bits().hash(state);
753        self.is_emoji.hash(state);
754    }
755}
756
757/// The configuration details for identifying a specific font.
758#[derive(Clone, Debug, Eq, PartialEq, Hash)]
759pub struct Font {
760    /// The font family name.
761    ///
762    /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
763    pub family: SharedString,
764
765    /// The font features to use.
766    pub features: FontFeatures,
767
768    /// The fallbacks fonts to use.
769    pub fallbacks: Option<FontFallbacks>,
770
771    /// The font weight.
772    pub weight: FontWeight,
773
774    /// The font style.
775    pub style: FontStyle,
776}
777
778/// Get a [`Font`] for a given name.
779pub fn font(family: impl Into<SharedString>) -> Font {
780    Font {
781        family: family.into(),
782        features: FontFeatures::default(),
783        weight: FontWeight::default(),
784        style: FontStyle::default(),
785        fallbacks: None,
786    }
787}
788
789impl Font {
790    /// Set this Font to be bold
791    pub fn bold(mut self) -> Self {
792        self.weight = FontWeight::BOLD;
793        self
794    }
795
796    /// Set this Font to be italic
797    pub fn italic(mut self) -> Self {
798        self.style = FontStyle::Italic;
799        self
800    }
801}
802
803/// A struct for storing font metrics.
804/// It is used to define the measurements of a typeface.
805#[derive(Clone, Copy, Debug)]
806pub struct FontMetrics {
807    /// The number of font units that make up the "em square",
808    /// a scalable grid for determining the size of a typeface.
809    pub(crate) units_per_em: u32,
810
811    /// The vertical distance from the baseline of the font to the top of the glyph covers.
812    pub(crate) ascent: f32,
813
814    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
815    pub(crate) descent: f32,
816
817    /// The recommended additional space to add between lines of type.
818    pub(crate) line_gap: f32,
819
820    /// The suggested position of the underline.
821    pub(crate) underline_position: f32,
822
823    /// The suggested thickness of the underline.
824    pub(crate) underline_thickness: f32,
825
826    /// The height of a capital letter measured from the baseline of the font.
827    pub(crate) cap_height: f32,
828
829    /// The height of a lowercase x.
830    pub(crate) x_height: f32,
831
832    /// The outer limits of the area that the font covers.
833    /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
834    pub(crate) bounding_box: Bounds<f32>,
835}
836
837impl FontMetrics {
838    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
839    pub fn ascent(&self, font_size: Pixels) -> Pixels {
840        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
841    }
842
843    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
844    pub fn descent(&self, font_size: Pixels) -> Pixels {
845        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
846    }
847
848    /// Returns the recommended additional space to add between lines of type in pixels.
849    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
850        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
851    }
852
853    /// Returns the suggested position of the underline in pixels.
854    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
855        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
856    }
857
858    /// Returns the suggested thickness of the underline in pixels.
859    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
860        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
861    }
862
863    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
864    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
865        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
866    }
867
868    /// Returns the height of a lowercase x in pixels.
869    pub fn x_height(&self, font_size: Pixels) -> Pixels {
870        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
871    }
872
873    /// Returns the outer limits of the area that the font covers in pixels.
874    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
875        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
876    }
877}
878
879#[allow(unused)]
880pub(crate) fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
881    // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
882    // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
883    // and so retained here for backward compatibility.
884    match name {
885        ".SystemUIFont" => system,
886        ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
887        ".ZedMono" | "Zed Plex Mono" => "Lilex",
888        _ => name,
889    }
890}