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    /// Font data: a TrueType or OpenType font or collection, or one
108    /// compressed as WOFF or WOFF2, which is decoded. Data is not checked
109    /// here; data that is not a font, or that fails to decode, fails when the
110    /// font is used. [`try_from_bytes`](Self::try_from_bytes) checks it.
111    pub fn from_bytes(data: impl Into<Vec<u8>>) -> Self {
112        let data = data.into();
113        let data = match decode_web_font(&data) {
114            Some(Ok(decoded)) => decoded,
115            _ => data,
116        };
117        Self {
118            data: Arc::<[u8]>::from(data),
119            face_index: 0,
120        }
121    }
122
123    /// Like [`from_bytes`](Self::from_bytes), but fails when the data is not
124    /// a font or a WOFF or WOFF2 file does not decode.
125    pub fn try_from_bytes(data: impl Into<Vec<u8>>) -> Result<Self> {
126        let data = data.into();
127        let data = match decode_web_font(&data) {
128            Some(decoded) => decoded?,
129            None => data,
130        };
131        if ttf_parser::fonts_in_collection(&data).is_none()
132            && ttf_parser::Face::parse(&data, 0).is_err()
133        {
134            return Err(Error::new(
135                "font data is not a TrueType, OpenType, WOFF, or WOFF2 font",
136            ));
137        }
138        Ok(Self {
139            data: Arc::<[u8]>::from(data),
140            face_index: 0,
141        })
142    }
143
144    /// The font's family name, preferring its typographic family, when the
145    /// font names one.
146    pub fn family_name(&self) -> Option<String> {
147        face_family_name(&self.data, self.face_index)
148    }
149
150    pub const fn with_face_index(mut self, face_index: u32) -> Self {
151        self.face_index = face_index;
152        self
153    }
154
155    pub fn bytes(&self) -> &[u8] {
156        &self.data
157    }
158
159    pub fn shared_bytes(&self) -> Arc<[u8]> {
160        Arc::clone(&self.data)
161    }
162
163    pub fn data_ptr(&self) -> usize {
164        self.data.as_ptr() as usize
165    }
166
167    pub fn data_len(&self) -> usize {
168        self.data.len()
169    }
170
171    pub const fn face_index(&self) -> u32 {
172        self.face_index
173    }
174}
175
176#[derive(Debug, Clone, PartialEq, Eq, Default)]
177pub struct FontRegistry {
178    pub(crate) fonts: HashMap<FontHandle, RegisteredFont>,
179}
180
181impl FontRegistry {
182    pub fn new() -> Self {
183        Self::default()
184    }
185
186    pub fn insert(&mut self, handle: FontHandle, font: RegisteredFont) -> Option<RegisteredFont> {
187        self.fonts.insert(handle, font)
188    }
189
190    pub fn get(&self, handle: FontHandle) -> Option<&RegisteredFont> {
191        self.fonts.get(&handle)
192    }
193
194    pub fn contains(&self, handle: FontHandle) -> bool {
195        self.fonts.contains_key(&handle)
196    }
197
198    pub fn len(&self) -> usize {
199        self.fonts.len()
200    }
201
202    pub fn is_empty(&self) -> bool {
203        self.fonts.is_empty()
204    }
205
206    pub(crate) fn cache_key(&self) -> Vec<(FontHandle, FaceCacheKey)> {
207        // The context retains every registered font's Arc-backed bytes, so their
208        // allocation identities cannot be reused while this key is cached.
209        let mut key = self
210            .fonts
211            .iter()
212            .map(|(handle, font)| (*handle, FaceCacheKey::from_registered_font(font)))
213            .collect::<Vec<_>>();
214        key.sort_unstable_by_key(|(handle, _)| *handle);
215        key
216    }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct ResolvedTextFace {
221    data: Arc<[u8]>,
222    face_index: u32,
223}
224
225impl ResolvedTextFace {
226    pub fn from_bytes(data: Arc<[u8]>, face_index: u32) -> Self {
227        Self { data, face_index }
228    }
229
230    pub fn bytes(&self) -> &[u8] {
231        &self.data
232    }
233
234    pub fn data_ptr(&self) -> usize {
235        self.data.as_ptr() as usize
236    }
237
238    pub fn data_len(&self) -> usize {
239        self.data.len()
240    }
241
242    pub fn shared_bytes(&self) -> Arc<[u8]> {
243        Arc::clone(&self.data)
244    }
245
246    pub const fn face_index(&self) -> u32 {
247        self.face_index
248    }
249
250    /// The font's family name, preferring its typographic family, when the
251    /// font names one.
252    pub fn family_name(&self) -> Option<String> {
253        face_family_name(self.bytes(), self.face_index)
254    }
255}
256
257/// The family name of a face, preferring its typographic family.
258fn face_family_name(data: &[u8], face_index: u32) -> Option<String> {
259    let face = ttf_parser::Face::parse(data, face_index).ok()?;
260    let names = face.names();
261    let named = |id| {
262        names
263            .into_iter()
264            .filter(|name| name.name_id == id && name.is_unicode())
265            .find_map(|name| name.to_string())
266    };
267    named(ttf_parser::name_id::TYPOGRAPHIC_FAMILY).or_else(|| named(ttf_parser::name_id::FAMILY))
268}
269
270/// Decode WOFF or WOFF2 data to an OpenType font; `None` when the data is
271/// neither.
272fn decode_web_font(data: &[u8]) -> Option<Result<Vec<u8>>> {
273    let decoded = match data.get(..4)? {
274        b"wOFF" => wuff::decompress_woff1(data),
275        b"wOF2" => wuff::decompress_woff2(data),
276        _ => return None,
277    };
278    Some(decoded.map_err(|_| Error::new("failed to decode WOFF or WOFF2 font data")))
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
282pub(crate) struct FaceCacheKey {
283    data_ptr: usize,
284    data_len: usize,
285    face_index: u32,
286}
287
288impl FaceCacheKey {
289    pub(crate) fn new(face: &ResolvedTextFace) -> Self {
290        Self {
291            data_ptr: face.data_ptr(),
292            data_len: face.data_len(),
293            face_index: face.face_index(),
294        }
295    }
296
297    pub(crate) fn from_registered_font(font: &RegisteredFont) -> Self {
298        Self {
299            data_ptr: font.data_ptr(),
300            data_len: font.data_len(),
301            face_index: font.face_index(),
302        }
303    }
304}
305
306#[derive(Debug, Clone)]
307pub(crate) struct ResolvedSpanInput {
308    pub id: TextSpanId,
309    pub text: String,
310    pub style: TextStyle,
311    pub family_name: Option<String>,
312}
313
314#[derive(Debug, Clone)]
315struct ExplicitFontSpec {
316    family_name: String,
317}
318
319#[derive(Debug)]
320pub(crate) struct FontContext {
321    pub font_system: FontSystem,
322    pub preparation: PreparationCaches,
323    default_face: ResolvedTextFace,
324    explicit_fonts: HashMap<FontHandle, ExplicitFontSpec>,
325    explicit_faces: HashMap<fontdb::ID, ResolvedTextFace>,
326    shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
327}
328
329impl FontContext {
330    pub(crate) fn glyph_metrics(
331        &mut self,
332        font: fontdb::ID,
333        glyph: u16,
334        face: &ResolvedTextFace,
335    ) -> Result<IntrinsicGlyphMetrics> {
336        let key = GlyphMetricsKey { font, glyph };
337        if let Some(metrics) = self.preparation.glyphs.get(&key) {
338            return Ok(*metrics);
339        }
340        let parsed = ttf_parser::Face::parse(face.bytes(), face.face_index())
341            .map_err(|_| Error::new("failed to parse text face metrics"))?;
342        let units_per_em = parsed.units_per_em();
343        if units_per_em == 0 {
344            return Err(Error::new(
345                "text face reported an invalid units-per-em value",
346            ));
347        }
348        let metrics = IntrinsicGlyphMetrics {
349            units_per_em: f32::from(units_per_em),
350            cap_height: parsed.capital_height().map(f32::from),
351            bounds: parsed.glyph_bounding_box(ttf_parser::GlyphId(glyph)),
352        };
353        self.preparation.glyphs.insert(key, metrics, 0);
354        Ok(metrics)
355    }
356
357    pub(crate) fn resolve_span(
358        &self,
359        span_id: TextSpanId,
360        text: String,
361        style: &TextStyle,
362    ) -> Result<ResolvedSpanInput> {
363        let family_name = if let Some(handle) = style.font {
364            let spec = self.explicit_fonts.get(&handle).ok_or_else(|| {
365                Error::new(format!("font handle {} is not registered", handle.get()))
366            })?;
367            Some(spec.family_name.clone())
368        } else if let Some(families) = style.font_families {
369            resolve_font_family_name(self.font_system.db(), families, style)
370        } else {
371            None
372        };
373
374        Ok(ResolvedSpanInput {
375            id: span_id,
376            text,
377            style: style.clone(),
378            family_name,
379        })
380    }
381
382    pub(crate) fn attrs_for_span<'a>(span: &'a ResolvedSpanInput, metadata: usize) -> Attrs<'a> {
383        let text_style = &span.style;
384        let mut attrs = Attrs::new()
385            .metrics(cosmic_metrics(text_style.font_size, text_style.line_height))
386            .metadata(metadata)
387            .weight(to_cosmic_weight(text_style.weight))
388            .style(to_cosmic_style(text_style.style))
389            .stretch(to_cosmic_stretch(text_style.stretch));
390        if !text_style.features.is_empty() {
391            attrs = attrs.font_features(to_cosmic_features(&text_style.features));
392        }
393
394        match span.family_name.as_deref() {
395            Some(name) => attrs.family(Family::Name(name)),
396            None => attrs,
397        }
398    }
399
400    pub(crate) fn resolve_face_index(
401        &self,
402        face_slots: &mut HashMap<fontdb::ID, usize>,
403        faces: &mut Vec<ResolvedTextFace>,
404        font_id: fontdb::ID,
405    ) -> Result<usize> {
406        if let Some(index) = face_slots.get(&font_id) {
407            return Ok(*index);
408        }
409
410        let face = self.resolve_face(font_id)?;
411        let index = faces.len();
412        faces.push(face);
413        face_slots.insert(font_id, index);
414        Ok(index)
415    }
416
417    pub(crate) fn resolve_face(&self, font_id: fontdb::ID) -> Result<ResolvedTextFace> {
418        if let Some(face) = self.explicit_faces.get(&font_id).cloned() {
419            return Ok(face);
420        }
421
422        if let Some(face) = self
423            .shared_faces
424            .lock()
425            .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
426            .get(&font_id)
427            .cloned()
428        {
429            return Ok(face);
430        }
431
432        let face = self
433            .font_system
434            .db()
435            .with_face_data(font_id, |font_data, face_index| {
436                ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
437            })
438            .ok_or_else(|| {
439                Error::new("failed to access font face data from cosmic-text database")
440            })?;
441
442        self.shared_faces
443            .lock()
444            .map_err(|_| Error::new("shared text face cache lock was poisoned"))?
445            .insert(font_id, face.clone());
446
447        Ok(face)
448    }
449
450    pub(crate) fn default_face(&self) -> &ResolvedTextFace {
451        &self.default_face
452    }
453}
454
455#[derive(Debug)]
456pub(crate) struct TextSystemState {
457    locale: String,
458    font_db: fontdb::Database,
459    default_face: ResolvedTextFace,
460    default_face_key: FaceCacheKey,
461    shared_faces: Arc<Mutex<HashMap<fontdb::ID, ResolvedTextFace>>>,
462}
463
464impl TextSystemState {
465    pub(crate) fn new() -> Result<Self> {
466        let mut font_db = fontdb::Database::new();
467        font_db.load_system_fonts();
468        // fontdb's system loader has no Android branch. Include native fonts
469        // before portable fallbacks so system-ui and script fallback can use
470        // the device's own families (including Roboto and color emoji).
471        #[cfg(target_os = "android")]
472        load_android_font_dirs(&mut font_db, &["/system/fonts", "/product/fonts"]);
473        load_bundled_fallback_fonts(&mut font_db);
474        Self::from_font_database(font_db)
475    }
476
477    #[cfg(test)]
478    pub(crate) fn with_bundled_fonts() -> Result<Self> {
479        let mut font_db = fontdb::Database::new();
480        load_bundled_portable_fallback_fonts(&mut font_db);
481        Self::from_font_database(font_db)
482    }
483
484    fn from_font_database(mut font_db: fontdb::Database) -> Result<Self> {
485        let locale = String::from("en-US");
486        configure_platform_generic_families(&mut font_db);
487
488        let families = [fontdb::Family::SansSerif];
489        let default_font = font_db
490            .query(&fontdb::Query {
491                families: &families,
492                weight: fontdb::Weight::NORMAL,
493                stretch: fontdb::Stretch::Normal,
494                style: fontdb::Style::Normal,
495            })
496            .or_else(|| font_db.faces().next().map(|face| face.id))
497            .ok_or_else(|| Error::new("failed to locate a font for text rendering"))?;
498
499        let default_face = font_db
500            .with_face_data(default_font, |font_data, face_index| {
501                ResolvedTextFace::from_bytes(Arc::<[u8]>::from(font_data.to_vec()), face_index)
502            })
503            .ok_or_else(|| Error::new("failed to access fallback system font data"))?;
504        let mut shared_faces = HashMap::new();
505        shared_faces.insert(default_font, default_face.clone());
506
507        Ok(Self {
508            locale,
509            font_db,
510            default_face_key: FaceCacheKey::new(&default_face),
511            default_face,
512            shared_faces: Arc::new(Mutex::new(shared_faces)),
513        })
514    }
515
516    pub(crate) fn default_face_key(&self) -> FaceCacheKey {
517        self.default_face_key
518    }
519
520    pub(crate) fn build_font_context(&self, font_registry: &FontRegistry) -> Result<FontContext> {
521        let mut font_db = self.font_db.clone();
522        let mut explicit_fonts = HashMap::new();
523        let mut explicit_faces = HashMap::new();
524
525        for (handle, font) in &font_registry.fonts {
526            let ids =
527                font_db.load_font_source(fontdb::Source::Binary(Arc::new(font.shared_bytes())));
528            let mut family_name = None;
529            for id in ids {
530                let face_info = font_db.face(id).ok_or_else(|| {
531                    Error::new("failed to register custom font face in text database")
532                })?;
533                explicit_faces.insert(
534                    id,
535                    ResolvedTextFace::from_bytes(font.shared_bytes(), face_info.index),
536                );
537
538                if face_info.index == font.face_index() {
539                    family_name = Some(
540                        face_info
541                            .families
542                            .first()
543                            .map(|(name, _language)| name.clone())
544                            .unwrap_or_else(|| face_info.post_script_name.clone()),
545                    );
546                }
547            }
548
549            let family_name = family_name.ok_or_else(|| {
550                Error::new("failed to register custom font face in text database")
551            })?;
552            explicit_fonts.insert(*handle, ExplicitFontSpec { family_name });
553        }
554
555        let font_system = FontSystem::new_with_locale_and_db(self.locale.clone(), font_db);
556        Ok(FontContext {
557            font_system,
558            preparation: PreparationCaches::default(),
559            default_face: self.default_face.clone(),
560            explicit_fonts,
561            explicit_faces,
562            shared_faces: Arc::clone(&self.shared_faces),
563        })
564    }
565}
566
567fn resolve_font_family_name(
568    font_db: &fontdb::Database,
569    stack: FontFamilyStack,
570    style: &TextStyle,
571) -> Option<String> {
572    let families = stack.iter().map(fontdb_family).collect::<Vec<_>>();
573    let font_id = font_db.query(&fontdb::Query {
574        families: &families,
575        weight: Weight(style.weight.value()),
576        stretch: to_cosmic_stretch(style.stretch),
577        style: to_cosmic_style(style.style),
578    })?;
579    let face = font_db.face(font_id)?;
580    face.families
581        .first()
582        .map(|(name, _language)| name.clone())
583        .or_else(|| (!face.post_script_name.is_empty()).then(|| face.post_script_name.clone()))
584}
585
586fn fontdb_family(name: &str) -> Family<'_> {
587    if name.eq_ignore_ascii_case("ui-sans-serif")
588        || name.eq_ignore_ascii_case("system-ui")
589        || name.eq_ignore_ascii_case("-apple-system")
590        || name.eq_ignore_ascii_case("BlinkMacSystemFont")
591        || name.eq_ignore_ascii_case("sans-serif")
592    {
593        Family::SansSerif
594    } else if name.eq_ignore_ascii_case("ui-serif") || name.eq_ignore_ascii_case("serif") {
595        Family::Serif
596    } else if name.eq_ignore_ascii_case("ui-monospace") || name.eq_ignore_ascii_case("monospace") {
597        Family::Monospace
598    } else if name.eq_ignore_ascii_case("cursive") {
599        Family::Cursive
600    } else if name.eq_ignore_ascii_case("fantasy") {
601        Family::Fantasy
602    } else {
603        Family::Name(name)
604    }
605}
606
607#[cfg(target_os = "windows")]
608const PLATFORM_SANS_FAMILIES: &[&str] = &["Segoe UI Variable Text", "Segoe UI", "Arial"];
609#[cfg(target_os = "windows")]
610const PLATFORM_SERIF_FAMILIES: &[&str] = &["Cambria", "Georgia", "Times New Roman"];
611#[cfg(target_os = "windows")]
612const PLATFORM_MONO_FAMILIES: &[&str] =
613    &["Cascadia Mono", "Cascadia Code", "Consolas", "Courier New"];
614
615#[cfg(target_os = "macos")]
616const PLATFORM_SANS_FAMILIES: &[&str] =
617    &["SF Pro Text", "SF Pro Display", "Helvetica Neue", "Arial"];
618#[cfg(target_os = "macos")]
619const PLATFORM_SERIF_FAMILIES: &[&str] = &["New York", "Times New Roman", "Georgia"];
620#[cfg(target_os = "macos")]
621const PLATFORM_MONO_FAMILIES: &[&str] = &["SFMono-Regular", "SF Mono", "Menlo", "Monaco"];
622
623#[cfg(target_os = "android")]
624const PLATFORM_SANS_FAMILIES: &[&str] = &["Roboto", "Noto Sans", "Droid Sans"];
625#[cfg(target_os = "android")]
626const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "Droid Serif"];
627#[cfg(target_os = "android")]
628const PLATFORM_MONO_FAMILIES: &[&str] = &["Droid Sans Mono", "Noto Sans Mono"];
629
630#[cfg(all(
631    target_arch = "wasm32",
632    not(any(target_os = "windows", target_os = "macos"))
633))]
634const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans"];
635#[cfg(all(
636    target_arch = "wasm32",
637    not(any(target_os = "windows", target_os = "macos"))
638))]
639const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif"];
640#[cfg(all(
641    target_arch = "wasm32",
642    not(any(target_os = "windows", target_os = "macos"))
643))]
644const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono"];
645
646#[cfg(all(
647    not(target_arch = "wasm32"),
648    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
649))]
650const PLATFORM_SANS_FAMILIES: &[&str] = &["Noto Sans", "Inter", "DejaVu Sans", "Liberation Sans"];
651#[cfg(all(
652    not(target_arch = "wasm32"),
653    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
654))]
655const PLATFORM_SERIF_FAMILIES: &[&str] = &["Noto Serif", "DejaVu Serif", "Liberation Serif"];
656#[cfg(all(
657    not(target_arch = "wasm32"),
658    not(any(target_os = "windows", target_os = "macos", target_os = "android"))
659))]
660const PLATFORM_MONO_FAMILIES: &[&str] = &["Noto Sans Mono", "DejaVu Sans Mono", "Liberation Mono"];
661
662#[cfg(any(target_os = "android", test))]
663fn load_android_font_dirs(font_db: &mut fontdb::Database, directories: &[&str]) {
664    for directory in directories {
665        font_db.load_fonts_dir(directory);
666    }
667}
668
669fn configure_platform_generic_families(font_db: &mut fontdb::Database) {
670    if let Some(family) = first_installed_family(font_db, PLATFORM_SANS_FAMILIES) {
671        font_db.set_sans_serif_family(family);
672    }
673    if let Some(family) = first_installed_family(font_db, PLATFORM_SERIF_FAMILIES) {
674        font_db.set_serif_family(family);
675    }
676    if let Some(family) = first_installed_family(font_db, PLATFORM_MONO_FAMILIES) {
677        font_db.set_monospace_family(family);
678    }
679}
680
681fn first_installed_family(font_db: &fontdb::Database, candidates: &[&str]) -> Option<String> {
682    candidates.iter().find_map(|candidate| {
683        font_db.faces().find_map(|face| {
684            face.families.iter().find_map(|(family, _language)| {
685                family
686                    .eq_ignore_ascii_case(candidate)
687                    .then(|| family.clone())
688            })
689        })
690    })
691}
692
693#[cfg(any(target_arch = "wasm32", target_os = "android"))]
694fn load_bundled_fallback_fonts(font_db: &mut fontdb::Database) {
695    load_bundled_portable_fallback_fonts(font_db);
696}
697
698#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
699fn load_bundled_portable_fallback_fonts(font_db: &mut fontdb::Database) {
700    // Share the embedded bytes instead of copying them into the heap; wasm
701    // linear memory never shrinks, so a copy would cost megabytes for good.
702    fn load_static(font_db: &mut fontdb::Database, bytes: &'static [u8]) -> Vec<fontdb::ID> {
703        font_db
704            .load_font_source(fontdb::Source::Binary(Arc::new(bytes)))
705            .into_iter()
706            .collect()
707    }
708
709    let sans_ids = load_static(font_db, include_bytes!("../assets/NotoSans-Regular.ttf"));
710    let _ = set_sans_serif_family_from_loaded_faces(font_db, &sans_ids);
711
712    let serif_ids = load_static(font_db, include_bytes!("../assets/NotoSerif-Variable.ttf"));
713    let _ = set_serif_family_from_loaded_faces(font_db, &serif_ids);
714
715    let mono_ids = load_static(
716        font_db,
717        include_bytes!("../assets/NotoSansMono-Variable.ttf"),
718    );
719    let _ = set_monospace_family_from_loaded_faces(font_db, &mono_ids);
720
721    // Keep complete script fonts available without browser downloads or system fonts.
722    for bytes in [
723        include_bytes!("../assets/NotoSansArabic-Regular.ttf").as_slice(),
724        include_bytes!("../assets/NotoSansHebrew-Regular.ttf").as_slice(),
725    ] {
726        load_static(font_db, bytes);
727    }
728}
729
730#[cfg(not(any(target_arch = "wasm32", target_os = "android")))]
731fn load_bundled_fallback_fonts(_font_db: &mut fontdb::Database) {}
732
733#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
734fn set_sans_serif_family_from_loaded_faces(
735    font_db: &mut fontdb::Database,
736    ids: &[fontdb::ID],
737) -> Option<String> {
738    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans")?;
739    font_db.set_sans_serif_family(name.clone());
740    Some(name)
741}
742
743#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
744fn set_serif_family_from_loaded_faces(
745    font_db: &mut fontdb::Database,
746    ids: &[fontdb::ID],
747) -> Option<String> {
748    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Serif")?;
749    font_db.set_serif_family(name.clone());
750    Some(name)
751}
752
753#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
754fn set_monospace_family_from_loaded_faces(
755    font_db: &mut fontdb::Database,
756    ids: &[fontdb::ID],
757) -> Option<String> {
758    let name = preferred_family_from_loaded_faces(font_db, ids, "Noto Sans Mono")?;
759    font_db.set_monospace_family(name.clone());
760    Some(name)
761}
762
763#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
764fn preferred_family_from_loaded_faces(
765    font_db: &fontdb::Database,
766    ids: &[fontdb::ID],
767    preferred: &str,
768) -> Option<String> {
769    let mut fallback = None;
770    for id in ids {
771        let Some(face_info) = font_db.face(*id) else {
772            continue;
773        };
774        for (name, _language) in &face_info.families {
775            if name.eq_ignore_ascii_case(preferred) {
776                return Some(name.clone());
777            }
778            fallback.get_or_insert_with(|| name.clone());
779        }
780        if fallback.is_none() && !face_info.post_script_name.is_empty() {
781            fallback = Some(face_info.post_script_name.clone());
782        }
783    }
784
785    fallback
786}
787
788/// The shaping metrics for a font size and line height. The shaper can't take
789/// a size or height of zero, so a zero, negative, or non-finite value becomes
790/// [`MIN_TEXT_METRIC`]: text set that small takes no visible space, and an
791/// app with a bad style token keeps running.
792pub(crate) fn cosmic_metrics(font_size: f32, line_height: f32) -> Metrics {
793    let usable = |value: f32| {
794        if value.is_finite() && value > 0.0 {
795            value
796        } else {
797            MIN_TEXT_METRIC
798        }
799    };
800    Metrics::new(usable(font_size), usable(line_height))
801}
802
803/// The smallest font size and line height the shaper is given, a sixty-fourth
804/// of a pixel.
805pub(crate) const MIN_TEXT_METRIC: f32 = 1.0 / 64.0;
806
807#[cfg(test)]
808mod font_database_tests {
809    use super::*;
810
811    #[test]
812    fn bundled_web_sans_font_becomes_generic_sans_serif() {
813        let mut font_db = fontdb::Database::new();
814        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
815            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
816        )));
817
818        let family_name = set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
819            .expect("bundled sans font should expose a family name");
820
821        assert_eq!(family_name, "Noto Sans");
822        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
823
824        let families = [fontdb::Family::SansSerif];
825        let font_id = font_db
826            .query(&fontdb::Query {
827                families: &families,
828                weight: fontdb::Weight::NORMAL,
829                stretch: fontdb::Stretch::Normal,
830                style: fontdb::Style::Normal,
831            })
832            .expect("generic sans-serif should resolve to bundled font");
833        let face = font_db
834            .face(font_id)
835            .expect("resolved bundled font face should still be registered");
836        assert!(face.families.iter().any(|(name, _)| name == "Noto Sans"));
837    }
838
839    #[test]
840    fn bundled_portable_fonts_resolve_all_theme_generic_stacks_on_native_tests() {
841        let mut font_db = fontdb::Database::new();
842        load_bundled_portable_fallback_fonts(&mut font_db);
843        configure_platform_generic_families(&mut font_db);
844
845        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), "Noto Sans");
846        assert_eq!(font_db.family_name(&fontdb::Family::Serif), "Noto Serif");
847        assert_eq!(
848            font_db.family_name(&fontdb::Family::Monospace),
849            "Noto Sans Mono"
850        );
851
852        let cases = [
853            (
854                FontFamilyStack::new("ui-sans-serif", &["system-ui", "sans-serif"]),
855                "Noto Sans",
856            ),
857            (
858                FontFamilyStack::new("ui-serif", &["Georgia", "serif"]),
859                "Noto Serif",
860            ),
861            (
862                FontFamilyStack::new("ui-monospace", &["Consolas", "monospace"]),
863                "Noto Sans Mono",
864            ),
865        ];
866
867        for (stack, expected) in cases {
868            let style = TextStyle {
869                font_families: Some(stack),
870                ..TextStyle::default()
871            };
872            let resolved = resolve_font_family_name(&font_db, stack, &style);
873            assert_eq!(resolved.as_deref(), Some(expected));
874
875            let font_id = font_db
876                .query(&fontdb::Query {
877                    families: &[fontdb_family(stack.primary)],
878                    weight: fontdb::Weight::NORMAL,
879                    stretch: fontdb::Stretch::Normal,
880                    style: fontdb::Style::Normal,
881                })
882                .expect("bundled generic family should resolve to an actual face");
883            let face = font_db
884                .face(font_id)
885                .expect("resolved bundled face should remain registered");
886            assert!(face.families.iter().any(|(name, _)| name == expected));
887            assert!(
888                font_db
889                    .with_face_data(font_id, |data, _index| !data.is_empty())
890                    .unwrap_or(false),
891                "resolved {expected} face should expose font bytes"
892            );
893        }
894    }
895
896    #[test]
897    fn theme_family_stack_resolves_generic_alias_after_missing_family() {
898        let mut font_db = fontdb::Database::new();
899        let ids = font_db.load_font_source(fontdb::Source::Binary(Arc::new(
900            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
901        )));
902        set_sans_serif_family_from_loaded_faces(&mut font_db, &ids)
903            .expect("bundled sans font should expose a family name");
904        let style = TextStyle {
905            font_families: Some(FontFamilyStack::new(
906                "Missing UI Family",
907                &["system-ui", "sans-serif"],
908            )),
909            ..TextStyle::default()
910        };
911
912        assert_eq!(
913            resolve_font_family_name(
914                &font_db,
915                style.font_families.expect("test family stack"),
916                &style,
917            )
918            .as_deref(),
919            Some("Noto Sans")
920        );
921    }
922
923    #[test]
924    fn platform_family_preference_uses_first_installed_candidate() {
925        let mut font_db = fontdb::Database::new();
926        font_db.load_font_source(fontdb::Source::Binary(Arc::new(
927            include_bytes!("../assets/NotoSans-Regular.ttf").to_vec(),
928        )));
929
930        assert_eq!(
931            first_installed_family(&font_db, &["Missing UI Family", "Noto Sans"]).as_deref(),
932            Some("Noto Sans")
933        );
934    }
935
936    #[test]
937    fn android_font_discovery_loads_device_fonts_and_keeps_portable_fallbacks() {
938        let directory = tempfile::tempdir().unwrap();
939        std::fs::write(
940            directory.path().join("device.ttf"),
941            include_bytes!("../assets/NotoSans-Regular.ttf"),
942        )
943        .unwrap();
944        std::fs::write(directory.path().join("invalid.ttf"), b"not a font").unwrap();
945        let missing = directory.path().join("missing");
946        let mut font_db = fontdb::Database::new();
947        load_android_font_dirs(
948            &mut font_db,
949            &[
950                missing.to_str().unwrap(),
951                directory.path().to_str().unwrap(),
952            ],
953        );
954        assert_eq!(
955            first_installed_family(&font_db, &["Noto Sans"]).as_deref(),
956            Some("Noto Sans")
957        );
958        load_bundled_portable_fallback_fonts(&mut font_db);
959        configure_platform_generic_families(&mut font_db);
960        for family in [
961            fontdb::Family::SansSerif,
962            fontdb::Family::Serif,
963            fontdb::Family::Monospace,
964        ] {
965            assert!(
966                font_db
967                    .query(&fontdb::Query {
968                        families: &[family],
969                        ..fontdb::Query::default()
970                    })
971                    .is_some(),
972                "native discovery must retain portable generics"
973            );
974        }
975    }
976
977    #[cfg(target_os = "windows")]
978    #[test]
979    fn windows_generic_sans_prefers_the_first_installed_ui_family() {
980        let mut font_db = fontdb::Database::new();
981        font_db.load_system_fonts();
982        let expected = first_installed_family(&font_db, PLATFORM_SANS_FAMILIES)
983            .expect("Windows should provide at least one supported UI font");
984
985        configure_platform_generic_families(&mut font_db);
986
987        assert_eq!(font_db.family_name(&fontdb::Family::SansSerif), expected);
988    }
989}