Skip to main content

mitsuami_core/l10n/
mod.rs

1//! Localization, with [Project Fluent](https://projectfluent.org).
2//!
3//! The app's translations are Fluent files, one set per language
4//! ([`Locales`], usually made by `locales!`). The core picks the app's
5//! language from the user's, as the platform lists them, and every
6//! message, number and date follows it:
7//!
8//! ```ignore
9//! // locales/en-US/app.ftl:
10//! //   files-selected = { $count ->
11//! //       [one] One file selected
12//! //      *[other] { $count } files selected
13//! //   }
14//! view! { <Text>{t!("files-selected", count = selected.get().len())}</Text> }
15//! ```
16//!
17//! [`t!`](crate::t) makes a closure, so the text follows the language and
18//! the arguments' signals; [`tr!`](crate::tr) gives the string once.
19//! Numbers and dates in messages are written by the platform, the way the
20//! user's region writes them. A right-to-left language lays the app out
21//! right to left, native controls and window chrome included.
22
23mod format;
24
25use std::cell::RefCell;
26use std::collections::HashSet;
27use std::rc::{Rc, Weak};
28use std::time::SystemTime;
29
30use fluent_bundle::bundle::FluentBundle;
31use fluent_bundle::{FluentArgs, FluentResource, FluentValue};
32use fluent_langneg::{NegotiationStrategy, negotiate_languages};
33use mitsuami_reactive::{Computed, Owner, Signal, signal};
34use unic_langid::CharacterDirection;
35
36pub use format::{
37    CurrencyDisplay, DateTimeFormat, DateTimeStyle, NumberFormat, NumberStyle, NumberSymbols, PlatformLocale,
38    basic_date_time, basic_number, format_date_time, format_number, format_number_with, rounded,
39};
40pub use unic_langid::LanguageIdentifier;
41
42/// The language mitsuami's own strings are written in, and the last one
43/// every app falls back to.
44const TOOLKIT_LANGUAGE: &str = "en-US";
45const TOOLKIT_STRINGS: &str = include_str!("../../locales/en-US/mitsuami.ftl");
46
47/// The app's translations: Fluent files, per language. `locales!` makes
48/// one from a folder at compile time, checking each file's syntax.
49///
50/// ```ignore
51/// Locales::new()
52///     .fallback("en-US")
53///     .add("en-US", include_str!("../locales/en-US/app.ftl"))
54///     .add("pt-BR", include_str!("../locales/pt-BR/app.ftl"))
55/// ```
56#[derive(Clone, Default)]
57pub struct Locales {
58    fallback: Option<LanguageIdentifier>,
59    resources: Vec<(LanguageIdentifier, Rc<FluentResource>)>,
60}
61
62impl std::fmt::Debug for Locales {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("Locales").field("fallback", &self.fallback).field("languages", &self.languages()).finish()
65    }
66}
67
68impl Locales {
69    pub fn new() -> Locales {
70        Locales::default()
71    }
72
73    /// The language shown when none of the user's is there, and where a
74    /// message missing from theirs is looked up. Without one, or one the
75    /// app has no files for, the first language added.
76    ///
77    /// # Panics
78    /// If `language` isn't a language tag.
79    pub fn fallback(mut self, language: &str) -> Locales {
80        self.fallback =
81            Some(parse_tag(language).unwrap_or_else(|| panic!("mitsuami: {language:?} isn't a language tag")));
82        self
83    }
84
85    /// Adds a Fluent file's text to a language.
86    ///
87    /// # Panics
88    /// If `language` isn't a language tag, or the text isn't Fluent.
89    pub fn add(self, language: &str, source: impl Into<String>) -> Locales {
90        self.add_file(language, "(source)", source)
91    }
92
93    /// [`add`](Locales::add), naming the file in errors.
94    pub fn add_file(mut self, language: &str, file: &str, source: impl Into<String>) -> Locales {
95        let tag = parse_tag(language).unwrap_or_else(|| panic!("mitsuami: {language:?} isn't a language tag"));
96        let resource = FluentResource::try_new(source.into()).unwrap_or_else(|(_, errors)| {
97            panic!("mitsuami: {file} ({language}) isn't valid Fluent: {errors:?}");
98        });
99        self.resources.push((tag, Rc::new(resource)));
100        self
101    }
102
103    /// The languages it has, in the order they were added.
104    pub fn languages(&self) -> Vec<LanguageIdentifier> {
105        let mut languages: Vec<LanguageIdentifier> = Vec::new();
106        for (language, _) in &self.resources {
107            if !languages.contains(language) {
108                languages.push(language.clone());
109            }
110        }
111        languages
112    }
113}
114
115/// A value passed to a message: a string, a number (which selects plural
116/// forms, and which the platform writes), or a date ([`SystemTime`]).
117#[derive(Clone, Debug, PartialEq)]
118pub struct Arg(FluentValue<'static>);
119
120/// What can be passed to a message in [`t!`](crate::t) and
121/// [`tr!`](crate::tr). A signal passes its value, and is tracked.
122pub trait ToArg {
123    fn to_arg(&self) -> Arg;
124}
125
126impl ToArg for Arg {
127    fn to_arg(&self) -> Arg {
128        self.clone()
129    }
130}
131
132impl<T: ToArg + ?Sized> ToArg for &T {
133    fn to_arg(&self) -> Arg {
134        (**self).to_arg()
135    }
136}
137
138impl ToArg for str {
139    fn to_arg(&self) -> Arg {
140        Arg(FluentValue::String(self.to_owned().into()))
141    }
142}
143
144impl ToArg for String {
145    fn to_arg(&self) -> Arg {
146        self.as_str().to_arg()
147    }
148}
149
150impl ToArg for std::borrow::Cow<'_, str> {
151    fn to_arg(&self) -> Arg {
152        self.as_ref().to_arg()
153    }
154}
155
156impl ToArg for char {
157    fn to_arg(&self) -> Arg {
158        self.to_string().to_arg()
159    }
160}
161
162/// `"true"` or `"false"`, to select on: `[true] … *[false] …`.
163impl ToArg for bool {
164    fn to_arg(&self) -> Arg {
165        self.to_string().to_arg()
166    }
167}
168
169macro_rules! number_args {
170    ($($t:ty),*) => {$(
171        impl ToArg for $t {
172            fn to_arg(&self) -> Arg {
173                Arg(FluentValue::from(*self))
174            }
175        }
176    )*};
177}
178
179number_args!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
180
181impl ToArg for SystemTime {
182    fn to_arg(&self) -> Arg {
183        Arg(FluentValue::Custom(Box::new(format::DateTimeArg { time: *self, format: DateTimeFormat::default() })))
184    }
185}
186
187/// `None` is no value: a selector's default variant, an empty placeable.
188impl<T: ToArg> ToArg for Option<T> {
189    fn to_arg(&self) -> Arg {
190        match self {
191            Some(value) => value.to_arg(),
192            None => Arg(FluentValue::None),
193        }
194    }
195}
196
197impl<T: ToArg + 'static> ToArg for Signal<T> {
198    fn to_arg(&self) -> Arg {
199        self.with(|value| value.to_arg())
200    }
201}
202
203impl<T: ToArg + Clone + 'static> ToArg for Computed<T> {
204    fn to_arg(&self) -> Arg {
205        self.get().to_arg()
206    }
207}
208
209/// A message as a closure, for any text a view shows: it follows the app's
210/// language, and the signals the arguments read.
211///
212/// ```ignore
213/// <Text>{t!("greeting", name = user.get().name)}</Text>
214/// <Button>{t!("save")}</Button>
215/// <TextInput placeholder=t!("search.placeholder")/>
216/// ```
217///
218/// `id.attribute` is one of a message's attributes. Arguments are
219/// anything [`ToArg`]: strings, numbers (which select plural forms, and
220/// which the platform writes, as the user's region writes them), dates
221/// ([`SystemTime`]), signals. Each is evaluated again in the closure.
222#[macro_export]
223macro_rules! t {
224    ($id:expr $(, $name:ident = $value:expr)* $(,)?) => {
225        move || $crate::tr!($id $(, $name = $value)*)
226    };
227}
228
229/// A message as a `String`, now, for text that isn't a view's: an alert's,
230/// a file name. Read in a closure or an effect, it follows the language
231/// there. See [`t!`](crate::t).
232#[macro_export]
233macro_rules! tr {
234    ($id:expr $(, $name:ident = $value:expr)* $(,)?) => {
235        $crate::l10n::tr(
236            ::core::convert::AsRef::<str>::as_ref(&$id),
237            &[$((::core::stringify!($name), $crate::l10n::ToArg::to_arg(&$value))),*],
238        )
239    };
240}
241
242/// A message in the app's language; `id.attribute` for an attribute. A
243/// message missing from every language is its id, and an error (which
244/// fails tests). Tracked: an effect that reads it runs again when the
245/// language changes. Use [`t!`](crate::t) or [`tr!`](crate::tr).
246pub fn tr(id: &str, args: &[(&str, Arg)]) -> String {
247    match active() {
248        Some(l10n) => {
249            let _ = l10n.version.get();
250            l10n.format(id, args)
251        }
252        None => id.to_owned(),
253    }
254}
255
256/// The app's language: the first of the user's it has (or the app asked
257/// for with [`set_language`]), else its fallback. Tracked.
258pub fn language() -> LanguageIdentifier {
259    match active() {
260        Some(l10n) => {
261            let _ = l10n.version.get();
262            l10n.state.borrow().chain[0].clone()
263        }
264        None => toolkit_language(),
265    }
266}
267
268/// Whether the app's language is written right to left, which lays the
269/// app out right to left. Tracked.
270pub fn is_right_to_left() -> bool {
271    is_rtl(&language())
272}
273
274/// The languages the app has translations for.
275pub fn available_languages() -> Vec<LanguageIdentifier> {
276    active().map(|l10n| l10n.state.borrow().locales.languages()).unwrap_or_default()
277}
278
279/// Shows the app in this language (the one of its languages that best
280/// matches it), in place of the user's: an in-app language setting, as
281/// some apps have. `None` goes back to the user's. Every message, the
282/// direction and mitsuami's own strings follow right away.
283pub fn set_language(language: Option<&str>) {
284    if let Some(l10n) = active() {
285        l10n.update(|state| state.requested = language.map(|l| vec![l.to_owned()]));
286    }
287}
288
289/// Replaces the app's translations (`App::locales` gives the first), and
290/// chooses its language from them again: translations the app loads
291/// itself, say, or a story's.
292pub fn set_locales(locales: Locales) {
293    if let Some(l10n) = active() {
294        l10n.set_locales(locales);
295    }
296}
297
298/// Tracks the language in the running effect, for code that builds text
299/// without [`tr`] (menus, which backends title).
300pub(crate) fn track() {
301    if let Some(l10n) = active() {
302        let _ = l10n.version.get();
303    }
304}
305
306/// Parses a BCP 47 tag, or a POSIX locale name (`pt_BR.UTF-8@euro`), as
307/// Linux lists them.
308pub fn parse_tag(tag: &str) -> Option<LanguageIdentifier> {
309    let tag = tag.split(['.', '@']).next().unwrap_or(tag).replace('_', "-");
310    if tag.is_empty() || tag == "C" || tag == "POSIX" {
311        return None;
312    }
313    tag.parse().ok()
314}
315
316pub(crate) fn is_rtl(language: &LanguageIdentifier) -> bool {
317    language.character_direction() == CharacterDirection::RTL
318}
319
320fn toolkit_language() -> LanguageIdentifier {
321    TOOLKIT_LANGUAGE.parse().expect("a valid tag")
322}
323
324thread_local! {
325    /// The localization of the app on this thread: the last `Ui` made.
326    /// Backends' own strings and `tr!` outside any view look it up here.
327    static ACTIVE: RefCell<Weak<Localization>> = const { RefCell::new(Weak::new()) };
328    static TOOLKIT: Rc<FluentResource> =
329        Rc::new(FluentResource::try_new(TOOLKIT_STRINGS.to_owned()).expect("mitsuami.ftl is valid Fluent"));
330}
331
332fn active() -> Option<Rc<Localization>> {
333    ACTIVE.with(|a| a.borrow().upgrade())
334}
335
336pub(crate) fn platform_locale() -> Option<Rc<dyn PlatformLocale>> {
337    active().map(|l10n| l10n.platform.clone())
338}
339
340type Bundle = FluentBundle<Rc<FluentResource>, intl_memoizer::IntlLangMemoizer>;
341
342/// `(language, right to left)`.
343type OnChange = Rc<dyn Fn(&LanguageIdentifier, bool)>;
344
345/// A `Ui`'s localization: the app's translations, the languages chosen
346/// from them, and the bundles to format messages with.
347pub(crate) struct Localization {
348    platform: Rc<dyn PlatformLocale>,
349    state: RefCell<State>,
350    /// Bumped when the language or the translations change: every message
351    /// read in an effect tracks it.
352    version: Signal<u64>,
353    /// `version`'s scope, disposed with the `Ui`.
354    scope: Owner,
355    /// Tells the `Ui` the language changed.
356    on_change: RefCell<Option<OnChange>>,
357}
358
359pub(crate) struct State {
360    locales: Locales,
361    /// The app's (or a test's) choice, in place of the user's languages.
362    requested: Option<Vec<String>>,
363    /// The languages messages are looked up in, in order; never empty.
364    chain: Vec<LanguageIdentifier>,
365    bundles: Vec<Bundle>,
366    /// Missing messages and formatting errors, for tests to fail on.
367    errors: Vec<String>,
368    reported: HashSet<String>,
369}
370
371impl Localization {
372    pub(crate) fn new(platform: Rc<dyn PlatformLocale>) -> Rc<Localization> {
373        let scope = Owner::new_root();
374        let version = scope.with(|| signal(0));
375        let mut state = State {
376            locales: Locales::new(),
377            requested: None,
378            chain: Vec::new(),
379            bundles: Vec::new(),
380            errors: Vec::new(),
381            reported: HashSet::new(),
382        };
383        state.chain = negotiate(&state, &*platform);
384        state.bundles = bundles(&mut state);
385        let l10n = Rc::new(Localization {
386            platform,
387            state: RefCell::new(state),
388            version,
389            scope,
390            on_change: RefCell::new(None),
391        });
392        ACTIVE.with(|a| *a.borrow_mut() = Rc::downgrade(&l10n));
393        l10n
394    }
395
396    pub(crate) fn set_on_change(&self, f: impl Fn(&LanguageIdentifier, bool) + 'static) {
397        *self.on_change.borrow_mut() = Some(Rc::new(f));
398    }
399
400    pub(crate) fn language(&self) -> LanguageIdentifier {
401        self.state.borrow().chain[0].clone()
402    }
403
404    /// The language, tracked.
405    pub(crate) fn current(&self) -> LanguageIdentifier {
406        let _ = self.version.get();
407        self.language()
408    }
409
410    /// Changes the translations or the languages asked for, and chooses
411    /// again.
412    pub(crate) fn update(&self, f: impl FnOnce(&mut State)) {
413        let language = {
414            let mut state = self.state.borrow_mut();
415            f(&mut state);
416            state.chain = negotiate(&state, &*self.platform);
417            state.bundles = bundles(&mut state);
418            state.chain[0].clone()
419        };
420        let on_change = self.on_change.borrow().clone();
421        if let Some(on_change) = on_change {
422            on_change(&language, is_rtl(&language));
423        }
424        self.version.update(|v| *v += 1);
425    }
426
427    pub(crate) fn set_locales(&self, locales: Locales) {
428        self.update(|state| state.locales = locales);
429    }
430
431    pub(crate) fn set_requested(&self, languages: Option<Vec<String>>) {
432        self.update(|state| state.requested = languages);
433    }
434
435    pub(crate) fn take_errors(&self) -> Vec<String> {
436        std::mem::take(&mut self.state.borrow_mut().errors)
437    }
438
439    fn format(&self, id: &str, args: &[(&str, Arg)]) -> String {
440        let (message_id, attribute) = match id.split_once('.') {
441            Some((message, attribute)) => (message, Some(attribute)),
442            None => (id, None),
443        };
444        let mut fluent_args = FluentArgs::with_capacity(args.len());
445        for (name, Arg(value)) in args {
446            fluent_args.set(*name, value.clone());
447        }
448        let found = {
449            let state = self.state.borrow();
450            state.bundles.iter().find_map(|bundle| {
451                let message = bundle.get_message(message_id)?;
452                let pattern = match attribute {
453                    Some(attribute) => message.get_attribute(attribute)?.value(),
454                    None => message.value()?,
455                };
456                let mut errors = Vec::new();
457                let text = bundle.format_pattern(pattern, Some(&fluent_args), &mut errors).into_owned();
458                Some((text, errors))
459            })
460        };
461        match found {
462            Some((text, errors)) => {
463                if !errors.is_empty() {
464                    self.report(format!("message {id:?}: {errors:?}"));
465                }
466                text
467            }
468            None => {
469                let chain = self.state.borrow().chain.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(", ");
470                self.report(format!("no message {id:?} in {chain}"));
471                id.to_owned()
472            }
473        }
474    }
475
476    fn report(&self, error: String) {
477        // Once each: a message shown by an effect that runs often would
478        // grow the list for as long as the app runs.
479        let mut state = self.state.borrow_mut();
480        if state.reported.insert(error.clone()) {
481            eprintln!("mitsuami: {error}");
482            state.errors.push(error);
483        }
484    }
485}
486
487impl Drop for Localization {
488    fn drop(&mut self) {
489        self.scope.dispose();
490    }
491}
492
493/// The app's languages the user prefers, in the user's order, then the
494/// app's fallback, then mitsuami's own language for its strings.
495fn negotiate(state: &State, platform: &dyn PlatformLocale) -> Vec<LanguageIdentifier> {
496    let requested = state.requested.clone().unwrap_or_else(|| platform.languages());
497    let requested: Vec<LanguageIdentifier> = requested.iter().filter_map(|tag| parse_tag(tag)).collect();
498    let available = state.locales.languages();
499    // A fallback the app has no translations for would show every
500    // message's id: its first language stands in.
501    let fallback =
502        state.locales.fallback.clone().filter(|f| available.contains(f)).or_else(|| available.first().cloned());
503    let mut chain: Vec<LanguageIdentifier> = match &fallback {
504        Some(fallback) => negotiate_languages(&requested, &available, Some(fallback), NegotiationStrategy::Filtering)
505            .into_iter()
506            .cloned()
507            .collect(),
508        None => Vec::new(),
509    };
510    let toolkit = toolkit_language();
511    if !chain.contains(&toolkit) {
512        chain.push(toolkit);
513    }
514    chain
515}
516
517fn bundles(state: &mut State) -> Vec<Bundle> {
518    let toolkit = toolkit_language();
519    let mut errors = Vec::new();
520    let bundles = state
521        .chain
522        .iter()
523        .map(|language| {
524            let mut bundle = Bundle::new(vec![language.clone()]);
525            bundle.set_formatter(Some(format::format_value));
526            let _ = bundle.add_builtins();
527            let _ = bundle.add_function("DATETIME", format::DATETIME);
528            for (_, resource) in state.locales.resources.iter().filter(|(l, _)| l == language) {
529                if let Err(e) = bundle.add_resource(resource.clone()) {
530                    errors.push(format!("{language}: {e:?}"));
531                }
532            }
533            // The app's own messages win over mitsuami's.
534            if *language == toolkit {
535                let _ = bundle.add_resource(TOOLKIT.with(Rc::clone));
536            }
537            bundle
538        })
539        .collect();
540    state.errors.extend(errors);
541    bundles
542}