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