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::{borrow::Cow, cell::OnceCell, collections::BTreeMap, 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<Cow<'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        Self::from_sources(
56            default,
57            sources
58                .iter()
59                .map(|&(locale, text)| (locale, Cow::Borrowed(text))),
60        )
61        .expect("validated generated translation catalog")
62    }
63
64    pub fn from_owned(default: &str, sources: BTreeMap<String, String>) -> Result<Self, String> {
65        let catalog = Self::from_sources(
66            default,
67            sources
68                .into_iter()
69                .map(|(locale, text)| (locale, Cow::Owned(text))),
70        )?;
71        for index in 0..catalog.locales.len() {
72            let bundle = catalog.build_bundle(index)?;
73            catalog.bundles[index]
74                .set(bundle)
75                .map_err(|_| "translation bundle was already initialized")?;
76        }
77        Ok(catalog)
78    }
79
80    fn from_sources(
81        default: &str,
82        sources: impl IntoIterator<Item = (impl AsRef<str>, Cow<'static, str>)>,
83    ) -> Result<Self, String> {
84        let mut default_index = None;
85        let mut locales = Vec::new();
86        let mut text = Vec::new();
87        for (locale, source) in sources {
88            let locale = locale.as_ref();
89            if locale == default {
90                default_index = Some(locales.len());
91            }
92            locales.push(
93                locale
94                    .parse::<LocaleId>()
95                    .map_err(|error| error.to_string())?,
96            );
97            text.push(source);
98        }
99        let bundles = locales.iter().map(|_| OnceCell::new()).collect();
100        Ok(Self {
101            locales,
102            sources: text,
103            bundles,
104            default: default_index.ok_or("translation catalog missing default language")?,
105        })
106    }
107
108    fn build_bundle(&self, index: usize) -> Result<FluentBundle<FluentResource>, String> {
109        let resource = FluentResource::try_new(self.sources[index].to_string())
110            .map_err(|(_, errors)| format!("invalid Fluent resource: {errors:?}"))?;
111        let mut bundle = FluentBundle::new(vec![self.locales[index].clone()]);
112        bundle
113            .add_resource(resource)
114            .map_err(|errors| format!("invalid Fluent messages: {errors:?}"))?;
115        bundle
116            .add_builtins()
117            .map_err(|errors| format!("invalid Fluent builtins: {errors:?}"))?;
118        Ok(bundle)
119    }
120
121    pub fn translate(
122        &self,
123        locale: &LocaleBinding,
124        id: &str,
125        args: &[(&str, TranslationValue<'_>)],
126    ) -> String {
127        let fallback = &self.locales[self.default];
128        let mut locales = match locale.language() {
129            Some(language) => negotiate_languages(
130                &[language],
131                &self.locales,
132                None,
133                NegotiationStrategy::Lookup,
134            ),
135            None => Vec::new(),
136        };
137        if !locales.contains(&fallback) {
138            locales.push(fallback);
139        }
140        let args: FluentArgs<'_> = args.iter().cloned().collect();
141        for language in locales {
142            let index = self
143                .locales
144                .iter()
145                .position(|candidate| candidate == language)
146                .expect("negotiated a catalog language");
147            let bundle = self.bundles[index]
148                .get_or_init(|| self.build_bundle(index).expect("validated Fluent resource"));
149            if let Some(pattern) = bundle.get_message(id).and_then(|message| message.value()) {
150                let mut errors = Vec::new();
151                let text = bundle.format_pattern(pattern, Some(&args), &mut errors);
152                if errors.is_empty() {
153                    return text.into_owned();
154                }
155            }
156        }
157        id.to_owned()
158    }
159}