diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 893bbd567..f5fea0192 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -161,11 +161,11 @@ MCP: `account_skin`. ## `horizon-launcher settings` -Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it), while-playing stay|minimize|hide (what the window does while the game runs). +Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it), while-playing stay|minimize|hide (what the window does while the game runs), language system|en|fr|ru (the window's language; system follows the computer's). horizon-launcher settings [KEY] [VALUE] -- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation, proxy, while-playing) +- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation, proxy, while-playing, language) - `VALUE`: The new value (with KEY) MCP: `settings`. diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 422c2ace9..c0fa55f15 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2763,6 +2763,7 @@ dependencies = [ "serde_json", "sha1", "sha2 0.10.9", + "sys-locale", "tar", "toml 1.1.8+spec-1.1.0", "trash", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 356e8ae2e..9e65a2281 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -22,6 +22,8 @@ tar = { version = "0.4", default-features = false } toml = "1.1" zip = { version = "2", default-features = false, features = ["deflate"] } dirs = "5" +# The system's preferred languages, for the window's language (i18n.rs). +sys-locale = "0.3" self-replace = "1" clap = { version = "4", features = ["derive"] } horizon-theme = { path = "../crates/horizon-theme" } diff --git a/launcher/README.md b/launcher/README.md index d76d8d897..9b617064b 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -129,6 +129,12 @@ The opening, then Play ([clip](docs/opening.webm)): the Console's Share log takes them out of the log too. `horizon-launcher account offline [NAME]`, `account select ` (an account or an offline name), `account forget-offline `. +- **Language**: English, French and Russian (the languages Horizon's own game menus have). + The window follows the system's language unless the player picks one in Settings > Launcher + (each named in itself); a string a table lacks shows in English. The tables are + `launcher/lang/.json`, English text to its translation, Horizon's own; a test fails when + the code asks `tr("…")` for a string a table lacks, or a table keeps one the code dropped. + `horizon-launcher settings language system|en|fr|ru`. - **Skin and cape**: each offline name's **Skin…** in Settings > Account shows the front of its skin and cape, takes a skin PNG (64×64, or the older 64×32) and a cape PNG (64×32), and picks classic or slim arms. The launcher keeps copies in its `skins/` folder and gives the game diff --git a/launcher/lang/fr.json b/launcher/lang/fr.json new file mode 100644 index 000000000..719f6fd52 --- /dev/null +++ b/launcher/lang/fr.json @@ -0,0 +1,87 @@ +{ + "Home": "Accueil", + "Mods": "Mods", + "Servers": "Serveurs", + "Versions": "Versions", + "Patch notes": "Notes de version", + "Settings": "Paramètres", + "Accounts, updates, and the launcher itself.": "Comptes, mises à jour et le launcher lui-même.", + "Account": "Compte", + "Updates": "Mises à jour", + "Launcher": "Launcher", + "Network": "Réseau", + "Game": "Jeu", + "AI": "IA", + "About": "À propos", + "Install new versions automatically": "Installer les nouvelles versions automatiquement", + "Your selected version only changes if you were playing the newest one.": "Votre version choisie ne change que si vous jouiez à la plus récente.", + "Appearance": "Apparence", + "Dark": "Sombre", + "Light": "Clair", + "System": "Système", + "Dark by default. System follows your computer's light or dark.": "Sombre par défaut. Système suit le mode clair ou sombre de votre ordinateur.", + "Language": "Langue", + "System follows your computer's language: {language} here. A string not translated yet shows in English.": "Système suit la langue de votre ordinateur : ici {language}. Un texte pas encore traduit s'affiche en anglais.", + "While playing": "Pendant le jeu", + "Stay": "Rester", + "Minimise": "Réduire", + "Hide": "Masquer", + "The launcher stays open while you play.": "Le launcher reste ouvert pendant que vous jouez.", + "The launcher goes down when the game starts, and comes back when it closes.": "Le launcher se réduit quand le jeu démarre et revient quand il se ferme.", + "The launcher hides when the game starts, and comes back when it closes.": "Le launcher se masque quand le jeu démarre et revient quand il se ferme.", + "Show the opening": "Afficher l'ouverture", + "The wordmark, while the release list loads.": "Le logo, pendant que la liste des versions se charge.", + "{version} available": "{version} disponible", + "Up to date": "À jour", + "up to date": "à jour", + "Checking…": "Vérification…", + "downloading {version}, {percent}%": "téléchargement de {version}, {percent} %", + "Updated to {version}. Restart the launcher to use it.": "Mis à jour vers {version}. Redémarrez le launcher pour l'utiliser.", + "the update failed: {error}": "la mise à jour a échoué : {error}", + "Install": "Installer", + "Restart": "Redémarrer", + "Check now": "Vérifier", + "Open": "Ouvrir", + "Data folder": "Dossier des données", + "Logs": "Journaux", + "crash reports beside it": "rapports de plantage à côté", + "Applications menu": "Menu des applications", + "Horizon and its icon are in your desktop's menu.": "Horizon et son icône sont dans le menu de votre bureau.", + "Not in your desktop's menu.": "Pas dans le menu de votre bureau.", + "Microsoft account (coming soon)": "Compte Microsoft (bientôt)", + "Microsoft account": "Compte Microsoft", + "Another account": "Un autre compte", + "Microsoft sign-in is coming soon. Until then the game plays offline: single player, LAN and servers in offline mode work.": "La connexion Microsoft arrive bientôt. D'ici là, le jeu se joue hors ligne : solo, LAN et serveurs en mode hors ligne fonctionnent.", + "Coming soon": "Bientôt", + "Microsoft account · plays": "Compte Microsoft · joue", + "Microsoft account · signed in": "Compte Microsoft · connecté", + "Asking Microsoft…": "Demande à Microsoft…", + "Add another account.": "Ajoutez un autre compte.", + "Copy code": "Copier le code", + "Open link": "Ouvrir le lien", + "Play as": "Jouer en tant que", + "Play offline": "Jouer hors ligne", + "Sign out": "Se déconnecter", + "Offline": "Hors ligne", + "Microsoft": "Microsoft", + "Offline, the game's name": "Hors ligne, le nom du jeu", + "Manage accounts": "Gérer les comptes", + "Offline name": "Nom hors ligne", + "Offline name · plays": "Nom hors ligne · joue", + "A name, 3 to 16 letters": "Un nom, de 3 à 16 lettres", + "Play offline under another name, and switch from the top bar. Online servers don't take offline names.": "Jouez hors ligne sous un autre nom, et changez depuis la barre du haut. Les serveurs en ligne n'acceptent pas les noms hors ligne.", + "Add": "Ajouter", + "Skin…": "Skin…", + "Forget": "Oublier", + "{name}'s skin": "Skin de {name}", + "{name}'s skin is kept.": "Le skin de {name} est enregistré.", + "{name}'s cape is kept.": "La cape de {name} est enregistrée.", + "Choose a skin…": "Choisir un skin…", + "Default skin": "Skin par défaut", + "Classic arms": "Bras classiques", + "Slim arms": "Bras fins", + "Choose a cape…": "Choisir une cape…", + "No cape": "Pas de cape", + "Default": "Par défaut", + "A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the launcher and given to the game when this name plays. The game draws the default skins for now; it uses these once it can. A Microsoft account's skin and cape: coming soon.": "Un PNG de skin 64×64 (ou 64×32) et un PNG de cape 64×32, gardés par le launcher et donnés au jeu quand ce nom joue. Le jeu dessine encore les skins par défaut ; il utilisera ceux-ci dès qu'il le pourra. Skin et cape d'un compte Microsoft : bientôt." +} diff --git a/launcher/lang/ru.json b/launcher/lang/ru.json new file mode 100644 index 000000000..127cda928 --- /dev/null +++ b/launcher/lang/ru.json @@ -0,0 +1,87 @@ +{ + "Home": "Главная", + "Mods": "Моды", + "Servers": "Серверы", + "Versions": "Версии", + "Patch notes": "Список изменений", + "Settings": "Настройки", + "Accounts, updates, and the launcher itself.": "Аккаунты, обновления и сам лаунчер.", + "Account": "Аккаунт", + "Updates": "Обновления", + "Launcher": "Лаунчер", + "Network": "Сеть", + "Game": "Игра", + "AI": "ИИ", + "About": "О программе", + "Install new versions automatically": "Устанавливать новые версии автоматически", + "Your selected version only changes if you were playing the newest one.": "Выбранная версия меняется, только если вы играли в самую новую.", + "Appearance": "Оформление", + "Dark": "Тёмное", + "Light": "Светлое", + "System": "Системное", + "Dark by default. System follows your computer's light or dark.": "По умолчанию тёмное. «Системное» следует светлой или тёмной теме компьютера.", + "Language": "Язык", + "System follows your computer's language: {language} here. A string not translated yet shows in English.": "«Системный» следует языку компьютера: здесь {language}. Ещё не переведённый текст показывается по-английски.", + "While playing": "Во время игры", + "Stay": "Оставаться", + "Minimise": "Свернуть", + "Hide": "Скрыть", + "The launcher stays open while you play.": "Лаунчер остаётся открытым, пока вы играете.", + "The launcher goes down when the game starts, and comes back when it closes.": "Лаунчер сворачивается при запуске игры и возвращается, когда она закрывается.", + "The launcher hides when the game starts, and comes back when it closes.": "Лаунчер скрывается при запуске игры и возвращается, когда она закрывается.", + "Show the opening": "Показывать заставку", + "The wordmark, while the release list loads.": "Логотип, пока загружается список версий.", + "{version} available": "Доступна {version}", + "Up to date": "Обновлено", + "up to date": "обновлено", + "Checking…": "Проверка…", + "downloading {version}, {percent}%": "загрузка {version}, {percent}%", + "Updated to {version}. Restart the launcher to use it.": "Обновлено до {version}. Перезапустите лаунчер, чтобы применить.", + "the update failed: {error}": "обновление не удалось: {error}", + "Install": "Установить", + "Restart": "Перезапустить", + "Check now": "Проверить", + "Open": "Открыть", + "Data folder": "Папка данных", + "Logs": "Журналы", + "crash reports beside it": "отчёты о сбоях рядом", + "Applications menu": "Меню приложений", + "Horizon and its icon are in your desktop's menu.": "Horizon и его значок есть в меню рабочего стола.", + "Not in your desktop's menu.": "Нет в меню рабочего стола.", + "Microsoft account (coming soon)": "Аккаунт Microsoft (скоро)", + "Microsoft account": "Аккаунт Microsoft", + "Another account": "Другой аккаунт", + "Microsoft sign-in is coming soon. Until then the game plays offline: single player, LAN and servers in offline mode work.": "Вход через Microsoft скоро появится. А пока игра работает офлайн: одиночная игра, LAN и серверы в офлайн-режиме.", + "Coming soon": "Скоро", + "Microsoft account · plays": "Аккаунт Microsoft · играет", + "Microsoft account · signed in": "Аккаунт Microsoft · вход выполнен", + "Asking Microsoft…": "Запрос к Microsoft…", + "Add another account.": "Добавьте ещё один аккаунт.", + "Copy code": "Скопировать код", + "Open link": "Открыть ссылку", + "Play as": "Играть за", + "Play offline": "Играть офлайн", + "Sign out": "Выйти", + "Offline": "Офлайн", + "Microsoft": "Microsoft", + "Offline, the game's name": "Офлайн, имя от игры", + "Manage accounts": "Управление аккаунтами", + "Offline name": "Офлайн-имя", + "Offline name · plays": "Офлайн-имя · играет", + "A name, 3 to 16 letters": "Имя, от 3 до 16 букв", + "Play offline under another name, and switch from the top bar. Online servers don't take offline names.": "Играйте офлайн под другим именем и переключайтесь в верхней панели. Онлайн-серверы не принимают офлайн-имена.", + "Add": "Добавить", + "Skin…": "Скин…", + "Forget": "Забыть", + "{name}'s skin": "Скин {name}", + "{name}'s skin is kept.": "Скин {name} сохранён.", + "{name}'s cape is kept.": "Плащ {name} сохранён.", + "Choose a skin…": "Выбрать скин…", + "Default skin": "Скин по умолчанию", + "Classic arms": "Обычные руки", + "Slim arms": "Тонкие руки", + "Choose a cape…": "Выбрать плащ…", + "No cape": "Без плаща", + "Default": "По умолчанию", + "A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the launcher and given to the game when this name plays. The game draws the default skins for now; it uses these once it can. A Microsoft account's skin and cape: coming soon.": "PNG скина 64×64 (или 64×32) и PNG плаща 64×32 хранятся в лаунчере и передаются игре, когда играет это имя. Пока игра рисует стандартные скины; она начнёт использовать эти, как только сможет. Скин и плащ аккаунта Microsoft: скоро." +} diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 3d900bd87..462b2cdb3 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -2604,6 +2604,9 @@ pub struct Settings { /// What the window does while the game runs. Stays by default. #[serde(default)] pub while_playing: WhilePlaying, + /// The window's language. Unset follows the system's (`i18n::Language::system`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub language: Option, } impl Settings { @@ -2628,6 +2631,12 @@ impl Settings { { fields.remove("while_playing"); } + // A language this launcher doesn't have yet follows the system's. + if fields.get("language").is_some_and(|l| { + serde_json::from_value::>(l.clone()).is_err() + }) { + fields.remove("language"); + } } serde_json::from_value(value).unwrap_or_default() } @@ -2635,6 +2644,10 @@ impl Settings { pub fn desktop_entry(&self) -> bool { self.desktop_entry.unwrap_or(true) } + /// The window's language: the one picked, else the system's. + pub fn language(&self) -> crate::i18n::Language { + self.language.unwrap_or_else(crate::i18n::Language::system) + } /// Whether new Horizon versions are installed automatically. pub fn auto_install(&self) -> bool { self.install_new_versions.unwrap_or(true) @@ -2965,6 +2978,18 @@ mod tests { assert_eq!(here == WhilePlaying::Hide, cfg!(target_os = "macos")); } + #[test] + fn the_language_follows_the_system_unless_picked() { + use crate::i18n::Language; + assert_eq!(Settings::parse("{}").language, None); + let fr = Settings::parse(r#"{"language": "fr"}"#); + assert_eq!(fr.language(), Language::French); + let future = Settings::parse(r#"{"language": "eo", "game_args": "--x"}"#); + assert_eq!((future.language, future.game_args.as_str()), (None, "--x")); + let saved = serde_json::to_value(Settings::default()).unwrap(); + assert!(saved.get("language").is_none(), "unset is left out"); + } + #[test] fn the_appearance_is_dark_unless_picked_and_an_unknown_one_keeps_the_rest() { assert_eq!(Settings::parse("{}").appearance, Appearance::Dark); diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 97f3eed09..ff7efcbc7 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -603,7 +603,8 @@ enum Cmd { /// Show the launcher's settings, or set one (the Settings page): selected-version TAG, /// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions /// on|off, opening-animation on|off, proxy http://host:port ("default" removes it), - /// while-playing stay|minimize|hide (what the window does while the game runs) + /// while-playing stay|minimize|hide (what the window does while the game runs), language + /// system|en|fr|ru (the window's language; system follows the computer's) Settings { #[arg(value_parser = SETTING_KEYS)] key: Option, @@ -740,7 +741,7 @@ pub fn command() -> clap::Command { pub const AI_COMMANDS: [&str; 2] = ["mcp", "agent-config"]; /// The keys `settings` sets. -const SETTING_KEYS: [&str; 7] = [ +const SETTING_KEYS: [&str; 8] = [ "selected-version", "minecraft-dir", "server-dir", @@ -748,6 +749,7 @@ const SETTING_KEYS: [&str; 7] = [ "opening-animation", "proxy", "while-playing", + "language", ]; fn on_off(value: &str) -> Result { @@ -770,6 +772,16 @@ fn set_setting(s: &mut backend::Settings, key: &str, value: &str) -> Result<(), s.while_playing = backend::WhilePlaying::parse(value) .ok_or_else(|| format!("{value}: say stay, minimize or hide"))? } + "language" => { + use horizon_launcher::i18n::Language; + s.language = match value.trim() { + "system" | "default" => None, + code => Some( + Language::parse(code) + .ok_or_else(|| format!("{value}: say system, en, fr or ru"))?, + ), + } + } "proxy" => { if value == "default" || value.is_empty() { s.proxy = None; @@ -796,6 +808,7 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value { "proxy": s.proxy, "desktop_entry": s.desktop_entry.unwrap_or(true), "while_playing": s.while_playing.name(), + "language": s.language.map_or("system", |l| l.code()), "no_ai": backend::no_ai(), }) } diff --git a/launcher/src/i18n.rs b/launcher/src/i18n.rs new file mode 100644 index 000000000..7635461d5 --- /dev/null +++ b/launcher/src/i18n.rs @@ -0,0 +1,134 @@ +//! The launcher's languages: English (the strings in the code), French and Russian, the +//! languages Horizon's own game menus have. A table per language (`launcher/lang/.json`) +//! maps each English string to its translation; a string the table lacks shows in English. +//! +//! The language follows the system's unless the player picks one in Settings +//! (`Settings::language`). Translations are Horizon's own, written for this launcher. +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::OnceLock; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Language { + #[default] + #[serde(rename = "en")] + English, + #[serde(rename = "fr")] + French, + #[serde(rename = "ru")] + Russian, +} + +impl Language { + pub const ALL: [Language; 3] = [Self::English, Self::French, Self::Russian]; + + /// Its code in `settings.json` and on the command line. + pub fn code(self) -> &'static str { + match self { + Self::English => "en", + Self::French => "fr", + Self::Russian => "ru", + } + } + + /// Its name in itself: what a player looks for in a list of languages. + pub fn name(self) -> &'static str { + match self { + Self::English => "English", + Self::French => "Français", + Self::Russian => "Русский", + } + } + + /// A language code (`fr`, `fr-CH`, `fr_FR.UTF-8`), if the launcher has it. + pub fn parse(code: &str) -> Option { + let lower = code.trim().to_ascii_lowercase(); + let base = lower.split(['-', '_', '.', '@']).next().unwrap_or(""); + Self::ALL.into_iter().find(|l| l.code() == base) + } + + /// The first of the system's preferred languages the launcher has, else English. + pub fn pick<'a>(preferred: impl IntoIterator) -> Self { + preferred + .into_iter() + .find_map(Self::parse) + .unwrap_or_default() + } + + /// The system's language, as far as the launcher has it. + pub fn system() -> Self { + let locales: Vec = sys_locale::get_locales().collect(); + Self::pick(locales.iter().map(String::as_str)) + } + + /// The table, as shipped: English text to this language's. + fn source(self) -> &'static str { + match self { + Self::English => "{}", + Self::French => include_str!("../lang/fr.json"), + Self::Russian => include_str!("../lang/ru.json"), + } + } +} + +static CURRENT: AtomicU8 = AtomicU8::new(0); + +/// Shows the launcher in `language` from now on. +pub fn set(language: Language) { + let i = Language::ALL + .iter() + .position(|l| *l == language) + .unwrap_or(0); + CURRENT.store(i as u8, Ordering::Relaxed); +} + +pub fn current() -> Language { + Language::ALL[CURRENT.load(Ordering::Relaxed) as usize % Language::ALL.len()] +} + +type Table = HashMap; + +fn table(language: Language) -> &'static Table { + static TABLES: OnceLock> = OnceLock::new(); + let tables = TABLES.get_or_init(|| { + Language::ALL + .iter() + .map(|l| { + serde_json::from_str::>(l.source()) + .unwrap_or_default() + .into_iter() + .map(|(en, said)| (en, &*Box::leak(said.into_boxed_str()))) + .collect() + }) + .collect() + }); + let i = Language::ALL + .iter() + .position(|l| *l == language) + .unwrap_or(0); + &tables[i] +} + +/// `en` in `language`, or `en` itself where the table lacks it. +pub fn tr_in(language: Language, en: &str) -> &str { + table(language).get(en).copied().unwrap_or(en) +} + +/// `en` in the launcher's language. +pub fn tr(en: &str) -> &str { + tr_in(current(), en) +} + +/// `en` in the launcher's language with its `{name}` holes filled. +pub fn trf(en: &str, args: &[(&str, &str)]) -> String { + let mut out = tr(en).to_string(); + for (name, value) in args { + out = out.replace(&format!("{{{name}}}"), value); + } + out +} + +#[cfg(test)] +#[path = "i18n/tests.rs"] +mod tests; diff --git a/launcher/src/i18n/tests.rs b/launcher/src/i18n/tests.rs new file mode 100644 index 000000000..b9674f976 --- /dev/null +++ b/launcher/src/i18n/tests.rs @@ -0,0 +1,135 @@ +use super::*; +use std::collections::BTreeSet; +use std::path::Path; + +/// Every Rust file of the launcher's sources. +fn sources(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + sources(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + // Comments left out: they quote strings too. + let code = std::fs::read_to_string(path).unwrap(); + let lines = code + .lines() + .map(|l| match l.trim_start().starts_with("//") { + true => "", + false => l, + }); + out.push(lines.collect::>().join("\n")); + } + } +} + +/// The string literal at the start of `code` (just after its opening quote), unescaped the way +/// Rust does: `\"`, `\\`, `\n`, and a backslash at a line's end that drops the next line's +/// indent. +fn literal(code: &str) -> String { + let mut out = String::new(); + let mut chars = code.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' => break, + '\\' => match chars.next() { + Some('n') => out.push('\n'), + Some('\n') => { + while chars.peek().is_some_and(|c| c.is_whitespace()) { + chars.next(); + } + } + Some(c) => out.push(c), + None => break, + }, + c => out.push(c), + } + } + out +} + +/// The English strings the code asks a translation for: `tr("…")` and `trf("…")`, and every +/// other string literal (some reach `tr` through a widget). +fn strings() -> (BTreeSet, BTreeSet) { + let mut files = Vec::new(); + sources( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), + &mut files, + ); + let (mut asked, mut all) = (BTreeSet::new(), BTreeSet::new()); + for file in &files { + for (at, _) in file.match_indices('"') { + let before = &file[..at]; + if before.ends_with('\\') || before.ends_with('\'') { + continue; + } + let s = literal(&file[at + 1..]); + let call = |name: &str| { + before.ends_with(&format!("{name}(")) && { + let head = &before[..before.len() - name.len() - 1]; + !head.ends_with(|c: char| c.is_alphanumeric() || c == '_') + } + }; + if call("tr") || call("trf") { + asked.insert(s.clone()); + } + all.insert(s); + } + } + (asked, all) +} + +fn holes(s: &str) -> BTreeSet<&str> { + s.split('{') + .skip(1) + .filter_map(|part| part.split_once('}').map(|(name, _)| name)) + .collect() +} + +#[test] +fn every_language_has_every_string_the_code_asks_for() { + let (asked, all) = strings(); + assert!(asked.contains("Language"), "the scan finds tr(\"…\")"); + for language in [Language::French, Language::Russian] { + let table: HashMap = serde_json::from_str(language.source()) + .unwrap_or_else(|e| panic!("lang/{}.json: {e}", language.code())); + let missing: Vec<_> = asked.iter().filter(|s| !table.contains_key(*s)).collect(); + assert!( + missing.is_empty(), + "lang/{}.json lacks {missing:#?}", + language.code() + ); + let unused: Vec<_> = table.keys().filter(|s| !all.contains(*s)).collect(); + assert!( + unused.is_empty(), + "lang/{}.json has strings the code no longer has: {unused:#?}", + language.code() + ); + for (en, said) in &table { + assert_eq!(holes(en), holes(said), "{}: {en:?}", language.code()); + assert!( + !said.trim().is_empty(), + "{}: {en:?} is empty", + language.code() + ); + } + } +} + +#[test] +fn the_system_language_is_the_first_one_the_launcher_has() { + assert_eq!(Language::pick(["fr-CH", "en-US"]), Language::French); + assert_eq!(Language::pick(["de-CH", "ru_RU.UTF-8"]), Language::Russian); + assert_eq!(Language::pick(["de-DE", "ja"]), Language::English); + assert_eq!(Language::pick([]), Language::English); + assert_eq!(Language::parse("FR"), Some(Language::French)); + assert_eq!(Language::parse("french"), None); + assert_eq!(serde_json::to_string(&Language::Russian).unwrap(), "\"ru\""); +} + +#[test] +fn a_missing_string_shows_in_english() { + assert_eq!(tr_in(Language::French, "Settings"), "Paramètres"); + assert_eq!(tr_in(Language::Russian, "Settings"), "Настройки"); + assert_eq!(tr_in(Language::English, "Settings"), "Settings"); + assert_eq!(tr_in(Language::French, "No such string"), "No such string"); +} diff --git a/launcher/src/language_page.rs b/launcher/src/language_page.rs new file mode 100644 index 000000000..5dd940311 --- /dev/null +++ b/launcher/src/language_page.rs @@ -0,0 +1,35 @@ +//! Settings' Language row (`horizon_launcher::i18n`): the system's language, or one the player +//! picks, each named in itself. +use super::*; +use horizon_launcher::i18n::Language; + +impl Launcher { + pub(super) fn language_row(&self, cx: &mut Context) -> Div { + let t = self.theme; + let mut options = vec![(None, "System")]; + options.extend(Language::ALL.map(|l| (Some(l), l.name()))); + let picker = segments("language", &options, self.settings.language, &t, { + let this = cx.entity().downgrade(); + move |choice, _, cx| { + let _ = this.update(cx, |this, cx| { + this.settings.language = choice; + this.settings.save(); + i18n::set(this.settings.language()); + cx.notify(); + }); + } + }); + let said = trf( + "System follows your computer's language: {language} here. A string not translated \ + yet shows in English.", + &[("language", Language::system().name())], + ); + index_row( + 0, + tr("Language"), + Some(div().child(said).into_any_element()), + Some(picker.into_any_element()), + &t, + ) + } +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 4d8cfaaf3..d971c9667 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -11,6 +11,7 @@ pub mod export; pub mod game_app; pub mod game_log; pub mod heads; +pub mod i18n; pub mod import; pub mod instances; pub mod launch; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 5532b468d..67b6d0f84 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -18,6 +18,7 @@ mod game_tools; mod import_page; mod instances_page; mod internet; +mod language_page; mod launch_page; mod markdown; mod mcp; @@ -47,6 +48,7 @@ use gpui::{ }; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; +use horizon_launcher::i18n::{self, tr, trf}; use horizon_launcher::instances; use horizon_launcher::telemetry; use scrollbar::Scrollbar; @@ -314,6 +316,7 @@ impl Launcher { }) .detach(); let mut settings = Settings::load(); + i18n::set(settings.language()); if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); } @@ -1191,6 +1194,8 @@ fn button( t: &Theme, ) -> Stateful
{ let id: SharedString = id.into(); + let label: SharedString = label.into(); + let label = SharedString::from(tr(&label).to_string()); let t = *t; let hover = match kind { Kind::Primary => t.on_face.opacity(0.10), @@ -1234,7 +1239,7 @@ fn button( .items_center() .gap(px(8.)) .pb(px(if kind == Kind::Ghost { 0. } else { 2. })) - .child(label.into()), + .child(label), ); keyboard(track_hover(base, id), &t).active(|s| s.opacity(theme::PRESSED).top(px(1.))) } @@ -1302,7 +1307,7 @@ fn section_title(label: &'static str, icon: &'static str, t: &Theme) -> Div { .child( blocks::pixel(18., FontWeight::SEMIBOLD) .text_color(t.ink) - .child(label), + .child(tr(label)), ) } @@ -1348,7 +1353,7 @@ fn segments( .when(!active, |d| { d.text_color(t.muted).hover(move |s| s.text_color(t.ink)) }) - .child(div().relative().child(label)) + .child(div().relative().child(tr(label))) .on_click(move |_: &ClickEvent, window, cx| pick(value, window, cx)) })) } @@ -1374,13 +1379,13 @@ fn page_header(title: &str, description: &str, t: &Theme) -> Div { .child( blocks::pixel(36., FontWeight::SEMIBOLD) .text_color(t.ink) - .child(title.to_string()), + .child(tr(title).to_string()), ) .child( text(theme::UI) .max_w(px(520.)) .text_color(t.muted) - .child(description.to_string()), + .child(tr(description).to_string()), ) } @@ -1563,7 +1568,7 @@ impl Launcher { blocks::pixel(16., FontWeight::MEDIUM) .relative() .text_color(if active { t.ink } else { t.muted }) - .child(label), + .child(tr(label)), ) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { this.go(page); @@ -2581,10 +2586,10 @@ impl Launcher { }), ); let horizon = match (&self.updates.horizon, &self.update_error) { - (Some(r), _) => format!("{} available", r.tag), + (Some(r), _) => trf("{version} available", &[("version", &r.tag)]), (None, Some(e)) => e.clone(), - (None, None) if self.checked.is_some() => "Up to date".to_string(), - _ => "Checking…".to_string(), + (None, None) if self.checked.is_some() => tr("Up to date").to_string(), + _ => tr("Checking…").to_string(), }; let horizon_action = self .updates @@ -2601,18 +2606,36 @@ impl Launcher { }); let launcher = match &self.self_update { SelfUpdate::Downloading(v, p) => { - format!("{} · downloading {v}, {:.0}%", backend::VERSION, p * 100.) + let done = format!("{:.0}", p * 100.); + let said = trf( + "downloading {version}, {percent}%", + &[("version", v), ("percent", &done)], + ); + format!("{} · {said}", backend::VERSION) } - SelfUpdate::Ready(v) => format!("Updated to {v}. Restart the launcher to use it."), - SelfUpdate::Failed(e) => format!("{} · the update failed: {e}", backend::VERSION), + SelfUpdate::Ready(v) => trf( + "Updated to {version}. Restart the launcher to use it.", + &[("version", v)], + ), + SelfUpdate::Failed(e) => format!( + "{} · {}", + backend::VERSION, + trf("the update failed: {error}", &[("error", e)]) + ), SelfUpdate::Idle => match &self.updates.launcher { Some(r) => format!( - "{} · {} available", + "{} · {}", backend::VERSION, - backend::launcher_version(&r.tag).unwrap_or_default() + trf( + "{version} available", + &[( + "version", + backend::launcher_version(&r.tag).unwrap_or_default() + )] + ) ), None if self.checked.is_some() && self.update_error.is_none() => { - format!("{} · up to date", backend::VERSION) + format!("{} · {}", backend::VERSION, tr("up to date")) } None => backend::VERSION.to_string(), }, @@ -2637,7 +2660,7 @@ impl Launcher { ), }; let mono = |s: String| div().font_family(theme::MONO).child(s).into_any_element(); - let plain = |s: &str| div().child(s.to_string()).into_any_element(); + let plain = |s: &str| div().child(tr(s).to_string()).into_any_element(); let (accounts, n) = self.account_rows(cx); let (offline, n) = self.offline_rows(n, cx); let appearance = segments( @@ -2684,7 +2707,7 @@ impl Launcher { .child(group("Updates", "reload")) .child(index_row( n + 1, - "Install new versions automatically", + tr("Install new versions automatically"), Some(plain( "Your selected version only changes if you were playing the newest one.", )), @@ -2694,15 +2717,16 @@ impl Launcher { .child(group("Launcher", "monitor")) .child(index_row( n + 3, - "Appearance", + tr("Appearance"), Some(plain("Dark by default. System follows your computer's light or dark.")), Some(appearance.into_any_element()), &t, )) + .child(self.language_row(cx)) .child(self.while_playing_row(n + 3, cx)) .child(index_row( n + 3, - "Show the opening", + tr("Show the opening"), Some(plain("The wordmark, while the release list loads.")), Some(opening.into_any_element()), &t, @@ -2717,24 +2741,25 @@ impl Launcher { .child(index_row(n + 7, "Horizon", Some(plain(&horizon)), horizon_action, &t)) .child(index_row( n + 8, - "Launcher", + tr("Launcher"), Some(plain(&launcher)), launcher_action, &t, )) .child(index_row( n + 9, - "Data folder", + tr("Data folder"), Some(mono(short(&backend::data_dir()))), None, &t, )) .child(index_row( n + 10, - "Logs", + tr("Logs"), Some(mono(format!( - "{} · crash reports beside it", - short(&backend::logs_dir()) + "{} · {}", + short(&backend::logs_dir()), + tr("crash reports beside it") ))), Some( button("open-logs", "Open", Kind::Secondary, &t) @@ -2750,7 +2775,7 @@ impl Launcher { .when(cfg!(target_os = "linux"), |d| { d.child(index_row( n + 11, - "Applications menu", + tr("Applications menu"), Some(plain(if self.settings.desktop_entry() { "Horizon and its icon are in your desktop's menu." } else { @@ -2976,11 +3001,11 @@ impl Launcher { a.name.clone(), Some( div() - .child(if plays { + .child(tr(if plays { "Microsoft account · plays" } else { "Microsoft account · signed in" - }) + })) .into_any_element(), ), Some(actions.into_any_element()), @@ -2993,8 +3018,8 @@ impl Launcher { Some(SignInState::Starting | SignInState::Code(_)) ); let detail = match &self.sign_in_state { - _ if !configured => div().child(account::NOT_CONFIGURED), - Some(SignInState::Starting) => div().child("Asking Microsoft…"), + _ if !configured => div().child(tr(account::NOT_CONFIGURED)), + Some(SignInState::Starting) => div().child(tr("Asking Microsoft…")), Some(SignInState::Code(code)) => div() .flex() .flex_col() @@ -3014,7 +3039,7 @@ impl Launcher { None if self.accounts.accounts.is_empty() => div().child( "Sign in to play on online servers with your name and skin. Without an account the game plays offline.", ), - None => div().child("Add another account."), + None => div().child(tr("Add another account.")), }; let detail = if self.keychain || self.accounts.accounts.is_empty() { detail @@ -3085,7 +3110,7 @@ impl Launcher { }; rows = rows.child(index_row( n, - title, + tr(title), Some(detail.into_any_element()), action, &t, diff --git a/launcher/src/skin_page.rs b/launcher/src/skin_page.rs index 00e977216..5b2f6ae09 100644 --- a/launcher/src/skin_page.rs +++ b/launcher/src/skin_page.rs @@ -81,9 +81,12 @@ impl Launcher { true => l.cape = true, }) }); - let what = if cape { "cape" } else { "skin" }; if let Some(p) = &mut self.skin { - p.note = Some(done.map(|()| format!("{name}'s {what} is kept."))); + let said = match cape { + false => trf("{name}'s skin is kept.", &[("name", &name)]), + true => trf("{name}'s cape is kept.", &[("name", &name)]), + }; + p.note = Some(done.map(|()| said)); } } @@ -136,7 +139,7 @@ impl Launcher { Some(i) => gpui::img(i).w(px(w)).h(px(h)).into_any_element(), None => text(theme::CAPTION) .text_color(t.muted) - .child(empty) + .child(tr(empty)) .into_any_element(), }) }; @@ -205,7 +208,7 @@ impl Launcher { .flex_1() .min_w_0() .gap(px(12.)) - .child(caps(format!("{name}'s skin")).text_color(t.muted)) + .child(caps(trf("{name}'s skin", &[("name", &name)])).text_color(t.muted)) .child(skin_buttons) .child(model) .child(cape_buttons) @@ -213,12 +216,12 @@ impl Launcher { Ok(said) => text(theme::CAPTION).text_color(t.muted).child(said), Err(e) => text(theme::CAPTION).text_color(t.danger).child(e), })) - .child(text(theme::CAPTION).text_color(t.muted).child( + .child(text(theme::CAPTION).text_color(t.muted).child(tr( "A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the \ launcher and given to the game when this name plays. The game \ draws the default skins for now; it uses these once it can. A \ Microsoft account's skin and cape: coming soon.", - )), + ))), ), ) } diff --git a/launcher/src/switch_page.rs b/launcher/src/switch_page.rs index a29d21044..eb1e0bbfc 100644 --- a/launcher/src/switch_page.rs +++ b/launcher/src/switch_page.rs @@ -12,12 +12,12 @@ impl Launcher { self.accounts .selected() .map_or_else(String::new, |a| a.name.clone()), - "Microsoft account", + tr("Microsoft account"), ), - Player::Offline(name) => (name, "Offline"), + Player::Offline(name) => (name, tr("Offline")), Player::GameName => ( self.offline_name.clone().unwrap_or_else(|| "Player".into()), - "Offline", + tr("Offline"), ), } } @@ -42,7 +42,7 @@ impl Launcher { ( Player::Microsoft(a.uuid.clone()), a.name.clone(), - "Microsoft", + tr("Microsoft"), ) }) .collect(); @@ -50,12 +50,12 @@ impl Launcher { self.accounts .offline .iter() - .map(|n| (Player::Offline(n.clone()), n.clone(), "Offline")), + .map(|n| (Player::Offline(n.clone()), n.clone(), tr("Offline"))), ); out.push(( Player::GameName, self.offline_name.clone().unwrap_or_else(|| "Player".into()), - "Offline, the game's name", + tr("Offline, the game's name"), )); out } @@ -123,7 +123,7 @@ impl Launcher { .text_color(t.muted) .cursor_pointer() .hover(move |s| s.bg(t.plate_soft).text_color(t.ink)) - .child("Manage accounts") + .child(tr("Manage accounts")) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { this.account_menu = false; this.go(Page::Settings); @@ -196,11 +196,11 @@ impl Launcher { name, Some( div() - .child(if plays { + .child(tr(if plays { "Offline name · plays" } else { "Offline name" - }) + })) .into_any_element(), ), Some(actions.into_any_element()), @@ -213,7 +213,7 @@ impl Launcher { .flex() .items_center() .gap(px(8.)) - .child(self.field(Field::OfflineName, "A name, 3 to 16 letters", 220., cx)) + .child(self.field(Field::OfflineName, tr("A name, 3 to 16 letters"), 220., cx)) .child( button("offline-add", "Add", Kind::Secondary, &t).on_click(cx.listener( |this, _: &ClickEvent, _, cx| { @@ -224,13 +224,13 @@ impl Launcher { ); rows = rows.child(index_row( n, - "Offline name", + tr("Offline name"), Some( div() - .child( + .child(tr( "Play offline under another name, and switch from the top bar. Online \ servers don't take offline names.", - ) + )) .into_any_element(), ), Some(add.into_any_element()), diff --git a/launcher/src/while_playing.rs b/launcher/src/while_playing.rs index d39309f7c..f724d7e22 100644 --- a/launcher/src/while_playing.rs +++ b/launcher/src/while_playing.rs @@ -83,8 +83,8 @@ impl Launcher { }; index_row( n, - "While playing", - Some(div().child(said).into_any_element()), + tr("While playing"), + Some(div().child(tr(said)).into_any_element()), Some(picker.into_any_element()), &t, )