Skip to main content

egui_pop_i18n/
catalog.rs

1//! Looking text up: one Fluent bundle per locale and a fallback chain
2//! ending in English.
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use fluent_bundle::concurrent::FluentBundle;
7use fluent_bundle::{FluentArgs, FluentResource};
8use fluent_syntax::ast::Entry;
9use unic_langid::LanguageIdentifier;
10
11use crate::locale::{self, ENGLISH, PSEUDO};
12
13type Bundle = FluentBundle<FluentResource>;
14
15/// A key split into its message and attribute: `id` or `id.attr`.
16pub fn split_key(key: &str) -> (&str, Option<&str>) {
17    match key.split_once('.') {
18        Some((id, attr)) => (id, Some(attr)),
19        None => (key, None),
20    }
21}
22
23/// The areas whose keys carry an owner's id right after them
24/// (`command-<owner>-…`).
25const AREAS: [&str; 6] = ["command", "panel", "menu", "setting", "plugin", "param"];
26
27/// Whether a message belongs to `owner` (a plugin, by its stable id):
28/// `<owner>-…` for its free messages, `<area>-<owner>-…` for its
29/// commands, panels, menus, settings and parameters, or `<area>-<owner>`
30/// itself (`plugin-<owner>`, the plugin's title).
31///
32/// ```
33/// use egui_pop_i18n::catalog::owned_by;
34///
35/// assert!(owned_by("acme", "acme-greeting"));
36/// assert!(owned_by("acme.denoise", "command-acme-denoise-run"));
37/// assert!(owned_by("acme", "plugin-acme"));
38/// assert!(!owned_by("acme", "plugin-acmex"));
39/// assert!(!owned_by("acme", "acmex-greeting"));
40/// assert!(!owned_by("acme", "panel-helios-acme"));
41/// ```
42pub fn owned_by(owner: &str, message: &str) -> bool {
43    let owner = egui_pop_core::strings::slug(owner);
44    let prefixed = |rest: &str| {
45        rest.strip_prefix(owner.as_str())
46            .is_some_and(|r| r.starts_with('-'))
47    };
48    prefixed(message)
49        || AREAS.iter().any(|area| {
50            message
51                .strip_prefix(area)
52                .and_then(|r| r.strip_prefix('-'))
53                .is_some_and(|r| r == owner || prefixed(r))
54        })
55}
56
57/// Catalogues per locale and the locale in use.
58///
59/// A lookup names a key (`id` or `id.attr`) and tries the current
60/// locale, then its parents (`fr-CA`, then `fr`), then English; what
61/// English lacks too is `None`, and the caller shows its own English
62/// text or the key. `x-pseudo` reads English, accented and lengthened.
63pub struct Catalog {
64    bundles: BTreeMap<String, Bundle>,
65    /// The message ids each locale defines.
66    ids: BTreeMap<String, BTreeSet<String>>,
67    /// The ids of each locale an application's catalogue may override
68    /// (egui-pop's own, see [`Catalog::add_base`]).
69    base: BTreeMap<String, BTreeSet<String>>,
70    /// What an application's catalogue overrode: (locale, id).
71    overridden: Vec<(String, String)>,
72    locale: String,
73    chain: Vec<String>,
74}
75
76impl std::fmt::Debug for Catalog {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("Catalog")
79            .field("locales", &self.bundles.keys().collect::<Vec<_>>())
80            .field("locale", &self.locale)
81            .finish()
82    }
83}
84
85impl Catalog {
86    /// No catalogue, in `locale`.
87    pub fn new(locale: &str) -> Self {
88        let mut c = Self {
89            bundles: BTreeMap::new(),
90            ids: BTreeMap::new(),
91            base: BTreeMap::new(),
92            overridden: Vec::new(),
93            locale: String::new(),
94            chain: Vec::new(),
95        };
96        c.set_locale(locale);
97        c
98    }
99
100    /// Switches the locale; the next lookups use it. A tag naming no
101    /// language selects English.
102    pub fn set_locale(&mut self, tag: &str) {
103        self.locale = locale::normalize(tag).unwrap_or_else(|| ENGLISH.into());
104        self.rechain();
105    }
106
107    fn rechain(&mut self) {
108        let available: Vec<&str> = self.bundles.keys().map(String::as_str).collect();
109        self.chain = locale::chain(&self.locale, &available);
110    }
111
112    /// The current locale's tag.
113    pub fn locale(&self) -> &str {
114        &self.locale
115    }
116
117    /// The locales a lookup tries, in order.
118    pub fn chain(&self) -> &[String] {
119        &self.chain
120    }
121
122    /// The locales that have a catalogue.
123    pub fn locales(&self) -> impl Iterator<Item = &str> {
124        self.bundles.keys().map(String::as_str)
125    }
126
127    /// Adds Fluent source to a locale's catalogue. Refused, with nothing
128    /// added, when it does not parse or defines a message already there,
129    /// unless that message came from a base catalogue
130    /// ([`Catalog::add_base`]): the new text overrides it, and
131    /// [`Catalog::overridden`] says so.
132    pub fn add(&mut self, tag: &str, source: &str) -> Result<(), String> {
133        self.add_with(tag, source, None, false)
134    }
135
136    /// Adds a base catalogue (egui-pop's own): an application's catalogue
137    /// added after it may override its messages, with a warning.
138    pub fn add_base(&mut self, tag: &str, source: &str) -> Result<(), String> {
139        self.add_with(tag, source, None, false)?;
140        let tag = locale::normalize(tag).unwrap_or_default();
141        let resource = FluentResource::try_new(source.to_string()).map_err(|_| "parsed above")?;
142        let ids = resource.entries().filter_map(|e| match e {
143            Entry::Message(m) => Some(m.id.name.to_string()),
144            _ => None,
145        });
146        self.base.entry(tag).or_default().extend(ids);
147        Ok(())
148    }
149
150    /// The base messages an application's catalogue overrode: (locale,
151    /// id), in order.
152    pub fn overridden(&self) -> &[(String, String)] {
153        &self.overridden
154    }
155
156    /// Adds Fluent source whose messages replace those already there (an
157    /// override directory over the embedded catalogues).
158    pub fn add_overriding(&mut self, tag: &str, source: &str) -> Result<(), String> {
159        self.add_with(tag, source, None, true)
160    }
161
162    /// Adds a plugin's Fluent source: every message must belong to
163    /// `owner` (see [`owned_by`]); a plugin translates its own commands,
164    /// panels and settings, never another's.
165    pub fn add_owned(&mut self, owner: &str, tag: &str, source: &str) -> Result<(), String> {
166        self.add_with(tag, source, Some(owner), false)
167    }
168
169    fn add_with(
170        &mut self,
171        tag: &str,
172        source: &str,
173        owner: Option<&str>,
174        overriding: bool,
175    ) -> Result<(), String> {
176        let tag = locale::normalize(tag)
177            .filter(|t| t != PSEUDO)
178            .ok_or_else(|| format!("`{tag}` names no language"))?;
179        let resource = FluentResource::try_new(source.to_string()).map_err(|(_, errors)| {
180            let errors: Vec<String> = errors.iter().map(ToString::to_string).collect();
181            format!("does not parse: {}", errors.join("; "))
182        })?;
183        let fresh = !self.bundles.contains_key(&tag);
184        let bundle = self
185            .bundles
186            .entry(tag.clone())
187            .or_insert_with(|| new_bundle(&tag));
188        let base = self.base.get(&tag);
189        let mut overrides = Vec::new();
190        for entry in resource.entries() {
191            if let Entry::Message(m) = entry {
192                let id = m.id.name;
193                if let Some(owner) = owner.filter(|o| !owned_by(o, id)) {
194                    return Err(format!("`{id}` does not belong to `{owner}`"));
195                }
196                if !overriding && bundle.has_message(id) {
197                    if base.is_some_and(|b| b.contains(id)) {
198                        overrides.push(id.to_string());
199                    } else {
200                        return Err(format!("`{id}` is already defined for {tag}"));
201                    }
202                }
203            }
204        }
205        let overriding = overriding || !overrides.is_empty();
206        if let Some(b) = self.base.get_mut(&tag) {
207            for id in &overrides {
208                b.remove(id);
209            }
210        }
211        self.overridden
212            .extend(overrides.into_iter().map(|id| (tag.clone(), id)));
213        let ids: Vec<String> = resource
214            .entries()
215            .filter_map(|e| match e {
216                Entry::Message(m) => Some(m.id.name.to_string()),
217                _ => None,
218            })
219            .collect();
220        if overriding {
221            bundle.add_resource_overriding(resource);
222        } else {
223            bundle.add_resource(resource).map_err(|errors| {
224                let errors: Vec<String> = errors.iter().map(ToString::to_string).collect();
225                errors.join("; ")
226            })?;
227        }
228        self.ids.entry(tag).or_default().extend(ids);
229        if fresh {
230            self.rechain();
231        }
232        Ok(())
233    }
234
235    /// The text of `key` along the chain, with the locale that had it.
236    pub fn find(&self, key: &str, args: Option<&FluentArgs>) -> Option<(String, String)> {
237        self.chain.iter().find_map(|tag| {
238            let b = self.bundles.get(tag)?;
239            format(b, key, args).map(|t| (tag.clone(), self.pseudo(t)))
240        })
241    }
242
243    /// The text of `key` along the chain, English included.
244    pub fn get(&self, key: &str, args: Option<&FluentArgs>) -> Option<String> {
245        self.find(key, args).map(|(_, t)| t)
246    }
247
248    /// The text of `key` in one locale's chain (not the current one).
249    pub fn get_in(&self, locale: &str, key: &str, args: Option<&FluentArgs>) -> Option<String> {
250        let tag = locale::normalize(locale).unwrap_or_else(|| ENGLISH.into());
251        let available: Vec<&str> = self.locales().collect();
252        let text = locale::chain(&tag, &available)
253            .iter()
254            .filter_map(|t| self.bundles.get(t))
255            .find_map(|b| format(b, key, args))?;
256        Some(if tag == PSEUDO { pseudo(&text) } else { text })
257    }
258
259    /// Whether the current locale's own language has `key`: English's
260    /// text, shown for a missing translation, does not count (unless the
261    /// locale is English).
262    pub fn translated(&self, key: &str) -> bool {
263        let english = locale::language(&self.locale) == ENGLISH;
264        self.chain
265            .iter()
266            .filter(|t| english || t.as_str() != ENGLISH)
267            .filter_map(|t| self.bundles.get(t))
268            .any(|b| format(b, key, None).is_some())
269    }
270
271    /// The text of `key`, else `english` (read as a Fluent pattern when
272    /// there are arguments: `{ $count -> [one] … *[other] … }`), else the
273    /// key itself.
274    pub fn text(&self, key: &str, english: &str, args: Option<&FluentArgs>) -> String {
275        if let Some(t) = self.get(key, args) {
276            return t;
277        }
278        let text = if english.is_empty() {
279            key.to_string()
280        } else {
281            english_text(english, args)
282        };
283        self.pseudo(text)
284    }
285
286    fn pseudo(&self, text: String) -> String {
287        if self.locale == PSEUDO {
288            pseudo(&text)
289        } else {
290            text
291        }
292    }
293
294    /// Every key a locale's catalogue defines (`id`, `id.attr`).
295    pub fn keys(&self, locale: &str) -> BTreeSet<String> {
296        let mut out = BTreeSet::new();
297        let Some(b) = self.bundles.get(locale) else {
298            return out;
299        };
300        for id in self.ids.get(locale).into_iter().flatten() {
301            if let Some(m) = b.get_message(id) {
302                if m.value().is_some() {
303                    out.insert(id.clone());
304                }
305                for a in m.attributes() {
306                    out.insert(format!("{id}.{}", a.id()));
307                }
308            }
309        }
310        out
311    }
312}
313
314fn new_bundle(tag: &str) -> Bundle {
315    let id: LanguageIdentifier = tag.parse().unwrap_or_default();
316    let mut b = FluentBundle::new_concurrent(vec![id]);
317    b.set_use_isolating(false);
318    b.set_formatter(Some(crate::format::fluent_formatter));
319    // NUMBER is Fluent's own; the formatter writes it for the locale.
320    let _ = b.add_builtins();
321    let _ = b.add_function(
322        "DATETIME",
323        crate::format::datetime_function(tag.to_string()),
324    );
325    b
326}
327
328/// `key` formatted by one bundle, if it has it.
329fn format(bundle: &Bundle, key: &str, args: Option<&FluentArgs>) -> Option<String> {
330    let (id, attr) = split_key(key);
331    let message = bundle.get_message(id)?;
332    let pattern = match attr {
333        Some(a) => message.get_attribute(a)?.value(),
334        None => message.value()?,
335    };
336    let mut errors = Vec::new();
337    Some(
338        bundle
339            .format_pattern(pattern, args, &mut errors)
340            .into_owned(),
341    )
342}
343
344fn pseudo(text: &str) -> String {
345    fluent_pseudo::transform_dom(text, false, true, true).into_owned()
346}
347
348/// English written in the code, with its arguments placed.
349pub fn english_text(english: &str, args: Option<&FluentArgs>) -> String {
350    let Some(args) = args else {
351        return english.to_string();
352    };
353    let source = format!("m = {}", english.replace('\n', "\n    "));
354    let Ok(resource) = FluentResource::try_new(source) else {
355        return english.to_string();
356    };
357    let mut bundle = new_bundle(ENGLISH);
358    if bundle.add_resource(resource).is_err() {
359        return english.to_string();
360    }
361    format(&bundle, "m", Some(args)).unwrap_or_else(|| english.to_string())
362}