BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / ui_locale.rs

ui_locale.rs

ui_locale.rs 12.1 KiB Download Raw
1use std::collections::HashMap;
2
3use store::Store;
4
5const META_KEY: &str = "ui.locale";
6const PREFERENCE_KEY: &str = "preference";
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum LocalePreference {
10 #[default]
11 Auto,
12 English,
13 German,
14}
15
16impl LocalePreference {
17 pub const ALL: [LocalePreference; 3] = [
18 LocalePreference::Auto,
19 LocalePreference::English,
20 LocalePreference::German,
21 ];
22
23 pub fn key(self) -> &'static str {
24 match self {
25 LocalePreference::Auto => "auto",
26 LocalePreference::English => "en",
27 LocalePreference::German => "de",
28 }
29 }
30
31 pub fn from_key(key: &str) -> Option<LocalePreference> {
32 Self::ALL
33 .into_iter()
34 .find(|preference| preference.key() == key)
35 }
36}
37
38pub fn os_language_tag() -> String {
39 sys_locale::get_locale().unwrap_or_else(|| "en".to_owned())
40}
41
42pub fn effective_locale(pref: LocalePreference) -> &'static str {
43 effective_locale_for(pref, &os_language_tag())
44}
45
46pub(crate) fn effective_locale_for(pref: LocalePreference, os_tag: &str) -> &'static str {
47 match pref {
48 LocalePreference::German => "de",
49 LocalePreference::English => "en",
50 LocalePreference::Auto => {
51 if os_tag.to_lowercase().starts_with("de") {
52 "de"
53 } else {
54 "en"
55 }
56 }
57 }
58}
59
60pub fn apply_locale(locale: &str) {
61 rust_i18n::set_locale(locale);
62 gpui_kit::component::set_locale(locale);
63}
64
65pub fn load(store: &Store) -> LocalePreference {
66 store
67 .meta(META_KEY)
68 .ok()
69 .flatten()
70 .map(|text| parse(&text))
71 .unwrap_or_default()
72}
73
74pub fn save(store: &Store, pref: LocalePreference) {
75 let _ = store.set_meta(META_KEY, &serialize(pref));
76}
77
78fn serialize(pref: LocalePreference) -> String {
79 format!("{PREFERENCE_KEY}={}", pref.key())
80}
81
82fn parse(text: &str) -> LocalePreference {
83 for line in text.lines() {
84 if let Some((PREFERENCE_KEY, value)) = line.split_once('=') {
85 if let Some(pref) = LocalePreference::from_key(value.trim()) {
86 return pref;
87 }
88 }
89 }
90 LocalePreference::default()
91}
92
93pub fn tr(key: &str) -> String {
94 rust_i18n::t!(key).to_string()
95}
96
97pub fn tr_args(key: &str, args: &HashMap<String, String>) -> String {
98 if args.is_empty() {
99 return tr(key);
100 }
101 let patterns: Vec<&str> = args.keys().map(String::as_str).collect();
102 let values: Vec<String> = patterns.iter().map(|name| args[*name].clone()).collect();
103 rust_i18n::replace_patterns(&tr(key), &patterns, &values)
104}
105
106/// `tr_with("regional.until", &[("time", "14:30")])` for a pattern with `%{time}`.
107pub fn tr_with(key: &str, args: &[(&str, &str)]) -> String {
108 let (patterns, values): (Vec<&str>, Vec<String>) = args
109 .iter()
110 .map(|(name, value)| (*name, (*value).to_owned()))
111 .unzip();
112 rust_i18n::replace_patterns(&tr(key), &patterns, &values)
113}
114
115/// Separator between an i18n key and a detail payload in `CallUpdate::Notice`.
116pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
117
118/// Resolve a call/UI notice payload: bare key, or `key` + detail after [`NOTICE_DETAIL_SEP`].
119pub fn localize_notice(payload: &str) -> String {
120 if let Some((key, detail)) = payload.split_once(NOTICE_DETAIL_SEP) {
121 let mut args = HashMap::new();
122 args.insert("detail".to_owned(), detail.to_owned());
123 return tr_args(key, &args);
124 }
125 if payload.contains('.') {
126 return tr(payload);
127 }
128 payload.to_owned()
129}
130
131pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
132 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
133}
134
135/// Serialises tests in this crate that read or set the global UI language.
136#[cfg(test)]
137pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
138 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
139 LOCK.lock().unwrap_or_else(|error| error.into_inner())
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use tempfile::tempdir;
146
147 /// Leaf keys (`a.b.c`) with the languages they define, read from the locale file.
148 fn leaf_languages() -> Vec<(String, Vec<String>)> {
149 let mut path: Vec<(usize, String)> = Vec::new();
150 let mut leaves: Vec<(String, Vec<String>)> = Vec::new();
151 for line in include_str!("../locales/app.yml").lines() {
152 let trimmed = line.trim_start();
153 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('_') {
154 continue;
155 }
156 let indent = line.len() - trimmed.len();
157 let Some((key, value)) = trimmed.split_once(':') else {
158 continue;
159 };
160 if key == "en" || key == "de" {
161 if let Some(last) = leaves.last_mut() {
162 last.1.push(key.to_owned());
163 }
164 continue;
165 }
166 path.retain(|(depth, _)| *depth < indent);
167 path.push((indent, key.to_owned()));
168 if value.trim().is_empty() {
169 let full: Vec<&str> = path.iter().map(|(_, key)| key.as_str()).collect();
170 leaves.push((full.join("."), Vec::new()));
171 }
172 }
173 leaves.retain(|(_, languages)| !languages.is_empty());
174 leaves
175 }
176
177 #[test]
178 fn calendar_strings_exist_in_english_and_german() {
179 const PREFIXES: [&str; 5] = [
180 "calendar.view.",
181 "calendar.weekday.",
182 "calendar.weekday_short.",
183 "calendar.month.",
184 "settings.calendar.",
185 ];
186 let leaves = leaf_languages();
187 let covered: Vec<_> = leaves
188 .iter()
189 .filter(|(key, _)| PREFIXES.iter().any(|prefix| key.starts_with(prefix)))
190 .collect();
191 assert!(
192 covered.len() > 60,
193 "only {} calendar keys found",
194 covered.len()
195 );
196 let missing: Vec<_> = covered
197 .iter()
198 .filter(|(_, languages)| {
199 !(languages.contains(&"en".into()) && languages.contains(&"de".into()))
200 })
201 .map(|(key, _)| key.as_str())
202 .collect();
203 assert!(missing.is_empty(), "missing en or de: {missing:?}");
204 }
205
206 #[test]
207 fn every_key_resolves_in_english_and_german() {
208 let _guard = locale_test_lock();
209 let keys: Vec<String> = leaf_languages()
210 .into_iter()
211 .map(|(key, _)| key.replace('"', ""))
212 .collect();
213 assert!(keys.len() > 500, "only {} keys found", keys.len());
214 for locale in ["en", "de"] {
215 rust_i18n::set_locale(locale);
216 let raw: Vec<_> = keys.iter().filter(|key| tr(key) == **key).collect();
217 assert!(raw.is_empty(), "{locale} shows raw keys: {raw:?}");
218 }
219 rust_i18n::set_locale("en");
220 }
221
222 #[test]
223 fn ui_locale_effective_prefers_explicit_english_and_german() {
224 let _guard = locale_test_lock();
225 assert_eq!(
226 effective_locale_for(LocalePreference::English, "de-DE"),
227 "en"
228 );
229 assert_eq!(
230 effective_locale_for(LocalePreference::German, "en-US"),
231 "de"
232 );
233 }
234
235 #[test]
236 fn ui_locale_effective_auto_follows_os_tag() {
237 let _guard = locale_test_lock();
238 assert_eq!(effective_locale_for(LocalePreference::Auto, "de-DE"), "de");
239 assert_eq!(effective_locale_for(LocalePreference::Auto, "de"), "de");
240 assert_eq!(effective_locale_for(LocalePreference::Auto, "en-US"), "en");
241 assert_eq!(effective_locale_for(LocalePreference::Auto, "fr-FR"), "en");
242 }
243
244 #[test]
245 fn ui_locale_load_save_roundtrip_in_store() {
246 let _guard = locale_test_lock();
247 let store = Store::open_in_memory().expect("in-memory store");
248 assert_eq!(load(&store), LocalePreference::Auto);
249 save(&store, LocalePreference::German);
250 assert_eq!(load(&store), LocalePreference::German);
251 save(&store, LocalePreference::English);
252 assert_eq!(load(&store), LocalePreference::English);
253 }
254
255 #[test]
256 fn ui_locale_persists_via_tempfile_store() {
257 let _guard = locale_test_lock();
258 let directory = tempdir().expect("tempdir");
259 let path = directory.path().join("locale.sqlite3");
260 let store = Store::open(&path).expect("store on disk");
261 save(&store, LocalePreference::German);
262 drop(store);
263 let store = Store::open(&path).expect("reopen store");
264 assert_eq!(load(&store), LocalePreference::German);
265 }
266
267 #[test]
268 fn ui_locale_unknown_preference_falls_back_to_auto() {
269 let _guard = locale_test_lock();
270 let store = Store::open_in_memory().expect("in-memory store");
271 let _ = store.set_meta(META_KEY, "preference=fr");
272 assert_eq!(load(&store), LocalePreference::Auto);
273 }
274
275 #[test]
276 fn ui_locale_tr_resolves_catalog_in_en_and_de() {
277 let _guard = locale_test_lock();
278 apply_locale("en");
279 assert_eq!(tr("common.cancel"), "Cancel");
280 apply_locale("de");
281 assert_eq!(tr("common.cancel"), "Abbrechen");
282 }
283
284 #[test]
285 fn ui_locale_tr_args_substitutes_detail() {
286 let _guard = locale_test_lock();
287 apply_locale("en");
288 let mut args = HashMap::new();
289 args.insert("detail".to_owned(), "timeout".to_owned());
290 assert_eq!(
291 tr_args("notice.generic_detail", &args),
292 "Something went wrong: timeout"
293 );
294 }
295
296 #[test]
297 fn ui_locale_notice_localizes_call_on_hold_in_de() {
298 let _guard = locale_test_lock();
299 apply_locale("de");
300 let localized = localize_notice("calls.notice.on_hold");
301 assert_eq!(localized, "Setzen Sie den Anruf zuerst fort");
302 }
303
304 #[test]
305 fn ui_locale_sidebar_and_status_menu_in_de() {
306 let _guard = locale_test_lock();
307 apply_locale("de");
308 assert_eq!(tr("sidebar.quick_views"), "Schnellansichten");
309 assert_eq!(tr("status_menu.view_account"), "Konto anzeigen");
310 assert_eq!(tr("shell.settings_and_more"), "Einstellungen und mehr");
311 }
312
313 #[test]
314 fn ui_locale_auth_banner_and_splash_keys() {
315 let _guard = locale_test_lock();
316 apply_locale("en");
317 assert_eq!(tr("auth.banner.connecting"), "Connecting...");
318 assert_ne!(tr("auth.banner.connecting"), "auth.banner.connecting");
319 apply_locale("de");
320 assert!(tr("auth.banner.connecting").contains("Verbindung"));
321 assert!(tr("auth.splash.awaiting_browser").contains("Browser"));
322 }
323
324 #[test]
325 fn ui_locale_tray_keys_resolve() {
326 let _guard = locale_test_lock();
327 apply_locale("en");
328 assert_eq!(tr("tray.open"), "Open");
329 assert_eq!(tr("tray.quit"), "Quit");
330 assert_eq!(tr("tray.notifications"), "Notifications");
331 apply_locale("de");
332 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
333 }
334
335 #[test]
336 fn ui_locale_notify_action_keys_resolve() {
337 let _guard = locale_test_lock();
338 apply_locale("en");
339 assert_eq!(tr("notify.mark_read"), "Mark as read");
340 assert_eq!(tr("notify.reply"), "Reply");
341 assert_eq!(tr("notify.decline"), "Decline");
342 assert_eq!(tr("notify.accept"), "Accept");
343 assert_eq!(tr("notify.audio"), "Audio");
344 assert_eq!(tr("notify.video"), "Video");
345 assert_eq!(tr("notify.join"), "Join");
346 assert_eq!(tr("notify.snooze"), "Snooze");
347 apply_locale("de");
348 assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");
349 assert_eq!(tr("notify.reply"), "Antworten");
350 assert_eq!(tr("notify.decline"), "Ablehnen");
351 assert_eq!(tr("notify.accept"), "Annehmen");
352 assert_eq!(tr("notify.audio"), "Audio");
353 assert_eq!(tr("notify.video"), "Video");
354 assert_eq!(tr("notify.join"), "Teilnehmen");
355 assert_eq!(tr("notify.snooze"), "Schlummern");
356 }
357
358 #[test]
359 fn ui_locale_fallback_missing_key_returns_english_or_key() {
360 let _guard = locale_test_lock();
361 apply_locale("de");
362 assert_eq!(tr("common.cancel"), "Abbrechen");
363 let missing = tr("catalog.does_not_exist_yet");
364 assert!(!missing.is_empty());
365 }
366}