Skip to main content

tilo_resource/
label.rs

1//! What a person calls a resource, in the language they read.
2//!
3//! A resource declares its name once, on its type, in the language the
4//! declaration is written in ([`Resource::LABEL`](crate::Resource::LABEL)).
5//! That name is the source text of one catalogue entry per kind, keyed by
6//! [`message_key`], so a resource published on a desktop that speaks another
7//! language is published named in it — and named by its declaration where
8//! no catalogue of theirs holds the key.
9//!
10//! An action is named the same way: what it declares is a [`Word`], a key of
11//! the catalogue beside the crate that declares it, its source text read
12//! from that catalogue when the crate was built. It is read in the person's
13//! language each time the action is published ([`Word::read`]), its
14//! placeables filled with the [`Argument`]s it carries — so an action bound
15//! to what a person is looking at ("Rename “report.pdf”") names it in every
16//! language too.
17//!
18//! A host that keeps a catalogue installs the lookup with
19//! [`install`]; until it does, every kind is named by its declaration text.
20//! This crate has no rendering or catalogue dependency, so the one path a
21//! translated name is read through stays the host's.
22
23use std::sync::RwLock;
24
25/// How a host resolves a key in the language the person reads, its
26/// placeables filled with `arguments`, joining the [`Catalogue`] that holds
27/// it first when one is named; `None` when none of their catalogues holds it
28/// as [`Fill`] asks.
29pub type Resolver =
30    fn(Option<&'static Catalogue>, &str, &[(&str, Argument)], Fill) -> Option<String>;
31
32/// What a resolution takes of a message whose placeables `arguments` leave
33/// unfilled.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum Fill {
36    /// A declared [`Word`], whose arguments its build checked against the
37    /// source language: a catalogue that still names a value it lacks is
38    /// shown as best it can be, and the host reports it.
39    AsGiven,
40    /// A key derived by convention (a parameter's title, a kind's name):
41    /// another message can share it — a history sentence for the field a
42    /// parameter sets ("Named the workbook { $new }") — and one that takes a
43    /// value this lookup cannot give is not this key's word.
44    Whole,
45}
46
47/// The catalogue beside a crate, as a declaration of it names its words by:
48/// its source language embedded, its other languages read where language
49/// packs are (`<root>/<locale>/<id>.ftl`) or beside the crate.
50#[derive(Debug)]
51pub struct Catalogue {
52    /// Its name in a language pack: the crate's package name.
53    pub id: &'static str,
54    /// The source language's Fluent text (`locales/en-US.ftl`).
55    pub source: &'static str,
56    /// The crate's `locales/` directory where it was built.
57    pub dir: &'static str,
58    /// Every locale the crate translates it into, its source among them.
59    pub locales: &'static [&'static str],
60}
61
62/// A declared word: a key of its crate's [`Catalogue`] and the text the
63/// catalogue's source language gives it.
64#[derive(Clone, Debug)]
65pub struct Word {
66    pub key: &'static str,
67    /// What the source language says: the text where no catalogue of the
68    /// person's holds the key.
69    pub source: &'static str,
70    pub catalogue: Option<&'static Catalogue>,
71    /// What the placeables of the message show (`name = …`), by the names
72    /// the message calls them: a word naming what a person looks at
73    /// ("Rename “report.pdf”") carries it here rather than in text no
74    /// catalogue can translate.
75    pub arguments: Vec<(&'static str, Argument)>,
76}
77
78impl Word {
79    /// The word in the person's language, its placeables filled — and its
80    /// declared text, its placeables filled too, where no catalogue of theirs
81    /// holds the key, or where no process installed one ([`install`]): a server or
82    /// an agent applying an action reads the same words as a window without the
83    /// catalogue syntax.
84    #[must_use]
85    pub fn read(&self) -> String {
86        resolve(self.catalogue, self.key, &self.arguments, Fill::AsGiven)
87            .unwrap_or_else(|| filled(self.source, &self.arguments))
88    }
89}
90
91/// `source` with its placeables filled from `arguments`: a simple one shows its
92/// argument, a select block the form its count names (else the `*` form), and
93/// a placeable no argument names stays as the catalogue wrote it.
94fn filled(source: &str, arguments: &[(&'static str, Argument)]) -> String {
95    let mut out = String::with_capacity(source.len());
96    let mut rest = source;
97    while let Some(open) = rest.find('{') {
98        out.push_str(rest.get(..open).unwrap_or_default());
99        let after = rest.get(open.saturating_add(1)..).unwrap_or_default();
100        let Some(close) = matching_close(after) else {
101            out.push_str(rest.get(open..).unwrap_or_default());
102            return out;
103        };
104        let placeable = after.get(..close).unwrap_or_default().trim();
105        rest = after.get(close.saturating_add(1)..).unwrap_or_default();
106        out.push_str(
107            &placeable_text(placeable, arguments).unwrap_or_else(|| format!("{{{placeable}}}")),
108        );
109    }
110    out.push_str(rest);
111    out
112}
113
114/// The offset of the `}` closing a placeable whose text starts at `after`:
115/// a select block holds placeables of its own, so braces pair up.
116fn matching_close(after: &str) -> Option<usize> {
117    let mut depth = 0_usize;
118    for (at, character) in after.char_indices() {
119        match character {
120            '{' => depth = depth.saturating_add(1),
121            '}' if depth == 0 => return Some(at),
122            '}' => depth = depth.saturating_sub(1),
123            _ => {}
124        }
125    }
126    None
127}
128
129/// What the placeable `placeable` (the text between its braces) shows, or
130/// `None` when no argument fills it.
131fn placeable_text(placeable: &str, arguments: &[(&'static str, Argument)]) -> Option<String> {
132    let (name, body) = match placeable.split_once("->") {
133        Some((name, body)) => (name.trim(), Some(body)),
134        None => (placeable, None),
135    };
136    let name = name.strip_prefix('$')?.trim();
137    let (_, value) = arguments.iter().find(|(called, _)| *called == name)?;
138    match body {
139        None => Some(shown(value)),
140        Some(body) => {
141            let wanted = match value {
142                Argument::Number(count) if (*count - 1.0).abs() < f64::EPSILON => "one",
143                _ => "other",
144            };
145            let forms: Vec<(&str, bool, &str)> = body
146                .lines()
147                .filter_map(|line| {
148                    let line = line.trim();
149                    let starred = line.starts_with('*');
150                    let line = line.strip_prefix('*').unwrap_or(line).trim_start();
151                    let (key, text) = line.strip_prefix('[')?.split_once(']')?;
152                    Some((key, starred, text.trim()))
153                })
154                .collect();
155            let (_, _, text) = forms
156                .iter()
157                .find(|(key, _, _)| *key == wanted)
158                .or_else(|| forms.iter().find(|(_, starred, _)| *starred))?;
159            Some(filled(text, arguments))
160        }
161    }
162}
163
164/// What one argument shows.
165fn shown(value: &Argument) -> String {
166    match value {
167        Argument::Text(text) => text.clone(),
168        Argument::Number(count) if count.fract() == 0.0 => format!("{count:.0}"),
169        Argument::Number(count) => count.to_string(),
170    }
171}
172
173/// One argument of a [`Word`]: what one of its placeables (`{ $name }`)
174/// shows in every language.
175#[derive(Clone, Debug, PartialEq)]
176pub enum Argument {
177    /// Words as they are, in no catalogue: the name of a file, a marker.
178    Text(String),
179    /// A number, which a message with count forms (`{ $count -> [one] … }`)
180    /// selects its form by.
181    Number(f64),
182}
183
184impl From<&str> for Argument {
185    fn from(text: &str) -> Self {
186        Self::Text(text.to_owned())
187    }
188}
189
190impl From<&String> for Argument {
191    fn from(text: &String) -> Self {
192        Self::Text(text.clone())
193    }
194}
195
196impl From<String> for Argument {
197    fn from(text: String) -> Self {
198        Self::Text(text)
199    }
200}
201
202impl From<std::borrow::Cow<'_, str>> for Argument {
203    fn from(text: std::borrow::Cow<'_, str>) -> Self {
204        Self::Text(text.into_owned())
205    }
206}
207
208/// A count a message shows, as the number its forms select by: a selection of
209/// one entry, or of several, that is never near what `f64` holds exactly.
210macro_rules! argument_from_count {
211    ($($t:ty),*) => {$(
212        impl From<$t> for Argument {
213            fn from(count: $t) -> Self {
214                #[allow(
215                    clippy::cast_precision_loss,
216                    clippy::cast_lossless,
217                    reason = "a count a message shows is far below what f64 holds exactly"
218                )]
219                let count = count as f64;
220                Self::Number(count)
221            }
222        }
223    )*};
224}
225
226argument_from_count!(usize, u32, i64, f64);
227
228/// `params`, each called what the catalogue of `word` calls it where it
229/// holds a word for it: the action's own (`<action key>-<param>`), else the
230/// one every action of `scope` (an operation or a kind) shares
231/// (`<scope>-<param>`). A parameter neither names keeps its schema as it is.
232#[must_use]
233pub fn titled(
234    word: &Word,
235    scope: &str,
236    params: Vec<tilo_actions::ActionParam>,
237) -> Vec<tilo_actions::ActionParam> {
238    let scope = message_key(scope);
239    params
240        .into_iter()
241        .map(|param| {
242            let name = message_key(param.name.as_ref());
243            let title = resolve(
244                word.catalogue,
245                &format!("{}-{name}", word.key),
246                &[],
247                Fill::Whole,
248            )
249            .or_else(|| resolve(word.catalogue, &format!("{scope}-{name}"), &[], Fill::Whole));
250            match title {
251                Some(title) => param.described(title),
252                None => param,
253            }
254        })
255        .collect()
256}
257
258/// `key` through the installed resolver, `None` without one.
259fn resolve(
260    catalogue: Option<&'static Catalogue>,
261    key: &str,
262    arguments: &[(&str, Argument)],
263    fill: Fill,
264) -> Option<String> {
265    let resolver = *RESOLVER
266        .read()
267        .unwrap_or_else(std::sync::PoisonError::into_inner);
268    resolver.and_then(|(resolve, _)| resolve(catalogue, key, arguments, fill))
269}
270
271/// How a host resolves [`noun_key`] with the count `1` (one of it) or `2`
272/// (several); `None` when none of their catalogues holds it.
273pub type NounResolver = fn(&str, u32) -> Option<String>;
274
275/// What the words resolve at now on this thread: it moves when the person's
276/// language, or a catalogue of theirs, does.
277pub type Revision = fn() -> u64;
278
279static RESOLVER: RwLock<Option<(Resolver, Revision)>> = RwLock::new(None);
280static NOUN_RESOLVER: RwLock<Option<NounResolver>> = RwLock::new(None);
281
282/// Let every kind published from now on be named through `resolver`.
283///
284/// A host installs its catalogue's lookup once per process; a later call
285/// replaces an earlier one.
286///
287/// # Panics
288/// Only if the lock was poisoned by a panic while installing, which is not
289/// a state any caller can be handed.
290pub fn install(resolver: Resolver, revision: Revision) {
291    *RESOLVER
292        .write()
293        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((resolver, revision));
294}
295
296/// What the words resolve at now on this thread ([`Revision`]); `0` before
297/// a host installed its catalogue. What is kept of a published action is
298/// built again when it moves, so it is published in the language read now.
299#[must_use]
300pub fn revision() -> u64 {
301    RESOLVER
302        .read()
303        .unwrap_or_else(std::sync::PoisonError::into_inner)
304        .map_or(0, |(_, revision)| revision())
305}
306
307/// Let every kind published from now on read its noun through `resolver`:
308/// one message with `$count`, one for a count of `1` and one for several
309/// ([`noun_key`]). A later call replaces an earlier one.
310///
311/// # Panics
312/// Only if the lock was poisoned by a panic while installing.
313pub fn install_noun(resolver: NounResolver) {
314    *NOUN_RESOLVER
315        .write()
316        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(resolver);
317}
318
319pub use tilo_actions::{message_key, noun_key};
320
321/// The catalogue beside the crate being built, as a `static`:
322/// `declared_catalogue!(CATALOGUE);`, its source language embedded and its
323/// other languages read from the language packs as a declaration's words are.
324///
325/// A declaration names its words through its own catalogue; a crate that
326/// publishes a resource of a kind no declaration of its owns — a service's
327/// rows, read from what the machine holds — names it through this one
328/// ([`localized`] of the kind and the name it declares).
329#[macro_export]
330macro_rules! declared_catalogue {
331    ($vis:vis $name:ident) => {
332        $vis static $name: $crate::label::Catalogue = $crate::label::Catalogue {
333            id: ::core::env!("CARGO_PKG_NAME"),
334            source: ::core::include_str!(::core::concat!(
335                ::core::env!("CARGO_MANIFEST_DIR"),
336                "/locales/en-US.ftl"
337            )),
338            dir: ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/locales"),
339            locales: &["de-DE", "en-US"],
340        };
341    };
342}
343
344/// What a resource of a kind this crate publishes from outside a document is
345/// called, in the person's language: the kind's entry in the catalogue beside
346/// this crate, read the way a declaration's words are.
347///
348/// Declares a module `i18n` holding the crate's `CATALOGUE` (through
349/// `declared_catalogue!`) and `pub(crate) fn name(kind, source)` (through
350/// [`localized`]).
351#[macro_export]
352macro_rules! declared_names {
353    () => {
354        mod i18n {
355            $crate::declared_catalogue!(CATALOGUE);
356
357            pub(crate) fn name(kind: &str, source: &str) -> String {
358                $crate::label::localized(kind, source, Some(&CATALOGUE))
359            }
360        }
361    };
362}
363
364/// `source`, the name the resource declares, in the person's language: the
365/// catalogue entry for `kind` when one of theirs holds it, `source` itself
366/// otherwise.
367#[must_use]
368pub fn localized(kind: &str, source: &str, catalogue: Option<&'static Catalogue>) -> String {
369    resolve(catalogue, &message_key(kind), &[], Fill::Whole).unwrap_or_else(|| source.to_owned())
370}
371
372/// [`localized`] of a resource that is being published under `label`: its
373/// declared name when the publisher kept that name, and `label` as it
374/// stands when the publisher names the resource itself — a state-dependent
375/// title, say — which no catalogue of the kind can know.
376#[must_use]
377pub fn published(
378    kind: &str,
379    label: &str,
380    declared: &str,
381    catalogue: Option<&'static Catalogue>,
382) -> String {
383    if label == declared {
384        localized(kind, declared, catalogue)
385    } else {
386        label.to_owned()
387    }
388}
389
390/// The noun `derived` for the type of `kind`, in the person's language: the
391/// catalogue's message for it, one and several, where one of theirs holds
392/// it, `derived` otherwise. A kind's noun is code's to derive and the
393/// catalogue's to refine, never a list of irregulars in code.
394#[must_use]
395pub fn localized_noun(kind: &str, derived: tilo_actions::Noun) -> tilo_actions::Noun {
396    let resolver = *NOUN_RESOLVER
397        .read()
398        .unwrap_or_else(std::sync::PoisonError::into_inner);
399    let Some(resolve) = resolver else {
400        return derived;
401    };
402    let key = noun_key(kind);
403    tilo_actions::Noun {
404        one: resolve(&key, 1).unwrap_or(derived.one),
405        many: resolve(&key, 2).unwrap_or(derived.many),
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    /// A word read where no process installed a lookup — a server applying an
414    /// action, an agent reading one — fills its placeables from the source
415    /// text rather than showing the catalogue syntax.
416    #[test]
417    fn a_word_without_a_lookup_fills_its_placeables() {
418        let pair = Word {
419            key: "merge-title-pair",
420            source: "Merge of { $ours } and { $theirs }",
421            catalogue: None,
422            arguments: vec![
423                ("ours", Argument::from("a.txt")),
424                ("theirs", Argument::from("b.txt")),
425            ],
426        };
427        assert_eq!(pair.read(), "Merge of a.txt and b.txt");
428        let rules = Word {
429            key: "zone-rules",
430            source: "{ $count ->\n    [one] 1 rule\n   *[other] { $count } rules\n}",
431            catalogue: None,
432            arguments: vec![("count", Argument::from(2_usize))],
433        };
434        assert_eq!(rules.read(), "2 rules");
435        let one = Word {
436            arguments: vec![("count", Argument::from(1_usize))],
437            ..rules
438        };
439        assert_eq!(one.read(), "1 rule");
440    }
441
442    fn german(
443        _: Option<&'static Catalogue>,
444        key: &str,
445        _: &[(&str, Argument)],
446        _: Fill,
447    ) -> Option<String> {
448        (key == "add-app-question").then(|| "Zu den Apps hinzufügen".to_owned())
449    }
450
451    tilo_test_env::scenario! {
452        fn a_kind_and_its_words_read_in_the_persons_language;
453
454        phase a_kind_reads_under_its_own_key;
455        {
456            assert_eq!(message_key("add-app.question"), "add-app-question");
457            assert_eq!(message_key("lock.screen"), "lock-screen");
458            assert_eq!(message_key("example.todo_list"), "example-todo-list");
459        }
460
461        phase a_kind_is_named_by_its_entry_and_by_its_declaration_without_one;
462        {
463            // The lookup is the process's, so every test here stands on a host
464            // that installed one.
465            install(german, || 0);
466            assert_eq!(
467                localized("add-app.question", "Add to apps", None),
468                "Zu den Apps hinzufügen"
469            );
470            assert_eq!(localized("lock.screen", "Lock screen", None), "Lock screen");
471        }
472
473        phase a_words_placeables_are_filled_in_the_language_it_is_read_in;
474        {
475            fn naming(
476                _: Option<&'static Catalogue>,
477                key: &str,
478                arguments: &[(&str, Argument)],
479                _: Fill,
480            ) -> Option<String> {
481                if key != "files-folder-rename-selected" {
482                    return None;
483                }
484                let named = arguments.iter().find_map(|(name, value)| match value {
485                    Argument::Text(text) if *name == "name" => Some(text.as_str()),
486                    _ => None,
487                });
488                Some(format!("„{}“ umbenennen", named.unwrap_or_default()))
489            }
490            install(naming, || 0);
491            let word = Word {
492                key: "files-folder-rename-selected",
493                source: "Rename \u{201c}{ $name }\u{201d}",
494                catalogue: None,
495                arguments: vec![("name", Argument::from("Bericht.pdf"))],
496            };
497            assert_eq!(word.read(), "„Bericht.pdf“ umbenennen");
498        }
499
500        phase a_resource_named_by_its_publisher_keeps_that_name;
501        {
502            install(german, || 0);
503            assert_eq!(
504                published("add-app.question", "Add to apps", "Add to apps", None),
505                "Zu den Apps hinzufügen"
506            );
507            assert_eq!(
508                published("add-app.question", "Frogs, by name", "Add to apps", None),
509                "Frogs, by name"
510            );
511        }
512
513        phase a_kind_refines_its_noun_from_its_entry_and_keeps_the_derived_one_without_it;
514        {
515            install_noun(|key, count| match (key, count) {
516                ("notes-note-noun", 1) => Some("notebook".to_owned()),
517                ("notes-note-noun", 2) => Some("notebooks".to_owned()),
518                _ => None,
519            });
520            assert_eq!(noun_key("notes.note"), "notes-note-noun");
521            assert_eq!(
522                localized_noun("notes.note", tilo_actions::Noun::of_type("Note")),
523                tilo_actions::Noun::new("notebook", "notebooks"),
524                "the catalogue says what the app calls it"
525            );
526            assert_eq!(
527                localized_noun("lock.screen", tilo_actions::Noun::of_type("Screen")),
528                tilo_actions::Noun::new("screen", "screens"),
529                "a noun no catalogue holds is the derived one"
530            );
531        }
532    }
533}