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 segment =
518 self.layout_line_no_separators(&text[range.clone()], font_size, &segment_font_runs);
519
520 let mut segment_runs = segment.runs;
521 for run in &mut segment_runs {
522 for glyph in &mut run.glyphs {
523 glyph.index += range.start;
524 glyph.position.x += layout.width;
525 }
526 }
527
528 for mut run in segment_runs {
529 if let Some(same_run) = layout
530 .runs
531 .last_mut()
532 .filter(|last| last.font_id == run.font_id)
533 {
534 same_run.glyphs.append(&mut run.glyphs);
535 } else {
536 layout.runs.push(run);
537 }
538 }
539
540 layout.width += segment.width;
541 layout.ascent = layout.ascent.max(segment.ascent);
542 layout.descent = layout.descent.max(segment.descent);
543 }
544
545 fn layout_line_no_separators(
546 &mut self,
547 text: &str,
548 font_size: Pixels,
549 font_runs: &[FontRun],
550 ) -> LineLayout {
551 let mut attrs_list = AttrsList::new(&Attrs::new());
552 let mut offs = 0;
553 for run in font_runs {
554 let run_end = offs + run.len;
555
556 let loaded_font = self.loaded_font(run.font_id);
557 let Some(face) = self.font_system.db().face(loaded_font.font.id()) else {
558 log::warn!(
559 "font face not found in database for font_id {:?}",
560 run.font_id
561 );
562 offs = run_end;
563 continue;
564 };
565 let Some(first_family) = face.families.first() else {
566 log::warn!(
567 "font face has no family names for font_id {:?}",
568 run.font_id
569 );
570 offs = run_end;
571 continue;
572 };
573
574 let primary_family_name: SharedString = first_family.0.clone().into();
575 let primary_stretch = face.stretch;
576 let primary_style = face.style;
577 let primary_weight = face.weight;
578 let primary_features = loaded_font.features.clone();
579 let fallback_chain = Arc::clone(&loaded_font.user_fallback_chain);
580
581 let primary_attrs = Attrs::new()
584 .metadata(run.font_id.0)
585 .family(Family::Name(&primary_family_name))
586 .stretch(primary_stretch)
587 .style(primary_style)
588 .weight(primary_weight)
589 .font_features(primary_features.clone());
590 let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = fallback_chain
591 .iter()
592 .map(|(fb_id, fb_name)| {
593 Attrs::new()
594 .metadata(fb_id.0)
595 .family(Family::Name(fb_name))
596 .stretch(primary_stretch)
597 .style(primary_style)
598 .weight(primary_weight)
599 .font_features(primary_features.clone())
600 })
601 .collect();
602
603 let spans = if fallback_chain.is_empty() {
604 let mut spans = SmallVec::<[RunSpan; 4]>::new();
605 spans.push(RunSpan {
606 start: offs,
607 end: run_end,
608 slot: None,
609 font_id: run.font_id,
610 });
611 spans
612 } else {
613 let loaded_fonts = &self.loaded_fonts;
614 let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch);
615 compute_run_spans(text, offs, run.len, run.font_id, &fallback_chain, &covers)
616 };
617
618 for span in spans {
619 let attrs = match span.slot {
620 None => &primary_attrs,
621 Some(ix) => &fallback_attrs[ix],
622 };
623 attrs_list.add_span(span.start..span.end, attrs);
624 }
625 offs = run_end;
626 }
627
628 let line = ShapeLine::new(
629 &mut self.font_system,
630 text,
631 &attrs_list,
632 cosmic_text::Shaping::Advanced,
633 4,
634 );
635 let mut layout_lines = Vec::with_capacity(1);
636 line.layout_to_buffer(
637 &mut self.scratch,
638 f32::from(font_size),
639 None, cosmic_text::Wrap::None,
641 Ellipsize::None,
642 None,
643 &mut layout_lines,
644 None,
645 cosmic_text::Hinting::Disabled,
646 );
647
648 let Some(layout) = layout_lines.first() else {
649 return LineLayout {
650 font_size,
651 width: Pixels::ZERO,
652 ascent: Pixels::ZERO,
653 descent: Pixels::ZERO,
654 runs: Vec::new(),
655 len: text.len(),
656 };
657 };
658
659 let mut runs: Vec<ShapedRun> = Vec::new();
660 for glyph in &layout.glyphs {
661 let mut font_id = FontId(glyph.metadata);
662 let mut loaded_font = self.loaded_font(font_id);
663 if loaded_font.font.id() != glyph.font_id {
664 match self.font_id_for_cosmic_id(glyph.font_id) {
665 std::result::Result::Ok(resolved_id) => {
666 font_id = resolved_id;
667 loaded_font = self.loaded_font(font_id);
668 }
669 Err(error) => {
670 log::warn!(
671 "failed to resolve cosmic font id {:?}: {error:#}",
672 glyph.font_id
673 );
674 continue;
675 }
676 }
677 }
678 let is_emoji = loaded_font.is_known_emoji_font;
679
680 if glyph.glyph_id == 3 && is_emoji {
682 continue;
683 }
684
685 let shaped_glyph = ShapedGlyph {
686 id: GlyphId(glyph.glyph_id as u32),
687 position: point(glyph.x.into(), glyph.y.into()),
688 index: glyph.start,
689 is_emoji,
690 };
691
692 if let Some(last_run) = runs
693 .last_mut()
694 .filter(|last_run| last_run.font_id == font_id)
695 {
696 last_run.glyphs.push(shaped_glyph);
697 } else {
698 runs.push(ShapedRun {
699 font_id,
700 glyphs: vec![shaped_glyph],
701 });
702 }
703 }
704
705 LineLayout {
706 font_size,
707 width: layout.w.into(),
708 ascent: layout.max_ascent.into(),
709 descent: layout.max_descent.into(),
710 runs,
711 len: text.len(),
712 }
713 }
714}
715
716#[inline(always)]
717fn is_paragraph_separator(character: char) -> bool {
718 unicode_bidi::bidi_class(character) == unicode_bidi::BidiClass::B
719}
720
721fn contains_paragraph_separator(text: &str) -> bool {
722 if text
723 .bytes()
724 .any(|byte| matches!(byte, b'\n' | b'\r' | 0x1c | 0x1d | 0x1e))
725 {
726 return true;
727 }
728
729 !text.is_ascii() && text.chars().any(is_paragraph_separator)
730}
731
732fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontRun; 4]> {
733 let mut clipped = SmallVec::new();
734 let mut offs = 0;
735 for run in font_runs {
736 let run_start = offs;
737 offs += run.len;
738 if offs <= range.start {
739 continue;
740 }
741 if run_start >= range.end {
742 break;
743 }
744 let start = run_start.max(range.start);
745 let end = offs.min(range.end);
746 if start < end {
747 clipped.push(FontRun {
748 len: end - start,
749 font_id: run.font_id,
750 });
751 }
752 }
753 clipped
754}
755
756#[cfg(feature = "font-kit")]
757fn find_best_match(
758 font: &Font,
759 candidates: &[FontId],
760 state: &CosmicTextSystemState,
761) -> Result<usize> {
762 let candidate_properties = candidates
763 .iter()
764 .map(|font_id| {
765 let database_id = state.loaded_font(*font_id).font.id();
766 let face_info = state
767 .font_system
768 .db()
769 .face(database_id)
770 .context("font face not found in database")?;
771 Ok(face_info_into_properties(face_info))
772 })
773 .collect::<Result<SmallVec<[_; 4]>>>()?;
774
775 let ix =
776 font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
777 .context("requested font family contains no font matching the other parameters")?;
778
779 Ok(ix)
780}
781
782#[cfg(not(feature = "font-kit"))]
783fn find_best_match(
784 font: &Font,
785 candidates: &[FontId],
786 state: &CosmicTextSystemState,
787) -> Result<usize> {
788 if candidates.is_empty() {
789 anyhow::bail!("requested font family contains no font matching the other parameters");
790 }
791 if candidates.len() == 1 {
792 return Ok(0);
793 }
794
795 let target_weight = font.weight.0;
796 let target_italic = matches!(
797 font.style,
798 rgpui::FontStyle::Italic | rgpui::FontStyle::Oblique
799 );
800
801 let mut best_index = 0;
802 let mut best_score = u32::MAX;
803
804 for (index, font_id) in candidates.iter().enumerate() {
805 let database_id = state.loaded_font(*font_id).font.id();
806 let face_info = state
807 .font_system
808 .db()
809 .face(database_id)
810 .context("font face not found in database")?;
811
812 let is_italic = matches!(
813 face_info.style,
814 cosmic_text::Style::Italic | cosmic_text::Style::Oblique
815 );
816 let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
817 let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
818 let score = style_penalty + weight_diff;
819
820 if score < best_score {
821 best_score = score;
822 best_index = index;
823 }
824 }
825
826 Ok(best_index)
827}
828
829#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832struct RunSpan {
833 start: usize,
834 end: usize,
835 slot: Option<usize>,
836 font_id: FontId,
837}
838
839fn compute_run_spans(
843 text: &str,
844 run_offset: usize,
845 run_len: usize,
846 primary: FontId,
847 fallback_chain: &[(FontId, SharedString)],
848 covers: &impl Fn(FontId, char) -> bool,
849) -> SmallVec<[RunSpan; 4]> {
850 let mut spans = SmallVec::new();
851 let run_end = run_offset + run_len;
852 if run_end <= run_offset {
853 return spans;
854 }
855 if fallback_chain.is_empty() {
856 spans.push(RunSpan {
857 start: run_offset,
858 end: run_end,
859 slot: None,
860 font_id: primary,
861 });
862 return spans;
863 }
864 let run_text = &text[run_offset..run_end];
865 let mut span_start = run_offset;
866 let mut span_slot: Option<usize> = None;
867 let mut span_font_id = primary;
868 for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) {
869 let abs = run_offset + grapheme_idx;
870 let ch = grapheme.chars().next().unwrap_or('\0');
871 let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);
872 if next_slot == span_slot {
873 continue;
874 }
875 if abs > span_start {
876 spans.push(RunSpan {
877 start: span_start,
878 end: abs,
879 slot: span_slot,
880 font_id: span_font_id,
881 });
882 }
883 span_start = abs;
884 span_slot = next_slot;
885 span_font_id = slot_font_id(next_slot, primary, fallback_chain);
886 }
887 if span_start < run_end {
888 spans.push(RunSpan {
889 start: span_start,
890 end: run_end,
891 slot: span_slot,
892 font_id: span_font_id,
893 });
894 }
895 spans
896}
897
898fn slot_font_id(
899 slot: Option<usize>,
900 primary: FontId,
901 fallback_chain: &[(FontId, SharedString)],
902) -> FontId {
903 match slot {
904 None => primary,
905 Some(ix) => fallback_chain[ix].0,
906 }
907}
908
909fn pick_covering_slot(
910 ch: char,
911 current: Option<usize>,
912 primary: FontId,
913 fallback_chain: &[(FontId, SharedString)],
914 covers: &impl Fn(FontId, char) -> bool,
915) -> Option<usize> {
916 if (ch as u32) <= 0x7F {
917 return None;
918 }
919 if covers(primary, ch) {
920 return None;
921 }
922 let current_id = slot_font_id(current, primary, fallback_chain);
923 if covers(current_id, ch) {
924 return current;
925 }
926
927 fallback_chain
928 .iter()
929 .position(|(fb_id, _)| covers(*fb_id, ch))
930}
931
932fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool {
933 loaded_fonts
934 .get(id.0)
935 .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0)
936}
937
938fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
939 let mut result = CosmicFontFeatures::new();
940 for feature in features.0.iter() {
941 let name_bytes: [u8; 4] = feature
942 .0
943 .as_bytes()
944 .try_into()
945 .context("Incorrect feature flag format")?;
946
947 let tag = cosmic_text::FeatureTag::new(&name_bytes);
948
949 result.set(tag, feature.1);
950 }
951 Ok(result)
952}
953
954#[cfg(feature = "font-kit")]
955fn font_into_properties(font: &rgpui::Font) -> font_kit::properties::Properties {
956 font_kit::properties::Properties {
957 style: match font.style {
958 rgpui::FontStyle::Normal => font_kit::properties::Style::Normal,
959 rgpui::FontStyle::Italic => font_kit::properties::Style::Italic,
960 rgpui::FontStyle::Oblique => font_kit::properties::Style::Oblique,
961 },
962 weight: font_kit::properties::Weight(font.weight.0),
963 stretch: Default::default(),
964 }
965}
966
967#[cfg(feature = "font-kit")]
968fn face_info_into_properties(
969 face_info: &cosmic_text::fontdb::FaceInfo,
970) -> font_kit::properties::Properties {
971 font_kit::properties::Properties {
972 style: match face_info.style {
973 cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
974 cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
975 cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
976 },
977 weight: font_kit::properties::Weight(face_info.weight.0.into()),
978 stretch: match face_info.stretch {
979 cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
980 cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
981 cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
982 cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
983 cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
984 cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
985 cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
986 cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
987 cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
988 },
989 }
990}
991
992fn check_is_known_emoji_font(postscript_name: &str) -> bool {
993 postscript_name == "NotoColorEmoji"
995}
996
997#[cfg(test)]
998mod tests {
999 use super::*;
1000
1001 fn fid(i: usize) -> FontId {
1002 FontId(i)
1003 }
1004
1005 fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> {
1006 ids.iter()
1007 .map(|&i| (fid(i), SharedString::from(format!("fb{i}"))))
1008 .collect()
1009 }
1010
1011 fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan {
1012 RunSpan {
1013 start,
1014 end,
1015 slot,
1016 font_id,
1017 }
1018 }
1019
1020 const IBM_PLEX: &[u8] =
1021 include_bytes!("../../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf");
1022
1023 const SEPARATORS: &[char] = &[
1026 '\u{000a}', '\u{000d}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{0085}', '\u{2029}',
1027 ];
1028
1029 fn text_system() -> Result<CosmicTextSystem> {
1030 let text_system = CosmicTextSystem::new_without_system_fonts("IBM Plex Sans");
1031 text_system.add_fonts(vec![Cow::Borrowed(IBM_PLEX)])?;
1032 Ok(text_system)
1033 }
1034
1035 fn layout_text(text_system: &CosmicTextSystem, text: &str) -> Result<LineLayout> {
1036 let font_id = text_system.font_id(&rgpui::font("IBM Plex Sans"))?;
1037 let runs = [FontRun {
1038 len: text.len(),
1039 font_id,
1040 }];
1041 Ok(text_system.layout_line(text, rgpui::px(14.0), &runs))
1042 }
1043
1044 #[test]
1047 fn shape_text_with_mixed_direction_paragraphs() -> Result<()> {
1048 let platform_text_system = Arc::new(text_system()?);
1049 let text_system = Arc::new(rgpui::TextSystem::new(platform_text_system));
1050 let window_text_system = rgpui::WindowTextSystem::new(text_system);
1051
1052 let text: SharedString = "first line\n\u{05d0}\u{001c}A".into();
1053 let runs = [rgpui::TextRun {
1054 len: text.len(),
1055 font: rgpui::font("IBM Plex Sans"),
1056 ..Default::default()
1057 }];
1058
1059 let lines = window_text_system.shape_text(text, rgpui::px(14.0), &runs, None, None)?;
1060
1061 assert_eq!(lines.len(), 2);
1062 assert_eq!(lines[1].len(), "\u{05d0}\u{001c}A".len());
1063 assert!(lines[1].width() > Pixels::ZERO);
1064 Ok(())
1065 }
1066
1067 #[test]
1068 fn layout_line_with_mixed_direction_paragraphs() -> Result<()> {
1069 let text_system = text_system()?;
1070
1071 for separator in SEPARATORS {
1072 for text in [
1073 format!("\u{05d0}{separator}A"),
1074 format!("A{separator}\u{05d0}"),
1075 ] {
1076 let layout = layout_text(&text_system, &text)?;
1077
1078 assert_eq!(layout.len, text.len(), "{text:?}");
1079 assert!(layout.width > Pixels::ZERO, "{text:?}");
1080 assert!(
1081 layout.runs.iter().any(|run| !run.glyphs.is_empty()),
1082 "{text:?}"
1083 );
1084 }
1085 }
1086
1087 Ok(())
1088 }
1089
1090 #[test]
1091 fn layout_line_with_separators_at_line_edges() -> Result<()> {
1092 let text_system = text_system()?;
1093
1094 for text in [
1095 "\u{001c}",
1096 "\u{001c}\u{001c}",
1097 "\u{001c}\u{05d0}",
1098 "\u{05d0}\u{001c}",
1099 "\u{05d0}\u{001c}\u{001c}A",
1100 "\u{001c}\u{05d0}\u{001c}A\u{001c}",
1101 ] {
1102 let layout = layout_text(&text_system, text)?;
1103 assert_eq!(layout.len, text.len(), "{text:?}");
1104 }
1105
1106 Ok(())
1107 }
1108
1109 #[test]
1113 fn layout_line_keeps_indices_and_positions_ordered_across_paragraphs() -> Result<()> {
1114 let text_system = text_system()?;
1115 let text = "ab\u{001c}cd\u{2029}ef";
1116 let layout = layout_text(&text_system, text)?;
1117
1118 let glyphs: Vec<_> = layout.runs.iter().flat_map(|run| &run.glyphs).collect();
1119 assert!(!glyphs.is_empty());
1120
1121 for glyph in &glyphs {
1122 assert!(glyph.index < text.len(), "{:?}", glyph.index);
1123 assert!(text.is_char_boundary(glyph.index), "{:?}", glyph.index);
1124 }
1125 for pair in glyphs.windows(2) {
1126 assert!(pair[0].index < pair[1].index);
1127 assert!(pair[0].position.x <= pair[1].position.x);
1128 }
1129
1130 assert!(layout.width > layout_text(&text_system, "ab")?.width);
1133 Ok(())
1134 }
1135
1136 #[test]
1139 fn layout_line_with_font_run_straddling_a_separator() -> Result<()> {
1140 let text_system = text_system()?;
1141 let font_id = text_system.font_id(&rgpui::font("IBM Plex Sans"))?;
1142 let text = "ab\u{001c}\u{05d0}\u{05d1}";
1143
1144 let runs = [
1146 FontRun {
1147 len: "ab\u{001c}\u{05d0}".len(),
1148 font_id,
1149 },
1150 FontRun {
1151 len: "\u{05d1}".len(),
1152 font_id,
1153 },
1154 ];
1155 let layout = text_system.layout_line(text, rgpui::px(14.0), &runs);
1156
1157 assert_eq!(layout.len, text.len());
1158 assert!(layout.width > Pixels::ZERO);
1159 Ok(())
1160 }
1161
1162 #[test]
1165 fn layout_line_without_separators_takes_fast_path() -> Result<()> {
1166 let text_system = text_system()?;
1167
1168 for text in [
1169 "hello world",
1170 "\u{05d0}\u{05d1}\u{05d2}",
1171 "mixed \u{05d0}\u{05d1}",
1172 ] {
1173 assert!(!contains_paragraph_separator(text), "{text:?}");
1174 let layout = layout_text(&text_system, text)?;
1175 assert_eq!(layout.len, text.len(), "{text:?}");
1176 assert!(layout.width > Pixels::ZERO, "{text:?}");
1177 }
1178
1179 Ok(())
1180 }
1181
1182 #[test]
1183 fn paragraph_separator_detection() {
1184 for separator in SEPARATORS {
1185 assert!(is_paragraph_separator(*separator), "{separator:?}");
1186 assert!(contains_paragraph_separator(&format!("a{separator}b")));
1187 }
1188
1189 for text in [
1190 "",
1191 "plain ascii",
1192 "\u{05d0}",
1193 "tab\there",
1194 "emoji \u{1f600}",
1195 ] {
1196 assert!(!contains_paragraph_separator(text), "{text:?}");
1197 }
1198 }
1199
1200 #[test]
1201 fn font_runs_are_clipped_to_segment() {
1202 let runs = [
1203 FontRun {
1204 len: 3,
1205 font_id: fid(1),
1206 },
1207 FontRun {
1208 len: 4,
1209 font_id: fid(2),
1210 },
1211 ];
1212
1213 assert_eq!(clip_font_runs(&runs, 0..7).as_slice(), &runs);
1214 assert_eq!(
1215 clip_font_runs(&runs, 2..5).as_slice(),
1216 &[
1217 FontRun {
1218 len: 1,
1219 font_id: fid(1)
1220 },
1221 FontRun {
1222 len: 2,
1223 font_id: fid(2)
1224 },
1225 ]
1226 );
1227 assert_eq!(
1228 clip_font_runs(&runs, 3..7).as_slice(),
1229 &[FontRun {
1230 len: 4,
1231 font_id: fid(2)
1232 }]
1233 );
1234 assert!(clip_font_runs(&runs, 5..5).is_empty());
1235 }
1236
1237 #[test]
1238 fn primary_wins_over_current_fallback_when_primary_covers() {
1239 let primary = fid(0);
1240 let fb = chain(&[1, 2]);
1241 let covers = |id: FontId, _: char| id == fid(0) || id == fid(1);
1242 assert_eq!(
1243 pick_covering_slot('a', Some(0), primary, &fb, &covers),
1244 None
1245 );
1246 }
1247
1248 #[test]
1249 fn primary_preferred_over_fallback_when_both_cover() {
1250 let primary = fid(0);
1251 let fb = chain(&[1]);
1252 let covers = |_: FontId, _: char| true;
1253 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1254 }
1255
1256 #[test]
1257 fn falls_through_chain_in_order() {
1258 let primary = fid(0);
1259 let fb = chain(&[1, 2, 3]);
1260 let covers = |id: FontId, _: char| id == fid(2);
1262 assert_eq!(
1263 pick_covering_slot('瀛?, None, primary, &fb, &covers),
1264 Some(1)
1265 );
1266 }
1267
1268 #[test]
1269 fn no_coverage_returns_primary() {
1270 let primary = fid(0);
1271 let fb = chain(&[1, 2]);
1272 let covers = |_: FontId, _: char| false;
1273 assert_eq!(
1276 pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers),
1277 None
1278 );
1279 }
1280
1281 #[test]
1282 fn empty_chain_always_returns_primary() {
1283 let primary = fid(0);
1284 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1285 let covers = |_: FontId, _: char| false;
1286 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
1287 }
1288
1289 #[test]
1290 fn slot_font_id_resolution() {
1291 let primary = fid(7);
1292 let fb = chain(&[10, 20]);
1293 assert_eq!(slot_font_id(None, primary, &fb), fid(7));
1294 assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10));
1295 assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20));
1296 }
1297
1298 #[test]
1299 fn run_spans_with_no_chain_emit_one_primary_span() {
1300 let primary = fid(0);
1301 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
1302 let covers = |_: FontId, _: char| false;
1303 let text = "hello";
1304 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1305 assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]);
1306 }
1307
1308 #[test]
1309 fn run_spans_use_byte_offsets_for_multibyte_chars() {
1310 let primary = fid(0);
1311 let fb = chain(&[1]);
1312 let covers = |id: FontId, ch: char| {
1314 if id == primary {
1315 ch.is_ascii()
1316 } else {
1317 !ch.is_ascii()
1318 }
1319 };
1320 let text = "a瀛梑";
1321 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1322 assert_eq!(
1324 spans.as_slice(),
1325 &[
1326 span(0, 1, None, primary),
1327 span(1, 4, Some(0), fid(1)),
1328 span(4, 5, None, primary),
1329 ]
1330 );
1331 }
1332
1333 #[test]
1334 fn run_spans_respect_run_offset() {
1335 let primary = fid(0);
1336 let fb = chain(&[1]);
1337 let covers = |id: FontId, ch: char| {
1338 if id == primary {
1339 ch.is_ascii()
1340 } else {
1341 !ch.is_ascii()
1342 }
1343 };
1344 let text = "xx瀛梱";
1346 let run_offset = 2;
1347 let run_len = text.len() - run_offset;
1348 let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers);
1349 assert_eq!(
1350 spans.as_slice(),
1351 &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)]
1352 );
1353 }
1354
1355 #[test]
1356 fn run_spans_keep_combining_marks_with_base_in_fallback() {
1357 let primary = fid(0);
1358 let fb = chain(&[1]);
1359 let covers = |id: FontId, ch: char| {
1363 if id == primary {
1364 ch.is_ascii()
1365 } else {
1366 ch == '\u{0905}'
1367 }
1368 };
1369 let text = "\u{0905}\u{0902}";
1371 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1372 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1373 }
1374
1375 #[test]
1376 fn run_spans_keep_zwj_inside_emoji_cluster() {
1377 let primary = fid(0);
1378 let fb = chain(&[1]);
1379 let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}';
1381 let text = "\u{1F469}\u{200D}\u{1F467}";
1383 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1384 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1385 }
1386
1387 #[test]
1388 fn run_spans_collapse_adjacent_same_slot() {
1389 let primary = fid(0);
1390 let fb = chain(&[1]);
1391 let covers = |id: FontId, ch: char| {
1392 if id == primary {
1393 ch.is_ascii()
1394 } else {
1395 !ch.is_ascii()
1396 }
1397 };
1398 let text = "测试文本";
1399 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1400 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1401 }
1402
1403 #[test]
1404 fn run_spans_empty_run_returns_no_spans() {
1405 let primary = fid(0);
1406 let fb = chain(&[1]);
1407 let covers = |_: FontId, _: char| true;
1408 let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers);
1409 assert!(spans.is_empty());
1410 }
1411}