1use 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
44pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.i18n");
46pub const SETTING_LANGUAGE: SettingId = SettingId::from_static("appearance.language");
48pub const SYSTEM: &str = "system";
50pub const SETTING_SHOW_KEYS: SettingId = SettingId::from_static("developer.show_keys");
53pub const SHOW_KEYS: PluginId = PluginId::from_static("egui_pop.i18n.show_keys");
55pub const STEP_RESOLVE: StepId = StepId::from_static("i18n.resolve");
57pub const LOCALE_CHANGED: &str = "locale.changed";
59
60static GLOBAL: RwLock<Option<I18n>> = RwLock::new(None);
61
62pub 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
76const INSTALLED: Slot<I18n> = Slot::new("i18n.installed");
78
79pub fn of(ctx: &egui::Context) -> Option<I18n> {
82 INSTALLED.get(ctx)
83}
84
85pub 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
115fn uninstall(ctx: &egui::Context) {
118 INSTALLED.remove(ctx);
119 strings::install(ctx, Arc::new(strings::English));
120 set_global(None);
121}
122
123pub 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
140pub 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
148pub 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 applied: Option<String>,
183 keys: bool,
185 installed: Option<u64>,
187}
188
189#[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 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 pub fn catalogues(mut self, catalogues: &'static [Catalogue]) -> Self {
234 self.catalogues.push(catalogues);
235 self
236 }
237
238 pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
241 self.dir = Some(dir.into());
242 self
243 }
244
245 pub fn env(mut self, var: &str) -> Self {
248 self.env = Some(var.into());
249 self
250 }
251
252 pub fn language(mut self, value: &str) -> Self {
255 self.language = value.into();
256 self
257 }
258
259 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 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 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 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
415fn hooked(app: &AppHandle) -> bool {
417 app.steps()
418 .iter()
419 .any(|s| s.spec.id == STEP_RESOLVE && !s.hooks.is_empty())
420}
421
422fn 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#[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}