use std::sync::RwLock;
pub type Resolver =
fn(Option<&'static Catalogue>, &str, &[(&str, Argument)], Fill) -> Option<String>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fill {
AsGiven,
Whole,
}
#[derive(Debug)]
pub struct Catalogue {
pub id: &'static str,
pub source: &'static str,
pub dir: &'static str,
pub locales: &'static [&'static str],
}
#[derive(Clone, Debug)]
pub struct Word {
pub key: &'static str,
pub source: &'static str,
pub catalogue: Option<&'static Catalogue>,
pub arguments: Vec<(&'static str, Argument)>,
}
impl Word {
#[must_use]
pub fn read(&self) -> String {
resolve(self.catalogue, self.key, &self.arguments, Fill::AsGiven)
.unwrap_or_else(|| filled(self.source, &self.arguments))
}
}
fn filled(source: &str, arguments: &[(&'static str, Argument)]) -> String {
let mut out = String::with_capacity(source.len());
let mut rest = source;
while let Some(open) = rest.find('{') {
out.push_str(rest.get(..open).unwrap_or_default());
let after = rest.get(open.saturating_add(1)..).unwrap_or_default();
let Some(close) = matching_close(after) else {
out.push_str(rest.get(open..).unwrap_or_default());
return out;
};
let placeable = after.get(..close).unwrap_or_default().trim();
rest = after.get(close.saturating_add(1)..).unwrap_or_default();
out.push_str(
&placeable_text(placeable, arguments).unwrap_or_else(|| format!("{{{placeable}}}")),
);
}
out.push_str(rest);
out
}
fn matching_close(after: &str) -> Option<usize> {
let mut depth = 0_usize;
for (at, character) in after.char_indices() {
match character {
'{' => depth = depth.saturating_add(1),
'}' if depth == 0 => return Some(at),
'}' => depth = depth.saturating_sub(1),
_ => {}
}
}
None
}
fn placeable_text(placeable: &str, arguments: &[(&'static str, Argument)]) -> Option<String> {
let (name, body) = match placeable.split_once("->") {
Some((name, body)) => (name.trim(), Some(body)),
None => (placeable, None),
};
let name = name.strip_prefix('$')?.trim();
let (_, value) = arguments.iter().find(|(called, _)| *called == name)?;
match body {
None => Some(shown(value)),
Some(body) => {
let wanted = match value {
Argument::Number(count) if (*count - 1.0).abs() < f64::EPSILON => "one",
_ => "other",
};
let forms: Vec<(&str, bool, &str)> = body
.lines()
.filter_map(|line| {
let line = line.trim();
let starred = line.starts_with('*');
let line = line.strip_prefix('*').unwrap_or(line).trim_start();
let (key, text) = line.strip_prefix('[')?.split_once(']')?;
Some((key, starred, text.trim()))
})
.collect();
let (_, _, text) = forms
.iter()
.find(|(key, _, _)| *key == wanted)
.or_else(|| forms.iter().find(|(_, starred, _)| *starred))?;
Some(filled(text, arguments))
}
}
}
fn shown(value: &Argument) -> String {
match value {
Argument::Text(text) => text.clone(),
Argument::Number(count) if count.fract() == 0.0 => format!("{count:.0}"),
Argument::Number(count) => count.to_string(),
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Argument {
Text(String),
Number(f64),
}
impl From<&str> for Argument {
fn from(text: &str) -> Self {
Self::Text(text.to_owned())
}
}
impl From<&String> for Argument {
fn from(text: &String) -> Self {
Self::Text(text.clone())
}
}
impl From<String> for Argument {
fn from(text: String) -> Self {
Self::Text(text)
}
}
impl From<std::borrow::Cow<'_, str>> for Argument {
fn from(text: std::borrow::Cow<'_, str>) -> Self {
Self::Text(text.into_owned())
}
}
macro_rules! argument_from_count {
($($t:ty),*) => {$(
impl From<$t> for Argument {
fn from(count: $t) -> Self {
#[allow(
clippy::cast_precision_loss,
clippy::cast_lossless,
reason = "a count a message shows is far below what f64 holds exactly"
)]
let count = count as f64;
Self::Number(count)
}
}
)*};
}
argument_from_count!(usize, u32, i64, f64);
#[must_use]
pub fn titled(
word: &Word,
scope: &str,
params: Vec<tilo_actions::ActionParam>,
) -> Vec<tilo_actions::ActionParam> {
let scope = message_key(scope);
params
.into_iter()
.map(|param| {
let name = message_key(param.name.as_ref());
let title = resolve(
word.catalogue,
&format!("{}-{name}", word.key),
&[],
Fill::Whole,
)
.or_else(|| resolve(word.catalogue, &format!("{scope}-{name}"), &[], Fill::Whole));
match title {
Some(title) => param.described(title),
None => param,
}
})
.collect()
}
fn resolve(
catalogue: Option<&'static Catalogue>,
key: &str,
arguments: &[(&str, Argument)],
fill: Fill,
) -> Option<String> {
let resolver = *RESOLVER
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
resolver.and_then(|(resolve, _)| resolve(catalogue, key, arguments, fill))
}
pub type NounResolver = fn(&str, u32) -> Option<String>;
pub type Revision = fn() -> u64;
static RESOLVER: RwLock<Option<(Resolver, Revision)>> = RwLock::new(None);
static NOUN_RESOLVER: RwLock<Option<NounResolver>> = RwLock::new(None);
pub fn install(resolver: Resolver, revision: Revision) {
*RESOLVER
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some((resolver, revision));
}
#[must_use]
pub fn revision() -> u64 {
RESOLVER
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.map_or(0, |(_, revision)| revision())
}
pub fn install_noun(resolver: NounResolver) {
*NOUN_RESOLVER
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(resolver);
}
pub use tilo_actions::{message_key, noun_key};
#[macro_export]
macro_rules! declared_catalogue {
($vis:vis $name:ident) => {
$vis static $name: $crate::label::Catalogue = $crate::label::Catalogue {
id: ::core::env!("CARGO_PKG_NAME"),
source: ::core::include_str!(::core::concat!(
::core::env!("CARGO_MANIFEST_DIR"),
"/locales/en-US.ftl"
)),
dir: ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/locales"),
locales: &["de-DE", "en-US"],
};
};
}
#[macro_export]
macro_rules! declared_names {
() => {
mod i18n {
$crate::declared_catalogue!(CATALOGUE);
pub(crate) fn name(kind: &str, source: &str) -> String {
$crate::label::localized(kind, source, Some(&CATALOGUE))
}
}
};
}
#[must_use]
pub fn localized(kind: &str, source: &str, catalogue: Option<&'static Catalogue>) -> String {
resolve(catalogue, &message_key(kind), &[], Fill::Whole).unwrap_or_else(|| source.to_owned())
}
#[must_use]
pub fn published(
kind: &str,
label: &str,
declared: &str,
catalogue: Option<&'static Catalogue>,
) -> String {
if label == declared {
localized(kind, declared, catalogue)
} else {
label.to_owned()
}
}
#[must_use]
pub fn localized_noun(kind: &str, derived: tilo_actions::Noun) -> tilo_actions::Noun {
let resolver = *NOUN_RESOLVER
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(resolve) = resolver else {
return derived;
};
let key = noun_key(kind);
tilo_actions::Noun {
one: resolve(&key, 1).unwrap_or(derived.one),
many: resolve(&key, 2).unwrap_or(derived.many),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_word_without_a_lookup_fills_its_placeables() {
let pair = Word {
key: "merge-title-pair",
source: "Merge of { $ours } and { $theirs }",
catalogue: None,
arguments: vec![
("ours", Argument::from("a.txt")),
("theirs", Argument::from("b.txt")),
],
};
assert_eq!(pair.read(), "Merge of a.txt and b.txt");
let rules = Word {
key: "zone-rules",
source: "{ $count ->\n [one] 1 rule\n *[other] { $count } rules\n}",
catalogue: None,
arguments: vec![("count", Argument::from(2_usize))],
};
assert_eq!(rules.read(), "2 rules");
let one = Word {
arguments: vec![("count", Argument::from(1_usize))],
..rules
};
assert_eq!(one.read(), "1 rule");
}
fn german(
_: Option<&'static Catalogue>,
key: &str,
_: &[(&str, Argument)],
_: Fill,
) -> Option<String> {
(key == "add-app-question").then(|| "Zu den Apps hinzufügen".to_owned())
}
tilo_test_env::scenario! {
fn a_kind_and_its_words_read_in_the_persons_language;
phase a_kind_reads_under_its_own_key;
{
assert_eq!(message_key("add-app.question"), "add-app-question");
assert_eq!(message_key("lock.screen"), "lock-screen");
assert_eq!(message_key("example.todo_list"), "example-todo-list");
}
phase a_kind_is_named_by_its_entry_and_by_its_declaration_without_one;
{
install(german, || 0);
assert_eq!(
localized("add-app.question", "Add to apps", None),
"Zu den Apps hinzufügen"
);
assert_eq!(localized("lock.screen", "Lock screen", None), "Lock screen");
}
phase a_words_placeables_are_filled_in_the_language_it_is_read_in;
{
fn naming(
_: Option<&'static Catalogue>,
key: &str,
arguments: &[(&str, Argument)],
_: Fill,
) -> Option<String> {
if key != "files-folder-rename-selected" {
return None;
}
let named = arguments.iter().find_map(|(name, value)| match value {
Argument::Text(text) if *name == "name" => Some(text.as_str()),
_ => None,
});
Some(format!("„{}“ umbenennen", named.unwrap_or_default()))
}
install(naming, || 0);
let word = Word {
key: "files-folder-rename-selected",
source: "Rename \u{201c}{ $name }\u{201d}",
catalogue: None,
arguments: vec![("name", Argument::from("Bericht.pdf"))],
};
assert_eq!(word.read(), "„Bericht.pdf“ umbenennen");
}
phase a_resource_named_by_its_publisher_keeps_that_name;
{
install(german, || 0);
assert_eq!(
published("add-app.question", "Add to apps", "Add to apps", None),
"Zu den Apps hinzufügen"
);
assert_eq!(
published("add-app.question", "Frogs, by name", "Add to apps", None),
"Frogs, by name"
);
}
phase a_kind_refines_its_noun_from_its_entry_and_keeps_the_derived_one_without_it;
{
install_noun(|key, count| match (key, count) {
("notes-note-noun", 1) => Some("notebook".to_owned()),
("notes-note-noun", 2) => Some("notebooks".to_owned()),
_ => None,
});
assert_eq!(noun_key("notes.note"), "notes-note-noun");
assert_eq!(
localized_noun("notes.note", tilo_actions::Noun::of_type("Note")),
tilo_actions::Noun::new("notebook", "notebooks"),
"the catalogue says what the app calls it"
);
assert_eq!(
localized_noun("lock.screen", tilo_actions::Noun::of_type("Screen")),
tilo_actions::Noun::new("screen", "screens"),
"a noun no catalogue holds is the derived one"
);
}
}
}