Skip to main content

egui_system_font_provider/
lib.rs

1//! Load system fonts on demand for characters that the fonts installed in egui lack.
2//!
3//! [`SystemFontProvider`] is an [`epaint::text::FontProvider`] backed by [`fontique`],
4//! which uses the operating system's own font fallback (CoreText, DirectWrite, fontconfig,
5//! or Android's `fonts.xml`) to find an installed font for a script and locale.
6//!
7//! ```no_run
8//! # let egui_ctx = egui::Context::default();
9//! egui_ctx.add_font_provider(std::sync::Arc::new(egui_system_font_provider::SystemFontProvider::new()));
10//! ```
11
12use epaint::{
13    mutex::Mutex,
14    text::{
15        FallbackRequest, FontData, FontFamily, FontInsert, FontPriority, FontProvider,
16        InsertFontFamily,
17    },
18};
19use fontique::{
20    Collection, CollectionOptions, FallbackKey, GenericFamily, Language, QueryFamily, QueryFont,
21    QueryStatus, Script, SourceCache, SourceCacheOptions,
22};
23use poll_promise::Promise;
24
25struct SystemFonts {
26    collection: Collection,
27    source_cache: SourceCache,
28}
29
30/// Finds installed system fonts for characters that the egui fonts lack.
31///
32/// Uses the operating system's own font fallback via [`fontique`],
33/// so e.g. 日本語 gets a Japanese font and العربية an Arabic font.
34/// The font files are memory-mapped, not copied.
35///
36/// Enumerating the system fonts can take hundreds of milliseconds,
37/// so [`Self::new`] starts doing that on a background thread.
38/// A lookup before it is done blocks until it is.
39pub struct SystemFontProvider {
40    /// Loaded on a background thread by [`Self::new`].
41    fonts: Mutex<Promise<SystemFonts>>,
42    locale: Option<Language>,
43}
44
45impl Default for SystemFontProvider {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl SystemFontProvider {
52    /// Start enumerating the system fonts on a background thread.
53    ///
54    /// Uses the system locale to pick between fonts (see [`Self::with_locale`]).
55    pub fn new() -> Self {
56        Self {
57            fonts: Mutex::new(Promise::spawn_thread(
58                "egui_system_font_provider",
59                load_system_fonts,
60            )),
61            locale: sys_locale::get_locale().and_then(|locale| parse_locale(&locale)),
62        }
63    }
64
65    /// The locale used to pick between fonts for the same script,
66    /// e.g. between a Japanese and a Simplified Chinese font for CJK ideographs.
67    ///
68    /// A BCP-47 language tag like `"ja"` or `"zh-Hans"`, or `None` for the platform default.
69    ///
70    /// Default: the system locale.
71    #[inline]
72    pub fn with_locale(mut self, locale: Option<&str>) -> Self {
73        self.locale = locale.and_then(parse_locale);
74        self
75    }
76}
77
78fn parse_locale(locale: &str) -> Option<Language> {
79    match Language::parse(locale) {
80        Ok(language) => Some(language),
81        Err(err) => {
82            log::warn!("Failed to parse locale {locale:?}: {err:?}");
83            None
84        }
85    }
86}
87
88fn load_system_fonts() -> SystemFonts {
89    let start = std::time::Instant::now();
90    let collection = Collection::new(CollectionOptions {
91        shared: false,
92        system_fonts: true,
93    });
94    log::debug!("Enumerated system fonts in {:?}", start.elapsed());
95    SystemFonts {
96        collection,
97        source_cache: SourceCache::new(SourceCacheOptions::default()),
98    }
99}
100
101impl FontProvider for SystemFontProvider {
102    fn font_for(&self, request: &FallbackRequest<'_>) -> Option<FontInsert> {
103        let FallbackRequest { cluster, family } = request;
104        let base_char = cluster.chars().next()?;
105
106        // Blocks if the background thread is not done enumerating the system fonts yet:
107        let mut fonts = self.fonts.lock();
108        let SystemFonts {
109            collection,
110            source_cache,
111        } = fonts.block_until_ready_mut();
112
113        let generic = match family {
114            FontFamily::Monospace => GenericFamily::Monospace,
115            FontFamily::Proportional | FontFamily::Name(_) => GenericFamily::SansSerif,
116        };
117
118        let font = if let Some(script) = script_of(base_char) {
119            // The fallback for a script may be a single font for one locale,
120            // e.g. a Japanese font for Han, which lacks many Simplified Chinese characters.
121            // So if it can't render the char, try the other locales of the script:
122            // TODO(https://github.com/linebender/parley/issues/644): remove `other_locales`
123            // once fontique falls back per char (https://github.com/linebender/parley/pull/689).
124            core::iter::chain(
125                [self.locale.as_ref()],
126                other_locales(script).iter().map(Some),
127            )
128            .find_map(|locale| {
129                let mut query = collection.query(source_cache);
130                query.set_families([QueryFamily::Generic(generic)]);
131                query.set_fallbacks(fallback_key(script, locale));
132                find_font(&mut query, base_char)
133            })
134        } else {
135            // Punctuation, symbols, emoji, etc. belong to no script, so there is no fallback for them.
136            // Try the generic families instead.
137            let mut query = collection.query(source_cache);
138            query.set_families(
139                [
140                    generic,
141                    GenericFamily::SystemUi,
142                    GenericFamily::Emoji,
143                    GenericFamily::Math,
144                    GenericFamily::Serif,
145                    GenericFamily::Monospace,
146                ]
147                .map(QueryFamily::Generic),
148            );
149            find_font(&mut query, base_char)
150        }?;
151
152        let family_name = collection.family_name(font.family.0).unwrap_or("unknown");
153        let name = format!("system:{family_name}:{}:{}", font.family.1, font.index);
154        log::debug!("Using {name:?} for {base_char:?}");
155
156        let (blob, _blob_id) = font.blob.into_raw_parts();
157        Some(FontInsert {
158            name,
159            data: FontData::from_blob(blob, font.index),
160            families: vec![InsertFontFamily {
161                family: (*family).clone(),
162                priority: FontPriority::Lowest,
163            }],
164        })
165    }
166}
167
168/// The first font in the query that can render `c`.
169fn find_font(query: &mut fontique::Query<'_>, c: char) -> Option<QueryFont> {
170    let mut found = None;
171    query.matches_with(|font| {
172        if can_render(font, c) {
173            found = Some(font.clone());
174            QueryStatus::Stop
175        } else {
176            QueryStatus::Continue
177        }
178    });
179    found
180}
181
182const HAN: Script = Script::from_bytes(*b"Hani");
183
184/// The locales of the Han fonts, starting with Simplified Chinese.
185///
186/// Simplified Chinese is `zh-SG` rather than `zh-CN`, because fontique treats `zh-CN`
187/// as the default Han locale. Its font is whatever the first locale-less Han lookup returned,
188/// which every `Query::set_fallbacks` does, so it is often the Japanese font.
189static HAN_LOCALES: std::sync::LazyLock<Vec<Language>> = std::sync::LazyLock::new(|| {
190    ["zh-SG", "zh-TW", "ja", "ko"]
191        .iter()
192        .filter_map(|locale| Language::parse(locale).ok())
193        .collect()
194});
195
196/// The fallback key for a script and locale, avoiding fontique's default Han locale (see [`HAN_LOCALES`]).
197fn fallback_key(script: Script, locale: Option<&Language>) -> FallbackKey {
198    let locale = match locale {
199        Some(locale) if script == HAN && is_simplified_chinese(locale) => HAN_LOCALES.first(),
200        locale => locale,
201    };
202    FallbackKey::new(script, locale)
203}
204
205/// Is this a Simplified Chinese locale, like `zh`, `zh-CN` or `zh-Hans`?
206///
207/// Mirrors how fontique picks between Simplified and Traditional Chinese.
208fn is_simplified_chinese(locale: &Language) -> bool {
209    locale.language() == "zh"
210        && locale.script() != Some("Hant")
211        && !matches!(locale.region(), Some("HK" | "TW" | "MO"))
212}
213
214/// Locales to try for a script when the fallback for the preferred locale lacks a char.
215///
216/// Only Han needs this: its fonts are per locale, and each covers a different set of characters.
217fn other_locales(script: Script) -> &'static [Language] {
218    if script == HAN { &HAN_LOCALES } else { &[] }
219}
220
221/// The script of a character, or `None` for characters shared between scripts (punctuation, symbols, …).
222fn script_of(c: char) -> Option<Script> {
223    use unicode_script::UnicodeScript as _;
224
225    match c.script() {
226        unicode_script::Script::Common
227        | unicode_script::Script::Inherited
228        | unicode_script::Script::Unknown => None,
229        script => Script::parse(script.short_name()).ok(),
230    }
231}
232
233/// Does the font have a glyph for the character that epaint can render?
234///
235/// That is an outline, a bitmap (`sbix`, `CBDT`), or a `COLR` glyph.
236fn can_render(font: &QueryFont, c: char) -> bool {
237    use skrifa::MetadataProvider as _;
238
239    let Some(glyph_id) = font.charmap().and_then(|charmap| charmap.map(c)) else {
240        return false;
241    };
242    let glyph_id = skrifa::GlyphId::new(glyph_id);
243    if glyph_id == skrifa::GlyphId::NOTDEF {
244        return false;
245    }
246    let Ok(font_ref) = skrifa::FontRef::from_index(font.blob.as_ref(), font.index) else {
247        return false;
248    };
249    font_ref.outline_glyphs().get(glyph_id).is_some()
250        || font_ref.color_glyphs().get(glyph_id).is_some()
251        || font_ref
252            .bitmap_strikes()
253            .glyph_for_size(skrifa::instance::Size::unscaled(), glyph_id)
254            .is_some()
255}
256
257#[cfg(test)]
258mod tests {
259    use std::sync::Arc;
260
261    use super::*;
262
263    #[test]
264    fn scripts() {
265        assert_eq!(script_of('a'), Some(Script::from_bytes(*b"Latn")));
266        assert_eq!(script_of('日'), Some(Script::from_bytes(*b"Hani")));
267        assert_eq!(script_of('ع'), Some(Script::from_bytes(*b"Arab")));
268        assert_eq!(script_of('1'), None);
269        assert_eq!(script_of('⌥'), None);
270        assert_eq!(script_of('\u{0301}'), None); // combining acute accent
271    }
272
273    #[test]
274    #[ignore = "Depends on which fonts are installed on this machine"]
275    #[expect(clippy::print_stdout)]
276    fn finds_system_fonts() {
277        let provider = SystemFontProvider::new();
278        for (c, script) in [
279            ('日', "CJK"),
280            ('ع', "Arabic"),
281            ('א', "Hebrew"),
282            ('क', "Devanagari"),
283            ('ก', "Thai"),
284            ('⌥', "Symbol"),
285        ] {
286            let cluster = c.to_string();
287            let request = FallbackRequest {
288                cluster: &cluster,
289                family: &FontFamily::Proportional,
290            };
291            let Some(insert) = provider.font_for(&request) else {
292                panic!("No system font for {script} {c:?}");
293            };
294            println!("{script} {c:?}: {}", insert.name);
295            assert!(insert.name.starts_with("system:"));
296        }
297    }
298
299    #[test]
300    fn simplified_chinese_locales() {
301        let is_simplified = |locale| is_simplified_chinese(&Language::parse(locale).unwrap());
302        for locale in ["zh", "zh-CN", "zh-Hans", "zh-Hans-CN", "zh-SG"] {
303            assert!(is_simplified(locale), "{locale}");
304        }
305        for locale in ["zh-TW", "zh-HK", "zh-MO", "zh-Hant", "ja", "ko", "de-DE"] {
306            assert!(!is_simplified(locale), "{locale}");
307        }
308    }
309
310    /// A `zh-CN` locale should get a Chinese font for characters shared with Japanese,
311    /// even after fontique has looked up Han without a locale.
312    #[test]
313    #[ignore = "Depends on which fonts are installed on this machine"]
314    #[expect(clippy::print_stdout)]
315    fn zh_cn_locale_prefers_chinese_font() {
316        let provider = SystemFontProvider::new().with_locale(Some("zh-CN"));
317        let ja_provider = SystemFontProvider::new().with_locale(Some("ja"));
318        let font_name = |provider: &SystemFontProvider, c: char| {
319            let cluster = c.to_string();
320            let request = FallbackRequest {
321                cluster: &cluster,
322                family: &FontFamily::Proportional,
323            };
324            provider.font_for(&request).unwrap().name
325        };
326
327        // Each of these does a locale-less Han lookup in fontique:
328        for c in ['ก', '한'] {
329            font_name(&provider, c);
330        }
331        let zh = font_name(&provider, '直');
332        let ja = font_name(&ja_provider, '直');
333        println!("zh-CN: {zh}, ja: {ja}");
334        assert_ne!(zh, ja, "zh-CN should not get the Japanese font");
335    }
336
337    /// With a non-CJK locale, the Han fallback may be a Japanese font,
338    /// which lacks many Simplified and Traditional Chinese characters.
339    ///
340    /// Other scripts are looked up first, because that changes what fontique returns for Han.
341    #[test]
342    #[ignore = "Depends on which fonts are installed on this machine"]
343    #[expect(clippy::print_stdout)]
344    fn finds_chinese_chars_with_non_cjk_locale() {
345        let provider = SystemFontProvider::new().with_locale(Some("de-DE"));
346        for c in ['ไ', '한', 'م', 'न', '这', '还', '測', '個'] {
347            let cluster = c.to_string();
348            let request = FallbackRequest {
349                cluster: &cluster,
350                family: &FontFamily::Proportional,
351            };
352            let Some(insert) = provider.font_for(&request) else {
353                panic!("No system font for {c:?}");
354            };
355            println!("{c:?}: {}", insert.name);
356        }
357    }
358
359    #[test]
360    #[ignore = "Depends on which fonts are installed on this machine"]
361    fn renders_cjk_through_egui_context() {
362        let ctx = egui::Context::default();
363        let font_id = egui::FontId::proportional(14.0);
364        let mut output = ctx.run_ui(Default::default(), |ui| {
365            ui.fonts_mut(|fonts| assert!(!fonts.has_glyph(&font_id, '日')));
366        });
367        output.textures_delta.clear();
368
369        ctx.add_font_provider(Arc::new(SystemFontProvider::new()));
370        let mut output = ctx.run_ui(Default::default(), |ui| {
371            ui.fonts_mut(|fonts| assert!(fonts.has_glyph(&font_id, '日')));
372            assert_eq!(ui.fonts(|fonts| fonts.discovered_fonts().len()), 1);
373        });
374        output.textures_delta.clear();
375    }
376}