1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
mod error;
mod raw;
use error::ResourceErr;
#[cfg(any(feature = "bin", feature = "stat", test))]
pub mod analysis;
use fluent_bundle::{bundle::FluentBundle, FluentResource};
use intl_memoizer::concurrent::IntlLangMemoizer;
use unic_langid::LanguageIdentifier;
use deunicode::deunicode;
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, io};
use assets::{
source::DirEntry, AssetExt, AssetHandle, AssetReadGuard, ReloadWatcher, SharedString,
};
use common_assets as assets;
use common_i18n::{Content, LocalizationArg};
use tracing::warn;
// Re-export for argument creation
pub use fluent::{fluent_args, FluentValue};
pub use fluent_bundle::FluentArgs;
/// The reference language, aka the more up-to-date localization data.
/// Also the default language at first startup.
pub const REFERENCE_LANG: &str = "en";
/// How a language can be described
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LanguageMetadata {
/// A human friendly language name (e.g. "English (US)")
pub language_name: String,
/// A short text identifier for this language (e.g. "en_US")
///
/// On the opposite of `language_name` that can change freely,
/// `language_identifier` value shall be stable in time as it
/// is used by setting components to store the language
/// selected by the user.
pub language_identifier: String,
}
/// Store font metadata
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Font {
/// Key to retrieve the font in the asset system
pub asset_key: String,
/// Scale ratio to resize the UI text dynamically
scale_ratio: f32,
}
impl Font {
/// Scale input size to final UI size
#[must_use]
pub fn scale(&self, value: u32) -> u32 { (value as f32 * self.scale_ratio).round() as u32 }
}
/// Store font metadata
pub type Fonts = HashMap<String, Font>;
/// Store internationalization data
struct Language {
/// The bundle storing all localized texts
pub(crate) bundle: FluentBundle<FluentResource, IntlLangMemoizer>,
/// Font configuration is stored here
pub(crate) fonts: Fonts,
pub(crate) metadata: LanguageMetadata,
}
impl Language {
fn try_msg<'a>(&'a self, key: &str, args: Option<&'a FluentArgs>) -> Option<Cow<'a, str>> {
let bundle = &self.bundle;
let msg = bundle.get_message(key)?;
let mut errs = Vec::new();
let msg = bundle.format_pattern(msg.value()?, args, &mut errs);
for err in errs {
tracing::error!("err: {err} for {key}");
}
Some(msg)
}
fn try_attr<'a>(
&'a self,
key: &str,
attr: &str,
args: Option<&'a FluentArgs>,
) -> Option<Cow<'a, str>> {
let bundle = &self.bundle;
let msg = bundle.get_message(key)?;
let attr = msg.get_attribute(attr)?;
let attr = attr.value();
let mut errs = Vec::new();
let msg = bundle.format_pattern(attr, args, &mut errs);
for err in errs {
tracing::error!("err: {err} for {key}");
}
Some(msg)
}
/// NOTE: Exists for legacy reasons, avoid.
// Read more in the issue on get_variation at Gitlab
fn try_variation<'a>(
&'a self,
key: &str,
seed: u16,
args: Option<&'a FluentArgs>,
) -> Option<Cow<'a, str>> {
let bundle = &self.bundle;
let msg = bundle.get_message(key)?;
let mut attrs = msg.attributes();
let mut errs = Vec::new();
let msg = if attrs.len() != 0 {
let idx = usize::from(seed) % attrs.len();
// unwrap is ok here, because idx is bound to attrs.len()
// by using modulo operator.
//
// For example:
// (I)
// * attributes = [.x = 5, .y = 7, z. = 4]
// * len = 3
// * seed can be 12, 50, 1
// 12 % 3 = 0, attrs.skip(0) => first element
// 50 % 3 = 2, attrs.skip(2) => third element
// 1 % 3 = 1, attrs.skip(1) => second element
// (II)
// * attributes = []
// * len = 0
// * no matter what seed is, we return None in code above
let variation = attrs.nth(idx).unwrap();
bundle.format_pattern(variation.value(), args, &mut errs)
} else {
// Fall back to single message if there are no attributes
bundle.format_pattern(msg.value()?, args, &mut errs)
};
for err in errs {
tracing::error!("err: {err} for {key}");
}
Some(msg)
}
}
impl assets::Compound for Language {
fn load(cache: assets::AnyCache, path: &SharedString) -> Result<Self, assets::BoxedError> {
let manifest = cache
.load::<raw::Manifest>(&[path, ".", "_manifest"].concat())?
.cloned();
let raw::Manifest {
convert_utf8_to_ascii,
fonts,
metadata,
} = manifest;
let lang_id: LanguageIdentifier = metadata.language_identifier.parse()?;
let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
// Here go dragons
for id in cache.load_rec_dir::<raw::Resource>(path)?.read().ids() {
match cache.load(id) {
Ok(handle) => {
let source: &raw::Resource = &handle.read();
let src = source.src.clone();
// NOTE:
// This deunicode whole file, which mean it may break if
// we have non-ascii keys.
// I don't consider this a problem, because having
// non-ascii keys is quite exotic.
let src = if convert_utf8_to_ascii {
deunicode(&src)
} else {
src
};
let resource = FluentResource::try_new(src).map_err(|(_ast, errs)| {
ResourceErr::parsing_error(errs, id.to_string(), &source.src)
})?;
bundle
.add_resource(resource)
.map_err(|e| ResourceErr::BundleError(format!("{e:?}")))?;
},
Err(err) => {
// TODO: shouldn't we just panic here?
warn!("Unable to load asset {id}, error={err:?}");
},
}
}
// NOTE:
// Basically a hack, but conrod can't use isolation marks yet.
// Veloren Issue 1649
bundle.set_use_isolating(false);
Ok(Self {
bundle,
fonts,
metadata,
})
}
}
/// The central data structure to handle localization in Veloren
// inherit Copy + Clone from AssetHandle (what?)
#[derive(Copy, Clone)]
pub struct LocalizationHandle {
active: AssetHandle<Language>,
watcher: ReloadWatcher,
fallback: Option<AssetHandle<Language>>,
pub use_english_fallback: bool,
}
/// Read [`LocalizationGuard`]
// arbitrary choice to minimize changing all of veloren
pub type Localization = LocalizationGuard;
/// RAII guard returned from [`LocalizationHandle::read()`], resembles
/// [`AssetGuard`]
pub struct LocalizationGuard {
active: AssetReadGuard<Language>,
fallback: Option<AssetReadGuard<Language>>,
}
impl LocalizationGuard {
/// Get a localized text from the given key in the fallback language.
pub fn try_fallback_msg(&self, key: &str) -> Option<Cow<str>> {
self.fallback.as_ref().and_then(|fb| fb.try_msg(key, None))
}
/// Get a localized text from the given key
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
pub fn try_msg(&self, key: &str) -> Option<Cow<str>> {
self.active
.try_msg(key, None)
.or_else(|| self.try_fallback_msg(key))
}
/// Get a localized text from the given key
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
pub fn get_msg(&self, key: &str) -> Cow<str> {
// NOTE: we clone the key if translation was missing
// We could use borrowed version, but it would mean that
// `key`, `self`, and result should have the same lifetime.
// Which would make it way more awkward to use with runtime generated keys.
self.try_msg(key)
.unwrap_or_else(|| Cow::Owned(key.to_owned()))
}
/// Get a localized text from the given key using given arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
pub fn try_msg_ctx<'a>(&'a self, key: &str, args: &'a FluentArgs) -> Option<Cow<'static, str>> {
// NOTE: as after using args we get our result owned (because you need
// to clone pattern during forming value from args), this conversion
// to Cow::Owned is no-op.
// We could use String here, but using Cow everywhere in i18n API is
// prefered for consistency.
self.active
.try_msg(key, Some(args))
.or_else(|| {
self.fallback
.as_ref()
.and_then(|fb| fb.try_msg(key, Some(args)))
})
.map(|res| Cow::Owned(res.into_owned()))
}
/// Get a localized text from the given key using given arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
pub fn get_msg_ctx<'a>(&'a self, key: &str, args: &'a FluentArgs) -> Cow<'static, str> {
self.try_msg_ctx(key, args)
.unwrap_or_else(|| Cow::Owned(key.to_owned()))
}
/// NOTE: Exists for legacy reasons, avoid.
///
/// Get a localized text from the variation of given key
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
// Read more in the issue on get_variation at Gitlab
pub fn try_variation(&self, key: &str, seed: u16) -> Option<Cow<str>> {
self.active.try_variation(key, seed, None).or_else(|| {
self.fallback
.as_ref()
.and_then(|fb| fb.try_variation(key, seed, None))
})
}
/// NOTE: Exists for legacy reasons, avoid.
///
/// Get a localized text from the variation of given key
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
// Read more in the issue on get_variation at Gitlab
pub fn get_variation(&self, key: &str, seed: u16) -> Cow<str> {
self.try_variation(key, seed)
.unwrap_or_else(|| Cow::Owned(key.to_owned()))
}
/// NOTE: Exists for legacy reasons, avoid.
///
/// Get a localized text from the variation of given key with given
/// arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
// Read more in the issue on get_variation at Gitlab
pub fn try_variation_ctx<'a>(
&'a self,
key: &str,
seed: u16,
args: &'a FluentArgs,
) -> Option<Cow<str>> {
self.active
.try_variation(key, seed, Some(args))
.or_else(|| {
self.fallback
.as_ref()
.and_then(|fb| fb.try_variation(key, seed, Some(args)))
})
}
// Function to localize content for given language.
//
// Returns Ok(localized_text) if found no errors.
// Returns Err(broken_text) on failure.
//
// broken_text will have i18n keys in it, just i18n key if it was instant miss
// or text with missed keys inlined if it was missed down the chain.
fn get_content_for_lang(lang: &Language, content: &Content) -> Result<String, String> {
match content {
Content::Plain(text) => Ok(text.clone()),
Content::Key(key) => lang
.try_msg(key, None)
.map(Cow::into_owned)
.ok_or_else(|| key.to_string()),
Content::Attr(key, attr) => lang
.try_attr(key, attr, None)
.map(Cow::into_owned)
.ok_or_else(|| format!("{key}.{attr}")),
Content::Localized { key, seed, args } => {
// flag to detect failure down the chain
let mut is_arg_failure = false;
let mut fargs = FluentArgs::new();
for (k, arg) in args {
let arg_val = match arg {
LocalizationArg::Content(content) => {
let arg_res = Self::get_content_for_lang(lang, content)
.unwrap_or_else(|broken_text| {
is_arg_failure = true;
broken_text
})
.into();
FluentValue::String(arg_res)
},
LocalizationArg::Nat(n) => FluentValue::from(n),
};
fargs.set(k, arg_val);
}
lang.try_variation(key, *seed, Some(&fargs))
.map(Cow::into_owned)
.ok_or_else(|| key.clone())
.and_then(|text| if is_arg_failure { Err(text) } else { Ok(text) })
},
}
}
/// Tries its best to localize compound message.
///
/// # Example
/// ```text
/// Content::Localized { "npc-speech-tell_site", seed, {
/// "dir" => Content::Localized("npc-speech-dir_north", seed, {})
/// "dist" => Content::Localized("npc-speech-dist_very_far", seed, {})
/// "site" => Content::Plain(site)
/// }}
/// ```
/// ```fluent
/// npc-speech-tell_site =
/// .a0 = Have you visited { $site }? It's just { $dir } of here!
/// .a1 = You should visit { $site } some time.
/// .a2 = If you travel { $dist } to the { $dir }, you can get to { $site }.
/// .a3 = To the { $dir } you'll find { $site }, it's { $dist }.
///
/// npc-speech-dir_north = north
/// # ... other keys
///
/// npc-speech-dist_very_far = very far away
/// # ... other keys
/// ```
///
/// 1) Because content we want is localized itself and has arguments, we
/// iterate over them and localize, recursively. Having that, we localize
/// our content.
/// 2) Now there is a chance that some of args have missing internalization.
/// In that case, we insert arg name as placeholder and mark it as
/// broken. Then we repeat *whole* procedure on fallback language if we
/// have it.
/// 3) Otherwise, return result from (1).
// NOTE: it's important that we only use one language at the time, because
// otherwise we will get partially-translated message.
//
// TODO: return Cow<str>?
pub fn get_content(&self, content: &Content) -> String {
match Self::get_content_for_lang(&self.active, content) {
Ok(text) => text,
// If localisation or some part of it failed, repeat with fallback.
// If it did fail as well, it's probably because fallback was disabled,
// so we don't have better option other than returning broken text
// we produced earlier.
Err(broken_text) => self
.fallback
.as_ref()
.and_then(|fb| Self::get_content_for_lang(fb, content).ok())
.unwrap_or(broken_text),
}
}
pub fn get_content_fallback(&self, content: &Content) -> String {
self.fallback
.as_ref()
.map(|fb| Self::get_content_for_lang(fb, content))
.transpose()
.map(|msg| msg.unwrap_or_default())
.unwrap_or_else(|e| e)
}
/// NOTE: Exists for legacy reasons, avoid.
///
/// Get a localized text from the variation of given key with given
/// arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
// Read more in the issue on get_variation at Gitlab
pub fn get_variation_ctx<'a>(&'a self, key: &str, seed: u16, args: &'a FluentArgs) -> Cow<str> {
self.try_variation_ctx(key, seed, args)
.unwrap_or_else(|| Cow::Owned(key.to_owned()))
}
/// Get a localized text from the given key by given attribute
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
pub fn try_attr(&self, key: &str, attr: &str) -> Option<Cow<str>> {
self.active.try_attr(key, attr, None).or_else(|| {
self.fallback
.as_ref()
.and_then(|fb| fb.try_attr(key, attr, None))
})
}
/// Get a localized text from the given key by given attribute
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
pub fn get_attr(&self, key: &str, attr: &str) -> Cow<str> {
self.try_attr(key, attr)
.unwrap_or_else(|| Cow::Owned(format!("{key}.{attr}")))
}
/// Get a localized text from the given key by given attribute and arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
pub fn try_attr_ctx(
&self,
key: &str,
attr: &str,
args: &FluentArgs,
) -> Option<Cow<'static, str>> {
// NOTE: we explicitly Own result, because in 99.999% cases it got
// owned during formatting of arguments, hence it's a no-op, but makes
// using this function much easier
self.active
.try_attr(key, attr, Some(args))
.or_else(|| {
self.fallback
.as_ref()
.and_then(|fb| fb.try_attr(key, attr, Some(args)))
})
.map(|res| Cow::Owned(res.into_owned()))
}
/// Get a localized text from the given key by given attribute and arguments
///
/// First lookup is done in the active language, second in
/// the fallback (if present).
/// If the key is not present in the localization object
/// then the key itself is returned.
pub fn get_attr_ctx(&self, key: &str, attr: &str, args: &FluentArgs) -> Cow<'static, str> {
self.try_attr_ctx(key, attr, args)
.unwrap_or_else(|| Cow::Owned(format!("{key}.{attr}")))
}
#[must_use]
pub fn fonts(&self) -> &Fonts { &self.active.fonts }
#[must_use]
pub fn metadata(&self) -> &LanguageMetadata { &self.active.metadata }
}
impl LocalizationHandle {
pub fn set_english_fallback(&mut self, use_english_fallback: bool) {
self.use_english_fallback = use_english_fallback;
}
#[must_use]
pub fn read(&self) -> LocalizationGuard {
LocalizationGuard {
active: self.active.read(),
fallback: if self.use_english_fallback {
self.fallback.map(|f| f.read())
} else {
None
},
}
}
/// # Errors
/// Returns error if active of fallback language can't be loaded
pub fn load(specifier: &str) -> Result<Self, assets::Error> {
let default_key = ["voxygen.i18n.", REFERENCE_LANG].concat();
let language_key = ["voxygen.i18n.", specifier].concat();
let is_default = language_key == default_key;
let active = Language::load(&language_key)?;
Ok(Self {
active,
watcher: active.reload_watcher(),
fallback: if is_default {
None
} else {
Some(Language::load(&default_key)?)
},
use_english_fallback: false,
})
}
#[must_use]
pub fn load_expect(specifier: &str) -> Self {
Self::load(specifier).expect("Can't load language files")
}
pub fn reloaded(&mut self) -> bool { self.watcher.reloaded() }
}
struct FindManifests;
impl assets::DirLoadable for FindManifests {
fn select_ids(
cache: assets::AnyCache,
specifier: &SharedString,
) -> io::Result<Vec<SharedString>> {
use assets::Source;
let mut specifiers = Vec::new();
let source = cache.raw_source();
source.read_dir(specifier, &mut |entry| {
if let DirEntry::Directory(spec) = entry {
let manifest_spec = [spec, ".", "_manifest"].concat();
if source.exists(DirEntry::File(&manifest_spec, "ron")) {
specifiers.push(manifest_spec.into());
}
}
})?;
Ok(specifiers)
}
}
#[derive(Clone, Debug)]
struct LocalizationList(Vec<LanguageMetadata>);
impl assets::Compound for LocalizationList {
fn load(cache: assets::AnyCache, specifier: &SharedString) -> Result<Self, assets::BoxedError> {
// List language directories
let languages = assets::load_rec_dir::<FindManifests>(specifier)
.unwrap_or_else(|e| panic!("Failed to get manifests from {}: {:?}", specifier, e))
.read()
.ids()
.filter_map(|spec| cache.load::<raw::Manifest>(spec).ok())
.map(|localization| localization.read().metadata.clone())
.collect();
Ok(LocalizationList(languages))
}
}
/// Load all the available languages located in the voxygen asset directory
#[must_use]
pub fn list_localizations() -> Vec<LanguageMetadata> {
let LocalizationList(list) = LocalizationList::load_expect_cloned("voxygen.i18n");
list
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
// Test that localization list is loaded (not empty)
fn check_localization_list() {
let list = list_localizations();
assert!(!list.is_empty());
}
#[test]
// Test that reference language can be loaded
fn validate_reference_language() { let _ = LocalizationHandle::load_expect(REFERENCE_LANG); }
#[test]
// Test to verify that all languages are valid and loadable
fn validate_all_localizations() {
let list = list_localizations();
for meta in list {
let _ = LocalizationHandle::load_expect(&meta.language_identifier);
}
}
#[test]
fn test_strict_all_localizations() {
use analysis::{Language, ReferenceLanguage};
use assets::find_root;
let root = find_root().unwrap();
let i18n_directory = root.join("assets/voxygen/i18n");
let reference = ReferenceLanguage::at(&i18n_directory.join(REFERENCE_LANG));
let list = list_localizations();
for meta in list {
let code = meta.language_identifier;
let lang = Language {
code: code.clone(),
path: i18n_directory.join(code.clone()),
};
// TODO: somewhere here should go check that all needed
// versions are given
reference.compare_with(&lang);
}
}
}