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