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
279static RESOLVER: RwLock<Option<(Resolver, Revision)>> = RwLock::new(None);
280static NOUN_RESOLVER: RwLock<Option<NounResolver>> = RwLock::new(None);
281
282pub 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#[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
307pub 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#[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#[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#[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#[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#[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 #[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 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}