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_engine::{
8    FallbackFontClass, Font, FontFallbacks, FontFeatures, FontId, FontMetrics, FontRun, GlyphId,
9    LineLayout, MissingGlyph, MissingGlyphSink, PlatformTextSystem, RenderGlyphParams,
10    SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ShapedGlyph, ShapedRun, TextRenderingMode,
11};
12use gpui_platform::{Bounds, DevicePixels, IsZero as _, Pixels, SharedString, Size, point, size};
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_engine::FontWeight, gpui_engine::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_engine::FontStyle::Normal,
112            cosmic_text::Style::Italic => gpui_engine::FontStyle::Italic,
113            cosmic_text::Style::Oblique => gpui_engine::FontStyle::Oblique,
114        };
115        Ok((gpui_engine::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
368                            .insert(fb_key.clone(), loaded.clone());
369                        loaded
370                    };
371                    let Some(&fb_id) = fb_ids.first() else {
372                        continue;
373                    };
374                    let db_id = self.loaded_fonts[fb_id.0].font.id();
375                    if let Some(face) = self.font_system.db().face(db_id)
376                        && let Some(family) = face.families.first()
377                    {
378                        chain.push((fb_id, SharedString::from(family.0.clone())));
379                    }
380                }
381                Arc::from(chain)
382            }
383            _ => Arc::from(Vec::new()),
384        };
385
386        gpui_engine::font_name_with_fallbacks(name, &self.system_font_fallback);
387
388        let families = self
389            .font_system
390            .db()
391            .faces()
392            .filter(|face| face.families.iter().any(|family| *name == family.0))
393            .map(|face| (face.id, face.post_script_name.clone()))
394            .collect::<SmallVec<[_; 4]>>();
395
396        let cosmic_features = cosmic_font_features(features)?;
397
398        let mut loaded_font_ids = SmallVec::new();
399        for (database_id, postscript_name) in families {
400            let key = LoadedFontKey {
401                database_id,
402                font: loaded_font_key.clone(),
403            };
404            if let Some(&font_id) = self.loaded_font_ids_by_key.get(&key) {
405                self.loaded_fonts[font_id.0].user_fallback_chain = Arc::clone(&user_fallback_chain);
406                loaded_font_ids.push(font_id);
407                continue;
408            }
409
410            let font = self
411                .font_system
412                .get_font(database_id, cosmic_text::Weight::NORMAL)
413                .context("Could not load font")?;
414
415            // HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback.
416            let allowed_bad_font_names = [
417                "SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent
418                "Segoe Fluent Icons",
419            ];
420
421            if font.as_swash().charmap().map('m') == 0
422                && !allowed_bad_font_names.contains(&postscript_name.as_str())
423            {
424                self.font_system.db_mut().remove_face(font.id());
425                continue;
426            };
427
428            let font_id = FontId(self.loaded_fonts.len());
429            loaded_font_ids.push(font_id);
430            self.loaded_fonts.push(LoadedFont {
431                font,
432                features: cosmic_features.clone(),
433                is_known_emoji_font: check_is_known_emoji_font(&postscript_name),
434                user_fallback_chain: Arc::clone(&user_fallback_chain),
435            });
436            self.loaded_font_ids_by_key.insert(key, font_id);
437        }
438
439        Ok(loaded_font_ids)
440    }
441
442    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
443        let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
444        Ok(Size {
445            width: glyph_metrics.advance_width(glyph_id.0 as u16),
446            height: glyph_metrics.advance_height(glyph_id.0 as u16),
447        })
448    }
449
450    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
451        let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch);
452        if glyph_id == 0 {
453            None
454        } else {
455            Some(GlyphId(glyph_id.into()))
456        }
457    }
458
459    fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
460        let image = self.render_glyph_image(params)?;
461        let bounds = Bounds {
462            origin: point(image.placement.left.into(), (-image.placement.top).into()),
463            size: size(image.placement.width.into(), image.placement.height.into()),
464        };
465        if !bounds.is_zero() {
466            self.pending_glyph_images.insert(params.clone(), image);
467        }
468        Ok(bounds)
469    }
470
471    #[profiling::function]
472    fn rasterize_glyph(
473        &mut self,
474        params: &RenderGlyphParams,
475        glyph_bounds: Bounds<DevicePixels>,
476    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
477        if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
478            anyhow::bail!("glyph bounds are empty");
479        }
480
481        let mut image = match self.pending_glyph_images.remove(params) {
482            Some(image) => image,
483            None => self.render_glyph_image(params)?,
484        };
485        let bitmap_size = glyph_bounds.size;
486        match image.content {
487            swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
488                // Convert from RGBA to BGRA.
489                for pixel in image.data.chunks_exact_mut(4) {
490                    pixel.swap(0, 2);
491                }
492                Ok((bitmap_size, image.data))
493            }
494            swash::scale::image::Content::Mask => {
495                if params.subpixel_rendering {
496                    // We must always return RGBA data when subpixel rendering is requested.
497                    let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
498                    Ok((bitmap_size, expanded))
499                } else {
500                    Ok((bitmap_size, image.data))
501                }
502            }
503        }
504    }
505
506    fn render_glyph_image(
507        &mut self,
508        params: &RenderGlyphParams,
509    ) -> Result<swash::scale::image::Image> {
510        let loaded_font = &self.loaded_fonts[params.font_id.0];
511        let font_ref = loaded_font.font.as_swash();
512        let pixel_size = f32::from(params.font_size);
513
514        let subpixel_offset = Vector::new(
515            params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor,
516            params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor,
517        );
518
519        let mut scaler = self
520            .swash_scale_context
521            .builder(font_ref)
522            .size(pixel_size * params.scale_factor)
523            .hint(true)
524            .build();
525
526        let sources: &[Source] = if params.is_emoji {
527            &[
528                Source::ColorOutline(0),
529                Source::ColorBitmap(StrikeWith::BestFit),
530                Source::Outline,
531            ]
532        } else {
533            &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline]
534        };
535
536        let mut renderer = Render::new(sources);
537        if params.subpixel_rendering {
538            // There seems to be a bug in Swash where the B and R values are swapped.
539            renderer
540                .format(Format::subpixel_bgra())
541                .offset(subpixel_offset);
542        } else {
543            renderer.format(Format::Alpha).offset(subpixel_offset);
544        }
545
546        let glyph_id: u16 = params.glyph_id.0.try_into()?;
547        renderer
548            .render(&mut scaler, glyph_id)
549            .with_context(|| format!("unable to render glyph via swash for {params:?}"))
550    }
551
552    /// This is used when cosmic_text has chosen a fallback font instead of using the requested
553    /// font, typically to handle some unicode characters. When this happens, `loaded_fonts` may not
554    /// yet have an entry for this fallback font, and so one is added.
555    ///
556    /// Note that callers shouldn't use this `FontId` somewhere that will retrieve the corresponding
557    /// `LoadedFont.features`, as it will have an arbitrarily chosen or empty value. The only
558    /// current use of this field is for the *input* of `layout_line`, and so it's fine to use
559    /// `font_id_for_cosmic_id` when computing the *output* of `layout_line`.
560    fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> {
561        if let Some(ix) = self
562            .loaded_fonts
563            .iter()
564            .position(|loaded_font| loaded_font.font.id() == id)
565        {
566            Ok(FontId(ix))
567        } else {
568            let font = self
569                .font_system
570                .get_font(id, cosmic_text::Weight::NORMAL)
571                .context("failed to get fallback font from cosmic-text font system")?;
572            let face = self
573                .font_system
574                .db()
575                .face(id)
576                .context("fallback font face not found in cosmic-text database")?;
577
578            let font_id = FontId(self.loaded_fonts.len());
579            self.loaded_fonts.push(LoadedFont {
580                font,
581                features: CosmicFontFeatures::new(),
582                is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name),
583                user_fallback_chain: Arc::from(Vec::new()),
584            });
585
586            Ok(font_id)
587        }
588    }
589
590    #[profiling::function]
591    fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
592        if contains_paragraph_separator(text) {
593            self.layout_line_with_separators(text, font_size, font_runs)
594        } else {
595            self.layout_line_no_separators(text, font_size, font_runs)
596        }
597    }
598
599    fn layout_line_with_separators(
600        &mut self,
601        text: &str,
602        font_size: Pixels,
603        font_runs: &[FontRun],
604    ) -> LineLayout {
605        let mut layout = LineLayout {
606            font_size,
607            len: text.len(),
608            ..Default::default()
609        };
610        let mut paragraph_start = 0;
611
612        for (separator_start, separator) in text
613            .char_indices()
614            .filter(|(_, character)| is_paragraph_separator(*character))
615        {
616            let separator_end = separator_start + separator.len_utf8();
617            self.shape_segment(
618                text,
619                paragraph_start..separator_start,
620                font_size,
621                font_runs,
622                &mut layout,
623            );
624            self.shape_segment(
625                text,
626                separator_start..separator_end,
627                font_size,
628                font_runs,
629                &mut layout,
630            );
631            paragraph_start = separator_end;
632        }
633
634        self.shape_segment(
635            text,
636            paragraph_start..text.len(),
637            font_size,
638            font_runs,
639            &mut layout,
640        );
641
642        layout
643    }
644
645    fn shape_segment(
646        &mut self,
647        text: &str,
648        range: Range<usize>,
649        font_size: Pixels,
650        font_runs: &[FontRun],
651        layout: &mut LineLayout,
652    ) {
653        if range.is_empty() {
654            return;
655        }
656
657        let segment_font_runs = clip_font_runs(font_runs, range.clone());
658        let segment =
659            self.layout_line_no_separators(&text[range.clone()], font_size, &segment_font_runs);
660
661        let mut segment_runs = segment.runs;
662        for run in &mut segment_runs {
663            for glyph in &mut run.glyphs {
664                glyph.index += range.start;
665                glyph.position.x += layout.width;
666            }
667        }
668
669        for mut run in segment_runs {
670            if let Some(same_run) = layout
671                .runs
672                .last_mut()
673                .filter(|last| last.font_id == run.font_id)
674            {
675                same_run.glyphs.append(&mut run.glyphs);
676            } else {
677                layout.runs.push(run);
678            }
679        }
680
681        layout.width += segment.width;
682        layout.ascent = layout.ascent.max(segment.ascent);
683        layout.descent = layout.descent.max(segment.descent);
684    }
685
686    fn layout_line_no_separators(
687        &mut self,
688        text: &str,
689        font_size: Pixels,
690        font_runs: &[FontRun],
691    ) -> LineLayout {
692        let mut attrs_list = AttrsList::new(&Attrs::new());
693        let mut offs = 0;
694        for run in font_runs {
695            let run_end = offs + run.len;
696
697            let Some(properties) = self.font_match_properties(run.font_id) else {
698                offs = run_end;
699                continue;
700            };
701
702            let primary_attrs = properties.attributes(run.font_id, &properties.primary_family_name);
703            let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = properties
704                .fallback_chain
705                .iter()
706                .map(|(font_id, family_name)| properties.attributes(*font_id, family_name))
707                .collect();
708
709            let spans = if properties.fallback_chain.is_empty() {
710                let mut spans = SmallVec::<[RunSpan; 4]>::new();
711                spans.push(RunSpan {
712                    start: offs,
713                    end: run_end,
714                    slot: None,
715                    font_id: run.font_id,
716                });
717                spans
718            } else {
719                let loaded_fonts = &self.loaded_fonts;
720                let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch);
721                compute_run_spans(
722                    text,
723                    offs,
724                    run.len,
725                    run.font_id,
726                    &properties.fallback_chain,
727                    &covers,
728                )
729            };
730
731            for span in spans {
732                let attrs = match span.slot {
733                    None => &primary_attrs,
734                    Some(ix) => &fallback_attrs[ix],
735                };
736                attrs_list.add_span(span.start..span.end, attrs);
737            }
738            offs = run_end;
739        }
740
741        let line = ShapeLine::new(
742            &mut self.font_system,
743            text,
744            &attrs_list,
745            cosmic_text::Shaping::Advanced,
746            4,
747        );
748        let mut layout_lines = Vec::with_capacity(1);
749        line.layout_to_buffer(
750            &mut self.scratch,
751            f32::from(font_size),
752            None, // We do our own wrapping
753            cosmic_text::Wrap::None,
754            Ellipsize::None,
755            None,
756            &mut layout_lines,
757            None,
758            cosmic_text::Hinting::Disabled,
759        );
760
761        let Some(layout) = layout_lines.first() else {
762            return LineLayout {
763                font_size,
764                width: Pixels::ZERO,
765                ascent: Pixels::ZERO,
766                descent: Pixels::ZERO,
767                runs: Vec::new(),
768                len: text.len(),
769            };
770        };
771
772        let missing_glyphs = self.missing_glyph_sink.as_ref().map(|_| {
773            self.missing_glyphs(
774                text,
775                font_runs,
776                layout
777                    .glyphs
778                    .iter()
779                    .filter(|glyph| glyph.glyph_id == 0)
780                    .map(|glyph| glyph.start),
781            )
782        });
783
784        let mut runs: Vec<ShapedRun> = Vec::new();
785        for glyph in &layout.glyphs {
786            let mut font_id = FontId(glyph.metadata);
787            let mut loaded_font = self.loaded_font(font_id);
788            if loaded_font.font.id() != glyph.font_id {
789                match self.font_id_for_cosmic_id(glyph.font_id) {
790                    std::result::Result::Ok(resolved_id) => {
791                        font_id = resolved_id;
792                        loaded_font = self.loaded_font(font_id);
793                    }
794                    Err(error) => {
795                        log::warn!(
796                            "failed to resolve cosmic font id {:?}: {error:#}",
797                            glyph.font_id
798                        );
799                        continue;
800                    }
801                }
802            }
803            let is_emoji = loaded_font.is_known_emoji_font;
804
805            // HACK: Prevent crash caused by variation selectors.
806            if glyph.glyph_id == 3 && is_emoji {
807                continue;
808            }
809
810            let shaped_glyph = ShapedGlyph {
811                id: GlyphId(glyph.glyph_id as u32),
812                position: point(glyph.x.into(), glyph.y.into()),
813                index: glyph.start,
814                is_emoji,
815            };
816
817            if let Some(last_run) = runs
818                .last_mut()
819                .filter(|last_run| last_run.font_id == font_id)
820            {
821                last_run.glyphs.push(shaped_glyph);
822            } else {
823                runs.push(ShapedRun {
824                    font_id,
825                    glyphs: vec![shaped_glyph],
826                });
827            }
828        }
829
830        if let Some((sink, missing_glyphs)) = self.missing_glyph_sink.as_ref().zip(missing_glyphs) {
831            sink.report(missing_glyphs);
832        }
833
834        LineLayout {
835            font_size,
836            width: layout.w.into(),
837            ascent: layout.max_ascent.into(),
838            descent: layout.max_descent.into(),
839            runs,
840            len: text.len(),
841        }
842    }
843
844    fn missing_glyphs(
845        &self,
846        text: &str,
847        font_runs: &[FontRun],
848        missing_text_indices: impl IntoIterator<Item = usize>,
849    ) -> Vec<MissingGlyph> {
850        let mut missing_text_indices = missing_text_indices.into_iter().peekable();
851        if missing_text_indices.peek().is_none() {
852            return Vec::new();
853        }
854        let mut missing_text_indices = missing_text_indices.collect::<Vec<_>>();
855        missing_text_indices.sort_unstable();
856        missing_text_indices.dedup();
857
858        let mut font_run_index = 0;
859        let mut font_run_end = font_runs.first().map_or(0, |font_run| font_run.len);
860        let mut missing_glyphs = Vec::new();
861        let mut missing_index = 0;
862        for (grapheme_start, grapheme) in text.grapheme_indices(true) {
863            let grapheme_end = grapheme_start + grapheme.len();
864            while missing_text_indices
865                .get(missing_index)
866                .is_some_and(|text_index| *text_index < grapheme_start)
867            {
868                missing_index += 1;
869            }
870            let Some(&text_index) = missing_text_indices.get(missing_index) else {
871                break;
872            };
873            if text_index >= grapheme_end {
874                continue;
875            }
876
877            while font_run_end <= text_index && font_run_index + 1 < font_runs.len() {
878                font_run_index += 1;
879                let Some(font_run) = font_runs.get(font_run_index) else {
880                    break;
881                };
882                font_run_end += font_run.len;
883            }
884            let font_class = self.fallback_font_class(
885                font_runs
886                    .get(font_run_index)
887                    .or_else(|| font_runs.last())
888                    .map(|font_run| font_run.font_id),
889            );
890            missing_glyphs.push(MissingGlyph::new(grapheme.into(), font_class));
891            while missing_text_indices
892                .get(missing_index)
893                .is_some_and(|text_index| *text_index < grapheme_end)
894            {
895                missing_index += 1;
896            }
897        }
898        missing_glyphs
899    }
900
901    fn fallback_font_class(&self, font_id: Option<FontId>) -> FallbackFontClass {
902        let Some(font_id) = font_id else {
903            return FallbackFontClass::Proportional;
904        };
905        let loaded_font = self.loaded_font(font_id);
906        let is_monospace = self
907            .font_system
908            .db()
909            .face(loaded_font.font.id())
910            .is_some_and(|face| face.monospaced);
911        if is_monospace {
912            FallbackFontClass::Monospace
913        } else {
914            FallbackFontClass::Proportional
915        }
916    }
917}
918
919#[inline(always)]
920fn is_paragraph_separator(character: char) -> bool {
921    unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B
922}
923
924fn contains_paragraph_separator(text: &str) -> bool {
925    if text
926        .bytes()
927        .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e))
928    {
929        return true;
930    }
931
932    !text.is_ascii() && text.chars().any(is_paragraph_separator)
933}
934
935fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontRun; 4]> {
936    let mut clipped = SmallVec::new();
937    let mut offs = 0;
938    for run in font_runs {
939        let run_start = offs;
940        offs += run.len;
941        if offs <= range.start {
942            continue;
943        }
944        if run_start >= range.end {
945            break;
946        }
947        let start = run_start.max(range.start);
948        let end = offs.min(range.end);
949        if start < end {
950            clipped.push(FontRun {
951                len: end - start,
952                font_id: run.font_id,
953            });
954        }
955    }
956    clipped
957}
958
959#[cfg(feature = "font-kit")]
960fn find_best_match(
961    font: &Font,
962    candidates: &[FontId],
963    state: &CosmicTextSystemState,
964) -> Result<usize> {
965    let candidate_properties = candidates
966        .iter()
967        .map(|font_id| {
968            let database_id = state.loaded_font(*font_id).font.id();
969            let face_info = state
970                .font_system
971                .db()
972                .face(database_id)
973                .context("font face not found in database")?;
974            Ok(face_info_into_properties(face_info))
975        })
976        .collect::<Result<SmallVec<[_; 4]>>>()?;
977
978    let ix =
979        font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
980            .context("requested font family contains no font matching the other parameters")?;
981
982    Ok(ix)
983}
984
985#[cfg(not(feature = "font-kit"))]
986fn find_best_match(
987    font: &Font,
988    candidates: &[FontId],
989    state: &CosmicTextSystemState,
990) -> Result<usize> {
991    if candidates.is_empty() {
992        anyhow::bail!("requested font family contains no font matching the other parameters");
993    }
994    if candidates.len() == 1 {
995        return Ok(0);
996    }
997
998    let target_weight = font.weight.0;
999    let target_italic = matches!(
1000        font.style,
1001        gpui_engine::FontStyle::Italic | gpui_engine::FontStyle::Oblique
1002    );
1003
1004    let mut best_index = 0;
1005    let mut best_score = u32::MAX;
1006
1007    for (index, font_id) in candidates.iter().enumerate() {
1008        let database_id = state.loaded_font(*font_id).font.id();
1009        let face_info = state
1010            .font_system
1011            .db()
1012            .face(database_id)
1013            .context("font face not found in database")?;
1014
1015        let is_italic = matches!(
1016            face_info.style,
1017            cosmic_text::Style::Italic | cosmic_text::Style::Oblique
1018        );
1019        let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
1020        let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
1021        let score = style_penalty + weight_diff;
1022
1023        if score < best_score {
1024            best_score = score;
1025            best_index = index;
1026        }
1027    }
1028
1029    Ok(best_index)
1030}
1031
1032/// one contiguous slice of a `FontRun` that maps to a single slot. `slot` is
1033/// `None` for the primary font and `Some(ix)` for `fallback_chain[ix]`.
1034#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1035struct RunSpan {
1036    start: usize,
1037    end: usize,
1038    slot: Option<usize>,
1039    font_id: FontId,
1040}
1041
1042/// walks `text[run_offset..run_offset + run_len]` and groups codepoints into
1043/// spans. inheriting codepoints stay in the current span so shaping clusters
1044/// like emoji zwj sequences and combining marks are not torn apart.
1045fn compute_run_spans(
1046    text: &str,
1047    run_offset: usize,
1048    run_len: usize,
1049    primary: FontId,
1050    fallback_chain: &[(FontId, SharedString)],
1051    covers: &impl Fn(FontId, char) -> bool,
1052) -> SmallVec<[RunSpan; 4]> {
1053    let mut spans = SmallVec::new();
1054    let run_end = run_offset + run_len;
1055    if run_end <= run_offset {
1056        return spans;
1057    }
1058    if fallback_chain.is_empty() {
1059        spans.push(RunSpan {
1060            start: run_offset,
1061            end: run_end,
1062            slot: None,
1063            font_id: primary,
1064        });
1065        return spans;
1066    }
1067    let run_text = &text[run_offset..run_end];
1068    let mut span_start = run_offset;
1069    let mut span_slot: Option<usize> = None;
1070    let mut span_font_id = primary;
1071    for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) {
1072        let abs = run_offset + grapheme_idx;
1073        let ch = grapheme.chars().next().unwrap_or('\0');
1074        let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);
1075        if next_slot == span_slot {
1076            continue;
1077        }
1078        if abs > span_start {
1079            spans.push(RunSpan {
1080                start: span_start,
1081                end: abs,
1082                slot: span_slot,
1083                font_id: span_font_id,
1084            });
1085        }
1086        span_start = abs;
1087        span_slot = next_slot;
1088        span_font_id = slot_font_id(next_slot, primary, fallback_chain);
1089    }
1090    if span_start < run_end {
1091        spans.push(RunSpan {
1092            start: span_start,
1093            end: run_end,
1094            slot: span_slot,
1095            font_id: span_font_id,
1096        });
1097    }
1098    spans
1099}
1100
1101fn slot_font_id(
1102    slot: Option<usize>,
1103    primary: FontId,
1104    fallback_chain: &[(FontId, SharedString)],
1105) -> FontId {
1106    match slot {
1107        None => primary,
1108        Some(ix) => fallback_chain[ix].0,
1109    }
1110}
1111
1112fn pick_covering_slot(
1113    ch: char,
1114    current: Option<usize>,
1115    primary: FontId,
1116    fallback_chain: &[(FontId, SharedString)],
1117    covers: &impl Fn(FontId, char) -> bool,
1118) -> Option<usize> {
1119    if (ch as u32) <= 0x7F {
1120        return None;
1121    }
1122    if covers(primary, ch) {
1123        return None;
1124    }
1125    let current_id = slot_font_id(current, primary, fallback_chain);
1126    if covers(current_id, ch) {
1127        return current;
1128    }
1129
1130    fallback_chain
1131        .iter()
1132        .position(|(fb_id, _)| covers(*fb_id, ch))
1133}
1134
1135fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool {
1136    loaded_fonts
1137        .get(id.0)
1138        .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0)
1139}
1140
1141fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
1142    let mut result = CosmicFontFeatures::new();
1143    for feature in features.0.iter() {
1144        let name_bytes: [u8; 4] = feature
1145            .0
1146            .as_bytes()
1147            .try_into()
1148            .context("Incorrect feature flag format")?;
1149
1150        let tag = cosmic_text::FeatureTag::new(&name_bytes);
1151
1152        result.set(tag, feature.1);
1153    }
1154    Ok(result)
1155}
1156
1157#[cfg(feature = "font-kit")]
1158fn font_into_properties(font: &gpui_engine::Font) -> font_kit::properties::Properties {
1159    font_kit::properties::Properties {
1160        style: match font.style {
1161            gpui_engine::FontStyle::Normal => font_kit::properties::Style::Normal,
1162            gpui_engine::FontStyle::Italic => font_kit::properties::Style::Italic,
1163            gpui_engine::FontStyle::Oblique => font_kit::properties::Style::Oblique,
1164        },
1165        weight: font_kit::properties::Weight(font.weight.0),
1166        stretch: Default::default(),
1167    }
1168}
1169
1170#[cfg(feature = "font-kit")]
1171fn face_info_into_properties(
1172    face_info: &cosmic_text::fontdb::FaceInfo,
1173) -> font_kit::properties::Properties {
1174    font_kit::properties::Properties {
1175        style: match face_info.style {
1176            cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
1177            cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
1178            cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
1179        },
1180        weight: font_kit::properties::Weight(face_info.weight.0.into()),
1181        stretch: match face_info.stretch {
1182            cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
1183            cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
1184            cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
1185            cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
1186            cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
1187            cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
1188            cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
1189            cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
1190            cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
1191        },
1192    }
1193}
1194
1195fn check_is_known_emoji_font(postscript_name: &str) -> bool {
1196    // TODO: Include other common emoji fonts
1197    postscript_name == "NotoColorEmoji"
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202    use super::*;
1203    #[cfg(feature = "test-support")]
1204    use std::{cell::RefCell, rc::Rc};
1205
1206    #[test]
1207    fn all_font_names_tracks_available_families() -> Result<()> {
1208        let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans");
1209        assert!(text_system.all_font_names().is_empty());
1210
1211        text_system.add_fonts(vec![Cow::Borrowed(include_bytes!(
1212            "../../../assets/fonts/lilex/Lilex-Regular.ttf"
1213        ))])?;
1214        assert_eq!(text_system.all_font_names(), ["Lilex"]);
1215
1216        text_system.add_fonts(vec![
1217            Cow::Borrowed(IBM_PLEX),
1218            Cow::Borrowed(include_bytes!("../../../assets/fonts/lilex/Lilex-Bold.ttf")),
1219        ])?;
1220        assert_eq!(text_system.all_font_names(), ["IBM Plex Sans", "Lilex"]);
1221        Ok(())
1222    }
1223
1224    fn fid(i: usize) -> FontId {
1225        FontId(i)
1226    }
1227
1228    fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> {
1229        ids.iter()
1230            .map(|&i| (fid(i), SharedString::from(format!("fb{i}"))))
1231            .collect()
1232    }
1233
1234    fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan {
1235        RunSpan {
1236            start,
1237            end,
1238            slot,
1239            font_id,
1240        }
1241    }
1242
1243    const IBM_PLEX: &[u8] =
1244        include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
1245    const LILEX: &[u8] = include_bytes!("../../../assets/fonts/lilex/Lilex-Regular.ttf");
1246
1247    /// Every code point of `Bidi_Class=B`, each of which starts a new bidi
1248    /// paragraph and so can split one line into mixed-direction paragraphs.
1249    const SEPARATORS: &[char] = &[
1250        '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}',
1251    ];
1252
1253    fn text_system() -> Result<CosmicTextSystem> {
1254        let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans");
1255        text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;
1256        Ok(text_system)
1257    }
1258
1259    #[test]
1260    fn font_properties_describe_the_selected_face() -> Result<()> {
1261        let text_system = text_system()?;
1262        let regular = gpui::font("IBM Plex Sans");
1263        let regular_id = text_system.font_id(&regular)?;
1264        for (weight, style) in [
1265            (gpui::FontWeight::MEDIUM, gpui::FontStyle::Normal),
1266            (gpui::FontWeight::BOLD, gpui::FontStyle::Italic),
1267            (gpui::FontWeight::NORMAL, gpui::FontStyle::Oblique),
1268        ] {
1269            let requested = Font {
1270                weight,
1271                style,
1272                ..regular.clone()
1273            };
1274            let font_id = text_system.font_id(&requested)?;
1275            assert_eq!(font_id, regular_id);
1276            assert_eq!(
1277                text_system.font_weight_and_style(font_id)?,
1278                (gpui::FontWeight::NORMAL, gpui::FontStyle::Normal)
1279            );
1280        }
1281        Ok(())
1282    }
1283
1284    fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result<LineLayout> {
1285        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1286        let runs = [FontRun {
1287            len: text.len(),
1288            font_id,
1289        }];
1290        Ok(text_system.layout_line(text, gpui_platform::px(14.0), &runs))
1291    }
1292
1293    /// Mirrors the original crash: mixed-direction text reaching the shaper
1294    /// through `shape_text`, which only splits lines on `\n`.
1295    #[test]
1296    fn shape_text_with_mixed_direction_paragraphs() -> Result<()> {
1297        let platform_text_system = Arc::new(text_system()?);
1298        let text_system = Arc::new(gpui::DefaultTextSystem::new(platform_text_system));
1299        let window_text_system = gpui::WindowTextSystem::new(text_system);
1300
1301        let text: SharedString = "first line\n\u{05d0}\u{001c}A".into();
1302        let runs = [gpui::TextRun {
1303            len: text.len(),
1304            font: gpui::font("IBM Plex Sans"),
1305            ..Default::default()
1306        }];
1307
1308        let lines =
1309            window_text_system.shape_text(text, gpui_platform::px(14.0), &runs, None, None)?;
1310
1311        assert_eq!(lines.len(), 2);
1312        assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len());
1313        assert!(lines[1].width() > Pixels::ZERO);
1314        Ok(())
1315    }
1316
1317    #[cfg(feature = "test-support")]
1318    #[test]
1319    fn reports_graphemes_that_exhaust_font_fallback() -> Result<()> {
1320        let platform_text_system = Arc::new(text_system()?);
1321        let dispatcher = gpui::TestDispatcher::new(0);
1322        let cx =
1323            gpui::TestAppContext::build_with_text_system(dispatcher, None, platform_text_system);
1324        let observed = Rc::new(RefCell::new(Vec::new()));
1325        let _subscription = cx.update(|cx| {
1326            let observed = observed.clone();
1327            cx.on_missing_glyphs(move |missing_glyphs, _| {
1328                observed.borrow_mut().extend_from_slice(missing_glyphs);
1329            })
1330        });
1331        let text: SharedString = "界".into();
1332
1333        cx.update(|cx| {
1334            let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
1335            let runs = [gpui::TextRun {
1336                len: text.len(),
1337                font: gpui::font("IBM Plex Sans"),
1338                ..Default::default()
1339            }];
1340            text_system.shape_line(text, gpui::px(14.0), &runs, None);
1341        });
1342        cx.run_until_parked();
1343
1344        let observed = observed.borrow();
1345        assert_eq!(observed.len(), 1);
1346        assert_eq!(observed[0].grapheme(), "界");
1347        assert_eq!(
1348            observed[0].font_class(),
1349            gpui::FallbackFontClass::Proportional
1350        );
1351        Ok(())
1352    }
1353
1354    #[test]
1355    fn combines_missing_glyphs_from_one_grapheme() -> Result<()> {
1356        let text_system = text_system()?;
1357        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1358        let text = "x\u{0301}";
1359        let runs = [FontRun {
1360            len: text.len(),
1361            font_id,
1362        }];
1363
1364        let missing_glyphs = text_system
1365            .0
1366            .read()
1367            .missing_glyphs(text, &runs, [0, "x".len()]);
1368
1369        assert_eq!(missing_glyphs.len(), 1);
1370        assert_eq!(missing_glyphs[0].grapheme(), text);
1371        Ok(())
1372    }
1373
1374    #[test]
1375    fn adding_fonts_invalidates_cached_line_layouts() -> Result<()> {
1376        let platform_text_system = Arc::new(text_system()?);
1377        let text_system = Arc::new(gpui::DefaultTextSystem::new(platform_text_system.clone()));
1378        let window_text_system = gpui::WindowTextSystem::new(text_system.clone());
1379        let text: SharedString = "cached text".into();
1380        let runs = [gpui::TextRun {
1381            len: text.len(),
1382            font: gpui::font("IBM Plex Sans"),
1383            ..Default::default()
1384        }];
1385
1386        let first_layout = window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None);
1387        let cached_layout =
1388            window_text_system.shape_line(text.clone(), gpui::px(14.0), &runs, None);
1389        assert!(std::ptr::eq::<LineLayout>(
1390            &**first_layout,
1391            &**cached_layout
1392        ));
1393        let loaded_font_count = platform_text_system.0.read().loaded_fonts.len();
1394
1395        text_system.add_fonts(vec![Cow::Borrowed(LILEX)])?;
1396
1397        let refreshed_layout = window_text_system.shape_line(text, gpui::px(14.0), &runs, None);
1398        assert!(!std::ptr::eq::<LineLayout>(
1399            &**first_layout,
1400            &**refreshed_layout
1401        ));
1402        assert_eq!(
1403            platform_text_system.0.read().loaded_fonts.len(),
1404            loaded_font_count
1405        );
1406        Ok(())
1407    }
1408
1409    #[test]
1410    fn layout_line_with_mixed_direction_paragraphs() -> Result<()> {
1411        let text_system = text_system()?;
1412
1413        for separator in SEPARATORS {
1414            for text in [
1415                format!("\u{05d0}{separator}A"),
1416                format!("A{separator}\u{05d0}"),
1417            ] {
1418                let layout = layout_text(&text_system, &text)?;
1419
1420                assert_eq!(layout.len, text.len(), "{text:?}");
1421                assert!(layout.width > Pixels::ZERO, "{text:?}");
1422                assert!(
1423                    layout.runs.iter().any(|run| !run.glyphs.is_empty()),
1424                    "{text:?}"
1425                );
1426            }
1427        }
1428
1429        Ok(())
1430    }
1431
1432    #[test]
1433    fn layout_line_with_separators_at_line_edges() -> Result<()> {
1434        let text_system = text_system()?;
1435
1436        for text in [
1437            "\u{001c}",
1438            "\u{001c}\u{001c}",
1439            "\u{001c}\u{05d0}",
1440            "\u{05d0}\u{001c}",
1441            "\u{05d0}\u{001c}\u{001c}A",
1442            "\u{001c}\u{05d0}\u{001c}A\u{001c}",
1443        ] {
1444            let layout = layout_text(&text_system, text)?;
1445            assert_eq!(layout.len, text.len(), "{text:?}");
1446        }
1447
1448        Ok(())
1449    }
1450
1451    /// Glyph indices must stay absolute and positions ordered across segment
1452    /// boundaries, otherwise cursor placement and hit testing desync. Uses
1453    /// single-direction text so visual order matches logical order.
1454    #[test]
1455    fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> {
1456        let text_system = text_system()?;
1457        let text = "ab\u{001c}cd\u{2029}ef";
1458        let layout = layout_text(&text_system, text)?;
1459
1460        let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect();
1461        assert!(!glyphs.is_empty());
1462
1463        for glyph in &glyphs {
1464            assert!(glyph.index < text.len(), "{:?}", glyph.index);
1465            assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index);
1466        }
1467        for pair in glyphs.windows(2) {
1468            assert!(pair[0].index < pair[1].index);
1469            assert!(pair[0].position.x <= pair[1].position.x);
1470        }
1471
1472        // Every segment contributes width, so the whole line is wider than its
1473        // leading paragraph alone.
1474        assert!(layout.width > layout_text(&text_system, "ab")?.width);
1475        Ok(())
1476    }
1477
1478    /// A font run boundary that does not line up with a paragraph boundary must
1479    /// still be clipped to the right segments.
1480    #[test]
1481    fn layout_line_with_font_run_straddling_a_separator() -> Result<()> {
1482        let text_system = text_system()?;
1483        let font_id = text_system.font_id(&gpui::font("IBM Plex Sans"))?;
1484        let text = "ab\u{001c}\u{05d0}\u{05d1}";
1485
1486        // The run boundary falls inside the trailing RTL paragraph.
1487        let runs = [
1488            FontRun {
1489                len: "ab\u{001c}\u{05d0}".len(),
1490                font_id,
1491            },
1492            FontRun {
1493                len: "\u{05d1}".len(),
1494                font_id,
1495            },
1496        ];
1497        let layout = text_system.layout_line(text, gpui_platform::px(14.0), &runs);
1498
1499        assert_eq!(layout.len, text.len());
1500        assert!(layout.width > Pixels::ZERO);
1501        Ok(())
1502    }
1503
1504    /// Lines with no separator take the fast path and must be shaped exactly as
1505    /// they were before paragraph splitting existed.
1506    #[test]
1507    fn layout_line_without_separators_takes_fast_path() -> Result<()> {
1508        let text_system = text_system()?;
1509
1510        for text in [
1511            "hello world",
1512            "\u{05d0}\u{05d1}\u{05d2}",
1513            "mixed \u{05d0}\u{05d1}",
1514        ] {
1515            assert!(!contains_paragraph_separator(text), "{text:?}");
1516            let layout = layout_text(&text_system, text)?;
1517            assert_eq!(layout.len, text.len(), "{text:?}");
1518            assert!(layout.width > Pixels::ZERO, "{text:?}");
1519        }
1520
1521        Ok(())
1522    }
1523
1524    /// cosmic-text sums word widths to get a line's width but accumulates glyph
1525    /// advances to position glyphs, so a trailing zero-advance glyph (here a
1526    /// zero-width space) can land a few ulps past the width. When that glyph is a
1527    /// wrap boundary, the row before it extends past the line's width, and hit
1528    /// testing in that sliver used to panic (ZED-BW8, ZED-75K, ZED-81Z).
1529    #[test]
1530    fn index_for_position_past_line_width() -> Result<()> {
1531        let text_system = Arc::new(gpui::DefaultTextSystem::new(Arc::new(text_system()?)));
1532        let window_text_system = gpui::WindowTextSystem::new(text_system);
1533        let text: SharedString = "Warning: this will delete files\u{200b}".into();
1534        let runs = [gpui::TextRun {
1535            len: text.len(),
1536            font: gpui::font("IBM Plex Sans"),
1537            ..Default::default()
1538        }];
1539        let lines =
1540            window_text_system.shape_text(text, gpui::px(14.), &runs, Some(gpui::px(4.)), None)?;
1541        let line = &lines[0];
1542        let width = line.unwrapped_layout.width;
1543        let boundary_glyph = |row: usize| {
1544            let boundary = line.wrap_boundaries()[row];
1545            &line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix]
1546        };
1547        let row = (1..line.wrap_boundaries().len())
1548            .find(|row| boundary_glyph(*row).position.x > width)
1549            .expect("trailing zero-width space should be a wrap boundary past the line width");
1550        let row_start_x = f32::from(boundary_glyph(row - 1).position.x);
1551        let row_end = boundary_glyph(row);
1552
1553        let mut x = f32::from(width) - row_start_x;
1554        while x + row_start_x < f32::from(width) {
1555            x = x.next_up();
1556        }
1557        assert!(gpui::px(x + row_start_x) < row_end.position.x);
1558
1559        let line_height = gpui::px(20.);
1560        let position = gpui::point(gpui::px(x), line_height * row as f32 + gpui::px(1.));
1561        assert_eq!(
1562            line.index_for_position(position, line_height),
1563            Err(row_end.index)
1564        );
1565        Ok(())
1566    }
1567
1568    #[test]
1569    fn paragraph_separator_detection() {
1570        for separator in SEPARATORS {
1571            assert!(is_paragraph_separator(*separator), "{separator:?}");
1572            assert!(contains_paragraph_separator(&format!("a{separator}b")));
1573        }
1574
1575        for text in [
1576            "",
1577            "plain ascii",
1578            "\u{05d0}",
1579            "tab\there",
1580            "emoji \u{1f600}",
1581        ] {
1582            assert!(!contains_paragraph_separator(text), "{text:?}");
1583        }
1584    }
1585
1586    #[test]
1587    fn font_runs_are_clipped_to_segment() {
1588        let runs = [
1589            FontRun {
1590                len: 3,
1591                font_id: fid(1),
1592            },
1593            FontRun {
1594                len: 4,
1595                font_id: fid(2),
1596            },
1597        ];
1598
1599        assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs);
1600        assert_eq!(
1601            clip_font_runs(&runs, 2..5).as_slice(),
1602            &[
1603                FontRun {
1604                    len: 1,
1605                    font_id: fid(1)
1606                },
1607                FontRun {
1608                    len: 2,
1609                    font_id: fid(2)
1610                },
1611            ]
1612        );
1613        assert_eq!(
1614            clip_font_runs(&runs, 3..7).as_slice(),
1615            &[FontRun {
1616                len: 4,
1617                font_id: fid(2)
1618            }]
1619        );
1620        assert!(clip_font_runs(&runs, 5..5).is_empty());
1621    }
1622
1623    #[test]
1624    fn primary_wins_over_current_fallback_when_primary_covers() {
1625        let primary = fid(0);
1626        let fb = chain(&[1, 2]);
1627        let covers = |id: FontId, _: char| id == fid(0) || id == fid(1);
1628        assert_eq!(
1629            pick_covering_slot('a', Some(0), primary, &fb, &covers),
1630            None
1631        );
1632    }
1633
1634    #[test]
1635    fn primary_preferred_over_fallback_when_both_cover() {
1636        let primary = fid(0);
1637        let fb = chain(&[1]);
1638        let covers = |_: FontId, _: char| true;
1639        assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1640    }
1641
1642    #[test]
1643    fn falls_through_chain_in_order() {
1644        let primary = fid(0);
1645        let fb = chain(&[1, 2, 3]);
1646        // only fallback 2 at index 1 covers.
1647        let covers = |id: FontId, _: char| id == fid(2);
1648        assert_eq!(
1649            pick_covering_slot('字', None, primary, &fb, &covers),
1650            Some(1)
1651        );
1652    }
1653
1654    #[test]
1655    fn no_coverage_returns_primary() {
1656        let primary = fid(0);
1657        let fb = chain(&[1, 2]);
1658        let covers = |_: FontId, _: char| false;
1659        // nothing covers. return `None` so the `cosmic-text` built in script
1660        // fallback can take over during shaping.
1661        assert_eq!(
1662            pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers),
1663            None
1664        );
1665    }
1666
1667    #[test]
1668    fn empty_chain_always_returns_primary() {
1669        let primary = fid(0);
1670        let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1671        let covers = |_: FontId, _: char| false;
1672        assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1673    }
1674
1675    #[test]
1676    fn slot_font_id_resolution() {
1677        let primary = fid(7);
1678        let fb = chain(&[10, 20]);
1679        assert_eq!(slot_font_id(None, primary, &fb), fid(7));
1680        assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10));
1681        assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20));
1682    }
1683
1684    #[test]
1685    fn run_spans_with_no_chain_emit_one_primary_span() {
1686        let primary = fid(0);
1687        let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1688        let covers = |_: FontId, _: char| false;
1689        let text = "hello";
1690        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1691        assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]);
1692    }
1693
1694    #[test]
1695    fn run_spans_use_byte_offsets_for_multibyte_chars() {
1696        let primary = fid(0);
1697        let fb = chain(&[1]);
1698        // primary covers ascii. fallback covers cjk.
1699        let covers = |id: FontId, ch: char| {
1700            if id == primary {
1701                ch.is_ascii()
1702            } else {
1703                !ch.is_ascii()
1704            }
1705        };
1706        let text = "a字b";
1707        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1708        // '字' is 3 bytes so split is at 1 then 4.
1709        assert_eq!(
1710            spans.as_slice(),
1711            &[
1712                span(0, 1, None, primary),
1713                span(1, 4, Some(0), fid(1)),
1714                span(4, 5, None, primary),
1715            ]
1716        );
1717    }
1718
1719    #[test]
1720    fn run_spans_respect_run_offset() {
1721        let primary = fid(0);
1722        let fb = chain(&[1]);
1723        let covers = |id: FontId, ch: char| {
1724            if id == primary {
1725                ch.is_ascii()
1726            } else {
1727                !ch.is_ascii()
1728            }
1729        };
1730        // outer text has a prefix that is not part of this run.
1731        let text = "xx字y";
1732        let run_offset = 2;
1733        let run_len = text.len() - run_offset;
1734        let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers);
1735        assert_eq!(
1736            spans.as_slice(),
1737            &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)]
1738        );
1739    }
1740
1741    #[test]
1742    fn run_spans_keep_combining_marks_with_base_in_fallback() {
1743        let primary = fid(0);
1744        let fb = chain(&[1]);
1745        // primary covers ascii only. fallback covers the base char.
1746        // combining mark must stay in the fallback span even when fallback
1747        // does not advertise coverage of it.
1748        let covers = |id: FontId, ch: char| {
1749            if id == primary {
1750                ch.is_ascii()
1751            } else {
1752                ch == '\u{0905}'
1753            }
1754        };
1755        // \u{0905} devanagari short a + \u{0902} candrabindu mark.
1756        let text = "\u{0905}\u{0902}";
1757        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1758        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1759    }
1760
1761    #[test]
1762    fn run_spans_keep_zwj_inside_emoji_cluster() {
1763        let primary = fid(0);
1764        let fb = chain(&[1]);
1765        // only fallback covers the emoji codepoints. zwj must not split.
1766        let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}';
1767        // family zwj sequence woman zwj girl.
1768        let text = "\u{1F469}\u{200D}\u{1F467}";
1769        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1770        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1771    }
1772
1773    #[test]
1774    fn run_spans_collapse_adjacent_same_slot() {
1775        let primary = fid(0);
1776        let fb = chain(&[1]);
1777        let covers = |id: FontId, ch: char| {
1778            if id == primary {
1779                ch.is_ascii()
1780            } else {
1781                !ch.is_ascii()
1782            }
1783        };
1784        let text = "字字字";
1785        let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1786        assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1787    }
1788
1789    #[test]
1790    fn run_spans_empty_run_returns_no_spans() {
1791        let primary = fid(0);
1792        let fb = chain(&[1]);
1793        let covers = |_: FontId, _: char| true;
1794        let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers);
1795        assert!(spans.is_empty());
1796    }
1797}