Skip to main content

qframe/i18n/
mod.rs

1//! Localisation: locale files, plural forms, system language detection and [`t!`](crate::t!).
2//!
3//! ```toml
4//! [meta]
5//! name = "Türkçe"
6//! code = "tr"
7//! fallback = "en"
8//!
9//! [files]
10//! count = { one = "{n} dosya", other = "{n} dosya" }
11//! ```
12//!
13//! Lookups try the active locale, then its `fallback` chain, then English. A key found
14//! nowhere is shown as `⟦key⟧` so a missing translation is visible on screen.
15//! [`I18n::has`] asks whether one language carries a key itself, without the fallbacks, so a
16//! test can keep every language complete.
17
18mod 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
38/// The final fallback locale.
39const ROOT_LOCALE: &str = "en";
40
41/// A value substituted into a `{placeholder}`.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Arg {
44    /// Text.
45    Text(String),
46    /// A count; the argument named `n` also selects the plural form.
47    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/// All locales known to an application and the active one.
93#[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    /// The built-in locales with English active.
103    #[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    /// Adds a locale from TOML text. A locale with an existing code is merged into it, the
114    /// new messages winning, so applications can extend and override the built-in text.
115    /// Returns whether the file was usable.
116    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    /// Loads every `*.toml` file in `dir`.
136    ///
137    /// # Errors
138    ///
139    /// Returns the I/O error when the directory cannot be read. A file that cannot be read is
140    /// skipped and reported in the diagnostics.
141    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    /// Problems found while loading.
151    #[must_use]
152    pub fn diagnostics(&self) -> &[Diagnostic] {
153        &self.diagnostics
154    }
155
156    /// `(code, display name)` of every locale, sorted by code; for a settings screen.
157    #[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    /// The active locale code.
163    #[must_use]
164    pub fn active(&self) -> &str {
165        &self.active
166    }
167
168    /// Activates `code`. Returns `false` and changes nothing when the locale is unknown.
169    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    /// Activates the locale that serves the language tag `tag`, such as a language setting of
179    /// `en-GB` or `pt_BR.UTF-8`, matched the way [`detect`](Self::detect) matches the system's
180    /// language: `en-GB` activates `en` when there is no `en-GB` locale.
181    ///
182    /// A tag that names a region also sets the [region](Self::region), so `en-GB` starts weeks on
183    /// Monday although English alone starts them on Sunday. A tag without one keeps the region, so
184    /// choosing `tr` from a list of languages does not forget the country the system is set to.
185    /// Returns `false` and changes nothing when no locale serves the tag.
186    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    /// The region whose conventions apply, such as `GB`, uppercase: the one set with
201    /// [`set_region`](Self::set_region) or [`select`](Self::select), or found by
202    /// [`detect_region`](Self::detect_region) when the environment was loaded. `None` leaves the
203    /// conventions to the language.
204    #[must_use]
205    pub fn region(&self) -> Option<&str> {
206        self.region.as_deref()
207    }
208
209    /// Sets the region, two letters such as `GB` or three digits such as `419`, in either case;
210    /// `None` leaves the conventions to the language again. Returns `false` and changes nothing
211    /// when `region` is not a region code.
212    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    /// The day a calendar week starts on.
229    ///
230    /// With a [region](Self::region) it is the region's, from the Unicode CLDR: Sunday in the
231    /// United States, Canada, Brazil, Portugal and Japan, Saturday in much of the Middle East,
232    /// Monday in the United Kingdom and most of the world. Without one it is the active
233    /// language's own `quvyta.date.first-weekday` key (`1` Monday to `7` Sunday), and Monday, the
234    /// ISO 8601 week, for a language that does not give it.
235    #[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    /// Translates `key` with `args`.
248    #[must_use]
249    pub fn translate(&self, key: &str, args: &[(&str, Arg)]) -> String {
250        let Some((language, message)) = self.find(key) else {
251            return format!("⟦{key}⟧");
252        };
253        let template = match message {
254            Message::Plain(template) => template,
255            Message::Plural(forms) => {
256                let count = args.iter().find_map(|(name, arg)| match (name, arg) {
257                    (&"n", Arg::Int(n)) => Some(*n),
258                    _ => None,
259                });
260                let category = count.map_or(PluralCategory::Other, |n| PluralCategory::of(language, n));
261                match forms.get(&category).or_else(|| forms.get(&PluralCategory::Other)) {
262                    Some(template) => template,
263                    None => return format!("⟦{key}⟧"),
264                }
265            }
266        };
267        render(template, args)
268    }
269
270    /// Whether the locale `code` itself defines `key`, as a plain message or as a plural table
271    /// (a plural key counts once, whatever forms it has).
272    ///
273    /// The language is always the one named, never the active one, so the answer does not change
274    /// with [`set_active`](Self::set_active). Only that locale's own text counts: a key it would
275    /// borrow from its `fallback` or from English is not its own, so `has` answers `false` for it
276    /// even though [`translate`](Self::translate) shows the borrowed text on screen. That lets a
277    /// test require every language to carry its own translation. An unknown `code` has no keys.
278    ///
279    /// Comparing `translate(key, &[])` with `key` cannot stand in for this: a key found nowhere
280    /// translates to `⟦key⟧`, which differs from the key.
281    #[must_use]
282    pub fn has(&self, code: &str, key: &str) -> bool {
283        self.locales.get(code).is_some_and(|locale| locale.messages.contains_key(key))
284    }
285
286    /// The plain text of `key` in every locale that defines it itself, the active locale first and
287    /// the others in code order. Lets input be read in any known language, such as the unit words
288    /// of a length of time typed by someone whose interface is in another language.
289    pub(crate) fn in_every_locale(&self, key: &str) -> Vec<String> {
290        let active = self.locales.get(&self.active).into_iter();
291        let others = self.locales.values().filter(|locale| locale.code != self.active);
292        active
293            .chain(others)
294            .filter_map(|locale| match locale.messages.get(key) {
295                Some(Message::Plain(template)) => Some(render(template, &[])),
296                _ => None,
297            })
298            .collect()
299    }
300
301    /// Keys present in `reference` but missing from `code`, sorted. Use in tests to keep
302    /// every translation complete.
303    #[must_use]
304    pub fn missing_keys(&self, code: &str, reference: &str) -> Vec<String> {
305        let (Some(target), Some(reference)) = (self.locales.get(code), self.locales.get(reference)) else {
306            return Vec::new();
307        };
308        reference.messages.keys().filter(|key| !target.messages.contains_key(*key)).cloned().collect()
309    }
310
311    /// The locale code to use for a system: the first of `LC_ALL`, `LC_MESSAGES`, `LANG`,
312    /// then the operating system setting, matched to a known locale code.
313    ///
314    /// Separators and case do not matter (`pt_BR.UTF-8` finds `pt-BR`), and the encoding and
315    /// modifier are ignored. The first of these that names a known locale wins:
316    ///
317    /// 1. the whole tag: `pt_BR` → `pt-BR`, `zh_Hant` → `zh-Hant`;
318    /// 2. the language with its writing system, which for Chinese follows the region: `zh_CN`
319    ///    and `zh_SG` → `zh-Hans`; `zh_TW`, `zh_HK` and `zh_MO` → `zh-Hant`;
320    /// 3. the language alone: `de_AT` → `de`;
321    /// 4. the one locale of that language, when there is exactly one: `pt_PT` → `pt-BR` when
322    ///    `pt-BR` is the only Portuguese, `zh` → `zh-Hans` when it is the only Chinese.
323    ///
324    /// `C` and `POSIX` name no language and give `None`, as does a language with no locale.
325    #[must_use]
326    pub fn detect(&self, env: impl Fn(&str) -> Option<String>) -> Option<String> {
327        self.matching(&system_tag(&["LC_ALL", "LC_MESSAGES", "LANG"], env)?)
328    }
329
330    /// The region the system is set to, uppercase: `GB` for `LANG=en_GB.UTF-8`. Reads the first of
331    /// `LC_ALL`, `LC_TIME`, `LANG`, then the operating system setting, since the calendar
332    /// conventions belong to `LC_TIME` where the language belongs to `LC_MESSAGES`. `None` when
333    /// that name gives no region, as `en` and `C.UTF-8` do.
334    #[must_use]
335    pub fn detect_region(&self, env: impl Fn(&str) -> Option<String>) -> Option<String> {
336        system_tag(&["LC_ALL", "LC_TIME", "LANG"], env)?.region().and_then(week::region_code)
337    }
338
339    /// The known locale code that serves `tag`; see [`I18n::detect`] for the order.
340    fn matching(&self, tag: &Tag) -> Option<String> {
341        let known = |wanted: &str| self.locales.keys().find(|code| code.eq_ignore_ascii_case(wanted)).cloned();
342        let only_one_of_the_language = || {
343            let mut same = self.locales.keys().filter(|code| tag::language_of(code) == tag.language);
344            let first = same.next()?;
345            same.next().is_none().then(|| first.clone())
346        };
347        known(&tag.full())
348            .or_else(|| tag.script().and_then(|script| known(&format!("{}-{script}", tag.language))))
349            .or_else(|| known(&tag.language))
350            .or_else(only_one_of_the_language)
351    }
352
353    fn find(&self, key: &str) -> Option<(&str, &Message)> {
354        let mut visited: Vec<&str> = Vec::new();
355        let mut code = Some(self.active.as_str());
356        while let Some(current) = code {
357            if visited.contains(&current) {
358                break;
359            }
360            visited.push(current);
361            let Some(locale) = self.locales.get(current) else {
362                break;
363            };
364            if let Some(message) = locale.messages.get(key) {
365                return Some((locale.code.as_str(), message));
366            }
367            code = locale.fallback.as_deref();
368        }
369        if visited.contains(&ROOT_LOCALE) {
370            return None;
371        }
372        self.locales.get(ROOT_LOCALE).and_then(|root| root.messages.get(key).map(|m| (root.code.as_str(), m)))
373    }
374}
375
376/// The locale key giving a language's first day of the week, for a language without a region.
377const FIRST_WEEKDAY: &str = "quvyta.date.first-weekday";
378
379/// The locale name in the first of `variables` that is set, or else the operating system's.
380fn system_tag(variables: &[&str], env: impl Fn(&str) -> Option<String>) -> Option<Tag> {
381    let from_env = variables.iter().filter_map(|name| env(name)).find(|value| !value.is_empty());
382    Tag::parse(&from_env.or_else(sys_locale::get_locale)?)
383}
384
385fn render(template: &Template, args: &[(&str, Arg)]) -> String {
386    let mut out = String::new();
387    for piece in &template.0 {
388        match piece {
389            Piece::Text(text) => out.push_str(text),
390            Piece::Arg(name) => match args.iter().find(|(arg_name, _)| arg_name == name) {
391                Some((_, Arg::Text(text))) => out.push_str(text),
392                Some((_, Arg::Int(n))) => {
393                    let _ = write!(out, "{n}");
394                }
395                None => {
396                    let _ = write!(out, "{{{name}}}");
397                }
398            },
399        }
400    }
401    out
402}
403
404thread_local! {
405    static ACTIVE: RefCell<Option<Arc<I18n>>> = const { RefCell::new(None) };
406}
407
408/// Runs `f` with `i18n` as the translator used by [`t!`](crate::t!) on this thread, restoring the
409/// previous translator afterwards, even if `f` panics.
410pub fn scope<R>(i18n: Arc<I18n>, f: impl FnOnce() -> R) -> R {
411    struct Restore(Option<Arc<I18n>>);
412    impl Drop for Restore {
413        fn drop(&mut self) {
414            let previous = self.0.take();
415            ACTIVE.with(|active| *active.borrow_mut() = previous);
416        }
417    }
418    let previous = ACTIVE.with(|active| active.borrow_mut().replace(i18n));
419    let _restore = Restore(previous);
420    f()
421}
422
423/// Translates with the translator installed by [`scope`]. Outside a scope every key is
424/// shown as `⟦key⟧`. Prefer the [`t!`](crate::t!) macro.
425#[must_use]
426pub fn translate_active(key: &str, args: &[(&str, Arg)]) -> String {
427    ACTIVE.with(|active| match active.borrow().as_ref() {
428        Some(i18n) => i18n.translate(key, args),
429        None => format!("⟦{key}⟧"),
430    })
431}
432
433/// The first day of the week of the translator installed by [`scope`], as
434/// [`I18n::first_weekday`] gives it: from the region when one is known, from the language
435/// otherwise. Outside a scope it is Monday.
436///
437/// The runtime installs the translator around `init`, `update` and the other [`App`](crate::runtime::App)
438/// methods, so week arithmetic in `update` agrees with the calendars the view draws.
439#[must_use]
440pub fn first_weekday() -> Weekday {
441    ACTIVE.with(|active| active.borrow().as_ref().map_or(Weekday::Monday, |i18n| i18n.first_weekday()))
442}
443
444/// Translates `key` without arguments with the translator installed by [`scope`], or `None` when
445/// neither the active locale, its fallbacks nor English define it: for keys only some
446/// languages need.
447pub(crate) fn translate_active_if_known(key: &str) -> Option<String> {
448    ACTIVE.with(|active| {
449        let active = active.borrow();
450        let i18n = active.as_ref()?;
451        i18n.find(key)?;
452        Some(i18n.translate(key, &[]))
453    })
454}
455
456/// Translates a key with the active translator.
457///
458/// ```
459/// use std::sync::Arc;
460/// use qframe::{i18n, t};
461///
462/// let mut catalog = i18n::I18n::builtin();
463/// catalog.add_source(
464///     "app-tr.toml",
465///     "[meta]\nname = \"Türkçe\"\ncode = \"tr\"\n[files]\ncount = { one = \"{n} dosya\", other = \"{n} dosya\" }\n",
466/// );
467/// catalog.set_active("tr");
468/// let label = i18n::scope(Arc::new(catalog), || t!("files.count", n = 3));
469/// assert_eq!(label, "3 dosya");
470/// ```
471#[macro_export]
472macro_rules! t {
473    ($key:expr $(,)?) => {
474        $crate::i18n::translate_active($key, &[])
475    };
476    ($key:expr, $($name:ident = $value:expr),+ $(,)?) => {
477        $crate::i18n::translate_active(
478            $key,
479            &[$((stringify!($name), $crate::i18n::Arg::from($value))),+],
480        )
481    };
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487    use std::collections::HashMap;
488
489    fn catalog() -> I18n {
490        let mut i18n = I18n::builtin();
491        assert!(i18n.add_source(
492            "app-en.toml",
493            "[meta]\nname = \"English\"\ncode = \"en\"\n[files]\ncount = { one = \"{n} file\", other = \"{n} files\" }\nhello = \"Hello {name}\"\nonly-en = \"English only\"\n",
494        ));
495        assert!(i18n.add_source(
496            "app-tr.toml",
497            "[meta]\nname = \"Türkçe\"\ncode = \"tr\"\nfallback = \"en\"\n[files]\ncount = { one = \"{n} dosya\", other = \"{n} dosya\" }\nhello = \"Merhaba {name}\"\n",
498        ));
499        i18n
500    }
501
502    fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
503        let map: HashMap<String, String> = pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
504        move |name| map.get(name).cloned()
505    }
506
507    #[test]
508    fn translates_with_args_plurals_and_fallback() {
509        let mut i18n = catalog();
510        assert_eq!(i18n.translate("files.count", &[("n", Arg::from(1))]), "1 file");
511        assert_eq!(i18n.translate("files.count", &[("n", Arg::from(3))]), "3 files");
512        assert!(i18n.set_active("tr"));
513        assert_eq!(i18n.translate("files.hello", &[("name", Arg::from("Ada"))]), "Merhaba Ada");
514        assert_eq!(i18n.translate("files.only-en", &[]), "English only");
515        assert_eq!(i18n.translate("files.nope", &[]), "⟦files.nope⟧");
516        assert_eq!(i18n.translate("files.hello", &[]), "Merhaba {name}");
517        assert!(!i18n.set_active("xx"));
518        assert_eq!(i18n.active(), "tr");
519    }
520
521    #[test]
522    fn later_files_extend_and_override_a_locale() {
523        let mut i18n = catalog();
524        assert!(i18n.add_source(
525            "more-en.toml",
526            "[meta]\nname = \"English (app)\"\ncode = \"en\"\n[files]\nhello = \"Hi {name}\"\n",
527        ));
528        assert_eq!(i18n.translate("files.hello", &[("name", Arg::from("Ada"))]), "Hi Ada");
529        assert_eq!(i18n.translate("files.only-en", &[]), "English only");
530        let names: Vec<(String, String)> =
531            i18n.list().into_iter().filter(|(code, _)| code == "en" || code == "tr").collect();
532        assert_eq!(names, vec![("en".to_owned(), "English (app)".to_owned()), ("tr".to_owned(), "Türkçe".to_owned())]);
533    }
534
535    #[test]
536    fn has_looks_at_the_named_language_only() {
537        let mut i18n = catalog();
538        assert!(i18n.has("en", "files.hello") && i18n.has("tr", "files.hello"));
539        assert!(i18n.has("en", "files.only-en"));
540        assert!(!i18n.has("tr", "files.only-en"), "borrowed from English, not Turkish's own");
541        assert!(i18n.set_active("tr"));
542        assert_eq!(i18n.translate("files.only-en", &[]), "English only", "yet the screen shows the fallback");
543        assert!(!i18n.has("tr", "files.only-en"), "the active language changes nothing");
544        assert!(i18n.has("en", "files.only-en"));
545        assert!(!i18n.has("en", "files.nope") && !i18n.has("tr", "files.nope"));
546        assert!(!i18n.has("xx", "files.hello"), "an unknown language has no keys");
547    }
548
549    #[test]
550    fn a_plural_key_counts_as_present() {
551        let i18n = catalog();
552        assert!(i18n.has("en", "files.count") && i18n.has("tr", "files.count"));
553        assert!(!i18n.has("en", "files.count.one"), "a form is not a key of its own");
554    }
555
556    #[test]
557    fn comparing_a_translation_with_its_key_misses_a_missing_key() {
558        let i18n = catalog();
559        let key = "files.nope";
560        assert_ne!(i18n.translate(key, &[]), key, "the indirect check passes");
561        assert!(!i18n.has("en", key), "has reports it missing");
562    }
563
564    #[test]
565    fn reports_missing_translations() {
566        assert_eq!(catalog().missing_keys("tr", "en"), vec!["files.only-en".to_owned()]);
567    }
568
569    #[test]
570    fn detects_language_from_environment() {
571        let i18n = catalog();
572        assert_eq!(i18n.detect(env(&[("LANG", "tr_TR.UTF-8")])), Some("tr".to_owned()));
573        assert_eq!(i18n.detect(env(&[("LC_ALL", "en_US.UTF-8"), ("LANG", "tr_TR.UTF-8")])), Some("en".to_owned()));
574        assert_eq!(i18n.detect(env(&[("LANG", "fi_FI.UTF-8")])), None);
575        assert_eq!(i18n.detect(env(&[("LANG", "C")])), None);
576        assert_eq!(i18n.detect(env(&[("LANG", "POSIX")])), None);
577        assert_eq!(i18n.detect(env(&[("LANG", "C.UTF-8")])), None);
578    }
579
580    /// A catalog with regional and script locales, as an application adding new languages has.
581    fn regional(codes: &[&str]) -> I18n {
582        let mut i18n = catalog();
583        for code in codes {
584            let source = format!("[meta]\nname = \"{code}\"\ncode = \"{code}\"\n[files]\nhello = \"{code}\"\n");
585            assert!(i18n.add_source(&format!("{code}.toml"), &source));
586        }
587        i18n
588    }
589
590    fn detected(i18n: &I18n, lang: &str) -> Option<String> {
591        i18n.detect(env(&[("LANG", lang)]))
592    }
593
594    #[test]
595    fn a_region_or_script_code_matches_whole_whatever_its_separator_and_case() {
596        let i18n = regional(&["pt-BR", "pt-PT", "zh-Hans", "zh-Hant", "de"]);
597        assert_eq!(detected(&i18n, "pt_BR.UTF-8").as_deref(), Some("pt-BR"));
598        assert_eq!(detected(&i18n, "pt_PT.UTF-8").as_deref(), Some("pt-PT"));
599        assert_eq!(detected(&i18n, "PT-br").as_deref(), Some("pt-BR"));
600        assert_eq!(detected(&i18n, "zh-hant").as_deref(), Some("zh-Hant"));
601        assert_eq!(detected(&i18n, "tr_TR.UTF-8").as_deref(), Some("tr"));
602    }
603
604    #[test]
605    fn a_regional_locale_chooses_plural_forms_by_its_language() {
606        let mut i18n = catalog();
607        assert!(i18n.add_source(
608            "pt-BR.toml",
609            "[meta]\nname = \"Português\"\ncode = \"pt-BR\"\n[files]\ncount = { one = \"{n} etapa\", other = \"{n} etapas\" }\n",
610        ));
611        assert!(i18n.set_active("pt-BR"));
612        assert_eq!(i18n.translate("files.count", &[("n", Arg::from(0))]), "0 etapa");
613        assert_eq!(i18n.translate("files.count", &[("n", Arg::from(2))]), "2 etapas");
614    }
615
616    #[test]
617    fn a_chinese_region_picks_its_script() {
618        let i18n = regional(&["zh-Hans", "zh-Hant"]);
619        for lang in ["zh_CN.UTF-8", "zh_SG.UTF-8", "zh-Hans", "zh_Hans_CN"] {
620            assert_eq!(detected(&i18n, lang).as_deref(), Some("zh-Hans"), "{lang}");
621        }
622        for lang in ["zh_TW.UTF-8", "zh_HK.UTF-8", "zh_MO.UTF-8", "zh-Hant"] {
623            assert_eq!(detected(&i18n, lang).as_deref(), Some("zh-Hant"), "{lang}");
624        }
625        assert_eq!(detected(&i18n, "zh"), None, "bare Chinese names no script, and both are known");
626    }
627
628    #[test]
629    fn a_region_without_a_locale_of_its_own_uses_the_language() {
630        let i18n = regional(&["de", "pt-BR", "pt-PT"]);
631        assert_eq!(detected(&i18n, "de_AT.UTF-8").as_deref(), Some("de"));
632        assert_eq!(detected(&i18n, "de_CH.UTF-8@euro").as_deref(), Some("de"));
633        assert_eq!(detected(&i18n, "pt_AO.UTF-8"), None, "two Portuguese locales and no plain one");
634    }
635
636    #[test]
637    fn the_only_locale_of_a_language_serves_every_region_of_it() {
638        let i18n = regional(&["pt-BR", "zh-Hans"]);
639        assert_eq!(detected(&i18n, "pt_PT.UTF-8").as_deref(), Some("pt-BR"));
640        assert_eq!(detected(&i18n, "pt").as_deref(), Some("pt-BR"));
641        assert_eq!(detected(&i18n, "zh").as_deref(), Some("zh-Hans"));
642        assert_eq!(detected(&i18n, "zh_TW.UTF-8").as_deref(), Some("zh-Hans"));
643        assert_eq!(detected(&i18n, "C"), None);
644    }
645
646    /// The languages the framework's own text comes in.
647    const BUILT_IN: [&str; 9] = ["de", "en", "es", "fr", "ja", "pt-BR", "ru", "tr", "zh-Hans"];
648
649    #[test]
650    fn the_framework_speaks_nine_languages() {
651        let codes: Vec<String> = I18n::builtin().list().into_iter().map(|(code, _)| code).collect();
652        assert_eq!(codes, BUILT_IN);
653    }
654
655    #[test]
656    fn every_built_in_plural_gives_each_form_its_language_uses() {
657        let i18n = I18n::builtin();
658        for (code, locale) in &i18n.locales {
659            for (key, message) in &locale.messages {
660                let Message::Plural(forms) = message else { continue };
661                for n in 0..=200 {
662                    let category = PluralCategory::of(code, n);
663                    assert!(forms.contains_key(&category), "{code} {key} has no `{}` form for {n}", category.name());
664                }
665            }
666        }
667    }
668
669    #[test]
670    fn the_system_language_finds_the_built_in_regional_locales() {
671        let i18n = I18n::builtin();
672        for (lang, code) in [
673            ("pt_BR.UTF-8", "pt-BR"),
674            ("pt_PT.UTF-8", "pt-BR"),
675            ("zh_CN.UTF-8", "zh-Hans"),
676            ("zh_TW.UTF-8", "zh-Hans"),
677            ("ja_JP.UTF-8", "ja"),
678            ("de_AT.UTF-8", "de"),
679            ("es_MX.UTF-8", "es"),
680            ("fr_CA.UTF-8", "fr"),
681            ("ru_RU.UTF-8", "ru"),
682            ("tr_TR.UTF-8", "tr"),
683        ] {
684            assert_eq!(i18n.detect(env(&[("LANG", lang)])).as_deref(), Some(code), "{lang}");
685        }
686    }
687
688    #[test]
689    fn a_week_starts_where_the_language_starts_it() {
690        let mut i18n = I18n::builtin();
691        for (code, first) in [
692            ("en", "7"),
693            ("tr", "1"),
694            ("de", "1"),
695            ("es", "1"),
696            ("fr", "1"),
697            ("pt-BR", "7"),
698            ("ru", "1"),
699            ("zh-Hans", "1"),
700            ("ja", "7"),
701        ] {
702            assert!(i18n.set_active(code));
703            assert_eq!(i18n.translate("quvyta.date.first-weekday", &[]), first, "{code}");
704        }
705    }
706
707    #[test]
708    fn without_a_region_the_language_gives_the_first_weekday() {
709        let mut i18n = I18n::builtin();
710        for (code, first) in [
711            ("en", Weekday::Sunday),
712            ("tr", Weekday::Monday),
713            ("de", Weekday::Monday),
714            ("pt-BR", Weekday::Sunday),
715            ("ja", Weekday::Sunday),
716            ("zh-Hans", Weekday::Monday),
717        ] {
718            assert!(i18n.set_active(code));
719            assert_eq!(i18n.first_weekday(), first, "{code}");
720        }
721    }
722
723    #[test]
724    fn a_detected_region_gives_the_first_weekday_over_the_language() {
725        let mut i18n = I18n::builtin();
726        for (lang, first) in [
727            ("en_GB.UTF-8", Weekday::Monday),
728            ("en_US.UTF-8", Weekday::Sunday),
729            ("pt_BR.UTF-8", Weekday::Sunday),
730            ("pt_PT.UTF-8", Weekday::Sunday),
731            ("ar_EG.UTF-8", Weekday::Saturday),
732            ("en_AU.UTF-8", Weekday::Monday),
733        ] {
734            let pairs = [("LANG", lang)];
735            let lookup = env(&pairs);
736            let code = i18n.detect(&lookup).unwrap_or_else(|| ROOT_LOCALE.to_owned());
737            assert!(i18n.set_active(&code));
738            let region = i18n.detect_region(&lookup);
739            assert!(i18n.set_region(region.as_deref()));
740            assert_eq!(i18n.first_weekday(), first, "{lang}");
741        }
742    }
743
744    #[test]
745    fn the_region_follows_the_calendar_variables() {
746        let i18n = I18n::builtin();
747        let region = |pairs: &[(&str, &str)]| i18n.detect_region(env(pairs));
748        assert_eq!(region(&[("LANG", "en_GB.UTF-8")]).as_deref(), Some("GB"));
749        assert_eq!(region(&[("LC_TIME", "en_GB.UTF-8"), ("LANG", "en_US.UTF-8")]).as_deref(), Some("GB"));
750        assert_eq!(region(&[("LC_MESSAGES", "en_GB.UTF-8"), ("LANG", "en_US.UTF-8")]).as_deref(), Some("US"));
751        assert_eq!(region(&[("LC_ALL", "de_AT.UTF-8"), ("LC_TIME", "en_GB.UTF-8")]).as_deref(), Some("AT"));
752        assert_eq!(region(&[("LANG", "es_419.UTF-8")]).as_deref(), Some("419"));
753        assert_eq!(region(&[("LANG", "en")]), None);
754        assert_eq!(region(&[("LANG", "C.UTF-8")]), None);
755    }
756
757    #[test]
758    fn without_a_region_an_unknown_language_starts_on_monday() {
759        let mut i18n = I18n::builtin();
760        assert!(
761            i18n.add_source(
762                "fi.toml",
763                "[meta]\nname = \"Suomi\"\ncode = \"fi\"\nfallback = \"en\"\n[app]\nx = \"x\"\n"
764            )
765        );
766        assert!(i18n.set_active("fi"));
767        assert_eq!(i18n.region(), None);
768        assert_eq!(i18n.first_weekday(), Weekday::Monday, "English's Sunday is not borrowed");
769    }
770
771    #[test]
772    fn a_region_set_by_the_application_decides_until_cleared() {
773        let mut i18n = I18n::builtin();
774        assert!(i18n.set_region(Some("gb")));
775        assert_eq!(i18n.region(), Some("GB"));
776        assert_eq!(i18n.first_weekday(), Weekday::Monday);
777        assert!(!i18n.set_region(Some("Britain")));
778        assert_eq!(i18n.region(), Some("GB"), "a bad code changes nothing");
779        assert!(i18n.set_region(None));
780        assert_eq!(i18n.first_weekday(), Weekday::Sunday, "English again");
781    }
782
783    #[test]
784    fn selecting_a_regional_tag_activates_its_language_and_region() {
785        let mut i18n = I18n::builtin();
786        assert!(i18n.select("en-GB"));
787        assert_eq!((i18n.active(), i18n.region()), ("en", Some("GB")));
788        assert_eq!(i18n.first_weekday(), Weekday::Monday);
789        assert!(i18n.select("tr"));
790        assert_eq!((i18n.active(), i18n.region()), ("tr", Some("GB")), "a tag without a region keeps it");
791        assert!(i18n.select("pt_BR.UTF-8"));
792        assert_eq!((i18n.active(), i18n.region()), ("pt-BR", Some("BR")));
793        assert!(!i18n.select("fi-FI"));
794        assert_eq!((i18n.active(), i18n.region()), ("pt-BR", Some("BR")), "no Finnish, nothing changes");
795        assert!(!i18n.select(""));
796    }
797
798    #[test]
799    fn the_first_weekday_of_the_active_translator_is_read_without_the_view() {
800        assert_eq!(first_weekday(), Weekday::Monday, "outside a scope");
801        let mut american = I18n::builtin();
802        assert!(american.set_region(Some("US")));
803        assert_eq!(scope(Arc::new(american), first_weekday), Weekday::Sunday);
804        let mut british = I18n::builtin();
805        assert!(british.set_region(Some("GB")));
806        assert_eq!(scope(Arc::new(british), first_weekday), Weekday::Monday);
807        assert_eq!(first_weekday(), Weekday::Monday, "the scope is gone again");
808    }
809
810    #[test]
811    fn macro_uses_scoped_translator() {
812        let mut i18n = catalog();
813        i18n.set_active("tr");
814        assert_eq!(t!("files.count", n = 2), "⟦files.count⟧");
815        let text = scope(Arc::new(i18n), || t!("files.count", n = 2));
816        assert_eq!(text, "2 dosya");
817        assert_eq!(t!("files.count", n = 2), "⟦files.count⟧");
818    }
819}