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