Skip to main content

freya_i18n/
i18n.rs

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/// `Locale` is a "place-holder" around what will eventually be a `fluent::FluentBundle`
17#[cfg_attr(test, derive(Debug, PartialEq))]
18pub struct Locale {
19    id: LanguageIdentifier,
20    resource: LocaleResource,
21}
22
23impl Locale {
24    /// Create a [`Locale`] from a static string containing Fluent (`.ftl`) content.
25    ///
26    /// Typically used with [`include_str!`] to embed locale files at compile time.
27    pub fn new_static(id: LanguageIdentifier, str: &'static str) -> Self {
28        Self {
29            id,
30            resource: LocaleResource::Static(str),
31        }
32    }
33
34    /// Create a [`Locale`] from a filesystem path to a Fluent (`.ftl`) file.
35    ///
36    /// The file will be read at runtime when the locale is loaded into a bundle.
37    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/// A `LocaleResource` can be static text, or a filesystem file.
56#[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/// The configuration for `I18n`.
95#[derive(Debug, PartialEq)]
96pub struct I18nConfig {
97    /// The initial language, can be later changed with [`I18n::set_language`]
98    pub id: LanguageIdentifier,
99
100    /// The final fallback language if no other locales are found for `id`.
101    /// A `Locale` must exist in `locales' if `fallback` is defined.
102    pub fallback: Option<LanguageIdentifier>,
103
104    /// The locale_resources added to the configuration.
105    pub locale_resources: Vec<LocaleResource>,
106
107    /// The locales added to the configuration.
108    pub locales: HashMap<LanguageIdentifier, usize>,
109}
110
111impl I18nConfig {
112    /// Create an i18n config with the selected [LanguageIdentifier].
113    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    /// Set a fallback [LanguageIdentifier].
123    pub fn with_fallback(mut self, fallback: LanguageIdentifier) -> Self {
124        self.fallback = Some(fallback);
125        self
126    }
127
128    /// Add [Locale].
129    /// It is possible to share locales resources. If this locale's resource
130    /// matches a previously added one, then this locale will use the existing one.
131    /// This is primarily for the static locale_resources to avoid string duplication.
132    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    /// Add multiple locales from given folder, based on their filename.
154    ///
155    /// If the path represents a folder, then the folder will be deep traversed for
156    /// all '*.ftl' files. If the filename represents a [LanguageIdentifier] then it
157    ///  will be added to the config.
158    ///
159    /// If the path represents a file, then the filename must represent a
160    /// unic_langid::LanguageIdentifier for it to be added to the config.
161    #[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    /// Add multiple locales from given folder, based on their filename.
194    ///
195    /// Will panic! on error.
196    #[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
224/// Initialize an [`I18n`] instance and provide it to descendant components.
225///
226/// This is the recommended way to set up i18n in your application. Call it once in a root
227/// component and then use [`I18n::get`] (or the `t!`, `te!`, `tid!` macros) in any
228/// descendant component to access translations.
229///
230/// The instance is shared across all windows. If another window already initialized it,
231/// that one is reused and `init` is not called.
232///
233/// See [`I18n::create`] for a manual initialization where you can also handle errors.
234///
235/// # Panics
236///
237/// Panics if the [`I18nConfig`] fails to produce a valid Fluent bundle.
238///
239/// ```rust
240/// # use freya::prelude::*;
241/// # use freya::i18n::*;
242/// fn app() -> impl IntoElement {
243///     let mut i18n = use_init_i18n(|| {
244///         I18nConfig::new(langid!("en-US"))
245///             .with_locale(Locale::new_static(
246///                 langid!("en-US"),
247///                 include_str!("../../../examples/i18n/en-US.ftl"),
248///             ))
249///             .with_locale(Locale::new_dynamic(
250///                 langid!("es-ES"),
251///                 "../../../examples/i18n/es-ES.ftl",
252///             ))
253///     });
254///
255///     let change_to_spanish = move |_| i18n.set_language(langid!("es-ES"));
256///
257///     rect()
258///         .child(t!("hello_world"))
259///         .child(Button::new().on_press(change_to_spanish).child("Spanish"))
260/// }
261/// ```
262pub fn use_init_i18n(init: impl FnOnce() -> I18nConfig) -> I18n {
263    use_hook(move || {
264        GlobalContexts::get().insert_context({
265            // Coverage false -ve: See https://github.com/xd009642/tarpaulin/issues/1675
266            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/// The main handle for accessing and managing internationalization state.
275///
276/// `I18n` holds the selected language, fallback language, locale resources, and the active
277/// [Fluent](https://projectfluent.org/) bundle used for translating messages. It is `Clone + Copy`
278/// so it can be freely passed around in components.
279///
280/// There are several ways to obtain an `I18n` instance:
281/// - [`use_init_i18n`] to create it and share it across all windows.
282/// - [`I18n::create`] to manually create one from an [`I18nConfig`] (useful when you need to handle errors).
283/// - [`I18n::create_global`] to create one with global lifetime, suitable for multi-window apps.
284/// - [`I18n::get`] or [`I18n::try_get`] to retrieve an already-provided instance.
285#[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    /// Try to retrieve the [`I18n`] instance from the global contexts.
296    ///
297    /// Returns `None` if no [`I18n`] has been provided via [`use_init_i18n`] in any window.
298    pub fn try_get() -> Option<Self> {
299        GlobalContexts::get().try_get_context()
300    }
301
302    /// Retrieve the [`I18n`] instance from the global contexts.
303    ///
304    /// This is the primary way to access the i18n state once any window has called
305    /// [`use_init_i18n`].
306    ///
307    /// # Panics
308    ///
309    /// Panics if no [`I18n`] has been provided.
310    ///
311    /// ```rust
312    /// # use freya::prelude::*;
313    /// # use freya::i18n::*;
314    /// #[derive(PartialEq)]
315    /// struct MyComponent;
316    ///
317    /// impl Component for MyComponent {
318    ///     fn render(&self) -> impl IntoElement {
319    ///         let mut i18n = I18n::get();
320    ///
321    ///         let change_to_english = move |_| i18n.set_language(langid!("en-US"));
322    ///
323    ///         rect()
324    ///             .child(t!("hello_world"))
325    ///             .child(Button::new().on_press(change_to_english).child("English"))
326    ///     }
327    /// }
328    /// ```
329    #[track_caller]
330    pub fn get() -> Self {
331        GlobalContexts::get().get_context()
332    }
333
334    /// Manually create an [`I18n`] instance from an [`I18nConfig`].
335    ///
336    /// Unlike [`use_init_i18n`], this does not provide the instance anywhere, so the `t!`
337    /// macros will not see it. Call this when you need explicit error handling during
338    /// initialization and pass the instance around by value.
339    ///
340    /// The created state is scoped to the current component. For global state that outlives
341    /// any single component, see [`I18n::create_global`].
342    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    /// Create an [`I18n`] instance with global lifetime.
366    ///
367    /// Unlike [`I18n::create`], the state created here is not scoped to any component and will
368    /// live for the entire duration of the application. [`use_init_i18n`] uses this internally
369    /// and shares the instance across all windows, so you rarely need to call it directly.
370    /// Call it when you need explicit error handling and share the result yourself by
371    /// inserting it into the [`GlobalContexts`].
372    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    /// Translate a message by its identifier, optionally with Fluent arguments.
396    ///
397    /// The `msg` can be a simple message id (e.g. `"hello"`) or a dotted attribute
398    /// id (e.g. `"my_component.placeholder"`). See [`I18n::decompose_identifier`] for details.
399    ///
400    /// Returns an error if the message id is not found, the pattern is missing,
401    /// or Fluent reports errors during formatting.
402    ///
403    /// Prefer the `t!`, `te!`, or `tid!` macros for ergonomic translations.
404    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    /// Split a message identifier into its message id and optional attribute name.
439    ///
440    /// - `"hello"` returns `("hello", None)`
441    /// - `"my_component.placeholder"` returns `("my_component", Some("placeholder"))`
442    ///
443    /// Returns an error if the identifier contains more than one dot.
444    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    /// Translate a message by its identifier, optionally with Fluent arguments.
454    ///
455    /// This is the panicking version of [`I18n::try_translate_with_args`].
456    ///
457    /// # Panics
458    ///
459    /// Panics if the translation fails for any reason.
460    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    /// Translate a message by its identifier, without arguments.
469    ///
470    /// Shorthand for `self.try_translate_with_args(msg, None)`.
471    #[inline]
472    pub fn try_translate(&self, msg: &str) -> Result<String, Error> {
473        self.try_translate_with_args(msg, None)
474    }
475
476    /// Translate a message by its identifier, without arguments.
477    ///
478    /// This is the panicking version of [`I18n::try_translate`].
479    ///
480    /// # Panics
481    ///
482    /// Panics if the translation fails for any reason.
483    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    /// Get the selected language.
492    #[inline]
493    pub fn language(&self) -> LanguageIdentifier {
494        self.selected_language.read().clone()
495    }
496
497    /// Get the fallback language.
498    pub fn fallback_language(&self) -> Option<LanguageIdentifier> {
499        self.fallback_language.read().clone()
500    }
501
502    /// Update the selected language, rebuilding the active Fluent bundle.
503    ///
504    /// Returns an error if the bundle cannot be rebuilt for the new language.
505    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    /// Update the selected language, rebuilding the active Fluent bundle.
511    ///
512    /// This is the panicking version of [`I18n::try_set_language`].
513    ///
514    /// # Panics
515    ///
516    /// Panics if the bundle cannot be rebuilt for the new language.
517    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    /// Update the fallback language, rebuilding the active Fluent bundle.
527    ///
528    /// The given language must have a corresponding [`Locale`] registered in the config.
529    /// Returns an error if no locale exists for the language or if the bundle cannot be rebuilt.
530    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    /// Update the fallback language, rebuilding the active Fluent bundle.
541    ///
542    /// This is the panicking version of [`I18n::try_set_fallback_language`].
543    ///
544    /// # Panics
545    ///
546    /// Panics if no locale exists for the language or if the bundle cannot be rebuilt.
547    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, &region_lang, locale_resources)?;
603    add_resource(&mut bundle, &variants_lang, locale_resources)?;
604
605    /* Add this code when the fluent crate includes FluentBundle::add_builtins.
606     * This will allow the use of built-in functions like `NUMBER` and `DATETIME`.
607     * See [Fluent issue](https://github.com/projectfluent/fluent-rs/issues/181) for more information.
608    bundle
609        .add_builtins()
610        .map_err(|e| Error::FluentErrorsDetected(e.to_string()))?;
611    */
612
613    Ok(bundle)
614}