capri-ui: add i18n module
This commit is contained in:
1 file changed
+130
@@ -0,0 +1,130 @@
|
||||
//! Interface translations: English source strings are the keys of
|
||||
//! `assets/i18n/interface-locales.json`; a missing locale or key falls back to English.
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
static BUNDLE_JSON: &[u8] = include_bytes!("../../../assets/i18n/interface-locales.json");
|
||||
|
||||
/// Bundle order; the JSON object order is lost by the map below.
|
||||
pub const LOCALES: [&str; 50] = [
|
||||
"en", "ru", "de", "fr", "es", "it", "pt", "nl", "pl", "uk", "cs", "sk", "bg", "hr", "sr", "sl", "ro", "hu", "el", "da", "no",
|
||||
"sv", "fi", "et", "lv", "lt", "is", "ca", "ar", "he", "fa", "ur", "hi", "bn", "ta", "te", "mr", "gu", "pa", "zh", "ja", "ko",
|
||||
"vi", "th", "id", "ms", "tl", "tr", "sw", "af",
|
||||
];
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Bundle {
|
||||
locales: HashMap<String, Locale>,
|
||||
#[serde(rename = "languageNames")]
|
||||
language_names: HashMap<String, Box<RawValue>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Locale {
|
||||
#[serde(rename = "nativeName")]
|
||||
native_name: String,
|
||||
direction: String,
|
||||
messages: Box<RawValue>,
|
||||
}
|
||||
|
||||
fn bundle() -> &'static Bundle {
|
||||
static BUNDLE: OnceLock<Bundle> = OnceLock::new();
|
||||
BUNDLE.get_or_init(|| serde_json::from_slice(BUNDLE_JSON).expect("bundled interface locales"))
|
||||
}
|
||||
|
||||
struct Active {
|
||||
id: String,
|
||||
rtl: bool,
|
||||
messages: HashMap<String, String>,
|
||||
names: HashMap<String, String>,
|
||||
}
|
||||
|
||||
static ACTIVE: RwLock<Option<Arc<Active>>> = RwLock::new(None);
|
||||
|
||||
fn load(id: &str) -> Active {
|
||||
let bundle = bundle();
|
||||
let id = if bundle.locales.contains_key(id) { id } else { "en" };
|
||||
let locale = &bundle.locales[id];
|
||||
let names = bundle.language_names.get(id).and_then(|raw| serde_json::from_str(raw.get()).ok()).unwrap_or_default();
|
||||
Active {
|
||||
id: id.to_string(),
|
||||
rtl: locale.direction == "rtl",
|
||||
messages: serde_json::from_str(locale.messages.get()).unwrap_or_default(),
|
||||
names,
|
||||
}
|
||||
}
|
||||
|
||||
fn active() -> Arc<Active> {
|
||||
if let Some(a) = ACTIVE.read().clone() {
|
||||
return a;
|
||||
}
|
||||
let a = Arc::new(load("en"));
|
||||
*ACTIVE.write() = Some(a.clone());
|
||||
a
|
||||
}
|
||||
|
||||
/// Switches the interface language; unknown ids mean English.
|
||||
pub fn set_locale(id: &str) {
|
||||
if ACTIVE.read().as_ref().is_some_and(|a| a.id == id) {
|
||||
return;
|
||||
}
|
||||
*ACTIVE.write() = Some(Arc::new(load(id)));
|
||||
}
|
||||
|
||||
pub fn locale() -> String {
|
||||
active().id.clone()
|
||||
}
|
||||
|
||||
/// Arabic, Hebrew, Persian and Urdu. egui has no bidi shaping: text is right-aligned only.
|
||||
pub fn rtl() -> bool {
|
||||
active().rtl
|
||||
}
|
||||
|
||||
/// Translation of an English UI key; unknown keys (owner data) pass through unchanged.
|
||||
pub fn t(key: &str) -> String {
|
||||
active().messages.get(key).cloned().unwrap_or_else(|| key.to_string())
|
||||
}
|
||||
|
||||
/// `t` with `{name}` placeholders replaced.
|
||||
pub fn tf(key: &str, values: &[(&str, &str)]) -> String {
|
||||
values.iter().fold(t(key), |text, (name, value)| text.replace(&format!("{{{name}}}"), value))
|
||||
}
|
||||
|
||||
/// Native name of an interface locale, for the language picker.
|
||||
pub fn native_name(id: &str) -> String {
|
||||
bundle().locales.get(id).map(|l| l.native_name.clone()).unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// Conversation language name in the interface language.
|
||||
pub fn language_name(id: &str) -> String {
|
||||
if let Some(name) = active().names.get(id) {
|
||||
return name.clone();
|
||||
}
|
||||
capri_core::persona::languages().iter().find(|l| l.id == id).map(|l| l.label.clone()).unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lookup_and_fallback() {
|
||||
// One test: the active locale is process-global.
|
||||
set_locale("fr");
|
||||
assert_ne!(t("Settings"), "Settings");
|
||||
assert_eq!(t("my own note"), "my own note");
|
||||
assert!(!rtl());
|
||||
assert_eq!(language_name("de"), "allemand");
|
||||
set_locale("he");
|
||||
assert!(rtl());
|
||||
set_locale("xx");
|
||||
assert_eq!(locale(), "en");
|
||||
assert_eq!(t("VOICE PENDING"), "PREPARING VOICE");
|
||||
assert_eq!(tf("{seconds} s", &[("seconds", "3")]), "3 s");
|
||||
assert_eq!(native_name("ru"), "Русский");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user