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