1use std::collections::BTreeMap;
14#[cfg(feature = "threads")]
15use std::path::Path;
16
17const ENGLISH: &str = include_str!("../locales/en.ftl");
18const SPANISH: &str = include_str!("../locales/es.ftl");
19const FRENCH: &str = include_str!("../locales/fr.ftl");
20const GERMAN: &str = include_str!("../locales/de.ftl");
21const PORTUGUESE: &str = include_str!("../locales/pt.ftl");
22const ARABIC: &str = include_str!("../locales/ar.ftl");
23
24#[derive(Clone, Debug)]
26pub struct Localizer {
32 locale: String,
33 messages: BTreeMap<String, String>,
34 fallback: BTreeMap<String, String>,
35}
36
37impl Default for Localizer {
38 fn default() -> Self {
39 Self::builtin("en")
40 }
41}
42
43impl Localizer {
44 pub fn builtin(locale: &str) -> Self {
47 let messages = match locale {
48 "es" => parse(SPANISH),
49 "fr" => parse(FRENCH),
50 "de" => parse(GERMAN),
51 "pt" => parse(PORTUGUESE),
52 "ar" => parse(ARABIC),
53 _ => parse(ENGLISH),
54 };
55 Self {
56 locale: locale.to_owned(),
57 messages,
58 fallback: parse(ENGLISH),
59 }
60 }
61
62 #[cfg(feature = "threads")]
63 pub fn load(directory: impl AsRef<Path>, locale: &str) -> Result<Self, LocalizationError> {
68 let plain = !locale.is_empty()
71 && locale.len() <= 32
72 && locale
73 .bytes()
74 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
75 if !plain {
76 return Ok(Self::builtin("en"));
77 }
78 let path = directory.as_ref().join(format!("{locale}.ftl"));
79 if path.is_file() {
80 let text = std::fs::read_to_string(&path).map_err(|error| LocalizationError::Io(error.to_string()))?;
81 let mut messages = Self::builtin(locale).messages;
82 messages.extend(parse(&text));
83 Ok(Self {
84 locale: locale.to_owned(),
85 messages,
86 fallback: parse(ENGLISH),
87 })
88 } else {
89 Ok(Self::builtin(locale))
90 }
91 }
92
93 pub fn locale(&self) -> &str {
95 &self.locale
96 }
97
98 pub fn is_rtl(&self) -> bool {
100 matches!(
101 self.locale.split(['-', '_']).next().unwrap_or(""),
102 "ar" | "he" | "fa" | "ur"
103 )
104 }
105
106 pub fn text(&self, key: &str) -> String {
108 self.translate(key, &[])
109 }
110
111 pub fn translate(&self, key: &str, args: &[(&str, &str)]) -> String {
113 let raw = self
114 .messages
115 .get(key)
116 .or_else(|| self.fallback.get(key))
117 .cloned()
118 .unwrap_or_else(|| key.to_owned());
119 interpolate(&raw, args)
120 }
121
122 pub fn plural(&self, key: &str, count: i64) -> String {
124 let raw = self
125 .messages
126 .get(key)
127 .or_else(|| self.fallback.get(key))
128 .cloned()
129 .unwrap_or_else(|| key.to_owned());
130 let category = if count == 1 { "one" } else { "other" };
131 let selected = select_plural(&raw, category).unwrap_or(raw);
132 interpolate(&selected, &[("count", &count.to_string())])
133 }
134}
135
136#[derive(Clone, Debug)]
138#[non_exhaustive]
139pub struct LocalizationState {
145 pub localizer: Localizer,
147}
148
149impl Default for LocalizationState {
150 fn default() -> Self {
151 Self::new("en")
152 }
153}
154
155impl LocalizationState {
156 pub fn new(locale: &str) -> Self {
158 Self {
159 localizer: Localizer::builtin(locale),
160 }
161 }
162
163 pub fn set_locale(&mut self, locale: &str) {
165 self.localizer = Localizer::builtin(locale);
166 }
167
168 pub fn t(&self, key: &str) -> String {
170 self.localizer.text(key)
171 }
172
173 pub fn locale(&self) -> &str {
175 self.localizer.locale()
176 }
177
178 pub fn is_rtl(&self) -> bool {
180 self.localizer.is_rtl()
181 }
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
186#[non_exhaustive]
187pub enum LocalizationError {
193 #[error("{0}")]
195 Io(String),
196}
197
198fn parse(text: &str) -> BTreeMap<String, String> {
199 let mut messages = BTreeMap::new();
200 let mut key: Option<String> = None;
201 let mut value = String::new();
202 for line in text.lines() {
203 if line.trim_start().starts_with('#') {
204 continue;
205 }
206 if !line.starts_with(char::is_whitespace) && line.contains('=') {
207 if let Some(key) = key.take() {
208 messages.insert(key, value.trim().to_owned());
209 }
210 let (name, rest) = line.split_once('=').unwrap_or((line, ""));
211 key = Some(name.trim().to_owned());
212 value = rest.trim_start().to_owned();
213 } else if key.is_some() {
214 value.push('\n');
215 value.push_str(line);
216 }
217 }
218 if let Some(key) = key {
219 messages.insert(key, value.trim().to_owned());
220 }
221 messages
222}
223
224fn interpolate(text: &str, args: &[(&str, &str)]) -> String {
225 let mut result = String::with_capacity(text.len());
228 let mut rest = text;
229 while let Some(start) = rest.find("{ $") {
230 result.push_str(rest.get(..start).unwrap_or_default());
231 let after = rest.get(start + 3..).unwrap_or_default();
232 let replaced = after.find(" }").and_then(|end| {
233 let name = after.get(..end).unwrap_or_default();
234 args.iter()
235 .find(|(key, _)| *key == name)
236 .map(|(_, value)| (end + 2, *value))
237 });
238 match replaced {
239 Some((consumed, value)) => {
240 result.push_str(value);
241 rest = after.get(consumed..).unwrap_or_default();
242 }
243 None => {
244 result.push_str("{ $");
245 rest = after;
246 }
247 }
248 }
249 result.push_str(rest);
250 result
251}
252
253fn select_plural(raw: &str, category: &str) -> Option<String> {
254 let start = raw.find("->")?;
255 let block = raw.get(start + 2..).unwrap_or_default();
256 let mut current: Option<String> = None;
257 let mut values: Vec<(String, String)> = Vec::new();
258 for line in block.lines() {
259 let trimmed = line.trim();
260 let selector = trimmed
261 .strip_prefix('[')
262 .or_else(|| trimmed.strip_prefix("*["))
263 .and_then(|rest| rest.split_once(']'));
264 if let Some((name, rest)) = selector {
265 let name = name.trim().to_owned();
266 current = Some(name.clone());
267 let text = rest.trim();
268 if !text.is_empty() {
269 values.push((name, text.to_owned()));
270 }
271 } else if let Some(name) = ¤t {
272 let text = trimmed.trim_end_matches('}').trim();
273 if text.is_empty() {
274 continue;
275 }
276 if let Some(entry) = values.iter_mut().find(|(key, _)| key == name) {
277 if !entry.1.is_empty() {
278 entry.1.push(' ');
279 }
280 entry.1.push_str(text);
281 } else {
282 values.push((name.clone(), text.to_owned()));
283 }
284 }
285 }
286 values
287 .into_iter()
288 .find(|(name, _)| name == category)
289 .map(|(_, value)| value)
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 #[test]
297 fn every_built_in_locale_translates_and_arabic_is_rtl() {
298 for (locale, save) in [
299 ("fr", "Enregistrer"),
300 ("de", "Speichern"),
301 ("pt", "Salvar"),
302 ("ar", "حفظ"),
303 ] {
304 assert_eq!(Localizer::builtin(locale).text("app.save"), save, "{locale}");
305 }
306 assert!(Localizer::builtin("ar").is_rtl());
307 assert!(!Localizer::builtin("fr").is_rtl());
308 assert_eq!(Localizer::builtin("ar").text("tabs.close"), "Close tab");
309 }
310
311 #[test]
312 fn english_and_spanish_strings_switch_at_runtime() {
313 let mut state = LocalizationState::new("en");
314 assert_eq!(state.t("app.save"), "Save");
315 state.set_locale("es");
316 assert_eq!(state.t("app.save"), "Guardar");
317 assert_eq!(state.t("devtools.performance"), "Rendimiento");
318 assert!(!state.is_rtl());
319 assert_eq!(state.t("missing.key"), "missing.key");
320 }
321
322 #[test]
323 fn plurals_use_one_and_other() {
324 let english = Localizer::builtin("en");
325 assert_eq!(english.plural("items", 1), "1 item");
326 assert_eq!(english.plural("items", 3), "3 items");
327 let spanish = Localizer::builtin("es");
328 assert_eq!(spanish.plural("files", 1), "1 archivo");
329 assert_eq!(spanish.plural("files", 2), "2 archivos");
330 assert!(Localizer::builtin("ar").is_rtl());
331 }
332
333 #[cfg(feature = "threads")]
334 #[test]
335 fn an_ftl_file_overrides_a_builtin() {
336 let directory = std::path::PathBuf::from("/tmp").join("crisol-locale-test");
337 std::fs::create_dir_all(&directory).expect("dir");
338 std::fs::write(directory.join("es.ftl"), "app.save = Guardar como\n").expect("write");
339 let localizer = Localizer::load(&directory, "es").expect("load");
340 assert_eq!(localizer.text("app.save"), "Guardar como");
341 assert_eq!(localizer.text("app.cancel"), "Cancelar");
342 let _ = std::fs::remove_dir_all(directory);
343 }
344
345 #[cfg(feature = "threads")]
346 #[test]
347 fn a_path_like_locale_falls_back_instead_of_escaping() {
348 let localizer = Localizer::load("/tmp", "../../etc/passwd").expect("fallback");
349 assert_eq!(localizer.locale(), "en");
350 }
351}