Skip to main content

eov_plugin_api/
i18n.rs

1//! Localisation of eov and its plugins.
2//!
3//! eov's interface is available in the [`LANGUAGES`] listed here. Every text
4//! is written in English, the source language, and translated through
5//! gettext catalogs (`.po` files) that sit beside the code that uses them:
6//!
7//! ```text
8//! translations/
9//! ├── <domain>.pot                      the template: every text, untranslated
10//! ├── de/LC_MESSAGES/<domain>.po        German
11//! ├── pt-BR/LC_MESSAGES/<domain>.po     Portuguese (Brazil)
12//! └── zh-Hant/LC_MESSAGES/<domain>.po   Chinese (Traditional)
13//! ```
14//!
15//! Folders are named by the language's BCP 47 tag ([`Language::tag`]); the
16//! spellings other gettext tools use (`pt_BR`, `zh_TW`, `nb_NO`) are found
17//! too ([`Language::catalog_folders`]). A text that a
18//! catalog lacks, or that is marked fuzzy, is shown in English: a missing
19//! translation never shows as an empty or raw text.
20//!
21//! # Texts in `.slint` files
22//!
23//! Mark them with Slint's `@tr("…")`. eov compiles a plugin's surfaces with
24//! the plugin's catalogs (see the manifest's `[i18n]` table), so they follow
25//! the language of the interface and change with it.
26//!
27//! # Texts made in Rust
28//!
29//! Use [`tr!`](crate::tr!) for every text a user reads: notifications,
30//! status texts, menu items, tooltips, errors. It has the syntax of the
31//! [`tr`](https://docs.rs/tr) crate's macro, so its `xtr` tool extracts the
32//! texts, and the placeholders of `@tr` (`{}`, `{0}`, `{name}`, `{n}` for
33//! the count of a plural text; `{{` and `}}` for braces):
34//!
35//! ```
36//! use eov_plugin_api::i18n::tr;
37//! let file = "case-12.svs";
38//! let count = 3;
39//! assert_eq!(tr!("Opened {}", file), "Opened case-12.svs");
40//! let _ = tr!("Toolbar" => "Open"); // with a context
41//! assert_eq!(tr!("One region" | "{n} regions" % count), "3 regions");
42//! let _ = tr!("Saved {count} regions to {file}", count = count, file = file);
43//! // Translators: a comment for translators, extracted with the text.
44//! let _ = tr!("Measure");
45//! ```
46//!
47//! eov loads a plugin's catalog for the language of the interface before
48//! it calls [`Plugin::create`](crate::sdk::Plugin::create), and again before
49//! it delivers [`HostEvent::LanguageChanged`](crate::protocol::HostEvent),
50//! so `tr!` always answers in the current language. Texts a plugin handed
51//! to eov earlier (toolbar tooltips, tool names) keep their language until
52//! the plugin hands them over again: do that when the language changes.
53//!
54//! Do not translate what is read by programs or other people's tools: file
55//! formats, JSON, CSV, log messages, identifiers, or data such as file
56//! names and slide properties.
57//!
58//! # The same text for the user and for the log
59//!
60//! A problem is often both shown to the user and written to eov's log,
61//! which stays English. Write it once, with `tr!`, and get it in both
62//! languages from [`shown_and_english`]; [`in_english`] runs any code with
63//! this thread's texts written in English:
64//!
65//! ```
66//! use eov_plugin_api::i18n::{self, tr};
67//! let name = "case-12.svs";
68//! let (shown, english) = i18n::shown_and_english(|| tr!("{} could not be read", i18n::isolate(name)));
69//! assert_eq!(english, "case-12.svs could not be read");
70//! # assert_eq!(shown, english);
71//! // host.info(english); host.notify(NotifyLevel::Warning, shown);
72//! ```
73//!
74//! # Writing direction and numbers
75//!
76//! Arabic, Persian and Hebrew are written from right to left. Wrap values
77//! that are inserted into a translated text, and that are written from left
78//! to right whatever the language (file names, paths, numbers with units),
79//! with [`isolate`], so the text around them keeps its order. Show
80//! decimal numbers with [`format_decimal`] and read numbers that users type
81//! with [`parse_decimal`]; both follow the language's decimal separator, as
82//! Slint does in the interface.
83
84use std::cell::Cell;
85use std::collections::HashMap;
86use std::fmt;
87use std::path::{Path, PathBuf};
88use std::sync::RwLock;
89use std::sync::atomic::{AtomicUsize, Ordering};
90
91/// Translates a text written in English: see the [module documentation](self).
92pub use crate::tr;
93
94/// The tag of the source language. Catalogs translate from it; it has none.
95pub const SOURCE_TAG: &str = "en";
96
97/// The writing direction of a language.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum Direction {
100    LeftToRight,
101    RightToLeft,
102}
103
104/// A language of eov's interface: one of [`LANGUAGES`]. Minor releases may
105/// add fields, so code outside this crate reads them and does not build or
106/// destructure a `Language` in full.
107#[derive(Debug, PartialEq, Eq, Hash)]
108#[non_exhaustive]
109pub struct Language {
110    /// The BCP 47 tag (`"de"`, `"pt-BR"`, `"zh-Hant"`): the name of its
111    /// catalog folders, the value of `language` in `config.toml` and of
112    /// `--language`, and what eov tells plugins.
113    pub tag: &'static str,
114    /// The language's name in itself (`"Deutsch"`), with the variant where
115    /// that matters (`"Português (Brasil)"`).
116    pub native_name: &'static str,
117    /// The language's name in English (`"German"`).
118    pub english_name: &'static str,
119    pub direction: Direction,
120    /// The `Plural-Forms` header of the language's catalogs (gettext
121    /// syntax): how many forms a text with a number has, and which one a
122    /// number takes.
123    pub plural_forms: &'static str,
124    /// The decimal separator, as the Unicode CLDR has it and as Slint
125    /// writes and reads numbers in the interface.
126    pub decimal_separator: char,
127}
128
129impl Language {
130    pub fn is_rtl(&self) -> bool {
131        self.direction == Direction::RightToLeft
132    }
133
134    pub fn is_source(&self) -> bool {
135        self.tag == SOURCE_TAG
136    }
137
138    /// The number of plural forms (`nplurals` in [`Self::plural_forms`]).
139    pub fn plural_count(&self) -> usize {
140        self.plural_forms
141            .split(';')
142            .find_map(|part| part.trim().strip_prefix("nplurals="))
143            .and_then(|count| count.trim().parse().ok())
144            .unwrap_or(2)
145    }
146
147    /// The tag in POSIX spelling (`pt_BR`), as some tools name folders.
148    pub fn posix_tag(&self) -> String {
149        self.tag.replace('-', "_")
150    }
151
152    /// The folder names gettext tools give this language's catalogs, in
153    /// the order eov looks for them: the tag (`zh-Hant`), its POSIX
154    /// spelling (`zh_Hant`), and the locale names msginit, Poedit and
155    /// Weblate use for it (`zh_TW`, `nb_NO`).
156    pub fn catalog_folders(&self) -> Vec<String> {
157        let mut folders = vec![self.tag.to_string()];
158        let posix = self.posix_tag();
159        if posix != self.tag {
160            folders.push(posix);
161        }
162        let conventional: &[&str] = match self.tag {
163            "zh-Hans" => &["zh_CN"],
164            "zh-Hant" => &["zh_TW"],
165            "nb" => &["nb_NO", "no"],
166            _ => &[],
167        };
168        folders.extend(conventional.iter().map(|folder| folder.to_string()));
169        folders
170    }
171}
172
173impl fmt::Display for Language {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.write_str(self.tag)
176    }
177}
178
179const ONE_FORM: &str = "nplurals=1; plural=0;";
180const TWO_FORMS: &str = "nplurals=2; plural=(n != 1);";
181const ONE_FOR_ZERO_AND_ONE: &str = "nplurals=2; plural=(n > 1);";
182const EAST_SLAVIC: &str = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);";
183
184const fn language(
185    tag: &'static str,
186    native_name: &'static str,
187    english_name: &'static str,
188    plural_forms: &'static str,
189    decimal_separator: char,
190) -> Language {
191    Language {
192        tag,
193        native_name,
194        english_name,
195        direction: Direction::LeftToRight,
196        plural_forms,
197        decimal_separator,
198    }
199}
200
201const fn rtl(language: Language) -> Language {
202    Language {
203        direction: Direction::RightToLeft,
204        ..language
205    }
206}
207
208/// Every language of the interface: English (the source) first, then the
209/// translations by tag. Plural forms follow the Unicode CLDR as gettext
210/// writes them; decimal separators are the CLDR's.
211///
212/// Minor releases add languages: treat this as a list of any length (it is
213/// a slice, so its type stays the same when one is added), and expect tags
214/// it does not have yet from newer eov versions ([`by_tag`] then answers
215/// `None`).
216pub static LANGUAGES: &[Language] = &[
217    language("en", "English", "English", TWO_FORMS, '.'),
218    rtl(language(
219        "ar",
220        "العربية",
221        "Arabic",
222        "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);",
223        '.',
224    )),
225    language(
226        "cs",
227        "Čeština",
228        "Czech",
229        "nplurals=3; plural=(n==1 ? 0 : n>=2 && n<=4 ? 1 : 2);",
230        ',',
231    ),
232    language("da", "Dansk", "Danish", TWO_FORMS, ','),
233    language("de", "Deutsch", "German", TWO_FORMS, ','),
234    language("el", "Ελληνικά", "Greek", TWO_FORMS, ','),
235    language("es", "Español", "Spanish", TWO_FORMS, ','),
236    rtl(language(
237        "fa",
238        "فارسی",
239        "Persian",
240        ONE_FOR_ZERO_AND_ONE,
241        '\u{066B}',
242    )),
243    language("fi", "Suomi", "Finnish", TWO_FORMS, ','),
244    language("fr", "Français", "French", ONE_FOR_ZERO_AND_ONE, ','),
245    rtl(language("he", "עברית", "Hebrew", TWO_FORMS, '.')),
246    language("hi", "हिन्दी", "Hindi", ONE_FOR_ZERO_AND_ONE, '.'),
247    language("hu", "Magyar", "Hungarian", TWO_FORMS, ','),
248    language("id", "Bahasa Indonesia", "Indonesian", ONE_FORM, ','),
249    language("it", "Italiano", "Italian", TWO_FORMS, ','),
250    language("ja", "日本語", "Japanese", ONE_FORM, '.'),
251    language("ko", "한국어", "Korean", ONE_FORM, '.'),
252    language("nb", "Norsk bokmål", "Norwegian Bokmål", TWO_FORMS, ','),
253    language("nl", "Nederlands", "Dutch", TWO_FORMS, ','),
254    language(
255        "pl",
256        "Polski",
257        "Polish",
258        "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);",
259        ',',
260    ),
261    language(
262        "pt-BR",
263        "Português (Brasil)",
264        "Portuguese (Brazil)",
265        ONE_FOR_ZERO_AND_ONE,
266        ',',
267    ),
268    language(
269        "ro",
270        "Română",
271        "Romanian",
272        "nplurals=3; plural=(n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);",
273        ',',
274    ),
275    language("ru", "Русский", "Russian", EAST_SLAVIC, ','),
276    language(
277        "sl",
278        "Slovenščina",
279        "Slovenian",
280        "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);",
281        ',',
282    ),
283    language("sv", "Svenska", "Swedish", TWO_FORMS, ','),
284    language("th", "ไทย", "Thai", ONE_FORM, '.'),
285    language("tr", "Türkçe", "Turkish", TWO_FORMS, ','),
286    language("uk", "Українська", "Ukrainian", EAST_SLAVIC, ','),
287    language("vi", "Tiếng Việt", "Vietnamese", ONE_FORM, ','),
288    language("zh-Hans", "简体中文", "Chinese (Simplified)", ONE_FORM, '.'),
289    language(
290        "zh-Hant",
291        "繁體中文",
292        "Chinese (Traditional)",
293        ONE_FORM,
294        '.',
295    ),
296];
297
298/// English, the source language.
299pub fn source() -> &'static Language {
300    &LANGUAGES[0]
301}
302
303/// The translations: every language but English.
304pub fn translations() -> &'static [Language] {
305    &LANGUAGES[1..]
306}
307
308/// The language with exactly this tag (letter case and `_` for `-` do not
309/// matter: `pt_br` is `pt-BR`). Use [`negotiate`] for locale names such as
310/// `pt_BR.UTF-8` or `zh-TW`.
311pub fn by_tag(tag: &str) -> Option<&'static Language> {
312    let tag = tag.trim().replace('_', "-");
313    LANGUAGES
314        .iter()
315        .find(|language| language.tag.eq_ignore_ascii_case(&tag))
316}
317
318/// The parts of a locale name that choose a language.
319#[derive(Debug, Default, PartialEq, Eq)]
320struct LocaleParts {
321    language: String,
322    script: Option<String>,
323    region: Option<String>,
324}
325
326/// Splits a BCP 47 tag (`zh-Hant-TW`) or a POSIX locale name
327/// (`pt_BR.UTF-8@euro`) into language, script and region. `C` and `POSIX`
328/// (no preference) give `None`.
329fn locale_parts(locale: &str) -> Option<LocaleParts> {
330    // POSIX: language[_territory][.codeset][@modifier].
331    let locale = locale.trim();
332    let locale = locale.split(['.', '@']).next().unwrap_or_default();
333    let mut subtags = locale.split(['-', '_']).filter(|part| !part.is_empty());
334    let language = subtags.next()?.to_ascii_lowercase();
335    if !(2..=3).contains(&language.len()) || !language.chars().all(|c| c.is_ascii_alphabetic()) {
336        // `C`, `POSIX` or not a language at all.
337        return None;
338    }
339    let mut parts = LocaleParts {
340        language,
341        ..Default::default()
342    };
343    for subtag in subtags {
344        let is_letters = subtag.chars().all(|c| c.is_ascii_alphabetic());
345        if subtag.len() == 4 && is_letters && parts.script.is_none() && parts.region.is_none() {
346            parts.script = Some(subtag.to_ascii_lowercase());
347        } else if parts.region.is_none()
348            && ((subtag.len() == 2 && is_letters)
349                || (subtag.len() == 3 && subtag.chars().all(|c| c.is_ascii_digit())))
350        {
351            parts.region = Some(subtag.to_ascii_uppercase());
352        } else if subtag.len() == 1 {
353            // An extension (`-u-nu-latn`) or private use (`-x-…`): the rest
354            // does not choose the language.
355            break;
356        }
357    }
358    Some(parts)
359}
360
361/// The language of the interface for a locale name of the system or the
362/// user: a BCP 47 tag (`pt-BR`, `zh-Hant-TW`, `es-419`) or a POSIX locale
363/// (`de_AT.UTF-8`). `None` when none of the [`LANGUAGES`] fits, and for `C`
364/// and `POSIX`.
365///
366/// Regional variants of a language take its translation (`de-CH` →
367/// German, `es-MX` → Spanish, `fr-CA` → French), except where a region
368/// writes differently from the translation:
369///
370/// - Chinese: Traditional characters for `Hant`, Taiwan, Hong Kong and
371///   Macao; Simplified characters for `Hans`, mainland China, Singapore,
372///   Malaysia and `zh` alone. A script, when given, decides.
373/// - Portuguese: the translation is Brazilian, so it is chosen for `pt-BR`
374///   and for `pt` alone (which the CLDR takes as Brazil), not for Portugal
375///   or Portuguese-speaking Africa, whose spelling and vocabulary differ:
376///   they get the next language the system prefers, or English. They can
377///   still choose Português (Brasil) in the settings.
378///
379/// Old and alternative codes are understood: `iw` (Hebrew), `in`
380/// (Indonesian), `no` and `nn` (Norwegian: Nynorsk readers get Bokmål,
381/// the other written standard every Norwegian reads).
382pub fn negotiate(locale: &str) -> Option<&'static Language> {
383    let parts = locale_parts(locale)?;
384    let region = parts.region.as_deref();
385    let tag = match parts.language.as_str() {
386        "zh" => match (parts.script.as_deref(), region) {
387            (Some("hant"), _) => "zh-Hant",
388            (Some("hans"), _) => "zh-Hans",
389            (Some(_), _) => return None,
390            (None, Some("TW" | "HK" | "MO")) => "zh-Hant",
391            (None, _) => "zh-Hans",
392        },
393        "pt" => match region {
394            None | Some("BR") => "pt-BR",
395            Some(_) => return None,
396        },
397        "iw" => "he",
398        "in" => "id",
399        "no" | "nn" => "nb",
400        // Serbian, Uzbek, … written in another script than the translation
401        // (none here) would be refused by the script check below.
402        other => other,
403    };
404    let language = by_tag(tag)?;
405    // A script the translation is not written in (`ar-Latn`, `ru-Latn`):
406    // a reader of that script may not read ours.
407    if parts.language != "zh"
408        && let Some(script) = parts.script.as_deref()
409        && script != default_script(language)
410    {
411        return None;
412    }
413    Some(language)
414}
415
416/// The ISO 15924 script (lower case) a language's translation is written in.
417fn default_script(language: &Language) -> &'static str {
418    match language.tag {
419        "ar" | "fa" => "arab",
420        "he" => "hebr",
421        "hi" => "deva",
422        "el" => "grek",
423        "ru" | "uk" => "cyrl",
424        "ja" => "jpan",
425        "ko" => "kore",
426        "th" => "thai",
427        "zh-Hans" => "hans",
428        "zh-Hant" => "hant",
429        _ => "latn",
430    }
431}
432
433/// The first of `locales` (in order of preference) that [`negotiate`]
434/// fits.
435pub fn negotiate_first<I, S>(locales: I) -> Option<&'static Language>
436where
437    I: IntoIterator<Item = S>,
438    S: AsRef<str>,
439{
440    locales
441        .into_iter()
442        .find_map(|locale| negotiate(locale.as_ref()))
443}
444
445// ---------------------------------------------------------------------------
446// The current language
447// ---------------------------------------------------------------------------
448
449/// The index into [`LANGUAGES`] of this library's current language. Each
450/// plugin library has its own (statics are not shared between libraries);
451/// eov and the SDK keep it up to date.
452#[cfg(not(feature = "thread-local-language"))]
453static CURRENT: AtomicUsize = AtomicUsize::new(0);
454
455// With `thread-local-language` (hosts' and plugins' tests), each thread has
456// its own language and catalog, so a test that switches languages does not
457// change the texts that tests on other threads compare.
458#[cfg(feature = "thread-local-language")]
459thread_local! {
460    static CURRENT: AtomicUsize = const { AtomicUsize::new(0) };
461    static CATALOG: RwLock<Option<Catalog>> = const { RwLock::new(None) };
462}
463
464fn current_index() -> usize {
465    #[cfg(not(feature = "thread-local-language"))]
466    return CURRENT.load(Ordering::Relaxed);
467    #[cfg(feature = "thread-local-language")]
468    return CURRENT.with(|current| current.load(Ordering::Relaxed));
469}
470
471fn set_current_index(index: usize) {
472    #[cfg(not(feature = "thread-local-language"))]
473    CURRENT.store(index, Ordering::Relaxed);
474    #[cfg(feature = "thread-local-language")]
475    CURRENT.with(|current| current.store(index, Ordering::Relaxed));
476}
477
478thread_local! {
479    /// Set while this thread writes its texts in English ([`in_english`]),
480    /// whatever the library's (or, with `thread-local-language`, this
481    /// thread's) language is.
482    static IN_ENGLISH: Cell<bool> = const { Cell::new(false) };
483}
484
485/// Whether this thread writes its texts in English just now
486/// ([`in_english`]).
487fn writing_english() -> bool {
488    IN_ENGLISH.with(Cell::get)
489}
490
491/// The language of the interface (English until eov says otherwise), and
492/// English while this thread runs [`in_english`].
493pub fn current() -> &'static Language {
494    if writing_english() {
495        return source();
496    }
497    &LANGUAGES[current_index().min(LANGUAGES.len() - 1)]
498}
499
500/// Runs `write` with this thread's texts written as in English:
501/// [`tr!`](crate::tr!) gives the English text (filled in, and with the
502/// English plural form), and everything that follows [`current`] does as
503/// for English: [`isolate`] adds no marks, [`format_decimal`] writes and
504/// [`parse_decimal`] reads numbers as in English, [`is_rtl`] is false;
505/// [`join_sentences`] joins as it does in every language. For the
506/// English line of eov's log or of a file, from the code that writes the
507/// shown text; see [`shown_and_english`] for both at once.
508///
509/// It affects only this thread, only Rust code (Slint's `@tr` texts keep
510/// the interface's language) and only until `write` returns, also when it
511/// panics. Calls may be nested. The language and the catalog stay as they
512/// are: [`set_current`] and [`set_catalog`] called inside `write` change
513/// them, and this thread follows them again once `write` returns.
514pub fn in_english<R>(write: impl FnOnce() -> R) -> R {
515    /// Puts this thread's language back, also when `write` panics.
516    struct Restore(bool);
517    impl Drop for Restore {
518        fn drop(&mut self) {
519            IN_ENGLISH.with(|english| english.set(self.0));
520        }
521    }
522    let _restore = Restore(IN_ENGLISH.with(|english| english.replace(true)));
523    write()
524}
525
526/// The text `write` makes in the interface's language (to show) and in
527/// English (for eov's log, files, batch output), written by the same code:
528///
529/// ```
530/// use eov_plugin_api::i18n::{self, tr};
531/// let name = "model.onnx";
532/// let (shown, english) =
533///     i18n::shown_and_english(|| tr!("{} could not be loaded", i18n::isolate(name)));
534/// assert_eq!(english, "model.onnx could not be loaded");
535/// # assert_eq!(shown, english);
536/// ```
537///
538/// `write` is called twice, the second time inside [`in_english`]: it
539/// should only make the text. Texts it inserts follow the language being
540/// written when they are made in `write` too (with `tr!`, [`isolate`],
541/// [`format_decimal`]); a text made earlier is inserted as it is, so keep
542/// both forms of such a text and insert the one for [`current`] (English
543/// when [`Language::is_source`]).
544pub fn shown_and_english(write: impl Fn() -> String) -> (String, String) {
545    let shown = write();
546    let english = in_english(&write);
547    (shown, english)
548}
549
550/// Whether the interface is written from right to left.
551pub fn is_rtl() -> bool {
552    current().is_rtl()
553}
554
555/// Makes `language` this library's current language for [`current`],
556/// [`isolate`], [`format_decimal`] and [`parse_decimal`], without changing
557/// the catalog (see [`set_catalog`]).
558pub fn set_current(language: &'static Language) {
559    if let Some(index) = LANGUAGES.iter().position(|l| std::ptr::eq(l, language)) {
560        set_current_index(index);
561    }
562}
563
564// ---------------------------------------------------------------------------
565// Catalogs
566// ---------------------------------------------------------------------------
567
568/// The translations of one domain (eov, or a plugin) into one language,
569/// read from a gettext `.po` file.
570///
571/// Only translated entries are used, as gettext's `msgfmt` compiles them:
572/// untranslated, fuzzy and obsolete ones are left out, so their texts show
573/// in English. Plural forms follow the catalog's `Plural-Forms` header.
574pub struct Catalog {
575    language: &'static Language,
576    /// The forms of each translated text (one, or one per plural form), by
577    /// context and English text.
578    messages: HashMap<(Option<String>, String), Vec<String>>,
579    plural: PluralRule,
580}
581
582impl fmt::Debug for Catalog {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        f.debug_struct("Catalog")
585            .field("language", &self.language.tag)
586            .field("messages", &self.messages.len())
587            .finish()
588    }
589}
590
591thread_local! {
592    /// Set while this thread reads a `.po` file (see [`reading_catalog`]).
593    static READING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
594}
595
596/// Whether this thread is reading a `.po` file. rspolib, the reader Slint
597/// uses too, panics on some malformed files; eov catches those panics and
598/// reports a bad catalog, and its panic hook asks this so that it does not
599/// record them as crashes.
600pub fn reading_catalog() -> bool {
601    READING.with(std::cell::Cell::get)
602}
603
604/// Reads a `.po` text with rspolib, turning its panics on malformed files
605/// into errors.
606fn read_po(text: &str) -> Result<rspolib::POFile, String> {
607    READING.with(|reading| reading.set(true));
608    let result = std::panic::catch_unwind(|| rspolib::pofile(text));
609    READING.with(|reading| reading.set(false));
610    match result {
611        Ok(Ok(file)) => Ok(file),
612        Ok(Err(error)) => Err(error.to_string()),
613        Err(payload) => Err(
614            match payload
615                .downcast_ref::<&str>()
616                .map(|text| text.to_string())
617                .or_else(|| payload.downcast_ref::<String>().cloned())
618            {
619                Some(text) => format!("malformed ({text})"),
620                None => "malformed".to_string(),
621            },
622        ),
623    }
624}
625
626/// Why a catalog could not be read.
627#[derive(Debug, Clone, PartialEq, Eq)]
628pub struct CatalogError {
629    pub message: String,
630}
631
632impl fmt::Display for CatalogError {
633    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634        f.write_str(&self.message)
635    }
636}
637
638impl std::error::Error for CatalogError {}
639
640impl Catalog {
641    /// Reads a catalog of `language` from the contents of a `.po` file.
642    ///
643    /// The file is read with rspolib (Slint reads its catalogs with it
644    /// too). Its plural rule comes from the `Plural-Forms` header, or from
645    /// the language when the header has none.
646    pub fn parse(language: &'static Language, po: &[u8]) -> Result<Self, CatalogError> {
647        use rspolib::prelude::*;
648        let error = |message: String| CatalogError { message };
649        let text = std::str::from_utf8(po)
650            .map_err(|e| error(format!("not UTF-8: {e}")))?
651            .trim_start_matches('\u{feff}')
652            .replace("\r\n", "\n");
653        if !text.contains("msgid") {
654            return Err(error("not a .po file: it has no msgid".to_string()));
655        }
656        // rspolib takes a path or the text of a file; a text spans several
657        // lines, so it is never taken for a path.
658        let file = read_po(&text).map_err(|e| error(format!("not a valid .po file: {e}")))?;
659        let forms = file
660            .metadata
661            .get("Plural-Forms")
662            .map(String::as_str)
663            .unwrap_or(language.plural_forms);
664        let plural = PluralRule::from_header(forms)
665            .map_err(|e| error(format!("Plural-Forms \"{forms}\": {e}")))?;
666        let messages = file
667            .entries
668            .iter()
669            .filter(|entry| entry.translated() && !entry.msgid.is_empty())
670            .map(|entry| {
671                let forms = match &entry.msgstr {
672                    Some(text) if entry.msgid_plural.is_none() => vec![text.clone()],
673                    _ => entry.msgstr_plural.clone(),
674                };
675                ((entry.msgctxt.clone(), entry.msgid.clone()), forms)
676            })
677            .collect();
678        Ok(Self {
679            language,
680            messages,
681            plural,
682        })
683    }
684
685    /// A catalog from texts read beforehand (eov compiles its own into the
686    /// program): `(context, English text, forms)`, with the forms of a
687    /// plural text in the order of `plural_forms` (a `Plural-Forms`
688    /// header; the language's when empty). Texts with no form or an empty
689    /// one are left out.
690    pub fn from_messages<'a>(
691        language: &'static Language,
692        plural_forms: &str,
693        messages: impl IntoIterator<Item = (Option<&'a str>, &'a str, &'a [&'a str])>,
694    ) -> Result<Self, CatalogError> {
695        let forms = if plural_forms.trim().is_empty() {
696            language.plural_forms
697        } else {
698            plural_forms
699        };
700        let plural = PluralRule::from_header(forms).map_err(|e| CatalogError {
701            message: format!("Plural-Forms \"{forms}\": {e}"),
702        })?;
703        let messages = messages
704            .into_iter()
705            .filter(|(_, msgid, forms)| {
706                !msgid.is_empty() && !forms.is_empty() && forms.iter().all(|f| !f.is_empty())
707            })
708            .map(|(context, msgid, forms)| {
709                (
710                    (context.map(str::to_string), msgid.to_string()),
711                    forms.iter().map(|f| f.to_string()).collect(),
712                )
713            })
714            .collect();
715        Ok(Self {
716            language,
717            messages,
718            plural,
719        })
720    }
721
722    /// Reads the catalog of `domain` for `language` from `dir` (see
723    /// [`find_catalog`]); `Ok(None)` when there is none.
724    pub fn load(
725        dir: &Path,
726        domain: &str,
727        language: &'static Language,
728    ) -> Result<Option<Self>, CatalogError> {
729        let Some(path) = find_catalog(dir, domain, language) else {
730            return Ok(None);
731        };
732        let bytes = std::fs::read(&path).map_err(|e| CatalogError {
733            message: format!("cannot read {}: {e}", path.display()),
734        })?;
735        Self::parse(language, &bytes)
736            .map(Some)
737            .map_err(|e| CatalogError {
738                message: format!("{}: {}", path.display(), e.message),
739            })
740    }
741
742    pub fn language(&self) -> &'static Language {
743        self.language
744    }
745
746    /// The number of translated messages.
747    pub fn len(&self) -> usize {
748        self.messages.len()
749    }
750
751    pub fn is_empty(&self) -> bool {
752        self.messages.is_empty()
753    }
754
755    fn lookup(&self, msgctxt: Option<&str>, msgid: &str) -> Option<&[String]> {
756        // Borrowed lookups would need a custom key type; texts are short.
757        self.messages
758            .get(&(msgctxt.map(str::to_string), msgid.to_string()))
759            .map(Vec::as_slice)
760    }
761
762    /// The translation of `msgid` with the context `msgctxt`, if the
763    /// catalog has one.
764    pub fn translate(&self, msgctxt: Option<&str>, msgid: &str) -> Option<&str> {
765        self.lookup(msgctxt, msgid)?.first().map(String::as_str)
766    }
767
768    /// The form of a text with a number `n`, if the catalog translates it.
769    pub fn ntranslate(&self, msgctxt: Option<&str>, singular: &str, n: u64) -> Option<&str> {
770        let forms = self.lookup(msgctxt, singular)?;
771        forms
772            .get(self.plural.form(n))
773            .filter(|form| !form.is_empty())
774            .map(String::as_str)
775    }
776
777    /// The plural form a number `n` takes in this catalog's language.
778    pub fn plural_form(&self, n: u64) -> usize {
779        self.plural.form(n)
780    }
781
782    /// The plural rule of the catalog: its `Plural-Forms` header's, or the
783    /// language's when it has none.
784    pub fn plural_rule(&self) -> &PluralRule {
785        &self.plural
786    }
787}
788
789/// A gettext plural rule: the C expression of a `Plural-Forms` header
790/// (`n%10==1 && n%100!=11 ? 0 : …`) that gives the form a number takes.
791#[derive(Debug, Clone, PartialEq)]
792pub struct PluralRule {
793    count: usize,
794    expression: Expression,
795}
796
797#[derive(Debug, Clone, PartialEq)]
798enum Expression {
799    N,
800    Number(u64),
801    Not(Box<Expression>),
802    Binary(Box<Expression>, BinaryOp, Box<Expression>),
803    Conditional(Box<Expression>, Box<Expression>, Box<Expression>),
804}
805
806#[derive(Debug, Clone, Copy, PartialEq)]
807enum BinaryOp {
808    Or,
809    And,
810    Eq,
811    Ne,
812    Lt,
813    Le,
814    Gt,
815    Ge,
816    Add,
817    Sub,
818    Mul,
819    Div,
820    Rem,
821}
822
823impl BinaryOp {
824    /// Binding strength, as in C (higher binds tighter).
825    fn precedence(self) -> u8 {
826        match self {
827            BinaryOp::Or => 1,
828            BinaryOp::And => 2,
829            BinaryOp::Eq | BinaryOp::Ne => 3,
830            BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => 4,
831            BinaryOp::Add | BinaryOp::Sub => 5,
832            BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => 6,
833        }
834    }
835
836    fn apply(self, a: u64, b: u64) -> u64 {
837        match self {
838            BinaryOp::Or => u64::from(a != 0 || b != 0),
839            BinaryOp::And => u64::from(a != 0 && b != 0),
840            BinaryOp::Eq => u64::from(a == b),
841            BinaryOp::Ne => u64::from(a != b),
842            BinaryOp::Lt => u64::from(a < b),
843            BinaryOp::Le => u64::from(a <= b),
844            BinaryOp::Gt => u64::from(a > b),
845            BinaryOp::Ge => u64::from(a >= b),
846            BinaryOp::Add => a.wrapping_add(b),
847            BinaryOp::Sub => a.wrapping_sub(b),
848            BinaryOp::Mul => a.wrapping_mul(b),
849            // gettext's own evaluator gives 0 for a division by zero.
850            BinaryOp::Div => a.checked_div(b).unwrap_or(0),
851            BinaryOp::Rem => a.checked_rem(b).unwrap_or(0),
852        }
853    }
854}
855
856impl Expression {
857    fn evaluate(&self, n: u64) -> u64 {
858        match self {
859            Expression::N => n,
860            Expression::Number(value) => *value,
861            Expression::Not(inner) => u64::from(inner.evaluate(n) == 0),
862            Expression::Binary(a, op, b) => match op {
863                // Short-circuit, as C does.
864                BinaryOp::Or if a.evaluate(n) != 0 => 1,
865                BinaryOp::And if a.evaluate(n) == 0 => 0,
866                _ => op.apply(a.evaluate(n), b.evaluate(n)),
867            },
868            Expression::Conditional(condition, then, otherwise) => {
869                if condition.evaluate(n) != 0 {
870                    then.evaluate(n)
871                } else {
872                    otherwise.evaluate(n)
873                }
874            }
875        }
876    }
877}
878
879/// Reads the plural expression (the grammar of GNU gettext's
880/// `plural.y`): conditionals, `||`, `&&`, comparisons, arithmetic, `!`,
881/// parentheses, `n` and unsigned numbers.
882struct ExpressionParser<'a> {
883    text: &'a [u8],
884    at: usize,
885}
886
887impl<'a> ExpressionParser<'a> {
888    fn skip_space(&mut self) {
889        while self.text.get(self.at).is_some_and(u8::is_ascii_whitespace) {
890            self.at += 1;
891        }
892    }
893
894    fn peek(&mut self) -> Option<u8> {
895        self.skip_space();
896        self.text.get(self.at).copied()
897    }
898
899    fn eat(&mut self, token: &str) -> bool {
900        self.skip_space();
901        if self.text[self.at..].starts_with(token.as_bytes()) {
902            self.at += token.len();
903            true
904        } else {
905            false
906        }
907    }
908
909    fn conditional(&mut self) -> Result<Expression, String> {
910        let condition = self.binary(1)?;
911        if self.eat("?") {
912            let then = self.conditional()?;
913            if !self.eat(":") {
914                return Err(format!("':' expected at {}", self.at));
915            }
916            let otherwise = self.conditional()?;
917            return Ok(Expression::Conditional(
918                Box::new(condition),
919                Box::new(then),
920                Box::new(otherwise),
921            ));
922        }
923        Ok(condition)
924    }
925
926    fn operator(&mut self) -> Option<(BinaryOp, usize)> {
927        self.skip_space();
928        let rest = &self.text[self.at..];
929        let two = |token: &[u8]| rest.starts_with(token);
930        Some(if two(b"||") {
931            (BinaryOp::Or, 2)
932        } else if two(b"&&") {
933            (BinaryOp::And, 2)
934        } else if two(b"==") {
935            (BinaryOp::Eq, 2)
936        } else if two(b"!=") {
937            (BinaryOp::Ne, 2)
938        } else if two(b"<=") {
939            (BinaryOp::Le, 2)
940        } else if two(b">=") {
941            (BinaryOp::Ge, 2)
942        } else {
943            match rest.first()? {
944                b'<' => (BinaryOp::Lt, 1),
945                b'>' => (BinaryOp::Gt, 1),
946                b'+' => (BinaryOp::Add, 1),
947                b'-' => (BinaryOp::Sub, 1),
948                b'*' => (BinaryOp::Mul, 1),
949                b'/' => (BinaryOp::Div, 1),
950                b'%' => (BinaryOp::Rem, 1),
951                _ => return None,
952            }
953        })
954    }
955
956    /// Binary operators binding at least as tightly as `min` (precedence
957    /// climbing; all of them associate to the left).
958    fn binary(&mut self, min: u8) -> Result<Expression, String> {
959        let mut left = self.unary()?;
960        while let Some((op, len)) = self.operator() {
961            if op.precedence() < min {
962                break;
963            }
964            self.at += len;
965            let right = self.binary(op.precedence() + 1)?;
966            left = Expression::Binary(Box::new(left), op, Box::new(right));
967        }
968        Ok(left)
969    }
970
971    fn unary(&mut self) -> Result<Expression, String> {
972        match self.peek() {
973            Some(b'!') => {
974                self.at += 1;
975                Ok(Expression::Not(Box::new(self.unary()?)))
976            }
977            Some(b'(') => {
978                self.at += 1;
979                let inner = self.conditional()?;
980                if !self.eat(")") {
981                    return Err(format!("')' expected at {}", self.at));
982                }
983                Ok(inner)
984            }
985            Some(b'n') => {
986                self.at += 1;
987                Ok(Expression::N)
988            }
989            Some(c) if c.is_ascii_digit() => {
990                let start = self.at;
991                while self.text.get(self.at).is_some_and(u8::is_ascii_digit) {
992                    self.at += 1;
993                }
994                std::str::from_utf8(&self.text[start..self.at])
995                    .ok()
996                    .and_then(|digits| digits.parse().ok())
997                    .map(Expression::Number)
998                    .ok_or_else(|| format!("number too large at {start}"))
999            }
1000            Some(c) => Err(format!("unexpected '{}' at {}", c as char, self.at)),
1001            None => Err("unexpected end".to_string()),
1002        }
1003    }
1004}
1005
1006impl PluralRule {
1007    /// Reads a `Plural-Forms` header value
1008    /// (`nplurals=2; plural=(n != 1);`).
1009    pub fn from_header(header: &str) -> Result<Self, String> {
1010        let mut count = None;
1011        let mut expression = None;
1012        for part in header.split(';') {
1013            let Some((key, value)) = part.split_once('=') else {
1014                continue;
1015            };
1016            match key.trim() {
1017                "nplurals" => {
1018                    count = Some(
1019                        value
1020                            .trim()
1021                            .parse::<usize>()
1022                            .map_err(|_| format!("nplurals is not a number: {value}"))?,
1023                    )
1024                }
1025                "plural" => expression = Some(value.trim()),
1026                _ => {}
1027            }
1028        }
1029        let count = count.ok_or("nplurals is missing")?;
1030        if !(1..=6).contains(&count) {
1031            return Err(format!("nplurals must be 1 to 6, not {count}"));
1032        }
1033        let text = expression.ok_or("plural is missing")?;
1034        let mut parser = ExpressionParser {
1035            text: text.as_bytes(),
1036            at: 0,
1037        };
1038        let expression = parser.conditional()?;
1039        parser.skip_space();
1040        if parser.at != text.len() {
1041            return Err(format!(
1042                "unexpected text after the expression: {}",
1043                &text[parser.at..]
1044            ));
1045        }
1046        Ok(Self { count, expression })
1047    }
1048
1049    /// How many forms a text with a number has.
1050    pub fn count(&self) -> usize {
1051        self.count
1052    }
1053
1054    /// The form `n` takes: always less than [`Self::count`].
1055    pub fn form(&self, n: u64) -> usize {
1056        usize::try_from(self.expression.evaluate(n))
1057            .unwrap_or(usize::MAX)
1058            .min(self.count - 1)
1059    }
1060
1061    /// Whether `other` gives every number the same form as this rule, as
1062    /// two spellings of one rule do (`plural=n != 1;` and
1063    /// `plural=(n != 1);`). Numbers are compared where gettext rules tell
1064    /// them apart: the small ones, and by their last two or three digits.
1065    /// The number of forms is not compared ([`Self::count`]).
1066    pub fn same_forms(&self, other: &PluralRule) -> bool {
1067        (0..=10_000u64)
1068            .chain([
1069                100_000,
1070                1_000_000,
1071                1_000_001,
1072                1_000_002,
1073                1_000_005,
1074                1_000_011,
1075                1_000_021,
1076                1_000_100,
1077                10_000_000,
1078                u64::from(u32::MAX),
1079            ])
1080            .all(|n| self.form(n) == other.form(n))
1081    }
1082}
1083
1084/// What [`check_catalog`] found in a catalog.
1085#[derive(Debug, Clone, Default, PartialEq, Eq)]
1086pub struct CatalogReport {
1087    pub translated: usize,
1088    pub fuzzy: usize,
1089    pub untranslated: usize,
1090    /// Texts of the template the catalog lacks (`context\u{4}text`).
1091    pub missing: Vec<String>,
1092    /// Texts the catalog has but the template no longer does.
1093    pub obsolete: Vec<String>,
1094    /// What is wrong: a header that does not fit the language (or lacks its
1095    /// plural rule), plural forms that are missing, placeholders that are
1096    /// lost or made up.
1097    pub problems: Vec<String>,
1098}
1099
1100impl CatalogReport {
1101    /// Whether every text of the template is translated, and nothing is
1102    /// wrong.
1103    pub fn is_complete(&self) -> bool {
1104        self.fuzzy == 0
1105            && self.untranslated == 0
1106            && self.missing.is_empty()
1107            && self.problems.is_empty()
1108    }
1109}
1110
1111/// The values a text inserts, as `format` and Slint fill them: the k-th
1112/// `{}` and `{k}` are the same value, so a translation may write `{1} … {0}`
1113/// to put them in another order.
1114fn inserted_values(text: &str) -> std::collections::BTreeSet<String> {
1115    let mut next = 0;
1116    placeholders_in_order(text)
1117        .into_iter()
1118        .map(|placeholder| {
1119            if placeholder == "{}" {
1120                next += 1;
1121                format!("{{{}}}", next - 1)
1122            } else {
1123                placeholder.to_string()
1124            }
1125        })
1126        .collect()
1127}
1128
1129/// The placeholders of a text (`{}`, `{0}`, `{name}`; not `{{` or `}}`).
1130pub fn placeholders(text: &str) -> std::collections::BTreeSet<&str> {
1131    placeholders_in_order(text).into_iter().collect()
1132}
1133
1134fn placeholders_in_order(text: &str) -> Vec<&str> {
1135    let mut found = Vec::new();
1136    let mut rest = text;
1137    while let Some(at) = rest.find('{') {
1138        let tail = &rest[at..];
1139        if let Some(after) = tail.strip_prefix("{{") {
1140            rest = after;
1141            continue;
1142        }
1143        match tail.find('}') {
1144            Some(end) if !tail[1..end].contains('{') => {
1145                found.push(&tail[..=end]);
1146                rest = &tail[end + 1..];
1147            }
1148            _ => rest = &tail[1..],
1149        }
1150    }
1151    found
1152}
1153
1154/// Checks a catalog of `language` (the text of its `.po` file) against
1155/// what eov needs to show it, and, when given, its template (`.pot`):
1156///
1157/// - the header names the language and has its plural rule
1158///   (`Plural-Forms`) in any spelling: as many forms as `language` has,
1159///   and the same form for every number ([`PluralRule::same_forms`]). A
1160///   header without one is reported too (`msgfmt --check` refuses a
1161///   catalog with plural texts without one), although eov reads a plugin's
1162///   catalog without one with the language's rule;
1163/// - a text with a number has as many forms as the language has, and each
1164///   form that numbers other than one take shows the number (`{n}`) when
1165///   the English does;
1166/// - every translation keeps the English text's placeholders and adds none
1167///   (`{}` and `{0}` stand for values eov inserts).
1168///
1169/// It also counts translated, fuzzy and untranslated texts, and lists the
1170/// template's texts the catalog lacks.
1171pub fn check_catalog(
1172    language: &'static Language,
1173    po: &str,
1174    template: Option<&str>,
1175) -> CatalogReport {
1176    use rspolib::prelude::*;
1177    let mut report = CatalogReport::default();
1178    let parse = |text: &str| {
1179        let text = text.trim_start_matches('\u{feff}').replace("\r\n", "\n");
1180        read_po(&text)
1181    };
1182    let file = match parse(po) {
1183        Ok(file) => file,
1184        Err(error) => {
1185            report
1186                .problems
1187                .push(format!("not a valid .po file: {error}"));
1188            return report;
1189        }
1190    };
1191    match file.metadata.get("Language") {
1192        Some(tag) if tag.trim() == language.tag => {}
1193        other => report.problems.push(format!(
1194            "the header says Language: {}, not {}",
1195            other.map(String::as_str).unwrap_or("(none)"),
1196            language.tag
1197        )),
1198    }
1199    let rule = match file.metadata.get("Plural-Forms") {
1200        Some(forms) => match (
1201            PluralRule::from_header(forms),
1202            PluralRule::from_header(language.plural_forms),
1203        ) {
1204            (Ok(rule), Ok(wanted))
1205                if rule.count() == wanted.count() && rule.same_forms(&wanted) =>
1206            {
1207                Some(rule)
1208            }
1209            (Err(error), _) => {
1210                report.problems.push(format!(
1211                    "the header's Plural-Forms {forms:?} cannot be read ({error}); {}'s is {}",
1212                    language.english_name, language.plural_forms
1213                ));
1214                None
1215            }
1216            _ => {
1217                report.problems.push(format!(
1218                    "the header's Plural-Forms {forms:?} is not the rule of {} ({}, in any spelling)",
1219                    language.english_name, language.plural_forms
1220                ));
1221                None
1222            }
1223        },
1224        None => {
1225            report.problems.push(format!(
1226                "the header has no Plural-Forms; {}'s is {}",
1227                language.english_name, language.plural_forms
1228            ));
1229            None
1230        }
1231    };
1232    let key = |context: &Option<String>, msgid: &str| match context {
1233        Some(context) => format!("{context}\u{4}{msgid}"),
1234        None => msgid.to_string(),
1235    };
1236    let mut keys = std::collections::BTreeSet::new();
1237    for entry in file
1238        .entries
1239        .iter()
1240        .filter(|e| !e.obsolete && !e.msgid.is_empty())
1241    {
1242        let name = key(&entry.msgctxt, &entry.msgid);
1243        keys.insert(name.clone());
1244        if entry.fuzzy() {
1245            report.fuzzy += 1;
1246            continue;
1247        }
1248        if !entry.translated() {
1249            report.untranslated += 1;
1250            continue;
1251        }
1252        report.translated += 1;
1253        let plural = entry.msgid_plural.as_deref();
1254        let sources: std::collections::BTreeSet<String> = inserted_values(&entry.msgid)
1255            .union(&inserted_values(plural.unwrap_or_default()))
1256            .cloned()
1257            .collect();
1258        let forms: Vec<&str> = match plural {
1259            Some(_) => entry.msgstr_plural.iter().map(String::as_str).collect(),
1260            None => entry.msgstr.iter().map(String::as_str).collect(),
1261        };
1262        if plural.is_some() && forms.len() != language.plural_count() {
1263            report.problems.push(format!(
1264                "{name:?}: {} plural forms, {} has {}",
1265                forms.len(),
1266                language.english_name,
1267                language.plural_count()
1268            ));
1269        }
1270        for (index, form) in forms.iter().enumerate() {
1271            let found = inserted_values(form);
1272            let made_up: Vec<&String> = found.difference(&sources).collect();
1273            if !made_up.is_empty() {
1274                report
1275                    .problems
1276                    .push(format!("{name:?}: the translation adds {made_up:?}"));
1277            }
1278            let lost: Vec<&String> = sources
1279                .iter()
1280                .filter(|p| p.as_str() != "{n}" && !found.contains(*p))
1281                .collect();
1282            if !lost.is_empty() {
1283                report
1284                    .problems
1285                    .push(format!("{name:?}: the translation loses {lost:?}"));
1286            }
1287            // A form that numbers other than 1 take must show the number.
1288            let shows_counts = match (&rule, plural) {
1289                (Some(rule), Some(plural)) if plural.contains("{n}") => {
1290                    (0..=200u64).any(|n| n != 1 && rule.form(n) == index)
1291                }
1292                (_, None) => entry.msgid.contains("{n}"),
1293                _ => false,
1294            };
1295            if shows_counts && !found.contains("{n}") {
1296                report.problems.push(format!(
1297                    "{name:?}: form {index} is used for counts other than 1 but does not show {{n}}"
1298                ));
1299            }
1300        }
1301    }
1302    if let Some(template) = template {
1303        match parse(template) {
1304            Ok(template) => {
1305                let wanted: std::collections::BTreeSet<String> = template
1306                    .entries
1307                    .iter()
1308                    .filter(|e| !e.obsolete && !e.msgid.is_empty())
1309                    .map(|e| key(&e.msgctxt, &e.msgid))
1310                    .collect();
1311                report.missing = wanted.difference(&keys).cloned().collect();
1312                report.obsolete = keys.difference(&wanted).cloned().collect();
1313            }
1314            Err(error) => report
1315                .problems
1316                .push(format!("the template is not valid: {error}")),
1317        }
1318    }
1319    report
1320}
1321
1322/// Where the catalog of `domain` for `language` belongs:
1323/// `<dir>/<tag>/LC_MESSAGES/<domain>.po`.
1324pub fn catalog_path(dir: &Path, domain: &str, language: &Language) -> PathBuf {
1325    dir.join(language.tag)
1326        .join("LC_MESSAGES")
1327        .join(format!("{domain}.po"))
1328}
1329
1330/// The catalog of `domain` for `language` in `dir`: in the tag's folder
1331/// (`pt-BR`), else under another spelling gettext tools use
1332/// ([`Language::catalog_folders`]: `pt_BR`, `zh_TW`). English has none.
1333pub fn find_catalog(dir: &Path, domain: &str, language: &Language) -> Option<PathBuf> {
1334    if language.is_source() {
1335        return None;
1336    }
1337    language
1338        .catalog_folders()
1339        .into_iter()
1340        .map(|folder| {
1341            dir.join(folder)
1342                .join("LC_MESSAGES")
1343                .join(format!("{domain}.po"))
1344        })
1345        .find(|path| path.is_file())
1346}
1347
1348/// A catalog without translations for `language`: just the header, with the
1349/// language's plural forms. eov puts one in for each language a plugin has
1350/// no catalog for, so that every bundle lists the same languages.
1351pub fn empty_catalog(language: &Language, domain: &str) -> String {
1352    format!(
1353        "msgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: {domain}\\n\"\n\"Language: {tag}\\n\"\n\
1354         \"MIME-Version: 1.0\\n\"\n\"Content-Type: text/plain; charset=UTF-8\\n\"\n\
1355         \"Content-Transfer-Encoding: 8bit\\n\"\n\"Plural-Forms: {plural}\\n\"\n",
1356        tag = language.tag,
1357        plural = language.plural_forms,
1358    )
1359}
1360
1361// ---------------------------------------------------------------------------
1362// Translating
1363// ---------------------------------------------------------------------------
1364
1365/// The catalog [`tr!`](crate::tr!) translates with. Each library (eov, and
1366/// each plugin) has its own: statics are not shared between libraries.
1367#[cfg(not(feature = "thread-local-language"))]
1368static CATALOG: RwLock<Option<Catalog>> = RwLock::new(None);
1369
1370/// Runs `f` with this library's catalog (this thread's with
1371/// `thread-local-language`).
1372fn with_catalog<R>(f: impl FnOnce(&RwLock<Option<Catalog>>) -> R) -> R {
1373    #[cfg(not(feature = "thread-local-language"))]
1374    return f(&CATALOG);
1375    #[cfg(feature = "thread-local-language")]
1376    return CATALOG.with(f);
1377}
1378
1379/// Makes `catalog` the one [`tr!`](crate::tr!) translates with, and its
1380/// language the [`current`] one; `None` shows the English texts. eov
1381/// and the plugin SDK call this when the language changes.
1382pub fn set_catalog(language: &'static Language, catalog: Option<Catalog>) {
1383    set_current(language);
1384    let catalog = catalog.filter(|c| std::ptr::eq(c.language(), language));
1385    with_catalog(|slot| {
1386        *slot
1387            .write()
1388            .unwrap_or_else(|poisoned| poisoned.into_inner()) = catalog
1389    });
1390}
1391
1392/// The translation of `msgid` (with the context `msgctxt`), or `msgid`
1393/// (always inside [`in_english`]).
1394pub fn translate(msgctxt: Option<&str>, msgid: &str) -> String {
1395    if writing_english() {
1396        return msgid.to_string();
1397    }
1398    with_catalog(|slot| {
1399        let catalog = slot.read().unwrap_or_else(|poisoned| poisoned.into_inner());
1400        catalog
1401            .as_ref()
1402            .and_then(|catalog| catalog.translate(msgctxt, msgid))
1403            .unwrap_or(msgid)
1404            .to_string()
1405    })
1406}
1407
1408/// The form of a text with a number `n` in the current language (in
1409/// English inside [`in_english`]).
1410pub fn ntranslate(msgctxt: Option<&str>, singular: &str, plural: &str, n: u64) -> String {
1411    if writing_english() {
1412        return if n == 1 { singular } else { plural }.to_string();
1413    }
1414    with_catalog(|slot| {
1415        let catalog = slot.read().unwrap_or_else(|poisoned| poisoned.into_inner());
1416        match catalog
1417            .as_ref()
1418            .and_then(|catalog| catalog.ntranslate(msgctxt, singular, n))
1419        {
1420            Some(translation) => translation.to_string(),
1421            // English: one, or many (including none).
1422            None if n == 1 => singular.to_string(),
1423            None => plural.to_string(),
1424        }
1425    })
1426}
1427
1428/// Fills the placeholders of a translated text, as Slint's `@tr` does:
1429/// `{}` takes the next argument, `{0}` the first, `{name}` the one with that
1430/// name; `{{` and `}}` are braces. A placeholder without its argument stays
1431/// as it is.
1432pub fn format(template: &str, args: &[(&str, &dyn fmt::Display)]) -> String {
1433    use std::fmt::Write;
1434    let mut out = String::with_capacity(template.len() + 16);
1435    let mut next = 0;
1436    let mut rest = template;
1437    while let Some(at) = rest.find(['{', '}']) {
1438        out.push_str(&rest[..at]);
1439        let tail = &rest[at..];
1440        if tail.starts_with("{{") || tail.starts_with("}}") {
1441            out.push_str(&tail[..1]);
1442            rest = &tail[2..];
1443            continue;
1444        }
1445        if let Some(after) = tail.strip_prefix('}') {
1446            out.push('}');
1447            rest = after;
1448            continue;
1449        }
1450        let Some(end) = tail.find('}') else {
1451            out.push_str(tail);
1452            rest = "";
1453            break;
1454        };
1455        let name = tail[1..end].trim();
1456        let arg = if name.is_empty() {
1457            next += 1;
1458            args.get(next - 1)
1459        } else if let Ok(index) = name.parse::<usize>() {
1460            args.get(index)
1461        } else {
1462            args.iter().find(|(arg_name, _)| *arg_name == name)
1463        };
1464        match arg {
1465            Some((_, value)) => {
1466                let _ = write!(out, "{value}");
1467            }
1468            None => out.push_str(&tail[..=end]),
1469        }
1470        rest = &tail[end + 1..];
1471    }
1472    out.push_str(rest);
1473    out
1474}
1475
1476/// Translates a text written in English, in the current language of this
1477/// library (see the [module documentation](crate::i18n)):
1478///
1479/// - `tr!("text")`, `tr!("text with {}", value)`, `tr!("{name}", name = value)`;
1480/// - `tr!("context" => "text", …)` for a text that needs a context to be
1481///   translated right (the same English word for different things);
1482/// - `tr!("one file" | "{n} files" % count, …)` for a text with a number:
1483///   each language has its own forms, and `{n}` is the number.
1484///
1485/// It returns a `String`. Arguments are formatted with `Display`.
1486#[macro_export]
1487macro_rules! tr {
1488    ($msgctxt:tt => $singular:tt | $plural:tt % $n:expr $(, $($args:tt)*)?) => {{
1489        let n = $n;
1490        $crate::i18n::format(
1491            &$crate::i18n::ntranslate(::core::option::Option::Some($msgctxt), $singular, $plural, n as u64),
1492            $crate::__tr_args!([] $($($args)*)? , n = n),
1493        )
1494    }};
1495    ($msgctxt:tt => $msgid:tt $(, $($args:tt)*)?) => {
1496        $crate::i18n::format(
1497            &$crate::i18n::translate(::core::option::Option::Some($msgctxt), $msgid),
1498            $crate::__tr_args!([] $($($args)*)?),
1499        )
1500    };
1501    ($singular:tt | $plural:tt % $n:expr $(, $($args:tt)*)?) => {{
1502        let n = $n;
1503        $crate::i18n::format(
1504            &$crate::i18n::ntranslate(::core::option::Option::None, $singular, $plural, n as u64),
1505            $crate::__tr_args!([] $($($args)*)? , n = n),
1506        )
1507    }};
1508    ($msgid:tt $(, $($args:tt)*)?) => {
1509        $crate::i18n::format(
1510            &$crate::i18n::translate(::core::option::Option::None, $msgid),
1511            $crate::__tr_args!([] $($($args)*)?),
1512        )
1513    };
1514}
1515
1516/// The arguments of [`tr!`] as `(name, value)` pairs; not public API.
1517#[doc(hidden)]
1518#[macro_export]
1519macro_rules! __tr_args {
1520    ([$($done:tt)*]) => { &[$($done)*] };
1521    ([$($done:tt)*] ,) => { &[$($done)*] };
1522    ([$($done:tt)*] , $($rest:tt)+) => { $crate::__tr_args!([$($done)*] $($rest)+) };
1523    ([$($done:tt)*] $name:ident = $value:expr , $($rest:tt)*) => {
1524        $crate::__tr_args!([$($done)* (::core::stringify!($name), &$value as &dyn ::core::fmt::Display),] , $($rest)*)
1525    };
1526    ([$($done:tt)*] $name:ident = $value:expr) => {
1527        $crate::__tr_args!([$($done)* (::core::stringify!($name), &$value as &dyn ::core::fmt::Display),])
1528    };
1529    ([$($done:tt)*] $name:ident , $($rest:tt)*) => {
1530        $crate::__tr_args!([$($done)* (::core::stringify!($name), &$name as &dyn ::core::fmt::Display),] , $($rest)*)
1531    };
1532    ([$($done:tt)*] $name:ident) => {
1533        $crate::__tr_args!([$($done)* (::core::stringify!($name), &$name as &dyn ::core::fmt::Display),])
1534    };
1535    ([$($done:tt)*] $value:expr , $($rest:tt)*) => {
1536        $crate::__tr_args!([$($done)* ("", &$value as &dyn ::core::fmt::Display),] , $($rest)*)
1537    };
1538    ([$($done:tt)*] $value:expr) => {
1539        $crate::__tr_args!([$($done)* ("", &$value as &dyn ::core::fmt::Display),])
1540    };
1541}
1542
1543// ---------------------------------------------------------------------------
1544// Direction and numbers
1545// ---------------------------------------------------------------------------
1546
1547/// First strong isolate: starts a run whose direction comes from its first
1548/// letter, without changing the order of the text around it.
1549const FSI: char = '\u{2068}';
1550/// Pop directional isolate: ends the run [`FSI`] started.
1551const PDI: char = '\u{2069}';
1552
1553/// `text` for insertion into a translated text: in a right-to-left
1554/// language it is isolated (U+2068 … U+2069), so that a file name, a path or
1555/// a number with its unit keeps its own order and does not reorder the text
1556/// around it. In left-to-right languages it is returned as it is.
1557pub fn isolate(text: impl fmt::Display) -> String {
1558    isolate_for(current(), text)
1559}
1560
1561/// [`isolate`] for a given language.
1562pub fn isolate_for(language: &Language, text: impl fmt::Display) -> String {
1563    if language.is_rtl() {
1564        format!("{FSI}{text}{PDI}")
1565    } else {
1566        text.to_string()
1567    }
1568}
1569
1570/// Separately translated sentences as one message, one after the other:
1571/// with a space between them, except after a sentence that ends in
1572/// full-width punctuation (`。`, `!`, `?`, a full-width closing bracket),
1573/// which Chinese and Japanese follow without a space. Empty sentences are
1574/// left out.
1575///
1576/// Build a message from whole sentences this way rather than with
1577/// `push(' ')` or `join(" ")`: then each sentence is translated on its own
1578/// and the space follows the writing of the language, including when one of
1579/// the sentences falls back to English.
1580pub fn join_sentences<S: AsRef<str>>(sentences: impl IntoIterator<Item = S>) -> String {
1581    /// Ends of a sentence after which Chinese and Japanese put no space.
1582    const FULL_WIDTH_ENDS: [char; 14] = [
1583        '。', '。', '.', '!', '?', ')', '」', '』', '】', '〕', '〉', '》', ']', '}',
1584    ];
1585    let mut text = String::new();
1586    for sentence in sentences {
1587        let sentence = sentence.as_ref().trim();
1588        if sentence.is_empty() {
1589            continue;
1590        }
1591        if !text.is_empty() && !text.ends_with(FULL_WIDTH_ENDS) {
1592            text.push(' ');
1593        }
1594        text.push_str(sentence);
1595    }
1596    text
1597}
1598
1599/// `value` with `decimals` digits after the decimal separator of the
1600/// current language (`1,50` in German, `1.50` in English).
1601pub fn format_decimal(value: f64, decimals: usize) -> String {
1602    format_decimal_for(current(), value, decimals)
1603}
1604
1605/// [`format_decimal`] for a given language.
1606pub fn format_decimal_for(language: &Language, value: f64, decimals: usize) -> String {
1607    let text = format!("{value:.decimals$}");
1608    if language.decimal_separator == '.' {
1609        text
1610    } else {
1611        text.replacen('.', &language.decimal_separator.to_string(), 1)
1612    }
1613}
1614
1615/// Reads a number a user typed: with the current language's decimal
1616/// separator, or with `.`, `,` or the Arabic decimal sign (people type what
1617/// they are used to), in Western, Arabic-Indic or Persian digits.
1618///
1619/// What could as well be a number with a thousands separator is refused
1620/// rather than guessed: two separators (`1.234,5`), and a whole number
1621/// written with the language's thousands separator (`1,600` where the
1622/// decimal separator is not `,`, `1.600` where it is). `0,25`, `2,5` and
1623/// `1234,5` are read as decimals in every language.
1624pub fn parse_decimal(text: &str) -> Option<f64> {
1625    parse_decimal_for(current(), text)
1626}
1627
1628/// [`parse_decimal`] for a given language.
1629pub fn parse_decimal_for(language: &Language, text: &str) -> Option<f64> {
1630    // Arabic-Indic and Persian digits, as their keyboards type them.
1631    let text: String = text
1632        .trim()
1633        .chars()
1634        .map(|c| match c {
1635            '\u{0660}'..='\u{0669}' => char::from(b'0' + (c as u32 - 0x0660) as u8),
1636            '\u{06F0}'..='\u{06F9}' => char::from(b'0' + (c as u32 - 0x06F0) as u8),
1637            c => c,
1638        })
1639        .collect();
1640    let thousands = if language.decimal_separator == ',' {
1641        '.'
1642    } else {
1643        ','
1644    };
1645    if has_thousands(&text, thousands) {
1646        return None;
1647    }
1648    let normalized: String = text
1649        .chars()
1650        .map(|c| match c {
1651            // The Arabic decimal sign is never a thousands separator (that is
1652            // U+066C, which is refused like any other character).
1653            '\u{066B}' | ',' => '.',
1654            '\u{2212}' => '-',
1655            c if c == language.decimal_separator => '.',
1656            c => c,
1657        })
1658        .collect();
1659    if normalized.matches('.').count() > 1 {
1660        return None;
1661    }
1662    normalized.parse::<f64>().ok().filter(|v| v.is_finite())
1663}
1664
1665/// Whether `text` (in Western digits) is a whole number written with one
1666/// `separator` between its thousands (`1,600`, `-12,500`): one to three
1667/// digits, the first not 0, then the separator and three digits.
1668fn has_thousands(text: &str, separator: char) -> bool {
1669    let text = text.strip_prefix(['+', '-', '\u{2212}']).unwrap_or(text);
1670    let Some((thousands, rest)) = text.split_once(separator) else {
1671        return false;
1672    };
1673    let digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
1674    (1..=3).contains(&thousands.len())
1675        && !thousands.starts_with('0')
1676        && digits(thousands)
1677        && rest.len() == 3
1678        && digits(rest)
1679}
1680
1681#[cfg(test)]
1682mod tests {
1683    use super::*;
1684
1685    #[test]
1686    fn the_languages_are_complete_and_ordered() {
1687        assert_eq!(LANGUAGES.len(), 31);
1688        assert!(source().is_source());
1689        let tags: Vec<&str> = translations().iter().map(|l| l.tag).collect();
1690        let mut sorted = tags.clone();
1691        sorted.sort_unstable();
1692        // Slint bundles catalogs in the order of their folder names; this
1693        // order is that one.
1694        assert_eq!(tags, sorted);
1695        for expected in [
1696            "zh-Hans", "ru", "pt-BR", "fr", "de", "es", "sl", "cs", "uk", "ar", "hi", "el", "ja",
1697            "ko", "it", "tr", "pl", "zh-Hant", "nl", "id", "vi", "th", "fa", "sv", "ro", "hu",
1698            "nb", "fi", "da", "he",
1699        ] {
1700            assert!(by_tag(expected).is_some(), "{expected} is missing");
1701        }
1702        let rtl: Vec<&str> = LANGUAGES
1703            .iter()
1704            .filter(|l| l.is_rtl())
1705            .map(|l| l.tag)
1706            .collect();
1707        assert_eq!(rtl, ["ar", "fa", "he"]);
1708    }
1709
1710    #[test]
1711    fn tags_are_matched_without_regard_to_case_and_separator() {
1712        assert_eq!(by_tag("pt-BR").unwrap().tag, "pt-BR");
1713        assert_eq!(by_tag("pt_br").unwrap().tag, "pt-BR");
1714        assert_eq!(by_tag("ZH-hant").unwrap().tag, "zh-Hant");
1715        assert_eq!(by_tag(" en ").unwrap().tag, "en");
1716        assert!(by_tag("pt").is_none());
1717        assert!(by_tag("xx").is_none());
1718    }
1719
1720    fn negotiated(locale: &str) -> Option<&'static str> {
1721        negotiate(locale).map(|l| l.tag)
1722    }
1723
1724    #[test]
1725    fn system_locales_are_negotiated() {
1726        // POSIX names, with codesets and modifiers.
1727        assert_eq!(negotiated("de_DE.UTF-8"), Some("de"));
1728        assert_eq!(negotiated("de_AT.UTF-8@euro"), Some("de"));
1729        assert_eq!(negotiated("fr_CA"), Some("fr"));
1730        assert_eq!(negotiated("es-419"), Some("es"));
1731        assert_eq!(negotiated("en-GB"), Some("en"));
1732        assert_eq!(negotiated("ja_JP.eucJP"), Some("ja"));
1733        assert_eq!(negotiated("ar-EG"), Some("ar"));
1734        assert_eq!(negotiated("fa_IR"), Some("fa"));
1735        assert_eq!(negotiated("he_IL.UTF-8"), Some("he"));
1736        // Old codes.
1737        assert_eq!(negotiated("iw_IL"), Some("he"));
1738        assert_eq!(negotiated("in_ID"), Some("id"));
1739        assert_eq!(negotiated("no_NO"), Some("nb"));
1740        assert_eq!(negotiated("nb-NO"), Some("nb"));
1741        assert_eq!(negotiated("nn_NO"), Some("nb"));
1742        // No preference, and languages without a translation.
1743        assert_eq!(negotiated("C"), None);
1744        assert_eq!(negotiated("POSIX"), None);
1745        assert_eq!(negotiated("C.UTF-8"), None);
1746        assert_eq!(negotiated(""), None);
1747        assert_eq!(negotiated("sr_RS"), None);
1748        assert_eq!(negotiated("ms_MY"), None);
1749        assert_eq!(negotiated("x-klingon"), None);
1750        // An extension does not change the language.
1751        assert_eq!(negotiated("de-DE-u-co-phonebk"), Some("de"));
1752    }
1753
1754    #[test]
1755    fn chinese_follows_the_script() {
1756        for (locale, tag) in [
1757            ("zh_CN.UTF-8", "zh-Hans"),
1758            ("zh-SG", "zh-Hans"),
1759            ("zh-MY", "zh-Hans"),
1760            ("zh", "zh-Hans"),
1761            ("zh-Hans", "zh-Hans"),
1762            ("zh-Hans-HK", "zh-Hans"),
1763            ("zh_TW", "zh-Hant"),
1764            ("zh-HK", "zh-Hant"),
1765            ("zh_MO.UTF-8", "zh-Hant"),
1766            ("zh-Hant", "zh-Hant"),
1767            ("zh-Hant-CN", "zh-Hant"),
1768        ] {
1769            assert_eq!(negotiated(locale), Some(tag), "{locale}");
1770        }
1771        // Chinese in another script (pinyin) has no translation.
1772        assert_eq!(negotiated("zh-Latn"), None);
1773    }
1774
1775    #[test]
1776    fn portuguese_is_brazilian_only_where_it_is_written_so() {
1777        assert_eq!(negotiated("pt_BR.UTF-8"), Some("pt-BR"));
1778        assert_eq!(negotiated("pt-BR"), Some("pt-BR"));
1779        assert_eq!(negotiated("pt"), Some("pt-BR"));
1780        for european in ["pt_PT", "pt-PT", "pt-AO", "pt_MZ.UTF-8"] {
1781            assert_eq!(negotiated(european), None, "{european}");
1782        }
1783        // The next preference is taken instead.
1784        assert_eq!(
1785            negotiate_first(["pt-PT", "es-ES", "en-US"]).map(|l| l.tag),
1786            Some("es")
1787        );
1788        assert_eq!(negotiate_first(["pt-PT"]).map(|l| l.tag), None);
1789    }
1790
1791    #[test]
1792    fn another_script_is_not_taken_for_the_translation() {
1793        assert_eq!(negotiated("ru-Cyrl"), Some("ru"));
1794        assert_eq!(negotiated("ru-Latn"), None);
1795        assert_eq!(negotiated("ar-Latn"), None);
1796        assert_eq!(negotiated("de-Latn-CH"), Some("de"));
1797    }
1798
1799    #[test]
1800    fn plural_counts_are_read_from_the_header() {
1801        assert_eq!(by_tag("ja").unwrap().plural_count(), 1);
1802        assert_eq!(by_tag("de").unwrap().plural_count(), 2);
1803        assert_eq!(by_tag("ru").unwrap().plural_count(), 3);
1804        assert_eq!(by_tag("sl").unwrap().plural_count(), 4);
1805        assert_eq!(by_tag("ar").unwrap().plural_count(), 6);
1806    }
1807
1808    /// A catalog for `language` with one plural text whose forms say their
1809    /// index, and one translated, one untranslated and one fuzzy text.
1810    fn sample_catalog(language: &'static Language) -> Catalog {
1811        let mut po = empty_catalog(language, "test");
1812        po.push_str("\nmsgid \"Close\"\nmsgstr \"[Close]\"\n");
1813        po.push_str("\nmsgctxt \"Menu\"\nmsgid \"Close\"\nmsgstr \"[Menu Close]\"\n");
1814        po.push_str("\nmsgid \"Untranslated\"\nmsgstr \"\"\n");
1815        po.push_str("\n#, fuzzy\nmsgid \"Fuzzy\"\nmsgstr \"[Fuzzy]\"\n");
1816        po.push_str("\nmsgid \"{n} file\"\nmsgid_plural \"{n} files\"\n");
1817        for form in 0..language.plural_count() {
1818            po.push_str(&format!("msgstr[{form}] \"form {form}: {{n}}\"\n"));
1819        }
1820        Catalog::parse(language, po.as_bytes()).unwrap()
1821    }
1822
1823    #[test]
1824    fn catalogs_translate_and_fall_back_to_english() {
1825        let catalog = sample_catalog(by_tag("de").unwrap());
1826        assert_eq!(catalog.len(), 3);
1827        assert_eq!(catalog.translate(None, "Close"), Some("[Close]"));
1828        assert_eq!(
1829            catalog.translate(Some("Menu"), "Close"),
1830            Some("[Menu Close]")
1831        );
1832        // Untranslated, fuzzy and unknown texts are not in the catalog, so
1833        // they show in English (see `the_macro_translates…`).
1834        assert_eq!(catalog.translate(None, "Untranslated"), None);
1835        assert_eq!(catalog.translate(None, "Fuzzy"), None);
1836        assert_eq!(catalog.translate(None, "Unknown"), None);
1837        assert_eq!(catalog.translate(Some("Other"), "Close"), None);
1838        assert_eq!(catalog.ntranslate(None, "{n} folder", 5), None);
1839    }
1840
1841    #[test]
1842    fn plural_forms_follow_each_language() {
1843        // The form each number takes, per language (Unicode CLDR).
1844        let cases: &[(&str, &[(u64, usize)])] = &[
1845            ("en", &[(0, 1), (1, 0), (2, 1), (101, 1)]),
1846            ("fr", &[(0, 0), (1, 0), (2, 1), (100, 1)]),
1847            ("pt-BR", &[(0, 0), (1, 0), (2, 1)]),
1848            ("ja", &[(0, 0), (1, 0), (2, 0), (100, 0)]),
1849            (
1850                "ru",
1851                &[
1852                    (1, 0),
1853                    (2, 1),
1854                    (4, 1),
1855                    (5, 2),
1856                    (11, 2),
1857                    (12, 2),
1858                    (21, 0),
1859                    (22, 1),
1860                    (25, 2),
1861                    (111, 2),
1862                ],
1863            ),
1864            ("uk", &[(1, 0), (3, 1), (7, 2), (31, 0)]),
1865            (
1866                "pl",
1867                &[(1, 0), (2, 1), (5, 2), (12, 2), (22, 1), (25, 2), (101, 2)],
1868            ),
1869            ("cs", &[(1, 0), (2, 1), (4, 1), (5, 2), (22, 2)]),
1870            (
1871                "sl",
1872                &[(1, 0), (2, 1), (3, 2), (4, 2), (5, 3), (101, 0), (102, 1)],
1873            ),
1874            (
1875                "ro",
1876                &[(0, 1), (1, 0), (2, 1), (19, 1), (20, 2), (101, 1), (120, 2)],
1877            ),
1878            (
1879                "ar",
1880                &[
1881                    (0, 0),
1882                    (1, 1),
1883                    (2, 2),
1884                    (3, 3),
1885                    (10, 3),
1886                    (11, 4),
1887                    (99, 4),
1888                    (100, 5),
1889                    (102, 5),
1890                    (103, 3),
1891                ],
1892            ),
1893            ("he", &[(1, 0), (2, 1), (20, 1)]),
1894            ("hi", &[(0, 0), (1, 0), (2, 1)]),
1895        ];
1896        for (tag, expected) in cases {
1897            let language = by_tag(tag).unwrap();
1898            let catalog = sample_catalog(language);
1899            for (n, form) in *expected {
1900                let text = catalog.ntranslate(None, "{n} file", *n);
1901                assert_eq!(
1902                    text,
1903                    Some(format!("form {form}: {{n}}").as_str()),
1904                    "{tag} n={n}"
1905                );
1906            }
1907        }
1908    }
1909
1910    #[test]
1911    fn every_language_has_a_valid_plural_rule() {
1912        for language in LANGUAGES {
1913            let catalog = sample_catalog(language);
1914            for n in 0..200 {
1915                let text = catalog.ntranslate(None, "{n} file", n).unwrap_or_default();
1916                let form: usize = text
1917                    .strip_prefix("form ")
1918                    .and_then(|rest| rest.split(':').next())
1919                    .and_then(|form| form.parse().ok())
1920                    .unwrap_or_else(|| panic!("{}: n={n} gave {text:?}", language.tag));
1921                assert!(form < language.plural_count(), "{}: n={n}", language.tag);
1922            }
1923        }
1924    }
1925
1926    #[test]
1927    fn plural_rules_are_read_and_evaluated_as_in_c() {
1928        let rule = |header: &str| PluralRule::from_header(header).unwrap();
1929        // Precedence: comparison over &&, && over ||, % over comparison.
1930        let polish = rule(by_tag("pl").unwrap().plural_forms);
1931        assert_eq!(polish.count(), 3);
1932        assert_eq!(
1933            (0..30).map(|n| polish.form(n)).collect::<Vec<_>>(),
1934            [
1935                2, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2,
1936                2, 2
1937            ]
1938        );
1939        assert_eq!(rule("nplurals=2; plural=n*2-3 > 1+1;").form(3), 1);
1940        assert_eq!(rule("nplurals=2; plural=!(n == 1);").form(1), 0);
1941        assert_eq!(rule("nplurals=3; plural=n/2 % 3;").form(10), 2);
1942        // Division by zero is 0, as gettext has it; forms stay in range.
1943        assert_eq!(rule("nplurals=2; plural=n/0;").form(5), 0);
1944        assert_eq!(rule("nplurals=2; plural=n;").form(9), 1);
1945        // A header without spaces, and with them everywhere.
1946        assert_eq!(rule("nplurals=2;plural=n!=1;").form(2), 1);
1947        assert_eq!(rule(" nplurals = 2 ; plural = ( n != 1 ) ; ").form(1), 0);
1948        for bad in [
1949            "plural=(n != 1);",
1950            "nplurals=2;",
1951            "nplurals=x; plural=0;",
1952            "nplurals=9; plural=0;",
1953            "nplurals=2; plural=(n != 1;",
1954            "nplurals=2; plural=n ? 1;",
1955            "nplurals=2; plural=n $ 1;",
1956            "nplurals=2; plural=n 1;",
1957        ] {
1958            assert!(PluralRule::from_header(bad).is_err(), "accepted {bad:?}");
1959        }
1960    }
1961
1962    #[test]
1963    fn a_broken_catalog_is_an_error() {
1964        let german = by_tag("de").unwrap();
1965        assert!(Catalog::parse(german, b"").is_err());
1966        assert!(Catalog::parse(german, b"\xff\xfe").is_err());
1967        let bad_rule = "msgid \"\"\nmsgstr \"Plural-Forms: nplurals=2; plural=n +;\\n\"\n";
1968        assert!(Catalog::parse(german, bad_rule.as_bytes()).is_err());
1969        // Windows line ends and a byte order mark are fine.
1970        let crlf = "\u{feff}msgid \"Close\"\r\nmsgstr \"Schließen\"\r\n";
1971        let catalog = Catalog::parse(german, crlf.as_bytes()).unwrap();
1972        assert_eq!(catalog.translate(None, "Close"), Some("Schließen"));
1973        // Without a header, the language's plural rule applies.
1974        let polish = by_tag("pl").unwrap();
1975        let headerless = "msgid \"{n} file\"\nmsgid_plural \"{n} files\"\n\
1976                          msgstr[0] \"plik\"\nmsgstr[1] \"pliki\"\nmsgstr[2] \"plików\"\n";
1977        let catalog = Catalog::parse(polish, headerless.as_bytes()).unwrap();
1978        assert_eq!(catalog.ntranslate(None, "{n} file", 5), Some("plików"));
1979    }
1980
1981    #[test]
1982    fn a_malformed_catalog_is_an_error_not_a_panic() {
1983        let german = by_tag("de").unwrap();
1984        // Each of these makes rspolib 0.1.2 panic.
1985        for broken in [
1986            "msgstr \"x\"\n",
1987            "\"\n",
1988            "# comment\n\"continued\"\n",
1989            "msgid_plural \"x\"\n",
1990            "msgid \"a\"\nmsgstr \"b\"\nmsgstr \"c\"\n",
1991        ] {
1992            assert!(
1993                Catalog::parse(german, format!("msgid \"\"\n{broken}").as_bytes()).is_err()
1994                    || Catalog::parse(german, broken.as_bytes()).is_err(),
1995                "accepted {broken:?}"
1996            );
1997            let _ = check_catalog(german, broken, None);
1998        }
1999        assert!(!reading_catalog());
2000    }
2001
2002    #[test]
2003    fn translations_may_reorder_anonymous_placeholders() {
2004        let japanese = by_tag("ja").unwrap();
2005        let po = empty_catalog(japanese, "t")
2006            + "\nmsgid \"{} of {}\"\nmsgstr \"{1} 件中 {0} 件\"\n"
2007            + "\nmsgid \"{} slides\"\nmsgstr \"{} 枚\"\n";
2008        let report = check_catalog(japanese, &po, None);
2009        assert!(report.problems.is_empty(), "{report:?}");
2010        let wrong =
2011            empty_catalog(japanese, "t") + "\nmsgid \"{} of {}\"\nmsgstr \"{1} 件中 {2} 件\"\n";
2012        assert!(!check_catalog(japanese, &wrong, None).problems.is_empty());
2013        // The formatter fills them in that order.
2014        let args: &[(&str, &dyn fmt::Display)] = &[("", &12), ("", &340)];
2015        assert_eq!(format("{1} 件中 {0} 件", args), "340 件中 12 件");
2016    }
2017
2018    #[test]
2019    fn catalogs_are_found_in_conventional_folders() {
2020        let dir = std::env::temp_dir().join(format!("eov-i18n-folders-{}", std::process::id()));
2021        let traditional = by_tag("zh-Hant").unwrap();
2022        let folder = dir.join("zh_TW").join("LC_MESSAGES");
2023        std::fs::create_dir_all(&folder).unwrap();
2024        std::fs::write(folder.join("demo.po"), empty_catalog(traditional, "demo")).unwrap();
2025        assert_eq!(
2026            find_catalog(&dir, "demo", traditional),
2027            Some(folder.join("demo.po"))
2028        );
2029        assert!(find_catalog(&dir, "demo", by_tag("zh-Hans").unwrap()).is_none());
2030        assert_eq!(
2031            by_tag("nb").unwrap().catalog_folders(),
2032            ["nb", "nb_NO", "no"]
2033        );
2034        assert_eq!(
2035            by_tag("pt-BR").unwrap().catalog_folders(),
2036            ["pt-BR", "pt_BR"]
2037        );
2038        let _ = std::fs::remove_dir_all(&dir);
2039    }
2040
2041    #[test]
2042    fn placeholders_are_found() {
2043        let found: Vec<&str> = placeholders("{} of {0}, {name} {{not}} {n}")
2044            .into_iter()
2045            .collect();
2046        assert_eq!(found, ["{0}", "{name}", "{n}", "{}"]);
2047        assert!(placeholders("no { placeholder").is_empty());
2048    }
2049
2050    #[test]
2051    fn catalogs_are_checked_against_the_language_and_the_template() {
2052        let polish = by_tag("pl").unwrap();
2053        let template = "msgid \"\"\nmsgstr \"\"\n\"Content-Type: text/plain; charset=UTF-8\\n\"\n\
2054            \nmsgid \"Open {}\"\nmsgstr \"\"\n\
2055            \nmsgid \"One slide\"\nmsgid_plural \"{n} slides\"\nmsgstr[0] \"\"\nmsgstr[1] \"\"\n\
2056            \nmsgid \"Close\"\nmsgstr \"\"\n";
2057        let good = empty_catalog(polish, "t")
2058            + "\nmsgid \"Open {}\"\nmsgstr \"Otwórz {}\"\n"
2059            + "\nmsgid \"One slide\"\nmsgid_plural \"{n} slides\"\n\
2060               msgstr[0] \"Jeden preparat\"\nmsgstr[1] \"{n} preparaty\"\nmsgstr[2] \"{n} preparatów\"\n"
2061            + "\nmsgid \"Close\"\nmsgstr \"Zamknij\"\n";
2062        let report = check_catalog(polish, &good, Some(template));
2063        assert!(report.is_complete(), "{report:?}");
2064        assert_eq!(report.translated, 3);
2065
2066        let bad = empty_catalog(polish, "t").replace("Language: pl", "Language: de")
2067            + "\nmsgid \"Open {}\"\nmsgstr \"Otwórz {x}\"\n"
2068            + "\nmsgid \"One slide\"\nmsgid_plural \"{n} slides\"\n\
2069               msgstr[0] \"Jeden preparat\"\nmsgstr[1] \"preparaty\"\n"
2070            + "\n#, fuzzy\nmsgid \"Gone\"\nmsgstr \"Nie ma\"\n";
2071        let report = check_catalog(polish, &bad, Some(template));
2072        assert!(!report.is_complete());
2073        assert_eq!(report.fuzzy, 1);
2074        assert_eq!(report.missing, ["Close"]);
2075        assert_eq!(report.obsolete, ["Gone"]);
2076        let problems = report.problems.join("\n");
2077        assert!(problems.contains("Language: de"), "{problems}");
2078        assert!(problems.contains("adds"), "{problems}");
2079        assert!(problems.contains("loses"), "{problems}");
2080        assert!(problems.contains("2 plural forms"), "{problems}");
2081        assert!(problems.contains("does not show {n}"), "{problems}");
2082    }
2083
2084    /// A catalog may write its language's plural rule in any spelling (as
2085    /// Weblate, msginit or Poedit write them); another rule, another number
2086    /// of forms and a header without a rule are reported.
2087    #[test]
2088    fn plural_rules_are_checked_by_the_forms_they_give() {
2089        let check = |tag: &str, forms: Option<&str>| {
2090            let language = by_tag(tag).unwrap();
2091            let header = empty_catalog(language, "t");
2092            let header = match forms {
2093                Some(forms) => header.replace(language.plural_forms, forms),
2094                None => header.replace(
2095                    &format!("\"Plural-Forms: {}\\n\"\n", language.plural_forms),
2096                    "",
2097                ),
2098            };
2099            assert_eq!(header.contains("Plural-Forms"), forms.is_some());
2100            check_catalog(
2101                language,
2102                &format!("{header}\nmsgid \"Close\"\nmsgstr \"x\"\n"),
2103                None,
2104            )
2105            .problems
2106        };
2107        for (tag, forms) in [
2108            ("de", "nplurals=2; plural=(n != 1);"),
2109            ("de", "nplurals=2; plural=n != 1;"),
2110            ("fr", "nplurals=2; plural=n>1"),
2111            (
2112                "cs",
2113                "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;",
2114            ),
2115            (
2116                "ru",
2117                "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);",
2118            ),
2119            ("ja", "nplurals=1; plural=0;"),
2120        ] {
2121            assert_eq!(
2122                check(tag, Some(forms)),
2123                Vec::<String>::new(),
2124                "{tag}: {forms}"
2125            );
2126        }
2127        for (tag, forms) in [
2128            ("pl", "nplurals=2; plural=(n != 1);"),
2129            ("de", "nplurals=3; plural=(n != 1);"),
2130            ("fr", "nplurals=2; plural=(n != 1);"),
2131            ("de", "nplurals=2; plural=n !! 1;"),
2132        ] {
2133            let problems = check(tag, Some(forms));
2134            assert!(
2135                problems.len() == 1 && problems[0].contains("Plural-Forms"),
2136                "{tag}: {forms}: {problems:?}"
2137            );
2138        }
2139        let problems = check("ro", None);
2140        assert!(
2141            problems.len() == 1 && problems[0].contains("no Plural-Forms"),
2142            "{problems:?}"
2143        );
2144        // Two spellings of one rule give the same forms; other rules do not.
2145        let rule = |forms: &str| PluralRule::from_header(forms).unwrap();
2146        assert!(
2147            rule("nplurals=2; plural=n>1;").same_forms(&rule(by_tag("fr").unwrap().plural_forms))
2148        );
2149        assert!(!rule("nplurals=2; plural=n!=1;").same_forms(&rule("nplurals=2; plural=n>1;")));
2150        let catalog = Catalog::parse(by_tag("fr").unwrap(), b"msgid \"\"\nmsgstr \"\"\n").unwrap();
2151        assert!(
2152            catalog
2153                .plural_rule()
2154                .same_forms(&rule("nplurals=2; plural=(n > 1);"))
2155        );
2156    }
2157
2158    #[test]
2159    fn catalogs_are_found_under_either_spelling() {
2160        let dir = std::env::temp_dir().join(format!("eov-i18n-test-{}", std::process::id()));
2161        let brazil = by_tag("pt-BR").unwrap();
2162        let posix = dir.join("pt_BR").join("LC_MESSAGES");
2163        std::fs::create_dir_all(&posix).unwrap();
2164        std::fs::write(
2165            posix.join("demo.po"),
2166            empty_catalog(brazil, "demo") + "\nmsgid \"Close\"\nmsgstr \"Fechar\"\n",
2167        )
2168        .unwrap();
2169        let catalog = Catalog::load(&dir, "demo", brazil).unwrap().unwrap();
2170        assert_eq!(catalog.translate(None, "Close"), Some("Fechar"));
2171        assert!(
2172            Catalog::load(&dir, "demo", by_tag("de").unwrap())
2173                .unwrap()
2174                .is_none()
2175        );
2176        assert!(Catalog::load(&dir, "demo", source()).unwrap().is_none());
2177        std::fs::write(posix.join("demo.po"), "msgid \"unterminated").unwrap();
2178        assert!(Catalog::load(&dir, "demo", brazil).is_err());
2179        let _ = std::fs::remove_dir_all(&dir);
2180    }
2181
2182    #[test]
2183    fn isolation_applies_to_right_to_left_languages_only() {
2184        let arabic = by_tag("ar").unwrap();
2185        assert_eq!(
2186            isolate_for(arabic, "slide.svs"),
2187            "\u{2068}slide.svs\u{2069}"
2188        );
2189        assert_eq!(isolate_for(by_tag("de").unwrap(), "slide.svs"), "slide.svs");
2190    }
2191
2192    #[test]
2193    fn decimals_follow_the_language() {
2194        let german = by_tag("de").unwrap();
2195        let persian = by_tag("fa").unwrap();
2196        assert_eq!(format_decimal_for(german, 1.5, 2), "1,50");
2197        assert_eq!(format_decimal_for(source(), 1.5, 2), "1.50");
2198        assert_eq!(format_decimal_for(persian, 0.25, 2), "0\u{066B}25");
2199        assert_eq!(format_decimal_for(german, -3.0, 0), "-3");
2200        for (text, value) in [
2201            ("1,5", Some(1.5)),
2202            ("1.5", Some(1.5)),
2203            (" 2 ", Some(2.0)),
2204            ("1.234,5", None),
2205            ("", None),
2206            ("abc", None),
2207            ("inf", None),
2208        ] {
2209            assert_eq!(parse_decimal_for(german, text), value, "{text:?}");
2210        }
2211        assert_eq!(parse_decimal_for(persian, "0\u{066B}25"), Some(0.25));
2212        assert_eq!(parse_decimal_for(source(), "0,25"), Some(0.25));
2213        // Persian and Arabic-Indic digits, as their keyboards type them,
2214        // and the Arabic decimal sign in any language.
2215        assert_eq!(parse_decimal_for(persian, "۰٫۲۵"), Some(0.25));
2216        assert_eq!(parse_decimal_for(by_tag("ar").unwrap(), "٠٫٢٥"), Some(0.25));
2217        assert_eq!(parse_decimal_for(persian, "0٫۲۵"), Some(0.25));
2218        assert_eq!(parse_decimal_for(persian, "۵۰"), Some(50.0));
2219        assert_eq!(parse_decimal_for(source(), "0\u{066B}5"), Some(0.5));
2220        assert_eq!(parse_decimal_for(source(), "\u{2212}2"), Some(-2.0));
2221        // The Arabic thousands separator is not a decimal point.
2222        assert_eq!(parse_decimal_for(persian, "1\u{066C}000"), None);
2223    }
2224
2225    #[test]
2226    fn thousands_are_refused_rather_than_read_as_decimals() {
2227        let english = source();
2228        let german = by_tag("de").unwrap();
2229        let persian = by_tag("fa").unwrap();
2230        for text in [
2231            "1,600",
2232            "10,000",
2233            "-12,500",
2234            "+100,000",
2235            "\u{2212}1,250",
2236            "۱,۶۰۰",
2237        ] {
2238            assert_eq!(parse_decimal_for(english, text), None, "{text:?}");
2239        }
2240        assert_eq!(parse_decimal_for(persian, "1,600"), None);
2241        // What cannot be a thousands separator is still a decimal comma.
2242        for (text, value) in [
2243            ("0,25", 0.25),
2244            ("2,5", 2.5),
2245            ("0,125", 0.125),
2246            ("1234,5", 1234.5),
2247            ("1,60", 1.6),
2248            ("1,6000", 1.6),
2249        ] {
2250            assert_eq!(parse_decimal_for(english, text), Some(value), "{text:?}");
2251        }
2252        // Where the decimal separator is a comma, it is the point.
2253        assert_eq!(parse_decimal_for(german, "1,600"), Some(1.6));
2254        assert_eq!(parse_decimal_for(german, "1.600"), None);
2255        assert_eq!(parse_decimal_for(german, "0.125"), Some(0.125));
2256        assert_eq!(parse_decimal_for(german, "1.5"), Some(1.5));
2257        assert_eq!(parse_decimal_for(english, "1.600"), Some(1.6));
2258    }
2259
2260    #[test]
2261    fn sentences_are_joined_as_their_script_writes_them() {
2262        assert_eq!(
2263            join_sentences(["One slide.", "Two layers."]),
2264            "One slide. Two layers."
2265        );
2266        assert_eq!(
2267            join_sentences(["已处理 1 张切片。", "跳过了 1 张切片(见 slides.csv)。"]),
2268            "已处理 1 张切片。跳过了 1 张切片(见 slides.csv)。"
2269        );
2270        assert_eq!(
2271            join_sentences(["スライドを処理しました!", "Check the file."]),
2272            "スライドを処理しました!Check the file."
2273        );
2274        // A sentence that fell back to English keeps its space.
2275        assert_eq!(
2276            join_sentences(["Check the file.", "已处理。"]),
2277            "Check the file. 已处理。"
2278        );
2279        assert_eq!(
2280            join_sentences(vec![String::new(), "Alone.".into(), " ".into()]),
2281            "Alone."
2282        );
2283        assert_eq!(join_sentences(Vec::<String>::new()), "");
2284    }
2285
2286    /// Tests that change this library's language or catalog run one at a
2287    /// time.
2288    fn global_language() -> std::sync::MutexGuard<'static, ()> {
2289        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2290        LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
2291    }
2292
2293    #[test]
2294    fn placeholders_are_filled_as_slint_does() {
2295        let file = "a.svs";
2296        let args: &[(&str, &dyn fmt::Display)] = &[("", &file), ("n", &3)];
2297        assert_eq!(format("{} has {n} levels", args), "a.svs has 3 levels");
2298        assert_eq!(format("{1}/{0}", args), "3/a.svs");
2299        assert_eq!(format("{{literal}} {}", args), "{literal} a.svs");
2300        assert_eq!(format("}} {", args), "} {");
2301        // A placeholder without an argument is shown, not dropped.
2302        assert_eq!(format("{missing} {5}", args), "{missing} {5}");
2303        assert_eq!(format("no placeholders", &[]), "no placeholders");
2304    }
2305
2306    #[test]
2307    fn the_macro_translates_with_the_current_catalog() {
2308        let _guard = global_language();
2309        let german = by_tag("de").unwrap();
2310        let po = empty_catalog(german, "test")
2311            + "\nmsgid \"Open {}\"\nmsgstr \"{} öffnen\"\n"
2312            + "\nmsgctxt \"Menu\"\nmsgid \"Close\"\nmsgstr \"Schließen\"\n"
2313            + "\nmsgid \"One slide in {folder}\"\nmsgid_plural \"{n} slides in {folder}\"\n"
2314            + "msgstr[0] \"Ein Schnitt in {folder}\"\nmsgstr[1] \"{n} Schnitte in {folder}\"\n";
2315        set_catalog(german, Some(Catalog::parse(german, po.as_bytes()).unwrap()));
2316        assert_eq!(current().tag, "de");
2317        let file = "x.svs";
2318        assert_eq!(crate::tr!("Open {}", file), "x.svs öffnen");
2319        assert_eq!(crate::tr!("Menu" => "Close"), "Schließen");
2320        assert_eq!(crate::tr!("Close"), "Close");
2321        let folder = "/data";
2322        assert_eq!(
2323            crate::tr!(
2324                "One slide in {folder}" | "{n} slides in {folder}" % 1,
2325                folder
2326            ),
2327            "Ein Schnitt in /data"
2328        );
2329        assert_eq!(
2330            crate::tr!(
2331                "One slide in {folder}" | "{n} slides in {folder}" % 7_usize,
2332                folder = "/x"
2333            ),
2334            "7 Schnitte in /x"
2335        );
2336        // Untranslated texts are formatted in English.
2337        assert_eq!(crate::tr!("Ctx" => "{} of {}", 1, 2), "1 of 2");
2338        assert_eq!(crate::tr!("One item" | "{n} items" % 2), "2 items");
2339        // A catalog of another language than the one chosen is not used.
2340        set_catalog(
2341            by_tag("fr").unwrap(),
2342            Some(Catalog::parse(german, po.as_bytes()).unwrap()),
2343        );
2344        assert_eq!(crate::tr!("Menu" => "Close"), "Close");
2345        set_catalog(source(), None);
2346        assert_eq!(crate::tr!("Open {}", file), "Open x.svs");
2347        assert_eq!(current().tag, "en");
2348    }
2349
2350    #[test]
2351    fn the_current_language_is_per_library() {
2352        let _guard = global_language();
2353        let before = current();
2354        set_current(by_tag("he").unwrap());
2355        assert!(is_rtl());
2356        assert_eq!(isolate("a.svs"), "\u{2068}a.svs\u{2069}");
2357        set_current(by_tag("de").unwrap());
2358        assert_eq!(format_decimal(2.25, 1), "2,2");
2359        assert_eq!(parse_decimal("2,5"), Some(2.5));
2360        set_current(source());
2361        assert!(!is_rtl());
2362        set_current(before);
2363    }
2364
2365    /// Back to English, without a catalog, when a test ends (also when it
2366    /// fails).
2367    struct BackToEnglish;
2368
2369    impl Drop for BackToEnglish {
2370        fn drop(&mut self) {
2371            set_catalog(source(), None);
2372        }
2373    }
2374
2375    #[test]
2376    fn texts_are_written_in_english_inside_in_english() {
2377        let _guard = global_language();
2378        let _english = BackToEnglish;
2379        let persian = by_tag("fa").unwrap();
2380        let po = empty_catalog(persian, "test")
2381            + "\nmsgid \"Open {}\"\nmsgstr \"باز کردن {}\"\n"
2382            + "\nmsgctxt \"Menu\"\nmsgid \"Close\"\nmsgstr \"بستن\"\n"
2383            + "\nmsgid \"One slide\"\nmsgid_plural \"{n} slides\"\n"
2384            + "msgstr[0] \"{n} اسلاید\"\nmsgstr[1] \"{n} اسلاید\"\n";
2385        set_catalog(
2386            persian,
2387            Some(Catalog::parse(persian, po.as_bytes()).unwrap()),
2388        );
2389        let write = || crate::tr!("Open {}", isolate("a.svs"));
2390        assert_eq!(write(), "باز کردن \u{2068}a.svs\u{2069}");
2391        let english = in_english(|| {
2392            assert!(current().is_source());
2393            assert!(!is_rtl());
2394            assert_eq!(crate::tr!("Menu" => "Close"), "Close");
2395            assert_eq!(crate::tr!("One slide" | "{n} slides" % 1), "One slide");
2396            assert_eq!(crate::tr!("One slide" | "{n} slides" % 0), "0 slides");
2397            assert_eq!(format_decimal(2.5, 1), "2.5");
2398            // Nested calls: English until the outer one ends.
2399            assert_eq!(in_english(write), "Open a.svs");
2400            assert!(current().is_source());
2401            write()
2402        });
2403        assert_eq!(english, "Open a.svs");
2404        // The interface's language again, which did not change meanwhile.
2405        assert_eq!(current().tag, "fa");
2406        assert_eq!(write(), "باز کردن \u{2068}a.svs\u{2069}");
2407        assert_eq!(crate::tr!("One slide" | "{n} slides" % 1), "1 اسلاید");
2408        assert_eq!(format_decimal(2.5, 1), "2\u{066B}5");
2409        // Numbers a user typed are read as in English, too.
2410        set_current(by_tag("de").unwrap());
2411        assert_eq!(parse_decimal("1.600"), None);
2412        assert_eq!(in_english(|| parse_decimal("1.600")), Some(1.6));
2413        assert_eq!(
2414            in_english(|| join_sentences(["Eins.", "Zwei."])),
2415            "Eins. Zwei."
2416        );
2417    }
2418
2419    #[test]
2420    fn english_ends_when_the_writing_panics() {
2421        let _guard = global_language();
2422        let _english = BackToEnglish;
2423        set_current(by_tag("he").unwrap());
2424        let result = std::panic::catch_unwind(|| {
2425            in_english(|| {
2426                assert!(!is_rtl());
2427                panic!("the writing failed")
2428            })
2429        });
2430        assert!(result.is_err());
2431        assert!(is_rtl());
2432        assert_eq!(isolate("a.svs"), "\u{2068}a.svs\u{2069}");
2433    }
2434
2435    #[test]
2436    fn english_is_written_on_this_thread_only() {
2437        let _guard = global_language();
2438        let _english = BackToEnglish;
2439        set_current(by_tag("he").unwrap());
2440        in_english(|| {
2441            let other = std::thread::spawn(|| {
2442                // With `thread-local-language`, each thread has its own
2443                // language; without, this is the library's (already he).
2444                set_current(by_tag("he").unwrap());
2445                (is_rtl(), isolate("x"))
2446            })
2447            .join()
2448            .unwrap();
2449            assert_eq!(other, (true, "\u{2068}x\u{2069}".to_string()));
2450            assert!(!is_rtl());
2451        });
2452        assert!(is_rtl());
2453    }
2454
2455    #[test]
2456    fn shown_and_english_texts_are_written_by_the_same_code() {
2457        let _guard = global_language();
2458        let _english = BackToEnglish;
2459        let german = by_tag("de").unwrap();
2460        let po = empty_catalog(german, "test")
2461            + "\nmsgid \"{} of {}\"\nmsgstr \"{} von {}\"\n"
2462            + "\nmsgid \"{n} tile could not be read\"\nmsgid_plural \"{n} tiles could not be read\"\n"
2463            + "msgstr[0] \"{n} Kachel war unlesbar\"\nmsgstr[1] \"{n} Kacheln waren unlesbar\"\n";
2464        set_catalog(german, Some(Catalog::parse(german, po.as_bytes()).unwrap()));
2465        let (shown, english) =
2466            shown_and_english(|| crate::tr!("{} of {}", format_decimal(1.5, 1), 3));
2467        assert_eq!(shown, "1,5 von 3");
2468        assert_eq!(english, "1.5 of 3");
2469        let failed = 2;
2470        assert_eq!(
2471            shown_and_english(|| crate::tr!(
2472                "{n} tile could not be read" | "{n} tiles could not be read" % failed
2473            )),
2474            (
2475                "2 Kacheln waren unlesbar".to_string(),
2476                "2 tiles could not be read".to_string()
2477            )
2478        );
2479        // Only the text is made in English: the language stays.
2480        assert_eq!(current().tag, "de");
2481        // In English, both are the same.
2482        set_catalog(source(), None);
2483        assert_eq!(
2484            shown_and_english(|| crate::tr!("{} of {}", 1, 2)),
2485            ("1 of 2".to_string(), "1 of 2".to_string())
2486        );
2487    }
2488}