1mod locale;
19mod plural;
20mod tag;
21mod week;
22
23use std::cell::RefCell;
24use std::collections::BTreeMap;
25use std::fmt::Write as _;
26use std::io;
27use std::path::Path;
28use std::sync::Arc;
29
30pub use plural::PluralCategory;
31
32use crate::assets;
33use crate::date::Weekday;
34use crate::diagnostics::Diagnostic;
35use locale::{Locale, Message, Piece, Template};
36use tag::Tag;
37
38const ROOT_LOCALE: &str = "en";
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Arg {
44 Text(String),
46 Int(i64),
48}
49
50impl From<&str> for Arg {
51 fn from(value: &str) -> Self {
52 Self::Text(value.to_owned())
53 }
54}
55
56impl From<String> for Arg {
57 fn from(value: String) -> Self {
58 Self::Text(value)
59 }
60}
61
62impl From<i64> for Arg {
63 fn from(value: i64) -> Self {
64 Self::Int(value)
65 }
66}
67
68impl From<i32> for Arg {
69 fn from(value: i32) -> Self {
70 Self::Int(i64::from(value))
71 }
72}
73
74impl From<u16> for Arg {
75 fn from(value: u16) -> Self {
76 Self::Int(i64::from(value))
77 }
78}
79
80impl From<u32> for Arg {
81 fn from(value: u32) -> Self {
82 Self::Int(i64::from(value))
83 }
84}
85
86impl From<usize> for Arg {
87 fn from(value: usize) -> Self {
88 Self::Int(i64::try_from(value).unwrap_or(i64::MAX))
89 }
90}
91
92#[derive(Debug, Clone)]
94pub struct I18n {
95 locales: BTreeMap<String, Locale>,
96 active: String,
97 region: Option<String>,
98 diagnostics: Vec<Diagnostic>,
99}
100
101impl I18n {
102 #[must_use]
104 pub fn builtin() -> Self {
105 let mut i18n =
106 Self { locales: BTreeMap::new(), active: ROOT_LOCALE.to_owned(), region: None, diagnostics: Vec::new() };
107 for (code, text) in assets::LOCALES {
108 i18n.add_source(&format!("{code}.toml"), text);
109 }
110 i18n
111 }
112
113 pub fn add_source(&mut self, file: &str, text: &str) -> bool {
117 let Some(parsed) = locale::parse(file, text, &mut self.diagnostics) else {
118 return false;
119 };
120 match self.locales.get_mut(&parsed.code) {
121 Some(existing) => {
122 existing.name = parsed.name;
123 if parsed.fallback.is_some() {
124 existing.fallback = parsed.fallback;
125 }
126 existing.messages.extend(parsed.messages);
127 }
128 None => {
129 self.locales.insert(parsed.code.clone(), parsed);
130 }
131 }
132 true
133 }
134
135 pub fn load_dir(&mut self, dir: &Path) -> io::Result<()> {
142 let found = assets::read_toml_dir(dir)?;
143 self.diagnostics.extend(found.skipped);
144 for (_, file, text) in found.files {
145 self.add_source(&file, &text);
146 }
147 Ok(())
148 }
149
150 #[must_use]
152 pub fn diagnostics(&self) -> &[Diagnostic] {
153 &self.diagnostics
154 }
155
156 #[must_use]
158 pub fn list(&self) -> Vec<(String, String)> {
159 self.locales.values().map(|l| (l.code.clone(), l.name.clone())).collect()
160 }
161
162 #[must_use]
164 pub fn active(&self) -> &str {
165 &self.active
166 }
167
168 pub fn set_active(&mut self, code: &str) -> bool {
170 if self.locales.contains_key(code) {
171 code.clone_into(&mut self.active);
172 true
173 } else {
174 false
175 }
176 }
177
178 pub fn select(&mut self, tag: &str) -> bool {
187 let Some(parsed) = Tag::parse(tag) else {
188 return self.set_active(tag);
189 };
190 let Some(code) = self.matching(&parsed) else {
191 return false;
192 };
193 self.active = code;
194 if let Some(region) = parsed.region().and_then(week::region_code) {
195 self.region = Some(region);
196 }
197 true
198 }
199
200 #[must_use]
205 pub fn region(&self) -> Option<&str> {
206 self.region.as_deref()
207 }
208
209 pub fn set_region(&mut self, region: Option<&str>) -> bool {
213 match region {
214 None => {
215 self.region = None;
216 true
217 }
218 Some(text) => match week::region_code(text) {
219 Some(code) => {
220 self.region = Some(code);
221 true
222 }
223 None => false,
224 },
225 }
226 }
227
228 #[must_use]
236 pub fn first_weekday(&self) -> Weekday {
237 if let Some(region) = &self.region {
238 return week::first_day(region);
239 }
240 let own = self.locales.get(&self.active).and_then(|locale| match locale.messages.get(FIRST_WEEKDAY) {
241 Some(Message::Plain(template)) => render(template, &[]).trim().parse::<u8>().ok(),
242 _ => None,
243 });
244 own.and_then(Weekday::from_number).unwrap_or(Weekday::Monday)
245 }
246
247 #[must_use]
255 pub fn decimal_separator(&self) -> char {
256 self.find(DECIMAL).map(|_| self.translate(DECIMAL, &[])).and_then(|text| text.chars().next()).unwrap_or('.')
257 }
258
259 #[must_use]
261 pub fn translate(&self, key: &str, args: &[(&str, Arg)]) -> String {
262 let Some((language, message)) = self.find(key) else {
263 return format!("⟦{key}⟧");
264 };
265 let template = match message {
266 Message::Plain(template) => template,
267 Message::Plural(forms) => {
268 let count = args.iter().find_map(|(name, arg)| match (name, arg) {
269 (&"n", Arg::Int(n)) => Some(*n),
270 _ => None,
271 });
272 let category = count.map_or(PluralCategory::Other, |n| PluralCategory::of(language, n));
273 match forms.get(&category).or_else(|| forms.get(&PluralCategory::Other)) {
274 Some(template) => template,
275 None => return format!("⟦{key}⟧"),
276 }
277 }
278 };
279 render(template, args)
280 }
281
282 #[must_use]
294 pub fn has(&self, code: &str, key: &str) -> bool {
295 self.locales.get(code).is_some_and(|locale| locale.messages.contains_key(key))
296 }
297
298 pub(crate) fn in_every_locale(&self, key: &str) -> Vec<String> {
302 let active = self.locales.get(&self.active).into_iter();
303 let others = self.locales.values().filter(|locale| locale.code != self.active);
304 active
305 .chain(others)
306 .filter_map(|locale| match locale.messages.get(key) {
307 Some(Message::Plain(template)) => Some(render(template, &[])),
308 _ => None,
309 })
310 .collect()
311 }
312
313 #[must_use]
316 pub fn missing_keys(&self, code: &str, reference: &str) -> Vec<String> {
317 let (Some(target), Some(reference)) = (self.locales.get(code), self.locales.get(reference)) else {
318 return Vec::new();
319 };
320 reference.messages.keys().filter(|key| !target.messages.contains_key(*key)).cloned().collect()
321 }
322
323 #[must_use]
338 pub fn detect(&self, env: impl Fn(&str) -> Option<String>) -> Option<String> {
339 self.matching(&system_tag(&["LC_ALL", "LC_MESSAGES", "LANG"], env)?)
340 }
341
342 #[must_use]
347 pub fn detect_region(&self, env: impl Fn(&str) -> Option<String>) -> Option<String> {
348 system_tag(&["LC_ALL", "LC_TIME", "LANG"], env)?.region().and_then(week::region_code)
349 }
350
351 fn matching(&self, tag: &Tag) -> Option<String> {
353 let known = |wanted: &str| self.locales.keys().find(|code| code.eq_ignore_ascii_case(wanted)).cloned();
354 let only_one_of_the_language = || {
355 let mut same = self.locales.keys().filter(|code| tag::language_of(code) == tag.language);
356 let first = same.next()?;
357 same.next().is_none().then(|| first.clone())
358 };
359 known(&tag.full())
360 .or_else(|| tag.script().and_then(|script| known(&format!("{}-{script}", tag.language))))
361 .or_else(|| known(&tag.language))
362 .or_else(only_one_of_the_language)
363 }
364
365 fn find(&self, key: &str) -> Option<(&str, &Message)> {
366 let mut visited: Vec<&str> = Vec::new();
367 let mut code = Some(self.active.as_str());
368 while let Some(current) = code {
369 if visited.contains(¤t) {
370 break;
371 }
372 visited.push(current);
373 let Some(locale) = self.locales.get(current) else {
374 break;
375 };
376 if let Some(message) = locale.messages.get(key) {
377 return Some((locale.code.as_str(), message));
378 }
379 code = locale.fallback.as_deref();
380 }
381 if visited.contains(&ROOT_LOCALE) {
382 return None;
383 }
384 self.locales.get(ROOT_LOCALE).and_then(|root| root.messages.get(key).map(|m| (root.code.as_str(), m)))
385 }
386}
387
388const FIRST_WEEKDAY: &str = "quvyta.date.first-weekday";
390
391const DECIMAL: &str = "quvyta.number.decimal";
393
394fn system_tag(variables: &[&str], env: impl Fn(&str) -> Option<String>) -> Option<Tag> {
396 let from_env = variables.iter().filter_map(|name| env(name)).find(|value| !value.is_empty());
397 Tag::parse(&from_env.or_else(sys_locale::get_locale)?)
398}
399
400fn render(template: &Template, args: &[(&str, Arg)]) -> String {
401 let mut out = String::new();
402 for piece in &template.0 {
405 match piece {
406 Piece::Text(text) => out.push_str(text),
407 Piece::Arg(name) => match args.iter().find(|(arg_name, _)| arg_name == name) {
408 Some((_, Arg::Text(text))) => out.push_str(text),
409 Some((_, Arg::Int(n))) => {
410 let _ = write!(out, "{n}");
411 }
412 None => {
413 let _ = write!(out, "{{{name}}}");
414 }
415 },
416 }
417 }
418 out
419}
420
421thread_local! {
422 static ACTIVE: RefCell<Option<Arc<I18n>>> = const { RefCell::new(None) };
423}
424
425pub fn scope<R>(i18n: Arc<I18n>, f: impl FnOnce() -> R) -> R {
428 struct Restore(Option<Arc<I18n>>);
429 impl Drop for Restore {
430 fn drop(&mut self) {
431 let previous = self.0.take();
432 ACTIVE.with(|active| *active.borrow_mut() = previous);
433 }
434 }
435 let previous = ACTIVE.with(|active| active.borrow_mut().replace(i18n));
436 let _restore = Restore(previous);
437 f()
438}
439
440#[must_use]
443pub fn translate_active(key: &str, args: &[(&str, Arg)]) -> String {
444 ACTIVE.with(|active| match active.borrow().as_ref() {
445 Some(i18n) => i18n.translate(key, args),
446 None => format!("⟦{key}⟧"),
447 })
448}
449
450#[must_use]
457pub fn first_weekday() -> Weekday {
458 ACTIVE.with(|active| active.borrow().as_ref().map_or(Weekday::Monday, |i18n| i18n.first_weekday()))
459}
460
461#[must_use]
464pub fn decimal_separator() -> char {
465 ACTIVE.with(|active| active.borrow().as_ref().map_or('.', |i18n| i18n.decimal_separator()))
466}
467
468#[must_use]
480pub fn number(value: f64, decimals: usize) -> String {
481 localize(format!("{value:.decimals$}"))
482}
483
484pub(crate) fn localize(text: String) -> String {
487 let separator = decimal_separator();
488 if separator == '.' { text } else { text.replace('.', &separator.to_string()) }
489}
490
491pub(crate) fn translate_active_if_known(key: &str) -> Option<String> {
495 ACTIVE.with(|active| {
496 let active = active.borrow();
497 let i18n = active.as_ref()?;
498 i18n.find(key)?;
499 Some(i18n.translate(key, &[]))
500 })
501}
502
503#[macro_export]
519macro_rules! t {
520 ($key:expr $(,)?) => {
521 $crate::i18n::translate_active($key, &[])
522 };
523 ($key:expr, $($name:ident = $value:expr),+ $(,)?) => {
524 $crate::i18n::translate_active(
525 $key,
526 &[$((stringify!($name), $crate::i18n::Arg::from($value))),+],
527 )
528 };
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534 use std::collections::HashMap;
535
536 fn catalog() -> I18n {
537 let mut i18n = I18n::builtin();
538 assert!(i18n.add_source(
539 "app-en.toml",
540 "[meta]\nname = \"English\"\ncode = \"en\"\n[files]\ncount = { one = \"{n} file\", other = \"{n} files\" }\nhello = \"Hello {name}\"\nonly-en = \"English only\"\n",
541 ));
542 assert!(i18n.add_source(
543 "app-tr.toml",
544 "[meta]\nname = \"Türkçe\"\ncode = \"tr\"\nfallback = \"en\"\n[files]\ncount = { one = \"{n} dosya\", other = \"{n} dosya\" }\nhello = \"Merhaba {name}\"\n",
545 ));
546 i18n
547 }
548
549 fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
550 let map: HashMap<String, String> = pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
551 move |name| map.get(name).cloned()
552 }
553
554 #[test]
555 fn translates_with_args_plurals_and_fallback() {
556 let mut i18n = catalog();
557 assert_eq!(i18n.translate("files.count", &[("n", Arg::from(1))]), "1 file");
558 assert_eq!(i18n.translate("files.count", &[("n", Arg::from(3))]), "3 files");
559 assert!(i18n.set_active("tr"));
560 assert_eq!(i18n.translate("files.hello", &[("name", Arg::from("Ada"))]), "Merhaba Ada");
561 assert_eq!(i18n.translate("files.only-en", &[]), "English only");
562 assert_eq!(i18n.translate("files.nope", &[]), "⟦files.nope⟧");
563 assert_eq!(i18n.translate("files.hello", &[]), "Merhaba {name}");
564 assert!(!i18n.set_active("xx"));
565 assert_eq!(i18n.active(), "tr");
566 }
567
568 #[test]
569 fn later_files_extend_and_override_a_locale() {
570 let mut i18n = catalog();
571 assert!(i18n.add_source(
572 "more-en.toml",
573 "[meta]\nname = \"English (app)\"\ncode = \"en\"\n[files]\nhello = \"Hi {name}\"\n",
574 ));
575 assert_eq!(i18n.translate("files.hello", &[("name", Arg::from("Ada"))]), "Hi Ada");
576 assert_eq!(i18n.translate("files.only-en", &[]), "English only");
577 let names: Vec<(String, String)> =
578 i18n.list().into_iter().filter(|(code, _)| code == "en" || code == "tr").collect();
579 assert_eq!(names, vec![("en".to_owned(), "English (app)".to_owned()), ("tr".to_owned(), "Türkçe".to_owned())]);
580 }
581
582 #[test]
583 fn has_looks_at_the_named_language_only() {
584 let mut i18n = catalog();
585 assert!(i18n.has("en", "files.hello") && i18n.has("tr", "files.hello"));
586 assert!(i18n.has("en", "files.only-en"));
587 assert!(!i18n.has("tr", "files.only-en"), "borrowed from English, not Turkish's own");
588 assert!(i18n.set_active("tr"));
589 assert_eq!(i18n.translate("files.only-en", &[]), "English only", "yet the screen shows the fallback");
590 assert!(!i18n.has("tr", "files.only-en"), "the active language changes nothing");
591 assert!(i18n.has("en", "files.only-en"));
592 assert!(!i18n.has("en", "files.nope") && !i18n.has("tr", "files.nope"));
593 assert!(!i18n.has("xx", "files.hello"), "an unknown language has no keys");
594 }
595
596 #[test]
597 fn a_plural_key_counts_as_present() {
598 let i18n = catalog();
599 assert!(i18n.has("en", "files.count") && i18n.has("tr", "files.count"));
600 assert!(!i18n.has("en", "files.count.one"), "a form is not a key of its own");
601 }
602
603 #[test]
604 fn comparing_a_translation_with_its_key_misses_a_missing_key() {
605 let i18n = catalog();
606 let key = "files.nope";
607 assert_ne!(i18n.translate(key, &[]), key, "the indirect check passes");
608 assert!(!i18n.has("en", key), "has reports it missing");
609 }
610
611 #[test]
612 fn reports_missing_translations() {
613 assert_eq!(catalog().missing_keys("tr", "en"), vec!["files.only-en".to_owned()]);
614 }
615
616 #[test]
617 fn detects_language_from_environment() {
618 let i18n = catalog();
619 assert_eq!(i18n.detect(env(&[("LANG", "tr_TR.UTF-8")])), Some("tr".to_owned()));
620 assert_eq!(i18n.detect(env(&[("LC_ALL", "en_US.UTF-8"), ("LANG", "tr_TR.UTF-8")])), Some("en".to_owned()));
621 assert_eq!(i18n.detect(env(&[("LANG", "fi_FI.UTF-8")])), None);
622 assert_eq!(i18n.detect(env(&[("LANG", "C")])), None);
623 assert_eq!(i18n.detect(env(&[("LANG", "POSIX")])), None);
624 assert_eq!(i18n.detect(env(&[("LANG", "C.UTF-8")])), None);
625 }
626
627 fn regional(codes: &[&str]) -> I18n {
629 let mut i18n = catalog();
630 for code in codes {
631 let source = format!("[meta]\nname = \"{code}\"\ncode = \"{code}\"\n[files]\nhello = \"{code}\"\n");
632 assert!(i18n.add_source(&format!("{code}.toml"), &source));
633 }
634 i18n
635 }
636
637 fn detected(i18n: &I18n, lang: &str) -> Option<String> {
638 i18n.detect(env(&[("LANG", lang)]))
639 }
640
641 #[test]
642 fn a_region_or_script_code_matches_whole_whatever_its_separator_and_case() {
643 let i18n = regional(&["pt-BR", "pt-PT", "zh-Hans", "zh-Hant", "de"]);
644 assert_eq!(detected(&i18n, "pt_BR.UTF-8").as_deref(), Some("pt-BR"));
645 assert_eq!(detected(&i18n, "pt_PT.UTF-8").as_deref(), Some("pt-PT"));
646 assert_eq!(detected(&i18n, "PT-br").as_deref(), Some("pt-BR"));
647 assert_eq!(detected(&i18n, "zh-hant").as_deref(), Some("zh-Hant"));
648 assert_eq!(detected(&i18n, "tr_TR.UTF-8").as_deref(), Some("tr"));
649 }
650
651 #[test]
652 fn a_regional_locale_chooses_plural_forms_by_its_language() {
653 let mut i18n = catalog();
654 assert!(i18n.add_source(
655 "pt-BR.toml",
656 "[meta]\nname = \"Português\"\ncode = \"pt-BR\"\n[files]\ncount = { one = \"{n} etapa\", other = \"{n} etapas\" }\n",
657 ));
658 assert!(i18n.set_active("pt-BR"));
659 assert_eq!(i18n.translate("files.count", &[("n", Arg::from(0))]), "0 etapa");
660 assert_eq!(i18n.translate("files.count", &[("n", Arg::from(2))]), "2 etapas");
661 }
662
663 #[test]
664 fn a_chinese_region_picks_its_script() {
665 let i18n = regional(&["zh-Hans", "zh-Hant"]);
666 for lang in ["zh_CN.UTF-8", "zh_SG.UTF-8", "zh-Hans", "zh_Hans_CN"] {
667 assert_eq!(detected(&i18n, lang).as_deref(), Some("zh-Hans"), "{lang}");
668 }
669 for lang in ["zh_TW.UTF-8", "zh_HK.UTF-8", "zh_MO.UTF-8", "zh-Hant"] {
670 assert_eq!(detected(&i18n, lang).as_deref(), Some("zh-Hant"), "{lang}");
671 }
672 assert_eq!(detected(&i18n, "zh"), None, "bare Chinese names no script, and both are known");
673 }
674
675 #[test]
676 fn a_region_without_a_locale_of_its_own_uses_the_language() {
677 let i18n = regional(&["de", "pt-BR", "pt-PT"]);
678 assert_eq!(detected(&i18n, "de_AT.UTF-8").as_deref(), Some("de"));
679 assert_eq!(detected(&i18n, "de_CH.UTF-8@euro").as_deref(), Some("de"));
680 assert_eq!(detected(&i18n, "pt_AO.UTF-8"), None, "two Portuguese locales and no plain one");
681 }
682
683 #[test]
684 fn the_only_locale_of_a_language_serves_every_region_of_it() {
685 let i18n = regional(&["pt-BR", "zh-Hans"]);
686 assert_eq!(detected(&i18n, "pt_PT.UTF-8").as_deref(), Some("pt-BR"));
687 assert_eq!(detected(&i18n, "pt").as_deref(), Some("pt-BR"));
688 assert_eq!(detected(&i18n, "zh").as_deref(), Some("zh-Hans"));
689 assert_eq!(detected(&i18n, "zh_TW.UTF-8").as_deref(), Some("zh-Hans"));
690 assert_eq!(detected(&i18n, "C"), None);
691 }
692
693 const BUILT_IN: [&str; 9] = ["de", "en", "es", "fr", "ja", "pt-BR", "ru", "tr", "zh-Hans"];
695
696 #[test]
697 fn the_framework_speaks_nine_languages() {
698 let codes: Vec<String> = I18n::builtin().list().into_iter().map(|(code, _)| code).collect();
699 assert_eq!(codes, BUILT_IN);
700 }
701
702 #[test]
703 fn every_built_in_plural_gives_each_form_its_language_uses() {
704 let i18n = I18n::builtin();
705 for (code, locale) in &i18n.locales {
706 for (key, message) in &locale.messages {
707 let Message::Plural(forms) = message else { continue };
708 for n in 0..=200 {
709 let category = PluralCategory::of(code, n);
710 assert!(forms.contains_key(&category), "{code} {key} has no `{}` form for {n}", category.name());
711 }
712 }
713 }
714 }
715
716 #[test]
717 fn the_system_language_finds_the_built_in_regional_locales() {
718 let i18n = I18n::builtin();
719 for (lang, code) in [
720 ("pt_BR.UTF-8", "pt-BR"),
721 ("pt_PT.UTF-8", "pt-BR"),
722 ("zh_CN.UTF-8", "zh-Hans"),
723 ("zh_TW.UTF-8", "zh-Hans"),
724 ("ja_JP.UTF-8", "ja"),
725 ("de_AT.UTF-8", "de"),
726 ("es_MX.UTF-8", "es"),
727 ("fr_CA.UTF-8", "fr"),
728 ("ru_RU.UTF-8", "ru"),
729 ("tr_TR.UTF-8", "tr"),
730 ] {
731 assert_eq!(i18n.detect(env(&[("LANG", lang)])).as_deref(), Some(code), "{lang}");
732 }
733 }
734
735 #[test]
736 fn a_week_starts_where_the_language_starts_it() {
737 let mut i18n = I18n::builtin();
738 for (code, first) in [
739 ("en", "7"),
740 ("tr", "1"),
741 ("de", "1"),
742 ("es", "1"),
743 ("fr", "1"),
744 ("pt-BR", "7"),
745 ("ru", "1"),
746 ("zh-Hans", "1"),
747 ("ja", "7"),
748 ] {
749 assert!(i18n.set_active(code));
750 assert_eq!(i18n.translate("quvyta.date.first-weekday", &[]), first, "{code}");
751 }
752 }
753
754 #[test]
755 fn without_a_region_the_language_gives_the_first_weekday() {
756 let mut i18n = I18n::builtin();
757 for (code, first) in [
758 ("en", Weekday::Sunday),
759 ("tr", Weekday::Monday),
760 ("de", Weekday::Monday),
761 ("pt-BR", Weekday::Sunday),
762 ("ja", Weekday::Sunday),
763 ("zh-Hans", Weekday::Monday),
764 ] {
765 assert!(i18n.set_active(code));
766 assert_eq!(i18n.first_weekday(), first, "{code}");
767 }
768 }
769
770 #[test]
771 fn a_detected_region_gives_the_first_weekday_over_the_language() {
772 let mut i18n = I18n::builtin();
773 for (lang, first) in [
774 ("en_GB.UTF-8", Weekday::Monday),
775 ("en_US.UTF-8", Weekday::Sunday),
776 ("pt_BR.UTF-8", Weekday::Sunday),
777 ("pt_PT.UTF-8", Weekday::Sunday),
778 ("ar_EG.UTF-8", Weekday::Saturday),
779 ("en_AU.UTF-8", Weekday::Monday),
780 ] {
781 let pairs = [("LANG", lang)];
782 let lookup = env(&pairs);
783 let code = i18n.detect(&lookup).unwrap_or_else(|| ROOT_LOCALE.to_owned());
784 assert!(i18n.set_active(&code));
785 let region = i18n.detect_region(&lookup);
786 assert!(i18n.set_region(region.as_deref()));
787 assert_eq!(i18n.first_weekday(), first, "{lang}");
788 }
789 }
790
791 #[test]
792 fn the_region_follows_the_calendar_variables() {
793 let i18n = I18n::builtin();
794 let region = |pairs: &[(&str, &str)]| i18n.detect_region(env(pairs));
795 assert_eq!(region(&[("LANG", "en_GB.UTF-8")]).as_deref(), Some("GB"));
796 assert_eq!(region(&[("LC_TIME", "en_GB.UTF-8"), ("LANG", "en_US.UTF-8")]).as_deref(), Some("GB"));
797 assert_eq!(region(&[("LC_MESSAGES", "en_GB.UTF-8"), ("LANG", "en_US.UTF-8")]).as_deref(), Some("US"));
798 assert_eq!(region(&[("LC_ALL", "de_AT.UTF-8"), ("LC_TIME", "en_GB.UTF-8")]).as_deref(), Some("AT"));
799 assert_eq!(region(&[("LANG", "es_419.UTF-8")]).as_deref(), Some("419"));
800 assert_eq!(region(&[("LANG", "en")]), None);
801 assert_eq!(region(&[("LANG", "C.UTF-8")]), None);
802 }
803
804 #[test]
805 fn without_a_region_an_unknown_language_starts_on_monday() {
806 let mut i18n = I18n::builtin();
807 assert!(
808 i18n.add_source(
809 "fi.toml",
810 "[meta]\nname = \"Suomi\"\ncode = \"fi\"\nfallback = \"en\"\n[app]\nx = \"x\"\n"
811 )
812 );
813 assert!(i18n.set_active("fi"));
814 assert_eq!(i18n.region(), None);
815 assert_eq!(i18n.first_weekday(), Weekday::Monday, "English's Sunday is not borrowed");
816 }
817
818 #[test]
819 fn a_region_set_by_the_application_decides_until_cleared() {
820 let mut i18n = I18n::builtin();
821 assert!(i18n.set_region(Some("gb")));
822 assert_eq!(i18n.region(), Some("GB"));
823 assert_eq!(i18n.first_weekday(), Weekday::Monday);
824 assert!(!i18n.set_region(Some("Britain")));
825 assert_eq!(i18n.region(), Some("GB"), "a bad code changes nothing");
826 assert!(i18n.set_region(None));
827 assert_eq!(i18n.first_weekday(), Weekday::Sunday, "English again");
828 }
829
830 #[test]
831 fn selecting_a_regional_tag_activates_its_language_and_region() {
832 let mut i18n = I18n::builtin();
833 assert!(i18n.select("en-GB"));
834 assert_eq!((i18n.active(), i18n.region()), ("en", Some("GB")));
835 assert_eq!(i18n.first_weekday(), Weekday::Monday);
836 assert!(i18n.select("tr"));
837 assert_eq!((i18n.active(), i18n.region()), ("tr", Some("GB")), "a tag without a region keeps it");
838 assert!(i18n.select("pt_BR.UTF-8"));
839 assert_eq!((i18n.active(), i18n.region()), ("pt-BR", Some("BR")));
840 assert!(!i18n.select("fi-FI"));
841 assert_eq!((i18n.active(), i18n.region()), ("pt-BR", Some("BR")), "no Finnish, nothing changes");
842 assert!(!i18n.select(""));
843 }
844
845 #[test]
846 fn the_first_weekday_of_the_active_translator_is_read_without_the_view() {
847 assert_eq!(first_weekday(), Weekday::Monday, "outside a scope");
848 let mut american = I18n::builtin();
849 assert!(american.set_region(Some("US")));
850 assert_eq!(scope(Arc::new(american), first_weekday), Weekday::Sunday);
851 let mut british = I18n::builtin();
852 assert!(british.set_region(Some("GB")));
853 assert_eq!(scope(Arc::new(british), first_weekday), Weekday::Monday);
854 assert_eq!(first_weekday(), Weekday::Monday, "the scope is gone again");
855 }
856
857 #[test]
858 fn macro_uses_scoped_translator() {
859 let mut i18n = catalog();
860 i18n.set_active("tr");
861 assert_eq!(t!("files.count", n = 2), "⟦files.count⟧");
862 let text = scope(Arc::new(i18n), || t!("files.count", n = 2));
863 assert_eq!(text, "2 dosya");
864 assert_eq!(t!("files.count", n = 2), "⟦files.count⟧");
865 }
866}