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