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