Skip to main content

gpui/
text_system.rs

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