Skip to main content

egui_pop_i18n/
plugin.rs

1//! The plugin: [`I18nPlugin`] connects an [`I18n`] to an application.
2//!
3//! - It installs the interface's strings provider
4//!   (`egui_pop_core::strings`), so egui-pop's own text and the titles of
5//!   what plugins declare are translated, and keeps it current.
6//! - It declares the `appearance.language` setting (`system`, then each
7//!   locale with a catalogue, shown by its own name), kept in the host's
8//!   store like every setting. When it changes, the locale switches, the
9//!   `locale.changed` signal (`{ "from", "to", "setting" }`) goes to the
10//!   host's journal, and the next frame shows the new language. `system`
11//!   reads an environment variable first when one is named
12//!   ([`I18nPlugin::env`]), then the system's language.
13//! - It declares the `i18n.resolve` step (ADR 0011): every lookup a
14//!   plugin hooks runs through it, with `{ "key", "locale", "args" }`; a
15//!   before-hook may redirect it (another key or locale), a run-hook
16//!   replace it (its result is the text, `null` for none), an after-hook
17//!   observe it. Without hooks, lookups do not run the step. With hooks,
18//!   each distinct lookup runs it once, at the next frame, and its answer
19//!   is kept until the locale or the catalogues change. [`ShowKeys`] is
20//!   such a hook: it shows keys instead of text.
21//! - It adds the `i18n` debug collector: the locale, its chain, the
22//!   locales, the keys missing per locale; actions `set_locale` and
23//!   `clear_missing`.
24
25use std::path::PathBuf;
26use std::sync::{Arc, Mutex, PoisonError, RwLock};
27
28use egui_pop_api::hooks::On;
29use egui_pop_api::steps::{Outcome, StepSpec};
30use egui_pop_api::zones::{self, Block};
31use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
32use egui_pop_core::debug::FnCollector;
33use egui_pop_core::lock;
34use egui_pop_core::state::Slot;
35use egui_pop_core::strings;
36use egui_pop_model::commands::Origin;
37use egui_pop_model::ids::{BlockId, OwnerId, PluginId, SettingId, StepId};
38use egui_pop_model::values::{Change, Descriptor, Set, Value};
39use serde_json::{Value as Json, json};
40
41use crate::i18n::{Catalogue, I18n, Provider, json_args};
42use crate::locale;
43
44/// The plugin's id.
45pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.i18n");
46/// The language setting: `system` or a locale.
47pub const SETTING_LANGUAGE: SettingId = SettingId::from_static("appearance.language");
48/// The setting's value that follows the system.
49pub const SYSTEM: &str = "system";
50/// Shows keys instead of text, through [`ShowKeys`] when the
51/// application has it.
52pub const SETTING_SHOW_KEYS: SettingId = SettingId::from_static("developer.show_keys");
53/// [`ShowKeys`]' id.
54pub const SHOW_KEYS: PluginId = PluginId::from_static("egui_pop.i18n.show_keys");
55/// The step every hooked lookup runs through.
56pub const STEP_RESOLVE: StepId = StepId::from_static("i18n.resolve");
57/// The signal published when the locale changes.
58pub const LOCALE_CHANGED: &str = "locale.changed";
59
60static GLOBAL: RwLock<Option<I18n>> = RwLock::new(None);
61
62/// The catalogues last installed ([`install`], or a connected plugin; an
63/// empty English one before): what [`crate::tr!`] reads.
64pub fn global() -> I18n {
65    GLOBAL
66        .read()
67        .unwrap_or_else(PoisonError::into_inner)
68        .clone()
69        .unwrap_or_default()
70}
71
72fn set_global(i18n: Option<I18n>) {
73    *GLOBAL.write().unwrap_or_else(PoisonError::into_inner) = i18n;
74}
75
76/// The catalogues installed in a context.
77const INSTALLED: Slot<I18n> = Slot::new("i18n.installed");
78
79/// The catalogues installed in an egui context, by [`install`] or the
80/// plugin.
81pub fn of(ctx: &egui::Context) -> Option<I18n> {
82    INSTALLED.get(ctx)
83}
84
85/// Installs catalogues in an egui context, for an application that does
86/// not use [`App`](egui_pop_api::App) and its [`I18nPlugin`]: [`t`],
87/// [`text`] and [`of`] read them in this context, [`crate::tr!`] reads
88/// them through [`global`], and egui-pop's own text is translated
89/// through a [`Provider`] installed as the context's strings provider.
90/// [`I18nPlugin`] installs its catalogues this way when it connects.
91///
92/// [`I18n`] is shared: a later [`I18n::set_locale`] or
93/// [`I18n::add`] shows at the next lookup, without installing again.
94/// The global is the process's, so the last call wins when several
95/// contexts install different catalogues. The plugin's other duties
96/// (the language setting, the `i18n.resolve` step, `locale.changed`)
97/// are left out: the application sets the locale itself.
98///
99/// ```
100/// use egui_pop_i18n::{I18n, args, install, t, tr};
101///
102/// let i18n = I18n::new("fr");
103/// i18n.add("fr", "hello = Bonjour, { $name } !\n").unwrap();
104/// let ctx = egui::Context::default();
105/// install(&ctx, &i18n);
106/// assert_eq!(t(&ctx, "hello", &args![name = "Ada"]), "Bonjour, Ada !");
107/// assert_eq!(tr!("hello", name = "Ada"), "Bonjour, Ada !");
108/// ```
109pub fn install(ctx: &egui::Context, i18n: &I18n) {
110    INSTALLED.set(ctx, i18n.clone());
111    strings::install(ctx, Arc::new(Provider::new(i18n.clone())));
112    set_global(Some(i18n.clone()));
113}
114
115/// Undoes [`install`]: the context back to the built-in English, the
116/// global back to an empty English catalogue.
117fn uninstall(ctx: &egui::Context) {
118    INSTALLED.remove(ctx);
119    strings::install(ctx, Arc::new(strings::English));
120    set_global(None);
121}
122
123/// The text of `key` in the context's language, with Fluent arguments;
124/// else the key itself. Without catalogues installed ([`install`] or the
125/// plugin), the interface's strings provider answers (or the key shows).
126///
127/// ```
128/// use egui_pop_i18n::{args, t};
129///
130/// let ctx = egui::Context::default();
131/// assert_eq!(t(&ctx, "greeting", &args![name = "Ada"]), "greeting");
132/// ```
133pub fn t(ctx: &egui::Context, key: &str, args: &crate::Args<'_>) -> String {
134    match of(ctx) {
135        Some(i) => i.t(key, args),
136        None => strings::lookup(ctx, key, ""),
137    }
138}
139
140/// [`t`] with the English shown when no catalogue has the key.
141pub fn text(ctx: &egui::Context, key: &str, english: &str, args: &crate::Args<'_>) -> String {
142    match of(ctx) {
143        Some(i) => i.text(key, english, args),
144        None => strings::lookup(ctx, key, english),
145    }
146}
147
148/// Switches the application's language through its setting
149/// (`system` or a locale with a catalogue).
150pub fn set_language(app: &AppHandle, value: &str) -> Result<(), String> {
151    lock(&app.store())
152        .set(
153            Set::new(
154                &setting_path(),
155                Change::To(Value::Choice(value.into())),
156                Origin::User,
157            )
158            .by(&OwnerId::from(&PLUGIN)),
159        )
160        .map(|_| ())
161        .map_err(|e| e.to_string())
162}
163
164fn setting_path() -> String {
165    format!("settings/{SETTING_LANGUAGE}")
166}
167
168fn show_keys_path() -> String {
169    format!("settings/{SETTING_SHOW_KEYS}")
170}
171
172fn show_keys_on(app: &AppHandle) -> bool {
173    lock(&app.store())
174        .get(&show_keys_path())
175        .and_then(|e| e.value.as_bool())
176        .unwrap_or(false)
177}
178
179#[derive(Debug, Default)]
180struct Follow {
181    /// The setting's value last applied.
182    applied: Option<String>,
183    /// Whether keys were shown, as last applied.
184    keys: bool,
185    /// The catalogues' generation the provider was installed at.
186    installed: Option<u64>,
187}
188
189/// Translations for an application, as a plugin (see the module).
190///
191/// ```
192/// use egui_pop_api::App;
193/// use egui_pop_i18n::{I18nPlugin, plugin};
194///
195/// let ctx = egui::Context::default();
196/// let app = App::builder().plugin(I18nPlugin::new()).build(&ctx).unwrap();
197/// plugin::set_language(app.handle(), "fr").unwrap();
198/// let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
199///     egui_pop_core::strings::lookup(ui.ctx(), "warm-up", "");
200/// });
201/// out.textures_delta.clear();
202/// ```
203#[derive(Debug)]
204pub struct I18nPlugin {
205    i18n: I18n,
206    catalogues: Vec<&'static [Catalogue]>,
207    dir: Option<PathBuf>,
208    env: Option<String>,
209    language: String,
210    follow: Arc<Mutex<Follow>>,
211}
212
213impl Default for I18nPlugin {
214    fn default() -> Self {
215        Self::new()
216    }
217}
218
219impl I18nPlugin {
220    /// With egui-pop's own catalogues (English and French).
221    pub fn new() -> Self {
222        Self {
223            i18n: I18n::new(locale::ENGLISH),
224            catalogues: vec![crate::i18n::EGUI_POP],
225            dir: None,
226            env: None,
227            language: SYSTEM.into(),
228            follow: Arc::default(),
229        }
230    }
231
232    /// Adds the application's catalogues (loaded at connect).
233    pub fn catalogues(mut self, catalogues: &'static [Catalogue]) -> Self {
234        self.catalogues.push(catalogues);
235        self
236    }
237
238    /// Reads `dir/<locale>/*.ftl` at connect, over the built-in
239    /// catalogues (a missing directory is fine).
240    pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
241        self.dir = Some(dir.into());
242        self
243    }
244
245    /// An environment variable naming a locale, read before the system's
246    /// language when the setting is `system` (`MYAPP_LANG=fr`).
247    pub fn env(mut self, var: &str) -> Self {
248        self.env = Some(var.into());
249        self
250    }
251
252    /// The language setting's default: [`SYSTEM`] (the default) or a
253    /// locale (tests and screenshots pin `en`).
254    pub fn language(mut self, value: &str) -> Self {
255        self.language = value.into();
256        self
257    }
258
259    /// The catalogues, to keep (they are shared).
260    pub fn i18n(&self) -> I18n {
261        self.i18n.clone()
262    }
263}
264
265impl Plugin for I18nPlugin {
266    fn id(&self) -> PluginId {
267        PLUGIN
268    }
269
270    fn title(&self) -> String {
271        "Language".into()
272    }
273
274    fn priority(&self) -> i32 {
275        // Before the plugins whose text it translates are drawn; first
276        // among peers so its setting leads its section.
277        100
278    }
279
280    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
281        let i18n = self.i18n.clone();
282        if i18n.locales().is_empty() {
283            for c in &self.catalogues {
284                i18n.add_catalogues(c).map_err(PluginError::Failed)?;
285            }
286            if let Some(dir) = &self.dir {
287                i18n.add_dir(dir).map_err(PluginError::Failed)?;
288            }
289            // An application's text over egui-pop's: kept, and said.
290            for (locale, key) in i18n.overridden() {
291                ctx.app().publish(
292                    "egui_pop.i18n",
293                    None,
294                    "i18n.overridden",
295                    serde_json::json!({ "locale": locale, "key": key }),
296                );
297            }
298        }
299        let offered = i18n.offered();
300        // Each language shows by its own name, whatever the locale.
301        let names: String = offered
302            .iter()
303            .filter(|(tag, _)| {
304                !i18n
305                    .keys(locale::ENGLISH)
306                    .contains(&strings::setting_choice_key(SETTING_LANGUAGE.as_str(), tag))
307            })
308            .map(|(tag, name)| {
309                format!(
310                    "{} = {name}\n",
311                    strings::setting_choice_key(SETTING_LANGUAGE.as_str(), tag)
312                )
313            })
314            .collect();
315        if !names.is_empty() {
316            i18n.add(locale::ENGLISH, &names)
317                .map_err(PluginError::Failed)?;
318        }
319        let mut choices = vec![SYSTEM.to_string()];
320        choices.extend(offered.into_iter().map(|(tag, _)| tag));
321        let default = if choices.contains(&self.language) {
322            self.language.as_str()
323        } else {
324            SYSTEM
325        };
326        let choices: Vec<&str> = choices.iter().map(String::as_str).collect();
327        ctx.setting(
328            SETTING_LANGUAGE,
329            Descriptor::choice("Language", &choices, default)
330                .description("The language of the interface; System follows the system's."),
331        )?
332        .setting(
333            SETTING_SHOW_KEYS,
334            Descriptor::bool("Show translation keys", false).description(
335                "Shows each text's translation key instead of the text, to find where it comes from.",
336            ),
337        )?;
338        ctx.step(
339            StepSpec::new(
340                STEP_RESOLVE,
341                "A translated text is looked up (`key`, `locale`, `args`); the result is the text, null for none.",
342            )
343            .args(json!({ "key": "egui-pop-retry", "locale": "fr", "args": {} })),
344        )?;
345        let (snap, act) = (i18n.clone(), i18n.clone());
346        let store = ctx.app().store();
347        ctx.collector(
348            FnCollector::new(
349                "i18n",
350                "Translations: the locale, its fallback chain, the locales, the keys missing per locale.",
351            )
352            .snapshot(move |_| {
353                json!({
354                    "locale": snap.locale(),
355                    "chain": snap.chain(),
356                    "locales": snap.locales(),
357                    "missing": snap.missing(),
358                })
359            })
360            .action(
361                "set_locale",
362                "Switches the language setting (`locale`: `system` or a locale).",
363                true,
364                move |_, args| {
365                    let to = args["locale"].as_str().ok_or("`locale` is missing")?;
366                    lock(&store)
367                        .set(
368                            Set::new(
369                                &setting_path(),
370                                Change::To(Value::Choice(to.into())),
371                                Origin::Agent("debug bridge".into()),
372                            )
373                            .by(&OwnerId::from(&PLUGIN)),
374                        )
375                        .map_err(|e| e.to_string())?;
376                    Ok(json!({ "setting": to }))
377                },
378            )
379            .args(json!({ "locale": "fr" }))
380            .action(
381                "clear_missing",
382                "Forgets the missing keys seen so far.",
383                true,
384                move |_, _| {
385                    act.clear_missing();
386                    Ok(Json::Null)
387                },
388            ),
389        )?;
390        let (follow, env, f_i18n) = (self.follow.clone(), self.env.clone(), i18n.clone());
391        ctx.block(
392            zones::OVERLAYS,
393            Block::add(
394                BlockId::from_static("egui_pop.i18n.follow"),
395                95,
396                move |_, app| {
397                    self::follow(app, &f_i18n, &follow, env.as_deref());
398                },
399            ),
400        );
401        for on in [On::Started, On::Connected, On::Disconnected] {
402            let i18n = i18n.clone();
403            ctx.on(on, move |app, _| i18n.set_hooked(hooked(app)));
404        }
405        install(&ctx.app().egui(), &i18n);
406        Ok(())
407    }
408
409    fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
410        uninstall(&ctx.app().egui());
411        *self.follow.lock().unwrap_or_else(PoisonError::into_inner) = Follow::default();
412    }
413}
414
415/// Whether a plugin hooks the `i18n.resolve` step.
416fn hooked(app: &AppHandle) -> bool {
417    app.steps()
418        .iter()
419        .any(|s| s.spec.id == STEP_RESOLVE && !s.hooks.is_empty())
420}
421
422/// Each frame: the setting applied, hooked lookups resolved, the
423/// provider current.
424fn follow(app: &AppHandle, i18n: &I18n, follow: &Mutex<Follow>, env: Option<&str>) {
425    let mut f = follow.lock().unwrap_or_else(PoisonError::into_inner);
426    let setting = lock(&app.store())
427        .get(&setting_path())
428        .and_then(|e| e.value.as_choice().map(str::to_string))
429        .unwrap_or_else(|| SYSTEM.into());
430    if f.applied.as_deref() != Some(setting.as_str()) {
431        let env = env.and_then(|v| std::env::var(v).ok());
432        let chosen = if setting == SYSTEM {
433            locale::choose(env.as_deref(), None, locale::system().as_deref())
434        } else {
435            locale::choose(None, Some(&setting), None)
436        };
437        let from = i18n.locale();
438        if chosen != from {
439            i18n.set_locale(&chosen);
440            app.publish(
441                "egui_pop",
442                None,
443                LOCALE_CHANGED,
444                json!({ "from": from, "to": i18n.locale(), "setting": setting }),
445            );
446        }
447        f.applied = Some(setting);
448    }
449    let keys = show_keys_on(app);
450    if keys != f.keys {
451        f.keys = keys;
452        if app.plugins().iter().any(|p| p.id == SHOW_KEYS) {
453            app.set_plugin_enabled(SHOW_KEYS, keys);
454        }
455    }
456    let pending = std::mem::take(&mut i18n.resolve().pending);
457    let mut answers = Vec::new();
458    for (id, asked) in pending {
459        let lookup = |args: &Json| {
460            let key = args["key"].as_str().unwrap_or_default();
461            let locale = args["locale"].as_str().unwrap_or(locale::ENGLISH);
462            let owned = json_args(&args["args"]);
463            let fargs: Vec<(&str, fluent_bundle::FluentValue<'_>)> =
464                owned.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();
465            i18n.get_in(locale, key, &fargs)
466        };
467        let out = app.step(&STEP_RESOLVE, asked.clone(), |_, args| {
468            Ok(lookup(args).map_or(Json::Null, Json::String))
469        });
470        let answer = match out {
471            Outcome::Done(Ok(Json::String(s))) => Some(s),
472            Outcome::Done(Ok(Json::Null)) => None,
473            Outcome::Done(Ok(other)) => Some(other.to_string()),
474            Outcome::Done(Err(_)) | Outcome::Vetoed { .. } => lookup(&asked),
475        };
476        answers.push((id, answer));
477    }
478    i18n.answer(answers);
479    let generation = i18n.generation();
480    if f.installed != Some(generation) {
481        let ctx = app.egui();
482        install(&ctx, i18n);
483        f.installed = Some(generation);
484        ctx.request_repaint();
485    }
486}
487
488/// A debug aid: every lookup shows its key instead of its text, through
489/// a run-hook on `i18n.resolve`. Connected while the
490/// `developer.show_keys` setting is on.
491#[derive(Clone, Copy, Debug, Default)]
492pub struct ShowKeys;
493
494impl Plugin for ShowKeys {
495    fn id(&self) -> PluginId {
496        SHOW_KEYS
497    }
498
499    fn title(&self) -> String {
500        "Translation keys".into()
501    }
502
503    fn requires(&self) -> Vec<PluginId> {
504        vec![PLUGIN]
505    }
506
507    fn enabled(&self, ctx: &Ctx<'_>) -> bool {
508        show_keys_on(&ctx.app())
509    }
510
511    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
512        ctx.replace(STEP_RESOLVE, |_, args| Ok(args["key"].clone()));
513        Ok(())
514    }
515}