egui_system_font_provider/
lib.rs1use 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
30pub struct SystemFontProvider {
40 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 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 #[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 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 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 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
168fn 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
184static 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
196fn 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
205fn 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
214fn other_locales(script: Script) -> &'static [Language] {
218 if script == HAN { &HAN_LOCALES } else { &[] }
219}
220
221fn 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
233fn 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); }
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 #[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 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 #[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}