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