1use 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#[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 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 pub const fn as_base(mut self) -> Self {
39 self.base = true;
40 self
41 }
42}
43
44pub 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#[derive(Debug, Default)]
63pub(crate) struct Resolve {
64 pub hooked: bool,
66 pub answers: HashMap<String, Option<String>>,
68 pub pending: BTreeMap<String, Json>,
70}
71
72#[derive(Debug)]
73struct Inner {
74 catalog: RwLock<Catalog>,
75 missing: Mutex<BTreeMap<String, BTreeSet<String>>>,
77 resolve: Mutex<Resolve>,
78 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#[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
113pub type Args<'a> = [(&'a str, FluentValue<'a>)];
115
116#[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
135fn 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
149pub(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 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 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 pub fn add(&self, locale: &str, source: &str) -> Result<(), String> {
212 self.write(|c| c.add(locale, source))
213 }
214
215 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 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 pub fn overridden(&self) -> Vec<(String, String)> {
239 self.read(|c| c.overridden().to_vec())
240 }
241
242 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 pub fn set_locale(&self, tag: &str) {
282 self.write(|c| c.set_locale(tag));
283 }
284
285 pub fn locale(&self) -> String {
287 self.read(|c| c.locale().to_string())
288 }
289
290 pub fn chain(&self) -> Vec<String> {
292 self.read(|c| c.chain().to_vec())
293 }
294
295 pub fn locales(&self) -> Vec<String> {
297 self.read(|c| c.locales().map(String::from).collect())
298 }
299
300 pub fn keys(&self, locale: &str) -> BTreeSet<String> {
302 self.read(|c| c.keys(locale))
303 }
304
305 pub fn generation(&self) -> u64 {
308 *lock(&self.inner.generation)
309 }
310
311 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 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 pub fn t(&self, key: &str, args: &Args<'_>) -> String {
357 self.text(key, "", args)
358 }
359
360 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 pub fn missing(&self) -> BTreeMap<String, BTreeSet<String>> {
370 lock(&self.inner.missing).clone()
371 }
372
373 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 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 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 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#[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 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 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 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}