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