1use std::{collections::BTreeMap, sync::OnceLock};
10
11#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
13pub enum Locale {
14 #[default]
15 En,
16 ZhCn,
17}
18
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
22pub enum Language {
23 #[default]
24 Auto,
25 English,
26 SimplifiedChinese,
27}
28
29impl Language {
30 pub fn parse(value: &str) -> Option<Self> {
31 match value {
32 "auto" => Some(Self::Auto),
33 "en" | "en-US" | "en-GB" => Some(Self::English),
34 "zh-CN" | "zh" | "zh-Hans" => Some(Self::SimplifiedChinese),
35 _ => None,
36 }
37 }
38
39 pub const fn code(self) -> &'static str {
40 match self {
41 Self::Auto => "auto",
42 Self::English => "en",
43 Self::SimplifiedChinese => "zh-CN",
44 }
45 }
46
47 pub fn resolve(self) -> Locale {
48 match self {
49 Self::Auto => Locale::system(),
50 Self::English => Locale::En,
51 Self::SimplifiedChinese => Locale::ZhCn,
52 }
53 }
54}
55
56impl Locale {
57 pub fn from_tag(tag: &str) -> Self {
61 if tag
62 .split(['-', '_', '.', '@'])
63 .next()
64 .is_some_and(|part| part.eq_ignore_ascii_case("zh"))
65 {
66 Self::ZhCn
67 } else {
68 Self::En
69 }
70 }
71
72 pub fn system() -> Self {
76 for name in ["RAZERS_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] {
77 if let Ok(value) = std::env::var(name) {
78 if !value.is_empty() && value != "auto" {
79 return Self::from_tag(&value);
80 }
81 }
82 }
83 sys_locale::get_locale().map_or(Self::En, |tag| Self::from_tag(&tag))
84 }
85
86 pub fn text(self, key: &str) -> &str {
90 catalog(self).get(key).map(String::as_str).unwrap_or(key)
91 }
92
93 pub fn format(self, key: &str, arguments: &[String]) -> String {
96 let template = self.text(key);
97 let mut output = String::new();
98 let mut rest = template;
99 while let Some(start) = rest.find('{') {
100 output.push_str(&rest[..start]);
101 let tail = &rest[start + 1..];
102 if let Some(end) = tail.find('}') {
103 if let Ok(index) = tail[..end].parse::<usize>() {
104 if let Some(argument) = arguments.get(index) {
105 output.push_str(argument);
106 rest = &tail[end + 1..];
107 continue;
108 }
109 }
110 }
111 output.push('{');
112 rest = tail;
113 }
114 output.push_str(rest);
115 output
116 }
117}
118
119pub fn language_args(args: Vec<String>) -> Result<(Option<Language>, Vec<String>), String> {
123 let mut language = None;
124 let mut remaining = Vec::new();
125 let mut args = args.into_iter();
126 while let Some(argument) = args.next() {
127 let value = if argument == "--lang" {
128 Some(args.next().ok_or("--lang expects auto, en, or zh-CN")?)
129 } else {
130 argument.strip_prefix("--lang=").map(str::to_owned)
131 };
132 if let Some(value) = value {
133 language = Some(Language::parse(&value).ok_or("--lang expects auto, en, or zh-CN")?);
134 } else {
135 remaining.push(argument);
136 }
137 }
138 Ok((language, remaining))
139}
140
141fn catalog(locale: Locale) -> &'static BTreeMap<String, String> {
142 static EN: OnceLock<BTreeMap<String, String>> = OnceLock::new();
143 static ZH: OnceLock<BTreeMap<String, String>> = OnceLock::new();
144 let (cell, source) = match locale {
145 Locale::En => (&EN, include_str!("../locales/en.json")),
146 Locale::ZhCn => (&ZH, include_str!("../locales/zh-CN.json")),
147 };
148 cell.get_or_init(|| {
149 serde_json::from_str(source).expect("validated embedded translation catalog")
150 })
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 fn placeholders(text: &str) -> Vec<usize> {
158 let mut result = text
159 .split('{')
160 .skip(1)
161 .filter_map(|part| part.split('}').next()?.parse().ok())
162 .collect::<Vec<_>>();
163 result.sort_unstable();
164 result
165 }
166
167 #[test]
168 fn catalogs_have_identical_keys_and_placeholders() {
169 let en = catalog(Locale::En);
170 let zh = catalog(Locale::ZhCn);
171 assert!(!en.is_empty());
172 assert_eq!(en.keys().collect::<Vec<_>>(), zh.keys().collect::<Vec<_>>());
173 for (key, value) in en {
174 assert!(!zh[key].trim().is_empty(), "empty translation: {key}");
175 assert_eq!(
176 placeholders(value),
177 placeholders(&zh[key]),
178 "placeholder mismatch: {key}"
179 );
180 }
181 }
182
183 #[test]
184 fn normalizes_locales_and_falls_back_to_english() {
185 for tag in ["zh_CN.UTF-8", "zh-Hans-CN", "ZH-cn", "zh_TW"] {
186 assert_eq!(Locale::from_tag(tag), Locale::ZhCn);
187 }
188 for tag in ["C", "POSIX", "en_US.UTF-8", "fr-FR", ""] {
189 assert_eq!(Locale::from_tag(tag), Locale::En);
190 }
191 assert_eq!(Locale::ZhCn.text("future message"), "future message");
192 }
193
194 #[test]
195 fn formatting_never_reinterprets_argument_contents() {
196 assert_eq!(
197 Locale::En.format("{0}: {1}", &["{1}".into(), "设备".into()]),
198 "{1}: 设备"
199 );
200 }
201
202 #[test]
203 fn parses_shared_language_options_and_rejects_mistakes() {
204 let (language, args) = language_args(vec!["help".into(), "--lang=zh-CN".into()]).unwrap();
205 assert_eq!(language, Some(Language::SimplifiedChinese));
206 assert_eq!(args, ["help"]);
207 assert!(language_args(vec!["--lang".into()]).is_err());
208 assert!(language_args(vec!["--lang=fr".into()]).is_err());
209 }
210}