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
279/// How a host reads the words of one answer in the language a caller declares (a BCP 47 tag),
280/// or in the person's own where it declares none: on this thread until what it hands back is
281/// dropped.
282pub type Reading = fn(Option<&str>) -> Box<dyn std::any::Any>;
283
284static RESOLVER: RwLock<Option<(Resolver, Revision)>> = RwLock::new(None);
285static NOUN_RESOLVER: RwLock<Option<NounResolver>> = RwLock::new(None);
286static READING: RwLock<Option<Reading>> = RwLock::new(None);
287
288/// Let the words of every answer from now on be read through `reading` ([`reading_in`]).
289///
290/// # Panics
291/// Only if the lock was poisoned by a panic while installing.
292pub fn install_reading(reading: Reading) {
293    *READING
294        .write()
295        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(reading);
296}
297
298/// `read`, every word it reads ([`Word::read`], [`localized`], [`keyed`]) read in `language`, or
299/// in the person's own where it is `None`: what a registry answers one caller's listing in.
300pub fn reading_in<T>(language: Option<&str>, read: impl FnOnce() -> T) -> T {
301    let reading = *READING
302        .read()
303        .unwrap_or_else(std::sync::PoisonError::into_inner);
304    let _reading = reading.map(|reading| reading(language));
305    read()
306}
307
308/// `future`, every word it reads read as [`reading_in`] reads them each time it runs: the work a
309/// provider goes on with after its query returned, which may wake on any thread.
310pub fn reading_while<F: std::future::Future>(
311    language: Option<String>,
312    future: F,
313) -> impl std::future::Future<Output = F::Output> {
314    let mut future = Box::pin(future);
315    std::future::poll_fn(move |cx| reading_in(language.as_deref(), || future.as_mut().poll(cx)))
316}
317
318/// Let every kind published from now on be named through `resolver`.
319///
320/// A host installs its catalogue's lookup once per process; a later call
321/// replaces an earlier one.
322///
323/// # Panics
324/// Only if the lock was poisoned by a panic while installing, which is not
325/// a state any caller can be handed.
326pub fn install(resolver: Resolver, revision: Revision) {
327    *RESOLVER
328        .write()
329        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((resolver, revision));
330}
331
332/// What the words resolve at now on this thread ([`Revision`]); `0` before
333/// a host installed its catalogue. What is kept of a published action is
334/// built again when it moves, so it is published in the language read now.
335#[must_use]
336pub fn revision() -> u64 {
337    RESOLVER
338        .read()
339        .unwrap_or_else(std::sync::PoisonError::into_inner)
340        .map_or(0, |(_, revision)| revision())
341}
342
343/// Let every kind published from now on read its noun through `resolver`:
344/// one message with `$count`, one for a count of `1` and one for several
345/// ([`noun_key`]). A later call replaces an earlier one.
346///
347/// # Panics
348/// Only if the lock was poisoned by a panic while installing.
349pub fn install_noun(resolver: NounResolver) {
350    *NOUN_RESOLVER
351        .write()
352        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(resolver);
353}
354
355pub use tilo_actions::{message_key, noun_key};
356
357/// The catalogue beside the crate being built, as a `static`:
358/// `declared_catalogue!(CATALOGUE);`, its source language embedded and its
359/// other languages read from the language packs as a declaration's words are.
360///
361/// A declaration names its words through its own catalogue; a crate that
362/// publishes a resource of a kind no declaration of its owns — a service's
363/// rows, read from what the machine holds — names it through this one
364/// ([`localized`] of the kind and the name it declares).
365#[macro_export]
366macro_rules! declared_catalogue {
367    ($vis:vis $name:ident) => {
368        $vis static $name: $crate::label::Catalogue = $crate::label::Catalogue {
369            id: ::core::env!("CARGO_PKG_NAME"),
370            source: ::core::include_str!(::core::concat!(
371                ::core::env!("CARGO_MANIFEST_DIR"),
372                "/locales/en-US.ftl"
373            )),
374            dir: ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/locales"),
375            locales: &["de-DE", "en-US"],
376        };
377    };
378}
379
380/// What a resource of a kind this crate publishes from outside a document is
381/// called, in the person's language: the kind's entry in the catalogue beside
382/// this crate, read the way a declaration's words are.
383///
384/// Declares a module `i18n` holding the crate's `CATALOGUE` (through
385/// `declared_catalogue!`) and `pub(crate) fn name(kind, source)` (through
386/// [`localized`]).
387#[macro_export]
388macro_rules! declared_names {
389    () => {
390        mod i18n {
391            $crate::declared_catalogue!(CATALOGUE);
392
393            pub(crate) fn name(kind: &str, source: &str) -> String {
394                $crate::label::localized(kind, source, Some(&CATALOGUE))
395            }
396        }
397    };
398}
399
400/// `source`, the name the resource declares, in the person's language: the
401/// catalogue entry for `kind` when one of theirs holds it, `source` itself
402/// otherwise.
403#[must_use]
404pub fn localized(kind: &str, source: &str, catalogue: Option<&'static Catalogue>) -> String {
405    resolve(catalogue, &message_key(kind), &[], Fill::Whole).unwrap_or_else(|| source.to_owned())
406}
407
408/// `source`, a word the catalogue `catalogue` keeps under `key`, as this thread reads it now: the
409/// catalogue's message where it holds one, `source` itself otherwise. What a row names a word
410/// of a catalogue without a declaration to read it from — a verb of a table of the host's — is
411/// read through.
412#[must_use]
413pub fn keyed(catalogue: &'static Catalogue, key: &str, source: &str) -> String {
414    resolve(Some(catalogue), key, &[], Fill::Whole).unwrap_or_else(|| source.to_owned())
415}
416
417/// [`localized`] of a resource that is being published under `label`: its
418/// declared name when the publisher kept that name, and `label` as it
419/// stands when the publisher names the resource itself — a state-dependent
420/// title, say — which no catalogue of the kind can know.
421#[must_use]
422pub fn published(
423    kind: &str,
424    label: &str,
425    declared: &str,
426    catalogue: Option<&'static Catalogue>,
427) -> String {
428    if label == declared {
429        localized(kind, declared, catalogue)
430    } else {
431        label.to_owned()
432    }
433}
434
435/// The noun `derived` for the type of `kind`, in the person's language: the
436/// catalogue's message for it, one and several, where one of theirs holds
437/// it, `derived` otherwise. A kind's noun is code's to derive and the
438/// catalogue's to refine, never a list of irregulars in code.
439#[must_use]
440pub fn localized_noun(kind: &str, derived: tilo_actions::Noun) -> tilo_actions::Noun {
441    let resolver = *NOUN_RESOLVER
442        .read()
443        .unwrap_or_else(std::sync::PoisonError::into_inner);
444    let Some(resolve) = resolver else {
445        return derived;
446    };
447    let key = noun_key(kind);
448    tilo_actions::Noun {
449        one: resolve(&key, 1).unwrap_or(derived.one),
450        many: resolve(&key, 2).unwrap_or(derived.many),
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    /// A word read where no process installed a lookup — a server applying an
459    /// action, an agent reading one — fills its placeables from the source
460    /// text rather than showing the catalogue syntax.
461    #[test]
462    fn a_word_without_a_lookup_fills_its_placeables() {
463        let pair = Word {
464            key: "merge-title-pair",
465            source: "Merge of { $ours } and { $theirs }",
466            catalogue: None,
467            arguments: vec![
468                ("ours", Argument::from("a.txt")),
469                ("theirs", Argument::from("b.txt")),
470            ],
471        };
472        assert_eq!(pair.read(), "Merge of a.txt and b.txt");
473        let rules = Word {
474            key: "zone-rules",
475            source: "{ $count ->\n    [one] 1 rule\n   *[other] { $count } rules\n}",
476            catalogue: None,
477            arguments: vec![("count", Argument::from(2_usize))],
478        };
479        assert_eq!(rules.read(), "2 rules");
480        let one = Word {
481            arguments: vec![("count", Argument::from(1_usize))],
482            ..rules
483        };
484        assert_eq!(one.read(), "1 rule");
485    }
486
487    fn german(
488        _: Option<&'static Catalogue>,
489        key: &str,
490        _: &[(&str, Argument)],
491        _: Fill,
492    ) -> Option<String> {
493        (key == "add-app-question").then(|| "Zu den Apps hinzufügen".to_owned())
494    }
495
496    tilo_test_env::scenario! {
497        fn a_kind_and_its_words_read_in_the_persons_language;
498
499        phase a_kind_reads_under_its_own_key;
500        {
501            assert_eq!(message_key("add-app.question"), "add-app-question");
502            assert_eq!(message_key("lock.screen"), "lock-screen");
503            assert_eq!(message_key("example.todo_list"), "example-todo-list");
504        }
505
506        phase a_kind_is_named_by_its_entry_and_by_its_declaration_without_one;
507        {
508            // The lookup is the process's, so every test here stands on a host
509            // that installed one.
510            install(german, || 0);
511            assert_eq!(
512                localized("add-app.question", "Add to apps", None),
513                "Zu den Apps hinzufügen"
514            );
515            assert_eq!(localized("lock.screen", "Lock screen", None), "Lock screen");
516        }
517
518        phase a_words_placeables_are_filled_in_the_language_it_is_read_in;
519        {
520            fn naming(
521                _: Option<&'static Catalogue>,
522                key: &str,
523                arguments: &[(&str, Argument)],
524                _: Fill,
525            ) -> Option<String> {
526                if key != "files-folder-rename-selected" {
527                    return None;
528                }
529                let named = arguments.iter().find_map(|(name, value)| match value {
530                    Argument::Text(text) if *name == "name" => Some(text.as_str()),
531                    _ => None,
532                });
533                Some(format!("„{}“ umbenennen", named.unwrap_or_default()))
534            }
535            install(naming, || 0);
536            let word = Word {
537                key: "files-folder-rename-selected",
538                source: "Rename \u{201c}{ $name }\u{201d}",
539                catalogue: None,
540                arguments: vec![("name", Argument::from("Bericht.pdf"))],
541            };
542            assert_eq!(word.read(), "„Bericht.pdf“ umbenennen");
543        }
544
545        phase a_resource_named_by_its_publisher_keeps_that_name;
546        {
547            install(german, || 0);
548            assert_eq!(
549                published("add-app.question", "Add to apps", "Add to apps", None),
550                "Zu den Apps hinzufügen"
551            );
552            assert_eq!(
553                published("add-app.question", "Frogs, by name", "Add to apps", None),
554                "Frogs, by name"
555            );
556        }
557
558        phase a_kind_refines_its_noun_from_its_entry_and_keeps_the_derived_one_without_it;
559        {
560            install_noun(|key, count| match (key, count) {
561                ("notes-note-noun", 1) => Some("notebook".to_owned()),
562                ("notes-note-noun", 2) => Some("notebooks".to_owned()),
563                _ => None,
564            });
565            assert_eq!(noun_key("notes.note"), "notes-note-noun");
566            assert_eq!(
567                localized_noun("notes.note", tilo_actions::Noun::of_type("Note")),
568                tilo_actions::Noun::new("notebook", "notebooks"),
569                "the catalogue says what the app calls it"
570            );
571            assert_eq!(
572                localized_noun("lock.screen", tilo_actions::Noun::of_type("Screen")),
573                tilo_actions::Noun::new("screen", "screens"),
574                "a noun no catalogue holds is the derived one"
575            );
576        }
577    }
578}