Skip to main content

egui_pop_i18n/
i18n.rs

1//! [`I18n`]: the catalogues an application shows, shared between the
2//! plugin, the interface's strings and the lookup helpers.
3
4use std::collections::{BTreeMap, BTreeSet, HashMap};
5use std::path::Path;
6use std::sync::{Arc, Mutex, PoisonError, RwLock};
7
8use egui_pop_core::strings::Arg;
9use fluent_bundle::{FluentArgs, FluentValue};
10use serde_json::{Map, Value as Json, json};
11
12use crate::catalog::Catalog;
13use crate::locale::{self, ENGLISH};
14
15/// One catalogue file built into the application: its locale, a name
16/// for messages, and its Fluent source (usually `include_str!`).
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct Catalogue {
19    pub locale: &'static str,
20    pub name: &'static str,
21    pub source: &'static str,
22    /// A base catalogue (egui-pop's own): one added after it may override
23    /// its messages, with a warning, instead of being refused.
24    pub base: bool,
25}
26
27impl Catalogue {
28    pub const fn new(locale: &'static str, name: &'static str, source: &'static str) -> Self {
29        Self {
30            locale,
31            name,
32            source,
33            base: false,
34        }
35    }
36
37    /// As a base catalogue (see [`Catalogue::base`]).
38    pub const fn as_base(mut self) -> Self {
39        self.base = true;
40        self
41    }
42}
43
44/// egui-pop's own catalogues: the interface's strings and what its
45/// plugins declare, in English and French.
46pub const EGUI_POP: &[Catalogue] = &[
47    Catalogue::new(
48        "en",
49        "egui-pop.ftl",
50        include_str!("../locales/en/egui-pop.ftl"),
51    )
52    .as_base(),
53    Catalogue::new(
54        "fr",
55        "egui-pop.ftl",
56        include_str!("../locales/fr/egui-pop.ftl"),
57    )
58    .as_base(),
59];
60
61/// A lookup waiting for the `i18n.resolve` step, or its answer.
62#[derive(Debug, Default)]
63pub(crate) struct Resolve {
64    /// Some plugin hooks the step: lookups go through it.
65    pub hooked: bool,
66    /// What the step answered, by lookup.
67    pub answers: HashMap<String, Option<String>>,
68    /// Lookups asked since the last frame, by their arguments.
69    pub pending: BTreeMap<String, Json>,
70}
71
72#[derive(Debug)]
73struct Inner {
74    catalog: RwLock<Catalog>,
75    /// Keys looked up and not found in the locale's own language.
76    missing: Mutex<BTreeMap<String, BTreeSet<String>>>,
77    resolve: Mutex<Resolve>,
78    /// Bumped whenever the text shown may change (locale, catalogues).
79    generation: Mutex<u64>,
80}
81
82fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
83    m.lock().unwrap_or_else(PoisonError::into_inner)
84}
85
86/// The application's catalogues and its locale. Cheap to clone: clones
87/// share them.
88///
89/// ```
90/// use egui_pop_i18n::{I18n, args};
91///
92/// let i18n = I18n::new("fr");
93/// i18n.add("fr", "files = { $count ->\n    [one] { $count } fichier\n   *[other] { $count } fichiers\n}\n").unwrap();
94/// i18n.add("en", "files = { $count ->\n    [one] { $count } file\n   *[other] { $count } files\n}\n").unwrap();
95/// assert_eq!(i18n.t("files", &args![count = 1]), "1 fichier");
96/// assert_eq!(i18n.t("files", &args![count = 1500]), "1\u{202f}500 fichiers");
97/// i18n.set_locale("en");
98/// assert_eq!(i18n.t("files", &args![count = 0]), "0 files");
99/// // Missing everywhere: the key itself.
100/// assert_eq!(i18n.t("nowhere", &[]), "nowhere");
101/// ```
102#[derive(Clone, Debug)]
103pub struct I18n {
104    inner: Arc<Inner>,
105}
106
107impl Default for I18n {
108    fn default() -> Self {
109        Self::new(ENGLISH)
110    }
111}
112
113/// Arguments of a lookup, by name.
114pub type Args<'a> = [(&'a str, FluentValue<'a>)];
115
116/// Builds lookup arguments: `args![count = 3, name = "Ada"]`.
117#[macro_export]
118macro_rules! args {
119    ($($name:ident = $value:expr),* $(,)?) => {
120        [$((stringify!($name), $crate::FluentValue::from($value))),*]
121    };
122}
123
124fn fluent_args<'a>(args: &'a Args<'a>) -> Option<FluentArgs<'a>> {
125    if args.is_empty() {
126        return None;
127    }
128    let mut out = FluentArgs::new();
129    for (k, v) in args {
130        out.set(*k, v.clone());
131    }
132    Some(out)
133}
134
135/// Arguments as JSON, for the `i18n.resolve` step.
136fn args_json(args: &Args<'_>) -> Json {
137    let mut m = Map::new();
138    for (k, v) in args {
139        let v = match v {
140            FluentValue::Number(n) => json!(n.value),
141            FluentValue::String(s) => json!(s),
142            _ => Json::Null,
143        };
144        m.insert((*k).to_string(), v);
145    }
146    Json::Object(m)
147}
148
149/// JSON arguments back to Fluent's.
150pub(crate) fn json_args(args: &Json) -> Vec<(String, FluentValue<'static>)> {
151    args.as_object()
152        .map(|m| {
153            m.iter()
154                .map(|(k, v)| {
155                    let v = match v {
156                        Json::Number(n) => {
157                            crate::format::fluent_number(n.as_f64().unwrap_or_default())
158                        }
159                        Json::String(s) => FluentValue::from(s.clone()),
160                        other => FluentValue::from(other.to_string()),
161                    };
162                    (k.clone(), v)
163                })
164                .collect()
165        })
166        .unwrap_or_default()
167}
168
169impl I18n {
170    /// No catalogue, in `locale`.
171    pub fn new(locale: &str) -> Self {
172        Self {
173            inner: Arc::new(Inner {
174                catalog: RwLock::new(Catalog::new(locale)),
175                missing: Mutex::new(BTreeMap::new()),
176                resolve: Mutex::new(Resolve::default()),
177                generation: Mutex::new(0),
178            }),
179        }
180    }
181
182    /// egui-pop's own catalogues ([`EGUI_POP`]), in `locale`.
183    pub fn with_egui_pop(locale: &str) -> Self {
184        let i = Self::new(locale);
185        i.add_catalogues(EGUI_POP)
186            .expect("egui-pop's own catalogues load");
187        i
188    }
189
190    fn read<R>(&self, f: impl FnOnce(&Catalog) -> R) -> R {
191        f(&self
192            .inner
193            .catalog
194            .read()
195            .unwrap_or_else(PoisonError::into_inner))
196    }
197
198    fn write<R>(&self, f: impl FnOnce(&mut Catalog) -> R) -> R {
199        let r = f(&mut self
200            .inner
201            .catalog
202            .write()
203            .unwrap_or_else(PoisonError::into_inner));
204        *lock(&self.inner.generation) += 1;
205        lock(&self.inner.resolve).answers.clear();
206        r
207    }
208
209    /// Adds Fluent source to a locale. Refused, with nothing added, when
210    /// it does not parse or defines a message already there.
211    pub fn add(&self, locale: &str, source: &str) -> Result<(), String> {
212        self.write(|c| c.add(locale, source))
213    }
214
215    /// Adds a plugin's Fluent source: every message must belong to
216    /// `owner` (see [`crate::catalog::owned_by`]).
217    pub fn add_owned(&self, owner: &str, locale: &str, source: &str) -> Result<(), String> {
218        self.write(|c| c.add_owned(owner, locale, source))
219    }
220
221    /// Adds catalogues built into the application.
222    pub fn add_catalogues(&self, catalogues: &[Catalogue]) -> Result<(), String> {
223        for c in catalogues {
224            self.write(|cat| {
225                if c.base {
226                    cat.add_base(c.locale, c.source)
227                } else {
228                    cat.add(c.locale, c.source)
229                }
230            })
231            .map_err(|e| format!("{}/{}: {e}", c.locale, c.name))?;
232        }
233        Ok(())
234    }
235
236    /// egui-pop's messages an application's catalogue overrode: (locale,
237    /// id). The plugin publishes each as an `i18n.overridden` warning.
238    pub fn overridden(&self) -> Vec<(String, String)> {
239        self.read(|c| c.overridden().to_vec())
240    }
241
242    /// Reads `dir/<locale>/*.ftl` over what is loaded: their messages
243    /// replace those of the same id (translators try their work without
244    /// rebuilding). Returns how many files were read; a missing
245    /// directory reads none.
246    pub fn add_dir(&self, dir: &Path) -> Result<usize, String> {
247        let Ok(entries) = std::fs::read_dir(dir) else {
248            return Ok(0);
249        };
250        let mut locales: Vec<_> = entries
251            .filter_map(|e| e.ok().map(|e| e.path()))
252            .filter(|p| p.is_dir())
253            .collect();
254        locales.sort();
255        let mut n = 0;
256        for ldir in locales {
257            let tag = ldir
258                .file_name()
259                .and_then(|n| n.to_str())
260                .unwrap_or_default()
261                .to_string();
262            let mut files: Vec<_> = std::fs::read_dir(&ldir)
263                .map_err(|e| format!("{}: {e}", ldir.display()))?
264                .filter_map(|e| e.ok().map(|e| e.path()))
265                .filter(|p| p.extension().is_some_and(|e| e == "ftl"))
266                .collect();
267            files.sort();
268            for f in files {
269                let source =
270                    std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?;
271                self.write(|c| c.add_overriding(&tag, &source))
272                    .map_err(|e| format!("{}: {e}", f.display()))?;
273                n += 1;
274            }
275        }
276        Ok(n)
277    }
278
279    /// Switches the locale (`fr`, `fr_FR.UTF-8`, `x-pseudo`); a tag
280    /// naming no language selects English.
281    pub fn set_locale(&self, tag: &str) {
282        self.write(|c| c.set_locale(tag));
283    }
284
285    /// The current locale.
286    pub fn locale(&self) -> String {
287        self.read(|c| c.locale().to_string())
288    }
289
290    /// The locales a lookup tries now, in order.
291    pub fn chain(&self) -> Vec<String> {
292        self.read(|c| c.chain().to_vec())
293    }
294
295    /// The locales that have a catalogue.
296    pub fn locales(&self) -> Vec<String> {
297        self.read(|c| c.locales().map(String::from).collect())
298    }
299
300    /// Every key a locale's catalogue defines.
301    pub fn keys(&self, locale: &str) -> BTreeSet<String> {
302        self.read(|c| c.keys(locale))
303    }
304
305    /// Changes whenever the text shown may change: a locale switched, a
306    /// catalogue added. Caches of translated text compare it.
307    pub fn generation(&self) -> u64 {
308        *lock(&self.inner.generation)
309    }
310
311    /// The text of `key` in the current locale, along its chain and
312    /// English; `None` when no catalogue has it. Goes through the
313    /// `i18n.resolve` step when a plugin hooks it, and counts a key the
314    /// locale's own language lacks as missing.
315    pub fn get(&self, key: &str, args: &Args<'_>) -> Option<String> {
316        let fargs = fluent_args(args);
317        let (locale, text, translated) = self.read(|c| {
318            (
319                c.locale().to_string(),
320                c.get(key, fargs.as_ref()),
321                c.translated(key),
322            )
323        });
324        if !translated {
325            lock(&self.inner.missing)
326                .entry(locale.clone())
327                .or_default()
328                .insert(key.to_string());
329        }
330        let mut r = lock(&self.inner.resolve);
331        if !r.hooked {
332            return text;
333        }
334        let asked = json!({ "key": key, "locale": locale, "args": args_json(args) });
335        let id = asked.to_string();
336        if let Some(answer) = r.answers.get(&id) {
337            return answer.clone();
338        }
339        r.pending.insert(id, asked);
340        text
341    }
342
343    /// The text of `key`, else `english` (a Fluent pattern when there
344    /// are arguments), else the key itself.
345    pub fn text(&self, key: &str, english: &str, args: &Args<'_>) -> String {
346        match self.get(key, args) {
347            Some(t) => t,
348            None => {
349                let fargs = fluent_args(args);
350                self.read(|c| c.text(key, english, fargs.as_ref()))
351            }
352        }
353    }
354
355    /// The text of `key`, else the key itself.
356    pub fn t(&self, key: &str, args: &Args<'_>) -> String {
357        self.text(key, "", args)
358    }
359
360    /// The text of `key` in one locale, without the step: what the
361    /// `i18n.resolve` step does by default.
362    pub fn get_in(&self, locale: &str, key: &str, args: &Args<'_>) -> Option<String> {
363        let fargs = fluent_args(args);
364        self.read(|c| c.get_in(locale, key, fargs.as_ref()))
365    }
366
367    /// Keys looked up and missing in each locale's own language (they
368    /// showed English or the key), since the last [`I18n::clear_missing`].
369    pub fn missing(&self) -> BTreeMap<String, BTreeSet<String>> {
370        lock(&self.inner.missing).clone()
371    }
372
373    /// Forgets the missing keys seen so far.
374    pub fn clear_missing(&self) {
375        lock(&self.inner.missing).clear();
376    }
377
378    pub(crate) fn resolve(&self) -> std::sync::MutexGuard<'_, Resolve> {
379        lock(&self.inner.resolve)
380    }
381
382    /// Whether lookups go through the `i18n.resolve` step.
383    pub(crate) fn set_hooked(&self, hooked: bool) {
384        let mut r = self.resolve();
385        if r.hooked != hooked {
386            r.hooked = hooked;
387            r.answers.clear();
388            r.pending.clear();
389            drop(r);
390            *lock(&self.inner.generation) += 1;
391        }
392    }
393
394    /// Answers from the step, then the text shown changes.
395    pub(crate) fn answer(&self, answers: Vec<(String, Option<String>)>) {
396        if answers.is_empty() {
397            return;
398        }
399        self.resolve().answers.extend(answers);
400        *lock(&self.inner.generation) += 1;
401    }
402
403    /// The locales that have a catalogue (English always), each with
404    /// its own name: what the language setting offers.
405    pub fn offered(&self) -> Vec<(String, String)> {
406        let mut out: Vec<(String, String)> = self
407            .locales()
408            .into_iter()
409            .map(|l| {
410                let name = locale::autonym(&l);
411                (l, name)
412            })
413            .collect();
414        if !out.iter().any(|(l, _)| l == ENGLISH) {
415            out.insert(0, (ENGLISH.into(), locale::autonym(ENGLISH)));
416        }
417        out
418    }
419}
420
421/// The interface's strings (`egui_pop_core::strings`) read from an
422/// [`I18n`], in one locale: installed in the egui context by the plugin,
423/// again whenever the locale changes.
424#[derive(Debug)]
425pub struct Provider {
426    i18n: I18n,
427    language: String,
428}
429
430impl Provider {
431    pub fn new(i18n: I18n) -> Self {
432        let language = i18n.locale();
433        Self { i18n, language }
434    }
435}
436
437impl egui_pop_core::strings::Strings for Provider {
438    fn get(&self, key: &str) -> Option<String> {
439        self.i18n.get(key, &[])
440    }
441
442    fn get_args(&self, key: &str, args: &[(&str, Arg<'_>)]) -> Option<String> {
443        // Text stays text, even "2026" or "1e3": only what the caller
444        // passed as a number is formatted (and selects plurals).
445        let args: Vec<(&str, FluentValue<'_>)> = args
446            .iter()
447            .map(|(k, v)| {
448                let v = match v {
449                    Arg::Num(n) => crate::format::fluent_number(*n),
450                    Arg::Str(s) => FluentValue::from(*s),
451                };
452                (*k, v)
453            })
454            .collect();
455        self.i18n.get(key, &args)
456    }
457
458    fn language(&self) -> &str {
459        &self.language
460    }
461
462    fn number(&self, value: f64, decimals: usize) -> Option<String> {
463        let options = fluent_bundle::types::FluentNumberOptions {
464            minimum_fraction_digits: Some(decimals),
465            maximum_fraction_digits: Some(decimals),
466            ..Default::default()
467        };
468        Some(crate::format::number_with(&self.language, value, &options))
469    }
470
471    fn quantity(&self, number: &str, unit: &str) -> Option<String> {
472        Some(crate::format::quantity(&self.language, number, unit))
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479
480    const FR: &str = r"
481panel-graph =
482    .title = Graphe
483images-selected =
484    { $count ->
485        [one] { $count } image sélectionnée
486       *[other] { $count } images sélectionnées
487    }
488";
489
490    fn i18n() -> I18n {
491        let i = I18n::new("fr-CA");
492        i.add("fr", FR).unwrap();
493        i.add("fr-CA", "panel-graph =\n    .title = Graphe (CA)\n")
494            .unwrap();
495        i.add("en", "panel-graph =\n    .title = Graph\nonly-en = Only\n")
496            .unwrap();
497        i
498    }
499
500    #[test]
501    fn the_chain_falls_back_to_the_parent_then_english_then_the_key() {
502        let i = i18n();
503        assert_eq!(i.t("panel-graph.title", &[]), "Graphe (CA)");
504        i.set_locale("fr");
505        assert_eq!(i.t("panel-graph.title", &[]), "Graphe");
506        assert_eq!(i.t("only-en", &[]), "Only");
507        assert_eq!(i.text("nowhere", "Code English", &[]), "Code English");
508        assert_eq!(i.t("nowhere", &[]), "nowhere");
509        i.set_locale("de");
510        assert_eq!(i.t("panel-graph.title", &[]), "Graph");
511        let missing = i.missing();
512        assert!(missing["fr"].contains("only-en"), "{missing:?}");
513        assert!(missing["fr"].contains("nowhere"));
514        assert!(!missing["fr"].contains("panel-graph.title"));
515        assert!(missing["de"].contains("panel-graph.title"));
516    }
517
518    #[test]
519    fn the_provider_writes_numbers_as_the_locale_does() {
520        use egui_pop_core::strings::Strings as _;
521        let fr = Provider::new(I18n::new("fr"));
522        assert_eq!(fr.number(1234.5, 2).as_deref(), Some("1\u{202f}234,50"));
523        assert_eq!(fr.number(-0.26, 1).as_deref(), Some("-0,3"));
524        let en = Provider::new(I18n::new("en"));
525        assert_eq!(en.number(1234.6, 0).as_deref(), Some("1,235"));
526        // The space before a unit is the locale's too.
527        assert_eq!(fr.quantity("1,50", "EV").as_deref(), Some("1,50\u{202f}EV"));
528        assert_eq!(en.quantity("50", "%").as_deref(), Some("50 %"));
529    }
530
531    #[test]
532    fn plurals_follow_the_locale() {
533        let i = i18n();
534        i.set_locale("fr");
535        let english = "{ $count ->\n    [one] { $count } image selected\n   *[other] { $count } images selected\n}";
536        assert_eq!(
537            i.text("images-selected", english, &args![count = 0]),
538            "0 image sélectionnée"
539        );
540        assert_eq!(
541            i.text("images-selected", english, &args![count = 2]),
542            "2 images sélectionnées"
543        );
544        i.set_locale("en");
545        assert_eq!(
546            i.text("images-selected", english, &args![count = 1]),
547            "1 image selected"
548        );
549        assert_eq!(
550            i.text("images-selected", english, &args![count = 0]),
551            "0 images selected"
552        );
553    }
554
555    #[test]
556    fn an_applications_catalogue_overrides_egui_pops_and_says_so() {
557        static APP: &[Catalogue] = &[Catalogue::new(
558            "fr",
559            "app.ftl",
560            "egui-pop-cancel = Laisser tomber\napp-hello = Salut\n",
561        )];
562        let i = I18n::with_egui_pop("fr");
563        assert!(i.overridden().is_empty());
564        i.add_catalogues(APP).unwrap();
565        assert_eq!(i.t("egui-pop-cancel", &[]), "Laisser tomber");
566        assert_eq!(i.t("app-hello", &[]), "Salut");
567        assert_eq!(
568            i.overridden(),
569            vec![("fr".to_string(), "egui-pop-cancel".to_string())]
570        );
571        // The application's own keys, twice: still refused.
572        let e = i.add("fr", "app-hello = Encore\n").unwrap_err();
573        assert!(e.contains("already defined"), "{e}");
574        let e = i.add("fr", "egui-pop-cancel = Encore\n").unwrap_err();
575        assert!(e.contains("already defined"), "{e}");
576    }
577
578    #[test]
579    fn a_plugin_adds_only_its_own_messages() {
580        let i = i18n();
581        i.add_owned("acme", "fr", "command-acme-run =\n    .title = Lancer\n")
582            .unwrap();
583        let e = i
584            .add_owned("acme", "fr", "panel-graph =\n    .title = Pirate\n")
585            .unwrap_err();
586        assert!(e.contains("does not belong"), "{e}");
587        let e = i
588            .add("fr", "panel-graph =\n    .title = Encore\n")
589            .unwrap_err();
590        assert!(e.contains("already defined"), "{e}");
591        assert!(i.add("fr", "broken = {").is_err());
592    }
593
594    #[test]
595    fn an_override_directory_replaces_messages() {
596        let dir = std::env::temp_dir().join(format!("egui-pop-i18n-{}", std::process::id()));
597        std::fs::create_dir_all(dir.join("fr")).unwrap();
598        std::fs::write(
599            dir.join("fr/x.ftl"),
600            "panel-graph =\n    .title = Graphique\n",
601        )
602        .unwrap();
603        let i = i18n();
604        i.set_locale("fr");
605        assert_eq!(i.add_dir(&dir).unwrap(), 1);
606        assert_eq!(i.t("panel-graph.title", &[]), "Graphique");
607        assert_eq!(i.add_dir(&dir.join("none")).unwrap(), 0);
608        std::fs::remove_dir_all(&dir).unwrap();
609    }
610
611    #[test]
612    fn the_pseudo_locale_accents_and_lengthens_english() {
613        let i = i18n();
614        i.set_locale("x-pseudo");
615        let english = "Show all commands";
616        let pseudo = i.text("command-x.title", english, &[]);
617        assert_ne!(pseudo, english);
618        assert!(!pseudo.is_ascii());
619        assert!(pseudo.chars().count() > english.chars().count());
620        assert!(!i.t("panel-graph.title", &[]).contains("Graphe"));
621    }
622
623    #[test]
624    fn egui_pops_catalogues_load() {
625        let i = I18n::with_egui_pop("fr");
626        assert!(i.locales().contains(&"fr".to_string()));
627        assert_eq!(i.t("egui-pop-retry", &[]), "Réessayer");
628    }
629
630    #[test]
631    fn the_provider_formats_numbers_and_keeps_text() {
632        use egui_pop_core::strings::Strings as _;
633        let i = I18n::new("fr");
634        i.add("fr", "n = { $n } éléments\nname = Ouvrir { $name }\n")
635            .unwrap();
636        let p = Provider::new(i);
637        assert_eq!(
638            p.get_args("n", &[("n", Arg::Num(1234.0))]).unwrap(),
639            "1\u{202f}234 éléments"
640        );
641        for name in ["2026", "007", "1e3", "3.14", "-1", "inf", "NaN"] {
642            assert_eq!(
643                p.get_args("name", &[("name", Arg::Str(name))]).unwrap(),
644                format!("Ouvrir {name}")
645            );
646        }
647        assert_eq!(p.language(), "fr");
648    }
649}