BlueGit

ict rusty-teams

Files

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

ui_locale.rs

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