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