Skip to main content

xrack_runtime/
localization.rs

1use crate::Property;
2use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
3use fluent_langneg::{NegotiationStrategy, negotiate_languages};
4use std::{cell::OnceCell, rc::Rc};
5
6pub use fluent_bundle::FluentValue as TranslationValue;
7pub use unic_langid::LanguageIdentifier as LocaleId;
8
9/// The requested UI language shared by components on the UI thread.
10/// Until a language is selected, each catalog uses its declared default.
11#[derive(Clone, Default)]
12pub struct LocaleContext(Rc<Property<Option<LocaleId>>>);
13
14impl LocaleContext {
15    /// Select a language for standalone components, such as offscreen renders.
16    /// Desktop applications can use `Desktop::set_locale` to also wake the event loop.
17    pub fn set_locale(&self, locale: &str) -> Result<(), String> {
18        let locale = locale
19            .parse::<LocaleId>()
20            .map_err(|error| format!("invalid UI locale `{locale}`: {error}"))?;
21        self.set_language(locale);
22        Ok(())
23    }
24
25    #[doc(hidden)]
26    pub fn set_language(&self, locale: LocaleId) {
27        self.0.set_if_changed(Some(locale));
28    }
29}
30
31/// One reactive connection shared by a generated component and its descendants.
32#[derive(Clone, Default)]
33pub struct LocaleBinding(Rc<Property<LocaleContext>>);
34
35impl LocaleBinding {
36    pub fn set_context(&self, context: LocaleContext) {
37        self.0.set(context);
38    }
39
40    fn language(&self) -> Option<LocaleId> {
41        self.0.get(LocaleContext::default).0.get(|| None)
42    }
43}
44
45/// Parsed catalogs shared by all instances of a generated UI on one thread.
46pub struct TranslationCatalog {
47    locales: Vec<LocaleId>,
48    sources: Vec<&'static str>,
49    bundles: Vec<OnceCell<FluentBundle<FluentResource>>>,
50    default: usize,
51}
52
53impl TranslationCatalog {
54    pub fn new(default: &str, sources: &[(&str, &'static str)]) -> Self {
55        let default = sources
56            .iter()
57            .position(|(locale, _)| *locale == default)
58            .expect("generated catalog has a default language");
59        let (locales, text) = sources
60            .iter()
61            .map(|(locale, source)| (locale.parse().expect("validated locale"), *source))
62            .unzip();
63        let bundles = sources.iter().map(|_| OnceCell::new()).collect();
64        Self {
65            locales,
66            sources: text,
67            bundles,
68            default,
69        }
70    }
71
72    pub fn translate(
73        &self,
74        locale: &LocaleBinding,
75        id: &str,
76        args: &[(&str, TranslationValue<'_>)],
77    ) -> String {
78        let fallback = &self.locales[self.default];
79        let mut locales = match locale.language() {
80            Some(language) => negotiate_languages(
81                &[language],
82                &self.locales,
83                None,
84                NegotiationStrategy::Lookup,
85            ),
86            None => Vec::new(),
87        };
88        if !locales.contains(&fallback) {
89            locales.push(fallback);
90        }
91        let args: FluentArgs<'_> = args.iter().cloned().collect();
92        for language in locales {
93            let index = self
94                .locales
95                .iter()
96                .position(|candidate| candidate == language)
97                .expect("negotiated a catalog language");
98            let bundle = self.bundles[index].get_or_init(|| {
99                let resource = FluentResource::try_new(self.sources[index].to_owned())
100                    .expect("validated Fluent resource");
101                let mut bundle = FluentBundle::new(vec![language.clone()]);
102                bundle
103                    .add_resource(resource)
104                    .expect("validated Fluent message IDs");
105                bundle.add_builtins().expect("validated Fluent builtins");
106                bundle
107            });
108            if let Some(pattern) = bundle.get_message(id).and_then(|message| message.value()) {
109                let mut errors = Vec::new();
110                let text = bundle.format_pattern(pattern, Some(&args), &mut errors);
111                if errors.is_empty() {
112                    return text.into_owned();
113                }
114            }
115        }
116        id.to_owned()
117    }
118}