Skip to main content

prt_core/i18n/
mod.rs

1//! Internationalization with runtime language switching.
2//!
3//! Supports English, Russian, and Chinese. Language is stored in an
4//! [`AtomicU8`] for lock-free reads — every frame calls [`strings()`]
5//! to get the current string table, so switching is instantaneous.
6//!
7//! # Language resolution priority
8//!
9//! 1. `--lang` CLI flag
10//! 2. `PRT_LANG` environment variable
11//! 3. System locale (via `sys-locale`)
12//! 4. English (default)
13//!
14//! # Adding a new language
15//!
16//! 1. Create `xx.rs` with `pub static STRINGS: Strings = Strings { ... }`
17//! 2. Add variant to [`Lang`] enum
18//! 3. Update [`strings()`], [`Lang::next()`], [`Lang::label()`], `Lang::from_u8()`
19//! 4. Compile — any missing `Strings` fields will be caught at compile time
20
21pub mod en;
22pub mod ru;
23pub mod zh;
24
25use std::sync::atomic::{AtomicU8, Ordering};
26
27/// Supported UI language.
28///
29/// Stored as `u8` in an `AtomicU8` for lock-free runtime switching.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Lang {
32    En = 0,
33    Ru = 1,
34    Zh = 2,
35}
36
37impl Lang {
38    /// Cycle to next language: En → Ru → Zh → En
39    pub fn next(self) -> Self {
40        match self {
41            Self::En => Self::Ru,
42            Self::Ru => Self::Zh,
43            Self::Zh => Self::En,
44        }
45    }
46
47    /// Short display name for status bar
48    pub fn label(self) -> &'static str {
49        match self {
50            Self::En => "EN",
51            Self::Ru => "RU",
52            Self::Zh => "ZH",
53        }
54    }
55
56    fn from_u8(v: u8) -> Self {
57        match v {
58            1 => Self::Ru,
59            2 => Self::Zh,
60            _ => Self::En,
61        }
62    }
63}
64
65static LANG: AtomicU8 = AtomicU8::new(0); // 0 = En
66
67/// Set the active UI language. Thread-safe, lock-free.
68pub fn set_lang(lang: Lang) {
69    LANG.store(lang as u8, Ordering::Relaxed);
70}
71
72/// Get the current UI language.
73pub fn lang() -> Lang {
74    Lang::from_u8(LANG.load(Ordering::Relaxed))
75}
76
77/// Get the string table for the current language.
78/// Called on every frame — must be fast (just an atomic load + match).
79pub fn strings() -> &'static Strings {
80    match lang() {
81        Lang::En => &en::STRINGS,
82        Lang::Ru => &ru::STRINGS,
83        Lang::Zh => &zh::STRINGS,
84    }
85}
86
87/// Detect language from environment: PRT_LANG env, then system locale, fallback En.
88pub fn detect_locale() -> Lang {
89    if let Ok(val) = std::env::var("PRT_LANG") {
90        return parse_lang(&val);
91    }
92
93    if let Some(locale) = sys_locale::get_locale() {
94        let lower = locale.to_lowercase();
95        if lower.starts_with("ru") {
96            return Lang::Ru;
97        }
98        if lower.starts_with("zh") {
99            return Lang::Zh;
100        }
101    }
102
103    Lang::En
104}
105
106/// Parse a language string (e.g. "ru", "chinese") into a [`Lang`] variant.
107/// Unknown strings default to English.
108pub fn parse_lang(s: &str) -> Lang {
109    match s.to_lowercase().as_str() {
110        "ru" | "russian" => Lang::Ru,
111        "zh" | "cn" | "chinese" => Lang::Zh,
112        _ => Lang::En,
113    }
114}
115
116/// All localizable UI strings for one language.
117///
118/// Each language module (`en`, `ru`, `zh`) provides a `static STRINGS: Strings`.
119/// Adding a field here forces all language files to be updated — compile-time
120/// completeness check.
121pub struct Strings {
122    pub app_name: &'static str,
123
124    // Header
125    pub connections: &'static str,
126    pub no_root_warning: &'static str,
127    pub sudo_ok: &'static str,
128    pub filter_label: &'static str,
129    pub search_mode: &'static str,
130
131    // Detail tabs
132    pub tab_tree: &'static str,
133    pub tab_network: &'static str,
134    pub tab_connection: &'static str,
135    pub no_selected_process: &'static str,
136
137    // View mode labels (fullscreen views)
138    pub view_chart: &'static str,
139    pub view_topology: &'static str,
140    pub view_process: &'static str,
141    pub view_namespaces: &'static str,
142
143    // Tree view
144    pub process_not_found: &'static str,
145
146    // Interface tab
147    pub iface_address: &'static str,
148    pub iface_interface: &'static str,
149    pub iface_protocol: &'static str,
150    pub iface_bind: &'static str,
151    pub iface_localhost_only: &'static str,
152    pub iface_all_interfaces: &'static str,
153    pub iface_specific: &'static str,
154    pub iface_loopback: &'static str,
155    pub iface_all: &'static str,
156
157    // Connection tab
158    pub conn_local: &'static str,
159    pub conn_remote: &'static str,
160    pub conn_state: &'static str,
161    pub conn_process: &'static str,
162    pub conn_cmdline: &'static str,
163
164    // Actions
165    pub help_text: &'static str,
166    pub kill_cancel: &'static str,
167    pub copied: &'static str,
168    pub refreshed: &'static str,
169    pub clipboard_unavailable: &'static str,
170    pub scan_error: &'static str,
171    pub cancelled: &'static str,
172    pub lang_switched: &'static str,
173
174    // Sudo
175    pub sudo_prompt_title: &'static str,
176    pub sudo_password_label: &'static str,
177    pub sudo_confirm_hint: &'static str,
178    pub sudo_failed: &'static str,
179    pub sudo_wrong_password: &'static str,
180    pub sudo_elevated: &'static str,
181
182    // Footer hints — common
183    pub hint_help: &'static str,
184    pub hint_search: &'static str,
185    pub hint_kill: &'static str,
186    pub hint_sudo: &'static str,
187    pub hint_quit: &'static str,
188    pub hint_lang: &'static str,
189
190    // Footer hints — context-specific
191    pub hint_back: &'static str,
192    pub hint_details: &'static str,
193    pub hint_views: &'static str,
194    pub hint_sort: &'static str,
195    pub hint_copy: &'static str,
196    pub hint_block: &'static str,
197    pub hint_trace: &'static str,
198    pub hint_navigate: &'static str,
199    pub hint_tabs: &'static str,
200
201    // Forward dialog
202    pub forward_prompt_title: &'static str,
203    pub forward_host_label: &'static str,
204    pub forward_confirm_hint: &'static str,
205    pub hint_forward: &'static str,
206
207    // Help overlay
208    pub help_title: &'static str,
209}
210
211impl Strings {
212    pub fn fmt_connections(&self, n: usize) -> String {
213        format!("{n} {}", self.connections)
214    }
215
216    pub fn fmt_kill_confirm(&self, name: &str, pid: u32) -> String {
217        match lang() {
218            Lang::En => format!("Kill {name} (pid {pid})?"),
219            Lang::Ru => format!("Завершить {name} (pid {pid})?"),
220            Lang::Zh => format!("终止 {name} (pid {pid})?"),
221        }
222    }
223
224    pub fn fmt_kill_sent(&self, sig: &str, name: &str, pid: u32) -> String {
225        match lang() {
226            Lang::En => format!("sent {sig} to {name} (pid {pid})"),
227            Lang::Ru => format!("отправлен {sig} → {name} (pid {pid})"),
228            Lang::Zh => format!("已发送 {sig} → {name} (pid {pid})"),
229        }
230    }
231
232    pub fn fmt_kill_failed(&self, err: &str) -> String {
233        match lang() {
234            Lang::En => format!("kill failed: {err}"),
235            Lang::Ru => format!("ошибка завершения: {err}"),
236            Lang::Zh => format!("终止失败: {err}"),
237        }
238    }
239
240    pub fn fmt_scan_error(&self, err: &str) -> String {
241        format!("{}: {err}", self.scan_error)
242    }
243
244    pub fn fmt_all_ports(&self, n: usize) -> String {
245        match lang() {
246            Lang::En => format!("--- All ports of process ({n}) ---"),
247            Lang::Ru => format!("--- Все порты процесса ({n}) ---"),
248            Lang::Zh => format!("--- 进程所有端口 ({n}) ---"),
249        }
250    }
251
252    pub fn fmt_sudo_error(&self, err: &str) -> String {
253        match lang() {
254            Lang::En => format!("sudo: {err}"),
255            Lang::Ru => format!("sudo ошибка: {err}"),
256            Lang::Zh => format!("sudo 错误: {err}"),
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn lang_next_cycles_all() {
267        let cases = [
268            (Lang::En, Lang::Ru),
269            (Lang::Ru, Lang::Zh),
270            (Lang::Zh, Lang::En),
271        ];
272        for (from, expected) in cases {
273            assert_eq!(from.next(), expected, "{:?}.next()", from);
274        }
275    }
276
277    #[test]
278    fn lang_next_full_cycle() {
279        let start = Lang::En;
280        let after_3 = start.next().next().next();
281        assert_eq!(after_3, start);
282    }
283
284    #[test]
285    fn lang_label() {
286        let cases = [(Lang::En, "EN"), (Lang::Ru, "RU"), (Lang::Zh, "ZH")];
287        for (lang, expected) in cases {
288            assert_eq!(lang.label(), expected);
289        }
290    }
291
292    #[test]
293    fn lang_from_u8_table() {
294        let cases = [
295            (0, Lang::En),
296            (1, Lang::Ru),
297            (2, Lang::Zh),
298            (99, Lang::En),
299            (255, Lang::En),
300        ];
301        for (val, expected) in cases {
302            assert_eq!(Lang::from_u8(val), expected, "from_u8({val})");
303        }
304    }
305
306    #[test]
307    fn parse_lang_table() {
308        let cases = [
309            ("en", Lang::En),
310            ("ru", Lang::Ru),
311            ("russian", Lang::Ru),
312            ("zh", Lang::Zh),
313            ("cn", Lang::Zh),
314            ("chinese", Lang::Zh),
315            ("EN", Lang::En),
316            ("RU", Lang::Ru),
317            ("ZH", Lang::Zh),
318            ("unknown", Lang::En),
319            ("", Lang::En),
320            ("fr", Lang::En),
321        ];
322        for (input, expected) in cases {
323            assert_eq!(parse_lang(input), expected, "parse_lang({input:?})");
324        }
325    }
326
327    #[test]
328    fn set_and_get_lang() {
329        set_lang(Lang::Ru);
330        assert_eq!(lang(), Lang::Ru);
331        set_lang(Lang::Zh);
332        assert_eq!(lang(), Lang::Zh);
333        set_lang(Lang::En);
334        assert_eq!(lang(), Lang::En);
335    }
336
337    #[test]
338    fn strings_returns_correct_lang() {
339        set_lang(Lang::En);
340        assert_eq!(strings().app_name, "PRT");
341        set_lang(Lang::Ru);
342        assert_eq!(strings().app_name, "PRT");
343        // Verify a lang-specific field
344        assert_eq!(strings().hint_quit, "выход");
345        set_lang(Lang::En);
346        assert_eq!(strings().hint_quit, "quit");
347    }
348
349    #[test]
350    fn strings_all_languages_have_non_empty_fields() {
351        for l in [Lang::En, Lang::Ru, Lang::Zh] {
352            set_lang(l);
353            let s = strings();
354            assert!(!s.app_name.is_empty(), "{:?} app_name empty", l);
355            assert!(!s.connections.is_empty(), "{:?} connections empty", l);
356            assert!(!s.help_text.is_empty(), "{:?} help_text empty", l);
357            assert!(!s.hint_help.is_empty(), "{:?} hint_help empty", l);
358            assert!(!s.hint_lang.is_empty(), "{:?} hint_lang empty", l);
359            assert!(!s.lang_switched.is_empty(), "{:?} lang_switched empty", l);
360        }
361        set_lang(Lang::En); // restore
362    }
363
364    #[test]
365    fn fmt_connections_contains_count() {
366        set_lang(Lang::En);
367        let s = strings();
368        assert!(s.fmt_connections(42).contains("42"));
369    }
370
371    #[test]
372    fn fmt_kill_confirm_contains_name_and_pid() {
373        for l in [Lang::En, Lang::Ru, Lang::Zh] {
374            set_lang(l);
375            let s = strings();
376            let msg = s.fmt_kill_confirm("nginx", 1234);
377            assert!(msg.contains("nginx"), "{:?}: {msg}", l);
378            assert!(msg.contains("1234"), "{:?}: {msg}", l);
379        }
380        set_lang(Lang::En);
381    }
382}