Skip to main content

gpui/
text_system.rs

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