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, 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 match bytes {
216 Cow::Borrowed(embedded_font) => {
217 db.load_font_data(embedded_font.to_vec());
218 }
219 Cow::Owned(bytes) => {
220 db.load_font_data(bytes);
221 }
222 }
223 }
224 Ok(())
225 }
226
227 #[profiling::function]
228 fn load_family(
229 &mut self,
230 name: &str,
231 features: &FontFeatures,
232 fallbacks: Option<&FontFallbacks>,
233 ) -> Result<SmallVec<[FontId; 4]>> {
234 let user_fallback_chain: Arc<[(FontId, SharedString)]> = match fallbacks {
238 Some(fallbacks) if !fallbacks.fallback_list().is_empty() => {
239 let mut chain: Vec<(FontId, SharedString)> = Vec::new();
240 for fallback_name in fallbacks.fallback_list() {
241 let fb_key = FontKey::new(
242 SharedString::from(fallback_name.clone()),
243 features.clone(),
244 None,
245 );
246 let fb_ids = if let Some(cached) = self.font_ids_by_family_cache.get(&fb_key) {
247 cached.clone()
248 } else {
249 let loaded = self.load_family(fallback_name, features, None)?;
250 self.font_ids_by_family_cache
251 .insert(fb_key.clone(), loaded.clone());
252 loaded
253 };
254 let Some(&fb_id) = fb_ids.first() else {
255 continue;
256 };
257 let db_id = self.loaded_fonts[fb_id.0].font.id();
258 if let Some(face) = self.font_system.db().face(db_id)
259 && let Some(family) = face.families.first()
260 {
261 chain.push((fb_id, SharedString::from(family.0.clone())));
262 }
263 }
264 Arc::from(chain)
265 }
266 _ => Arc::from(Vec::new()),
267 };
268
269 let name = rgpui::font_name_with_fallbacks(name, &self.system_font_fallback);
270
271 let families = self
272 .font_system
273 .db()
274 .faces()
275 .filter(|face| face.families.iter().any(|family| *name == family.0))
276 .map(|face| (face.id, face.post_script_name.clone()))
277 .collect::<SmallVec<[_; 4]>>();
278
279 let cosmic_features = cosmic_font_features(features)?;
280
281 let mut loaded_font_ids = SmallVec::new();
282 for (font_id, postscript_name) in families {
283 let font = self
284 .font_system
285 .get_font(font_id, cosmic_text::Weight::NORMAL)
286 .context("Could not load font")?;
287
288 let allowed_bad_font_names = [
290 "SegoeFluentIcons", "Segoe Fluent Icons",
292 ];
293
294 if font.as_swash().charmap().map('m') == 0
295 && !allowed_bad_font_names.contains(&postscript_name.as_str())
296 {
297 self.font_system.db_mut().remove_face(font.id());
298 continue;
299 };
300
301 let font_id = FontId(self.loaded_fonts.len());
302 loaded_font_ids.push(font_id);
303 self.loaded_fonts.push(LoadedFont {
304 font,
305 features: cosmic_features.clone(),
306 is_known_emoji_font: check_is_known_emoji_font(&postscript_name),
307 user_fallback_chain: Arc::clone(&user_fallback_chain),
308 });
309 }
310
311 Ok(loaded_font_ids)
312 }
313
314 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
315 let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
316 Ok(Size {
317 width: glyph_metrics.advance_width(glyph_id.0 as u16),
318 height: glyph_metrics.advance_height(glyph_id.0 as u16),
319 })
320 }
321
322 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
323 let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch);
324 if glyph_id == 0 {
325 None
326 } else {
327 Some(GlyphId(glyph_id.into()))
328 }
329 }
330
331 fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
332 let image = self.render_glyph_image(params)?;
333 Ok(Bounds {
334 origin: point(image.placement.left.into(), (-image.placement.top).into()),
335 size: size(image.placement.width.into(), image.placement.height.into()),
336 })
337 }
338
339 #[profiling::function]
340 fn rasterize_glyph(
341 &mut self,
342 params: &RenderGlyphParams,
343 glyph_bounds: Bounds<DevicePixels>,
344 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
345 if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
346 anyhow::bail!("glyph bounds are empty");
347 }
348
349 let mut image = self.render_glyph_image(params)?;
350 let bitmap_size = glyph_bounds.size;
351 match image.content {
352 swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
353 for pixel in image.data.chunks_exact_mut(4) {
355 pixel.swap(0, 2);
356 }
357 Ok((bitmap_size, image.data))
358 }
359 swash::scale::image::Content::Mask => {
360 if params.subpixel_rendering {
361 let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
363 Ok((bitmap_size, expanded))
364 } else {
365 Ok((bitmap_size, image.data))
366 }
367 }
368 }
369 }
370
371 fn render_glyph_image(
372 &mut self,
373 params: &RenderGlyphParams,
374 ) -> Result<swash::scale::image::Image> {
375 let loaded_font = &self.loaded_fonts[params.font_id.0];
376 let font_ref = loaded_font.font.as_swash();
377 let pixel_size = f32::from(params.font_size);
378
379 let subpixel_offset = Vector::new(
380 params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor,
381 params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor,
382 );
383
384 let mut scaler = self
385 .swash_scale_context
386 .builder(font_ref)
387 .size(pixel_size * params.scale_factor)
388 .hint(true)
389 .build();
390
391 let sources: &[Source] = if params.is_emoji {
392 &[
393 Source::ColorOutline(0),
394 Source::ColorBitmap(StrikeWith::BestFit),
395 Source::Outline,
396 ]
397 } else {
398 &[Source::Bitmap(StrikeWith::ExactSize), Source::Outline]
399 };
400
401 let mut renderer = Render::new(sources);
402 if params.subpixel_rendering {
403 renderer
405 .format(Format::subpixel_bgra())
406 .offset(subpixel_offset);
407 } else {
408 renderer.format(Format::Alpha).offset(subpixel_offset);
409 }
410
411 let glyph_id: u16 = params.glyph_id.0.try_into()?;
412 renderer
413 .render(&mut scaler, glyph_id)
414 .with_context(|| format!("unable to render glyph via swash for {params:?}"))
415 }
416
417 fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> {
426 if let Some(ix) = self
427 .loaded_fonts
428 .iter()
429 .position(|loaded_font| loaded_font.font.id() == id)
430 {
431 Ok(FontId(ix))
432 } else {
433 let font = self
434 .font_system
435 .get_font(id, cosmic_text::Weight::NORMAL)
436 .context("failed to get fallback font from cosmic-text font system")?;
437 let face = self
438 .font_system
439 .db()
440 .face(id)
441 .context("fallback font face not found in cosmic-text database")?;
442
443 let font_id = FontId(self.loaded_fonts.len());
444 self.loaded_fonts.push(LoadedFont {
445 font,
446 features: CosmicFontFeatures::new(),
447 is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name),
448 user_fallback_chain: Arc::from(Vec::new()),
449 });
450
451 Ok(font_id)
452 }
453 }
454
455 #[profiling::function]
456 fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
457 let mut attrs_list = AttrsList::new(&Attrs::new());
458 let mut offs = 0;
459 for run in font_runs {
460 let run_end = offs + run.len;
461
462 let loaded_font = self.loaded_font(run.font_id);
463 let Some(face) = self.font_system.db().face(loaded_font.font.id()) else {
464 log::warn!(
465 "font face not found in database for font_id {:?}",
466 run.font_id
467 );
468 offs = run_end;
469 continue;
470 };
471 let Some(first_family) = face.families.first() else {
472 log::warn!(
473 "font face has no family names for font_id {:?}",
474 run.font_id
475 );
476 offs = run_end;
477 continue;
478 };
479
480 let primary_family_name: SharedString = first_family.0.clone().into();
481 let primary_stretch = face.stretch;
482 let primary_style = face.style;
483 let primary_weight = face.weight;
484 let primary_features = loaded_font.features.clone();
485 let fallback_chain = Arc::clone(&loaded_font.user_fallback_chain);
486
487 let primary_attrs = Attrs::new()
490 .metadata(run.font_id.0)
491 .family(Family::Name(&primary_family_name))
492 .stretch(primary_stretch)
493 .style(primary_style)
494 .weight(primary_weight)
495 .font_features(primary_features.clone());
496 let fallback_attrs: SmallVec<[Attrs<'_>; 4]> = fallback_chain
497 .iter()
498 .map(|(fb_id, fb_name)| {
499 Attrs::new()
500 .metadata(fb_id.0)
501 .family(Family::Name(fb_name))
502 .stretch(primary_stretch)
503 .style(primary_style)
504 .weight(primary_weight)
505 .font_features(primary_features.clone())
506 })
507 .collect();
508
509 let spans = if fallback_chain.is_empty() {
510 let mut spans = SmallVec::<[RunSpan; 4]>::new();
511 spans.push(RunSpan {
512 start: offs,
513 end: run_end,
514 slot: None,
515 font_id: run.font_id,
516 });
517 spans
518 } else {
519 let loaded_fonts = &self.loaded_fonts;
520 let covers = |id: FontId, ch: char| charmap_covers(loaded_fonts, id, ch);
521 compute_run_spans(text, offs, run.len, run.font_id, &fallback_chain, &covers)
522 };
523
524 for span in spans {
525 let attrs = match span.slot {
526 None => &primary_attrs,
527 Some(ix) => &fallback_attrs[ix],
528 };
529 attrs_list.add_span(span.start..span.end, attrs);
530 }
531 offs = run_end;
532 }
533
534 let line = ShapeLine::new(
535 &mut self.font_system,
536 text,
537 &attrs_list,
538 cosmic_text::Shaping::Advanced,
539 4,
540 );
541 let mut layout_lines = Vec::with_capacity(1);
542 line.layout_to_buffer(
543 &mut self.scratch,
544 f32::from(font_size),
545 None, cosmic_text::Wrap::None,
547 Ellipsize::None,
548 None,
549 &mut layout_lines,
550 None,
551 cosmic_text::Hinting::Disabled,
552 );
553
554 let Some(layout) = layout_lines.first() else {
555 return LineLayout {
556 font_size,
557 width: Pixels::ZERO,
558 ascent: Pixels::ZERO,
559 descent: Pixels::ZERO,
560 runs: Vec::new(),
561 len: text.len(),
562 };
563 };
564
565 let mut runs: Vec<ShapedRun> = Vec::new();
566 for glyph in &layout.glyphs {
567 let mut font_id = FontId(glyph.metadata);
568 let mut loaded_font = self.loaded_font(font_id);
569 if loaded_font.font.id() != glyph.font_id {
570 match self.font_id_for_cosmic_id(glyph.font_id) {
571 std::result::Result::Ok(resolved_id) => {
572 font_id = resolved_id;
573 loaded_font = self.loaded_font(font_id);
574 }
575 Err(error) => {
576 log::warn!(
577 "failed to resolve cosmic font id {:?}: {error:#}",
578 glyph.font_id
579 );
580 continue;
581 }
582 }
583 }
584 let is_emoji = loaded_font.is_known_emoji_font;
585
586 if glyph.glyph_id == 3 && is_emoji {
588 continue;
589 }
590
591 let shaped_glyph = ShapedGlyph {
592 id: GlyphId(glyph.glyph_id as u32),
593 position: point(glyph.x.into(), glyph.y.into()),
594 index: glyph.start,
595 is_emoji,
596 };
597
598 if let Some(last_run) = runs
599 .last_mut()
600 .filter(|last_run| last_run.font_id == font_id)
601 {
602 last_run.glyphs.push(shaped_glyph);
603 } else {
604 runs.push(ShapedRun {
605 font_id,
606 glyphs: vec![shaped_glyph],
607 });
608 }
609 }
610
611 LineLayout {
612 font_size,
613 width: layout.w.into(),
614 ascent: layout.max_ascent.into(),
615 descent: layout.max_descent.into(),
616 runs,
617 len: text.len(),
618 }
619 }
620}
621
622#[cfg(feature = "font-kit")]
623fn find_best_match(
624 font: &Font,
625 candidates: &[FontId],
626 state: &CosmicTextSystemState,
627) -> Result<usize> {
628 let candidate_properties = candidates
629 .iter()
630 .map(|font_id| {
631 let database_id = state.loaded_font(*font_id).font.id();
632 let face_info = state
633 .font_system
634 .db()
635 .face(database_id)
636 .context("font face not found in database")?;
637 Ok(face_info_into_properties(face_info))
638 })
639 .collect::<Result<SmallVec<[_; 4]>>>()?;
640
641 let ix =
642 font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
643 .context("requested font family contains no font matching the other parameters")?;
644
645 Ok(ix)
646}
647
648#[cfg(not(feature = "font-kit"))]
649fn find_best_match(
650 font: &Font,
651 candidates: &[FontId],
652 state: &CosmicTextSystemState,
653) -> Result<usize> {
654 if candidates.is_empty() {
655 anyhow::bail!("requested font family contains no font matching the other parameters");
656 }
657 if candidates.len() == 1 {
658 return Ok(0);
659 }
660
661 let target_weight = font.weight.0;
662 let target_italic = matches!(
663 font.style,
664 rgpui::FontStyle::Italic | rgpui::FontStyle::Oblique
665 );
666
667 let mut best_index = 0;
668 let mut best_score = u32::MAX;
669
670 for (index, font_id) in candidates.iter().enumerate() {
671 let database_id = state.loaded_font(*font_id).font.id();
672 let face_info = state
673 .font_system
674 .db()
675 .face(database_id)
676 .context("font face not found in database")?;
677
678 let is_italic = matches!(
679 face_info.style,
680 cosmic_text::Style::Italic | cosmic_text::Style::Oblique
681 );
682 let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
683 let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
684 let score = style_penalty + weight_diff;
685
686 if score < best_score {
687 best_score = score;
688 best_index = index;
689 }
690 }
691
692 Ok(best_index)
693}
694
695#[derive(Debug, Clone, Copy, PartialEq, Eq)]
698struct RunSpan {
699 start: usize,
700 end: usize,
701 slot: Option<usize>,
702 font_id: FontId,
703}
704
705fn compute_run_spans(
709 text: &str,
710 run_offset: usize,
711 run_len: usize,
712 primary: FontId,
713 fallback_chain: &[(FontId, SharedString)],
714 covers: &impl Fn(FontId, char) -> bool,
715) -> SmallVec<[RunSpan; 4]> {
716 let mut spans = SmallVec::new();
717 let run_end = run_offset + run_len;
718 if run_end <= run_offset {
719 return spans;
720 }
721 if fallback_chain.is_empty() {
722 spans.push(RunSpan {
723 start: run_offset,
724 end: run_end,
725 slot: None,
726 font_id: primary,
727 });
728 return spans;
729 }
730 let run_text = &text[run_offset..run_end];
731 let mut span_start = run_offset;
732 let mut span_slot: Option<usize> = None;
733 let mut span_font_id = primary;
734 for (grapheme_idx, grapheme) in run_text.grapheme_indices(true) {
735 let abs = run_offset + grapheme_idx;
736 let ch = grapheme.chars().next().unwrap_or('\0');
737 let next_slot = pick_covering_slot(ch, span_slot, primary, fallback_chain, covers);
738 if next_slot == span_slot {
739 continue;
740 }
741 if abs > span_start {
742 spans.push(RunSpan {
743 start: span_start,
744 end: abs,
745 slot: span_slot,
746 font_id: span_font_id,
747 });
748 }
749 span_start = abs;
750 span_slot = next_slot;
751 span_font_id = slot_font_id(next_slot, primary, fallback_chain);
752 }
753 if span_start < run_end {
754 spans.push(RunSpan {
755 start: span_start,
756 end: run_end,
757 slot: span_slot,
758 font_id: span_font_id,
759 });
760 }
761 spans
762}
763
764fn slot_font_id(
765 slot: Option<usize>,
766 primary: FontId,
767 fallback_chain: &[(FontId, SharedString)],
768) -> FontId {
769 match slot {
770 None => primary,
771 Some(ix) => fallback_chain[ix].0,
772 }
773}
774
775fn pick_covering_slot(
776 ch: char,
777 current: Option<usize>,
778 primary: FontId,
779 fallback_chain: &[(FontId, SharedString)],
780 covers: &impl Fn(FontId, char) -> bool,
781) -> Option<usize> {
782 if (ch as u32) <= 0x7F {
783 return None;
784 }
785 if covers(primary, ch) {
786 return None;
787 }
788 let current_id = slot_font_id(current, primary, fallback_chain);
789 if covers(current_id, ch) {
790 return current;
791 }
792 for (ix, (fb_id, _)) in fallback_chain.iter().enumerate() {
793 if covers(*fb_id, ch) {
794 return Some(ix);
795 }
796 }
797 None
798}
799
800fn charmap_covers(loaded_fonts: &[LoadedFont], id: FontId, ch: char) -> bool {
801 loaded_fonts
802 .get(id.0)
803 .is_some_and(|loaded| loaded.font.as_swash().charmap().map(ch) != 0)
804}
805
806fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
807 let mut result = CosmicFontFeatures::new();
808 for feature in features.0.iter() {
809 let name_bytes: [u8; 4] = feature
810 .0
811 .as_bytes()
812 .try_into()
813 .context("Incorrect feature flag format")?;
814
815 let tag = cosmic_text::FeatureTag::new(&name_bytes);
816
817 result.set(tag, feature.1);
818 }
819 Ok(result)
820}
821
822#[cfg(feature = "font-kit")]
823fn font_into_properties(font: &rgpui::Font) -> font_kit::properties::Properties {
824 font_kit::properties::Properties {
825 style: match font.style {
826 rgpui::FontStyle::Normal => font_kit::properties::Style::Normal,
827 rgpui::FontStyle::Italic => font_kit::properties::Style::Italic,
828 rgpui::FontStyle::Oblique => font_kit::properties::Style::Oblique,
829 },
830 weight: font_kit::properties::Weight(font.weight.0),
831 stretch: Default::default(),
832 }
833}
834
835#[cfg(feature = "font-kit")]
836fn face_info_into_properties(
837 face_info: &cosmic_text::fontdb::FaceInfo,
838) -> font_kit::properties::Properties {
839 font_kit::properties::Properties {
840 style: match face_info.style {
841 cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
842 cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
843 cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
844 },
845 weight: font_kit::properties::Weight(face_info.weight.0.into()),
846 stretch: match face_info.stretch {
847 cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
848 cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
849 cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
850 cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
851 cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
852 cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
853 cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
854 cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
855 cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
856 },
857 }
858}
859
860fn check_is_known_emoji_font(postscript_name: &str) -> bool {
861 postscript_name == "NotoColorEmoji"
863}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868
869 fn fid(i: usize) -> FontId {
870 FontId(i)
871 }
872
873 fn chain(ids: &[usize]) -> SmallVec<[(FontId, SharedString); 4]> {
874 ids.iter()
875 .map(|&i| (fid(i), SharedString::from(format!("fb{i}"))))
876 .collect()
877 }
878
879 fn span(start: usize, end: usize, slot: Option<usize>, font_id: FontId) -> RunSpan {
880 RunSpan {
881 start,
882 end,
883 slot,
884 font_id,
885 }
886 }
887
888 #[test]
889 fn primary_wins_over_current_fallback_when_primary_covers() {
890 let primary = fid(0);
891 let fb = chain(&[1, 2]);
892 let covers = |id: FontId, _: char| id == fid(0) || id == fid(1);
893 assert_eq!(
894 pick_covering_slot('a', Some(0), primary, &fb, &covers),
895 None
896 );
897 }
898
899 #[test]
900 fn primary_preferred_over_fallback_when_both_cover() {
901 let primary = fid(0);
902 let fb = chain(&[1]);
903 let covers = |_: FontId, _: char| true;
904 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
905 }
906
907 #[test]
908 fn falls_through_chain_in_order() {
909 let primary = fid(0);
910 let fb = chain(&[1, 2, 3]);
911 let covers = |id: FontId, _: char| id == fid(2);
913 assert_eq!(
914 pick_covering_slot('字', None, primary, &fb, &covers),
915 Some(1)
916 );
917 }
918
919 #[test]
920 fn no_coverage_returns_primary() {
921 let primary = fid(0);
922 let fb = chain(&[1, 2]);
923 let covers = |_: FontId, _: char| false;
924 assert_eq!(
927 pick_covering_slot('\u{1F600}', Some(1), primary, &fb, &covers),
928 None
929 );
930 }
931
932 #[test]
933 fn empty_chain_always_returns_primary() {
934 let primary = fid(0);
935 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
936 let covers = |_: FontId, _: char| false;
937 assert_eq!(pick_covering_slot('a', None, primary, &fb, &covers), None);
938 }
939
940 #[test]
941 fn slot_font_id_resolution() {
942 let primary = fid(7);
943 let fb = chain(&[10, 20]);
944 assert_eq!(slot_font_id(None, primary, &fb), fid(7));
945 assert_eq!(slot_font_id(Some(0), primary, &fb), fid(10));
946 assert_eq!(slot_font_id(Some(1), primary, &fb), fid(20));
947 }
948
949 #[test]
950 fn run_spans_with_no_chain_emit_one_primary_span() {
951 let primary = fid(0);
952 let fb: SmallVec<[(FontId, SharedString); 4]> = SmallVec::new();
953 let covers = |_: FontId, _: char| false;
954 let text = "测试test";
955 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
956 assert_eq!(spans.as_slice(), &[span(0, text.len(), None, primary)]);
957 }
958
959 #[test]
960 fn run_spans_use_byte_offsets_for_multibyte_chars() {
961 let primary = fid(0);
962 let fb = chain(&[1]);
963 let covers = |id: FontId, ch: char| {
965 if id == primary {
966 ch.is_ascii()
967 } else {
968 !ch.is_ascii()
969 }
970 };
971 let text = "测试test";
972 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
973 assert_eq!(
975 spans.as_slice(),
976 &[
977 span(0, 1, None, primary),
978 span(1, 4, Some(0), fid(1)),
979 span(4, 5, None, primary),
980 ]
981 );
982 }
983
984 #[test]
985 fn run_spans_respect_run_offset() {
986 let primary = fid(0);
987 let fb = chain(&[1]);
988 let covers = |id: FontId, ch: char| {
989 if id == primary {
990 ch.is_ascii()
991 } else {
992 !ch.is_ascii()
993 }
994 };
995 let text = "测试test";
997 let run_offset = 2;
998 let run_len = text.len() - run_offset;
999 let spans = compute_run_spans(text, run_offset, run_len, primary, &fb, &covers);
1000 assert_eq!(
1001 spans.as_slice(),
1002 &[span(2, 5, Some(0), fid(1)), span(5, 6, None, primary)]
1003 );
1004 }
1005
1006 #[test]
1007 fn run_spans_keep_combining_marks_with_base_in_fallback() {
1008 let primary = fid(0);
1009 let fb = chain(&[1]);
1010 let covers = |id: FontId, ch: char| {
1014 if id == primary {
1015 ch.is_ascii()
1016 } else {
1017 ch == '\u{0905}'
1018 }
1019 };
1020 let text = "测试test";
1022 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1023 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1024 }
1025
1026 #[test]
1027 fn run_spans_keep_zwj_inside_emoji_cluster() {
1028 let primary = fid(0);
1029 let fb = chain(&[1]);
1030 let covers = |id: FontId, ch: char| id == fid(1) && ch != '\u{200D}';
1032 let text = "测试test";
1034 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1035 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1036 }
1037
1038 #[test]
1039 fn run_spans_collapse_adjacent_same_slot() {
1040 let primary = fid(0);
1041 let fb = chain(&[1]);
1042 let covers = |id: FontId, ch: char| {
1043 if id == primary {
1044 ch.is_ascii()
1045 } else {
1046 !ch.is_ascii()
1047 }
1048 };
1049 let text = "测试test";
1050 let spans = compute_run_spans(text, 0, text.len(), primary, &fb, &covers);
1051 assert_eq!(spans.as_slice(), &[span(0, text.len(), Some(0), fid(1))]);
1052 }
1053
1054 #[test]
1055 fn run_spans_empty_run_returns_no_spans() {
1056 let primary = fid(0);
1057 let fb = chain(&[1]);
1058 let covers = |_: FontId, _: char| true;
1059 let spans = compute_run_spans("anything", 3, 0, primary, &fb, &covers);
1060 assert!(spans.is_empty());
1061 }
1062}