1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::collections::HashMap;
use std::fs::read_dir;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentResource, FluentValue};

use crate::error::LoaderError;

pub use unic_langid::{langid, langids, LanguageIdentifier};

/// A builder pattern struct for constructing `ArcLoader`s.
pub struct ArcLoaderBuilder<'a, 'b> {
    location: &'a Path,
    fallback: LanguageIdentifier,
    shared: Option<&'b [PathBuf]>,
    customize: Option<fn(&mut FluentBundle<Arc<FluentResource>>)>,
}

impl<'a, 'b> ArcLoaderBuilder<'a, 'b> {
    /// Adds Fluent resources that are shared across all localizations.
    pub fn shared_resources(mut self, shared: Option<&'b [PathBuf]>) -> Self {
        self.shared = shared;
        self
    }

    /// Allows you to customise each `FluentBundle`.
    pub fn customize(mut self, customize: fn(&mut FluentBundle<Arc<FluentResource>>)) -> Self {
        self.customize = Some(customize);
        self
    }

    /// Constructs an `ArcLoader` from the settings provided.
    pub fn build(self) -> Result<ArcLoader, Box<dyn std::error::Error>> {
        let mut resources = HashMap::new();

        for entry in read_dir(self.location)? {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                if let Ok(lang) = entry.file_name().into_string() {
                    let lang_resources = crate::fs::read_from_dir(entry.path())?
                        .into_iter()
                        .map(Arc::new)
                        .collect::<Vec<_>>();
                    resources.insert(lang.parse::<LanguageIdentifier>()?, lang_resources);
                }
            }
        }

        let mut bundles = HashMap::new();
        for (lang, v) in resources.iter() {
            let mut bundle = FluentBundle::new(vec![lang.clone()]);

            for shared_resource in self.shared.as_deref().unwrap_or(&[]) {
                bundle
                    .add_resource(Arc::new(crate::fs::read_from_file(shared_resource)?))
                    .map_err(|errors| LoaderError::FluentBundle { errors })?;
            }

            for res in v {
                bundle
                    .add_resource(res.clone())
                    .map_err(|errors| LoaderError::FluentBundle { errors })?;
            }

            if let Some(customize) = self.customize {
                (customize)(&mut bundle);
            }

            bundles.insert(lang.clone(), bundle);
        }

        let fallbacks = super::build_fallbacks(&*resources.keys().cloned().collect::<Vec<_>>());

        Ok(ArcLoader {
            bundles,
            fallbacks,
            fallback: self.fallback,
        })
    }
}

/// A loader that uses `Arc<FluentResource>` as its backing storage. This is
/// mainly useful for when you need to load fluent at run time. You can
/// configure the initialisation with `ArcLoaderBuilder`.
/// ```no_run
/// use fluent_templates::ArcLoader;
///
/// let loader = ArcLoader::builder("locales/", unic_langid::langid!("en-US"))
///     .shared_resources(Some(&["locales/core.ftl".into()]))
///     .customize(|bundle| bundle.set_use_isolating(false))
///     .build()
///     .unwrap();
/// ```
pub struct ArcLoader {
    bundles: HashMap<LanguageIdentifier, FluentBundle<Arc<FluentResource>>>,
    fallback: LanguageIdentifier,
    fallbacks: HashMap<LanguageIdentifier, Vec<LanguageIdentifier>>,
}

impl super::Loader for ArcLoader {
    // Traverse the fallback chain,
    fn lookup_complete<T: AsRef<str>>(
        &self,
        lang: &LanguageIdentifier,
        text_id: &str,
        args: Option<&HashMap<T, FluentValue>>,
    ) -> String {
        if let Some(fallbacks) = self.fallbacks.get(lang) {
            for l in fallbacks {
                if let Some(val) = self.lookup_single_language(l, text_id, args) {
                    return val;
                }
            }
        }
        if *lang != self.fallback {
            if let Some(val) = self.lookup_single_language(&self.fallback, text_id, args) {
                return val;
            }
        }
        format!("Unknown localization {}", text_id)
    }

    fn locales(&self) -> Box<dyn Iterator<Item = &LanguageIdentifier> + '_> {
        Box::new(self.fallbacks.keys())
    }
}

impl ArcLoader {
    /// Creates a new `ArcLoaderBuilder`
    pub fn builder<P: AsRef<Path> + ?Sized>(
        location: &P,
        fallback: LanguageIdentifier,
    ) -> ArcLoaderBuilder {
        ArcLoaderBuilder {
            location: location.as_ref(),
            fallback,
            shared: None,
            customize: None,
        }
    }

    /// Convenience function to look up a string for a single language
    pub fn lookup_single_language<T: AsRef<str>>(
        &self,
        lang: &LanguageIdentifier,
        text_id: &str,
        args: Option<&HashMap<T, FluentValue>>,
    ) -> Option<String> {
        super::shared::lookup_single_language(&self.bundles, lang, text_id, args)
    }

    /// Convenience function to look up a string without falling back to the
    /// default fallback language
    pub fn lookup_no_default_fallback<S: AsRef<str>>(
        &self,
        lang: &LanguageIdentifier,
        text_id: &str,
        args: Option<&HashMap<S, FluentValue>>,
    ) -> Option<String> {
        super::shared::lookup_no_default_fallback(
            &self.bundles,
            &self.fallbacks,
            lang,
            text_id,
            args,
        )
    }
}