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