1use std::{
2 collections::HashMap,
3 path::PathBuf,
4};
5
6use fluent::{
7 FluentArgs,
8 FluentBundle,
9 FluentResource,
10};
11use freya_core::prelude::*;
12use unic_langid::LanguageIdentifier;
13
14use crate::error::Error;
15
16#[cfg_attr(test, derive(Debug, PartialEq))]
18pub struct Locale {
19 id: LanguageIdentifier,
20 resource: LocaleResource,
21}
22
23impl Locale {
24 pub fn new_static(id: LanguageIdentifier, str: &'static str) -> Self {
28 Self {
29 id,
30 resource: LocaleResource::Static(str),
31 }
32 }
33
34 pub fn new_dynamic(id: LanguageIdentifier, path: impl Into<PathBuf>) -> Self {
38 Self {
39 id,
40 resource: LocaleResource::Path(path.into()),
41 }
42 }
43}
44
45impl<T> From<(LanguageIdentifier, T)> for Locale
46where
47 T: Into<LocaleResource>,
48{
49 fn from((id, resource): (LanguageIdentifier, T)) -> Self {
50 let resource = resource.into();
51 Self { id, resource }
52 }
53}
54
55#[derive(Debug, PartialEq)]
57pub enum LocaleResource {
58 Static(&'static str),
59
60 Path(PathBuf),
61}
62
63impl LocaleResource {
64 pub fn try_to_resource_string(&self) -> Result<String, Error> {
65 match self {
66 Self::Static(str) => Ok(str.to_string()),
67
68 Self::Path(path) => std::fs::read_to_string(path)
69 .map_err(|e| Error::LocaleResourcePathReadFailed(e.to_string())),
70 }
71 }
72
73 pub fn to_resource_string(&self) -> String {
74 let result = self.try_to_resource_string();
75 match result {
76 Ok(string) => string,
77 Err(err) => panic!("failed to create resource string {self:?}: {err}"),
78 }
79 }
80}
81
82impl From<&'static str> for LocaleResource {
83 fn from(value: &'static str) -> Self {
84 Self::Static(value)
85 }
86}
87
88impl From<PathBuf> for LocaleResource {
89 fn from(value: PathBuf) -> Self {
90 Self::Path(value)
91 }
92}
93
94#[derive(Debug, PartialEq)]
96pub struct I18nConfig {
97 pub id: LanguageIdentifier,
99
100 pub fallback: Option<LanguageIdentifier>,
103
104 pub locale_resources: Vec<LocaleResource>,
106
107 pub locales: HashMap<LanguageIdentifier, usize>,
109}
110
111impl I18nConfig {
112 pub fn new(id: LanguageIdentifier) -> Self {
114 Self {
115 id,
116 fallback: None,
117 locale_resources: Vec::new(),
118 locales: HashMap::new(),
119 }
120 }
121
122 pub fn with_fallback(mut self, fallback: LanguageIdentifier) -> Self {
124 self.fallback = Some(fallback);
125 self
126 }
127
128 pub fn with_locale<T>(mut self, locale: T) -> Self
133 where
134 T: Into<Locale>,
135 {
136 let locale = locale.into();
137 let locale_resources_len = self.locale_resources.len();
138
139 let index = self
140 .locale_resources
141 .iter()
142 .position(|r| *r == locale.resource)
143 .unwrap_or(locale_resources_len);
144
145 if index == locale_resources_len {
146 self.locale_resources.push(locale.resource)
147 };
148
149 self.locales.insert(locale.id, index);
150 self
151 }
152
153 #[cfg(feature = "discovery")]
162 pub fn try_with_auto_locales(self, path: PathBuf) -> Result<Self, Error> {
163 if path.is_dir() {
164 let files = find_ftl_files(&path)?;
165 files
166 .into_iter()
167 .try_fold(self, |acc, file| acc.with_auto_pathbuf(file))
168 } else if is_ftl_file(&path) {
169 self.with_auto_pathbuf(path)
170 } else {
171 Err(Error::InvalidPath(path.to_string_lossy().to_string()))
172 }
173 }
174
175 #[cfg(feature = "discovery")]
176 fn with_auto_pathbuf(self, file: PathBuf) -> Result<Self, Error> {
177 assert!(is_ftl_file(&file));
178
179 let stem = file.file_stem().ok_or_else(|| {
180 Error::InvalidLanguageId(format!("No file stem: '{}'", file.display()))
181 })?;
182
183 let id_str = stem.to_str().ok_or_else(|| {
184 Error::InvalidLanguageId(format!("Cannot convert: {}", stem.to_string_lossy()))
185 })?;
186
187 let id = LanguageIdentifier::from_bytes(id_str.as_bytes())
188 .map_err(|e| Error::InvalidLanguageId(e.to_string()))?;
189
190 Ok(self.with_locale((id, file)))
191 }
192
193 #[cfg(feature = "discovery")]
197 pub fn with_auto_locales(self, path: PathBuf) -> Self {
198 let path_name = path.display().to_string();
199 let result = self.try_with_auto_locales(path);
200 match result {
201 Ok(result) => result,
202 Err(err) => panic!("with_auto_locales must have valid pathbuf {path_name}: {err}",),
203 }
204 }
205}
206
207#[cfg(feature = "discovery")]
208fn find_ftl_files(folder: &PathBuf) -> Result<Vec<PathBuf>, Error> {
209 let ftl_files: Vec<PathBuf> = walkdir::WalkDir::new(folder)
210 .into_iter()
211 .filter_map(|entry| entry.ok())
212 .filter(|entry| is_ftl_file(entry.path()))
213 .map(|entry| entry.path().to_path_buf())
214 .collect();
215
216 Ok(ftl_files)
217}
218
219#[cfg(feature = "discovery")]
220fn is_ftl_file(entry: &std::path::Path) -> bool {
221 entry.is_file() && entry.extension().map(|ext| ext == "ftl").unwrap_or(false)
222}
223
224pub fn use_init_i18n(init: impl FnOnce() -> I18nConfig) -> I18n {
263 use_hook(move || {
264 GlobalContexts::get().insert_context({
265 match I18n::create_global(init()) {
267 Ok(i18n) => i18n,
268 Err(e) => panic!("Failed to create I18n context: {e}"),
269 }
270 })
271 })
272}
273
274#[derive(Clone, Copy)]
286pub struct I18n {
287 selected_language: State<LanguageIdentifier>,
288 fallback_language: State<Option<LanguageIdentifier>>,
289 locale_resources: State<Vec<LocaleResource>>,
290 locales: State<HashMap<LanguageIdentifier, usize>>,
291 active_bundle: State<FluentBundle<FluentResource>>,
292}
293
294impl I18n {
295 pub fn try_get() -> Option<Self> {
299 GlobalContexts::get().try_get_context()
300 }
301
302 #[track_caller]
330 pub fn get() -> Self {
331 GlobalContexts::get().get_context()
332 }
333
334 pub fn create(
343 I18nConfig {
344 id: selected_language,
345 fallback: fallback_language,
346 locale_resources,
347 locales,
348 }: I18nConfig,
349 ) -> Result<Self, Error> {
350 let bundle = try_create_bundle(
351 &selected_language,
352 &fallback_language,
353 &locale_resources,
354 &locales,
355 )?;
356 Ok(Self {
357 selected_language: State::create(selected_language),
358 fallback_language: State::create(fallback_language),
359 locale_resources: State::create(locale_resources),
360 locales: State::create(locales),
361 active_bundle: State::create(bundle),
362 })
363 }
364
365 pub fn create_global(
373 I18nConfig {
374 id: selected_language,
375 fallback: fallback_language,
376 locale_resources,
377 locales,
378 }: I18nConfig,
379 ) -> Result<Self, Error> {
380 let bundle = try_create_bundle(
381 &selected_language,
382 &fallback_language,
383 &locale_resources,
384 &locales,
385 )?;
386 Ok(Self {
387 selected_language: State::create_global(selected_language),
388 fallback_language: State::create_global(fallback_language),
389 locale_resources: State::create_global(locale_resources),
390 locales: State::create_global(locales),
391 active_bundle: State::create_global(bundle),
392 })
393 }
394
395 pub fn try_translate_with_args(
405 &self,
406 msg: &str,
407 args: Option<&FluentArgs>,
408 ) -> Result<String, Error> {
409 let (message_id, attribute_name) = Self::decompose_identifier(msg)?;
410
411 let bundle = self.active_bundle.read();
412
413 let message = bundle
414 .get_message(message_id)
415 .ok_or_else(|| Error::MessageIdNotFound(message_id.into()))?;
416
417 let pattern = if let Some(attribute_name) = attribute_name {
418 let attribute = message
419 .get_attribute(attribute_name)
420 .ok_or_else(|| Error::AttributeIdNotFound(msg.to_string()))?;
421 attribute.value()
422 } else {
423 message
424 .value()
425 .ok_or_else(|| Error::MessagePatternNotFound(message_id.into()))?
426 };
427
428 let mut errors = vec![];
429 let translation = bundle
430 .format_pattern(pattern, args, &mut errors)
431 .to_string();
432
433 (errors.is_empty())
434 .then_some(translation)
435 .ok_or_else(|| Error::FluentErrorsDetected(format!("{errors:#?}")))
436 }
437
438 pub fn decompose_identifier(msg: &str) -> Result<(&str, Option<&str>), Error> {
445 let parts: Vec<&str> = msg.split('.').collect();
446 match parts.as_slice() {
447 [message_id] => Ok((message_id, None)),
448 [message_id, attribute_name] => Ok((message_id, Some(attribute_name))),
449 _ => Err(Error::InvalidMessageId(msg.to_string())),
450 }
451 }
452
453 pub fn translate_with_args(&self, msg: &str, args: Option<&FluentArgs>) -> String {
461 let result = self.try_translate_with_args(msg, args);
462 match result {
463 Ok(translation) => translation,
464 Err(err) => panic!("Failed to translate {msg}: {err}"),
465 }
466 }
467
468 #[inline]
472 pub fn try_translate(&self, msg: &str) -> Result<String, Error> {
473 self.try_translate_with_args(msg, None)
474 }
475
476 pub fn translate(&self, msg: &str) -> String {
484 let result = self.try_translate(msg);
485 match result {
486 Ok(translation) => translation,
487 Err(err) => panic!("Failed to translate {msg}: {err}"),
488 }
489 }
490
491 #[inline]
493 pub fn language(&self) -> LanguageIdentifier {
494 self.selected_language.read().clone()
495 }
496
497 pub fn fallback_language(&self) -> Option<LanguageIdentifier> {
499 self.fallback_language.read().clone()
500 }
501
502 pub fn try_set_language(&mut self, id: LanguageIdentifier) -> Result<(), Error> {
506 *self.selected_language.write() = id;
507 self.try_update_active_bundle()
508 }
509
510 pub fn set_language(&mut self, id: LanguageIdentifier) {
518 let id_name = id.to_string();
519 let result = self.try_set_language(id);
520 match result {
521 Ok(()) => (),
522 Err(err) => panic!("cannot set language {id_name}: {err}"),
523 }
524 }
525
526 pub fn try_set_fallback_language(&mut self, id: LanguageIdentifier) -> Result<(), Error> {
531 self.locales
532 .read()
533 .get(&id)
534 .ok_or_else(|| Error::FallbackMustHaveLocale(id.to_string()))?;
535
536 *self.fallback_language.write() = Some(id);
537 self.try_update_active_bundle()
538 }
539
540 pub fn set_fallback_language(&mut self, id: LanguageIdentifier) {
548 let id_name = id.to_string();
549 let result = self.try_set_fallback_language(id);
550 match result {
551 Ok(()) => (),
552 Err(err) => panic!("cannot set fallback language {id_name}: {err}"),
553 }
554 }
555
556 fn try_update_active_bundle(&mut self) -> Result<(), Error> {
557 let bundle = try_create_bundle(
558 &self.selected_language.peek(),
559 &self.fallback_language.peek(),
560 &self.locale_resources.peek(),
561 &self.locales.peek(),
562 )?;
563
564 self.active_bundle.set(bundle);
565 Ok(())
566 }
567}
568
569fn try_create_bundle(
570 selected_language: &LanguageIdentifier,
571 fallback_language: &Option<LanguageIdentifier>,
572 locale_resources: &[LocaleResource],
573 locales: &HashMap<LanguageIdentifier, usize>,
574) -> Result<FluentBundle<FluentResource>, Error> {
575 let add_resource = move |bundle: &mut FluentBundle<FluentResource>,
576 langid: &LanguageIdentifier,
577 locale_resources: &[LocaleResource]| {
578 if let Some(&i) = locales.get(langid) {
579 let resource = &locale_resources[i];
580 let resource =
581 FluentResource::try_new(resource.try_to_resource_string()?).map_err(|e| {
582 Error::FluentErrorsDetected(format!("resource langid: {langid}\n{e:#?}"))
583 })?;
584 bundle.add_resource_overriding(resource);
585 };
586 Ok(())
587 };
588
589 let mut bundle = FluentBundle::new(vec![selected_language.clone()]);
590 if let Some(fallback_language) = fallback_language {
591 add_resource(&mut bundle, fallback_language, locale_resources)?;
592 }
593
594 let (language, script, region, variants) = selected_language.clone().into_parts();
595 let variants_lang = LanguageIdentifier::from_parts(language, script, region, &variants);
596 let region_lang = LanguageIdentifier::from_parts(language, script, region, &[]);
597 let script_lang = LanguageIdentifier::from_parts(language, script, None, &[]);
598 let language_lang = LanguageIdentifier::from_parts(language, None, None, &[]);
599
600 add_resource(&mut bundle, &language_lang, locale_resources)?;
601 add_resource(&mut bundle, &script_lang, locale_resources)?;
602 add_resource(&mut bundle, ®ion_lang, locale_resources)?;
603 add_resource(&mut bundle, &variants_lang, locale_resources)?;
604
605 Ok(bundle)
614}