1use std::{
2 collections::HashMap,
3 sync::{Arc, Mutex},
4};
5
6use cosmic_text::{Attrs, Family, FeatureTag, FontSystem, Metrics, Stretch, Style, Weight, fontdb};
7use sui_core::{Error, FontHandle, Rect, Result};
8use ttf_parser::GlyphId;
9
10use crate::model::{FontFamilyStack, TextSpanId, TextStyle};
11use crate::style::{FontFeatures, FontStretch, FontStyle, FontWeight};
12
13pub(crate) fn to_cosmic_weight(weight: FontWeight) -> Weight {
16 Weight(weight.value())
17}
18
19pub(crate) fn to_cosmic_style(style: FontStyle) -> Style {
20 match style {
21 FontStyle::Normal => Style::Normal,
22 FontStyle::Italic => Style::Italic,
23 FontStyle::Oblique => Style::Oblique,
24 }
25}
26
27pub(crate) fn to_cosmic_stretch(stretch: FontStretch) -> Stretch {
28 match stretch {
29 FontStretch::UltraCondensed => Stretch::UltraCondensed,
30 FontStretch::ExtraCondensed => Stretch::ExtraCondensed,
31 FontStretch::Condensed => Stretch::Condensed,
32 FontStretch::SemiCondensed => Stretch::SemiCondensed,
33 FontStretch::Normal => Stretch::Normal,
34 FontStretch::SemiExpanded => Stretch::SemiExpanded,
35 FontStretch::Expanded => Stretch::Expanded,
36 FontStretch::ExtraExpanded => Stretch::ExtraExpanded,
37 FontStretch::UltraExpanded => Stretch::UltraExpanded,
38 }
39}
40
41pub(crate) fn to_cosmic_features(features: &FontFeatures) -> cosmic_text::FontFeatures {
42 let mut out = cosmic_text::FontFeatures::new();
43 for feature in features.iter() {
44 out.set(FeatureTag::new(&feature.tag), feature.value);
45 }
46 out
47}
48
49#[cfg(test)]
50mod attrs_mapping_tests {
51 use super::*;
52 use crate::style::FontFeature;
53
54 #[test]
55 fn weight_maps_to_cosmic_weight() {
56 assert_eq!(to_cosmic_weight(FontWeight::NORMAL), Weight(400));
57 assert_eq!(to_cosmic_weight(FontWeight::BOLD), Weight(700));
58 assert_eq!(to_cosmic_weight(FontWeight::new(550)), Weight(550));
59 }
60
61 #[test]
62 fn style_maps_to_cosmic_style() {
63 assert_eq!(to_cosmic_style(FontStyle::Normal), Style::Normal);
64 assert_eq!(to_cosmic_style(FontStyle::Italic), Style::Italic);
65 assert_eq!(to_cosmic_style(FontStyle::Oblique), Style::Oblique);
66 }
67
68 #[test]
69 fn stretch_maps_to_cosmic_stretch() {
70 assert_eq!(to_cosmic_stretch(FontStretch::Normal), Stretch::Normal);
71 assert_eq!(
72 to_cosmic_stretch(FontStretch::Condensed),
73 Stretch::Condensed
74 );
75 assert_eq!(
76 to_cosmic_stretch(FontStretch::UltraExpanded),
77 Stretch::UltraExpanded
78 );
79 }
80
81 #[test]
82 fn features_map_to_cosmic_features_preserving_tag_value_and_order() {
83 let mut features = FontFeatures::new();
84 features
85 .disable(FontFeature::STANDARD_LIGATURES)
86 .enable(FontFeature::SMALL_CAPS);
87
88 let mut expected = cosmic_text::FontFeatures::new();
89 expected.set(FeatureTag::new(b"liga"), 0);
90 expected.set(FeatureTag::new(b"smcp"), 1);
91
92 assert_eq!(to_cosmic_features(&features), expected);
93 assert_eq!(
94 to_cosmic_features(&FontFeatures::new()),
95 cosmic_text::FontFeatures::new()
96 );
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct RegisteredFont {
102 data: Arc<[u8]>,
103 face_index: u32,
104}
105
106impl RegisteredFont {
107 pub fn from_bytes(data: impl Into<Vec<u8>>) -> Self {
108 Self {
109 data: Arc::<[u8]>::from(data.into()),
110 face_index: 0,
111 }
112 }
113
114 pub const fn with_face_index(mut self, face_index: u32) -> Self {
115 self.face_index = face_index;
116 self
117 }
118
119 pub fn bytes(&self) -> &[u8] {
120 &self.data
121 }
122
123 pub fn shared_bytes(&self) -> Arc<[u8]> {
124 Arc::clone(&self.data)
125 }
126
127 pub fn data_ptr(&self) -> usize {
128 self.data.as_ptr() as usize
129 }
130
131 pub fn data_len(&self) -> usize {
132 self.data.len()
133 }
134
135 pub const fn face_index(&self) -> u32 {
136 self.face_index
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Default)]
141pub struct FontRegistry {
142 pub(crate) fonts: HashMap<FontHandle, RegisteredFont>,
143}
144
145impl FontRegistry {
146 pub fn new() -> Self {
147 Self::default()
148 }
149
150 pub fn insert(&mut self, handle: FontHandle, font: RegisteredFont) -> Option<RegisteredFont> {
151 self.fonts.insert(handle, font)
152 }
153
154 pub fn get(&self, handle: FontHandle) -> Option<&RegisteredFont> {
155 self.fonts.get(&handle)
156 }
157
158 pub fn contains(&self, handle: FontHandle) -> bool {
159 self.fonts.contains_key(&handle)
160 }
161
162 pub fn len(&self) -> usize {
163 self.fonts.len()
164 }
165
166 pub fn is_empty(&self) -> bool {
167 self.fonts.is_empty()
168 }
169
170 pub(crate) fn cache_key(&self) -> Vec<(FontHandle, FaceCacheKey)> {
171 let mut key = self
174 .fonts
175 .iter()
176 .map(|(handle, font)| (*handle, FaceCacheKey::from_registered_font(font)))
177 .collect::<Vec<_>>();
178 key.sort_unstable_by_key(|(handle, _)| *handle);
179 key
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct ResolvedTextFace {
185 data: Arc<[u8]>,
186 face_index: u32,
187}
188
189impl ResolvedTextFace {
190 pub fn from_bytes(data: Arc<[u8]>, face_index: u32) -> Self {
191 Self { data, face_index }
192 }
193
194 pub fn bytes(&self) -> &[u8] {
195 &self.data
196 }
197
198 pub fn data_ptr(&self) -> usize {
199 self.data.as_ptr() as usize
200 }
201
202 pub fn data_len(&self) -> usize {
203 self.data.len()
204 }
205
206 pub fn shared_bytes(&self) -> Arc<[u8]> {
207 Arc::clone(&self.data)
208 }
209
210 pub const fn face_index(&self) -> u32 {
211 self.face_index
212 }
213
214 pub(crate) fn glyph_bounds(
215 &self,
216 glyph_id: u16,
217 origin_x: f32,
218 origin_y: f32,
219 scale: f32,
220 ) -> Option<Rect> {
221 let face = ttf_parser::Face::parse(self.bytes(), self.face_index()).ok()?;
222 face.glyph_bounding_box(GlyphId(glyph_id)).map(|bbox| {
223 let min_x = origin_x + (f32::from(bbox.x_min) * scale);
224 let max_x = origin_x + (f32::from(bbox.x_max) * scale);
225 let min_y = origin_y - (f32::from(bbox.y_max) * scale);
226 let max_y = origin_y - (f32::from(bbox.y_min) * scale);
227 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
228 })
229 }
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233pub(crate) struct FaceCacheKey {
234 data_ptr: usize,
235 data_len: usize,
236 face_index: u32,
237}
238
239impl FaceCacheKey {
240 pub(crate) fn new(face: &ResolvedTextFace) -> Self {
241 Self {
242 data_ptr: face.data_ptr(),
243 data_len: face.data_len(),
244 face_index: face.face_index(),
245 }
246 }
247
248 pub(crate) fn from_registered_font(font: &RegisteredFont) -> Self {
249 Self {
250 data_ptr: font.data_ptr(),
251 data_len: font.data_len(),
252 face_index: font.face_index(),
253 }
254 }
255}
256
257#[derive(Debug, Clone)]
258pub(crate) struct ResolvedSpanInput {
259 pub id: TextSpanId,
260 pub text: String,
261 pub style: TextStyle,
262 pub family_name: Option<String>,
263}
264
265#[derive(Debug, Clone)]
266struct ExplicitFontSpec {
267 family_name: String,
268}
269
270#[derive(Debug)]
271pub(crate) struct FontContext {
272 pub font_system: FontSystem,
273 default_face: ResolvedTextFace,
274 explicit_fonts: HashMap<FontHandle, ExplicitFontSpec>,
275 explicit_faces: HashMap<fontdb::ID, ResolvedTextFace>,
276 shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
277}
278
279impl FontContext {
280 pub(crate) fn resolve_span(
281 &self,
282 span_id: TextSpanId,
283 text: String,
284 style: &TextStyle,
285 ) -> Result<ResolvedSpanInput> {
286 let family_name = if let Some(handle) = style.font {
287 let spec = self.explicit_fonts.get(&handle).ok_or_else(|| {
288 Error::new(format!("font handle {} is not registered", handle.get()))
289 })?;
290 Some(spec.family_name.clone())
291 } else if let Some(families) = style.font_families {
292 resolve_font_family_name(self.font_system.db(), families, style)
293 } else {
294 None
295 };
296
297 Ok(ResolvedSpanInput {
298 id: span_id,
299 text,
300 style: style.clone(),
301 family_name,
302 })
303 }
304
305 pub(crate) fn attrs_for_span<'a>(span: &'a ResolvedSpanInput, metadata: usize) -> Attrs<'a> {
306 let text_style = &span.style;
307 let mut attrs = Attrs::new()
308 .metrics(Metrics::new(text_style.font_size, text_style.line_height))
309 .metadata(metadata)
310 .weight(to_cosmic_weight(text_style.weight))
311 .style(to_cosmic_style(text_style.style))
312 .stretch(to_cosmic_stretch(text_style.stretch));
313 if !text_style.features.is_empty() {
314 attrs = attrs.font_features(to_cosmic_features(&text_style.features));
315 }
316
317 match span.family_name.as_deref() {
318 Some(name) => attrs.family(Family::Name(name)),
319 None => attrs,
320 }
321 }
322
323 pub(crate) fn resolve_face_index(
324 &self,
325 face_slots: &mut HashMap<fontdb::ID, usize>,
326 faces: &mut Vec<ResolvedTextFace>,
327 font_id: fontdb::ID,
328 ) -> Result<usize> {
329 if let Some(index) = face_slots.get(&font_id) {
330 return Ok(*index);
331 }
332
333 let face = self.resolve_face(font_id)?;
334 let index = faces.len();
335 faces.push(face);
336 face_slots.insert(font_id, index);
337 Ok(index)
338 }
339
340 pub(crate) fn resolve_face(&self, font_id: fontdb::ID) -> Result<ResolvedTextFace> {
341 if let Some(face) = self.explicit_faces.get(&font_id).cloned() {
342 return Ok(face);
343 }
344
345 if let Some(face) = self
346 .shared_faces
347 .lock()
348 .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
349 .get(&font_id)
350 .cloned()
351 {
352 return Ok(face);
353 }
354
355 let face = self
356 .font_system
357 .db()
358 .with_face_data(font_id, |font_data, face_index| {
359 ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
360 })
361 .ok_or_else(|| {
362 Error::new("failed to access font face data from cosmic-text database")
363 })?;
364
365 self.shared_faces
366 .lock()
367 .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
368 .insert(font_id, face.clone());
369
370 Ok(face)
371 }
372
373 pub(crate) fn default_face(&self) -> &ResolvedTextFace {
374 &self.default_face
375 }
376}
377
378#[derive(Debug)]
379pub(crate) struct TextSystemState {
380 locale: String,
381 font_db: fontdb::Database,
382 default_face: ResolvedTextFace,
383 default_face_key: FaceCacheKey,
384 shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
385}
386
387impl TextSystemState {
388 pub(crate) fn new() -> Result<Self> {
389 let locale = String::from("en-US");
390 let mut font_db = fontdb::Database::new();
391 font_db.load_system_fonts();
392 load_bundled_fallback_fonts(&mut font_db);
393 configure_platform_generic_families(&mut font_db);
394
395 let families = [fontdb::Family::SansSerif];
396 let default_font = font_db
397 .query(&fontdb::Query {
398 families: &families,
399 weight: fontdb::Weight::NORMAL,
400 stretch: fontdb::Stretch::Normal,
401 style: fontdb::Style::Normal,
402 })
403 .or_else(|| font_db.faces().next().map(|face| face.id))
404 .ok_or_else(|| Error::new("failed to locate a font for text rendering"))?;
405
406 let default_face = font_db
407 .with_face_data(default_font, |font_data, face_index| {
408 ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
409 })
410 .ok_or_else(|| Error::new("failed to access fallback system font data"))?;
411 let mut shared_faces = HashMap::new();
412 shared_faces.insert(default_font, default_face.clone());
413
414 Ok(Self {
415 locale,
416 font_db,
417 default_face_key: FaceCacheKey::new(&default_face),
418 default_face,
419 shared_faces: Arc::new(Mutex::new(shared_faces)),
420 })
421 }
422
423 pub(crate) fn default_face_key(&self) -> FaceCacheKey {
424 self.default_face_key
425 }
426
427 pub(crate) fn build_font_context(&self, font_registry: &FontRegistry) -> Result<FontContext> {
428 let mut font_db = self.font_db.clone();
429 let mut explicit_fonts = HashMap::new();
430 let mut explicit_faces = HashMap::new();
431
432 for (handle, font) in &font_registry.fonts {
433 let ids =
434 font_db.load_font_source(fontdb::Source::Binary(Arc::new(font.bytes().to_vec())));
435 let mut family_name = None;
436 for id in ids {
437 let face_info = font_db.face(id).ok_or_else(|| {
438 Error::new("failed to register custom font face in text database")
439 })?;
440 explicit_faces.insert(
441 id,
442 ResolvedTextFace::from_bytes(font.shared_bytes(), face_info.index),
443 );
444
445 if face_info.index == font.face_index() {
446 family_name = Some(
447 face_info
448 .families
449 .first()
450 .map(|(name, _language)| name.clone())
451 .unwrap_or_else(|| face_info.post_script_name.clone()),
452 );
453 }
454 }
455
456 let family_name = family_name.ok_or_else(|| {
457 Error::new("failed to register custom font face in text database")
458 })?;
459 explicit_fonts.insert(*handle, ExplicitFontSpec { family_name });
460 }
461
462 let font_system = FontSystem::new_with_locale_and_db(self.locale.clone(), font_db);
463 Ok(FontContext {
464 font_system,
465 default_face: self.default_face.clone(),
466 explicit_fonts,
467 explicit_faces,
468 shared_faces: Arc::clone(&self.shared_faces),
469 })
470 }
471}
472
473fn resolve_font_family_name(
474 font_db: &fontdb::Database,
475 stack: FontFamilyStack,
476 style: &TextStyle,
477) -> Option<String> {
478 let families = stack.iter().map(fontdb_family).collect::<Vec<_>>();
479 let font_id = font_db.query(&fontdb::Query {
480 families: &families,
481 weight: Weight(style.weight.value()),
482 stretch: to_cosmic_stretch(style.stretch),
483 style: to_cosmic_style(style.style),
484 })?;
485 let face = font_db.face(font_id)?;
486 face.families
487 .first()
488 .map(|(name, _language)| name.clone())
489 .or_else(|| (!face.post_script_name.is_empty()).then(|| face.post_script_name.clone()))
490}
491
492fn fontdb_family(name: &str) -> Family<'_> {
493 if name.eq_ignore_ascii_case("ui-sans-serif")
494 || name.eq_ignore_ascii_case("system-ui")
495 || name.eq_ignore_ascii_case("-apple-system")
496 || name.eq_ignore_ascii_case("BlinkMacSystemFont")
497 || name.eq_ignore_ascii_case("sans-serif")
498 {
499 Family::SansSerif
500 } else if name.eq_ignore_ascii_case("ui-serif") || name.eq_ignore_ascii_case("serif") {
501 Family::Serif
502 } else if name.eq_ignore_ascii_case("ui-monospace") || name.eq_ignore_ascii_case("monospace") {
503 Family::Monospace
504 } else if name.eq_ignore_ascii_case("cursive") {
505 Family::Cursive
506 } else if name.eq_ignore_ascii_case("fantasy") {
507 Family::Fantasy
508 } else {
509 Family::Name(name)
510 }
511}
512
513#[cfg(target_os = "windows")]
514const PLATFORM_SANS_FAMILIES: &[&str] = &["Segoe UI Variable Text", "Segoe UI", "Arial"];
515#[cfg(target_os = "windows")]
516const PLATFORM_SERIF_FAMILIES: &[&str] = &["Cambria", "Georgia", "Times New Roman"];
517#[cfg(target_os = "windows")]
518const PLATFORM_MONO_FAMILIES: &[&str] =
519 &["Cascadia Mono", "Cascadia Code", "Consolas", "Courier New"];
520
521#[cfg(target_os = "macos")]
522const PLATFORM_SANS_FAMILIES: &[&str] =
523 &["SF Pro Text", "SF Pro Display", "Helvetica Neue", "Arial"];
524#[cfg(target_os = "macos")]
525const PLATFORM_SERIF_FAMILIES: &[&str] = &["New York", "Times New Roman", "Georgia"];
526#[cfg(target_os = "macos")]
527const PLATFORM_MONO_FAMILIES: &[&str] = &["SFMono-Regular", "SF Mono", "Menlo", "Monaco"];
528
529#[cfg(all(
530 target_arch = "wasm32",
531 not(any(target_os = "windows", target_os = "macos"))
532))]
533const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans"];
534#[cfg(all(
535 target_arch = "wasm32",
536 not(any(target_os = "windows", target_os = "macos"))
537))]
538const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif"];
539#[cfg(all(
540 target_arch = "wasm32",
541 not(any(target_os = "windows", target_os = "macos"))
542))]
543const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono"];
544
545#[cfg(all(
546 not(target_arch = "wasm32"),
547 not(any(target_os = "windows", target_os = "macos"))
548))]
549const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans", "Inter", "DejaVu Sans", "Liberation Sans"];
550#[cfg(all(
551 not(target_arch = "wasm32"),
552 not(any(target_os = "windows", target_os = "macos"))
553))]
554const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "DejaVu Serif", "Liberation Serif"];
555#[cfg(all(
556 not(target_arch = "wasm32"),
557 not(any(target_os = "windows", target_os = "macos"))
558))]
559const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono", "DejaVu Sans Mono", "Liberation Mono"];
560
561fn configure_platform_generic_families(font_db: &mut fontdb::Database) {
562 if let Some(family) = first_installed_family(font_db, PLATFORM_SANS_FAMILIES) {
563 font_db.set_sans_serif_family(family);
564 }
565 if let Some(family) = first_installed_family(font_db, PLATFORM_SERIF_FAMILIES) {
566 font_db.set_serif_family(family);
567 }
568 if let Some(family) = first_installed_family(font_db, PLATFORM_MONO_FAMILIES) {
569 font_db.set_monospace_family(family);
570 }
571}
572
573fn first_installed_family(font_db: &fontdb::Database, candidates: &[&str]) -> Option<String> {
574 candidates.iter().find_map(|candidate| {
575 font_db.faces().find_map(|face| {
576 face.families.iter().find_map(|(family, _language)| {
577 family
578 .eq_ignore_ascii_case(candidate)
579 .then(|| family.clone())
580 })
581 })
582 })
583}
584
585#[cfg(any(target_arch = "wasm32", target_os = "android"))]
586fn load_bundled_fallback_fonts(font_db: &mut fontdb::Database) {
587 load_bundled_portable_fallback_fonts(font_db);
588}
589
590#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
591fn load_bundled_portable_fallback_fonts(font_db: &mut fontdb::Database) {
592 let sans_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
593 include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
594 )));
595 let _ = set_sans_serif_family_from_loaded_faces(font_db, &sans_ids);
596
597 let serif_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
598 include_bytes!("../assets/NotoSerif-Variable.ttf").to_vec(),
599 )));
600 let _ = set_serif_family_from_loaded_faces(font_db, &serif_ids);
601
602 let mono_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
603 include_bytes!("../assets/NotoSansMono-Variable.ttf").to_vec(),
604 )));
605 let _ = set_monospace_family_from_loaded_faces(font_db, &mono_ids);
606}
607
608#[cfg(not(any(target_arch = "wasm32", target_os = "android")))]
609fn load_bundled_fallback_fonts(_font_db: &mut fontdb::Database) {}
610
611#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
612fn set_sans_serif_family_from_loaded_faces(
613 font_db: &mut fontdb::Database,
614 ids: &[fontdb::ID],
615) -> Option<String> {
616 let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans")?;
617 font_db.set_sans_serif_family(name.clone());
618 Some(name)
619}
620
621#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
622fn set_serif_family_from_loaded_faces(
623 font_db: &mut fontdb::Database,
624 ids: &[fontdb::ID],
625) -> Option<String> {
626 let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Serif")?;
627 font_db.set_serif_family(name.clone());
628 Some(name)
629}
630
631#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
632fn set_monospace_family_from_loaded_faces(
633 font_db: &mut fontdb::Database,
634 ids: &[fontdb::ID],
635) -> Option<String> {
636 let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans Mono")?;
637 font_db.set_monospace_family(name.clone());
638 Some(name)
639}
640
641#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
642fn preferred_family_from_loaded_faces(
643 font_db: &fontdb::Database,
644 ids: &[fontdb::ID],
645 preferred: &str,
646) -> Option<String> {
647 let mut fallback = None;
648 for id in ids {
649 let Some(face_info) = font_db.face(*id) else {
650 continue;
651 };
652 for (name, _language) in &face_info.families {
653 if name.eq_ignore_ascii_case(preferred) {
654 return Some(name.clone());
655 }
656 fallback.get_or_insert_with(|| name.clone());
657 }
658 if fallback.is_none() && !face_info.post_script_name.is_empty() {
659 fallback = Some(face_info.post_script_name.clone());
660 }
661 }
662
663 fallback
664}
665
666#[cfg(test)]
667mod font_database_tests {
668 use super::*;
669
670 #[test]
671 fn bundled_web_sans_font_becomes_generic_sans_serif() {
672 let mut font_db = fontdb::Database::new();
673 let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
674 include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
675 )));
676
677 let family_name = set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
678 .expect("bundled sans font should expose a family name");
679
680 assert_eq!(family_name, "Noto Sans");
681 assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
682
683 let families = [fontdb::Family::SansSerif];
684 let font_id = font_db
685 .query(&fontdb::Query {
686 families: &families,
687 weight: fontdb::Weight::NORMAL,
688 stretch: fontdb::Stretch::Normal,
689 style: fontdb::Style::Normal,
690 })
691 .expect("generic sans-serif should resolve to bundled font");
692 let face = font_db
693 .face(font_id)
694 .expect("resolved bundled font face should still be registered");
695 assert!(face.families.iter().any(|(name, _)| name == "Noto Sans"));
696 }
697
698 #[test]
699 fn bundled_portable_fonts_resolve_all_theme_generic_stacks_on_native_tests() {
700 let mut font_db = fontdb::Database::new();
701 load_bundled_portable_fallback_fonts(&mut font_db);
702 configure_platform_generic_families(&mut font_db);
703
704 assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
705 assert_eq!(font_db.family_name(&fontdb::Family::Serif), "Noto Serif");
706 assert_eq!(
707 font_db.family_name(&fontdb::Family::Monospace),
708 "Noto Sans Mono"
709 );
710
711 let cases = [
712 (
713 FontFamilyStack::new("ui-sans-serif", &["system-ui", "sans-serif"]),
714 "Noto Sans",
715 ),
716 (
717 FontFamilyStack::new("ui-serif", &["Georgia", "serif"]),
718 "Noto Serif",
719 ),
720 (
721 FontFamilyStack::new("ui-monospace", &["Consolas", "monospace"]),
722 "Noto Sans Mono",
723 ),
724 ];
725
726 for (stack, expected) in cases {
727 let style = TextStyle {
728 font_families: Some(stack),
729 ..TextStyle::default()
730 };
731 let resolved = resolve_font_family_name(&font_db, stack, &style);
732 assert_eq!(resolved.as_deref(), Some(expected));
733
734 let font_id = font_db
735 .query(&fontdb::Query {
736 families: &[fontdb_family(stack.primary)],
737 weight: fontdb::Weight::NORMAL,
738 stretch: fontdb::Stretch::Normal,
739 style: fontdb::Style::Normal,
740 })
741 .expect("bundled generic family should resolve to an actual face");
742 let face = font_db
743 .face(font_id)
744 .expect("resolved bundled face should remain registered");
745 assert!(face.families.iter().any(|(name, _)| name == expected));
746 assert!(
747 font_db
748 .with_face_data(font_id, |data, _index| !data.is_empty())
749 .unwrap_or(false),
750 "resolved {expected} face should expose font bytes"
751 );
752 }
753 }
754
755 #[test]
756 fn theme_family_stack_resolves_generic_alias_after_missing_family() {
757 let mut font_db = fontdb::Database::new();
758 let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
759 include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
760 )));
761 set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
762 .expect("bundled sans font should expose a family name");
763 let style = TextStyle {
764 font_families: Some(FontFamilyStack::new(
765 "Missing UI Family",
766 &["system-ui", "sans-serif"],
767 )),
768 ..TextStyle::default()
769 };
770
771 assert_eq!(
772 resolve_font_family_name(
773 &font_db,
774 style.font_families.expect("test family stack"),
775 &style,
776 )
777 .as_deref(),
778 Some("Noto Sans")
779 );
780 }
781
782 #[test]
783 fn platform_family_preference_uses_first_installed_candidate() {
784 let mut font_db = fontdb::Database::new();
785 font_db.load_font_source(fontdb::Source::Binary(Arc::new(
786 include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
787 )));
788
789 assert_eq!(
790 first_installed_family(&font_db, &["Missing UI Family", "Noto Sans"]).as_deref(),
791 Some("Noto Sans")
792 );
793 }
794
795 #[cfg(target_os = "windows")]
796 #[test]
797 fn windows_generic_sans_prefers_the_first_installed_ui_family() {
798 let mut font_db = fontdb::Database::new();
799 font_db.load_system_fonts();
800 let expected = first_installed_family(&font_db, PLATFORM_SANS_FAMILIES)
801 .expect("Windows should provide at least one supported UI font");
802
803 configure_platform_generic_families(&mut font_db);
804
805 assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), expected);
806 }
807}