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