Skip to main content

gpui/
text_system.rs

1mod font_fallbacks;
2mod font_features;
3mod line;
4mod line_layout;
5mod line_wrapper;
6
7pub use font_fallbacks::*;
8pub use font_features::*;
9pub use line::*;
10pub use line_layout::*;
11pub use line_wrapper::*;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16    Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
17    StrikethroughStyle, TextRenderingMode, UnderlineStyle, px,
18};
19use anyhow::Context as _;
20use collections::{FxHashMap, FxHashSet};
21use core::fmt;
22use derive_more::{Add, Deref, FromStr, Sub};
23use itertools::Itertools;
24use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
25use smallvec::{SmallVec, smallvec};
26use std::{
27    borrow::Cow,
28    cell::Cell,
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    platform_text_system: Arc<dyn PlatformTextSystem>,
233    font_ids_by_font: RwLock<FxHashMap<Font, CachedFont>>,
234    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
235    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
236    wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<CharWidthCache>>>,
237    fallback_font_stack: SmallVec<[Font; 2]>,
238    font_generation: Arc<AtomicUsize>,
239    missing_glyph_reporter: Arc<MissingGlyphReporter>,
240    missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,
241}
242
243#[derive(Clone)]
244enum CachedFont {
245    Direct(FontId),
246    Fallback(FontId),
247    Missing(Arc<anyhow::Error>),
248}
249
250impl TextSystem {
251    /// Create a new TextSystem with the given platform text system.
252    pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
253        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
254        let missing_glyph_generation = Arc::<AtomicUsize>::default();
255        TextSystem {
256            platform_text_system,
257            font_metrics: RwLock::default(),
258            raster_bounds: RwLock::default(),
259            font_ids_by_font: RwLock::default(),
260            wrapper_pool: Mutex::default(),
261            fallback_font_stack: smallvec![
262                // TODO: Remove this when Linux have implemented setting fallbacks.
263                font(".ZedMono"),
264                font(".ZedSans"),
265                font("Helvetica"),
266                font("Segoe UI"),     // Windows
267                font("Ubuntu"),       // Gnome (Ubuntu)
268                font("Adwaita Sans"), // Gnome 47
269                font("Cantarell"),    // Gnome
270                font("Noto Sans"),    // KDE
271                font("DejaVu Sans"),
272                font("Arial"), // macOS, Windows
273            ],
274            font_generation: Arc::default(),
275            missing_glyph_reporter: Arc::new(MissingGlyphReporter {
276                generation: missing_glyph_generation.clone(),
277                sender,
278            }),
279            missing_glyph_receiver: Mutex::new(Some(MissingGlyphReceiver {
280                state: MissingGlyphState::default(),
281                generation: missing_glyph_generation,
282                receiver,
283            })),
284        }
285    }
286
287    /// Get sorted, unique font family names available to the platform text system.
288    ///
289    /// Includes fonts registered with [`Self::add_fonts`].
290    pub fn all_font_names(&self) -> Vec<String> {
291        let mut names = self.platform_text_system.all_font_names();
292        names.sort_unstable();
293        names.dedup();
294        names
295    }
296
297    /// Add a font's data to the text system.
298    ///
299    /// Cached font resolution and line layouts are invalidated after installation.
300    /// Layouts already in progress may complete against the previous font set.
301    pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
302        self.platform_text_system.add_fonts(fonts)?;
303        self.font_ids_by_font.write().clear();
304        self.missing_glyph_reporter.reset();
305        self.font_generation.fetch_add(1, Ordering::Release);
306        Ok(())
307    }
308
309    /// Takes the receiver for missing-glyph reports.
310    ///
311    /// Only one receiver is available for each text system. Returns `None` when
312    /// the receiver was already taken or another caller is taking it.
313    pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
314        self.missing_glyph_receiver
315            .try_lock()
316            .and_then(|mut receiver| receiver.take())
317    }
318
319    pub(crate) fn enable_missing_glyph_reporting(&self) {
320        self.platform_text_system
321            .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
322    }
323
324    pub(crate) fn disable_missing_glyph_reporting(&self) {
325        self.platform_text_system.set_missing_glyph_sink(None);
326        self.missing_glyph_reporter.reset();
327    }
328
329    #[cfg(test)]
330    pub(crate) fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
331        self.missing_glyph_reporter.report(missing_glyphs);
332    }
333
334    /// Get the Font for the Font Id.
335    pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
336        let lock = self.font_ids_by_font.read();
337        lock.iter()
338            .filter_map(|(font, result)| match result {
339                CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),
340                _ => None,
341            })
342            .next()
343    }
344
345    /// Resolves the specified font, falling back to the default font stack if
346    /// the font fails to load.
347    ///
348    /// # Panics
349    ///
350    /// Panics if the font and none of the fallbacks can be resolved.
351    pub fn resolve_font(&self, font: &Font) -> FontId {
352        if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
353            self.font_ids_by_font.read().get(font)
354        {
355            return *font_id;
356        }
357        self.resolve_font_uncached(font)
358    }
359
360    /// Prewarm any system font caches needed to shape text.
361    ///
362    /// This may be expensive, so callers should generally invoke it on a
363    /// background executor. Missing entries are still populated on demand by
364    /// the normal shaping path.
365    pub fn prewarm_fonts(&self, fonts: &[Font]) {
366        let mut font_ids = SmallVec::<[FontId; 8]>::new();
367        for font in fonts {
368            let font_id = self.resolve_font(font);
369            if !font_ids.contains(&font_id) {
370                font_ids.push(font_id);
371            }
372        }
373        self.platform_text_system.prewarm_fonts(&font_ids);
374    }
375
376    /// Get the bounding box for the given font and font size.
377    /// A font's bounding box is the smallest rectangle that could enclose all glyphs
378    /// in the font. superimposed over one another.
379    pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
380        self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
381    }
382
383    /// Get the typographic bounds for the given character, in the given font and size.
384    pub fn typographic_bounds(
385        &self,
386        font_id: FontId,
387        font_size: Pixels,
388        character: char,
389    ) -> Result<Bounds<Pixels>> {
390        let glyph_id = self
391            .platform_text_system
392            .glyph_for_char(font_id, character)
393            .with_context(|| format!("glyph not found for character '{character}'"))?;
394        let bounds = self
395            .platform_text_system
396            .typographic_bounds(font_id, glyph_id)?;
397        Ok(self.read_metrics(font_id, |metrics| {
398            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
399        }))
400    }
401
402    /// Get the advance width for the given character, in the given font and size.
403    pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
404        let glyph_id = self
405            .platform_text_system
406            .glyph_for_char(font_id, ch)
407            .with_context(|| format!("glyph not found for character '{ch}'"))?;
408        let result = self.platform_text_system.advance(font_id, glyph_id)?
409            / self.units_per_em(font_id) as f32;
410
411        Ok(result * font_size)
412    }
413
414    // Consider removing this?
415    /// Returns the shaped layout width of for the given character, in the given font and size.
416    pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
417        let mut buffer = [0; 4];
418        let buffer = ch.encode_utf8(&mut buffer);
419        self.platform_text_system
420            .layout_line(
421                buffer,
422                font_size,
423                &[FontRun {
424                    len: buffer.len(),
425                    font_id,
426                }],
427            )
428            .width
429    }
430
431    /// Returns the width of an `em`.
432    ///
433    /// Uses the width of the `m` character in the given font and size.
434    pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
435        Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
436    }
437
438    /// Returns the advance width of an `em`.
439    ///
440    /// Uses the advance width of the `m` character in the given font and size.
441    pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
442        Ok(self.advance(font_id, font_size, 'm')?.width)
443    }
444
445    /// Returns the width of an `ch`.
446    ///
447    /// Uses the width of the `0` character in the given font and size.
448    pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
449        Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
450    }
451
452    /// Returns the advance width of an `ch`.
453    ///
454    /// Uses the advance width of the `0` character in the given font and size.
455    pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
456        Ok(self.advance(font_id, font_size, '0')?.width)
457    }
458
459    /// Get the number of font size units per 'em square',
460    /// Per MDN: "an abstract square whose height is the intended distance between
461    /// lines of type in the same type size"
462    pub fn units_per_em(&self, font_id: FontId) -> u32 {
463        self.read_metrics(font_id, |metrics| metrics.units_per_em)
464    }
465
466    /// Get the height of a capital letter in the given font and size.
467    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
468        self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
469    }
470
471    /// Get the height of the x character in the given font and size.
472    pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
473        self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
474    }
475
476    /// Get the recommended distance from the baseline for the given font
477    pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
478        self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
479    }
480
481    /// Get the recommended distance below the baseline for the given font,
482    /// in single spaced text.
483    pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
484        self.read_metrics(font_id, |metrics| metrics.descent(font_size))
485    }
486
487    /// Get the recommended baseline offset for the given font and line height.
488    pub fn baseline_offset(
489        &self,
490        font_id: FontId,
491        font_size: Pixels,
492        line_height: Pixels,
493    ) -> Pixels {
494        let ascent = self.ascent(font_id, font_size);
495        let descent = self.descent(font_id, font_size);
496        let padding_top = (line_height - ascent - descent) / 2.;
497        padding_top + ascent
498    }
499
500    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
501        let lock = self.font_metrics.upgradable_read();
502
503        if let Some(metrics) = lock.get(&font_id) {
504            read(metrics)
505        } else {
506            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
507            let metrics = lock
508                .entry(font_id)
509                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
510            read(metrics)
511        }
512    }
513
514    /// Returns a handle to a line wrapper, for the given font and font size.
515    pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
516        let lock = &mut self.wrapper_pool.lock();
517        let font_id = self.resolve_font(&font);
518        let char_widths = lock
519            .entry(FontIdWithSize { font_id, font_size })
520            .or_default()
521            .pop()
522            .unwrap_or_default();
523        let wrapper = LineWrapper::new(font_id, font_size, self.clone(), char_widths);
524
525        LineWrapperHandle {
526            wrapper: Some(wrapper),
527            text_system: self.clone(),
528        }
529    }
530
531    /// Get the rasterized size and location of a specific, rendered glyph.
532    pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
533        let raster_bounds = self.raster_bounds.upgradable_read();
534        if let Some(bounds) = raster_bounds.get(params) {
535            Ok(*bounds)
536        } else {
537            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
538            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
539            raster_bounds.insert(params.clone(), bounds);
540            Ok(bounds)
541        }
542    }
543
544    pub(crate) fn rasterize_glyph(
545        &self,
546        params: &RenderGlyphParams,
547    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
548        let raster_bounds = self.raster_bounds(params)?;
549        self.platform_text_system
550            .rasterize_glyph(params, raster_bounds)
551    }
552
553    /// Returns the dilation level to use for a glyph painted in the given color.
554    pub(crate) fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
555        self.platform_text_system.glyph_dilation_for_color(color)
556    }
557
558    /// Returns the text rendering mode recommended by the platform for the given font and size.
559    /// The return value will never be [`TextRenderingMode::PlatformDefault`].
560    pub(crate) fn recommended_rendering_mode(
561        &self,
562        font_id: FontId,
563        font_size: Pixels,
564    ) -> TextRenderingMode {
565        self.platform_text_system
566            .recommended_rendering_mode(font_id, font_size)
567    }
568
569    fn resolve_font_uncached(&self, font: &Font) -> FontId {
570        let mut font_error = None;
571        let font_id = {
572            let mut font_ids = self.font_ids_by_font.upgradable_read();
573            if let Some(CachedFont::Direct(font_id) | CachedFont::Fallback(font_id)) =
574                font_ids.get(font)
575            {
576                return *font_id;
577            }
578
579            let mut lookup_font = |candidate: &Font| {
580                let cached = if let Some(cached) = font_ids.get(candidate) {
581                    cached.clone()
582                } else {
583                    let cached = match self.platform_text_system.font_id(candidate) {
584                        Ok(font_id) => CachedFont::Direct(font_id),
585                        Err(error) => CachedFont::Missing(Arc::new(error)),
586                    };
587                    font_ids.with_upgraded(|font_ids| {
588                        font_ids.insert(candidate.clone(), cached.clone());
589                    });
590                    cached
591                };
592                match cached {
593                    CachedFont::Direct(font_id) => Some(font_id),
594                    CachedFont::Fallback(_) => None,
595                    CachedFont::Missing(error) => {
596                        if candidate == font {
597                            font_error = Some(error);
598                        }
599                        None
600                    }
601                }
602            };
603
604            if let Some(font_id) = lookup_font(font) {
605                Some(font_id)
606            } else {
607                let font_id = self.fallback_font_stack.iter().find_map(lookup_font);
608                if let Some(font_id) = font_id {
609                    font_ids.with_upgraded(|font_ids| {
610                        font_ids.insert(font.clone(), CachedFont::Fallback(font_id));
611                    });
612                }
613                font_id
614            }
615        };
616        if let Some(error) = font_error {
617            log::warn!("failed to load font {font:?}: {error:#}");
618        }
619        font_id.unwrap_or_else(|| {
620            panic!(
621                "failed to resolve font '{}' or any of the fallbacks: {}",
622                font.family,
623                self.fallback_font_stack
624                    .iter()
625                    .map(|fallback| &fallback.family)
626                    .join(", ")
627            );
628        })
629    }
630}
631
632/// The GPUI text layout subsystem.
633#[derive(Deref)]
634pub struct WindowTextSystem {
635    line_layout_cache: LineLayoutCache,
636    font_runs_buffer: Cell<Vec<FontRun>>,
637    #[deref]
638    text_system: Arc<TextSystem>,
639}
640
641impl WindowTextSystem {
642    /// Create a new WindowTextSystem with the given TextSystem.
643    pub fn new(text_system: Arc<TextSystem>) -> Self {
644        Self {
645            line_layout_cache: LineLayoutCache::new(
646                text_system.platform_text_system.clone(),
647                text_system.font_generation.clone(),
648            ),
649            font_runs_buffer: Cell::default(),
650            text_system,
651        }
652    }
653
654    pub(crate) fn layout_index(&self) -> LineLayoutIndex {
655        self.line_layout_cache.layout_index()
656    }
657
658    pub(crate) fn reuse_layouts(&self, index: Range<LineLayoutIndex>) {
659        self.line_layout_cache.reuse_layouts(index)
660    }
661
662    pub(crate) fn truncate_layouts(&self, index: LineLayoutIndex) {
663        self.line_layout_cache.truncate_layouts(index)
664    }
665
666    /// Shape the given line, at the given font_size, for painting to the screen.
667    /// Subsets of the line can be styled independently with the `runs` parameter.
668    ///
669    /// Note that this method can only shape a single line of text. It will panic
670    /// if the text contains newlines. If you need to shape multiple lines of text,
671    /// use [`Self::shape_text`] instead.
672    pub fn shape_line(
673        &self,
674        text: SharedString,
675        font_size: Pixels,
676        runs: &[TextRun],
677        force_width: Option<Pixels>,
678    ) -> ShapedLine {
679        debug_assert!(
680            text.find('\n').is_none(),
681            "text argument should not contain newlines"
682        );
683
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 layout = self.layout_line(&text, font_size, runs, force_width);
705
706        ShapedLine {
707            layout,
708            text,
709            decoration_runs,
710        }
711    }
712
713    /// Shape a multi line string of text, at the given font_size, for painting to the screen.
714    /// Subsets of the text can be styled independently with the `runs` parameter.
715    /// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
716    pub fn shape_text(
717        &self,
718        text: SharedString,
719        font_size: Pixels,
720        runs: &[TextRun],
721        wrap_width: Option<Pixels>,
722        line_clamp: Option<usize>,
723    ) -> Result<SmallVec<[WrappedLine; 1]>> {
724        let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
725        let mut font_runs = self.font_runs_buffer.take();
726
727        let mut lines = SmallVec::new();
728        let max_wrap_lines = line_clamp;
729        let mut wrapped_lines = 0;
730
731        let mut process_line = |line_text: SharedString, line_start, line_end| {
732            font_runs.clear();
733
734            let mut decoration_runs = <Vec<DecorationRun>>::with_capacity(32);
735            let mut run_start = line_start;
736            while run_start < line_end {
737                let Some(run) = runs.peek_mut() else {
738                    log::warn!("`TextRun`s do not cover the entire to be shaped text");
739                    break;
740                };
741
742                let run_len_within_line = cmp::min(line_end - run_start, run.len);
743
744                let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
745                    && last_run.color == run.color
746                    && last_run.underline == run.underline
747                    && last_run.strikethrough == run.strikethrough
748                    && last_run.background_color == run.background_color
749                {
750                    last_run.len += run_len_within_line as u32;
751                    false
752                } else {
753                    decoration_runs.push(DecorationRun {
754                        len: run_len_within_line as u32,
755                        color: run.color,
756                        background_color: run.background_color,
757                        underline: run.underline,
758                        strikethrough: run.strikethrough,
759                    });
760                    true
761                };
762
763                let font_id = self.resolve_font(&run.font);
764                if let Some(font_run) = font_runs.last_mut()
765                    && font_id == font_run.font_id
766                    && !decoration_changed
767                {
768                    font_run.len += run_len_within_line;
769                } else {
770                    font_runs.push(FontRun {
771                        len: run_len_within_line,
772                        font_id,
773                    });
774                }
775
776                // Preserve the remainder of the run for the next line
777                run.len -= run_len_within_line;
778                if run.len == 0 {
779                    runs.next();
780                }
781                run_start += run_len_within_line;
782            }
783
784            let layout = self.line_layout_cache.layout_wrapped_line(
785                &line_text,
786                font_size,
787                &font_runs,
788                wrap_width,
789                max_wrap_lines.map(|max| max.saturating_sub(wrapped_lines)),
790            );
791            wrapped_lines += layout.wrap_boundaries.len();
792
793            lines.push(WrappedLine {
794                layout,
795                decoration_runs,
796                text: line_text,
797            });
798
799            // Skip `\n` character.
800            if let Some(run) = runs.peek_mut() {
801                run.len -= 1;
802                if run.len == 0 {
803                    runs.next();
804                }
805            }
806        };
807
808        let mut split_lines = text.split('\n');
809
810        // Special case single lines to prevent allocating a sharedstring
811        if let Some(first_line) = split_lines.next()
812            && let Some(second_line) = split_lines.next()
813        {
814            let mut line_start = 0;
815            process_line(
816                SharedString::new(first_line),
817                line_start,
818                line_start + first_line.len(),
819            );
820            line_start += first_line.len() + '\n'.len_utf8();
821            process_line(
822                SharedString::new(second_line),
823                line_start,
824                line_start + second_line.len(),
825            );
826            for line_text in split_lines {
827                line_start += line_text.len() + '\n'.len_utf8();
828                process_line(
829                    SharedString::new(line_text),
830                    line_start,
831                    line_start + line_text.len(),
832                );
833            }
834        } else {
835            let end = text.len();
836            process_line(text, 0, end);
837        }
838
839        self.font_runs_buffer.set(font_runs);
840
841        Ok(lines)
842    }
843
844    pub(crate) fn finish_frame(&self) {
845        self.line_layout_cache.finish_frame()
846    }
847
848    /// Layout the given line of text, at the given font_size.
849    /// Subsets of the line can be styled independently with the `runs` parameter.
850    /// Generally, you should prefer to use [`Self::shape_line`] instead, which
851    /// can be painted directly.
852    pub fn layout_line(
853        &self,
854        text: &str,
855        font_size: Pixels,
856        runs: &[TextRun],
857        force_width: Option<Pixels>,
858    ) -> Arc<LineLayout> {
859        let mut last_run = None::<&TextRun>;
860        let mut font_runs = self.font_runs_buffer.take();
861        font_runs.clear();
862
863        for run in runs.iter() {
864            let decoration_changed = if let Some(last_run) = last_run
865                && last_run.color == run.color
866                && last_run.underline == run.underline
867                && last_run.strikethrough == run.strikethrough
868            // we do not consider differing background color relevant, as it does not affect glyphs
869            // && last_run.background_color == run.background_color
870            {
871                false
872            } else {
873                last_run = Some(run);
874                true
875            };
876
877            let font_id = self.resolve_font(&run.font);
878            if let Some(font_run) = font_runs.last_mut()
879                && font_id == font_run.font_id
880                && !decoration_changed
881            {
882                font_run.len += run.len;
883            } else {
884                font_runs.push(FontRun {
885                    len: run.len,
886                    font_id,
887                });
888            }
889        }
890
891        let layout = self.line_layout_cache.layout_line(
892            &SharedString::new(text),
893            font_size,
894            &font_runs,
895            force_width,
896        );
897
898        self.font_runs_buffer.set(font_runs);
899
900        layout
901    }
902
903    /// Returns the shaped layout width of for the given character, in the given font and size.
904    pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
905        let mut buffer = [0; 4];
906        let buffer: &_ = ch.encode_utf8(&mut buffer);
907        self.line_layout_cache
908            .layout_line(
909                buffer,
910                font_size,
911                &[FontRun {
912                    len: buffer.len(),
913                    font_id,
914                }],
915                None,
916            )
917            .width
918    }
919
920    /// Returns the shaped layout width of an `em`.
921    pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
922        self.layout_width(font_id, font_size, 'm')
923    }
924}
925
926#[derive(Hash, Eq, PartialEq)]
927struct FontIdWithSize {
928    font_id: FontId,
929    font_size: Pixels,
930}
931
932/// A handle into the text system, which can be used to compute the wrapped layout of text
933pub struct LineWrapperHandle {
934    wrapper: Option<LineWrapper>,
935    text_system: Arc<TextSystem>,
936}
937
938impl Drop for LineWrapperHandle {
939    fn drop(&mut self) {
940        let mut state = self.text_system.wrapper_pool.lock();
941        let wrapper = self.wrapper.take().unwrap();
942        state
943            .get_mut(&FontIdWithSize {
944                font_id: wrapper.font_id,
945                font_size: wrapper.font_size,
946            })
947            .unwrap()
948            .push(wrapper.into_char_widths());
949    }
950}
951
952impl Deref for LineWrapperHandle {
953    type Target = LineWrapper;
954
955    fn deref(&self) -> &Self::Target {
956        self.wrapper.as_ref().unwrap()
957    }
958}
959
960impl DerefMut for LineWrapperHandle {
961    fn deref_mut(&mut self) -> &mut Self::Target {
962        self.wrapper.as_mut().unwrap()
963    }
964}
965
966/// The degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0,
967/// with 400.0 as normal.
968#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Add, Sub, FromStr)]
969#[serde(transparent)]
970pub struct FontWeight(pub f32);
971
972impl Display for FontWeight {
973    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
974        write!(f, "{}", self.0)
975    }
976}
977
978impl From<f32> for FontWeight {
979    fn from(weight: f32) -> Self {
980        FontWeight(weight)
981    }
982}
983
984impl Default for FontWeight {
985    #[inline]
986    fn default() -> FontWeight {
987        FontWeight::NORMAL
988    }
989}
990
991impl Hash for FontWeight {
992    fn hash<H: Hasher>(&self, state: &mut H) {
993        state.write_u32(u32::from_be_bytes(self.0.to_be_bytes()));
994    }
995}
996
997impl Eq for FontWeight {}
998
999impl FontWeight {
1000    /// Thin weight (100), the thinnest value.
1001    pub const THIN: FontWeight = FontWeight(100.0);
1002    /// Extra light weight (200).
1003    pub const EXTRA_LIGHT: FontWeight = FontWeight(200.0);
1004    /// Light weight (300).
1005    pub const LIGHT: FontWeight = FontWeight(300.0);
1006    /// Normal (400).
1007    pub const NORMAL: FontWeight = FontWeight(400.0);
1008    /// Medium weight (500, higher than normal).
1009    pub const MEDIUM: FontWeight = FontWeight(500.0);
1010    /// Semibold weight (600).
1011    pub const SEMIBOLD: FontWeight = FontWeight(600.0);
1012    /// Bold weight (700).
1013    pub const BOLD: FontWeight = FontWeight(700.0);
1014    /// Extra-bold weight (800).
1015    pub const EXTRA_BOLD: FontWeight = FontWeight(800.0);
1016    /// Black weight (900), the thickest value.
1017    pub const BLACK: FontWeight = FontWeight(900.0);
1018
1019    /// All of the font weights, in order from thinnest to thickest.
1020    pub const ALL: [FontWeight; 9] = [
1021        Self::THIN,
1022        Self::EXTRA_LIGHT,
1023        Self::LIGHT,
1024        Self::NORMAL,
1025        Self::MEDIUM,
1026        Self::SEMIBOLD,
1027        Self::BOLD,
1028        Self::EXTRA_BOLD,
1029        Self::BLACK,
1030    ];
1031}
1032
1033impl schemars::JsonSchema for FontWeight {
1034    fn schema_name() -> std::borrow::Cow<'static, str> {
1035        "FontWeight".into()
1036    }
1037
1038    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1039        use schemars::json_schema;
1040        json_schema!({
1041            "type": "number",
1042            "minimum": Self::THIN,
1043            "maximum": Self::BLACK,
1044            "default": Self::default(),
1045            "description": "Font weight value between 100 (thin) and 900 (black)"
1046        })
1047    }
1048}
1049
1050/// Allows italic or oblique faces to be selected.
1051#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default, Serialize, Deserialize, JsonSchema)]
1052pub enum FontStyle {
1053    /// A face that is neither italic not obliqued.
1054    #[default]
1055    Normal,
1056    /// A form that is generally cursive in nature.
1057    Italic,
1058    /// A typically-sloped version of the regular face.
1059    Oblique,
1060}
1061
1062impl Display for FontStyle {
1063    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1064        Debug::fmt(self, f)
1065    }
1066}
1067
1068/// A styled run of text, for use in [`crate::TextLayout`].
1069#[derive(Clone, Debug, PartialEq, Eq, Default)]
1070pub struct TextRun {
1071    /// A number of utf8 bytes
1072    pub len: usize,
1073    /// The font to use for this run.
1074    pub font: Font,
1075    /// The color
1076    pub color: Hsla,
1077    /// The background color (if any)
1078    pub background_color: Option<Hsla>,
1079    /// The underline style (if any)
1080    pub underline: Option<UnderlineStyle>,
1081    /// The strikethrough style (if any)
1082    pub strikethrough: Option<StrikethroughStyle>,
1083}
1084
1085#[cfg(all(target_os = "macos", test))]
1086impl TextRun {
1087    fn with_len(&self, len: usize) -> Self {
1088        let mut this = self.clone();
1089        this.len = len;
1090        this
1091    }
1092}
1093
1094/// An identifier for a specific glyph, as returned by [`WindowTextSystem::layout_line`].
1095#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1096#[repr(C)]
1097pub struct GlyphId(pub u32);
1098
1099/// Parameters for rendering a glyph, used as cache keys for raster bounds.
1100///
1101/// This struct identifies a specific glyph rendering configuration including
1102/// font, size, subpixel positioning, and scale factor. It's used to look up
1103/// cached raster bounds and sprite atlas entries.
1104#[derive(Clone, Debug, PartialEq)]
1105#[expect(missing_docs)]
1106pub struct RenderGlyphParams {
1107    pub font_id: FontId,
1108    pub glyph_id: GlyphId,
1109    pub font_size: Pixels,
1110    pub subpixel_variant: Point<u8>,
1111    pub scale_factor: f32,
1112    pub is_emoji: bool,
1113    pub subpixel_rendering: bool,
1114    pub dilation: u8,
1115}
1116
1117impl Eq for RenderGlyphParams {}
1118
1119impl Hash for RenderGlyphParams {
1120    fn hash<H: Hasher>(&self, state: &mut H) {
1121        self.font_id.0.hash(state);
1122        self.glyph_id.0.hash(state);
1123        self.font_size.0.to_bits().hash(state);
1124        self.subpixel_variant.hash(state);
1125        self.scale_factor.to_bits().hash(state);
1126        self.is_emoji.hash(state);
1127        self.subpixel_rendering.hash(state);
1128        self.dilation.hash(state);
1129    }
1130}
1131
1132/// The configuration details for identifying a specific font.
1133#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1134pub struct Font {
1135    /// The font family name.
1136    ///
1137    /// The special name ".SystemUIFont" is used to identify the system UI font, which varies based on platform.
1138    pub family: SharedString,
1139
1140    /// The font features to use.
1141    pub features: FontFeatures,
1142
1143    /// The fallbacks fonts to use.
1144    pub fallbacks: Option<FontFallbacks>,
1145
1146    /// The font weight.
1147    pub weight: FontWeight,
1148
1149    /// The font style.
1150    pub style: FontStyle,
1151}
1152
1153impl Default for Font {
1154    fn default() -> Self {
1155        font(".SystemUIFont")
1156    }
1157}
1158
1159/// Get a [`Font`] for a given name.
1160pub fn font(family: impl Into<SharedString>) -> Font {
1161    Font {
1162        family: family.into(),
1163        features: FontFeatures::default(),
1164        weight: FontWeight::default(),
1165        style: FontStyle::default(),
1166        fallbacks: None,
1167    }
1168}
1169
1170impl Font {
1171    /// Set this Font to be bold
1172    pub fn bold(mut self) -> Self {
1173        self.weight = FontWeight::BOLD;
1174        self
1175    }
1176
1177    /// Set this Font to be italic
1178    pub fn italic(mut self) -> Self {
1179        self.style = FontStyle::Italic;
1180        self
1181    }
1182}
1183
1184/// A struct for storing font metrics.
1185/// It is used to define the measurements of a typeface.
1186#[derive(Clone, Copy, Debug)]
1187pub struct FontMetrics {
1188    /// The number of font units that make up the "em square",
1189    /// a scalable grid for determining the size of a typeface.
1190    pub units_per_em: u32,
1191
1192    /// The vertical distance from the baseline of the font to the top of the glyph covers.
1193    pub ascent: f32,
1194
1195    /// The vertical distance from the baseline of the font to the bottom of the glyph covers.
1196    pub descent: f32,
1197
1198    /// The recommended additional space to add between lines of type.
1199    pub line_gap: f32,
1200
1201    /// The suggested position of the underline.
1202    pub underline_position: f32,
1203
1204    /// The suggested thickness of the underline.
1205    pub underline_thickness: f32,
1206
1207    /// The height of a capital letter measured from the baseline of the font.
1208    pub cap_height: f32,
1209
1210    /// The height of a lowercase x.
1211    pub x_height: f32,
1212
1213    /// The outer limits of the area that the font covers.
1214    /// Corresponds to the xMin / xMax / yMin / yMax values in the OpenType `head` table
1215    pub bounding_box: Bounds<f32>,
1216}
1217
1218impl FontMetrics {
1219    /// Returns the vertical distance from the baseline of the font to the top of the glyph covers in pixels.
1220    pub fn ascent(&self, font_size: Pixels) -> Pixels {
1221        Pixels((self.ascent / self.units_per_em as f32) * font_size.0)
1222    }
1223
1224    /// Returns the vertical distance from the baseline of the font to the bottom of the glyph covers in pixels.
1225    pub fn descent(&self, font_size: Pixels) -> Pixels {
1226        Pixels((self.descent / self.units_per_em as f32) * font_size.0)
1227    }
1228
1229    /// Returns the recommended additional space to add between lines of type in pixels.
1230    pub fn line_gap(&self, font_size: Pixels) -> Pixels {
1231        Pixels((self.line_gap / self.units_per_em as f32) * font_size.0)
1232    }
1233
1234    /// Returns the suggested position of the underline in pixels.
1235    pub fn underline_position(&self, font_size: Pixels) -> Pixels {
1236        Pixels((self.underline_position / self.units_per_em as f32) * font_size.0)
1237    }
1238
1239    /// Returns the suggested thickness of the underline in pixels.
1240    pub fn underline_thickness(&self, font_size: Pixels) -> Pixels {
1241        Pixels((self.underline_thickness / self.units_per_em as f32) * font_size.0)
1242    }
1243
1244    /// Returns the height of a capital letter measured from the baseline of the font in pixels.
1245    pub fn cap_height(&self, font_size: Pixels) -> Pixels {
1246        Pixels((self.cap_height / self.units_per_em as f32) * font_size.0)
1247    }
1248
1249    /// Returns the height of a lowercase x in pixels.
1250    pub fn x_height(&self, font_size: Pixels) -> Pixels {
1251        Pixels((self.x_height / self.units_per_em as f32) * font_size.0)
1252    }
1253
1254    /// Returns the outer limits of the area that the font covers in pixels.
1255    pub fn bounding_box(&self, font_size: Pixels) -> Bounds<Pixels> {
1256        (self.bounding_box / self.units_per_em as f32 * font_size.0).map(px)
1257    }
1258}
1259
1260/// Maps well-known virtual font names to their concrete equivalents.
1261#[allow(unused)]
1262pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
1263    // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
1264    // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
1265    // and so retained here for backward compatibility.
1266    match name {
1267        ".SystemUIFont" => system,
1268        ".ZedSans" | "Zed Plex Sans" => "IBM Plex Sans",
1269        ".ZedMono" | "Zed Plex Mono" => "Lilex",
1270        _ => name,
1271    }
1272}
1273
1274/// Like [`font_name_with_fallbacks`] but accepts and returns [`SharedString`] references.
1275#[allow(unused)]
1276pub fn font_name_with_fallbacks_shared<'a>(
1277    name: &'a SharedString,
1278    system: &'a SharedString,
1279) -> &'a SharedString {
1280    // Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
1281    // in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
1282    // and so retained here for backward compatibility.
1283    match name.as_str() {
1284        ".SystemUIFont" => system,
1285        ".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
1286        ".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
1287        _ => name,
1288    }
1289}
1290
1291#[cfg(test)]
1292mod font_resolution_tests {
1293    use super::*;
1294    use crate::NoopTextSystem;
1295
1296    #[test]
1297    fn caches_resolved_font_fallbacks() {
1298        let mut text_system = TextSystem::new(Arc::new(NoopTextSystem::new()));
1299        let requested = font("Missing Font").bold().italic();
1300        let missing = CachedFont::Missing(Arc::new(anyhow::anyhow!("missing font")));
1301        {
1302            let mut font_ids = text_system.font_ids_by_font.write();
1303            font_ids.insert(requested.clone(), missing.clone());
1304            for fallback in &text_system.fallback_font_stack {
1305                font_ids.insert(fallback.clone(), missing.clone());
1306            }
1307            font_ids.insert(font("Arial"), CachedFont::Direct(FontId(42)));
1308        }
1309
1310        assert_eq!(text_system.resolve_font(&requested), FontId(42));
1311        assert_eq!(text_system.get_font_for_id(FontId(42)), Some(font("Arial")));
1312
1313        text_system.fallback_font_stack.clear();
1314        assert_eq!(text_system.resolve_font(&requested), FontId(42));
1315    }
1316}
1317
1318#[cfg(test)]
1319mod line_wrapper_pool_tests {
1320    use super::*;
1321    use crate::NoopTextSystem;
1322
1323    #[test]
1324    fn pooled_line_wrappers_do_not_retain_text_system() {
1325        let text_system = Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new())));
1326        let weak_text_system = Arc::downgrade(&text_system);
1327
1328        let mut wrapper = text_system.line_wrapper(font(".ZedMono"), px(16.));
1329        let fragments = [LineFragment::text("hello world")];
1330        wrapper
1331            .wrap_line(&fragments, px(40.), IndentAdjustment::default())
1332            .for_each(drop);
1333        drop(wrapper);
1334        drop(text_system);
1335
1336        assert!(weak_text_system.upgrade().is_none());
1337    }
1338}
1339
1340#[cfg(test)]
1341mod missing_glyph_tests {
1342    use super::*;
1343    use futures::FutureExt as _;
1344
1345    #[test]
1346    fn bounds_retained_missing_glyphs() {
1347        let (reporter, mut receiver) = missing_glyph_channel();
1348        reporter.report(
1349            (0..MAX_REPORTED_MISSING_GLYPHS)
1350                .map(|index| {
1351                    MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
1352                })
1353                .collect(),
1354        );
1355        assert!(receiver.recv().now_or_never().unwrap().is_ok());
1356
1357        let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
1358        reporter.report(vec![newest.clone()]);
1359        assert!(receiver.recv().now_or_never().unwrap().is_ok());
1360
1361        let state = &receiver.state;
1362        assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
1363        assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
1364        assert!(state.reported.contains(&newest));
1365    }
1366
1367    #[test]
1368    fn dropping_receiver_closes_and_clears_reports() {
1369        let (reporter, receiver) = missing_glyph_channel();
1370        reporter.report(vec![missing_glyph("missing")]);
1371
1372        drop(receiver);
1373
1374        assert!(reporter.sender.is_closed());
1375        assert!(reporter.sender.is_empty());
1376    }
1377
1378    fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
1379        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
1380        let generation = Arc::<AtomicUsize>::default();
1381        let reporter = MissingGlyphReporter {
1382            generation: generation.clone(),
1383            sender,
1384        };
1385        let receiver = MissingGlyphReceiver {
1386            state: MissingGlyphState::default(),
1387            generation,
1388            receiver,
1389        };
1390        (reporter, receiver)
1391    }
1392
1393    fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
1394        MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
1395    }
1396}