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
57                .languages(requested)
58                .into_iter()
59                .next()
60                .unwrap_or_else(|| &catalog.locales[catalog.default])
61                .to_string(),
62            None => requested.map_or_else(|| "und".to_owned(), |locale| locale.to_string()),
63        }
64    }
65
66    fn with_number<T>(
67        &self,
68        catalog: Option<&TranslationCatalog>,
69        use_number: impl FnOnce(&LocalizedNumber) -> T,
70    ) -> T {
71        // Keep regional number conventions even when the translation catalog
72        // resolves a requested language to a less specific tag.
73        let language = self.language().unwrap_or_else(|| {
74            catalog.map_or_else(LocaleId::default, |catalog| {
75                catalog.locales[catalog.default].clone()
76            })
77        });
78        let mut cache = self.number.borrow_mut();
79        if cache
80            .as_ref()
81            .is_some_and(|(cached, _)| *cached != language)
82        {
83            *cache = None;
84        }
85        let (_, formatter) = cache.get_or_insert_with(|| {
86            let formatter = LocalizedNumber::new(&language.to_string());
87            (language, formatter)
88        });
89        use_number(formatter)
90    }
91
92    #[doc(hidden)]
93    pub fn format_number_int(
94        &self,
95        catalog: Option<&TranslationCatalog>,
96        value: i64,
97        decimals: i64,
98    ) -> String {
99        let ascii = crate::format_fixed_int(value, decimals.clamp(0, 20) as usize);
100        self.with_number(catalog, |format| format.format(ascii))
101    }
102
103    #[doc(hidden)]
104    pub fn format_number_float(
105        &self,
106        catalog: Option<&TranslationCatalog>,
107        value: f64,
108        decimals: i64,
109    ) -> String {
110        let ascii = crate::format_fixed_float(value, decimals.clamp(0, 20) as usize);
111        self.with_number(catalog, |format| format.format(ascii))
112    }
113
114    #[doc(hidden)]
115    pub fn parse_number(
116        &self,
117        catalog: Option<&TranslationCatalog>,
118        text: &str,
119        fallback: f64,
120    ) -> f64 {
121        self.with_number(catalog, |format| format.parse(text))
122            .unwrap_or(fallback)
123    }
124}
125
126/// Parsed catalogs shared by all instances of a generated UI on one thread.
127pub struct TranslationCatalog {
128    locales: Vec<LocaleId>,
129    sources: Vec<Cow<'static, str>>,
130    bundles: Vec<OnceCell<FluentBundle<FluentResource>>>,
131    default: usize,
132}
133
134impl TranslationCatalog {
135    #[expect(
136        clippy::expect_used,
137        reason = "the compiler validates sources before generating calls to this constructor"
138    )]
139    pub fn new(default: &str, sources: &[(&str, &'static str)]) -> Self {
140        Self::from_sources(
141            default,
142            sources
143                .iter()
144                .map(|&(locale, text)| (locale, Cow::Borrowed(text))),
145        )
146        .expect("validated generated translation catalog")
147    }
148
149    pub fn from_owned(default: &str, sources: BTreeMap<String, String>) -> Result<Self, String> {
150        let catalog = Self::from_sources(
151            default,
152            sources
153                .into_iter()
154                .map(|(locale, text)| (locale, Cow::Owned(text))),
155        )?;
156        for index in 0..catalog.locales.len() {
157            let bundle = catalog.build_bundle(index)?;
158            catalog.bundles[index]
159                .set(bundle)
160                .map_err(|_| "translation bundle was already initialized")?;
161        }
162        Ok(catalog)
163    }
164
165    /// Expose the catalog text to the XR resource validator.
166    #[doc(hidden)]
167    pub fn sources(&self) -> impl Iterator<Item = (&LocaleId, &str, bool)> {
168        self.locales
169            .iter()
170            .zip(&self.sources)
171            .enumerate()
172            .map(|(index, (locale, source))| (locale, source.as_ref(), index == self.default))
173    }
174
175    fn from_sources(
176        default: &str,
177        sources: impl IntoIterator<Item = (impl AsRef<str>, Cow<'static, str>)>,
178    ) -> Result<Self, String> {
179        let mut default_index = None;
180        let mut locales = Vec::new();
181        let mut text = Vec::new();
182        for (locale, source) in sources {
183            let locale = locale.as_ref();
184            if locale == default {
185                default_index = Some(locales.len());
186            }
187            locales.push(
188                locale
189                    .parse::<LocaleId>()
190                    .map_err(|error| error.to_string())?,
191            );
192            text.push(source);
193        }
194        let bundles = locales.iter().map(|_| OnceCell::new()).collect();
195        Ok(Self {
196            locales,
197            sources: text,
198            bundles,
199            default: default_index.ok_or("translation catalog missing default language")?,
200        })
201    }
202
203    fn build_bundle(&self, index: usize) -> Result<FluentBundle<FluentResource>, String> {
204        let resource = FluentResource::try_new(self.sources[index].to_string())
205            .map_err(|(_, errors)| format!("invalid Fluent resource: {errors:?}"))?;
206        let mut bundle = FluentBundle::new(vec![self.locales[index].clone()]);
207        bundle
208            .add_resource(resource)
209            .map_err(|errors| format!("invalid Fluent messages: {errors:?}"))?;
210        bundle
211            .add_builtins()
212            .map_err(|errors| format!("invalid Fluent builtins: {errors:?}"))?;
213        Ok(bundle)
214    }
215
216    fn languages(&self, requested: Option<LocaleId>) -> Vec<&LocaleId> {
217        let fallback = &self.locales[self.default];
218        let mut locales = match requested {
219            Some(language) => negotiate_languages(
220                &[language],
221                &self.locales,
222                None,
223                NegotiationStrategy::Lookup,
224            ),
225            None => Vec::new(),
226        };
227        if !locales.contains(&fallback) {
228            locales.push(fallback);
229        }
230        locales
231    }
232
233    pub fn translate(
234        &self,
235        locale: &LocaleBinding,
236        id: &str,
237        args: &[(&str, TranslationValue<'_>)],
238    ) -> String {
239        let args: FluentArgs<'_> = args.iter().cloned().collect();
240        for language in self.languages(locale.language()) {
241            let Some(index) = self
242                .locales
243                .iter()
244                .position(|candidate| candidate == language)
245            else {
246                continue;
247            };
248            #[expect(
249                clippy::expect_used,
250                reason = "catalog construction validates every bundle against the same sources"
251            )]
252            let bundle = self.bundles[index]
253                .get_or_init(|| self.build_bundle(index).expect("validated Fluent resource"));
254            if let Some(pattern) = bundle.get_message(id).and_then(|message| message.value()) {
255                let mut errors = Vec::new();
256                let text = bundle.format_pattern(pattern, Some(&args), &mut errors);
257                if errors.is_empty() {
258                    return text.into_owned();
259                }
260            }
261        }
262        id.to_owned()
263    }
264}