1use std::sync::RwLock;
24
25pub type Resolver =
30 fn(Option<&'static Catalogue>, &str, &[(&str, Argument)], Fill) -> Option<String>;
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum Fill {
36 AsGiven,
40 Whole,
45}
46
47#[derive(Debug)]
51pub struct Catalogue {
52 pub id: &'static str,
54 pub source: &'static str,
56 pub dir: &'static str,
58 pub locales: &'static [&'static str],
60}
61
62#[derive(Clone, Debug)]
65pub struct Word {
66 pub key: &'static str,
67 pub source: &'static str,
70 pub catalogue: Option<&'static Catalogue>,
71 pub arguments: Vec<(&'static str, Argument)>,
76}
77
78impl Word {
79 #[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
91fn 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
114fn 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
129fn 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
164fn 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#[derive(Clone, Debug, PartialEq)]
176pub enum Argument {
177 Text(String),
179 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
208macro_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#[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
258fn 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
271pub type NounResolver = fn(&str, u32) -> Option<String>;
274
275pub type Revision = fn() -> u64;
278
279pub 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
288pub fn install_reading(reading: Reading) {
293 *READING
294 .write()
295 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(reading);
296}
297
298pub 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
308pub 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
318pub 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#[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
343pub 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#[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#[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#[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#[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#[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#[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 #[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 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}