pub use fluent::FluentArgs;
use fluent::FluentResource;
use fluent::bundle::FluentBundle;
use std::collections::HashMap;
use std::sync::{LazyLock, RwLock};
use unic_langid::LanguageIdentifier;
const DEFAULT_LOCALE: &str = "en";
const FALLBACK_LOCALE: &str = "en";
#[cfg(feature = "tokio")]
tokio::task_local! {
pub static TASK_LOCALE: String;
}
static GLOBAL_LOCALE: RwLock<String> = RwLock::new(String::new());
type ConcurrentBundle = FluentBundle<FluentResource, intl_memoizer::concurrent::IntlLangMemoizer>;
static BUNDLES: LazyLock<RwLock<HashMap<String, ConcurrentBundle>>> = LazyLock::new(|| {
let mut bundles = HashMap::new();
let en_bundle = create_bundle("en-US", include_str!("../locales/en-US/main.ftl"));
let ru_bundle = create_bundle("ru-RU", include_str!("../locales/ru-RU/main.ftl"));
bundles.insert("en".to_string(), en_bundle);
bundles.insert("ru".to_string(), ru_bundle);
RwLock::new(bundles)
});
fn create_bundle(lang: &str, source: &str) -> ConcurrentBundle {
let resource = FluentResource::try_new(source.to_string())
.expect("Failed to parse embedded core FTL resource");
let lang_id: LanguageIdentifier = lang
.parse()
.expect("Invalid language identifier for bundle creation");
let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
bundle.set_use_isolating(false);
bundle
.add_resource(resource)
.expect("Failed to add resource to core bundle");
bundle
}
pub fn register_resource(lang: &str, source: &'static str) {
let resource = match FluentResource::try_new(source.to_string()) {
Ok(res) => res,
Err((res, errors)) => {
log::error!(
"Syntax errors parsing external FTL for locale '{}': {:?}",
lang,
errors
);
res
}
};
let short_lang = lang.split('-').next().unwrap_or(lang).to_lowercase();
if let Ok(mut bundles) = BUNDLES.write() {
if let Some(bundle) = bundles.get_mut(&short_lang) {
let _ = bundle.add_resource_overriding(resource);
} else {
let lang_id: LanguageIdentifier = match lang.parse() {
Ok(id) => id,
Err(_) => DEFAULT_LOCALE.parse().expect("Failed fallback lang_id"),
};
let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
bundle.set_use_isolating(false);
let _ = bundle.add_resource(resource);
bundles.insert(short_lang, bundle);
}
}
}
pub fn set_global_locale(locale: &str) {
if let Ok(mut global) = GLOBAL_LOCALE.write() {
*global = locale.to_lowercase();
}
}
fn get_current_locale() -> String {
#[cfg(feature = "tokio")]
{
if let Ok(task_locale) = TASK_LOCALE.try_with(|l| l.clone()) {
if !task_locale.is_empty() {
return task_locale;
}
}
}
if let Ok(global) = GLOBAL_LOCALE.read() {
if !global.is_empty() {
return global.clone();
}
}
sys_locale::get_locale()
.and_then(|l| l.split('-').next().map(|s| s.to_string()))
.unwrap_or_else(|| DEFAULT_LOCALE.to_string())
}
fn format_message(
bundle: &ConcurrentBundle,
key: &str,
args: Option<&FluentArgs>,
) -> Option<String> {
let msg = bundle.get_message(key)?;
let pattern = msg.value()?;
let mut errors = vec![];
let formatted = bundle.format_pattern(pattern, args, &mut errors);
if formatted.contains("\\n") {
Some(formatted.replace("\\n", "\n"))
} else {
Some(formatted.into_owned())
}
}
pub fn translate(key: &str, args: Option<&FluentArgs>) -> String {
let locale = get_current_locale();
if let Ok(bundles) = BUNDLES.read() {
let active_locale = if bundles.contains_key(&locale) {
locale.as_str()
} else {
FALLBACK_LOCALE
};
if let Some(bundle) = bundles.get(active_locale) {
if let Some(formatted) = format_message(bundle, key, args) {
return formatted;
}
}
if active_locale != FALLBACK_LOCALE {
if let Some(fallback) = bundles.get(FALLBACK_LOCALE) {
if let Some(formatted) = format_message(fallback, key, args) {
return formatted;
}
}
}
}
format!("[{}]", key)
}
#[macro_export]
macro_rules! tr {
($key:expr) => {
$crate::i18n::translate($key, None)
};
($key:expr, $($name:expr => $val:expr),+ $(,)?) => {
{
let mut args = $crate::i18n::FluentArgs::new();
$( args.set($name, $val.to_string()); )+
$crate::i18n::translate($key, Some(&args))
}
};
}