1use anyhow::{Context as _, Ok, Result};
2use cosmic_text::{
3 Attrs, AttrsList, Ellipsize, Family, Font as CosmicTextFont,
4 FontFeatures as CosmicFontFeatures, FontSystem, ShapeBuffer, ShapeLine,
5};
6use rgpui::{
7 Bounds, DevicePixels, Font, FontFallbacks, FontFeatures, FontId, FontMetrics, FontRun, GlyphId,
8 LineLayout, Pixels, PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X,
9 SUBPIXEL_VARIANTS_Y, ShapedGlyph, ShapedRun, SharedString, Size, TextRenderingMode, point,
10 size,
11};
12use std::collections::HashMap;
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
43struct CosmicTextSystemState {
44 font_system: FontSystem,
45 scratch: ShapeBuffer,
46 swash_scale_context: ScaleContext,
47 loaded_fonts: Vec<LoadedFont>,
49 font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>,
52 system_font_fallback: String,
53}
54
55struct LoadedFont {
56 font: Arc<CosmicTextFont>,
57 features: CosmicFontFeatures,
58 is_known_emoji_font: bool,
59 user_fallback_chain: Arc<[(FontId, SharedString)]>,
62}
63
64impl CosmicTextSystem {
65 pub fn new(system_font_fallback: &str) -> Self {
66 let font_system = FontSystem::new();
67
68 Self(RwLock::new(CosmicTextSystemState {
69 font_system,
70 scratch: ShapeBuffer::default(),
71 swash_scale_context: ScaleContext::new(),
72 loaded_fonts: Vec::new(),
73 font_ids_by_family_cache: HashMap::default(),
74 system_font_fallback: system_font_fallback.to_string(),
75 }))
76 }
77
78 pub fn new_without_system_fonts(system_font_fallback: &str) -> Self {
79 let font_system = FontSystem::new_with_locale_and_db(
80 "en-US".to_string(),
81 cosmic_text::fontdb::Database::new(),
82 );
83
84 Self(RwLock::new(CosmicTextSystemState {
85 font_system,
86 scratch: ShapeBuffer::default(),
87 swash_scale_context: ScaleContext::new(),
88 loaded_fonts: Vec::new(),
89 font_ids_by_family_cache: HashMap::default(),
90 system_font_fallback: system_font_fallback.to_string(),
91 }))
92 }
93}
94
95impl PlatformTextSystem for CosmicTextSystem {
96 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
97 self.0.write().add_fonts(fonts)
98 }
99
100 fn all_font_names(&self) -> Vec<String> {
101 let mut result = self
102 .0
103 .read()
104 .font_system
105 .db()
106 .faces()
107 .filter_map(|face| face.families.first().map(|family| family.0.clone()))
108 .collect_vec();
109 result.sort_unstable();
110 result.dedup();
111 result
112 }
113
114 fn font_id(&self, font: &Font) -> Result<FontId> {
115 let mut state = self.0.write();
116 let key = FontKey::new(
117 font.family.clone(),
118 font.features.clone(),
119 font.fallbacks.clone(),
120 );
121 let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&key) {
122 font_ids.as_slice()
123 } else {
124 let font_ids =
125 state.load_family(&font.family, &font.features, font.fallbacks.as_ref())?;
126 state.font_ids_by_family_cache.insert(key.clone(), font_ids);
127 state.font_ids_by_family_cache[&key].as_ref()
128 };
129
130 let ix = find_best_match(font, candidates, &state)?;
131
132 Ok(candidates[ix])
133 }
134
135 fn font_metrics(&self, font_id: FontId) -> FontMetrics {
136 let metrics = self
137 .0
138 .read()
139 .loaded_font(font_id)
140 .font
141 .as_swash()
142 .metrics(&[]);
143
144 FontMetrics {
145 units_per_em: metrics.units_per_em as u32,
146 ascent: metrics.ascent,
147 descent: -metrics.descent,
148 line_gap: metrics.leading,
149 underline_position: metrics.underline_offset,
150 underline_thickness: metrics.stroke_size,
151 cap_height: metrics.cap_height,
152 x_height: metrics.x_height,
153 bounding_box: Bounds {
154 origin: point(0.0, 0.0),
155 size: size(metrics.max_width, metrics.ascent + metrics.descent),
156 },
157 }
158 }
159
160 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
161 let lock = self.0.read();
162 let glyph_metrics = lock.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
163 let glyph_id = glyph_id.0 as u16;
164 Ok(Bounds {
165 origin: point(0.0, 0.0),
166 size: size(
167 glyph_metrics.advance_width(glyph_id),
168 glyph_metrics.advance_height(glyph_id),
169 ),
170 })
171 }
172
173 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
174 self.0.read().advance(font_id, glyph_id)
175 }
176
177 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
178 self.0.read().glyph_for_char(font_id, ch)
179 }
180
181 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
182 self.0.write().raster_bounds(params)
183 }
184
185 fn rasterize_glyph(
186 &self,
187 params: &RenderGlyphParams,
188 raster_bounds: Bounds<DevicePixels>,
189 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
190 self.0.write().rasterize_glyph(params, raster_bounds)
191 }
192
193 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
194 self.0.write().layout_line(text, font_size, runs)
195 }
196
197 fn recommended_rendering_mode(
198 &self,
199 _font_id: FontId,
200 _font_size: Pixels,
201 ) -> TextRenderingMode {
202 TextRenderingMode::Subpixel
203 }
204}
205
206impl CosmicTextSystemState {
207 fn loaded_font(&self, font_id: FontId) -> &LoadedFont {
208 &self.loaded_fonts[font_id.0]
209 }
210
211 #[profiling::function]
212 fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
213 let db = self.font_system.db_mut();
214 for bytes in fonts {
215 db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(bytes)));
217 }
218 Ok(())
219 }
220
221 #[profiling::function]
222 fn load_family(
223 &mut self,
224 name: &str,
225 features: &FontFeatures,
226 fallbacks: Option<&FontFallbacks>,
227 ) -> Result<SmallVec<[FontId; 4]>> {
228 let user_fallback_chain: Arc<[(FontId, SharedString)]> = match fallbacks {
232 Some(fallbacks) if !fallbacks.fallback_list().is_empty() => {
233 let mut chain: Vec<(FontId, SharedString)> = Vec::new();
234 for fallback_name in fallbacks.fallback_list() {
235 let fb_key = FontKey::new(
236 SharedString::from(fallback_name.clone()),
237 features.clone(),
238 None,
239 );
240 let fb_ids = if let Some(cached) = self.font_ids_by_family_cache.get(&fb_key) {
241 cached.clone()
242 } else {
243 let loaded = self.load_family(fallback_name, features, None)?;
244 self.font_ids_by_family_cache
245 .insert(fb_key.clone(), loaded.clone());
246 loaded
247 };
248 let Some(&fb_id) = fb_ids.first() else {
249 continue;
250 };
251 let db_id = self.loaded_fonts[fb_id.0].font.id();
252 if let Some(face) = self.font_system.db().face(db_id)
253 && let Some(family) = face.families.first()
254 {
255 chain.push((fb_id, SharedString::from(family.0.clone())));
256 }
257 }
258 Arc::from(chain)
259 }
260 _ => Arc::from(Vec::new()),
261 };
262
263 let name = rgpui::font_name_with_fallbacks(name, &self.system_font_fallback);
264
265 let families = self
266 .font_system
267 .db()
268 .faces()
269 .filter(|face| face.families.iter().any(|family| *name == family.0))
270 .map(|face| (face.id, face.post_script_name.clone()))
271 .collect::<SmallVec<[_; 4]>>();
272
273 let cosmic_features = cosmic_font_features(features)?;
274
275 let mut loaded_font_ids = SmallVec::new();
276 for (font_id, postscript_name) in families {
277 let font = self
278 .font_system
279 .get_font(font_id, cosmic_text::Weight::NORMAL)
280 .context("Could not load font")?;
281
282 let allowed_bad_font_names = [
284 "SegoeFluentIcons", "Segoe Fluent Icons",
286 ];
287
288 if font.as_swash().charmap().map('m') == 0
289 && !allowed_bad_font_names.contains(&postscript_name.as_str())
290 {
291 self.font_system.db_mut().remove_face(font.id());
292 continue;
293 };
294
295 let font_id = FontId(self.loaded_fonts.len());
296 loaded_font_ids.push(font_id);
297 self.loaded_fonts.push(LoadedFont {
298 font,
299 features: cosmic_features.clone(),
300 is_known_emoji_font: check_is_known_emoji_font(&postscript_name),
301 user_fallback_chain: Arc::clone(&user_fallback_chain),
302 });
303 }
304
305 Ok(loaded_font_ids)
306 }
307
308 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
309 let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
310 Ok(Size {
311 width: glyph_metrics.advance_width(glyph_id.0 as u16),
312 height: glyph_metrics.advance_height(glyph_id.0 as u16),
313 })
314 }
315
316 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
317 let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch);
318 if glyph_id == 0 {
319 None
320 } else {
321 Some(GlyphId(glyph_id.into()))
322 }
323 }
324
325 fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
326 let image = self.render_glyph_image(params)?;
327 Ok(Bounds {
328 origin: point(image.placement.left.into(), (-image.placement.top).into()),
329 size: size(image.placement.width.into(), image.placement.height.into()),
330 })
331 }
332
333 #[profiling::function]
334 fn rasterize_glyph(
335 &mut self,
336 params: &RenderGlyphParams,
337 glyph_bounds: Bounds<DevicePixels>,
338 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
339 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
340 anyhow::bail!("glyph bounds are empty");
341 }
342
343 let mut image = self.render_glyph_image(params)?;
344 let bitmap_size = glyph_bounds.size;
345 match image.content {
346 swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
347 for pixel in image.data.chunks_exact_mut(4) {
349 pixel.swap(0, 2);
350 }
351 Ok((bitmap_size, image.data))
352 }
353 swash::scale::image::Content::Mask => {
354 if params.subpixel_rendering {
355 let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
357 Ok((bitmap_size, expanded))
358 } else {
359 Ok((bitmap_size, image.data))
360 }
361 }
362 }
363 }
364
365 fn render_glyph_image(
366 &mut self,
367 params: &RenderGlyphParams,
368 ) -> Result<swash::scale::image::Image> {
369 let loaded_font = &self.loaded_fonts[params.font_id.0];
370 let font_ref = loaded_font.font.as_swash();
371 let pixel_size = f32::from(params.font_size);
372
373 let subpixel_offset = Vector::new(
374 params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor,
375 params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor,
376 );
377
378 let mut scaler = self
379 .swash_scale_context
380 .builder(font_ref)
381 .size(pixel_size * params.scale_factor)
382 .hint(true)
383 .build();
384
385 let sources: &[Source] = if params.is_emoji {
386 &[
387 Source::ColorOutline(0),
388 Source::ColorBitmap(StrikeWith::BestFit),
389 Source::Outline,
390 ]
391 } else {
392 &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline]
393 };
394
395 let mut renderer = Render::new(sources);
396 if params.subpixel_rendering {
397 renderer
399 .format(Format::subpixel_bgra())
400 .offset(subpixel_offset);
401 } else {
402 renderer.format(Format::Alpha).offset(subpixel_offset);
403 }
404
405 let glyph_id: u16 = params.glyph_id.0.try_into()?;
406 renderer
407 .render(&mut scaler, glyph_id)
408 .with_context(|| format!("unable to render glyph via swash for {params:?}"))
409 }
410
411 fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> {
420 if let Some(ix) = self
421 .loaded_fonts
422 .iter()
423 .position(|loaded_font| loaded_font.font.id() == id)
424 {
425 Ok(FontId(ix))
426 } else {
427 let font = self
428 .font_system
429 .get_font(id, cosmic_text::Weight::NORMAL)
430 .context("failed to get fallback font from cosmic-text font system")?;
431 let face = self
432 .font_system
433 .db()
434 .face(id)
435 .context("fallback font face not found in cosmic-text database")?;
436
437 let font_id = FontId(self.loaded_fonts.len());
438 self.loaded_fonts.push(LoadedFont {
439 font,
440 features: CosmicFontFeatures::new(),
441 is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name),
442 user_fallback_chain: Arc::from(Vec::new()),
443 });
444
445 Ok(font_id)
446 }
447 }
448
449 #[profiling::function]
450 fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
451 if contains_paragraph_separator(text) {
452 self.layout_line_with_separators(text, font_size, font_runs)
453 } else {
454 self.layout_line_no_separators(text, font_size, font_runs)
455 }
456 }
457
458 fn layout_line_with_separators(
459 &mut self,
460 text: &str,
461 font_size: Pixels,
462 font_runs: &[FontRun],
463 ) -> LineLayout {
464 let mut layout = LineLayout {
465 font_size,
466 len: text.len(),
467 ..Default::default()
468 };
469 let mut paragraph_start = 0;
470
471 for (separator_start, separator) in text
472 .char_indices()
473 .filter(|(_, character)| is_paragraph_separator(*character))
474 {
475 let separator_end = separator_start + separator.len_utf8();
476 self.shape_segment(
477 text,
478 paragraph_start..separator_start,
479 font_size,
480 font_runs,
481 &mut layout,
482 );
483 self.shape_segment(
484 text,
485 separator_start..separator_end,
486 font_size,
487 font_runs,
488 &mut layout,
489 );
490 paragraph_start = separator_end;
491 }
492
493 self.shape_segment(
494 text,
495 paragraph_start..text.len(),
496 font_size,
497 font_runs,
498 &mut layout,
499 );
500
501 layout
502 }
503
504 fn shape_segment(
505 &mut self,
506 text: &str,
507 range: Range<usize>,
508 font_size: Pixels,
509 font_runs: &[FontRun],
510 layout: &mut LineLayout,
511 ) {
512 if range.is_empty() {
513 return;
514 }
515
516 let segment_font_runs = clip_font_runs(font_runs, range.clone());
517 let start = text.floor_char_boundary(range.start.min(text.len()));
520 let end = text
521 .floor_char_boundary(range.end.min(text.len()))
522 .max(start);
523 let segment =
524 self.layout_line_no_separators(&text[start..end], font_size, &segment_font_runs);
525
526 let mut segment_runs = segment.runs;
527 for run in &mut segment_runs {
528 for glyph in &mut run.glyphs {
529 glyph.index += start;
530 glyph.position.x += layout.width;
531 }
532 }
533
534 for mut run in segment_runs {
535 if let Some(same_run) = layout
536 .runs
537 .last_mut()
538 .filter(|last| last.font_id == run.font_id)
539 {
540 same_run.glyphs.append(&mut run.glyphs);
541 } else {
542 layout.runs.push(run);
543 }
544 }
545
546 layout.width += segment.width;
547 layout.ascent = layout.ascent.max(segment.ascent);
548 layout.descent = layout.descent.max(segment.descent);
549 }
550
551 fn layout_line_no_separators(
552 &mut self,
553 text: &str,
554 font_size: Pixels,
555 font_runs: &[FontRun],
556 ) -> LineLayout {
557 let mut attrs_list = AttrsList::new(&Attrs::new());
558 let mut offs = 0;
559 for run in font_runs {
560 let run_end = offs + run.len;
561
562 let loaded_font = self.loaded_font(run.font_id);
563 let Some(face) = self.font_system.db().face(loaded_font.font.id()) else {
564 log::warn!(
565 "font face not found in database for font_id {:?}",
566 run.font_id
567 );
568 offs = run_end;
569 continue;
570 };
571 let Some(first_family) = face.families.first() else {
572 log::warn!(
573 "font face has no family names for font_id {:?}",
574 run.font_id
575 );
576 offs = run_end;
577 continue;
578 };
579
580 let primary_family_name: SharedString = first_family.0.clone().into();
581 let primary_stretch = face.stretch;
582 let primary_style = face.style;
583 let primary_weight = face.weight;
584 let primary_features = loaded_font.features.clone();
585 let fallback_chain = Arc::clone(&loaded_font.user_fallback_chain);
586
587 let primary_attrs = Attrs::new()
590 .metadata(run.font_id.0)
591 .family(Family::Name(&primary_family_name))
592 .stretch(primary_stretch)
593 .style(primary_style)
594 .weight(primary_weight)
595 .font_features(primary_features.clone());
596 let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = fallback_chain
597 .iter()
598 .map(|(fb_id, fb_name)| {
599 Attrs::new()
600 .metadata(fb_id.0)
601 .family(Family::Name(fb_name))
602 .stretch(primary_stretch)
603 .style(primary_style)
604 .weight(primary_weight)
605 .font_features(primary_features.clone())
606 })
607 .collect();
608
609 let spans = if fallback_chain.is_empty() {
610 let mut spans = SmallVec::<[RunSpan; 4]>::new();
611 spans.push(RunSpan {
612 start: offs,
613 end: run_end,
614 slot: None,
615 font_id: run.font_id,
616 });
617 spans
618 } else {
619 let loaded_fonts = &self.loaded_fonts;
620 let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch);
621 compute_run_spans(text, offs, run.len, run.font_id, &fallback_chain, &covers)
622 };
623
624 for span in spans {
625 let attrs = match span.slot {
626 None => &primary_attrs,
627 Some(ix) => &fallback_attrs[ix],
628 };
629 attrs_list.add_span(span.start..span.end, attrs);
630 }
631 offs = run_end;
632 }
633
634 let line = ShapeLine::new(
635 &mut self.font_system,
636 text,
637 &attrs_list,
638 cosmic_text::Shaping::Advanced,
639 4,
640 );
641 let mut layout_lines = Vec::with_capacity(1);
642 line.layout_to_buffer(
643 &mut self.scratch,
644 f32::from(font_size),
645 None, cosmic_text::Wrap::None,
647 Ellipsize::None,
648 None,
649 &mut layout_lines,
650 None,
651 cosmic_text::Hinting::Disabled,
652 );
653
654 let Some(layout) = layout_lines.first() else {
655 return LineLayout {
656 font_size,
657 width: Pixels::ZERO,
658 ascent: Pixels::ZERO,
659 descent: Pixels::ZERO,
660 runs: Vec::new(),
661 len: text.len(),
662 };
663 };
664
665 let mut runs: Vec<ShapedRun> = Vec::new();
666 for glyph in &layout.glyphs {
667 let mut font_id = FontId(glyph.metadata);
668 let mut loaded_font = self.loaded_font(font_id);
669 if loaded_font.font.id() != glyph.font_id {
670 match self.font_id_for_cosmic_id(glyph.font_id) {
671 std::result::Result::Ok(resolved_id) => {
672 font_id = resolved_id;
673 loaded_font = self.loaded_font(font_id);
674 }
675 Err(error) => {
676 log::warn!(
677 "failed to resolve cosmic font id {:?}: {error:#}",
678 glyph.font_id
679 );
680 continue;
681 }
682 }
683 }
684 let is_emoji = loaded_font.is_known_emoji_font;
685
686 if glyph.glyph_id == 3 && is_emoji {
688 continue;
689 }
690
691 let shaped_glyph = ShapedGlyph {
692 id: GlyphId(glyph.glyph_id as u32),
693 position: point(glyph.x.into(), glyph.y.into()),
694 index: glyph.start,
695 is_emoji,
696 };
697
698 if let Some(last_run) = runs
699 .last_mut()
700 .filter(|last_run| last_run.font_id == font_id)
701 {
702 last_run.glyphs.push(shaped_glyph);
703 } else {
704 runs.push(ShapedRun {
705 font_id,
706 glyphs: vec![shaped_glyph],
707 });
708 }
709 }
710
711 LineLayout {
712 font_size,
713 width: layout.w.into(),
714 ascent: layout.max_ascent.into(),
715 descent: layout.max_descent.into(),
716 runs,
717 len: text.len(),
718 }
719 }
720}
721
722#[inline(always)]
723fn is_paragraph_separator(character: char) -> bool {
724 unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B
725}
726
727fn contains_paragraph_separator(text: &str) -> bool {
728 if text
729 .bytes()
730 .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e))
731 {
732 return true;
733 }
734
735 !text.is_ascii() && text.chars().any(is_paragraph_separator)
736}
737
738fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontRun; 4]> {
739 let mut clipped = SmallVec::new();
740 let mut offs = 0;
741 for run in font_runs {
742 let run_start = offs;
743 offs += run.len;
744 if offs <= range.start {
745 continue;
746 }
747 if run_start >= range.end {
748 break;
749 }
750 let start = run_start.max(range.start);
751 let end = offs.min(range.end);
752 if start < end {
753 clipped.push(FontRun {
754 len: end - start,
755 font_id: run.font_id,
756 });
757 }
758 }
759 clipped
760}
761
762#[cfg(feature = "font-kit")]
763fn find_best_match(
764 font: &Font,
765 candidates: &[FontId],
766 state: &CosmicTextSystemState,
767) -> Result<usize> {
768 let candidate_properties = candidates
769 .iter()
770 .map(|font_id| {
771 let database_id = state.loaded_font(*font_id).font.id();
772 let face_info = state
773 .font_system
774 .db()
775 .face(database_id)
776 .context("font face not found in database")?;
777 Ok(face_info_into_properties(face_info))
778 })
779 .collect::<Result<SmallVec<[_; 4]>>>()?;
780
781 let ix =
782 font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
783 .context("requested font family contains no font matching the other parameters")?;
784
785 Ok(ix)
786}
787
788#[cfg(not(feature = "font-kit"))]
789fn find_best_match(
790 font: &Font,
791 candidates: &[FontId],
792 state: &CosmicTextSystemState,
793) -> Result<usize> {
794 if candidates.is_empty() {
795 anyhow::bail!("requested font family contains no font matching the other parameters");
796 }
797 if candidates.len() == 1 {
798 return Ok(0);
799 }
800
801 let target_weight = font.weight.0;
802 let target_italic = matches!(
803 font.style,
804 rgpui::FontStyle::Italic | rgpui::FontStyle::Oblique
805 );
806
807 let mut best_index = 0;
808 let mut best_score = u32::MAX;
809
810 for (index, font_id) in candidates.iter().enumerate() {
811 let database_id = state.loaded_font(*font_id).font.id();
812 let face_info = state
813 .font_system
814 .db()
815 .face(database_id)
816 .context("font face not found in database")?;
817
818 let is_italic = matches!(
819 face_info.style,
820 cosmic_text::Style::Italic | cosmic_text::Style::Oblique
821 );
822 let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
823 let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
824 let score = style_penalty + weight_diff;
825
826 if score < best_score {
827 best_score = score;
828 best_index = index;
829 }
830 }
831
832 Ok(best_index)
833}
834
835#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838struct RunSpan {
839 start: usize,
840 end: usize,
841 slot: Option<usize>,
842 font_id: FontId,
843}
844
845fn compute_run_spans(
849 text: &str,
850 run_offset: usize,
851 run_len: usize,
852 primary: FontId,
853 fallback_chain: &[(FontId, SharedString)],
854 covers: &impl Fn(FontId, char) -> bool,
855) -> SmallVec<[RunSpan; 4]> {
856 let mut spans = SmallVec::new();
857 let run_end = run_offset + run_len;
858 if run_end <= run_offset {
859 return spans;
860 }
861 let run_offset = text.floor_char_boundary(run_offset.min(text.len()));
864 let run_end = text
865 .floor_char_boundary(run_end.min(text.len()))
866 .max(run_offset);
867 if run_end <= run_offset {
868 return spans;
869 }
870 if fallback_chain.is_empty() {
871 spans.push(RunSpan {
872 start: run_offset,
873 end: run_end,
874 slot: None,
875 font_id: primary,
876 });
877 return spans;
878 }
879 let run_text = &text[run_offset..run_end];
880 let mut span_start = run_offset;
881 let mut span_slot: Option<usize> = None;
882 let mut span_font_id = primary;
883 for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) {
884 let abs = run_offset + grapheme_idx;
885 let ch = grapheme.chars().next().unwrap_or('\0');
886 let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);
887 if next_slot == span_slot {
888 continue;
889 }
890 if abs > span_start {
891 spans.push(RunSpan {
892 start: span_start,
893 end: abs,
894 slot: span_slot,
895 font_id: span_font_id,
896 });
897 }
898 span_start = abs;
899 span_slot = next_slot;
900 span_font_id = slot_font_id(next_slot, primary, fallback_chain);
901 }
902 if span_start < run_end {
903 spans.push(RunSpan {
904 start: span_start,
905 end: run_end,
906 slot: span_slot,
907 font_id: span_font_id,
908 });
909 }
910 spans
911}
912
913fn slot_font_id(
914 slot: Option<usize>,
915 primary: FontId,
916 fallback_chain: &[(FontId, SharedString)],
917) -> FontId {
918 match slot {
919 None => primary,
920 Some(ix) => fallback_chain[ix].0,
921 }
922}
923
924fn pick_covering_slot(
925 ch: char,
926 current: Option<usize>,
927 primary: FontId,
928 fallback_chain: &[(FontId, SharedString)],
929 covers: &impl Fn(FontId, char) -> bool,
930) -> Option<usize> {
931 if (ch as u32) <= 0x7F {
932 return None;
933 }
934 if covers(primary, ch) {
935 return None;
936 }
937 let current_id = slot_font_id(current, primary, fallback_chain);
938 if covers(current_id, ch) {
939 return current;
940 }
941
942 fallback_chain
943 .iter()
944 .position(|(fb_id, _)| covers(*fb_id, ch))
945}
946
947fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool {
948 loaded_fonts
949 .get(id.0)
950 .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0)
951}
952
953fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
954 let mut result = CosmicFontFeatures::new();
955 for feature in features.0.iter() {
956 let name_bytes: [u8; 4] = feature
957 .0
958 .as_bytes()
959 .try_into()
960 .context("Incorrect feature flag format")?;
961
962 let tag = cosmic_text::FeatureTag::new(&name_bytes);
963
964 result.set(tag, feature.1);
965 }
966 Ok(result)
967}
968
969#[cfg(feature = "font-kit")]
970fn font_into_properties(font: &rgpui::Font) -> font_kit::properties::Properties {
971 font_kit::properties::Properties {
972 style: match font.style {
973 rgpui::FontStyle::Normal => font_kit::properties::Style::Normal,
974 rgpui::FontStyle::Italic => font_kit::properties::Style::Italic,
975 rgpui::FontStyle::Oblique => font_kit::properties::Style::Oblique,
976 },
977 weight: font_kit::properties::Weight(font.weight.0),
978 stretch: Default::default(),
979 }
980}
981
982#[cfg(feature = "font-kit")]
983fn face_info_into_properties(
984 face_info: &cosmic_text::fontdb::FaceInfo,
985) -> font_kit::properties::Properties {
986 font_kit::properties::Properties {
987 style: match face_info.style {
988 cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
989 cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
990 cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
991 },
992 weight: font_kit::properties::Weight(face_info.weight.0.into()),
993 stretch: match face_info.stretch {
994 cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
995 cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
996 cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
997 cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
998 cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
999 cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
1000 cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
1001 cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
1002 cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
1003 },
1004 }
1005}
1006
1007fn check_is_known_emoji_font(postscript_name: &str) -> bool {
1008 postscript_name == "NotoColorEmoji"
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014 use super::*;
1015
1016 fn fid(i: usize) -> FontId {
1017 FontId(i)
1018 }
1019
1020 fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> {
1021 ids.iter()
1022 .map(|&i| (fid(i), SharedString::from(format!("fb{i}"))))
1023 .collect()
1024 }
1025
1026 fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan {
1027 RunSpan {
1028 start,
1029 end,
1030 slot,
1031 font_id,
1032 }
1033 }
1034
1035 const IBM_PLEX: &[u8] =
1036 include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
1037
1038 const SEPARATORS: &[char] = &[
1041 '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}',
1042 ];
1043
1044 fn text_system() -> Result<CosmicTextSystem> {
1045 let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans");
1046 text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;
1047 Ok(text_system)
1048 }
1049
1050 fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result<LineLayout> {
1051 let font_id = text_system.font_id(&rgpui::font("IBM Plex Sans"))?;
1052 let runs = [FontRun {
1053 len: text.len(),
1054 font_id,
1055 }];
1056 Ok(text_system.layout_line(text, rgpui::px(14.0), &runs))
1057 }
1058
1059 #[test]
1062 fn shape_text_with_mixed_direction_paragraphs() -> Result<()> {
1063 let platform_text_system = Arc::new(text_system()?);
1064 let text_system = Arc::new(rgpui::TextSystem::new(platform_text_system));
1065 let window_text_system = rgpui::WindowTextSystem::new(text_system);
1066
1067 let text: SharedString = "first line\n\u{05d0}\u{001c}A".into();
1068 let runs = [rgpui::TextRun {
1069 len: text.len(),
1070 font: rgpui::font("IBM Plex Sans"),
1071 ..Default::default()
1072 }];
1073
1074 let lines = window_text_system.shape_text(text, rgpui::px(14.0), &runs, None, None)?;
1075
1076 assert_eq!(lines.len(), 2);
1077 assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len());
1078 assert!(lines[1].width() > Pixels::ZERO);
1079 Ok(())
1080 }
1081
1082 #[test]
1083 fn layout_line_with_mixed_direction_paragraphs() -> Result<()> {
1084 let text_system = text_system()?;
1085
1086 for separator in SEPARATORS {
1087 for text in [
1088 format!("\u{05d0}{separator}A"),
1089 format!("A{separator}\u{05d0}"),
1090 ] {
1091 let layout = layout_text(&text_system, &text)?;
1092
1093 assert_eq!(layout.len, text.len(), "{text:?}");
1094 assert!(layout.width > Pixels::ZERO, "{text:?}");
1095 assert!(
1096 layout.runs.iter().any(|run| !run.glyphs.is_empty()),
1097 "{text:?}"
1098 );
1099 }
1100 }
1101
1102 Ok(())
1103 }
1104
1105 #[test]
1106 fn layout_line_with_separators_at_line_edges() -> Result<()> {
1107 let text_system = text_system()?;
1108
1109 for text in [
1110 "\u{001c}",
1111 "\u{001c}\u{001c}",
1112 "\u{001c}\u{05d0}",
1113 "\u{05d0}\u{001c}",
1114 "\u{05d0}\u{001c}\u{001c}A",
1115 "\u{001c}\u{05d0}\u{001c}A\u{001c}",
1116 ] {
1117 let layout = layout_text(&text_system, text)?;
1118 assert_eq!(layout.len, text.len(), "{text:?}");
1119 }
1120
1121 Ok(())
1122 }
1123
1124 #[test]
1128 fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> {
1129 let text_system = text_system()?;
1130 let text = "ab\u{001c}cd\u{2029}ef";
1131 let layout = layout_text(&text_system, text)?;
1132
1133 let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect();
1134 assert!(!glyphs.is_empty());
1135
1136 for glyph in &glyphs {
1137 assert!(glyph.index < text.len(), "{:?}", glyph.index);
1138 assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index);
1139 }
1140 for pair in glyphs.windows(2) {
1141 assert!(pair[0].index < pair[1].index);
1142 assert!(pair[0].position.x <= pair[1].position.x);
1143 }
1144
1145 assert!(layout.width > layout_text(&text_system, "ab")?.width);
1148 Ok(())
1149 }
1150
1151 #[test]
1154 fn layout_line_with_font_run_straddling_a_separator() -> Result<()> {
1155 let text_system = text_system()?;
1156 let font_id = text_system.font_id(&rgpui::font("IBM Plex Sans"))?;
1157 let text = "ab\u{001c}\u{05d0}\u{05d1}";
1158
1159 let runs = [
1161 FontRun {
1162 len: "ab\u{001c}\u{05d0}".len(),
1163 font_id,
1164 },
1165 FontRun {
1166 len: "\u{05d1}".len(),
1167 font_id,
1168 },
1169 ];
1170 let layout = text_system.layout_line(text, rgpui::px(14.0), &runs);
1171
1172 assert_eq!(layout.len, text.len());
1173 assert!(layout.width > Pixels::ZERO);
1174 Ok(())
1175 }
1176
1177 #[test]
1180 fn layout_line_without_separators_takes_fast_path() -> Result<()> {
1181 let text_system = text_system()?;
1182
1183 for text in [
1184 "hello world",
1185 "\u{05d0}\u{05d1}\u{05d2}",
1186 "mixed \u{05d0}\u{05d1}",
1187 ] {
1188 assert!(!contains_paragraph_separator(text), "{text:?}");
1189 let layout = layout_text(&text_system, text)?;
1190 assert_eq!(layout.len, text.len(), "{text:?}");
1191 assert!(layout.width > Pixels::ZERO, "{text:?}");
1192 }
1193
1194 Ok(())
1195 }
1196
1197 #[test]
1198 fn paragraph_separator_detection() {
1199 for separator in SEPARATORS {
1200 assert!(is_paragraph_separator(*separator), "{separator:?}");
1201 assert!(contains_paragraph_separator(&format!("a{separator}b")));
1202 }
1203
1204 for text in [
1205 "",
1206 "plain ascii",
1207 "\u{05d0}",
1208 "tab\there",
1209 "emoji \u{1f600}",
1210 ] {
1211 assert!(!contains_paragraph_separator(text), "{text:?}");
1212 }
1213 }
1214
1215 #[test]
1216 fn font_runs_are_clipped_to_segment() {
1217 let runs = [
1218 FontRun {
1219 len: 3,
1220 font_id: fid(1),
1221 },
1222 FontRun {
1223 len: 4,
1224 font_id: fid(2),
1225 },
1226 ];
1227
1228 assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs);
1229 assert_eq!(
1230 clip_font_runs(&runs, 2..5).as_slice(),
1231 &[
1232 FontRun {
1233 len: 1,
1234 font_id: fid(1)
1235 },
1236 FontRun {
1237 len: 2,
1238 font_id: fid(2)
1239 },
1240 ]
1241 );
1242 assert_eq!(
1243 clip_font_runs(&runs, 3..7).as_slice(),
1244 &[FontRun {
1245 len: 4,
1246 font_id: fid(2)
1247 }]
1248 );
1249 assert!(clip_font_runs(&runs, 5..5).is_empty());
1250 }
1251
1252 #[test]
1253 fn primary_wins_over_current_fallback_when_primary_covers() {
1254 let primary = fid(0);
1255 let fb = chain(&[1, 2]);
1256 let covers = |id: FontId, _: char| id == fid(0) || id == fid(1);
1257 assert_eq!(
1258 pick_covering_slot('a', Some(0), primary, &fb, &covers),
1259 None
1260 );
1261 }
1262
1263 #[test]
1264 fn primary_preferred_over_fallback_when_both_cover() {
1265 let primary = fid(0);
1266 let fb = chain(&[1]);
1267 let covers = |_: FontId, _: char| true;
1268 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1269 }
1270
1271 #[test]
1272 fn falls_through_chain_in_order() {
1273 let primary = fid(0);
1274 let fb = chain(&[1, 2, 3]);
1275 let covers = |id: FontId, _: char| id == fid(2);
1277 assert_eq!(
1278 pick_covering_slot('瀛', None, primary, &fb, &covers),
1279 Some(1)
1280 );
1281 }
1282
1283 #[test]
1284 fn no_coverage_returns_primary() {
1285 let primary = fid(0);
1286 let fb = chain(&[1, 2]);
1287 let covers = |_: FontId, _: char| false;
1288 assert_eq!(
1291 pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers),
1292 None
1293 );
1294 }
1295
1296 #[test]
1297 fn empty_chain_always_returns_primary() {
1298 let primary = fid(0);
1299 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1300 let covers = |_: FontId, _: char| false;
1301 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1302 }
1303
1304 #[test]
1305 fn slot_font_id_resolution() {
1306 let primary = fid(7);
1307 let fb = chain(&[10, 20]);
1308 assert_eq!(slot_font_id(None, primary, &fb), fid(7));
1309 assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10));
1310 assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20));
1311 }
1312
1313 #[test]
1314 fn run_spans_with_no_chain_emit_one_primary_span() {
1315 let primary = fid(0);
1316 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1317 let covers = |_: FontId, _: char| false;
1318 let text = "hello";
1319 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1320 assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]);
1321 }
1322
1323 #[test]
1324 fn run_spans_use_byte_offsets_for_multibyte_chars() {
1325 let primary = fid(0);
1326 let fb = chain(&[1]);
1327 let covers = |id: FontId, ch: char| {
1329 if id == primary {
1330 ch.is_ascii()
1331 } else {
1332 !ch.is_ascii()
1333 }
1334 };
1335 let text = "a瀛b";
1336 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1337 assert_eq!(
1339 spans.as_slice(),
1340 &[
1341 span(0, 1, None, primary),
1342 span(1, 4, Some(0), fid(1)),
1343 span(4, 5, None, primary),
1344 ]
1345 );
1346 }
1347
1348 #[test]
1349 fn run_spans_respect_run_offset() {
1350 let primary = fid(0);
1351 let fb = chain(&[1]);
1352 let covers = |id: FontId, ch: char| {
1353 if id == primary {
1354 ch.is_ascii()
1355 } else {
1356 !ch.is_ascii()
1357 }
1358 };
1359 let text = "xx瀛x";
1361 let run_offset = 2;
1362 let run_len = text.len() - run_offset;
1363 let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers);
1364 assert_eq!(
1365 spans.as_slice(),
1366 &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)]
1367 );
1368 }
1369
1370 #[test]
1371 fn run_spans_keep_combining_marks_with_base_in_fallback() {
1372 let primary = fid(0);
1373 let fb = chain(&[1]);
1374 let covers = |id: FontId, ch: char| {
1378 if id == primary {
1379 ch.is_ascii()
1380 } else {
1381 ch == '\u{0905}'
1382 }
1383 };
1384 let text = "\u{0905}\u{0902}";
1386 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1387 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1388 }
1389
1390 #[test]
1391 fn run_spans_keep_zwj_inside_emoji_cluster() {
1392 let primary = fid(0);
1393 let fb = chain(&[1]);
1394 let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}';
1396 let text = "\u{1F469}\u{200D}\u{1F467}";
1398 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1399 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1400 }
1401
1402 #[test]
1403 fn run_spans_collapse_adjacent_same_slot() {
1404 let primary = fid(0);
1405 let fb = chain(&[1]);
1406 let covers = |id: FontId, ch: char| {
1407 if id == primary {
1408 ch.is_ascii()
1409 } else {
1410 !ch.is_ascii()
1411 }
1412 };
1413 let text = "测试文本";
1414 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1415 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1416 }
1417
1418 #[test]
1419 fn run_spans_empty_run_returns_no_spans() {
1420 let primary = fid(0);
1421 let fb = chain(&[1]);
1422 let covers = |_: FontId, _: char| true;
1423 let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers);
1424 assert!(spans.is_empty());
1425 }
1426}