Skip to main content

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