BlueGit

ict rusty-teams

Files

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

ui_locale.rs

ui_locale.rs 10.2 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/// Separator between an i18n key and a detail payload in `CallUpdate::Notice`.
107pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
108
109/// Resolve a call/UI notice payload: bare key, or `key` + detail after [`NOTICE_DETAIL_SEP`].
110pub fn localize_notice(payload: &str) -> String {
111 if let Some((key, detail)) = payload.split_once(NOTICE_DETAIL_SEP) {
112 let mut args = HashMap::new();
113 args.insert("detail".to_owned(), detail.to_owned());
114 return tr_args(key, &args);
115 }
116 if payload.contains('.') {
117 return tr(payload);
118 }
119 payload.to_owned()
120}
121
122pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124}
125
126/// Serialises tests in this crate that read or set the global UI language.
127#[cfg(test)]
128pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
129 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130 LOCK.lock().unwrap_or_else(|error| error.into_inner())
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use tempfile::tempdir;
137
138 /// Leaf keys (`a.b.c`) with the languages they define, read from the locale file.
139 fn leaf_languages() -> Vec<(String, Vec<String>)> {
140 let mut path: Vec<(usize, String)> = Vec::new();
141 let mut leaves: Vec<(String, Vec<String>)> = Vec::new();
142 for line in include_str!("../locales/app.yml").lines() {
143 let trimmed = line.trim_start();
144 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('_') {
145 continue;
146 }
147 let indent = line.len() - trimmed.len();
148 let Some((key, value)) = trimmed.split_once(':') else {
149 continue;
150 };
151 if key == "en" || key == "de" {
152 if let Some(last) = leaves.last_mut() {
153 last.1.push(key.to_owned());
154 }
155 continue;
156 }
157 path.retain(|(depth, _)| *depth < indent);
158 path.push((indent, key.to_owned()));
159 if value.trim().is_empty() {
160 let full: Vec<&str> = path.iter().map(|(_, key)| key.as_str()).collect();
161 leaves.push((full.join("."), Vec::new()));
162 }
163 }
164 leaves.retain(|(_, languages)| !languages.is_empty());
165 leaves
166 }
167
168 #[test]
169 fn calendar_strings_exist_in_english_and_german() {
170 const PREFIXES: [&str; 5] = [
171 "calendar.view.",
172 "calendar.weekday.",
173 "calendar.weekday_short.",
174 "calendar.month.",
175 "settings.calendar.",
176 ];
177 let leaves = leaf_languages();
178 let covered: Vec<_> = leaves
179 .iter()
180 .filter(|(key, _)| PREFIXES.iter().any(|prefix| key.starts_with(prefix)))
181 .collect();
182 assert!(
183 covered.len() > 60,
184 "only {} calendar keys found",
185 covered.len()
186 );
187 let missing: Vec<_> = covered
188 .iter()
189 .filter(|(_, languages)| {
190 !(languages.contains(&"en".into()) && languages.contains(&"de".into()))
191 })
192 .map(|(key, _)| key.as_str())
193 .collect();
194 assert!(missing.is_empty(), "missing en or de: {missing:?}");
195 }
196
197 #[test]
198 fn ui_locale_effective_prefers_explicit_english_and_german() {
199 let _guard = locale_test_lock();
200 assert_eq!(
201 effective_locale_for(LocalePreference::English, "de-DE"),
202 "en"
203 );
204 assert_eq!(
205 effective_locale_for(LocalePreference::German, "en-US"),
206 "de"
207 );
208 }
209
210 #[test]
211 fn ui_locale_effective_auto_follows_os_tag() {
212 let _guard = locale_test_lock();
213 assert_eq!(effective_locale_for(LocalePreference::Auto, "de-DE"), "de");
214 assert_eq!(effective_locale_for(LocalePreference::Auto, "de"), "de");
215 assert_eq!(effective_locale_for(LocalePreference::Auto, "en-US"), "en");
216 assert_eq!(effective_locale_for(LocalePreference::Auto, "fr-FR"), "en");
217 }
218
219 #[test]
220 fn ui_locale_load_save_roundtrip_in_store() {
221 let _guard = locale_test_lock();
222 let store = Store::open_in_memory().expect("in-memory store");
223 assert_eq!(load(&store), LocalePreference::Auto);
224 save(&store, LocalePreference::German);
225 assert_eq!(load(&store), LocalePreference::German);
226 save(&store, LocalePreference::English);
227 assert_eq!(load(&store), LocalePreference::English);
228 }
229
230 #[test]
231 fn ui_locale_persists_via_tempfile_store() {
232 let _guard = locale_test_lock();
233 let directory = tempdir().expect("tempdir");
234 let path = directory.path().join("locale.sqlite3");
235 let store = Store::open(&path).expect("store on disk");
236 save(&store, LocalePreference::German);
237 drop(store);
238 let store = Store::open(&path).expect("reopen store");
239 assert_eq!(load(&store), LocalePreference::German);
240 }
241
242 #[test]
243 fn ui_locale_unknown_preference_falls_back_to_auto() {
244 let _guard = locale_test_lock();
245 let store = Store::open_in_memory().expect("in-memory store");
246 let _ = store.set_meta(META_KEY, "preference=fr");
247 assert_eq!(load(&store), LocalePreference::Auto);
248 }
249
250 #[test]
251 fn ui_locale_tr_resolves_catalog_in_en_and_de() {
252 let _guard = locale_test_lock();
253 apply_locale("en");
254 assert_eq!(tr("common.cancel"), "Cancel");
255 apply_locale("de");
256 assert_eq!(tr("common.cancel"), "Abbrechen");
257 }
258
259 #[test]
260 fn ui_locale_tr_args_substitutes_detail() {
261 let _guard = locale_test_lock();
262 apply_locale("en");
263 let mut args = HashMap::new();
264 args.insert("detail".to_owned(), "timeout".to_owned());
265 assert_eq!(
266 tr_args("notice.generic_detail", &args),
267 "Something went wrong: timeout"
268 );
269 }
270
271 #[test]
272 fn ui_locale_notice_localizes_call_on_hold_in_de() {
273 let _guard = locale_test_lock();
274 apply_locale("de");
275 let localized = localize_notice("calls.notice.on_hold");
276 assert_eq!(localized, "Setzen Sie den Anruf zuerst fort");
277 }
278
279 #[test]
280 fn ui_locale_sidebar_and_status_menu_in_de() {
281 let _guard = locale_test_lock();
282 apply_locale("de");
283 assert_eq!(tr("sidebar.quick_views"), "Schnellansichten");
284 assert_eq!(tr("status_menu.view_account"), "Konto anzeigen");
285 assert_eq!(tr("shell.settings_and_more"), "Einstellungen und mehr");
286 }
287
288 #[test]
289 fn ui_locale_auth_banner_and_splash_keys() {
290 let _guard = locale_test_lock();
291 apply_locale("en");
292 assert_eq!(tr("auth.banner.connecting"), "Connecting...");
293 assert_ne!(tr("auth.banner.connecting"), "auth.banner.connecting");
294 apply_locale("de");
295 assert!(tr("auth.banner.connecting").contains("Verbindung"));
296 assert!(tr("auth.splash.awaiting_browser").contains("Browser"));
297 }
298
299 #[test]
300 fn ui_locale_tray_keys_resolve() {
301 let _guard = locale_test_lock();
302 apply_locale("en");
303 assert_eq!(tr("tray.open"), "Open");
304 assert_eq!(tr("tray.quit"), "Quit");
305 assert_eq!(tr("tray.mute_sound"), "Mute sound");
306 apply_locale("de");
307 assert_eq!(tr("tray.do_not_disturb"), "Nicht stören");
308 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
309 }
310
311 #[test]
312 fn ui_locale_fallback_missing_key_returns_english_or_key() {
313 let _guard = locale_test_lock();
314 apply_locale("de");
315 assert_eq!(tr("common.cancel"), "Abbrechen");
316 let missing = tr("catalog.does_not_exist_yet");
317 assert!(!missing.is_empty());
318 }
319}