Skip to main content

gpui_wgpu/
cosmic_text_system.rs

1use anyhow::{Context as _, Ok, Result};
2use collections::HashMap;
3use cosmic_text::{
4    Attrs, AttrsList, Ellipsize, Family, Font as CosmicTextFont,
5    FontFeatures as CosmicFontFeatures, FontSystem, ShapeBuffer, ShapeLine, Stretch, Style, Weight,
6};
7use gpui::{
8    Bounds, DevicePixels, FallbackFontClass, Font, FontFallbacks, FontFeatures, FontId,
9    FontMetrics, FontRun, GlyphId, IsZero as _, LineLayout, MissingGlyph, MissingGlyphSink, Pixels,
10    PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ShapedGlyph,
11    ShapedRun, SharedString, Size, TextRenderingMode, point, size,
12};
13
14use itertools::Itertools;
15use parking_lot::RwLock;
16use smallvec::SmallVec;
17use std::{borrow::Cow, ops::Range, sync::Arc};
18use swash::{
19    scale::{Render, ScaleContext, Source, StrikeWith},
20    zeno::{Format, Vector},
21};
22use unicode_segmentation::UnicodeSegmentation;
23
24pub struct CosmicTextSystem(RwLock<CosmicTextSystemState>);
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27struct FontKey {
28    family: SharedString,
29    features: FontFeatures,
30    fallbacks: Option<FontFallbacks>,
31}
32
33impl FontKey {
34    fn new(family: SharedString, features: FontFeatures, fallbacks: Option<FontFallbacks>) -> Self {
35        Self {
36            family,
37            features,
38            fallbacks,
39        }
40    }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44struct LoadedFontKey {
45    database_id: cosmic_text::fontdb::ID,
46    font: FontKey,
47}
48
49struct CosmicTextSystemState {
50    font_system: FontSystem,
51    scratch: ShapeBuffer,
52    swash_scale_context: ScaleContext,
53    pending_glyph_images: HashMap<RenderGlyphParams, swash::scale::image::Image>,
54    /// Contains all already loaded fonts, including all faces. Indexed by `FontId`.
55    loaded_fonts: Vec<LoadedFont>,
56    loaded_font_ids_by_key: HashMap<LoadedFontKey, FontId>,
57    /// Caches the `FontId`s associated with a specific family to avoid iterating the font database
58    /// for every font face in a family.
59    font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>,
60    system_font_fallback: String,
61    missing_glyph_sink: Option<Arc<dyn MissingGlyphSink>>,
62}
63
64struct LoadedFont {
65    font: Arc<CosmicTextFont>,
66    features: CosmicFontFeatures,
67    is_known_emoji_font: bool,
68    /// resolved at load time so `layout_line` shares one chain across faces.
69    /// `Arc` keeps clone cheap on the per-run hot path.
70    user_fallback_chain: Arc<[(FontId, SharedString)]>,
71}
72
73struct FontMatchProperties {
74    primary_family_name: SharedString,
75    stretch: Stretch,
76    style: Style,
77    weight: Weight,
78    features: CosmicFontFeatures,
79    fallback_chain: Arc<[(FontId, SharedString)]>,
80}
81
82impl FontMatchProperties {
83    fn attributes<'a>(&'a self, font_id: FontId, family_name: &'a str) -> Attrs<'a> {
84        Attrs::new()
85            .metadata(font_id.0)
86            .family(Family::Name(family_name))
87            .stretch(self.stretch)
88            .style(self.style)
89            .weight(self.weight)
90            .font_features(self.features.clone())
91    }
92}
93
94impl CosmicTextSystem {
95    /// Returns the selected face's weight and style, which may differ from the request.
96    pub fn font_weight_and_style(
97        &self,
98        font_id: FontId,
99    ) -> Result<(gpui::FontWeight, gpui::FontStyle)> {
100        let state = self.0.read();
101        let font = state
102            .loaded_fonts
103            .get(font_id.0)
104            .context("invalid font ID")?;
105        let face = state
106            .font_system
107            .db()
108            .face(font.font.id())
109            .context("font face not found")?;
110        let style = match face.style {
111            cosmic_text::Style::Normal => gpui::FontStyle::Normal,
112            cosmic_text::Style::Italic => gpui::FontStyle::Italic,
113            cosmic_text::Style::Oblique => gpui::FontStyle::Oblique,
114        };
115        Ok((gpui::FontWeight(face.weight.0 as f32), style))
116    }
117
118    /// Builds reports for unresolved source indices after an outer text system
119    /// has applied its own fallback.
120    pub fn missing_glyphs(
121        &self,
122        text: &str,
123        font_runs: &[FontRun],
124        missing_text_indices: impl IntoIterator<Item = usize>,
125    ) -> Vec<MissingGlyph> {
126        self.0
127            .read()
128            .missing_glyphs(text, font_runs, missing_text_indices)
129    }
130
131    pub fn new(system_font_fallback: &str) -> Self {
132        let font_system = FontSystem::new();
133
134        Self(RwLock::new(CosmicTextSystemState {
135            font_system,
136            scratch: ShapeBuffer::default(),
137            swash_scale_context: ScaleContext::new(),
138            pending_glyph_images: HashMap::default(),
139            loaded_fonts: Vec::new(),
140            loaded_font_ids_by_key: HashMap::default(),
141            font_ids_by_family_cache: HashMap::default(),
142            system_font_fallback: system_font_fallback.to_string(),
143            missing_glyph_sink: None,
144        }))
145    }
146
147    pub fn new_without_system_fonts(system_font_fallback: &str) -> Self {
148        let font_system = FontSystem::new_with_locale_and_db(
149            "en-US".to_string(),
150            cosmic_text::fontdb::Database::new(),
151        );
152
153        Self(RwLock::new(CosmicTextSystemState {
154            font_system,
155            scratch: ShapeBuffer::default(),
156            swash_scale_context: ScaleContext::new(),
157            pending_glyph_images: HashMap::default(),
158            loaded_fonts: Vec::new(),
159            loaded_font_ids_by_key: HashMap::default(),
160            font_ids_by_family_cache: HashMap::default(),
161            system_font_fallback: system_font_fallback.to_string(),
162            missing_glyph_sink: None,
163        }))
164    }
165}
166
167impl PlatformTextSystem for CosmicTextSystem {
168    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
169        self.0.write().add_fonts(fonts)
170    }
171
172    fn set_missing_glyph_sink(&self, sink: Option<Arc<dyn MissingGlyphSink>>) {
173        self.0.write().missing_glyph_sink = sink;
174    }
175
176    fn all_font_names(&self) -> Vec<String> {
177        let mut result = self
178            .0
179            .read()
180            .font_system
181            .db()
182            .faces()
183            .filter_map(|face| face.families.first().map(|family| family.0.clone()))
184            .collect_vec();
185        result.sort_unstable();
186        result.dedup();
187        result
188    }
189
190    fn font_id(&self, font: &Font) -> Result<FontId> {
191        let mut state = self.0.write();
192        let key = FontKey::new(
193            font.family.clone(),
194            font.features.clone(),
195            font.fallbacks.clone(),
196        );
197        let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&key) {
198            font_ids.as_slice()
199        } else {
200            let font_ids =
201                state.load_family(&font.family, &font.features, font.fallbacks.as_ref())?;
202            state.font_ids_by_family_cache.insert(key.clone(), font_ids);
203            state.font_ids_by_family_cache[&key].as_ref()
204        };
205
206        let ix = find_best_match(font, candidates, &state)?;
207
208        Ok(candidates[ix])
209    }
210
211    fn prewarm_fonts(&self, font_ids: &[FontId]) {
212        self.0.write().prewarm_fonts(font_ids);
213    }
214
215    fn font_metrics(&self, font_id: FontId) -> FontMetrics {
216        let metrics = self
217            .0
218            .read()
219            .loaded_font(font_id)
220            .font
221            .as_swash()
222            .metrics(&[]);
223
224        FontMetrics {
225            units_per_em: metrics.units_per_em as u32,
226            ascent: metrics.ascent,
227            descent: -metrics.descent,
228            line_gap: metrics.leading,
229            underline_position: metrics.underline_offset,
230            underline_thickness: metrics.stroke_size,
231            cap_height: metrics.cap_height,
232            x_height: metrics.x_height,
233            bounding_box: Bounds {
234                origin: point(0.0, 0.0),
235                size: size(metrics.max_width, metrics.ascent + metrics.descent),
236            },
237        }
238    }
239
240    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
241        let lock = self.0.read();
242        let glyph_metrics = lock.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
243        let glyph_id = glyph_id.0 as u16;
244        Ok(Bounds {
245            origin: point(0.0, 0.0),
246            size: size(
247                glyph_metrics.advance_width(glyph_id),
248                glyph_metrics.advance_height(glyph_id),
249            ),
250        })
251    }
252
253    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
254        self.0.read().advance(font_id, glyph_id)
255    }
256
257    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
258        self.0.read().glyph_for_char(font_id, ch)
259    }
260
261    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
262        self.0.write().raster_bounds(params)
263    }
264
265    fn rasterize_glyph(
266        &self,
267        params: &RenderGlyphParams,
268        raster_bounds: Bounds<DevicePixels>,
269    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
270        self.0.write().rasterize_glyph(params, raster_bounds)
271    }
272
273    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
274        self.0.write().layout_line(text, font_size, runs)
275    }
276
277    fn recommended_rendering_mode(
278        &self,
279        _font_id: FontId,
280        _font_size: Pixels,
281    ) -> TextRenderingMode {
282        TextRenderingMode::Subpixel
283    }
284}
285
286impl CosmicTextSystemState {
287    fn loaded_font(&self, font_id: FontId) -> &LoadedFont {
288        &self.loaded_fonts[font_id.0]
289    }
290
291    fn font_match_properties(&self, font_id: FontId) -> Option<FontMatchProperties> {
292        let loaded_font = self.loaded_font(font_id);
293        let Some(face) = self.font_system.db().face(loaded_font.font.id()) else {
294            log::warn!("font face not found in database for font_id {:?}", font_id);
295            return None;
296        };
297        let Some(first_family) = face.families.first() else {
298            log::warn!("font face has no family names for font_id {:?}", font_id);
299            return None;
300        };
301
302        Some(FontMatchProperties {
303            primary_family_name: first_family.0.clone().into(),
304            stretch: face.stretch,
305            style: face.style,
306            weight: face.weight,
307            features: loaded_font.features.clone(),
308            fallback_chain: Arc::clone(&loaded_font.user_fallback_chain),
309        })
310    }
311
312    fn prewarm_fonts(&mut self, font_ids: &[FontId]) {
313        for &font_id in font_ids {
314            let Some(properties) = self.font_match_properties(font_id) else {
315                continue;
316            };
317            let primary_attributes =
318                properties.attributes(font_id, &properties.primary_family_name);
319            self.font_system.get_font_matches(&primary_attributes);
320
321            for (fallback_id, fallback_name) in &*properties.fallback_chain {
322                let fallback_attributes = properties.attributes(*fallback_id, fallback_name);
323                self.font_system.get_font_matches(&fallback_attributes);
324            }
325        }
326    }
327
328    #[profiling::function]
329    fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
330        self.font_ids_by_family_cache.clear();
331        let db = self.font_system.db_mut();
332        for bytes in fonts {
333            db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(bytes)));
334        }
335        Ok(())
336    }
337
338    #[profiling::function]
339    fn load_family(
340        &mut self,
341        name: &str,
342        features: &FontFeatures,
343        fallbacks: Option<&FontFallbacks>,
344    ) -> Result<SmallVec<[FontId; 4]>> {
345        let loaded_font_key = FontKey::new(
346            SharedString::from(name.to_owned()),
347            features.clone(),
348            fallbacks.cloned(),
349        );
350
351        // recurse with `fallbacks = None` so a fallback family cannot pull in
352        // another chain. missing fallback families are dropped so a typo in
353        // settings still lets the primary family load.
354        let user_fallback_chain: Arc<[(FontId, SharedString)]> = match fallbacks {
355            Some(fallbacks) if !fallbacks.fallback_list().is_empty() => {
356                let mut chain: Vec<(FontId, SharedString)> = Vec::new();
357                for fallback_name in fallbacks.fallback_list() {
358                    let fb_key = FontKey::new(
359                        SharedString::from(fallback_name.clone()),
360                        features.clone(),
361                        None,
362                    );
363                    let fb_ids = if let Some(cached) = self.font_ids_by_family_cache.get(&fb_key) {
364                        cached.clone()
365                    } else {
366                        let loaded = self.load_family(fallback_name, features, None)?;
367                        self.font_ids_by_family_cache.insert(fb_key, loaded.clone());
368                        loaded
369                    };
370                    let Some(&fb_id) = fb_ids.first() else {
371                        continue;
372                    };
373                    let db_id = self.loaded_fonts[fb_id.0].font.id();
374                    if let Some(face) = self.font_system.db().face(db_id)
375                        && let Some(family) = face.families.first()
376                    {
377                        chain.push((fb_id, SharedString::from(family.0.clone())));
378                    }
379                }
380                Arc::from(chain)
381            }
382            _ => Arc::from(Vec::new()),
383        };
384
385        let name = gpui::font_name_with_fallbacks(name, &self.system_font_fallback);
386
387        let families = self
388            .font_system
389            .db()
390            .faces()
391            .filter(|face| face.families.iter().any(|family| *name == family.0))
392            .map(|face| (face.id, face.post_script_name.clone()))
393            .collect::<SmallVec<[_; 4]>>();
394
395        let cosmic_features = cosmic_font_features(features)?;
396
397        let mut loaded_font_ids = SmallVec::new();
398        for (database_id, postscript_name) in families {
399            let key = LoadedFontKey {
400                database_id,
401                font: loaded_font_key.clone(),
402            };
403            if let Some(&font_id) = self.loaded_font_ids_by_key.get(&key) {
404                self.loaded_fonts[font_id.0].user_fallback_chain = Arc::clone(&user_fallback_chain);
405                loaded_font_ids.push(font_id);
406                continue;
407            }
408
409            let font = self
410                .font_system
411                .get_font(database_id, cosmic_text::Weight::NORMAL)
412                .context("Could not load font")?;
413
414            // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback.
415            let allowed_bad_font_names = [
416                "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent
417                "Segoe Fluent Icons",
418            ];
419
420            // This only decides whether a face can be a primary font. The
421            // editor measures layout with the width of 'm' and would panic
422            // without it.
423            //
424            // Don't remove the face from the font database. Arabic, Devanagari
425            // and emoji fonts often have no Latin glyphs, and they are exactly
426            // what cosmic-text falls back to when the primary font lacks a
427            // glyph.
428            if font.as_swash().charmap().map('m') == 0
429                && !allowed_bad_font_names.contains(&postscript_name.as_str())
430            {
431                continue;
432            };
433
434            let font_id = FontId(self.loaded_fonts.len());
435            loaded_font_ids.push(font_id);
436            self.loaded_fonts.push(LoadedFont {
437                font,
438                features: cosmic_features.clone(),
439                is_known_emoji_font: check_is_known_emoji_font(&postscript_name),
440                user_fallback_chain: Arc::clone(&user_fallback_chain),
441            });
442            self.loaded_font_ids_by_key.insert(key, font_id);
443        }
444
445        Ok(loaded_font_ids)
446    }
447
448    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
449        let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
450        Ok(Size {
451            width: glyph_metrics.advance_width(glyph_id.0 as u16),
452            height: glyph_metrics.advance_height(glyph_id.0 as u16),
453        })
454    }
455
456    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
457        let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch);
458        if glyph_id == 0 {
459            None
460        } else {
461            Some(GlyphId(glyph_id.into()))
462        }
463    }
464
465    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
466        let image = self.render_glyph_image(params)?;
467        let bounds = Bounds {
468            origin: point(image.placement.left.into(), (-image.placement.top).into()),
469            size: size(image.placement.width.into(), image.placement.height.into()),
470        };
471        if !bounds.is_zero() {
472            self.pending_glyph_images.insert(params.clone(), image);
473        }
474        Ok(bounds)
475    }
476
477    #[profiling::function]
478    fn rasterize_glyph(
479        &mut self,
480        params: &RenderGlyphParams,
481        glyph_bounds: Bounds<DevicePixels>,
482    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
483        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
484            anyhow::bail!("glyph bounds are empty");
485        }
486
487        let mut image = match self.pending_glyph_images.remove(params) {
488            Some(image) => image,
489            None => self.render_glyph_image(params)?,
490        };
491        let bitmap_size = glyph_bounds.size;
492        match image.content {
493            swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
494                // Convert from RGBA to BGRA.
495                for pixel in image.data.chunks_exact_mut(4) {
496                    pixel.swap(0, 2);
497                }
498                Ok((bitmap_size, image.data))
499            }
500            swash::scale::image::Content::Mask => {
501                if params.subpixel_rendering {
502                    // We must always return RGBA data when subpixel rendering is requested.
503                    let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
504                    Ok((bitmap_size, expanded))
505                } else {
506                    Ok((bitmap_size, image.data))
507                }
508            }
509        }
510    }
511
512    fn render_glyph_image(
513        &mut self,
514        params: &RenderGlyphParams,
515    ) -> Result<swash::scale::image::Image> {
516        let loaded_font = &self.loaded_fonts[params.font_id.0];
517        let font_ref = loaded_font.font.as_swash();
518        let pixel_size = f32::from(params.font_size);
519
520        let subpixel_offset = Vector::new(
521            params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor,
522            params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor,
523        );
524
525        let mut scaler = self
526            .swash_scale_context
527            .builder(font_ref)
528            .size(pixel_size * params.scale_factor)
529            .hint(true)
530            .build();
531
532        let sources: &[Source] = if params.is_emoji {
533            &[
534                Source::ColorOutline(0),
535                Source::ColorBitmap(StrikeWith::BestFit),
536                Source::Outline,
537            ]
538        } else {
539            &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline]
540        };
541
542        let mut renderer = Render::new(sources);
543        if params.subpixel_rendering {
544            // There seems to be a bug in Swash where the B and R values are swapped.
545            renderer
546                .format(Format::subpixel_bgra())
547                .offset(subpixel_offset);
548        } else {
549            renderer.format(Format::Alpha).offset(subpixel_offset);
550        }
551
552        let glyph_id: u16 = params.glyph_id.0.try_into()?;
553        renderer
554            .render(&mut scaler, glyph_id)
555            .with_context(|| format!("unable to render glyph via swash for {params:?}"))
556    }
557
558    /// This is used when cosmic_text has chosen a fallback font instead of using the requested
559    /// font, typically to handle some unicode characters. When this happens, `loaded_fonts` may not
560    /// yet have an entry for this fallback font, and so one is added.
561    ///
562    /// Note that callers shouldn't use this `FontId` somewhere that will retrieve the corresponding
563    /// `LoadedFont.features`, as it will have an arbitrarily chosen or empty value. The only
564    /// current use of this field is for the *input* of `layout_line`, and so it's fine to use
565    /// `font_id_for_cosmic_id` when computing the *output* of `layout_line`.
566    fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> {
567        if let Some(ix) = self
568            .loaded_fonts
569            .iter()
570            .position(|loaded_font| loaded_font.font.id() == id)
571        {
572            Ok(FontId(ix))
573        } else {
574            let font = self
575                .font_system
576                .get_font(id, cosmic_text::Weight::NORMAL)
577                .context("failed to get fallback font from cosmic-text font system")?;
578            let face = self
579                .font_system
580                .db()
581                .face(id)
582                .context("fallback font face not found in cosmic-text database")?;
583
584            let font_id = FontId(self.loaded_fonts.len());
585            self.loaded_fonts.push(LoadedFont {
586                font,
587                features: CosmicFontFeatures::new(),
588                is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name),
589                user_fallback_chain: Arc::from(Vec::new()),
590            });
591
592            Ok(font_id)
593        }
594    }
595
596    #[profiling::function]
597    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
598        if contains_paragraph_separator(text) {
599            self.layout_line_with_separators(text, font_size, font_runs)
600        } else {
601            self.layout_line_no_separators(text, font_size, font_runs)
602        }
603    }
604
605    fn layout_line_with_separators(
606        &mut self,
607        text: &str,
608        font_size: Pixels,
609        font_runs: &[FontRun],
610    ) -> LineLayout {
611        let mut layout = LineLayout {
612            font_size,
613            len: text.len(),
614            ..Default::default()
615        };
616        let mut paragraph_start = 0;
617
618        for (separator_start, separator) in text
619            .char_indices()
620            .filter(|(_, character)| is_paragraph_separator(*character))
621        {
622            let separator_end = separator_start + separator.len_utf8();
623            self.shape_segment(
624                text,
625                paragraph_start..separator_start,
626                font_size,
627                font_runs,
628                &mut layout,
629            );
630            self.shape_segment(
631                text,
632                separator_start..separator_end,
633                font_size,
634                font_runs,
635                &mut layout,
636            );
637            paragraph_start = separator_end;
638        }
639
640        self.shape_segment(
641            text,
642            paragraph_start..text.len(),
643            font_size,
644            font_runs,
645            &mut layout,
646        );
647
648        layout
649    }
650
651    fn shape_segment(
652        &mut self,
653        text: &str,
654        range: Range<usize>,
655        font_size: Pixels,
656        font_runs: &[FontRun],
657        layout: &mut LineLayout,
658    ) {
659        if range.is_empty() {
660            return;
661        }
662
663        let segment_font_runs = clip_font_runs(font_runs, range.clone());
664        let segment =
665            self.layout_line_no_separators(&text[range.clone()], font_size, &segment_font_runs);
666
667        let mut segment_runs = segment.runs;
668        for run in &mut segment_runs {
669            for glyph in &mut run.glyphs {
670                glyph.index += range.start;
671                glyph.position.x += layout.width;
672            }
673        }
674
675        for mut run in segment_runs {
676            if let Some(same_run) = layout
677                .runs
678                .last_mut()
679                .filter(|last| last.font_id == run.font_id)
680            {
681                same_run.glyphs.append(&mut run.glyphs);
682            } else {
683                layout.runs.push(run);
684            }
685        }
686
687        layout.width += segment.width;
688        layout.ascent = layout.ascent.max(segment.ascent);
689        layout.descent = layout.descent.max(segment.descent);
690    }
691
692    fn layout_line_no_separators(
693        &mut self,
694        text: &str,
695        font_size: Pixels,
696        font_runs: &[FontRun],
697    ) -> LineLayout {
698        let mut attrs_list = AttrsList::new(&Attrs::new());
699        let mut offs = 0;
700        for run in font_runs {
701            let run_end = offs + run.len;
702
703            let Some(properties) = self.font_match_properties(run.font_id) else {
704                offs = run_end;
705                continue;
706            };
707
708            let primary_attrs = properties.attributes(run.font_id, &properties.primary_family_name);
709            let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = properties
710                .fallback_chain
711                .iter()
712                .map(|(font_id, family_name)| properties.attributes(*font_id, family_name))
713                .collect();
714
715            let spans = if properties.fallback_chain.is_empty() {
716                let mut spans = SmallVec::<[RunSpan; 4]>::new();
717                spans.push(RunSpan {
718                    start: offs,
719                    end: run_end,
720                    slot: None,
721                    font_id: run.font_id,
722                });
723                spans
724            } else {
725                let loaded_fonts = &self.loaded_fonts;
726                let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch);
727                compute_run_spans(
728                    text,
729                    offs,
730                    run.len,
731                    run.font_id,
732                    &properties.fallback_chain,
733                    &covers,
734                )
735            };
736
737            for span in spans {
738                let attrs = match span.slot {
739                    None => &primary_attrs,
740                    Some(ix) => &fallback_attrs[ix],
741                };
742                attrs_list.add_span(span.start..span.end, attrs);
743            }
744            offs = run_end;
745        }
746
747        let line = ShapeLine::new(
748            &mut self.font_system,
749            text,
750            &attrs_list,
751            cosmic_text::Shaping::Advanced,
752            4,
753        );
754        let mut layout_lines = Vec::with_capacity(1);
755        line.layout_to_buffer(
756            &mut self.scratch,
757            f32::from(font_size),
758            None, // We do our own wrapping
759            cosmic_text::Wrap::None,
760            Ellipsize::None,
761            None,
762            &mut layout_lines,
763            None,
764            cosmic_text::Hinting::Disabled,
765        );
766
767        let Some(layout) = layout_lines.first() else {
768            return LineLayout {
769                font_size,
770                width: Pixels::ZERO,
771                ascent: Pixels::ZERO,
772                descent: Pixels::ZERO,
773                runs: Vec::new(),
774                len: text.len(),
775            };
776        };
777
778        let missing_glyphs = self.missing_glyph_sink.as_ref().map(|_| {
779            self.missing_glyphs(
780                text,
781                font_runs,
782                layout
783                    .glyphs
784                    .iter()
785                    .filter(|glyph| glyph.glyph_id == 0)
786                    .map(|glyph| glyph.start),
787            )
788        });
789
790        let mut runs: Vec<ShapedRun> = Vec::new();
791        for glyph in &layout.glyphs {
792            let mut font_id = FontId(glyph.metadata);
793            let mut loaded_font = self.loaded_font(font_id);
794            if loaded_font.font.id() != glyph.font_id {
795                match self.font_id_for_cosmic_id(glyph.font_id) {
796                    std::result::Result::Ok(resolved_id) => {
797                        font_id = resolved_id;
798                        loaded_font = self.loaded_font(font_id);
799                    }
800                    Err(error) => {
801                        log::warn!(
802                            "failed to resolve cosmic font id {:?}: {error:#}",
803                            glyph.font_id
804                        );
805                        continue;
806                    }
807                }
808            }
809            let is_emoji = loaded_font.is_known_emoji_font;
810
811            // HACK: Prevent crash caused by variation selectors.
812            if glyph.glyph_id == 3 && is_emoji {
813                continue;
814            }
815
816            let shaped_glyph = ShapedGlyph {
817                id: GlyphId(glyph.glyph_id as u32),
818                position: point(
819                    (glyph.x + glyph.x_offset * f32::from(font_size)).into(),
820                    (glyph.y - glyph.y_offset * f32::from(font_size)).into(),
821                ),
822                index: glyph.start,
823                is_emoji,
824            };
825
826            if let Some(last_run) = runs
827                .last_mut()
828                .filter(|last_run| last_run.font_id == font_id)
829            {
830                last_run.glyphs.push(shaped_glyph);
831            } else {
832                runs.push(ShapedRun {
833                    font_id,
834                    glyphs: vec![shaped_glyph],
835                });
836            }
837        }
838
839        if let Some((sink, missing_glyphs)) = self.missing_glyph_sink.as_ref().zip(missing_glyphs) {
840            sink.report(missing_glyphs);
841        }
842
843        LineLayout {
844            font_size,
845            width: layout.w.into(),
846            ascent: layout.max_ascent.into(),
847            descent: layout.max_descent.into(),
848            runs,
849            len: text.len(),
850        }
851    }
852
853    fn missing_glyphs(
854        &self,
855        text: &str,
856        font_runs: &[FontRun],
857        missing_text_indices: impl IntoIterator<Item = usize>,
858    ) -> Vec<MissingGlyph> {
859        let mut missing_text_indices = missing_text_indices.into_iter().peekable();
860        if missing_text_indices.peek().is_none() {
861            return Vec::new();
862        }
863        let mut missing_text_indices = missing_text_indices.collect::<Vec<_>>();
864        missing_text_indices.sort_unstable();
865        missing_text_indices.dedup();
866
867        let mut font_run_index = 0;
868        let mut font_run_end = font_runs.first().map_or(0, |font_run| font_run.len);
869        let mut missing_glyphs = Vec::new();
870        let mut missing_index = 0;
871        for (grapheme_start, grapheme) in text.grapheme_indices(true) {
872            let grapheme_end = grapheme_start + grapheme.len();
873            while missing_text_indices
874                .get(missing_index)
875                .is_some_and(|text_index| *text_index < grapheme_start)
876            {
877                missing_index += 1;
878            }
879            let Some(&text_index) = missing_text_indices.get(missing_index) else {
880                break;
881            };
882            if text_index >= grapheme_end {
883                continue;
884            }
885
886            while font_run_end <= text_index && font_run_index + 1 < font_runs.len() {
887                font_run_index += 1;
888                let Some(font_run) = font_runs.get(font_run_index) else {
889                    break;
890                };
891                font_run_end += font_run.len;
892            }
893            let font_class = self.fallback_font_class(
894                font_runs
895                    .get(font_run_index)
896                    .or_else(|| font_runs.last())
897                    .map(|font_run| font_run.font_id),
898            );
899            missing_glyphs.push(MissingGlyph::new(grapheme.into(), font_class));
900            while missing_text_indices
901                .get(missing_index)
902                .is_some_and(|text_index| *text_index < grapheme_end)
903            {
904                missing_index += 1;
905            }
906        }
907        missing_glyphs
908    }
909
910    fn fallback_font_class(&self, font_id: Option<FontId>) -> FallbackFontClass {
911        let Some(font_id) = font_id else {
912            return FallbackFontClass::Proportional;
913        };
914        let loaded_font = self.loaded_font(font_id);
915        let is_monospace = self
916            .font_system
917            .db()
918            .face(loaded_font.font.id())
919            .is_some_and(|face| face.monospaced);
920        if is_monospace {
921            FallbackFontClass::Monospace
922        } else {
923            FallbackFontClass::Proportional
924        }
925    }
926}
927
928#[inline(always)]
929fn is_paragraph_separator(character: char) -> bool {
930    unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B
931}
932
933fn contains_paragraph_separator(text: &str) -> bool {
934    if text
935        .bytes()
936        .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e))
937    {
938        return true;
939    }
940
941    !text.is_ascii() && text.chars().any(is_paragraph_separator)
942}
943
944fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontRun; 4]> {
945    let mut clipped = SmallVec::new();
946    let mut offs = 0;
947    for run in font_runs {
948        let run_start = offs;
949        offs += run.len;
950        if offs <= range.start {
951            continue;
952        }
953        if run_start >= range.end {
954            break;
955        }
956        let start = run_start.max(range.start);
957        let end = offs.min(range.end);
958        if start < end {
959            clipped.push(FontRun {
960                len: end - start,
961                font_id: run.font_id,
962            });
963        }
964    }
965    clipped
966}
967
968#[cfg(feature = "font-kit")]
969fn find_best_match(
970    font: &Font,
971    candidates: &[FontId],
972    state: &CosmicTextSystemState,
973) -> Result<usize> {
974    let candidate_properties = candidates
975        .iter()
976        .map(|font_id| {
977            let database_id = state.loaded_font(*font_id).font.id();
978            let face_info = state
979                .font_system
980                .db()
981                .face(database_id)
982                .context("font face not found in database")?;
983            Ok(face_info_into_properties(face_info))
984        })
985        .collect::<Result<SmallVec<[_; 4]>>>()?;
986
987    let ix =
988        font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
989            .context("requested font family contains no font matching the other parameters")?;
990
991    Ok(ix)
992}
993
994#[cfg(not(feature = "font-kit"))]
995fn find_best_match(
996    font: &Font,
997    candidates: &[FontId],
998    state: &CosmicTextSystemState,
999) -> Result<usize> {
1000    if candidates.is_empty() {
1001        anyhow::bail!("requested font family contains no font matching the other parameters");
1002    }
1003    if candidates.len() == 1 {
1004        return Ok(0);
1005    }
1006
1007    let target_weight = font.weight.0;
1008    let target_italic = matches!(
1009        font.style,
1010        gpui::FontStyle::Italic | gpui::FontStyle::Oblique
1011    );
1012
1013    let mut best_index = 0;
1014    let mut best_score = u32::MAX;
1015
1016    for (index, font_id) in candidates.iter().enumerate() {
1017        let database_id = state.loaded_font(*font_id).font.id();
1018        let face_info = state
1019            .font_system
1020            .db()
1021            .face(database_id)
1022            .context("font face not found in database")?;
1023
1024        let is_italic = matches!(
1025            face_info.style,
1026            cosmic_text::Style::Italic | cosmic_text::Style::Oblique
1027        );
1028        let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
1029        let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
1030        let score = style_penalty + weight_diff;
1031
1032        if score < best_score {
1033            best_score = score;
1034            best_index = index;
1035        }
1036    }
1037
1038    Ok(best_index)
1039}
1040
1041/// one contiguous slice of a `FontRun` that maps to a single slot. `slot` is
1042/// `None` for the primary font and `Some(ix)` for `fallback_chain[ix]`.
1043#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1044struct RunSpan {
1045    start: usize,
1046    end: usize,
1047    slot: Option<usize>,
1048    font_id: FontId,
1049}
1050
1051/// walks `text[run_offset..run_offset + run_len]` and groups codepoints into
1052/// spans. inheriting codepoints stay in the current span so shaping clusters
1053/// like emoji zwj sequences and combining marks are not torn apart.
1054fn compute_run_spans(
1055    text: &str,
1056    run_offset: usize,
1057    run_len: usize,
1058    primary: FontId,
1059    fallback_chain: &[(FontId, SharedString)],
1060    covers: &impl Fn(FontId, char) -> bool,
1061) -> SmallVec<[RunSpan; 4]> {
1062    let mut spans = SmallVec::new();
1063    let run_end = run_offset + run_len;
1064    if run_end <= run_offset {
1065        return spans;
1066    }
1067    if fallback_chain.is_empty() {
1068        spans.push(RunSpan {
1069            start: run_offset,
1070            end: run_end,
1071            slot: None,
1072            font_id: primary,
1073        });
1074        return spans;
1075    }
1076    let run_text = &text[run_offset..run_end];
1077    let mut span_start = run_offset;
1078    let mut span_slot: Option<usize> = None;
1079    let mut span_font_id = primary;
1080    for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) {
1081        let abs = run_offset + grapheme_idx;
1082        let ch = grapheme.chars().next().unwrap_or('\0');
1083        let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);
1084        if next_slot == span_slot {
1085            continue;
1086        }
1087        if abs > span_start {
1088            spans.push(RunSpan {
1089                start: span_start,
1090                end: abs,
1091                slot: span_slot,
1092                font_id: span_font_id,
1093            });
1094        }
1095        span_start = abs;
1096        span_slot = next_slot;
1097        span_font_id = slot_font_id(next_slot, primary, fallback_chain);
1098    }
1099    if span_start < run_end {
1100        spans.push(RunSpan {
1101            start: span_start,
1102            end: run_end,
1103            slot: span_slot,
1104            font_id: span_font_id,
1105        });
1106    }
1107    spans
1108}
1109
1110fn slot_font_id(
1111    slot: Option<usize>,
1112    primary: FontId,
1113    fallback_chain: &[(FontId, SharedString)],
1114) -> FontId {
1115    match slot {
1116        None => primary,
1117        Some(ix) => fallback_chain[ix].0,
1118    }
1119}
1120
1121fn pick_covering_slot(
1122    ch: char,
1123    current: Option<usize>,
1124    primary: FontId,
1125    fallback_chain: &[(FontId, SharedString)],
1126    covers: &impl Fn(FontId, char) -> bool,
1127) -> Option<usize> {
1128    if (ch as u32) <= 0x7F {
1129        return None;
1130    }
1131    if covers(primary, ch) {
1132        return None;
1133    }
1134    let current_id = slot_font_id(current, primary, fallback_chain);
1135    if covers(current_id, ch) {
1136        return current;
1137    }
1138
1139    fallback_chain
1140        .iter()
1141        .position(|(fb_id, _)| covers(*fb_id, ch))
1142}
1143
1144fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool {
1145    loaded_fonts
1146        .get(id.0)
1147        .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0)
1148}
1149
1150fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
1151    let mut result = CosmicFontFeatures::new();
1152    for feature in features.0.iter() {
1153        let name_bytes: [u8; 4] = feature
1154            .0
1155            .as_bytes()
1156            .try_into()
1157            .context("Incorrect feature flag format")?;
1158
1159        let tag = cosmic_text::FeatureTag::new(&name_bytes);
1160
1161        result.set(tag, feature.1);
1162    }
1163    Ok(result)
1164}
1165
1166#[cfg(feature = "font-kit")]
1167fn font_into_properties(font: &gpui::Font) -> font_kit::properties::Properties {
1168    font_kit::properties::Properties {
1169        style: match font.style {
1170            gpui::FontStyle::Normal => font_kit::properties::Style::Normal,
1171            gpui::FontStyle::Italic => font_kit::properties::Style::Italic,
1172            gpui::FontStyle::Oblique => font_kit::properties::Style::Oblique,
1173        },
1174        weight: font_kit::properties::Weight(font.weight.0),
1175        stretch: Default::default(),
1176    }
1177}
1178
1179#[cfg(feature = "font-kit")]
1180fn face_info_into_properties(
1181    face_info: &cosmic_text::fontdb::FaceInfo,
1182) -> font_kit::properties::Properties {
1183    font_kit::properties::Properties {
1184        style: match face_info.style {
1185            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
1186            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
1187            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
1188        },
1189        weight: font_kit::properties::Weight(face_info.weight.0.into()),
1190        stretch: match face_info.stretch {
1191            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
1192            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
1193            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
1194            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
1195            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
1196            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
1197            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
1198            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
1199            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
1200        },
1201    }
1202}
1203
1204fn check_is_known_emoji_font(postscript_name: &str) -> bool {
1205    // TODO: Include other common emoji fonts
1206    postscript_name == "NotoColorEmoji"
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211    use super::*;
1212
1213    #[cfg(feature = "test-support")]
1214    use std::{cell::RefCell, rc::Rc};
1215    use std::{
1216        sync::mpsc,
1217        thread,
1218        time::{Duration, Instant},
1219    };
1220
1221    #[test]
1222    fn all_font_names_tracks_available_families() -> Result<()> {
1223        let text_system = gpui::TextSystem::new(Arc::new(
1224            CosmicTextSystem::new_without_system_fonts("IBM Plex Sans"),
1225        ));
1226        assert!(text_system.all_font_names().is_empty());
1227
1228        text_system.add_fonts(vec![Cow::Borrowed(include_bytes!(
1229            "../../../assets/fonts/lilex/Lilex-Regular.ttf"
1230        ))])?;
1231        assert_eq!(text_system.all_font_names(), ["Lilex"]);
1232
1233        text_system.add_fonts(vec![
1234            Cow::Borrowed(IBM_PLEX),
1235            Cow::Borrowed(include_bytes!("../../../assets/fonts/lilex/Lilex-Bold.ttf")),
1236        ])?;
1237        assert_eq!(text_system.all_font_names(), ["IBM Plex Sans", "Lilex"]);
1238        Ok(())
1239    }
1240
1241    fn fid(i: usize) -> FontId {
1242        FontId(i)
1243    }
1244
1245    fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> {
1246        ids.iter()
1247            .map(|&i| (fid(i), SharedString::from(format!("fb{i}"))))
1248            .collect()
1249    }
1250
1251    fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan {
1252        RunSpan {
1253            start,
1254            end,
1255            slot,
1256            font_id,
1257        }
1258    }
1259
1260    const IBM_PLEX: &[u8] =
1261        include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
1262    const LILEX: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf");
1263
1264    /// Every code point of `Bidi_Class=B`, each of which starts a new bidi
1265    /// paragraph and so can split one line into mixed-direction paragraphs.
1266    const SEPARATORS: &[char] = &[
1267        '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}',
1268    ];
1269
1270    fn text_system() -> Result<CosmicTextSystem> {
1271        let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans");
1272        text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;
1273        Ok(text_system)
1274    }
1275
1276    #[test]
1277    fn cached_font_resolution_does_not_wait_for_cold_lookups() -> Result<()> {
1278        for family in [".ZedSans", "Missing Font"] {
1279            let platform_text_system = Arc::new(text_system()?);
1280            let text_system = gpui::TextSystem::new(platform_text_system.clone());
1281            let cached = gpui::font(family);
1282            let expected = platform_text_system.font_id(&gpui::font(".ZedSans"))?;
1283            assert_eq!(text_system.resolve_font(&cached), expected);
1284            let (sender, receiver) = mpsc::channel();
1285
1286            thread::scope(|scope| {
1287                let backend = platform_text_system.0.read();
1288                let deadline = Instant::now() + Duration::from_secs(5);
1289                let cold = scope.spawn(|| text_system.resolve_font(&cached.clone().bold()));
1290                while !platform_text_system.0.is_locked_exclusive() && Instant::now() < deadline {
1291                    thread::yield_now();
1292                }
1293                let cold_waiting = platform_text_system.0.is_locked_exclusive();
1294                let warm = scope.spawn(|| sender.send(text_system.resolve_font(&cached)));
1295                let result =
1296                    receiver.recv_timeout(deadline.saturating_duration_since(Instant::now()));
1297                drop(backend);
1298                let cold_result = cold.join();
1299                let warm_result = warm.join();
1300
1301                assert!(cold_waiting);
1302                assert_eq!(result.expect("cached lookup blocked"), expected);
1303                assert_eq!(cold_result.expect("cold lookup panicked"), expected);
1304                warm_result
1305                    .expect("warm lookup panicked")
1306                    .expect("receiver dropped");
1307            });
1308        }
1309        Ok(())
1310    }
1311
1312    #[test]
1313    fn adding_fonts_retries_cached_font_failures() -> Result<()> {
1314        let platform_text_system = Arc::new(CosmicTextSystem::new_without_system_fonts("Lilex"));
1315        let text_system = gpui::TextSystem::new(platform_text_system.clone());
1316        text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;
1317        let original_fallback = platform_text_system.font_id(&gpui::font(".ZedSans"))?;
1318        let requests = [
1319            gpui::Font::default(),
1320            gpui::font("Lilex"),
1321            gpui::font("Missing Font"),
1322        ];
1323        for requested in &requests {
1324            assert_eq!(text_system.resolve_font(requested), original_fallback);
1325        }
1326        assert_eq!(
1327            text_system.get_font_for_id(original_fallback),
1328            Some(gpui::font(".ZedSans"))
1329        );
1330
1331        text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?;
1332        for (requested, resolved) in requests.iter().zip([".SystemUIFont", "Lilex", ".ZedMono"]) {
1333            let installed = platform_text_system.font_id(&gpui::font(resolved))?;
1334            assert_ne!(installed, original_fallback);
1335            assert_eq!(text_system.resolve_font(requested), installed);
1336        }
1337        Ok(())
1338    }
1339
1340    #[test]
1341    fn font_properties_describe_the_selected_face() -> Result<()> {
1342        let text_system = text_system()?;
1343        let regular = gpui::font("IBM Plex Sans");
1344        let regular_id = text_system.font_id(&regular)?;
1345        for (weight, style) in [
1346            (gpui::FontWeight::MEDIUM, gpui::FontStyle::Normal),
1347            (gpui::FontWeight::BOLD, gpui::FontStyle::Italic),
1348            (gpui::FontWeight::NORMAL, gpui::FontStyle::Oblique),
1349        ] {
1350            let requested = Font {
1351                weight,
1352                style,
1353                ..regular.clone()
1354            };
1355            let font_id = text_system.font_id(&requested)?;
1356            assert_eq!(font_id, regular_id);
1357            assert_eq!(
1358                text_system.font_weight_and_style(font_id)?,
1359                (gpui::FontWeight::NORMAL, gpui::FontStyle::Normal)
1360            );
1361        }
1362        Ok(())
1363    }
1364
1365    fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result<LineLayout> {
1366        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1367        let runs = [FontRun {
1368            len: text.len(),
1369            font_id,
1370        }];
1371        Ok(text_system.layout_line(text, gpui::px(14.0), &runs))
1372    }
1373
1374    #[test]
1375    fn combining_marks_are_positioned_over_their_base() -> Result<()> {
1376        let text_system = text_system()?;
1377        let layout = layout_text(&text_system, "v\u{0304}v")?;
1378        let glyphs = layout
1379            .runs
1380            .iter()
1381            .flat_map(|run| run.glyphs.iter())
1382            .collect::<Vec<_>>();
1383        assert_eq!(glyphs.len(), 3);
1384        let base = glyphs[0].position;
1385        let mark = glyphs[1].position;
1386        let next = glyphs[2].position;
1387        assert!(mark.x > base.x);
1388        assert!(
1389            mark.x < next.x,
1390            "combining mark positioned after its base: mark.x={:?}, next.x={:?}",
1391            mark.x,
1392            next.x
1393        );
1394        Ok(())
1395    }
1396
1397    /// Mirrors the original crash: mixed-direction text reaching the shaper
1398    /// through `shape_text`, which only splits lines on `\n`.
1399    #[test]
1400    fn shape_text_with_mixed_direction_paragraphs() -> Result<()> {
1401        let platform_text_system = Arc::new(text_system()?);
1402        let text_system = Arc::new(gpui::TextSystem::new(platform_text_system));
1403        let window_text_system = gpui::WindowTextSystem::new(text_system);
1404
1405        let text: SharedString = "first line\n\u{05d0}\u{001c}A".into();
1406        let runs = [gpui::TextRun {
1407            len: text.len(),
1408            font: gpui::font("IBM Plex Sans"),
1409            ..Default::default()
1410        }];
1411
1412        let lines = window_text_system.shape_text(text, gpui::px(14.0), &runs, None, None)?;
1413
1414        assert_eq!(lines.len(), 2);
1415        assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len());
1416        assert!(lines[1].width() > Pixels::ZERO);
1417        Ok(())
1418    }
1419
1420    #[cfg(feature = "test-support")]
1421    #[test]
1422    fn reports_graphemes_that_exhaust_font_fallback() -> Result<()> {
1423        let platform_text_system = Arc::new(text_system()?);
1424        let dispatcher = gpui::TestDispatcher::new(0);
1425        let cx =
1426            gpui::TestAppContext::build_with_text_system(dispatcher, None, platform_text_system);
1427        let observed = Rc::new(RefCell::new(Vec::new()));
1428        let _subscription = cx.update(|cx| {
1429            let observed = observed.clone();
1430            cx.on_missing_glyphs(move |missing_glyphs, _| {
1431                observed.borrow_mut().extend_from_slice(missing_glyphs);
1432            })
1433        });
1434        let text: SharedString = "界".into();
1435
1436        cx.update(|cx| {
1437            let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
1438            let runs = [gpui::TextRun {
1439                len: text.len(),
1440                font: gpui::font("IBM Plex Sans"),
1441                ..Default::default()
1442            }];
1443            text_system.shape_line(text, gpui::px(14.0), &runs, None);
1444        });
1445        cx.run_until_parked();
1446
1447        let observed = observed.borrow();
1448        assert_eq!(observed.len(), 1);
1449        assert_eq!(observed[0].grapheme(), "界");
1450        assert_eq!(
1451            observed[0].font_class(),
1452            gpui::FallbackFontClass::Proportional
1453        );
1454        Ok(())
1455    }
1456
1457    #[test]
1458    fn combines_missing_glyphs_from_one_grapheme() -> Result<()> {
1459        let text_system = text_system()?;
1460        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1461        let text = "x\u{0301}";
1462        let runs = [FontRun {
1463            len: text.len(),
1464            font_id,
1465        }];
1466
1467        let missing_glyphs = text_system
1468            .0
1469            .read()
1470            .missing_glyphs(text, &runs, [0, "x".len()]);
1471
1472        assert_eq!(missing_glyphs.len(), 1);
1473        assert_eq!(missing_glyphs[0].grapheme(), text);
1474        Ok(())
1475    }
1476
1477    #[test]
1478    fn adding_fonts_invalidates_cached_line_layouts() -> Result<()> {
1479        let platform_text_system = Arc::new(text_system()?);
1480        let text_system = Arc::new(gpui::TextSystem::new(platform_text_system.clone()));
1481        let window_text_system = gpui::WindowTextSystem::new(text_system.clone());
1482        let text: SharedString = "cached text".into();
1483        let runs = [gpui::TextRun {
1484            len: text.len(),
1485            font: gpui::font("IBM Plex Sans"),
1486            ..Default::default()
1487        }];
1488
1489        let first_layout = window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None);
1490        let cached_layout =
1491            window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None);
1492        assert!(std::ptr::eq::<LineLayout>(
1493            &**first_layout,
1494            &**cached_layout
1495        ));
1496        let loaded_font_count = platform_text_system.0.read().loaded_fonts.len();
1497
1498        text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?;
1499
1500        let refreshed_layout = window_text_system.shape_line(text, gpui::px(14.0), &runs, None);
1501        assert!(!std::ptr::eq::<LineLayout>(
1502            &**first_layout,
1503            &**refreshed_layout
1504        ));
1505        assert_eq!(
1506            platform_text_system.0.read().loaded_fonts.len(),
1507            loaded_font_count
1508        );
1509        Ok(())
1510    }
1511
1512    #[test]
1513    fn layout_line_with_mixed_direction_paragraphs() -> Result<()> {
1514        let text_system = text_system()?;
1515
1516        for separator in SEPARATORS {
1517            for text in [
1518                format!("\u{05d0}{separator}A"),
1519                format!("A{separator}\u{05d0}"),
1520            ] {
1521                let layout = layout_text(&text_system, &text)?;
1522
1523                assert_eq!(layout.len, text.len(), "{text:?}");
1524                assert!(layout.width > Pixels::ZERO, "{text:?}");
1525                assert!(
1526                    layout.runs.iter().any(|run| !run.glyphs.is_empty()),
1527                    "{text:?}"
1528                );
1529            }
1530        }
1531
1532        Ok(())
1533    }
1534
1535    #[test]
1536    fn layout_line_with_separators_at_line_edges() -> Result<()> {
1537        let text_system = text_system()?;
1538
1539        for text in [
1540            "\u{001c}",
1541            "\u{001c}\u{001c}",
1542            "\u{001c}\u{05d0}",
1543            "\u{05d0}\u{001c}",
1544            "\u{05d0}\u{001c}\u{001c}A",
1545            "\u{001c}\u{05d0}\u{001c}A\u{001c}",
1546        ] {
1547            let layout = layout_text(&text_system, text)?;
1548            assert_eq!(layout.len, text.len(), "{text:?}");
1549        }
1550
1551        Ok(())
1552    }
1553
1554    /// Glyph indices must stay absolute and positions ordered across segment
1555    /// boundaries, otherwise cursor placement and hit testing desync. Uses
1556    /// single-direction text so visual order matches logical order.
1557    #[test]
1558    fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> {
1559        let text_system = text_system()?;
1560        let text = "ab\u{001c}cd\u{2029}ef";
1561        let layout = layout_text(&text_system, text)?;
1562
1563        let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect();
1564        assert!(!glyphs.is_empty());
1565
1566        for glyph in &glyphs {
1567            assert!(glyph.index < text.len(), "{:?}", glyph.index);
1568            assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index);
1569        }
1570        for pair in glyphs.windows(2) {
1571            assert!(pair[0].index < pair[1].index);
1572            assert!(pair[0].position.x <= pair[1].position.x);
1573        }
1574
1575        // Every segment contributes width, so the whole line is wider than its
1576        // leading paragraph alone.
1577        assert!(layout.width > layout_text(&text_system, "ab")?.width);
1578        Ok(())
1579    }
1580
1581    /// A font run boundary that does not line up with a paragraph boundary must
1582    /// still be clipped to the right segments.
1583    #[test]
1584    fn layout_line_with_font_run_straddling_a_separator() -> Result<()> {
1585        let text_system = text_system()?;
1586        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1587        let text = "ab\u{001c}\u{05d0}\u{05d1}";
1588
1589        // The run boundary falls inside the trailing RTL paragraph.
1590        let runs = [
1591            FontRun {
1592                len: "ab\u{001c}\u{05d0}".len(),
1593                font_id,
1594            },
1595            FontRun {
1596                len: "\u{05d1}".len(),
1597                font_id,
1598            },
1599        ];
1600        let layout = text_system.layout_line(text, gpui::px(14.0), &runs);
1601
1602        assert_eq!(layout.len, text.len());
1603        assert!(layout.width > Pixels::ZERO);
1604        Ok(())
1605    }
1606
1607    /// Lines with no separator take the fast path and must be shaped exactly as
1608    /// they were before paragraph splitting existed.
1609    #[test]
1610    fn layout_line_without_separators_takes_fast_path() -> Result<()> {
1611        let text_system = text_system()?;
1612
1613        for text in [
1614            "hello world",
1615            "\u{05d0}\u{05d1}\u{05d2}",
1616            "mixed \u{05d0}\u{05d1}",
1617        ] {
1618            assert!(!contains_paragraph_separator(text), "{text:?}");
1619            let layout = layout_text(&text_system, text)?;
1620            assert_eq!(layout.len, text.len(), "{text:?}");
1621            assert!(layout.width > Pixels::ZERO, "{text:?}");
1622        }
1623
1624        Ok(())
1625    }
1626
1627    /// cosmic-text sums word widths to get a line's width but accumulates glyph
1628    /// advances to position glyphs, so a trailing zero-advance glyph (here a
1629    /// zero-width space) can land a few ulps past the width. When that glyph is a
1630    /// wrap boundary, the row before it extends past the line's width, and hit
1631    /// testing in that sliver used to panic (ZED-BW8, ZED-75K, ZED-81Z).
1632    #[test]
1633    fn index_for_position_past_line_width() -> Result<()> {
1634        let text_system = Arc::new(gpui::TextSystem::new(Arc::new(text_system()?)));
1635        let window_text_system = gpui::WindowTextSystem::new(text_system);
1636        let text: SharedString = "Warning: this will delete files\u{200b}".into();
1637        let runs = [gpui::TextRun {
1638            len: text.len(),
1639            font: gpui::font("IBM Plex Sans"),
1640            ..Default::default()
1641        }];
1642        let lines =
1643            window_text_system.shape_text(text, gpui::px(14.), &runs, Some(gpui::px(4.)), None)?;
1644        let line = &lines[0];
1645        let width = line.unwrapped_layout.width;
1646        let boundary_glyph = |row: usize| {
1647            let boundary = line.wrap_boundaries()[row];
1648            &line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix]
1649        };
1650        let row = (1..line.wrap_boundaries().len())
1651            .find(|row| boundary_glyph(*row).position.x > width)
1652            .expect("trailing zero-width space should be a wrap boundary past the line width");
1653        let row_start_x = f32::from(boundary_glyph(row - 1).position.x);
1654        let row_end = boundary_glyph(row);
1655
1656        let mut x = f32::from(width) - row_start_x;
1657        while x + row_start_x < f32::from(width) {
1658            x = x.next_up();
1659        }
1660        assert!(gpui::px(x + row_start_x) < row_end.position.x);
1661
1662        let line_height = gpui::px(20.);
1663        let position = gpui::point(gpui::px(x), line_height * row as f32 + gpui::px(1.));
1664        assert_eq!(
1665            line.index_for_position(position, line_height),
1666            Err(row_end.index)
1667        );
1668        Ok(())
1669    }
1670
1671    #[test]
1672    fn paragraph_separator_detection() {
1673        for separator in SEPARATORS {
1674            assert!(is_paragraph_separator(*separator), "{separator:?}");
1675            assert!(contains_paragraph_separator(&format!("a{separator}b")));
1676        }
1677
1678        for text in [
1679            "",
1680            "plain ascii",
1681            "\u{05d0}",
1682            "tab\there",
1683            "emoji \u{1f600}",
1684        ] {
1685            assert!(!contains_paragraph_separator(text), "{text:?}");
1686        }
1687    }
1688
1689    #[test]
1690    fn font_runs_are_clipped_to_segment() {
1691        let runs = [
1692            FontRun {
1693                len: 3,
1694                font_id: fid(1),
1695            },
1696            FontRun {
1697                len: 4,
1698                font_id: fid(2),
1699            },
1700        ];
1701
1702        assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs);
1703        assert_eq!(
1704            clip_font_runs(&runs, 2..5).as_slice(),
1705            &[
1706                FontRun {
1707                    len: 1,
1708                    font_id: fid(1)
1709                },
1710                FontRun {
1711                    len: 2,
1712                    font_id: fid(2)
1713                },
1714            ]
1715        );
1716        assert_eq!(
1717            clip_font_runs(&runs, 3..7).as_slice(),
1718            &[FontRun {
1719                len: 4,
1720                font_id: fid(2)
1721            }]
1722        );
1723        assert!(clip_font_runs(&runs, 5..5).is_empty());
1724    }
1725
1726    #[test]
1727    fn primary_wins_over_current_fallback_when_primary_covers() {
1728        let primary = fid(0);
1729        let fb = chain(&[1, 2]);
1730        let covers = |id: FontId, _: char| id == fid(0) || id == fid(1);
1731        assert_eq!(
1732            pick_covering_slot('a', Some(0), primary, &fb, &covers),
1733            None
1734        );
1735    }
1736
1737    #[test]
1738    fn primary_preferred_over_fallback_when_both_cover() {
1739        let primary = fid(0);
1740        let fb = chain(&[1]);
1741        let covers = |_: FontId, _: char| true;
1742        assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1743    }
1744
1745    #[test]
1746    fn falls_through_chain_in_order() {
1747        let primary = fid(0);
1748        let fb = chain(&[1, 2, 3]);
1749        // only fallback 2 at index 1 covers.
1750        let covers = |id: FontId, _: char| id == fid(2);
1751        assert_eq!(
1752            pick_covering_slot('字', None, primary, &fb, &covers),
1753            Some(1)
1754        );
1755    }
1756
1757    #[test]
1758    fn no_coverage_returns_primary() {
1759        let primary = fid(0);
1760        let fb = chain(&[1, 2]);
1761        let covers = |_: FontId, _: char| false;
1762        // nothing covers. return `None` so the `cosmic-text` built in script
1763        // fallback can take over during shaping.
1764        assert_eq!(
1765            pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers),
1766            None
1767        );
1768    }
1769
1770    #[test]
1771    fn empty_chain_always_returns_primary() {
1772        let primary = fid(0);
1773        let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1774        let covers = |_: FontId, _: char| false;
1775        assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1776    }
1777
1778    #[test]
1779    fn slot_font_id_resolution() {
1780        let primary = fid(7);
1781        let fb = chain(&[10, 20]);
1782        assert_eq!(slot_font_id(None, primary, &fb), fid(7));
1783        assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10));
1784        assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20));
1785    }
1786
1787    #[test]
1788    fn run_spans_with_no_chain_emit_one_primary_span() {
1789        let primary = fid(0);
1790        let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1791        let covers = |_: FontId, _: char| false;
1792        let text = "hello";
1793        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1794        assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]);
1795    }
1796
1797    #[test]
1798    fn run_spans_use_byte_offsets_for_multibyte_chars() {
1799        let primary = fid(0);
1800        let fb = chain(&[1]);
1801        // primary covers ascii. fallback covers cjk.
1802        let covers = |id: FontId, ch: char| {
1803            if id == primary {
1804                ch.is_ascii()
1805            } else {
1806                !ch.is_ascii()
1807            }
1808        };
1809        let text = "a字b";
1810        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1811        // '字' is 3 bytes so split is at 1 then 4.
1812        assert_eq!(
1813            spans.as_slice(),
1814            &[
1815                span(0, 1, None, primary),
1816                span(1, 4, Some(0), fid(1)),
1817                span(4, 5, None, primary),
1818            ]
1819        );
1820    }
1821
1822    #[test]
1823    fn run_spans_respect_run_offset() {
1824        let primary = fid(0);
1825        let fb = chain(&[1]);
1826        let covers = |id: FontId, ch: char| {
1827            if id == primary {
1828                ch.is_ascii()
1829            } else {
1830                !ch.is_ascii()
1831            }
1832        };
1833        // outer text has a prefix that is not part of this run.
1834        let text = "xx字y";
1835        let run_offset = 2;
1836        let run_len = text.len() - run_offset;
1837        let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers);
1838        assert_eq!(
1839            spans.as_slice(),
1840            &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)]
1841        );
1842    }
1843
1844    #[test]
1845    fn run_spans_keep_combining_marks_with_base_in_fallback() {
1846        let primary = fid(0);
1847        let fb = chain(&[1]);
1848        // primary covers ascii only. fallback covers the base char.
1849        // combining mark must stay in the fallback span even when fallback
1850        // does not advertise coverage of it.
1851        let covers = |id: FontId, ch: char| {
1852            if id == primary {
1853                ch.is_ascii()
1854            } else {
1855                ch == '\u{0905}'
1856            }
1857        };
1858        // \u{0905} devanagari short a + \u{0902} candrabindu mark.
1859        let text = "\u{0905}\u{0902}";
1860        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1861        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1862    }
1863
1864    #[test]
1865    fn run_spans_keep_zwj_inside_emoji_cluster() {
1866        let primary = fid(0);
1867        let fb = chain(&[1]);
1868        // only fallback covers the emoji codepoints. zwj must not split.
1869        let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}';
1870        // family zwj sequence woman zwj girl.
1871        let text = "\u{1F469}\u{200D}\u{1F467}";
1872        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1873        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1874    }
1875
1876    #[test]
1877    fn run_spans_collapse_adjacent_same_slot() {
1878        let primary = fid(0);
1879        let fb = chain(&[1]);
1880        let covers = |id: FontId, ch: char| {
1881            if id == primary {
1882                ch.is_ascii()
1883            } else {
1884                !ch.is_ascii()
1885            }
1886        };
1887        let text = "字字字";
1888        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1889        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1890    }
1891
1892    #[test]
1893    fn run_spans_empty_run_returns_no_spans() {
1894        let primary = fid(0);
1895        let fb = chain(&[1]);
1896        let covers = |_: FontId, _: char| true;
1897        let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers);
1898        assert!(spans.is_empty());
1899    }
1900}