BlueGit

ict rusty-teams

Files

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

ui_locale.rs

ui_locale.rs 7.5 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#[cfg(test)]
127mod tests {
128 use std::sync::{Mutex, MutexGuard};
129
130 use super::*;
131 use tempfile::tempdir;
132
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
136 }
137
138 #[test]
139 fn ui_locale_effective_prefers_explicit_english_and_german() {
140 let _guard = locale_test_lock();
141 assert_eq!(
142 effective_locale_for(LocalePreference::English, "de-DE"),
143 "en"
144 );
145 assert_eq!(
146 effective_locale_for(LocalePreference::German, "en-US"),
147 "de"
148 );
149 }
150
151 #[test]
152 fn ui_locale_effective_auto_follows_os_tag() {
153 let _guard = locale_test_lock();
154 assert_eq!(effective_locale_for(LocalePreference::Auto, "de-DE"), "de");
155 assert_eq!(effective_locale_for(LocalePreference::Auto, "de"), "de");
156 assert_eq!(effective_locale_for(LocalePreference::Auto, "en-US"), "en");
157 assert_eq!(effective_locale_for(LocalePreference::Auto, "fr-FR"), "en");
158 }
159
160 #[test]
161 fn ui_locale_load_save_roundtrip_in_store() {
162 let _guard = locale_test_lock();
163 let store = Store::open_in_memory().expect("in-memory store");
164 assert_eq!(load(&store), LocalePreference::Auto);
165 save(&store, LocalePreference::German);
166 assert_eq!(load(&store), LocalePreference::German);
167 save(&store, LocalePreference::English);
168 assert_eq!(load(&store), LocalePreference::English);
169 }
170
171 #[test]
172 fn ui_locale_persists_via_tempfile_store() {
173 let _guard = locale_test_lock();
174 let directory = tempdir().expect("tempdir");
175 let path = directory.path().join("locale.sqlite3");
176 let store = Store::open(&path).expect("store on disk");
177 save(&store, LocalePreference::German);
178 drop(store);
179 let store = Store::open(&path).expect("reopen store");
180 assert_eq!(load(&store), LocalePreference::German);
181 }
182
183 #[test]
184 fn ui_locale_unknown_preference_falls_back_to_auto() {
185 let _guard = locale_test_lock();
186 let store = Store::open_in_memory().expect("in-memory store");
187 let _ = store.set_meta(META_KEY, "preference=fr");
188 assert_eq!(load(&store), LocalePreference::Auto);
189 }
190
191 #[test]
192 fn ui_locale_tr_resolves_catalog_in_en_and_de() {
193 let _guard = locale_test_lock();
194 apply_locale("en");
195 assert_eq!(tr("common.cancel"), "Cancel");
196 apply_locale("de");
197 assert_eq!(tr("common.cancel"), "Abbrechen");
198 }
199
200 #[test]
201 fn ui_locale_tr_args_substitutes_detail() {
202 let _guard = locale_test_lock();
203 apply_locale("en");
204 let mut args = HashMap::new();
205 args.insert("detail".to_owned(), "timeout".to_owned());
206 assert_eq!(
207 tr_args("notice.generic_detail", &args),
208 "Something went wrong: timeout"
209 );
210 }
211
212 #[test]
213 fn ui_locale_notice_localizes_call_on_hold_in_de() {
214 let _guard = locale_test_lock();
215 apply_locale("de");
216 let localized = localize_notice("calls.notice.on_hold");
217 assert_eq!(localized, "Setzen Sie den Anruf zuerst fort");
218 }
219
220 #[test]
221 fn ui_locale_sidebar_and_status_menu_in_de() {
222 let _guard = locale_test_lock();
223 apply_locale("de");
224 assert_eq!(tr("sidebar.quick_views"), "Schnellansichten");
225 assert_eq!(tr("status_menu.view_account"), "Konto anzeigen");
226 assert_eq!(tr("shell.settings_and_more"), "Einstellungen und mehr");
227 }
228
229 #[test]
230 fn ui_locale_tray_keys_resolve() {
231 let _guard = locale_test_lock();
232 apply_locale("en");
233 assert_eq!(tr("tray.open"), "Open");
234 assert_eq!(tr("tray.quit"), "Quit");
235 assert_eq!(tr("tray.mute_sound"), "Mute sound");
236 apply_locale("de");
237 assert_eq!(tr("tray.do_not_disturb"), "Nicht stören");
238 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
239 }
240
241 #[test]
242 fn ui_locale_fallback_missing_key_returns_english_or_key() {
243 let _guard = locale_test_lock();
244 apply_locale("de");
245 assert_eq!(tr("common.cancel"), "Abbrechen");
246 let missing = tr("catalog.does_not_exist_yet");
247 assert!(!missing.is_empty());
248 }
249}