Files
horizon-airdef/crates/horizon-client/src/lang.rs
T
Ludovic Marie bbae62fc4b Render subtitles exactly as vanilla's SubtitleOverlay
The overlay listens to the sound engine from the frame that renders it with
Show Subtitles on until one renders with it off (keeping its captions),
forgets plays as it renders, picks the latest play in range (the first of
full ties), fades in float arithmetic, lays the boxes out in integers under
the pose translation and takes its background from the text background
opacity options. Translations now apply the game's deprecated.json renames,
as ClientLanguage does ("Chick hurts"). tools/test_subtitle_parity.py runs
vanilla's SubtitleOverlay on 1500 scripted cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:07:47 +02:00

218 lines
7.4 KiB
Rust

//! Languages (ClientLanguage / LanguageManager): `lang/<code>.json` from the
//! resource root and enabled packs layered over `en_us`, the language list
//! from `pack.mcmeta` `language` sections, and a process-wide current
//! language used by every screen.
use std::{
collections::{BTreeMap, HashMap},
sync::{Arc, RwLock},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageInfo {
pub code: String,
pub name: String,
pub region: String,
pub bidirectional: bool,
}
impl LanguageInfo {
/// LanguageInfo.toComponent: "Name (Region)".
pub fn label(&self) -> String {
format!("{} ({})", self.name, self.region)
}
}
#[derive(Default)]
pub struct Language {
pub code: String,
map: HashMap<String, String>,
}
pub const DEFAULT: &str = "en_us";
static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
fn read(&self, path: &str) -> Option<Vec<u8>>;
}
impl ResourceSource for std::path::PathBuf {
fn read(&self, path: &str) -> Option<Vec<u8>> {
std::fs::read(self.join(path)).ok()
}
}
/// DeprecatedTranslationsInfo.applyToMap: drop removed keys, then move each
/// renamed key's text to its new key (a missing old key removes the new one).
pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
let Ok(info) = serde_json::from_slice::<serde_json::Value>(json) else {
return;
};
for key in info["removed"].as_array().into_iter().flatten() {
if let Some(k) = key.as_str() {
map.remove(k);
}
}
for (from, to) in info["renamed"].as_object().into_iter().flatten() {
let Some(to) = to.as_str() else { continue };
match map.remove(from) {
Some(value) => {
map.insert(to.to_owned(), value);
}
None => {
map.remove(to);
}
}
}
}
impl Language {
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
Self {
code: code.to_owned(),
map,
}
}
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
/// from every source in priority order (later sources override).
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
let mut map = HashMap::new();
let mut codes = vec![DEFAULT];
if code != DEFAULT {
codes.push(code);
}
for c in codes {
for source in sources {
let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else {
continue;
};
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
map.extend(entries);
}
}
}
// DeprecatedTranslationsInfo.loadFromDefaultResource().applyToMap: the
// game's own deprecated.json, not a resource pack's.
if let Some(bytes) = sources
.iter()
.find_map(|s| s.read("assets/minecraft/lang/deprecated.json"))
{
apply_deprecated(&mut map, &bytes);
}
Self {
code: code.to_owned(),
map,
}
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(String::as_str)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
/// Languages declared by `pack.mcmeta` files (the vanilla asset root first).
pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
let mut found: BTreeMap<String, LanguageInfo> = BTreeMap::new();
found.insert(
DEFAULT.into(),
LanguageInfo {
code: DEFAULT.into(),
name: "English".into(),
region: "US".into(),
bidirectional: false,
},
);
for source in sources {
for path in ["assets/pack.mcmeta", "pack.mcmeta"] {
let Some(bytes) = source.read(path) else {
continue;
};
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
continue;
};
for (code, info) in value["language"].as_object().into_iter().flatten() {
// Only languages whose file exists somewhere are selectable.
let file = format!("assets/minecraft/lang/{code}.json");
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
continue;
}
found.insert(
code.clone(),
LanguageInfo {
code: code.clone(),
name: info["name"].as_str().unwrap_or(code).to_owned(),
region: info["region"].as_str().unwrap_or("").to_owned(),
bidirectional: info["bidirectional"].as_bool().unwrap_or(false),
},
);
}
}
}
found.into_values().collect()
}
pub fn set(language: Language) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
}
pub fn current() -> Option<Arc<Language>> {
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn code() -> String {
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
}
/// Language.getOrDefault: the translation, or the key itself.
pub fn get(key: &str) -> String {
current()
.and_then(|l| l.get(key).map(str::to_owned))
.unwrap_or_else(|| key.to_owned())
}
/// The translation, or `fallback` when the key is missing.
pub fn get_or(key: &str, fallback: &str) -> String {
current()
.and_then(|l| l.get(key).map(str::to_owned))
.unwrap_or_else(|| fallback.to_owned())
}
pub fn has(key: &str) -> bool {
current().is_some_and(|l| l.get(key).is_some())
}
/// I18n.get with plain string arguments.
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String {
crate::text::Text::tr(key, args).plain()
}
#[cfg(test)]
mod tests {
use super::*;
struct Mem(HashMap<String, Vec<u8>>);
impl ResourceSource for Mem {
fn read(&self, path: &str) -> Option<Vec<u8>> {
self.0.get(path).cloned()
}
}
#[test]
fn layers_selected_language_over_english() {
let base = Mem(HashMap::from([
("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()),
("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()),
("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()),
]));
let pack = Mem(HashMap::from([(
"assets/minecraft/lang/fr_fr.json".into(),
br#"{"b":"Banane"}"#.to_vec(),
)]));
let sources: [&dyn ResourceSource; 2] = [&base, &pack];
let fr = Language::load(&sources, "fr_fr");
assert_eq!(fr.get("a"), Some("Pomme"));
assert_eq!(fr.get("b"), Some("Banane"));
let langs = available(&sources);
// de_de has no file, so only English and French are offered.
assert_eq!(
langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(),
["en_us", "fr_fr"]
);
assert_eq!(langs[1].label(), "Français (France)");
}
}