Skip to main content

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