Skip to content
157 changes: 109 additions & 48 deletions crates/ui-egui/src/fonts.rs
Original file line number Diff line number Diff line change
@@ -1,92 +1,153 @@
//! Arabic fallback fonts for the UI. egui's default fonts have no Arabic glyphs, so translated
//! UIs need fallback fonts from the operating system.
//!
//! Windows: Segoe UI, Tahoma, Arial
//! macOS: SF Arabic, Geeza Pro, Arial Unicode
//! Linux: Noto Sans Arabic, DejaVu Sans
//! System fallback fonts for Arabic and Hebrew UI text.
//! Both scripts are requested when the language picker is visible, so their
//! native-script language names can be drawn before the user selects them.
//! No font binaries are bundled with MaterialCraft by this module.

use std::sync::Arc;

use egui::{FontData, FontFamily};

/// Candidate system font files: (path, face index in a collection).
/// Existing system font candidates, ordered by preference; Hebrew and Arabic
/// have separate lists because an Arabic-only face cannot draw Hebrew.
#[cfg(not(target_arch = "wasm32"))]
fn system_files() -> Vec<(std::path::PathBuf, u32)> {
fn system_files(hebrew: bool) -> Vec<(std::path::PathBuf, u32)> {
use std::path::PathBuf;
let mut v: Vec<(PathBuf, u32)> = Vec::new();
if cfg!(windows) {
let fonts = PathBuf::from(std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into())).join("Fonts");
let files: &[&str] = &["segoeui.ttf", "tahoma.ttf", "arial.ttf"];
let fonts = PathBuf::from(std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into()))
.join("Fonts");
let files: &[&str] = if hebrew {
&["segoeui.ttf", "arial.ttf", "david.ttf", "tahoma.ttf"]
} else {
&["segoeui.ttf", "tahoma.ttf", "arial.ttf"]
};
v.extend(files.iter().map(|f| (fonts.join(f), 0)));
} else if cfg!(target_os = "macos") {
let files: &[&str] = &["/System/Library/Fonts/SFArabic.ttf", "/System/Library/Fonts/Supplemental/GeezaPro.ttc"];
let files: &[&str] = if hebrew {
&[
"/System/Library/Fonts/SFHebrew.ttf",
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
]
} else {
&[
"/System/Library/Fonts/SFArabic.ttf",
"/System/Library/Fonts/Supplemental/GeezaPro.ttc",
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
]
};
v.extend(files.iter().map(|f| (PathBuf::from(f), 0)));
v.push((PathBuf::from("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"), 0));
} else {
for f in [
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf",
"/usr/local/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
"/usr/local/share/fonts/dejavu/DejaVuSans.ttf",
] {
v.push((PathBuf::from(f), 0));
}
let files: &[&str] = if hebrew {
&[
"/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf",
"/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf",
"/usr/share/fonts/google-noto/NotoSansHebrew-Regular.ttf",
"/usr/local/share/fonts/noto/NotoSansHebrew-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
]
} else {
&[
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf",
"/usr/local/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
"/usr/local/share/fonts/dejavu/DejaVuSans.ttf",
]
};
v.extend(files.iter().map(|f| (PathBuf::from(f), 0)));
}
v
}

/// Fallback fonts manager for the egui context.
/// Loaded system faces persist as egui fallbacks when the user changes language.
#[derive(Default)]
pub struct UiFonts {
installed: bool,
data: Option<Arc<FontData>>,
attempted_arabic: bool,
attempted_hebrew: bool,
arabic: Option<Arc<FontData>>,
hebrew: Option<Arc<FontData>>,
}

impl UiFonts {
/// Update fallback fonts according to active language and whether the preferences dialog is open.
/// Install a font if its script is selected, or both while the picker is open.
pub fn update(&mut self, ctx: &egui::Context, language: &str, preferences_open: bool) {
let want_arabic = language == "ar" || preferences_open;
if !want_arabic || self.installed {
let want_hebrew = language == "he" || preferences_open;
let mut changed = false;
if want_arabic && !self.attempted_arabic {
self.attempted_arabic = true;
self.arabic = Self::load_system(false);
changed = true;
}
if want_hebrew && !self.attempted_hebrew {
self.attempted_hebrew = true;
self.hebrew = Self::load_system(true);
changed = true;
}
if !changed {
return;
}
let Some(data) = self.load_arabic() else { return };

let mut defs = crate::theme::font_definitions();
let name = "script-Arab".to_string();
defs.font_data.insert(name.clone(), data);
defs.families.entry(FontFamily::Proportional).or_default().push(name.clone());
defs.families.entry(FontFamily::Monospace).or_default().push(name);
ctx.set_fonts(defs);
self.installed = true;
let mut installed_any = false;
for (name, data) in [
("script-Arab", self.arabic.as_ref()),
("script-Hebr", self.hebrew.as_ref()),
] {
if let Some(data) = data {
let name = name.to_string();
defs.font_data.insert(name.clone(), data.clone());
defs.families
.entry(FontFamily::Proportional)
.or_default()
.push(name.clone());
defs.families
.entry(FontFamily::Monospace)
.or_default()
.push(name);
installed_any = true;
}
}
if installed_any {
ctx.set_fonts(defs);
}
}

/// Whether an Arabic fallback font has been found and loaded.
/// Whether an Arabic fallback was found and loaded.
pub fn covers_arabic(&self) -> bool {
self.data.is_some()
self.arabic.is_some()
}

fn load_arabic(&mut self) -> Option<Arc<FontData>> {
if let Some(d) = &self.data {
return Some(d.clone());
}
/// Whether a Hebrew fallback was found and loaded.
pub fn covers_hebrew(&self) -> bool {
self.hebrew.is_some()
}

fn load_system(hebrew: bool) -> Option<Arc<FontData>> {
#[cfg(not(target_arch = "wasm32"))]
for (path, index) in system_files() {
let Ok(meta) = std::fs::metadata(&path) else { continue };
for (path, index) in system_files(hebrew) {
let Ok(meta) = std::fs::metadata(&path) else {
continue;
};
if !meta.is_file() || meta.len() == 0 || meta.len() > (128 << 20) {
continue;
}
if let Ok(bytes) = std::fs::read(&path) {
let mut data = FontData::from_owned(bytes);
data.index = index;
let arc = Arc::new(data);
self.data = Some(arc.clone());
log::info!("UI font fallback for Arabic: {}", path.display());
return Some(arc);
let name = if hebrew { "Hebrew" } else { "Arabic" };
log::info!("UI font fallback for {}: {}", name, path.display());
return Some(Arc::new(data));
}
}
log::warn!("no font found for Arabic text; system fonts may show boxes");
let name = if hebrew { "Hebrew" } else { "Arabic" };
log::warn!(
"no font found for {} UI text; system fonts may show boxes",
name
);
None
}
}