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        // fontdb's system loader has no Android branch. Include native fonts
418        // before portable fallbacks so system-ui and script fallback can use
419        // the device's own families (including Roboto and color emoji).
420        #[cfg(target_os = "android")]
421        load_android_font_dirs(&mut font_db, &["/system/fonts", "/product/fonts"]);
422        load_bundled_fallback_fonts(&mut font_db);
423        Self::from_font_database(font_db)
424    }
425
426    #[cfg(test)]
427    pub(crate) fn with_bundled_fonts() -> Result<Self> {
428        let mut font_db = fontdb::Database::new();
429        load_bundled_portable_fallback_fonts(&mut font_db);
430        Self::from_font_database(font_db)
431    }
432
433    fn from_font_database(mut font_db: fontdb::Database) -> Result<Self> {
434        let locale = String::from("en-US");
435        configure_platform_generic_families(&mut font_db);
436
437        let families = [fontdb::Family::SansSerif];
438        let default_font = font_db
439            .query(&fontdb::Query {
440                families: &families,
441                weight: fontdb::Weight::NORMAL,
442                stretch: fontdb::Stretch::Normal,
443                style: fontdb::Style::Normal,
444            })
445            .or_else(|| font_db.faces().next().map(|face| face.id))
446            .ok_or_else(|| Error::new("failed to locate a font for text rendering"))?;
447
448        let default_face = font_db
449            .with_face_data(default_font, |font_data, face_index| {
450                ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
451            })
452            .ok_or_else(|| Error::new("failed to access fallback system font data"))?;
453        let mut shared_faces = HashMap::new();
454        shared_faces.insert(default_font, default_face.clone());
455
456        Ok(Self {
457            locale,
458            font_db,
459            default_face_key: FaceCacheKey::new(&default_face),
460            default_face,
461            shared_faces: Arc::new(Mutex::new(shared_faces)),
462        })
463    }
464
465    pub(crate) fn default_face_key(&self) -> FaceCacheKey {
466        self.default_face_key
467    }
468
469    pub(crate) fn build_font_context(&self, font_registry: &FontRegistry) -> Result<FontContext> {
470        let mut font_db = self.font_db.clone();
471        let mut explicit_fonts = HashMap::new();
472        let mut explicit_faces = HashMap::new();
473
474        for (handle, font) in &font_registry.fonts {
475            let ids =
476                font_db.load_font_source(fontdb::Source::Binary(Arc::new(font.bytes().to_vec())));
477            let mut family_name = None;
478            for id in ids {
479                let face_info = font_db.face(id).ok_or_else(|| {
480                    Error::new("failed to register custom font face in text database")
481                })?;
482                explicit_faces.insert(
483                    id,
484                    ResolvedTextFace::from_bytes(font.shared_bytes(), face_info.index),
485                );
486
487                if face_info.index == font.face_index() {
488                    family_name = Some(
489                        face_info
490                            .families
491                            .first()
492                            .map(|(name, _language)| name.clone())
493                            .unwrap_or_else(|| face_info.post_script_name.clone()),
494                    );
495                }
496            }
497
498            let family_name = family_name.ok_or_else(|| {
499                Error::new("failed to register custom font face in text database")
500            })?;
501            explicit_fonts.insert(*handle, ExplicitFontSpec { family_name });
502        }
503
504        let font_system = FontSystem::new_with_locale_and_db(self.locale.clone(), font_db);
505        Ok(FontContext {
506            font_system,
507            preparation: PreparationCaches::default(),
508            default_face: self.default_face.clone(),
509            explicit_fonts,
510            explicit_faces,
511            shared_faces: Arc::clone(&self.shared_faces),
512        })
513    }
514}
515
516fn resolve_font_family_name(
517    font_db: &fontdb::Database,
518    stack: FontFamilyStack,
519    style: &TextStyle,
520) -> Option<String> {
521    let families = stack.iter().map(fontdb_family).collect::<Vec<_>>();
522    let font_id = font_db.query(&fontdb::Query {
523        families: &families,
524        weight: Weight(style.weight.value()),
525        stretch: to_cosmic_stretch(style.stretch),
526        style: to_cosmic_style(style.style),
527    })?;
528    let face = font_db.face(font_id)?;
529    face.families
530        .first()
531        .map(|(name, _language)| name.clone())
532        .or_else(|| (!face.post_script_name.is_empty()).then(|| face.post_script_name.clone()))
533}
534
535fn fontdb_family(name: &str) -> Family<'_> {
536    if name.eq_ignore_ascii_case("ui-sans-serif")
537        || name.eq_ignore_ascii_case("system-ui")
538        || name.eq_ignore_ascii_case("-apple-system")
539        || name.eq_ignore_ascii_case("BlinkMacSystemFont")
540        || name.eq_ignore_ascii_case("sans-serif")
541    {
542        Family::SansSerif
543    } else if name.eq_ignore_ascii_case("ui-serif") || name.eq_ignore_ascii_case("serif") {
544        Family::Serif
545    } else if name.eq_ignore_ascii_case("ui-monospace") || name.eq_ignore_ascii_case("monospace") {
546        Family::Monospace
547    } else if name.eq_ignore_ascii_case("cursive") {
548        Family::Cursive
549    } else if name.eq_ignore_ascii_case("fantasy") {
550        Family::Fantasy
551    } else {
552        Family::Name(name)
553    }
554}
555
556#[cfg(target_os = "windows")]
557const PLATFORM_SANS_FAMILIES: &[&str] = &["Segoe UI Variable Text", "Segoe UI", "Arial"];
558#[cfg(target_os = "windows")]
559const PLATFORM_SERIF_FAMILIES: &[&str] = &["Cambria", "Georgia", "Times New Roman"];
560#[cfg(target_os = "windows")]
561const PLATFORM_MONO_FAMILIES: &[&str] =
562    &["Cascadia Mono", "Cascadia Code", "Consolas", "Courier New"];
563
564#[cfg(target_os = "macos")]
565const PLATFORM_SANS_FAMILIES: &[&str] =
566    &["SF Pro Text", "SF Pro Display", "Helvetica Neue", "Arial"];
567#[cfg(target_os = "macos")]
568const PLATFORM_SERIF_FAMILIES: &[&str] = &["New York", "Times New Roman", "Georgia"];
569#[cfg(target_os = "macos")]
570const PLATFORM_MONO_FAMILIES: &[&str] = &["SFMono-Regular", "SF Mono", "Menlo", "Monaco"];
571
572#[cfg(target_os = "android")]
573const PLATFORM_SANS_FAMILIES: &[&str] = &["Roboto", "Noto Sans", "Droid Sans"];
574#[cfg(target_os = "android")]
575const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "Droid Serif"];
576#[cfg(target_os = "android")]
577const PLATFORM_MONO_FAMILIES: &[&str] = &["Droid Sans Mono", "Noto Sans Mono"];
578
579#[cfg(all(
580    target_arch = "wasm32",
581    not(any(target_os = "windows", target_os = "macos"))
582))]
583const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans"];
584#[cfg(all(
585    target_arch = "wasm32",
586    not(any(target_os = "windows", target_os = "macos"))
587))]
588const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif"];
589#[cfg(all(
590    target_arch = "wasm32",
591    not(any(target_os = "windows", target_os = "macos"))
592))]
593const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono"];
594
595#[cfg(all(
596    not(target_arch = "wasm32"),
597    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
598))]
599const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans", "Inter", "DejaVu Sans", "Liberation Sans"];
600#[cfg(all(
601    not(target_arch = "wasm32"),
602    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
603))]
604const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "DejaVu Serif", "Liberation Serif"];
605#[cfg(all(
606    not(target_arch = "wasm32"),
607    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
608))]
609const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono", "DejaVu Sans Mono", "Liberation Mono"];
610
611#[cfg(any(target_os = "android", test))]
612fn load_android_font_dirs(font_db: &mut fontdb::Database, directories: &[&str]) {
613    for directory in directories {
614        font_db.load_fonts_dir(directory);
615    }
616}
617
618fn configure_platform_generic_families(font_db: &mut fontdb::Database) {
619    if let Some(family) = first_installed_family(font_db, PLATFORM_SANS_FAMILIES) {
620        font_db.set_sans_serif_family(family);
621    }
622    if let Some(family) = first_installed_family(font_db, PLATFORM_SERIF_FAMILIES) {
623        font_db.set_serif_family(family);
624    }
625    if let Some(family) = first_installed_family(font_db, PLATFORM_MONO_FAMILIES) {
626        font_db.set_monospace_family(family);
627    }
628}
629
630fn first_installed_family(font_db: &fontdb::Database, candidates: &[&str]) -> Option<String> {
631    candidates.iter().find_map(|candidate| {
632        font_db.faces().find_map(|face| {
633            face.families.iter().find_map(|(family, _language)| {
634                family
635                    .eq_ignore_ascii_case(candidate)
636                    .then(|| family.clone())
637            })
638        })
639    })
640}
641
642#[cfg(any(target_arch = "wasm32", target_os = "android"))]
643fn load_bundled_fallback_fonts(font_db: &mut fontdb::Database) {
644    load_bundled_portable_fallback_fonts(font_db);
645}
646
647#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
648fn load_bundled_portable_fallback_fonts(font_db: &mut fontdb::Database) {
649    let sans_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
650        include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
651    )));
652    let _ = set_sans_serif_family_from_loaded_faces(font_db, &sans_ids);
653
654    let serif_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
655        include_bytes!("../assets/NotoSerif-Variable.ttf").to_vec(),
656    )));
657    let _ = set_serif_family_from_loaded_faces(font_db, &serif_ids);
658
659    let mono_ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
660        include_bytes!("../assets/NotoSansMono-Variable.ttf").to_vec(),
661    )));
662    let _ = set_monospace_family_from_loaded_faces(font_db, &mono_ids);
663
664    // Keep complete script fonts available without browser downloads or system fonts.
665    for bytes in [
666        include_bytes!("../assets/NotoSansArabic-Regular.ttf").as_slice(),
667        include_bytes!("../assets/NotoSansHebrew-Regular.ttf").as_slice(),
668    ] {
669        font_db.load_font_source(fontdb::Source::Binary(Arc::new(bytes.to_vec())));
670    }
671}
672
673#[cfg(not(any(target_arch = "wasm32", target_os = "android")))]
674fn load_bundled_fallback_fonts(_font_db: &mut fontdb::Database) {}
675
676#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
677fn set_sans_serif_family_from_loaded_faces(
678    font_db: &mut fontdb::Database,
679    ids: &[fontdb::ID],
680) -> Option<String> {
681    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans")?;
682    font_db.set_sans_serif_family(name.clone());
683    Some(name)
684}
685
686#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
687fn set_serif_family_from_loaded_faces(
688    font_db: &mut fontdb::Database,
689    ids: &[fontdb::ID],
690) -> Option<String> {
691    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Serif")?;
692    font_db.set_serif_family(name.clone());
693    Some(name)
694}
695
696#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
697fn set_monospace_family_from_loaded_faces(
698    font_db: &mut fontdb::Database,
699    ids: &[fontdb::ID],
700) -> Option<String> {
701    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans Mono")?;
702    font_db.set_monospace_family(name.clone());
703    Some(name)
704}
705
706#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
707fn preferred_family_from_loaded_faces(
708    font_db: &fontdb::Database,
709    ids: &[fontdb::ID],
710    preferred: &str,
711) -> Option<String> {
712    let mut fallback = None;
713    for id in ids {
714        let Some(face_info) = font_db.face(*id) else {
715            continue;
716        };
717        for (name, _language) in &face_info.families {
718            if name.eq_ignore_ascii_case(preferred) {
719                return Some(name.clone());
720            }
721            fallback.get_or_insert_with(|| name.clone());
722        }
723        if fallback.is_none() && !face_info.post_script_name.is_empty() {
724            fallback = Some(face_info.post_script_name.clone());
725        }
726    }
727
728    fallback
729}
730
731/// The shaping metrics for a font size and line height. The shaper can't take
732/// a size or height of zero, so a zero, negative, or non-finite value becomes
733/// [`MIN_TEXT_METRIC`]: text set that small takes no visible space, and an
734/// app with a bad style token keeps running.
735pub(crate) fn cosmic_metrics(font_size: f32, line_height: f32) -> Metrics {
736    let usable = |value: f32| {
737        if value.is_finite() && value > 0.0 {
738            value
739        } else {
740            MIN_TEXT_METRIC
741        }
742    };
743    Metrics::new(usable(font_size), usable(line_height))
744}
745
746/// The smallest font size and line height the shaper is given, a sixty-fourth
747/// of a pixel.
748pub(crate) const MIN_TEXT_METRIC: f32 = 1.0 / 64.0;
749
750#[cfg(test)]
751mod font_database_tests {
752    use super::*;
753
754    #[test]
755    fn bundled_web_sans_font_becomes_generic_sans_serif() {
756        let mut font_db = fontdb::Database::new();
757        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
758            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
759        )));
760
761        let family_name = set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
762            .expect("bundled sans font should expose a family name");
763
764        assert_eq!(family_name, "Noto Sans");
765        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
766
767        let families = [fontdb::Family::SansSerif];
768        let font_id = font_db
769            .query(&fontdb::Query {
770                families: &families,
771                weight: fontdb::Weight::NORMAL,
772                stretch: fontdb::Stretch::Normal,
773                style: fontdb::Style::Normal,
774            })
775            .expect("generic sans-serif should resolve to bundled font");
776        let face = font_db
777            .face(font_id)
778            .expect("resolved bundled font face should still be registered");
779        assert!(face.families.iter().any(|(name, _)| name == "Noto Sans"));
780    }
781
782    #[test]
783    fn bundled_portable_fonts_resolve_all_theme_generic_stacks_on_native_tests() {
784        let mut font_db = fontdb::Database::new();
785        load_bundled_portable_fallback_fonts(&mut font_db);
786        configure_platform_generic_families(&mut font_db);
787
788        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
789        assert_eq!(font_db.family_name(&fontdb::Family::Serif), "Noto Serif");
790        assert_eq!(
791            font_db.family_name(&fontdb::Family::Monospace),
792            "Noto Sans Mono"
793        );
794
795        let cases = [
796            (
797                FontFamilyStack::new("ui-sans-serif", &["system-ui", "sans-serif"]),
798                "Noto Sans",
799            ),
800            (
801                FontFamilyStack::new("ui-serif", &["Georgia", "serif"]),
802                "Noto Serif",
803            ),
804            (
805                FontFamilyStack::new("ui-monospace", &["Consolas", "monospace"]),
806                "Noto Sans Mono",
807            ),
808        ];
809
810        for (stack, expected) in cases {
811            let style = TextStyle {
812                font_families: Some(stack),
813                ..TextStyle::default()
814            };
815            let resolved = resolve_font_family_name(&font_db, stack, &style);
816            assert_eq!(resolved.as_deref(), Some(expected));
817
818            let font_id = font_db
819                .query(&fontdb::Query {
820                    families: &[fontdb_family(stack.primary)],
821                    weight: fontdb::Weight::NORMAL,
822                    stretch: fontdb::Stretch::Normal,
823                    style: fontdb::Style::Normal,
824                })
825                .expect("bundled generic family should resolve to an actual face");
826            let face = font_db
827                .face(font_id)
828                .expect("resolved bundled face should remain registered");
829            assert!(face.families.iter().any(|(name, _)| name == expected));
830            assert!(
831                font_db
832                    .with_face_data(font_id, |data, _index| !data.is_empty())
833                    .unwrap_or(false),
834                "resolved {expected} face should expose font bytes"
835            );
836        }
837    }
838
839    #[test]
840    fn theme_family_stack_resolves_generic_alias_after_missing_family() {
841        let mut font_db = fontdb::Database::new();
842        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
843            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
844        )));
845        set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
846            .expect("bundled sans font should expose a family name");
847        let style = TextStyle {
848            font_families: Some(FontFamilyStack::new(
849                "Missing UI Family",
850                &["system-ui", "sans-serif"],
851            )),
852            ..TextStyle::default()
853        };
854
855        assert_eq!(
856            resolve_font_family_name(
857                &font_db,
858                style.font_families.expect("test family stack"),
859                &style,
860            )
861            .as_deref(),
862            Some("Noto Sans")
863        );
864    }
865
866    #[test]
867    fn platform_family_preference_uses_first_installed_candidate() {
868        let mut font_db = fontdb::Database::new();
869        font_db.load_font_source(fontdb::Source::Binary(Arc::new(
870            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
871        )));
872
873        assert_eq!(
874            first_installed_family(&font_db, &["Missing UI Family", "Noto Sans"]).as_deref(),
875            Some("Noto Sans")
876        );
877    }
878
879    #[test]
880    fn android_font_discovery_loads_device_fonts_and_keeps_portable_fallbacks() {
881        let directory = tempfile::tempdir().unwrap();
882        std::fs::write(
883            directory.path().join("device.ttf"),
884            include_bytes!("../assets/NotoSans-Regular.ttf"),
885        )
886        .unwrap();
887        std::fs::write(directory.path().join("invalid.ttf"), b"not a font").unwrap();
888        let missing = directory.path().join("missing");
889        let mut font_db = fontdb::Database::new();
890        load_android_font_dirs(
891            &mut font_db,
892            &[
893                missing.to_str().unwrap(),
894                directory.path().to_str().unwrap(),
895            ],
896        );
897        assert_eq!(
898            first_installed_family(&font_db, &["Noto Sans"]).as_deref(),
899            Some("Noto Sans")
900        );
901        load_bundled_portable_fallback_fonts(&mut font_db);
902        configure_platform_generic_families(&mut font_db);
903        for family in [
904            fontdb::Family::SansSerif,
905            fontdb::Family::Serif,
906            fontdb::Family::Monospace,
907        ] {
908            assert!(
909                font_db
910                    .query(&fontdb::Query {
911                        families: &[family],
912                        ..fontdb::Query::default()
913                    })
914                    .is_some(),
915                "native discovery must retain portable generics"
916            );
917        }
918    }
919
920    #[cfg(target_os = "windows")]
921    #[test]
922    fn windows_generic_sans_prefers_the_first_installed_ui_family() {
923        let mut font_db = fontdb::Database::new();
924        font_db.load_system_fonts();
925        let expected = first_installed_family(&font_db, PLATFORM_SANS_FAMILIES)
926            .expect("Windows should provide at least one supported UI font");
927
928        configure_platform_generic_families(&mut font_db);
929
930        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), expected);
931    }
932}