Skip to main content

gpui/
text_system.rs

1// Modified by Longbridge for gpui-fast.
2mod font_fallbacks;
3mod font_features;
4mod line;
5mod line_layout;
6mod line_wrapper;
7
8pub use font_fallbacks::*;
9pub use font_features::*;
10pub use line::*;
11pub use line_layout::*;
12pub use line_wrapper::*;
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
18    StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
19};
20use anyhow::{Context as _, anyhow};
21use collections::{FxHashMap, FxHashSet};
22use core::fmt;
23use derive_more::{Add, Deref, FromStr, Sub};
24use itertools::Itertools;
25use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
26use smallvec::{SmallVec, smallvec};
27use std::{
28    borrow::Cow,
29    cmp,
30    collections::VecDeque,
31    fmt::{Debug, Display, Formatter},
32    hash::{Hash, Hasher},
33    ops::{Deref, DerefMut, Range},
34    sync::{
35        Arc,
36        atomic::{AtomicUsize, Ordering},
37    },
38};
39
40/// An opaque identifier for a specific font.
41#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
42#[repr(C)]
43pub struct FontId(pub usize);
44
45/// An opaque identifier for a specific font family.
46#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
47pub struct FontFamilyId(pub usize);
48
49/// Number of subpixel glyph variants along the X axis.
50pub const SUBPIXEL_VARIANTS_X: u8 = 4;
51
52/// Number of subpixel glyph variants along the Y axis.
53pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
54
55// Leave enough room below the underline for its stroke while keeping it below the baseline.
56const UNDERLINE_DESCENT_OFFSET_FACTOR: f32 = 0.618;
57
58/// Returns the vertical offset used to paint an underline within a line.
59pub fn underline_y_offset(line_height: Pixels, ascent: Pixels, descent: Pixels) -> Pixels {
60    let padding_top = (line_height - ascent - descent) / 2.;
61    padding_top + ascent + descent * UNDERLINE_DESCENT_OFFSET_FACTOR
62}
63
64const MAX_REPORTED_MISSING_GLYPHS: usize = 1024;
65
66/// The spacing behavior required of a fallback font.
67#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
68pub enum FallbackFontClass {
69    /// A proportionally spaced fallback font.
70    Proportional,
71    /// A fixed-width fallback font.
72    Monospace,
73}
74
75/// A grapheme cluster that could not be represented by any available font.
76#[derive(Clone, Debug, Eq, Hash, PartialEq)]
77pub struct MissingGlyph {
78    grapheme: SharedString,
79    font_class: FallbackFontClass,
80}
81
82impl MissingGlyph {
83    /// Creates a missing-glyph report.
84    pub fn new(grapheme: SharedString, font_class: FallbackFontClass) -> Self {
85        Self {
86            grapheme,
87            font_class,
88        }
89    }
90
91    /// Returns the unresolved grapheme cluster.
92    pub fn grapheme(&self) -> &str {
93        &self.grapheme
94    }
95
96    /// Returns the spacing behavior required of a fallback font.
97    pub fn font_class(&self) -> FallbackFontClass {
98        self.font_class
99    }
100}
101
102/// Accepts missing glyphs detected by a platform text system.
103pub trait MissingGlyphSink: Send + Sync {
104    /// Reports grapheme clusters that exhausted font fallback.
105    fn report(&self, missing_glyphs: Vec<MissingGlyph>);
106}
107
108#[derive(Default)]
109struct MissingGlyphState {
110    reported: FxHashSet<MissingGlyph>,
111    reported_order: VecDeque<MissingGlyph>,
112    generation: usize,
113}
114
115impl MissingGlyphState {
116    fn reset(&mut self, generation: usize) {
117        self.reported.clear();
118        self.reported_order.clear();
119        self.generation = generation;
120    }
121}
122
123struct QueuedMissingGlyph {
124    generation: usize,
125    missing_glyph: MissingGlyph,
126}
127
128/// Collects missing-glyph reports without invoking application code during layout.
129struct MissingGlyphReporter {
130    generation: Arc<AtomicUsize>,
131    sender: async_channel::Sender<QueuedMissingGlyph>,
132}
133
134impl MissingGlyphSink for MissingGlyphReporter {
135    fn report(&self, missing_glyphs: Vec<MissingGlyph>) {
136        if self.sender.is_closed() {
137            return;
138        }
139
140        let generation = self.generation.load(Ordering::Acquire);
141        // Repetitions within a line must not fill the queue before its other
142        // missing glyphs. Cross-report deduplication belongs to the receiver.
143        for missing_glyph in missing_glyphs.into_iter().unique() {
144            let queued = QueuedMissingGlyph {
145                generation,
146                missing_glyph,
147            };
148            if self.sender.try_send(queued).is_err() {
149                break;
150            }
151        }
152    }
153}
154
155impl MissingGlyphReporter {
156    fn reset(&self) {
157        self.generation.fetch_add(1, Ordering::AcqRel);
158    }
159}
160
161/// Receives batches of grapheme clusters that exhausted font fallback.
162pub(crate) struct MissingGlyphReceiver {
163    state: MissingGlyphState,
164    generation: Arc<AtomicUsize>,
165    receiver: async_channel::Receiver<QueuedMissingGlyph>,
166}
167
168impl MissingGlyphReceiver {
169    /// Waits until at least one new missing glyph has been observed.
170    ///
171    /// # Errors
172    ///
173    /// Returns [`async_channel::RecvError`] if the reporting channel is closed.
174    pub(crate) async fn recv(
175        &mut self,
176    ) -> std::result::Result<Vec<MissingGlyph>, async_channel::RecvError> {
177        loop {
178            let queued = self.receiver.recv().await?;
179            let mut missing_glyphs = Vec::new();
180            for queued in std::iter::once(queued)
181                .chain(std::iter::from_fn(|| self.receiver.try_recv().ok()))
182                .take(MAX_REPORTED_MISSING_GLYPHS)
183            {
184                let generation = self.generation.load(Ordering::Acquire);
185                if self.state.generation != generation {
186                    self.state.reset(generation);
187                    missing_glyphs.clear();
188                }
189                if queued.generation != generation
190                    || !self.state.reported.insert(queued.missing_glyph.clone())
191                {
192                    continue;
193                }
194                self.state
195                    .reported_order
196                    .push_back(queued.missing_glyph.clone());
197                missing_glyphs.push(queued.missing_glyph);
198                if self.state.reported.len() > MAX_REPORTED_MISSING_GLYPHS
199                    && let Some(expired) = self.state.reported_order.pop_front()
200                {
201                    self.state.reported.remove(&expired);
202                }
203            }
204            if !missing_glyphs.is_empty() {
205                return Ok(missing_glyphs);
206            }
207            // A producer can keep refilling the queue with already-reported
208            // glyphs. Bound work per poll even when every report is filtered out.
209            let mut yielded = false;
210            std::future::poll_fn(|cx| {
211                if std::mem::replace(&mut yielded, true) {
212                    std::task::Poll::Ready(())
213                } else {
214                    cx.waker().wake_by_ref();
215                    std::task::Poll::Pending
216                }
217            })
218            .await;
219        }
220    }
221}
222
223impl Drop for MissingGlyphReceiver {
224    fn drop(&mut self) {
225        self.receiver.close();
226        while self.receiver.try_recv().is_ok() {}
227    }
228}
229
230/// The GPUI text rendering sub system.
231pub struct TextSystem {
232    pub(crate) platform_text_system: Arc<dyn PlatformTextSystem>,
233    font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
234    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
235    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
236    wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
237    font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
238    pub(crate) fallback_font_stack: SmallVec<[Font; 2]>,
239    font_generation: Arc<AtomicUsize>,
240    missing_glyph_reporter: Arc<MissingGlyphReporter>,
241    missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,
242}
243
244impl TextSystem {
245    /// Create a new TextSystem with the given platform text system.
246    pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
247        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
248        let missing_glyph_generation = Arc::<AtomicUsize>::default();
249        TextSystem {
250            platform_text_system,
251            font_metrics: RwLock::default(),
252            raster_bounds: RwLock::default(),
253            font_ids_by_font: RwLock::default(),
254            wrapper_pool: Mutex::default(),
255            font_runs_pool: Mutex::default(),
256            fallback_font_stack: smallvec![
257                // TODO: Remove this when Linux have implemented setting fallbacks.
258                font(".ZedMono"),
259                font(".ZedSans"),
260                font("Helvetica"),
261                font("Segoe UI"),     // Windows
262                font("Ubuntu"),       // Gnome (Ubuntu)
263                font("Adwaita Sans"), // Gnome 47
264                font("Cantarell"),    // Gnome
265                font("Noto Sans"),    // KDE
266                font("DejaVu Sans"),
267                font("Arial"), // macOS, Windows
268            ],
269            font_generation: Arc::default(),
270            missing_glyph_reporter: Arc::new(MissingGlyphReporter {
271                generation: missing_glyph_generation.clone(),
272                sender,
273            }),
274            missing_glyph_receiver: Mutex::new(Some(MissingGlyphReceiver {
275                state: MissingGlyphState::default(),
276                generation: missing_glyph_generation,
277                receiver,
278            })),
279        }
280    }
281
282    /// Get sorted, unique font family names available to the platform text system.
283    ///
284    /// Includes fonts registered with [`Self::add_fonts`].
285    pub fn all_font_names(&self) -> Vec<String> {
286        let mut names = self.platform_text_system.all_font_names();
287        names.sort_unstable();
288        names.dedup();
289        names
290    }
291
292    /// Add a font's data to the text system.
293    ///
294    /// Cached font resolution and line layouts are invalidated after installation.
295    /// Layouts already in progress may complete against the previous font set.
296    pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
297        crate::fast::text::fonts_changed();
298        self.platform_text_system.add_fonts(fonts)?;
299        self.font_ids_by_font.write().clear();
300        self.missing_glyph_reporter.reset();
301        self.font_generation.fetch_add(1, Ordering::Release);
302        Ok(())
303    }
304
305    /// Takes the receiver for missing-glyph reports.
306    ///
307    /// Only one receiver is available for each text system. Returns `None` when
308    /// the receiver was already taken or another caller is taking it.
309    pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
310        self.missing_glyph_receiver
311            .try_lock()
312            .and_then(|mut receiver| receiver.take())
313    }
314
315    pub(crate) fn enable_missing_glyph_reporting(&self) {
316        self.platform_text_system
317            .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
318    }
319
320    pub(crate) fn disable_missing_glyph_reporting(&self) {
321        self.platform_text_system.set_missing_glyph_sink(None);
322        self.missing_glyph_reporter.reset();
323    }
324
325    #[cfg(test)]
326    pub(crate) fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
327        self.missing_glyph_reporter.report(missing_glyphs);
328    }
329
330    /// Get the FontId for the configure font family and style.
331    pub(crate) fn font_id(&self, font: &Font) -> Result<FontId> {
332        fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
333            match font_id {
334                Ok(font_id) => Ok(*font_id),
335                Err(err) => Err(anyhow!("{err}")),
336            }
337        }
338
339        let font_id = self
340            .font_ids_by_font
341            .read()
342            .get(font)
343            .map(clone_font_id_result);
344        if let Some(font_id) = font_id {
345            font_id
346        } else {
347            let font_id = self.platform_text_system.font_id(font);
348            self.font_ids_by_font
349                .write()
350                .insert(font.clone(), clone_font_id_result(&font_id));
351            font_id
352        }
353    }
354
355    /// Get the Font for the Font Id.
356    pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
357        let lock = self.font_ids_by_font.read();
358        lock.iter()
359            .filter_map(|(font, result)| match result {
360                Ok(font_id) if *font_id == id => Some(font.clone()),
361                _ => None,
362            })
363            .next()
364    }
365
366    /// Resolves the specified font, falling back to the default font stack if
367    /// the font fails to load.
368    ///
369    /// # Panics
370    ///
371    /// Panics if the font and none of the fallbacks can be resolved.
372    pub fn resolve_font(&self, font: &Font) -> FontId {
373        crate::fast::text::resolve_font(self, font)
374    }
375
376    /// Prewarm any system font caches needed to shape text.
377    ///
378    /// This may be expensive, so callers should generally invoke it on a
379    /// background executor. Missing entries are still populated on demand by
380    /// the normal shaping path.
381    pub fn prewarm_fonts(&self, fonts: &[Font]) {
382        let mut font_ids = SmallVec::<[FontId; 8]>::new();
383        for font in fonts {
384            let font_id = self.resolve_font(font);
385            if !font_ids.contains(&font_id) {
386                font_ids.push(font_id);
387            }
388        }
389        self.platform_text_system.prewarm_fonts(&font_ids);
390    }
391
392    /// Get the bounding box for the given font and font size.
393    /// A font's bounding box is the smallest rectangle that could enclose all glyphs
394    /// in the font. superimposed over one another.
395    pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
396        self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
397    }
398
399    /// Get the typographic bounds for the given character, in the given font and size.
400    pub fn typographic_bounds(
401        &self,
402        font_id: FontId,
403        font_size: Pixels,
404        character: char,
405    ) -> Result<Bounds<Pixels>> {
406        let glyph_id = self
407            .platform_text_system
408            .glyph_for_char(font_id, character)
409            .with_context(|| format!("glyph not found for character '{character}'"))?;
410        let bounds = self
411            .platform_text_system
412            .typographic_bounds(font_id, glyph_id)?;
413        Ok(self.read_metrics(font_id, |metrics| {
414            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
415        }))
416    }
417
418    /// Get the advance width for the given character, in the given font and size.
419    pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
420        let glyph_id = self
421            .platform_text_system
422            .glyph_for_char(font_id, ch)
423            .with_context(|| format!("glyph not found for character '{ch}'"))?;
424        let result = self.platform_text_system.advance(font_id, glyph_id)?
425            / self.units_per_em(font_id) as f32;
426
427        Ok(result * font_size)
428    }
429
430    // Consider removing this?
431    /// Returns the shaped layout width of for the given character, in the given font and size.
432    pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
433        let mut buffer = [0; 4];
434        let buffer = ch.encode_utf8(&mut buffer);
435        self.platform_text_system
436            .layout_line(
437                buffer,
438                font_size,
439                &[FontRun {
440                    len: buffer.len(),
441                    font_id,
442                }],
443            )
444            .width
445    }
446
447    /// Returns the width of an `em`.
448    ///
449    /// Uses the width of the `m` character in the given font and size.
450    pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
451        Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
452    }
453
454    /// Returns the advance width of an `em`.
455    ///
456    /// Uses the advance width of the `m` character in the given font and size.
457    pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
458        Ok(self.advance(font_id, font_size, 'm')?.width)
459    }
460
461    /// Returns the width of an `ch`.
462    ///
463    /// Uses the width of the `0` character in the given font and size.
464    pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
465        Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
466    }
467
468    /// Returns the advance width of an `ch`.
469    ///
470    /// Uses the advance width of the `0` character in the given font and size.
471    pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
472        Ok(self.advance(font_id, font_size, '0')?.width)
473    }
474
475    /// Get the number of font size units per 'em square',
476    /// Per MDN: "an abstract square whose height is the intended distance between
477    /// lines of type in the same type size"
478    pub fn units_per_em(&self, font_id: FontId) -> u32 {
479        self.read_metrics(font_id, |metrics| metrics.units_per_em)
480    }
481
482    /// Get the height of a capital letter in the given font and size.
483    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
484        self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
485    }
486
487    /// Get the height of the x character in the given font and size.
488    pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
489        self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
490    }
491
492    /// Get the recommended distance from the baseline for the given font
493    pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
494        self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
495    }
496
497    /// Get the recommended distance below the baseline for the given font,
498    /// in single spaced text.
499    pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
500        self.read_metrics(font_id, |metrics| metrics.descent(font_size))
501    }
502
503    /// Get the recommended baseline offset for the given font and line height.
504    pub fn baseline_offset(
505        &self,
506        font_id: FontId,
507        font_size: Pixels,
508        line_height: Pixels,
509    ) -> Pixels {
510        let ascent = self.ascent(font_id, font_size);
511        let descent = self.descent(font_id, font_size);
512        let padding_top = (line_height - ascent - descent) / 2.;
513        padding_top + ascent
514    }
515
516    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
517        let lock = self.font_metrics.upgradable_read();
518
519        if let Some(metrics) = lock.get(&font_id) {
520            read(metrics)
521        } else {
522            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
523            let metrics = lock
524                .entry(font_id)
525                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
526            read(metrics)
527        }
528    }
529
530    /// Returns a handle to a line wrapper, for the given font and font size.
531    pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
532        let lock = &mut self.wrapper_pool.lock();
533        let font_id = self.resolve_font(&font);
534        let wrappers = lock
535            .entry(FontIdWithSize { font_id, font_size })
536            .or_default();
537        let wrapper = wrappers
538            .pop()
539            .unwrap_or_else(|| LineWrapper::new(font_id, font_size, self.clone()));
540
541        LineWrapperHandle {
542            wrapper: Some(wrapper),
543            text_system: self.clone(),
544        }
545    }
546
547    /// Get the rasterized size and location of a specific, rendered glyph.
548    pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
549        let raster_bounds = self.raster_bounds.upgradable_read();
550        if let Some(bounds) = raster_bounds.get(params) {
551            Ok(*bounds)
552        } else {
553            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
554            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
555            raster_bounds.insert(params.clone(), bounds);
556            Ok(bounds)
557        }
558    }
559
560    pub(crate) fn rasterize_glyph(
561        &self,
562        params: &RenderGlyphParams,
563    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
564        let raster_bounds = self.raster_bounds(params)?;
565        self.platform_text_system
566            .rasterize_glyph(params, raster_bounds)
567    }
568
569    /// Returns the dilation level to use for a glyph painted in the given color.
570    pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
571        self.platform_text_system.glyph_dilation_for_color(color)
572    }
573
574    /// Returns the text rendering mode recommended by the platform for the given font and size.
575    /// The return value will never be [`TextRenderingMode::PlatformDefault`].
576    pub(crate) fn recommended_rendering_mode(
577        &self,
578        font_id: FontId,
579        font_size: Pixels,
580    ) -> TextRenderingMode {
581        self.platform_text_system
582            .recommended_rendering_mode(font_id, font_size)
583    }
584}
585
586/// The GPUI text layout subsystem.
587#[derive(Deref)]
588pub struct WindowTextSystem {
589    pub(crate) line_layout_cache: LineLayoutCache,
590    #[deref]
591    text_system: Arc<TextSystem>,
592}
593
594impl WindowTextSystem {
595    /// Create a new WindowTextSystem with the given TextSystem.
596    pub fn new(text_system: Arc<TextSystem>) -> Self {
597        Self {
598            line_layout_cache: LineLayoutCache::new(
599                text_system.platform_text_system.clone(),
600                text_system.font_generation.clone(),
601            ),
602            text_system,
603        }
604    }
605
606    pub(crate) fn layout_index(&self) -> LineLayoutIndex {
607        self.line_layout_cache.layout_index()
608    }
609
610    pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
611        self.line_layout_cache.reuse_layouts(index)
612    }
613
614    pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
615        self.line_layout_cache.truncate_layouts(index)
616    }
617
618    /// Shape the given line, at the given font_size, for painting to the screen.
619    /// Subsets of the line can be styled independently with the `runs` parameter.
620    ///
621    /// Note that this method can only shape a single line of text. It will panic
622    /// if the text contains newlines. If you need to shape multiple lines of text,
623    /// use [`Self::shape_text`] instead.
624    pub fn shape_line(
625        &self,
626        text: SharedString,
627        font_size: Pixels,
628        runs: &[TextRun],
629        force_width: Option<Pixels>,
630    ) -> ShapedLine {
631        debug_assert!(
632            text.find('\n').is_none(),
633            "text argument should not contain newlines"
634        );
635
636        let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
637        for run in runs {
638            if let Some(last_run) = decoration_runs.last_mut()
639                && last_run.color == run.color
640                && last_run.underline == run.underline
641                && last_run.strikethrough == run.strikethrough
642                && last_run.background_color == run.background_color
643            {
644                last_run.len += run.len as u32;
645                continue;
646            }
647            decoration_runs.push(DecorationRun {
648                len: run.len as u32,
649                color: run.color,
650                background_color: run.background_color,
651                underline: run.underline,
652                strikethrough: run.strikethrough,
653            });
654        }
655
656        let layout = self.layout_line(&text, font_size, runs, force_width);
657
658        ShapedLine {
659            layout,
660            text,
661            decoration_runs,
662        }
663    }
664
665    /// Shape the given line using a caller-provided content hash as the cache key.
666    ///
667    /// This enables cache hits without materializing a contiguous `SharedString` for the text.
668    /// If the cache misses, `materialize_text` is invoked to produce the `SharedString` for shaping.
669    ///
670    /// Contract (caller enforced):
671    /// - Same `text_hash` implies identical text content (collision risk accepted by caller).
672    /// - `text_len` should be the UTF-8 byte length of the text (helps reduce accidental collisions).
673    ///
674    /// Like [`Self::shape_line`], this must be used only for single-line text (no `\n`).
675    pub fn shape_line_by_hash(
676        &self,
677        text_hash: u64,
678        text_len: usize,
679        font_size: Pixels,
680        runs: &[TextRun],
681        force_width: Option<Pixels>,
682        materialize_text: impl FnOnce() -> SharedString,
683    ) -> ShapedLine {
684        let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
685        for run in runs {
686            if let Some(last_run) = decoration_runs.last_mut()
687                && last_run.color == run.color
688                && last_run.underline == run.underline
689                && last_run.strikethrough == run.strikethrough
690                && last_run.background_color == run.background_color
691            {
692                last_run.len += run.len as u32;
693                continue;
694            }
695            decoration_runs.push(DecorationRun {
696                len: run.len as u32,
697                color: run.color,
698                background_color: run.background_color,
699                underline: run.underline,
700                strikethrough: run.strikethrough,
701            });
702        }
703
704        let mut used_force_width = force_width;
705        let layout = self.layout_line_by_hash(
706            text_hash,
707            text_len,
708            font_size,
709            runs,
710            used_force_width,
711            || {
712                let text = materialize_text();
713                debug_assert!(
714                    text.find('\n').is_none(),
715                    "text argument should not contain newlines"
716                );
717                text
718            },
719        );
720
721        // We only materialize actual text on cache miss; on hit we avoid allocations.
722        // Since `ShapedLine` carries a `SharedString`, use an empty placeholder for hits.
723        // NOTE: Callers must not rely on `ShapedLine.text` for content when using this API.
724        let text: SharedString = SharedString::new_static("");
725
726        ShapedLine {
727            layout,
728            text,
729            decoration_runs,
730        }
731    }
732
733    /// Shape a multi line string of text, at the given font_size, for painting to the screen.
734    /// Subsets of the text can be styled independently with the `runs` parameter.
735    /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
736    pub fn shape_text(
737        &self,
738        text: SharedString,
739        font_size: Pixels,
740        runs: &[TextRun],
741        wrap_width: Option<Pixels>,
742        line_clamp: Option<usize>,
743    ) -> Result<SmallVec<[WrappedLine; 1]>> {
744        let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
745        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
746
747        let mut lines = SmallVec::new();
748        let mut max_wrap_lines = line_clamp;
749        let mut wrapped_lines = 0;
750
751        let mut process_line = |line_text: SharedString, line_start, line_end| {
752            font_runs.clear();
753
754            let mut decoration_runs = crate::fast::text::decoration_runs();
755            let mut run_start = line_start;
756            while run_start < line_end {
757                let Some(run) = runs.peek_mut() else {
758                    log::warn!("`TextRun`s do not cover the entire to be shaped text");
759                    break;
760                };
761
762                let run_len_within_line = cmp::min(line_end - run_start, run.len);
763
764                let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
765                    && last_run.color == run.color
766                    && last_run.underline == run.underline
767                    && last_run.strikethrough == run.strikethrough
768                    && last_run.background_color == run.background_color
769                {
770                    last_run.len += run_len_within_line as u32;
771                    false
772                } else {
773                    decoration_runs.push(DecorationRun {
774                        len: run_len_within_line as u32,
775                        color: run.color,
776                        background_color: run.background_color,
777                        underline: run.underline,
778                        strikethrough: run.strikethrough,
779                    });
780                    true
781                };
782
783                let font_id = self.resolve_font(&run.font);
784                if let Some(font_run) = font_runs.last_mut()
785                    && font_id == font_run.font_id
786                    && !decoration_changed
787                {
788                    font_run.len += run_len_within_line;
789                } else {
790                    font_runs.push(FontRun {
791                        len: run_len_within_line,
792                        font_id,
793                    });
794                }
795
796                // Preserve the remainder of the run for the next line
797                run.len -= run_len_within_line;
798                if run.len == 0 {
799                    runs.next();
800                }
801                run_start += run_len_within_line;
802            }
803
804            let layout = self.line_layout_cache.layout_wrapped_line(
805                &line_text,
806                font_size,
807                &font_runs,
808                wrap_width,
809                max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
810            );
811            wrapped_lines += layout.wrap_boundaries.len();
812
813            lines.push(WrappedLine {
814                layout,
815                decoration_runs,
816                text: line_text,
817            });
818
819            // Skip `\n` character.
820            if let Some(run) = runs.peek_mut() {
821                run.len -= 1;
822                if run.len == 0 {
823                    runs.next();
824                }
825            }
826        };
827
828        let mut split_lines = text.split('\n');
829
830        // Special case single lines to prevent allocating a sharedstring
831        if let Some(first_line) = split_lines.next()
832            && let Some(second_line) = split_lines.next()
833        {
834            let mut line_start = 0;
835            process_line(
836                SharedString::new(first_line),
837                line_start,
838                line_start + first_line.len(),
839            );
840            line_start += first_line.len() + '\n'.len_utf8();
841            process_line(
842                SharedString::new(second_line),
843                line_start,
844                line_start + second_line.len(),
845            );
846            for line_text in split_lines {
847                line_start += line_text.len() + '\n'.len_utf8();
848                process_line(
849                    SharedString::new(line_text),
850                    line_start,
851                    line_start + line_text.len(),
852                );
853            }
854        } else {
855            let end = text.len();
856            process_line(text, 0, end);
857        }
858
859        self.font_runs_pool.lock().push(font_runs);
860
861        Ok(lines)
862    }
863
864    pub(crate) fn finish_frame(&self) {
865        self.line_layout_cache.finish_frame()
866    }
867
868    /// Layout the given line of text, at the given font_size.
869    /// Subsets of the line can be styled independently with the `runs` parameter.
870    /// Generally, you should prefer to use [`Self::shape_line`] instead, which
871    /// can be painted directly.
872    pub fn layout_line(
873        &self,
874        text: &str,
875        font_size: Pixels,
876        runs: &[TextRun],
877        force_width: Option<Pixels>,
878    ) -> Arc<LineLayout> {
879        let mut last_run = None::<&TextRun>;
880        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
881        font_runs.clear();
882
883        for run in runs.iter() {
884            let decoration_changed = if let Some(last_run) = last_run
885                && last_run.color == run.color
886                && last_run.underline == run.underline
887                && last_run.strikethrough == run.strikethrough
888            // we do not consider differing background color relevant, as it does not affect glyphs
889            // && last_run.background_color == run.background_color
890            {
891                false
892            } else {
893                last_run = Some(run);
894                true
895            };
896
897            let font_id = self.resolve_font(&run.font);
898            if let Some(font_run) = font_runs.last_mut()
899                && font_id == font_run.font_id
900                && !decoration_changed
901            {
902                font_run.len += run.len;
903            } else {
904                font_runs.push(FontRun {
905                    len: run.len,
906                    font_id,
907                });
908            }
909        }
910
911        let layout = self.line_layout_cache.layout_line(
912            &SharedString::new(text),
913            font_size,
914            &font_runs,
915            force_width,
916        );
917
918        self.font_runs_pool.lock().push(font_runs);
919
920        layout
921    }
922
923    /// Returns the shaped layout width of for the given character, in the given font and size.
924    pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
925        let mut buffer = [0; 4];
926        let buffer: &_ = ch.encode_utf8(&mut buffer);
927        self.line_layout_cache
928            .layout_line(
929                buffer,
930                font_size,
931                &[FontRun {
932                    len: buffer.len(),
933                    font_id,
934                }],
935                None,
936            )
937            .width
938    }
939
940    /// Returns the shaped layout width of an `em`.
941    pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
942        self.layout_width(font_id, font_size, 'm')
943    }
944
945    /// Probe the line layout cache using a caller-provided content hash, without allocating.
946    ///
947    /// Returns `Some(layout)` if the layout is already cached in either the current frame
948    /// or the previous frame. Returns `None` if it is not cached.
949    ///
950    /// Contract (caller enforced):
951    /// - Same `text_hash` implies identical text content (collision risk accepted by caller).
952    /// - `text_len` should be the UTF-8 byte length of the text (helps reduce accidental collisions).
953    pub fn try_layout_line_by_hash(
954        &self,
955        text_hash: u64,
956        text_len: usize,
957        font_size: Pixels,
958        runs: &[TextRun],
959        force_width: Option<Pixels>,
960    ) -> Option<Arc<LineLayout>> {
961        let mut last_run = None::<&TextRun>;
962        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
963        font_runs.clear();
964
965        for run in runs.iter() {
966            let decoration_changed = if let Some(last_run) = last_run
967                && last_run.color == run.color
968                && last_run.underline == run.underline
969                && last_run.strikethrough == run.strikethrough
970            // we do not consider differing background color relevant, as it does not affect glyphs
971            // && last_run.background_color == run.background_color
972            {
973                false
974            } else {
975                last_run = Some(run);
976                true
977            };
978
979            let font_id = self.resolve_font(&run.font);
980            if let Some(font_run) = font_runs.last_mut()
981                && font_id == font_run.font_id
982                && !decoration_changed
983            {
984                font_run.len += run.len;
985            } else {
986                font_runs.push(FontRun {
987                    len: run.len,
988                    font_id,
989                });
990            }
991        }
992
993        let layout = self.line_layout_cache.try_layout_line_by_hash(
994            text_hash,
995            text_len,
996            font_size,
997            &font_runs,
998            force_width,
999        );
1000
1001        self.font_runs_pool.lock().push(font_runs);
1002
1003        layout
1004    }
1005
1006    /// Layout the given line of text using a caller-provided content hash as the cache key.
1007    ///
1008    /// This enables cache hits without materializing a contiguous `SharedString` for the text.
1009    /// If the cache misses, `materialize_text` is invoked to produce the `SharedString` for shaping.
1010    ///
1011    /// Contract (caller enforced):
1012    /// - Same `text_hash` implies identical text content (collision risk accepted by caller).
1013    /// - `text_len` should be the UTF-8 byte length of the text (helps reduce accidental collisions).
1014    pub fn layout_line_by_hash(
1015        &self,
1016        text_hash: u64,
1017        text_len: usize,
1018        font_size: Pixels,
1019        runs: &[TextRun],
1020        force_width: Option<Pixels>,
1021        materialize_text: impl FnOnce() -> SharedString,
1022    ) -> Arc<LineLayout> {
1023        let mut last_run = None::<&TextRun>;
1024        let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
1025        font_runs.clear();
1026
1027        for run in runs.iter() {
1028            let decoration_changed = if let Some(last_run) = last_run
1029                && last_run.color == run.color
1030                && last_run.underline == run.underline
1031                && last_run.strikethrough == run.strikethrough
1032            // we do not consider differing background color relevant, as it does not affect glyphs
1033            // && last_run.background_color == run.background_color
1034            {
1035                false
1036            } else {
1037                last_run = Some(run);
1038                true
1039            };
1040
1041            let font_id = self.resolve_font(&run.font);
1042            if let Some(font_run) = font_runs.last_mut()
1043                && font_id == font_run.font_id
1044                && !decoration_changed
1045            {
1046                font_run.len += run.len;
1047            } else {
1048                font_runs.push(FontRun {
1049                    len: run.len,
1050                    font_id,
1051                });
1052            }
1053        }
1054
1055        let layout = self.line_layout_cache.layout_line_by_hash(
1056            text_hash,
1057            text_len,
1058            font_size,
1059            &font_runs,
1060            force_width,
1061            materialize_text,
1062        );
1063
1064        self.font_runs_pool.lock().push(font_runs);
1065
1066        layout
1067    }
1068}
1069
1070#[derive(Hash, Eq, PartialEq)]
1071struct FontIdWithSize {
1072    font_id: FontId,
1073    font_size: Pixels,
1074}
1075
1076/// A handle into the text system, which can be used to compute the wrapped layout of text
1077pub struct LineWrapperHandle {
1078    wrapper: Option<LineWrapper>,
1079    text_system: Arc<TextSystem>,
1080}
1081
1082impl Drop for LineWrapperHandle {
1083    fn drop(&mut self) {
1084        let mut state = self.text_system.wrapper_pool.lock();
1085        let wrapper = self.wrapper.take().unwrap();
1086        state
1087            .get_mut(&FontIdWithSize {
1088                font_id: wrapper.font_id,
1089                font_size: wrapper.font_size,
1090            })
1091            .unwrap()
1092            .push(wrapper);
1093    }
1094}
1095
1096impl Deref for LineWrapperHandle {
1097    type Target = LineWrapper;
1098
1099    fn deref(&self) -> &Self::Target {
1100        self.wrapper.as_ref().unwrap()
1101    }
1102}
1103
1104impl DerefMut for LineWrapperHandle {
1105    fn deref_mut(&mut self) -> &mut Self::Target {
1106        self.wrapper.as_mut().unwrap()
1107    }
1108}
1109
1110/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
1111/// with 400.0 as normal.
1112#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
1113#[serde(transparent)]
1114pub struct FontWeight(pub f32);
1115
1116impl Display for FontWeight {
1117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1118        write!(f, "{}", self.0)
1119    }
1120}
1121
1122impl From<f32> for FontWeight {
1123    fn from(weight: f32) -> Self {
1124        FontWeight(weight)
1125    }
1126}
1127
1128impl Default for FontWeight {
1129    #[inline]
1130    fn default() -> FontWeight {
1131        FontWeight::NORMAL
1132    }
1133}
1134
1135impl Hash for FontWeight {
1136    fn hash<H: Hasher>(&self, state: &mut H) {
1137        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
1138    }
1139}
1140
1141impl Eq for FontWeight {}
1142
1143impl FontWeight {
1144    /// Thin weight (100), the thinnest value.
1145    pub const THIN: FontWeight = FontWeight(100.0);
1146    /// Extra light weight (200).
1147    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1148    /// Light weight (300).
1149    pub const LIGHT: FontWeight = FontWeight(300.0);
1150    /// Normal (400).
1151    pub const NORMAL: FontWeight = FontWeight(400.0);
1152    /// Medium weight (500, higher than normal).
1153    pub const MEDIUM: FontWeight = FontWeight(500.0);
1154    /// Semibold weight (600).
1155    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1156    /// Bold weight (700).
1157    pub const BOLD: FontWeight = FontWeight(700.0);
1158    /// Extra-bold weight (800).
1159    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1160    /// Black weight (900), the thickest value.
1161    pub const BLACK: FontWeight = FontWeight(900.0);
1162
1163    /// All of the font weights, in order from thinnest to thickest.
1164    pub const ALL: [FontWeight; 9] = [
1165        Self::THIN,
1166        Self::EXTRA_LIGHT,
1167        Self::LIGHT,
1168        Self::NORMAL,
1169        Self::MEDIUM,
1170        Self::SEMIBOLD,
1171        Self::BOLD,
1172        Self::EXTRA_BOLD,
1173        Self::BLACK,
1174    ];
1175}
1176
1177impl schemars::JsonSchema for FontWeight {
1178    fn schema_name() -> std::borrow::Cow<'static, str> {
1179        "FontWeight".into()
1180    }
1181
1182    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1183        use schemars::json_schema;
1184        json_schema!({
1185            "type": "number",
1186            "minimum": Self::THIN,
1187            "maximum": Self::BLACK,
1188            "default": Self::default(),
1189            "description": "Font weight value between 100 (thin) and 900 (black)"
1190        })
1191    }
1192}
1193
1194/// Allows italic or oblique faces to be selected.
1195#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1196pub enum FontStyle {
1197    /// A face that is neither italic not obliqued.
1198    #[default]
1199    Normal,
1200    /// A form that is generally cursive in nature.
1201    Italic,
1202    /// A typically-sloped version of the regular face.
1203    Oblique,
1204}
1205
1206impl Display for FontStyle {
1207    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1208        Debug::fmt(self, f)
1209    }
1210}
1211
1212/// A styled run of text, for use in [`crate::TextLayout`].
1213#[derive(Clone, Debug, PartialEq, Eq, Default)]
1214pub struct TextRun {
1215    /// A number of utf8 bytes
1216    pub len: usize,
1217    /// The font to use for this run.
1218    pub font: Font,
1219    /// The color
1220    pub color: Hsla,
1221    /// The background color (if any)
1222    pub background_color: Option<Hsla>,
1223    /// The underline style (if any)
1224    pub underline: Option<UnderlineStyle>,
1225    /// The strikethrough style (if any)
1226    pub strikethrough: Option<StrikethroughStyle>,
1227}
1228
1229#[cfg(all(target_os = "macos", test))]
1230impl TextRun {
1231    fn with_len(&self, len: usize) -> Self {
1232        let mut this = self.clone();
1233        this.len = len;
1234        this
1235    }
1236}
1237
1238/// An identifier for a specific glyph, as returned by [`WindowTextSystem::layout_line`].
1239#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1240#[repr(C)]
1241pub struct GlyphId(pub u32);
1242
1243/// Parameters for rendering a glyph, used as cache keys for raster bounds.
1244///
1245/// This struct identifies a specific glyph rendering configuration including
1246/// font, size, subpixel positioning, and scale factor. It's used to look up
1247/// cached raster bounds and sprite atlas entries.
1248#[derive(Clone, Debug, PartialEq)]
1249#[expect(missing_docs)]
1250pub struct RenderGlyphParams {
1251    pub font_id: FontId,
1252    pub glyph_id: GlyphId,
1253    pub font_size: Pixels,
1254    pub subpixel_variant: Point<u8>,
1255    pub scale_factor: f32,
1256    pub is_emoji: bool,
1257    pub subpixel_rendering: bool,
1258    pub dilation: u8,
1259}
1260
1261impl Eq for RenderGlyphParams {}
1262
1263impl Hash for RenderGlyphParams {
1264    fn hash<H: Hasher>(&self, state: &mut H) {
1265        self.font_id.0.hash(state);
1266        self.glyph_id.0.hash(state);
1267        self.font_size.0.to_bits().hash(state);
1268        self.subpixel_variant.hash(state);
1269        self.scale_factor.to_bits().hash(state);
1270        self.is_emoji.hash(state);
1271        self.subpixel_rendering.hash(state);
1272        self.dilation.hash(state);
1273    }
1274}
1275
1276/// The configuration details for identifying a specific font.
1277#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1278pub struct Font {
1279    /// The font family name.
1280    ///
1281    /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
1282    pub family: SharedString,
1283
1284    /// The font features to use.
1285    pub features: FontFeatures,
1286
1287    /// The fallbacks fonts to use.
1288    pub fallbacks: Option<FontFallbacks>,
1289
1290    /// The font weight.
1291    pub weight: FontWeight,
1292
1293    /// The font style.
1294    pub style: FontStyle,
1295}
1296
1297impl Default for Font {
1298    fn default() -> Self {
1299        font(".SystemUIFont")
1300    }
1301}
1302
1303/// Get a [`Font`] for a given name.
1304pub fn font(family: impl Into<SharedString>) -> Font {
1305    Font {
1306        family: family.into(),
1307        features: FontFeatures::default(),
1308        weight: FontWeight::default(),
1309        style: FontStyle::default(),
1310        fallbacks: None,
1311    }
1312}
1313
1314impl Font {
1315    /// Set this Font to be bold
1316    pub fn bold(mut self) -> Self {
1317        self.weight = FontWeight::BOLD;
1318        self
1319    }
1320
1321    /// Set this Font to be italic
1322    pub fn italic(mut self) -> Self {
1323        self.style = FontStyle::Italic;
1324        self
1325    }
1326}
1327
1328/// A struct for storing font metrics.
1329/// It is used to define the measurements of a typeface.
1330#[derive(Clone, Copy, Debug)]
1331pub struct FontMetrics {
1332    /// The number of font units that make up the "em square",
1333    /// a scalable grid for determining the size of a typeface.
1334    pub units_per_em: u32,
1335
1336    /// The vertical distance from the baseline of the font to the top of the glyph covers.
1337    pub ascent: f32,
1338
1339    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
1340    pub descent: f32,
1341
1342    /// The recommended additional space to add between lines of type.
1343    pub line_gap: f32,
1344
1345    /// The suggested position of the underline.
1346    pub underline_position: f32,
1347
1348    /// The suggested thickness of the underline.
1349    pub underline_thickness: f32,
1350
1351    /// The height of a capital letter measured from the baseline of the font.
1352    pub cap_height: f32,
1353
1354    /// The height of a lowercase x.
1355    pub x_height: f32,
1356
1357    /// The outer limits of the area that the font covers.
1358    /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
1359    pub bounding_box: Bounds<f32>,
1360}
1361
1362impl FontMetrics {
1363    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
1364    pub fn ascent(&self, font_size: Pixels) -> Pixels {
1365        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1366    }
1367
1368    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
1369    pub fn descent(&self, font_size: Pixels) -> Pixels {
1370        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1371    }
1372
1373    /// Returns the recommended additional space to add between lines of type in pixels.
1374    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1375        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1376    }
1377
1378    /// Returns the suggested position of the underline in pixels.
1379    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1380        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1381    }
1382
1383    /// Returns the suggested thickness of the underline in pixels.
1384    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1385        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1386    }
1387
1388    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
1389    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1390        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1391    }
1392
1393    /// Returns the height of a lowercase x in pixels.
1394    pub fn x_height(&self, font_size: Pixels) -> Pixels {
1395        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1396    }
1397
1398    /// Returns the outer limits of the area that the font covers in pixels.
1399    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1400        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1401    }
1402}
1403
1404/// Maps well-known virtual font names to their concrete equivalents.
1405#[allow(unused)]
1406pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1407    // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
1408    // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
1409    // and so retained here for backward compatibility.
1410    match name {
1411        ".SystemUIFont" => system,
1412        ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1413        ".ZedMono" | "Zed Plex Mono" => "Lilex",
1414        _ => name,
1415    }
1416}
1417
1418/// Like [`font_name_with_fallbacks`] but accepts and returns [`SharedString`] references.
1419#[allow(unused)]
1420pub fn font_name_with_fallbacks_shared<'a>(
1421    name: &'a SharedString,
1422    system: &'a SharedString,
1423) -> &'a SharedString {
1424    // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
1425    // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
1426    // and so retained here for backward compatibility.
1427    match name.as_str() {
1428        ".SystemUIFont" => system,
1429        ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1430        ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1431        _ => name,
1432    }
1433}
1434
1435#[cfg(test)]
1436mod missing_glyph_tests {
1437    use super::*;
1438    use futures::FutureExt as _;
1439
1440    #[test]
1441    fn bounds_retained_missing_glyphs() {
1442        let (reporter, mut receiver) = missing_glyph_channel();
1443        reporter.report(
1444            (0..MAX_REPORTED_MISSING_GLYPHS)
1445                .map(|index| {
1446                    MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1447                })
1448                .collect(),
1449        );
1450        assert!(receiver.recv().now_or_never().unwrap().is_ok());
1451
1452        let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1453        reporter.report(vec![newest.clone()]);
1454        assert!(receiver.recv().now_or_never().unwrap().is_ok());
1455
1456        let state = &receiver.state;
1457        assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1458        assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1459        assert!(state.reported.contains(&newest));
1460    }
1461
1462    #[test]
1463    fn dropping_receiver_closes_and_clears_reports() {
1464        let (reporter, receiver) = missing_glyph_channel();
1465        reporter.report(vec![missing_glyph("missing")]);
1466
1467        drop(receiver);
1468
1469        assert!(reporter.sender.is_closed());
1470        assert!(reporter.sender.is_empty());
1471    }
1472
1473    fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1474        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1475        let generation = Arc::<AtomicUsize>::default();
1476        let reporter = MissingGlyphReporter {
1477            generation: generation.clone(),
1478            sender,
1479        };
1480        let receiver = MissingGlyphReceiver {
1481            state: MissingGlyphState::default(),
1482            generation,
1483            receiver,
1484        };
1485        (reporter, receiver)
1486    }
1487
1488    fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1489        MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1490    }
1491}