Skip to main content

xrack_runtime/
localization.rs

1use crate::{Property, localized_number::LocalizedNumber};
2use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
3use fluent_langneg::{NegotiationStrategy, negotiate_languages};
4use std::{
5    borrow::Cow,
6    cell::{OnceCell, RefCell},
7    collections::BTreeMap,
8    rc::Rc,
9};
10
11pub use fluent_bundle::FluentValue as TranslationValue;
12pub use unic_langid::LanguageIdentifier as LocaleId;
13
14/// The requested UI language shared by components on the UI thread.
15/// Until a language is selected, each catalog uses its declared default.
16#[derive(Clone, Default)]
17pub struct LocaleContext(Rc<Property<Option<LocaleId>>>);
18
19impl LocaleContext {
20    /// Select a language for standalone components, such as offscreen renders.
21    /// Desktop applications can use `Desktop::set_locale` to also wake the event loop.
22    pub fn set_locale(&self, locale: &str) -> Result<(), String> {
23        let locale = locale
24            .parse::<LocaleId>()
25            .map_err(|error| format!("invalid UI locale `{locale}`: {error}"))?;
26        self.set_language(locale);
27        Ok(())
28    }
29
30    #[doc(hidden)]
31    pub fn set_language(&self, locale: LocaleId) {
32        self.0.set_if_changed(Some(locale));
33    }
34}
35
36/// One reactive connection shared by a generated component and its descendants.
37#[derive(Clone, Default)]
38pub struct LocaleBinding {
39    context: Rc<Property<LocaleContext>>,
40    number: Rc<RefCell<Option<(LocaleId, LocalizedNumber)>>>,
41}
42
43impl LocaleBinding {
44    pub fn set_context(&self, context: LocaleContext) {
45        self.context.set(context);
46    }
47
48    fn language(&self) -> Option<LocaleId> {
49        self.context.get(LocaleContext::default).0.get(|| None)
50    }
51
52    #[doc(hidden)]
53    pub fn locale(&self, catalog: Option<&TranslationCatalog>) -> String {
54        let requested = self.language();
55        match catalog {
56            Some(catalog) => catalog.languages(requested).first().unwrap().to_string(),
57            None => requested.map_or_else(|| "und".to_owned(), |locale| locale.to_string()),
58        }
59    }
60
61    fn with_number<T>(
62        &self,
63        catalog: Option<&TranslationCatalog>,
64        use_number: impl FnOnce(&LocalizedNumber) -> T,
65    ) -> T {
66        // Keep regional number conventions even when the translation catalog
67        // resolves a requested language to a less specific tag.
68        let language = self.language().unwrap_or_else(|| {
69            catalog.map_or_else(LocaleId::default, |catalog| {
70                catalog.locales[catalog.default].clone()
71            })
72        });
73        let mut cache = self.number.borrow_mut();
74        if cache.as_ref().is_none_or(|(cached, _)| *cached != language) {
75            let formatter = LocalizedNumber::new(&language.to_string());
76            *cache = Some((language, formatter));
77        }
78        use_number(&cache.as_ref().unwrap().1)
79    }
80
81    #[doc(hidden)]
82    pub fn format_number_int(
83        &self,
84        catalog: Option<&TranslationCatalog>,
85        value: i64,
86        decimals: i64,
87    ) -> String {
88        let ascii = crate::format_fixed_int(value, decimals.clamp(0, 20) as usize);
89        self.with_number(catalog, |format| format.format(ascii))
90    }
91
92    #[doc(hidden)]
93    pub fn format_number_float(
94        &self,
95        catalog: Option<&TranslationCatalog>,
96        value: f64,
97        decimals: i64,
98    ) -> String {
99        let ascii = crate::format_fixed_float(value, decimals.clamp(0, 20) as usize);
100        self.with_number(catalog, |format| format.format(ascii))
101    }
102
103    #[doc(hidden)]
104    pub fn parse_number(
105        &self,
106        catalog: Option<&TranslationCatalog>,
107        text: &str,
108        fallback: f64,
109    ) -> f64 {
110        self.with_number(catalog, |format| format.parse(text))
111            .unwrap_or(fallback)
112    }
113}
114
115/// Parsed catalogs shared by all instances of a generated UI on one thread.
116pub struct TranslationCatalog {
117    locales: Vec<LocaleId>,
118    sources: Vec<Cow<'static, str>>,
119    bundles: Vec<OnceCell<FluentBundle<FluentResource>>>,
120    default: usize,
121}
122
123impl TranslationCatalog {
124    pub fn new(default: &str, sources: &[(&str, &'static str)]) -> Self {
125        Self::from_sources(
126            default,
127            sources
128                .iter()
129                .map(|&(locale, text)| (locale, Cow::Borrowed(text))),
130        )
131        .expect("validated generated translation catalog")
132    }
133
134    pub fn from_owned(default: &str, sources: BTreeMap<String, String>) -> Result<Self, String> {
135        let catalog = Self::from_sources(
136            default,
137            sources
138                .into_iter()
139                .map(|(locale, text)| (locale, Cow::Owned(text))),
140        )?;
141        for index in 0..catalog.locales.len() {
142            let bundle = catalog.build_bundle(index)?;
143            catalog.bundles[index]
144                .set(bundle)
145                .map_err(|_| "translation bundle was already initialized")?;
146        }
147        Ok(catalog)
148    }
149
150    /// Expose the catalog text to the XR resource validator.
151    #[doc(hidden)]
152    pub fn sources(&self) -> impl Iterator<Item = (&LocaleId, &str, bool)> {
153        self.locales
154            .iter()
155            .zip(&self.sources)
156            .enumerate()
157            .map(|(index, (locale, source))| (locale, source.as_ref(), index == self.default))
158    }
159
160    fn from_sources(
161        default: &str,
162        sources: impl IntoIterator<Item = (impl AsRef<str>, Cow<'static, str>)>,
163    ) -> Result<Self, String> {
164        let mut default_index = None;
165        let mut locales = Vec::new();
166        let mut text = Vec::new();
167        for (locale, source) in sources {
168            let locale = locale.as_ref();
169            if locale == default {
170                default_index = Some(locales.len());
171            }
172            locales.push(
173                locale
174                    .parse::<LocaleId>()
175                    .map_err(|error| error.to_string())?,
176            );
177            text.push(source);
178        }
179        let bundles = locales.iter().map(|_| OnceCell::new()).collect();
180        Ok(Self {
181            locales,
182            sources: text,
183            bundles,
184            default: default_index.ok_or("translation catalog missing default language")?,
185        })
186    }
187
188    fn build_bundle(&self, index: usize) -> Result<FluentBundle<FluentResource>, String> {
189        let resource = FluentResource::try_new(self.sources[index].to_string())
190            .map_err(|(_, errors)| format!("invalid Fluent resource: {errors:?}"))?;
191        let mut bundle = FluentBundle::new(vec![self.locales[index].clone()]);
192        bundle
193            .add_resource(resource)
194            .map_err(|errors| format!("invalid Fluent messages: {errors:?}"))?;
195        bundle
196            .add_builtins()
197            .map_err(|errors| format!("invalid Fluent builtins: {errors:?}"))?;
198        Ok(bundle)
199    }
200
201    fn languages(&self, requested: Option<LocaleId>) -> Vec<&LocaleId> {
202        let fallback = &self.locales[self.default];
203        let mut locales = match requested {
204            Some(language) => negotiate_languages(
205                &[language],
206                &self.locales,
207                None,
208                NegotiationStrategy::Lookup,
209            ),
210            None => Vec::new(),
211        };
212        if !locales.contains(&fallback) {
213            locales.push(fallback);
214        }
215        locales
216    }
217
218    pub fn translate(
219        &self,
220        locale: &LocaleBinding,
221        id: &str,
222        args: &[(&str, TranslationValue<'_>)],
223    ) -> String {
224        let args: FluentArgs<'_> = args.iter().cloned().collect();
225        for language in self.languages(locale.language()) {
226            let index = self
227                .locales
228                .iter()
229                .position(|candidate| candidate == language)
230                .expect("negotiated a catalog language");
231            let bundle = self.bundles[index]
232                .get_or_init(|| self.build_bundle(index).expect("validated Fluent resource"));
233            if let Some(pattern) = bundle.get_message(id).and_then(|message| message.value()) {
234                let mut errors = Vec::new();
235                let text = bundle.format_pattern(pattern, Some(&args), &mut errors);
236                if errors.is_empty() {
237                    return text.into_owned();
238                }
239            }
240        }
241        id.to_owned()
242    }
243}