Skip to main content

sui_text/
font.rs

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
13/// Map sui-text's `FontWeight` to cosmic-text's `Weight` (drives bold-face selection and, for
14/// variable fonts, the `wght` shaping instance).
15pub(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
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct ResolvedTextFace {
173    data: Arc<[u8]>,
174    face_index: u32,
175}
176
177impl ResolvedTextFace {
178    pub fn from_bytes(data: Arc<[u8]>, face_index: u32) -> Self {
179        Self { data, face_index }
180    }
181
182    pub fn bytes(&self) -> &[u8] {
183        &self.data
184    }
185
186    pub fn data_ptr(&self) -> usize {
187        self.data.as_ptr() as usize
188    }
189
190    pub fn data_len(&self) -> usize {
191        self.data.len()
192    }
193
194    pub fn shared_bytes(&self) -> Arc<[u8]> {
195        Arc::clone(&self.data)
196    }
197
198    pub const fn face_index(&self) -> u32 {
199        self.face_index
200    }
201
202    pub(crate) fn glyph_bounds(
203        &self,
204        glyph_id: u16,
205        origin_x: f32,
206        origin_y: f32,
207        scale: f32,
208    ) -> Option<Rect> {
209        let face = ttf_parser::Face::parse(self.bytes(), self.face_index()).ok()?;
210        face.glyph_bounding_box(GlyphId(glyph_id)).map(|bbox| {
211            let min_x = origin_x + (f32::from(bbox.x_min) * scale);
212            let max_x = origin_x + (f32::from(bbox.x_max) * scale);
213            let min_y = origin_y - (f32::from(bbox.y_max) * scale);
214            let max_y = origin_y - (f32::from(bbox.y_min) * scale);
215            Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
216        })
217    }
218}
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
221pub(crate) struct FaceCacheKey {
222    data_ptr: usize,
223    data_len: usize,
224    face_index: u32,
225}
226
227impl FaceCacheKey {
228    pub(crate) fn new(face: &ResolvedTextFace) -> Self {
229        Self {
230            data_ptr: face.data_ptr(),
231            data_len: face.data_len(),
232            face_index: face.face_index(),
233        }
234    }
235
236    pub(crate) fn from_registered_font(font: &RegisteredFont) -> Self {
237        Self {
238            data_ptr: font.data_ptr(),
239            data_len: font.data_len(),
240            face_index: font.face_index(),
241        }
242    }
243}
244
245#[derive(Debug, Clone)]
246pub(crate) struct ResolvedSpanInput {
247    pub id: TextSpanId,
248    pub text: String,
249    pub style: TextStyle,
250    pub family_name: Option<String>,
251}
252
253#[derive(Debug, Clone)]
254struct ExplicitFontSpec {
255    family_name: String,
256}
257
258#[derive(Debug)]
259pub(crate) struct FontContext {
260    pub font_system: FontSystem,
261    default_face: ResolvedTextFace,
262    explicit_fonts: HashMap<FontHandle, ExplicitFontSpec>,
263    explicit_faces: HashMap<fontdb::ID, ResolvedTextFace>,
264    shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
265}
266
267impl FontContext {
268    pub(crate) fn resolve_span(
269        &self,
270        span_id: TextSpanId,
271        text: String,
272        style: &TextStyle,
273    ) -> Result<ResolvedSpanInput> {
274        let family_name = if let Some(handle) = style.font {
275            let spec = self.explicit_fonts.get(&handle).ok_or_else(|| {
276                Error::new(format!("font handle {} is not registered", handle.get()))
277            })?;
278            Some(spec.family_name.clone())
279        } else if let Some(families) = style.font_families {
280            resolve_font_family_name(self.font_system.db(), families, style)
281        } else {
282            None
283        };
284
285        Ok(ResolvedSpanInput {
286            id: span_id,
287            text,
288            style: style.clone(),
289            family_name,
290        })
291    }
292
293    pub(crate) fn attrs_for_span<'a>(span: &'a ResolvedSpanInput, metadata: usize) -> Attrs<'a> {
294        let text_style = &span.style;
295        let mut attrs = Attrs::new()
296            .metrics(Metrics::new(text_style.font_size, text_style.line_height))
297            .metadata(metadata)
298            .weight(to_cosmic_weight(text_style.weight))
299            .style(to_cosmic_style(text_style.style))
300            .stretch(to_cosmic_stretch(text_style.stretch));
301        if !text_style.features.is_empty() {
302            attrs = attrs.font_features(to_cosmic_features(&text_style.features));
303        }
304
305        match span.family_name.as_deref() {
306            Some(name) => attrs.family(Family::Name(name)),
307            None => attrs,
308        }
309    }
310
311    pub(crate) fn resolve_face_index(
312        &self,
313        face_slots: &mut HashMap<fontdb::ID, usize>,
314        faces: &mut Vec<ResolvedTextFace>,
315        font_id: fontdb::ID,
316    ) -> Result<usize> {
317        if let Some(index) = face_slots.get(&font_id) {
318            return Ok(*index);
319        }
320
321        let face = self.resolve_face(font_id)?;
322        let index = faces.len();
323        faces.push(face);
324        face_slots.insert(font_id, index);
325        Ok(index)
326    }
327
328    pub(crate) fn resolve_face(&self, font_id: fontdb::ID) -> Result<ResolvedTextFace> {
329        if let Some(face) = self.explicit_faces.get(&font_id).cloned() {
330            return Ok(face);
331        }
332
333        if let Some(face) = self
334            .shared_faces
335            .lock()
336            .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
337            .get(&font_id)
338            .cloned()
339        {
340            return Ok(face);
341        }
342
343        let face = self
344            .font_system
345            .db()
346            .with_face_data(font_id, |font_data, face_index| {
347                ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
348            })
349            .ok_or_else(|| {
350                Error::new("failed to access font face data from cosmic-text database")
351            })?;
352
353        self.shared_faces
354            .lock()
355            .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
356            .insert(font_id, face.clone());
357
358        Ok(face)
359    }
360
361    pub(crate) fn default_face(&self) -> &ResolvedTextFace {
362        &self.default_face
363    }
364}
365
366#[derive(Debug)]
367pub(crate) struct TextSystemState {
368    locale: String,
369    font_db: fontdb::Database,
370    default_face: ResolvedTextFace,
371    default_face_key: FaceCacheKey,
372    shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
373}
374
375impl TextSystemState {
376    pub(crate) fn new() -> Result<Self> {
377        let locale = String::from("en-US");
378        let mut font_db = fontdb::Database::new();
379        font_db.load_system_fonts();
380        load_bundled_fallback_fonts(&mut font_db);
381        configure_platform_generic_families(&mut font_db);
382
383        let families = [fontdb::Family::SansSerif];
384        let default_font = font_db
385            .query(&fontdb::Query {
386                families: &families,
387                weight: fontdb::Weight::NORMAL,
388                stretch: fontdb::Stretch::Normal,
389                style: fontdb::Style::Normal,
390            })
391            .or_else(|| font_db.faces().next().map(|face| face.id))
392            .ok_or_else(|| Error::new("failed to locate a font for text rendering"))?;
393
394        let default_face = font_db
395            .with_face_data(default_font, |font_data, face_index| {
396                ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
397            })
398            .ok_or_else(|| Error::new("failed to access fallback system font data"))?;
399        let mut shared_faces = HashMap::new();
400        shared_faces.insert(default_font, default_face.clone());
401
402        Ok(Self {
403            locale,
404            font_db,
405            default_face_key: FaceCacheKey::new(&default_face),
406            default_face,
407            shared_faces: Arc::new(Mutex::new(shared_faces)),
408        })
409    }
410
411    pub(crate) fn default_face_key(&self) -> FaceCacheKey {
412        self.default_face_key
413    }
414
415    pub(crate) fn build_font_context(&self, font_registry: &FontRegistry) -> Result<FontContext> {
416        let mut font_db = self.font_db.clone();
417        let mut explicit_fonts = HashMap::new();
418        let mut explicit_faces = HashMap::new();
419
420        for (handle, font) in &font_registry.fonts {
421            let ids =
422                font_db.load_font_source(fontdb::Source::Binary(Arc::new(font.bytes().to_vec())));
423            let mut family_name = None;
424            for id in ids {
425                let face_info = font_db.face(id).ok_or_else(|| {
426                    Error::new("failed to register custom font face in text database")
427                })?;
428                explicit_faces.insert(
429                    id,
430                    ResolvedTextFace::from_bytes(font.shared_bytes(), face_info.index),
431                );
432
433                if face_info.index == font.face_index() {
434                    family_name = Some(
435                        face_info
436                            .families
437                            .first()
438                            .map(|(name, _language)| name.clone())
439                            .unwrap_or_else(|| face_info.post_script_name.clone()),
440                    );
441                }
442            }
443
444            let family_name = family_name.ok_or_else(|| {
445                Error::new("failed to register custom font face in text database")
446            })?;
447            explicit_fonts.insert(*handle, ExplicitFontSpec { family_name });
448        }
449
450        let font_system = FontSystem::new_with_locale_and_db(self.locale.clone(), font_db);
451        Ok(FontContext {
452            font_system,
453            default_face: self.default_face.clone(),
454            explicit_fonts,
455            explicit_faces,
456            shared_faces: Arc::clone(&self.shared_faces),
457        })
458    }
459}
460
461fn resolve_font_family_name(
462    font_db: &fontdb::Database,
463    stack: FontFamilyStack,
464    style: &TextStyle,
465) -> Option<String> {
466    let families = stack.iter().map(fontdb_family).collect::<Vec<_>>();
467    let font_id = font_db.query(&fontdb::Query {
468        families: &families,
469        weight: Weight(style.weight.value()),
470        stretch: to_cosmic_stretch(style.stretch),
471        style: to_cosmic_style(style.style),
472    })?;
473    let face = font_db.face(font_id)?;
474    face.families
475        .first()
476        .map(|(name, _language)| name.clone())
477        .or_else(|| (!face.post_script_name.is_empty()).then(|| face.post_script_name.clone()))
478}
479
480fn fontdb_family(name: &str) -> Family<'_> {
481    if name.eq_ignore_ascii_case("ui-sans-serif")
482        || name.eq_ignore_ascii_case("system-ui")
483        || name.eq_ignore_ascii_case("-apple-system")
484        || name.eq_ignore_ascii_case("BlinkMacSystemFont")
485        || name.eq_ignore_ascii_case("sans-serif")
486    {
487        Family::SansSerif
488    } else if name.eq_ignore_ascii_case("ui-serif") || name.eq_ignore_ascii_case("serif") {
489        Family::Serif
490    } else if name.eq_ignore_ascii_case("ui-monospace") || name.eq_ignore_ascii_case("monospace") {
491        Family::Monospace
492    } else if name.eq_ignore_ascii_case("cursive") {
493        Family::Cursive
494    } else if name.eq_ignore_ascii_case("fantasy") {
495        Family::Fantasy
496    } else {
497        Family::Name(name)
498    }
499}
500
501#[cfg(target_os = "windows")]
502const PLATFORM_SANS_FAMILIES: &[&str] = &["Segoe UI Variable Text", "Segoe UI", "Arial"];
503#[cfg(target_os = "windows")]
504const PLATFORM_SERIF_FAMILIES: &[&str] = &["Cambria", "Georgia", "Times New Roman"];
505#[cfg(target_os = "windows")]
506const PLATFORM_MONO_FAMILIES: &[&str] =
507    &["Cascadia Mono", "Cascadia Code", "Consolas", "Courier New"];
508
509#[cfg(target_os = "macos")]
510const PLATFORM_SANS_FAMILIES: &[&str] =
511    &["SF Pro Text", "SF Pro Display", "Helvetica Neue", "Arial"];
512#[cfg(target_os = "macos")]
513const PLATFORM_SERIF_FAMILIES: &[&str] = &["New York", "Times New Roman", "Georgia"];
514#[cfg(target_os = "macos")]
515const PLATFORM_MONO_FAMILIES: &[&str] = &["SFMono-Regular", "SF Mono", "Menlo", "Monaco"];
516
517#[cfg(all(
518    target_arch = "wasm32",
519    not(any(target_os = "windows", target_os = "macos"))
520))]
521const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans"];
522#[cfg(all(
523    target_arch = "wasm32",
524    not(any(target_os = "windows", target_os = "macos"))
525))]
526const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif"];
527#[cfg(all(
528    target_arch = "wasm32",
529    not(any(target_os = "windows", target_os = "macos"))
530))]
531const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono"];
532
533#[cfg(all(
534    not(target_arch = "wasm32"),
535    not(any(target_os = "windows", target_os = "macos"))
536))]
537const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans", "Inter", "DejaVu Sans", "Liberation Sans"];
538#[cfg(all(
539    not(target_arch = "wasm32"),
540    not(any(target_os = "windows", target_os = "macos"))
541))]
542const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "DejaVu Serif", "Liberation Serif"];
543#[cfg(all(
544    not(target_arch = "wasm32"),
545    not(any(target_os = "windows", target_os = "macos"))
546))]
547const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono", "DejaVu Sans Mono", "Liberation Mono"];
548
549fn configure_platform_generic_families(font_db: &mut fontdb::Database) {
550    if let Some(family) = first_installed_family(font_db, PLATFORM_SANS_FAMILIES) {
551        font_db.set_sans_serif_family(family);
552    }
553    if let Some(family) = first_installed_family(font_db, PLATFORM_SERIF_FAMILIES) {
554        font_db.set_serif_family(family);
555    }
556    if let Some(family) = first_installed_family(font_db, PLATFORM_MONO_FAMILIES) {
557        font_db.set_monospace_family(family);
558    }
559}
560
561fn first_installed_family(font_db: &fontdb::Database, candidates: &[&str]) -> Option<String> {
562    candidates.iter().find_map(|candidate| {
563        font_db.faces().find_map(|face| {
564            face.families.iter().find_map(|(family, _language)| {
565                family
566                    .eq_ignore_ascii_case(candidate)
567                    .then(|| family.clone())
568            })
569        })
570    })
571}
572
573#[cfg(target_arch = "wasm32")]
574fn load_bundled_fallback_fonts(font_db: &mut fontdb::Database) {
575    load_bundled_wasm_fallback_fonts(font_db);
576}
577
578#[cfg(any(target_arch = "wasm32", test))]
579fn load_bundled_wasm_fallback_fonts(font_db: &mut fontdb::Database) {
580    let sans_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
581        include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
582    )));
583    let _ = set_sans_serif_family_from_loaded_faces(font_db, &sans_ids);
584
585    let serif_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
586        include_bytes!("../assets/NotoSerif-Variable.ttf").to_vec(),
587    )));
588    let _ = set_serif_family_from_loaded_faces(font_db, &serif_ids);
589
590    let mono_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
591        include_bytes!("../assets/NotoSansMono-Variable.ttf").to_vec(),
592    )));
593    let _ = set_monospace_family_from_loaded_faces(font_db, &mono_ids);
594}
595
596#[cfg(not(target_arch = "wasm32"))]
597fn load_bundled_fallback_fonts(_font_db: &mut fontdb::Database) {}
598
599#[cfg(any(target_arch = "wasm32", test))]
600fn set_sans_serif_family_from_loaded_faces(
601    font_db: &mut fontdb::Database,
602    ids: &[fontdb::ID],
603) -> Option<String> {
604    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans")?;
605    font_db.set_sans_serif_family(name.clone());
606    Some(name)
607}
608
609#[cfg(any(target_arch = "wasm32", test))]
610fn set_serif_family_from_loaded_faces(
611    font_db: &mut fontdb::Database,
612    ids: &[fontdb::ID],
613) -> Option<String> {
614    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Serif")?;
615    font_db.set_serif_family(name.clone());
616    Some(name)
617}
618
619#[cfg(any(target_arch = "wasm32", test))]
620fn set_monospace_family_from_loaded_faces(
621    font_db: &mut fontdb::Database,
622    ids: &[fontdb::ID],
623) -> Option<String> {
624    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans Mono")?;
625    font_db.set_monospace_family(name.clone());
626    Some(name)
627}
628
629#[cfg(any(target_arch = "wasm32", test))]
630fn preferred_family_from_loaded_faces(
631    font_db: &fontdb::Database,
632    ids: &[fontdb::ID],
633    preferred: &str,
634) -> Option<String> {
635    let mut fallback = None;
636    for id in ids {
637        let Some(face_info) = font_db.face(*id) else {
638            continue;
639        };
640        for (name, _language) in &face_info.families {
641            if name.eq_ignore_ascii_case(preferred) {
642                return Some(name.clone());
643            }
644            fallback.get_or_insert_with(|| name.clone());
645        }
646        if fallback.is_none() && !face_info.post_script_name.is_empty() {
647            fallback = Some(face_info.post_script_name.clone());
648        }
649    }
650
651    fallback
652}
653
654#[cfg(test)]
655mod font_database_tests {
656    use super::*;
657
658    #[test]
659    fn bundled_web_sans_font_becomes_generic_sans_serif() {
660        let mut font_db = fontdb::Database::new();
661        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
662            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
663        )));
664
665        let family_name = set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
666            .expect("bundled sans font should expose a family name");
667
668        assert_eq!(family_name, "Noto Sans");
669        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
670
671        let families = [fontdb::Family::SansSerif];
672        let font_id = font_db
673            .query(&fontdb::Query {
674                families: &families,
675                weight: fontdb::Weight::NORMAL,
676                stretch: fontdb::Stretch::Normal,
677                style: fontdb::Style::Normal,
678            })
679            .expect("generic sans-serif should resolve to bundled font");
680        let face = font_db
681            .face(font_id)
682            .expect("resolved bundled font face should still be registered");
683        assert!(face.families.iter().any(|(name, _)| name == "Noto Sans"));
684    }
685
686    #[test]
687    fn bundled_wasm_fonts_resolve_all_theme_generic_stacks_on_native_tests() {
688        let mut font_db = fontdb::Database::new();
689        load_bundled_wasm_fallback_fonts(&mut font_db);
690        configure_platform_generic_families(&mut font_db);
691
692        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
693        assert_eq!(font_db.family_name(&fontdb::Family::Serif), "Noto Serif");
694        assert_eq!(
695            font_db.family_name(&fontdb::Family::Monospace),
696            "Noto Sans Mono"
697        );
698
699        let cases = [
700            (
701                FontFamilyStack::new("ui-sans-serif", &["system-ui", "sans-serif"]),
702                "Noto Sans",
703            ),
704            (
705                FontFamilyStack::new("ui-serif", &["Georgia", "serif"]),
706                "Noto Serif",
707            ),
708            (
709                FontFamilyStack::new("ui-monospace", &["Consolas", "monospace"]),
710                "Noto Sans Mono",
711            ),
712        ];
713
714        for (stack, expected) in cases {
715            let style = TextStyle {
716                font_families: Some(stack),
717                ..TextStyle::default()
718            };
719            let resolved = resolve_font_family_name(&font_db, stack, &style);
720            assert_eq!(resolved.as_deref(), Some(expected));
721
722            let font_id = font_db
723                .query(&fontdb::Query {
724                    families: &[fontdb_family(stack.primary)],
725                    weight: fontdb::Weight::NORMAL,
726                    stretch: fontdb::Stretch::Normal,
727                    style: fontdb::Style::Normal,
728                })
729                .expect("bundled generic family should resolve to an actual face");
730            let face = font_db
731                .face(font_id)
732                .expect("resolved bundled face should remain registered");
733            assert!(face.families.iter().any(|(name, _)| name == expected));
734            assert!(
735                font_db
736                    .with_face_data(font_id, |data, _index| !data.is_empty())
737                    .unwrap_or(false),
738                "resolved {expected} face should expose font bytes"
739            );
740        }
741    }
742
743    #[test]
744    fn theme_family_stack_resolves_generic_alias_after_missing_family() {
745        let mut font_db = fontdb::Database::new();
746        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
747            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
748        )));
749        set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
750            .expect("bundled sans font should expose a family name");
751        let style = TextStyle {
752            font_families: Some(FontFamilyStack::new(
753                "Missing UI Family",
754                &["system-ui", "sans-serif"],
755            )),
756            ..TextStyle::default()
757        };
758
759        assert_eq!(
760            resolve_font_family_name(
761                &font_db,
762                style.font_families.expect("test family stack"),
763                &style,
764            )
765            .as_deref(),
766            Some("Noto Sans")
767        );
768    }
769
770    #[test]
771    fn platform_family_preference_uses_first_installed_candidate() {
772        let mut font_db = fontdb::Database::new();
773        font_db.load_font_source(fontdb::Source::Binary(Arc::new(
774            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
775        )));
776
777        assert_eq!(
778            first_installed_family(&font_db, &["Missing UI Family", "Noto Sans"]).as_deref(),
779            Some("Noto Sans")
780        );
781    }
782
783    #[cfg(target_os = "windows")]
784    #[test]
785    fn windows_generic_sans_prefers_the_first_installed_ui_family() {
786        let mut font_db = fontdb::Database::new();
787        font_db.load_system_fonts();
788        let expected = first_installed_family(&font_db, PLATFORM_SANS_FAMILIES)
789            .expect("Windows should provide at least one supported UI font");
790
791        configure_platform_generic_families(&mut font_db);
792
793        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), expected);
794    }
795}