diff --git a/Cargo.lock b/Cargo.lock index 7c19092..9e520a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2459,6 +2459,7 @@ dependencies = [ "rfd", "serde", "serde_json", + "sys-locale", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 0eb3447..ed7cb99 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -23,6 +23,7 @@ image = { workspace = true } zip = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sys-locale = "0.3" rfd = { workspace = true } # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } @@ -33,7 +34,7 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration"] } +web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] } # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs new file mode 100644 index 0000000..4be466b --- /dev/null +++ b/crates/ui-egui/src/fonts.rs @@ -0,0 +1,92 @@ +//! 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 + +use std::sync::Arc; + +use egui::{FontData, FontFamily}; + +/// Candidate system font files: (path, face index in a collection). +#[cfg(not(target_arch = "wasm32"))] +fn system_files() -> 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"]; + 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"]; + 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)); + } + } + v +} + +/// Fallback fonts manager for the egui context. +#[derive(Default)] +pub struct UiFonts { + installed: bool, + data: Option>, +} + +impl UiFonts { + /// Update fallback fonts according to active language and whether the preferences dialog 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 { + 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; + } + + /// Whether an Arabic fallback font has been found and loaded. + pub fn covers_arabic(&self) -> bool { + self.data.is_some() + } + + fn load_arabic(&mut self) -> Option> { + if let Some(d) = &self.data { + return Some(d.clone()); + } + #[cfg(not(target_arch = "wasm32"))] + for (path, index) in system_files() { + 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); + } + } + log::warn!("no font found for Arabic text; system fonts may show boxes"); + None + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 68d287c..8f3d144 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,12 +1,167 @@ -//! Interface text. English only for now; every user-facing string goes through [`tr`] (or is -//! marked with [`n_`] where it is stored), so translations can be added without touching callers. +//! UI text lookup. Keys are the English strings, so English needs no table and a missing +//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`] +//! for text with `{name}` placeholders); each language is a static `(English, translation)` +//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it. -/// Mark a string for translation where it is stored; translate with [`tr`] where it is shown. +use std::collections::HashMap; +use std::fmt::Display; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicUsize, Ordering}; + +mod ar; + +pub struct Language { + /// BCP 47 code ("en", "ar"). + pub code: &'static str, + /// The language's own name, for the picker. + pub name: &'static str, + /// Its English name (the picker's fallback when no font can draw `name`). + pub english: &'static str, + /// `(English, translation)` pairs, in any order. + pub table: &'static [(&'static str, &'static str)], +} + +const COUNT: usize = 2; + +pub static LANGUAGES: [Language; COUNT] = + [Language { code: "en", name: "English", english: "English", table: &[] }, Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE }]; + +static MAPS: [OnceLock>; COUNT] = [const { OnceLock::new() }; COUNT]; +static CURRENT: AtomicUsize = AtomicUsize::new(0); + +/// Switch the UI language (unknown codes fall back to English). +pub fn set_language(code: &str) { + CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed); +} + +/// The current UI language. +pub fn current() -> &'static Language { + LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0]) +} + +/// Returns true if `code` is a right-to-left language (e.g. Arabic `"ar"`). +pub fn is_rtl_code(code: &str) -> bool { + craft_ui::direction::resolve(code, craft_ui::direction::Setting::Language) == craft_ui::direction::Direction::Rtl +} + +/// Returns true if the current UI language is right-to-left. +pub fn is_rtl() -> bool { + is_rtl_code(current().code) +} + +/// `text` in the current language (unchanged when it has no translation). +pub fn tr(text: &str) -> &str { + let i = CURRENT.load(Ordering::Relaxed); + let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text }; + if lang.table.is_empty() { + return text; + } + map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text) +} + +/// Marks a static string for translation where it is defined (gettext's `N_`); it is translated +/// with [`tr`] where it is shown. The key test collects both. pub const fn n_(text: &'static str) -> &'static str { text } -/// The text in the interface language. -pub fn tr(text: &str) -> &str { - text +/// `template` translated, with each `{name}` replaced by its value in `args`. +pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String { + let mut out = String::with_capacity(template.len() + 16); + let mut rest = tr(template); + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) { + Some((close, v)) => { + use std::fmt::Write as _; + let _ = write!(out, "{v}"); + rest = &after[close + 1..]; + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// The supported language for a locale such as "ar-EG", "ar-SA" ("en" when none matches). +pub fn language_for_locale(locale: &str) -> &'static str { + let lang = locale.split(['-', '_', '.', '@']).next().unwrap_or("").to_ascii_lowercase(); + match lang.as_str() { + "ar" => "ar", + l => LANGUAGES.iter().find(|x| x.code == l).map_or("en", |x| x.code), + } +} + +/// The operating system's (or browser's) UI language, for the first run. +pub fn os_language() -> &'static str { + #[cfg(not(target_arch = "wasm32"))] + let locale = sys_locale::get_locale(); + #[cfg(target_arch = "wasm32")] + let locale = web_sys::window().and_then(|w| w.navigator().language()); + locale.map_or("en", |l| language_for_locale(&l)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn language_switching_and_arabic_translations_work() { + set_language("en"); + assert_eq!(current().code, "en"); + assert_eq!(tr("Properties"), "Properties"); + assert!(!is_rtl()); + + set_language("ar"); + assert_eq!(current().code, "ar"); + assert_eq!(tr("Properties"), "الخصائص"); + assert_eq!(tr("Preferences"), "التفضيلات"); + assert_eq!(tr("New graph"), "مخطط جديد"); + assert_eq!(tr("Export outputs"), "تصدير المخرجات"); + assert_eq!(tr("Welcome to MaterialCraft"), "مرحباً بك في MaterialCraft"); + assert!(is_rtl()); + + // Live formatting + let formatted = trf("Hello {name}", &[("name", &"World")]); + assert_eq!(formatted, "Hello World"); + + // Fallback for unknown text + assert_eq!(tr("Unknown untranslated string 1234"), "Unknown untranslated string 1234"); + + // Reset to English + set_language("en"); + } + + #[test] + fn locale_detection() { + assert_eq!(language_for_locale("ar"), "ar"); + assert_eq!(language_for_locale("ar-EG"), "ar"); + assert_eq!(language_for_locale("ar_SA.UTF-8"), "ar"); + assert_eq!(language_for_locale("en-US"), "en"); + assert_eq!(language_for_locale("fr-FR"), "en"); + } + + #[test] + fn arabic_table_has_no_duplicate_keys() { + let mut seen = std::collections::HashSet::new(); + for (k, _) in ar::TABLE { + assert!(seen.insert(*k), "duplicate key in ar::TABLE: {k:?}"); + } + } + + #[test] + fn placeholders_match_between_key_and_arabic_translation() { + for (k, v) in ar::TABLE { + let mut kp: Vec<&str> = k.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect(); + let mut vp: Vec<&str> = v.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect(); + kp.sort(); + vp.sort(); + assert_eq!(kp, vp, "mismatched placeholders in {k:?} vs {v:?}"); + } + } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs new file mode 100644 index 0000000..8fec061 --- /dev/null +++ b/crates/ui-egui/src/i18n/ar.rs @@ -0,0 +1,373 @@ +//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("$pos", "$pos"), + ("$size", "$size"), + ("(checker)", "(رقعة شطرنج)"), + ("1024 px", "1024 بكسل"), + ("16 bits", "16 بت"), + ("16 bits per channel", "16 بت لكل قناة"), + ("16 bits per channel float (HDR)", "16 بت لكل قناة فاصلة عائمة (HDR)"), + ("2048 px", "2048 بكسل"), + ("256 px", "256 بكسل"), + ("2D View", "عرض ثنائي الأبعاد"), + ("32 bits float", "32 بت فاصلة عائمة"), + ("32 bits per channel float (HDR)", "32 بت لكل قناة فاصلة عائمة (HDR)"), + ("3D pan limit (mesh radii)", "حد التحريك ثلاثي الأبعاد (أنصاف أقطار المجسم)"), + ("3D pan speed", "سرعة التحريك ثلاثي الأبعاد"), + ("3D View", "عرض ثلاثي الأبعاد"), + ("512 px", "512 بكسل"), + ("8 bits", "8 بت"), + ("8 bits per channel", "8 بت لكل قناة"), + ("About MaterialCraft", "حول MaterialCraft"), + ("About MaterialCraft...", "حول MaterialCraft..."), + ("Absolute", "مطلق"), + ("Accent color", "لون التمييز"), + ("Actual pixels", "البكسلات الفعلية"), + ("Add", "إضافة"), + ("Add Comment", "إضافة تعليق"), + ("Add comment", "إضافة تعليق"), + ("Add Dot node", "إضافة عقدة نقطية"), + ("Add Frame", "إضافة إطار"), + ("Add frame around selection", "إضافة إطار حول التحديد"), + ("Add frame around the selection", "إضافة إطار حول التحديد"), + ("Add Navigation pin", "إضافة دبوس تنقل"), + ("Add navigation pin", "إضافة دبوس تنقل"), + ("Add node", "إضافة عقدة"), + ("Add Output nodes with usages (base color, normal, ...) to see the material", "أضف عُقد مخرجات مع استخداماتها (اللون الأساسي، الناظم، ...) لمعاينة المادة"), + ("Align centers horizontally", "محاذاة المراكز أفقياً"), + ("Align centers vertically", "محاذاة المراكز رأسياً"), + ("Align left", "محاذاة لليسار"), + ("Align top", "محاذاة للأعلى"), + ("All nodes", "كل العقد"), + ("Amber", "كهرماني"), + ("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."), + ("And", "و (And)"), + ("Apply", "تطبيق"), + ("Arc tangent 2", "ظل زاوية قوسي 2"), + ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), + ("As JSON", "بصيغة JSON"), + ("Atomic nodes", "عقد أولية"), + ("Attributes", "السمات"), + ("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"), + ("Bad function", "دالة غير صالحة"), + ("Base parameters", "المعلمات الأساسية"), + ("Bind to input", "ربط بالمدخل"), + ("Bit depth", "عمق البت"), + ("Blends", "عمليات الدمج"), + ("Blue", "أزرق"), + ("Boolean", "منطقي"), + ("Brick wall", "جدار طوب"), + ("Brightness", "السطوع"), + ( + "Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.", + "أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك.", + ), + ("Cache", "الذاكرة المؤقتة"), + ("Camera", "الكاميرا"), + ("Cancel", "إلغاء"), + ("Cast", "تحويل النوع"), + ("Ceil", "الحد الأعلى (Ceil)"), + ("Choose a folder to export to", "اختر مجلداً للتصدير إليه"), + ("Clamp", "تقييد النطاق (Clamp)"), + ("Clear cache", "مسح الذاكرة المؤقتة"), + ("Clear recent packages", "مسح الحزم الأخيرة"), + ("Close all", "إغلاق الكل"), + ("Community (Discord)", "المجتمع (Discord)"), + ("Comparison", "مقارنة"), + ("Compute graph", "حساب المخطط"), + ("Computing...", "جاري الحساب..."), + ("Console", "وحدة التحكم"), + ("Constant", "ثابت"), + ("Control", "تحكم"), + ("Copper", "نحاسي"), + ("Copy", "نسخ"), + ("Copy selection", "نسخ التحديد"), + ("Coral", "مرجاني"), + ("Cosine", "جيب التمام (Cosine)"), + ("Couldn't export", "تعذر التصدير"), + ("Couldn't import", "تعذر الاستيراد"), + ("Couldn't load", "تعذر التحميل"), + ("Couldn't open", "تعذر الفتح"), + ("Couldn't save", "تعذر الحفظ"), + ("Create", "إنشاء"), + ("Create graph from selection", "إنشاء مخطط من التحديد"), + ("Create graph in", "إنشاء مخطط في"), + ("Cube", "مكعب"), + ("Cut", "قص"), + ("Cyan", "سماوي"), + ("Cylinder", "أسطوانة"), + ("Dark", "داكن"), + ("Default", "افتراضي"), + ("Delete", "حذف"), + ("Delete and relink", "حذف وإعادة ربط"), + ("Delete input", "حذف المدخل"), + ("Delete preset", "حذف الإعداد المسبق"), + ("Delete selection", "حذف التحديد"), + ("Disable selection", "تعطيل التحديد"), + ("Display", "عرض"), + ("Distribute horizontally", "توزيع أفقي"), + ("Distribute vertically", "توزيع رأسي"), + ("Division", "قسمة"), + ("Documentation", "التوثيق"), + ("Documentation...", "التوثيق..."), + ("Dot Product", "الجداء السلمي (Dot Product)"), + ("Double-click a node to show it here", "انقر نقراً مزدوجاً على عقدة لعرضها هنا"), + ("Downloaded", "تم التنزيل"), + ("Duplicate", "تكرار"), + ("Duplicate selection", "تكرار التحديد"), + ("Duplicate selection without link", "تكرار التحديد بدون ربط"), + ("Edit", "تحرير"), + ("Edit function graph...", "تحرير مخطط الدوال..."), + ("Empty", "فارغ"), + ("Empty package", "حزمة فارغة"), + ("Engine", "المحرك"), + ("Environment", "البيئة"), + ("Environment background", "خلفية البيئة"), + ("Equal", "مساوٍ"), + ("Exit", "خروج"), + ("Explorer", "المستكشف"), + ("Exponential", "دالة أسية (Exp)"), + ("Export", "تصدير"), + ("Export material...", "تصدير المادة..."), + ("Export outputs", "تصدير المخرجات"), + ("Export outputs...", "تصدير المخرجات..."), + ("Export outputs... (Ctrl+Shift+E)", "تصدير المخرجات... (Ctrl+Shift+E)"), + ("Exported", "تم التصدير"), + ("Expose as graph input", "كشف كمدخل للمخطط"), + ("Exposure", "التعريض"), + ("File", "ملف"), + ("File names", "أسماء الملفات"), + ("files", "ملفات"), + ("Filters", "مرشحات"), + ("Fit", "ملاءمة"), + ("Float", "فاصلة عائمة (Float)"), + ("Float2", "فاصلة عائمة ثنائية (Float2)"), + ("Float3", "فاصلة عائمة ثلاثية (Float3)"), + ("Float4", "فاصلة عائمة رباعية (Float4)"), + ("Flood fill", "تعبئة متصلة (Flood fill)"), + ("Floor", "الحد الأدنى (Floor)"), + ("Folder", "المجلد"), + ("Format", "الصيغة"), + ("Fractional part", "الجزء الكسري"), + ("Frame all", "تأطير الكل"), + ("Frame all (F)", "تأطير الكل (F)"), + ("Frame all / the selection", "تأطير الكل / التحديد"), + ("Front", "أمامي"), + ("Full size", "الحجم الكامل"), + ("full size", "الحجم الكامل"), + ("Function", "دالة"), + ("function", "دالة"), + ("Function graph", "مخطط الدوال"), + ("function nodes", "عقد الدوال"), + ("Function of", "دالة لـ"), + ("Get variable", "جلب متغير"), + ("Go to pin", "الانتقال إلى الدبوس"), + ("Graph", "مخطط"), + ("Graph instance", "نسخة المخطط"), + ("Graph items", "عناصر المخطط"), + ("Graph name", "اسم المخطط"), + ("Graph's format", "صيغة المخطط"), + ("Graph...", "مخطط..."), + ("Graphs in this package", "المخططات في هذه الحزمة"), + ("Greater", "أكبر من"), + ("Greater or equal", "أكبر من أو يساوي"), + ("Green", "أخضر"), + ("Height (parallax) depth", "عمق الارتفاع (اختلاف المنظر)"), + ("Help", "مساعدة"), + ("Histogram", "المخطط البياني (Histogram)"), + ("History", "السجل"), + ("Home", "الرئيسية"), + ("Home screen...", "الشاشة الرئيسية..."), + ("Icons", "أيقونات"), + ("If...Else", "إذا...وإلا (If...Else)"), + ("Import bitmap...", "استيراد صورة نقطية..."), + ("Imported", "تم الاستيراد"), + ("Input parameters", "معلمات المدخلات"), + ("Input previews", "معاينات المدخلات"), + ("Instance parameters", "معلمات النسخة"), + ("Integer", "عدد صحيح"), + ("Interface scale", "حجم واجهة المستخدم"), + ("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."), + ("Key at", "مفتاح عند"), + ("Language", "اللغة"), + ("Last compute", "آخر حساب"), + ("Lava rock", "صخور بركانية"), + ("Length", "الطول"), + ("Library", "المكتبة"), + ("Light", "فاتح"), + ("Linear interpolation", "استيفاء خطي (Lerp)"), + ("List", "قائمة"), + ("Load mesh...", "تحميل مجسم..."), + ("Logarithm", "لوغاريتم"), + ("Logical", "منطقي"), + ("Lower", "أصغر من"), + ("Lower or equal", "أصغر من أو يساوي"), + ("Mat ball", "كرة المادة"), + ("Material filters", "مرشحات المواد"), + ("Maximum", "الحد الأقصى"), + ("Medium dark", "داكن متوسط"), + ("Medium light", "فاتح متوسط"), + ("Minimum", "الحد الأدنى"), + ("Modulo", "باقي القسمة (Modulo)"), + ("Mossy ground", "أرضية مغطاة بالطحالب"), + ("Multiplication", "ضرب"), + ("Name", "الاسم"), + ("Negation", "نفي / سالب"), + ("New", "جديد"), + ("New graph", "مخطط جديد"), + ("New graph...", "مخطط جديد..."), + ("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"), + ("New random seed", "بذرة عشوائية جديدة"), + ("Night", "ليل"), + ("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"), + ("No graph is open", "لا يوجد مخطط مفتوح"), + ("No matching node", "لا توجد عقدة مطابقة"), + ("No presets yet", "لا توجد إعدادات مسبقة بعد"), + ("No recent packages", "لا توجد حزم حديثة"), + ("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"), + ("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."), + ("Noises", "تشويشات"), + ("None", "بلا"), + ("Normal", "الناظم (Normal)"), + ("Normalize", "تسوية (Normalize)"), + ("Not", "ليس (Not)"), + ("Not equal", "غير مساوٍ"), + ("Nothing matches", "لا توجد تطابقات"), + ("Open", "فتح"), + ("Open graph", "فتح المخطط"), + ("Open package...", "فتح حزمة..."), + ("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"), + ("Open...", "فتح..."), + ("Opened", "تم الفتح"), + ("Operator", "معامل حسابي"), + ("Ops", "عمليات"), + ("Or", "أو (Or)"), + ("Output format", "صيغة المخرج"), + ("Output size", "حجم المخرج"), + ("Outputs", "المخرجات"), + ("Overcast", "غائم"), + ("Painted metal plates", "صفائح معدنية مطلية"), + ("Pan the camera", "تحريك الكاميرا"), + ("Pan the graph", "تحريك المخطط"), + ("Parent size:", "حجم العنصر الأصل:"), + ("Paste", "لصق"), + ("Patterns", "أنماط"), + ("PBR material (outputs only)", "مادة PBR (مخرجات فقط)"), + ("Perlin noise", "تشويش بيرلين (Perlin noise)"), + ("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"), + ("Pink", "وردي"), + ("Plane", "مستوى"), + ("Polished marble", "رخام مصقول"), + ("Power", "قوة / أس (Power)"), + ("Preferences", "التفضيلات"), + ("Preferences...", "التفضيلات..."), + ("Preset name", "اسم الإعداد المسبق"), + ("Presets", "الإعدادات المسبقة"), + ("Preview", "معاينة"), + ("Preview size", "حجم المعاينة"), + ("Preview size while editing", "حجم المعاينة أثناء التحرير"), + ("Properties", "الخصائص"), + ("Random", "عشوائي"), + ("Random seed", "بذرة عشوائية"), + ("Recent", "الأخيرة"), + ("Recent packages", "الحزم الأخيرة"), + ("Redo", "إعادة"), + ("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"), + ("Relative to input", "نسبي إلى المدخل"), + ("Relative to parent", "نسبي إلى الأصل"), + ("Reload resources", "إعادة تحميل الموارد"), + ("Remove function", "إزالة الدالة"), + ("Render time", "وقت التصيير"), + ("Renderer", "المصير"), + ("Report a bug...", "الإبلاغ عن خطأ..."), + ("Reset layout", "إعادة ضبط التخطيط"), + ("Reset parameters", "إعادة ضبط المعلمات"), + ("Reset scene", "إعادة ضبط المشهد"), + ("Reset to default", "إعادة ضبط للافتراضي"), + ("Resources", "الموارد"), + ("Revert", "استرجاع"), + ("Right-click a node parameter > Expose as graph input", "انقر بزر الفأرة الأيمن على معلمة العقدة > كشف كمدخل للمخطط"), + ( + "Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.", + "انقر بزر الفأرة الأيمن أو مفتاح المسافة لإضافة عمليات؛ اسحب من نقطة المخرج إلى المدخل؛ العقدة المميزة بنجمة هي النتيجة.", + ), + ("Rotation", "التدوير"), + ("Rounded cube", "مكعب مدور الحواف"), + ("Rusty metal", "معدن صدئ"), + ("Sample Color", "عينة لونية"), + ("Sample Gray", "عينة تدرج رمادي"), + ("Samplers", "عينات"), + ("Samples", "عينات"), + ("Save", "حفظ"), + ("Save (Ctrl+S)", "حفظ (Ctrl+S)"), + ("Save as...", "حفظ باسم..."), + ("Save image...", "حفظ الصورة..."), + ("Save package", "حفظ الحزمة"), + ("Save preset", "حفظ الإعداد المسبق"), + ("Saved", "تم الحفظ"), + ("Scene", "المشهد"), + ("Search", "بحث"), + ("Search nodes...", "البحث في العقد..."), + ("Select all", "تحديد الكل"), + ("Select downstream nodes", "تحديد العقد اللاحقة"), + ("Select upstream nodes", "تحديد العقد السابقة"), + ("Send to TextureCraft", "إرسال إلى TextureCraft"), + ("Sent to TextureCraft: find it on the shelf under My smart materials", "أُرسل إلى TextureCraft: ستجده على الرف ضمن موادي الذكية"), + ("Set function...", "تعيين دالة..."), + ("Shortcuts", "الاختصارات"), + ("Shortcuts list...", "قائمة الاختصارات..."), + ("Show at startup", "إظهار عند بدء التشغيل"), + ("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"), + ("Show node thumbnails", "إظهار الصور المصغرة للعقد"), + ("Showing", "عرض"), + ("Side", "جانبي"), + ("Sine", "جيب الزاوية (Sine)"), + ("Size", "الحجم"), + ("Specific parameters", "المعلمات المخصصة"), + ("Sphere", "كرة"), + ("Square root", "جذر تربيعي"), + ("Stone tiles", "بلاط حجري"), + ("Studio", "استوديو"), + ("Subtraction", "طرح"), + ("Sunset", "غروب"), + ("SVG", "رسوم متجهة (SVG)"), + ("Swizzle", "إعادة ترتيب القنوات (Swizzle)"), + ("Tangent", "ظل الزاوية (Tangent)"), + ("Templates", "القوالب"), + ("Text", "نص"), + ("Texture generators", "مولدات الخامات"), + ("The instanced graph is missing", "المخطط المنسوخ مفقود"), + ("This graph exposes no inputs", "هذا المخطط لا يكشف أي مدخلات"), + ("This package", "هذه الحزمة"), + ("threads", "خيوط معالجة"), + ("Tile 3x3", "تكرار 3x3"), + ("Tiling", "التكرار"), + ("Tiling (H and V)", "التكرار (أفقياً ورأسياً)"), + ("To Float", "إلى فاصلة عائمة"), + ("To Integer", "إلى عدد صحيح"), + ("Tools", "أدوات"), + ("Top", "علوي"), + ("Torus", "شكل حلقي (Torus)"), + ("Transforms", "التحويلات"), + ("Turn the environment", "تدوير البيئة"), + ("Unbind", "فك الارتباط"), + ("Undo", "تراجع"), + ("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"), + ("Use as result", "استخدام كنتيجة"), + ("Variables", "متغيرات"), + ("Vector", "متجه"), + ("Vector Float2", "متجه ثنائي (Float2)"), + ("Vector Float3", "متجه ثلاثي (Float3)"), + ("Vector Float4", "متجه رباعي (Float4)"), + ("Version", "الإصدار"), + ("View in 2D view", "عرض في العرض ثنائي الأبعاد"), + ("Violet", "بنفسجي"), + ("Weathering", "التجوية والتقادم"), + ("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"), + ("Wicker weave", "نسيج قش"), + ("Windows", "نوافذ"), + ("Wood planks", "ألواح خشبية"), + ("Woven fabric", "قماش منسوج"), + ("Zoom the graph and the views", "تقريب المخطط وطرق العرض"), +]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 184fe83..68aac01 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -11,6 +11,7 @@ pub mod control; pub mod cook; pub mod docking; pub mod explorer; +pub mod fonts; pub mod function_editor; pub mod graph_view; pub mod i18n; @@ -70,6 +71,8 @@ pub struct MaterialCraftApp { #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, styled: Option<(theme::Brightness, theme::Accent)>, + /// Fallback fonts for Arabic. + pub fonts: fonts::UiFonts, /// The icon font is installed (it takes effect on the frame after `set_fonts`). fonts_ready: bool, } @@ -79,6 +82,7 @@ impl MaterialCraftApp { let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_default(); theme::install(&cc.egui_ctx); let mut app = MaterialCraftApp::headless(session, ui); + i18n::set_language(&app.ui.prefs.language); app.fonts_ready = true; app.ui.windows.home = app.ui.prefs.show_home; app @@ -109,8 +113,10 @@ impl MaterialCraftApp { last_time: 0.0, next_autosave, styled: None, + fonts: fonts::UiFonts::default(), fonts_ready: false, }; + i18n::set_language(&app.ui.prefs.language); app.apply_prefs(); app } @@ -206,6 +212,8 @@ impl MaterialCraftApp { ctx.request_repaint(); return; } + i18n::set_language(&self.ui.prefs.language); + self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences); let now = ctx.input(|i| i.time); let dt = (now - self.last_time) as f32; if dt > 0.0 { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b6d2a3..1c9fc42 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -11,6 +11,8 @@ use crate::theme::{Accent, Brightness}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Prefs { + /// UI language code (`i18n::LANGUAGES`). + pub language: String, pub brightness: Brightness, pub accent: Accent, pub ui_scale: f32, @@ -31,6 +33,7 @@ pub struct Prefs { impl Default for Prefs { fn default() -> Self { Prefs { + language: crate::i18n::os_language().into(), brightness: Brightness::default(), accent: Accent::default(), ui_scale: 1.0, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 13ee6b8..00c3e74 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -271,8 +271,17 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; - modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 300.0), |ui| { + modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| { let p = &mut app.ui.prefs; + let current_lang = crate::i18n::current(); + crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| { + for l in &crate::i18n::LANGUAGES { + if ui.selectable_label(p.language == l.code, l.name).clicked() { + p.language = l.code.to_owned(); + crate::i18n::set_language(&p.language); + } + } + }); crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| { for b in Brightness::ALL { ui.selectable_value(&mut p.brightness, b, tr(b.label())); diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0fc1308..fc92f43 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -8,6 +8,7 @@ so catalogs can be added without touching callers. Today only English ships. | Language | Code | Status | Notes | |---|---|---|---| | English | `en` | Complete | Source language | +| Arabic | `ar` | Complete | Full UI translation table (`crates/ui-egui/src/i18n/ar.rs`), system font fallbacks (Segoe UI / SF Arabic / Noto Sans Arabic), live language picker in Preferences | | French, German, Spanish, Portuguese (Brazil), Italian | `fr`, `de`, `es`, `pt-br`, `it` | Not started | Planned with the shared craft-i18n catalogs | | Japanese, Chinese (Simplified), Korean | `ja`, `zh-hans`, `ko` | Not started | Needs the craft-fonts CJK faces (`CRAFT_FONTS_DIR`), as in TextureCraft | @@ -15,4 +16,5 @@ so catalogs can be added without touching callers. Today only English ships. | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Add complete Arabic (`ar`) UI localization and font fallbacks | | 2026-11-02 | major | First version |