Medlar/crates/core/src/strings.rs
2026-11-24 23:29:30 -06:00

293 lines
11 KiB
Rust

//! Every text the user sees, by key.
//!
//! English is `lang/en.json`. A user file `languages/<code>.json` replaces any of its texts; what it lacks stays English.
//! A text is a string with `{name}` arguments, or an object with one text per plural category, chosen by the argument `n`.
//! Categories are those of Unicode CLDR: `zero`, `one`, `two`, `few`, `many` and `other` (always needed).
use std::collections::HashMap;
use std::fmt::Display;
use std::fs;
use std::path::Path;
use std::sync::{Arc, LazyLock, RwLock};
/// Text of a key written in the source. A test checks that the key exists.
/// `tr!("queue.main")`, `tr!("tasks.count", n = 3)`.
#[macro_export]
macro_rules! tr {
($key:literal $(, $name:ident = $value:expr)* $(,)?) => {
$crate::strings::text($key, &[$((stringify!($name), &$value)),*])
};
}
pub type Args<'a> = &'a [(&'a str, &'a dyn Display)];
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(untagged)]
enum Text {
Plain(String),
Plural(HashMap<String, String>),
}
pub struct Catalogue {
language: String,
texts: HashMap<String, Text>,
/// Keys taken from the user's file, which may need other plural rules than English.
own: HashMap<String, Text>,
}
static CURRENT: LazyLock<RwLock<Arc<Catalogue>>> = LazyLock::new(|| RwLock::new(Arc::new(Catalogue::english())));
/// Makes a catalogue the one `tr!` uses.
pub fn set(catalogue: Catalogue) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(catalogue);
}
/// Text of a key known only at run time, such as `state.<name>`. Prefer `tr!`.
pub fn text(key: &str, args: Args) -> String {
let current = CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone();
current.text(key, args)
}
impl Catalogue {
pub fn english() -> Catalogue {
let texts = serde_json::from_str(include_str!("../lang/en.json")).expect("lang/en.json is checked by a test");
Catalogue { language: "en".into(), texts, own: HashMap::new() }
}
/// The catalogue for `language`, or for the desktop's language when that is empty.
/// The second value says why a language file was left out.
pub fn load(folder: &Path, language: &str) -> (Catalogue, Option<String>) {
let wanted = if language.is_empty() { desktop_language() } else { language.into() };
let mut catalogue = Catalogue::english();
let mut problem = None;
let short = wanted.split(['-', '_']).next().unwrap_or_default().to_string();
for code in [wanted, short] {
// The code becomes a file name.
if code.is_empty() || !code.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {
continue;
}
let path = folder.join(format!("{code}.json"));
let Ok(bytes) = fs::read(&path) else { continue };
match serde_json::from_slice::<HashMap<String, Text>>(&bytes) {
Ok(own) => {
catalogue.own = own;
catalogue.language = code;
break;
}
Err(e) => problem = Some(format!("{}: {e}", path.display())),
}
}
(catalogue, problem)
}
pub fn language(&self) -> &str {
&self.language
}
/// Codes of the files in the user's folder, and English.
pub fn available(folder: &Path) -> Vec<String> {
let mut codes = vec!["en".to_string()];
for entry in fs::read_dir(folder).into_iter().flatten().flatten() {
let path = entry.path();
if path.extension().is_some_and(|e| e == "json")
&& let Some(code) = path.file_stem().and_then(|s| s.to_str())
{
codes.push(code.into());
}
}
codes.sort();
codes.dedup();
codes
}
pub fn text(&self, key: &str, args: Args) -> String {
let n = args.iter().find(|(name, _)| *name == "n").and_then(|(_, v)| v.to_string().parse().ok());
let found = |texts: &HashMap<String, Text>, language: &str| match texts.get(key)? {
Text::Plain(text) => Some(fill(text, args)),
Text::Plural(forms) => {
let form = n.map_or("other", |n| plural(language, n));
Some(fill(forms.get(form).or_else(|| forms.get("other"))?, args))
}
};
found(&self.own, &self.language).or_else(|| found(&self.texts, "en")).unwrap_or_else(|| {
log::warn!("no text for {key}");
key.into()
})
}
}
/// Puts arguments in. One pass, so braces inside a value stay as they are.
fn fill(text: &str, args: Args) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
rest = &rest[open..];
let Some(close) = rest.find('}') else { break };
match args.iter().find(|(name, _)| *name == &rest[1..close]) {
Some((_, value)) => out.push_str(&value.to_string()),
None => out.push_str(&rest[..=close]),
}
rest = &rest[close + 1..];
}
out + rest
}
/// CLDR plural category of a whole number.
fn plural(language: &str, n: u64) -> &'static str {
let (n10, n100) = (n % 10, n % 100);
let teen = (11..=14).contains(&n100);
match language.split(['-', '_']).next().unwrap_or_default() {
"ja" | "zh" | "ko" | "vi" | "th" | "id" | "ms" => "other",
"fr" | "pt" if n <= 1 => "one",
"ru" | "uk" | "be" => match n10 {
1 if n100 != 11 => "one",
2..=4 if !teen => "few",
_ => "many",
},
"sr" | "hr" | "bs" => match n10 {
1 if n100 != 11 => "one",
2..=4 if !teen => "few",
_ => "other",
},
"pl" => match n10 {
_ if n == 1 => "one",
2..=4 if !teen => "few",
_ => "many",
},
"cs" | "sk" if (2..=4).contains(&n) => "few",
"ro" if n == 0 || (n != 1 && (1..=19).contains(&n100)) => "few",
"ar" => match n {
0 => "zero",
1 => "one",
2 => "two",
_ if (3..=10).contains(&n100) => "few",
_ if n100 >= 11 => "many",
_ => "other",
},
_ if n == 1 => "one",
_ => "other",
}
}
fn desktop_language() -> String {
let value = ["LC_ALL", "LC_MESSAGES", "LANG"].iter().filter_map(|v| std::env::var(v).ok()).find(|v| !v.is_empty());
// `de_DE.UTF-8@euro` is `de_DE`.
value.unwrap_or_default().split(['.', '@']).next().unwrap_or_default().into()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{ErrorKind, Priority, State};
use std::path::PathBuf;
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
sources(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
/// Keys of the `tr!` calls in a source text.
fn keys(source: &str) -> Vec<String> {
let call = concat!("tr", "!(");
let code: String = source.lines().filter(|l| !l.trim_start().starts_with("//")).collect::<Vec<_>>().join("\n");
// Other macros end in the same letters.
let calls = code.match_indices(call).filter(|(i, _)| !code[..*i].ends_with(|c: char| c.is_alphanumeric() || c == '_'));
let literal = |c: &str| Some(c.trim_start().strip_prefix('"')?.split_once('"')?.0.to_string());
calls.filter_map(|(i, _)| literal(&code[i + call.len()..])).collect()
}
#[test]
fn every_key_used_exists() {
let mut files = vec![];
sources(&Path::new(env!("CARGO_MANIFEST_DIR")).join(".."), &mut files);
let english = Catalogue::english();
let mut missing: Vec<String> = vec![];
let mut used = 0;
for file in files {
for key in keys(&fs::read_to_string(&file).unwrap()) {
used += 1;
if !english.texts.contains_key(&key) {
missing.push(format!("{key} in {}", file.display()));
}
}
}
assert!(used > 5, "the scan found only {used} keys");
assert!(missing.is_empty(), "no text for: {missing:#?}");
}
#[test]
fn the_scan_sees_calls_over_several_lines() {
let source = format!("{}\n \"a.b\",\n n = 1); // x\n// {0}\"c.d\")", concat!("tr", "!("));
assert_eq!(keys(&source), ["a.b"]);
}
#[test]
fn every_name_has_a_label() {
let english = Catalogue::english();
let names = State::ALL.iter().map(|s| format!("state.{}", s.name()));
let names = names.chain(Priority::ALL.iter().map(|p| format!("priority.{}", p.name())));
for key in names.chain(ErrorKind::ALL.iter().map(|e| format!("error.{}", e.name()))) {
assert!(english.texts.contains_key(&key), "{key}");
}
}
#[test]
fn every_plural_has_other() {
for (key, text) in Catalogue::english().texts {
if let Text::Plural(forms) = text {
assert!(forms.contains_key("other"), "{key}");
}
}
}
#[test]
fn arguments_and_plurals() {
let en = Catalogue::english();
assert_eq!(en.text("tasks.count", &[("n", &1)]), "1 download");
assert_eq!(en.text("tasks.count", &[("n", &0)]), "0 downloads");
assert_eq!(en.text("no.such.key", &[]), "no.such.key");
assert_eq!(fill("{a} and {b} {", &[("a", &"{b}"), ("b", &2)]), "{b} and 2 {");
}
#[test]
fn user_files_are_layered_on_english() {
let dir = tempfile::tempdir().unwrap();
let file = r#"{"tasks.count": {"one": "{n} загрузка", "few": "{n} загрузки", "many": "{n} загрузок"}}"#;
fs::write(dir.path().join("ru.json"), file).unwrap();
let (ru, problem) = Catalogue::load(dir.path(), "ru_RU");
assert_eq!((problem, ru.language()), (None, "ru"));
assert_eq!(ru.text("tasks.count", &[("n", &22)]), "22 загрузки");
assert_eq!(ru.text("tasks.count", &[("n", &11)]), "11 загрузок");
assert_eq!(ru.text("queue.main", &[]), "Main");
assert_eq!(Catalogue::available(dir.path()), ["en", "ru"]);
}
#[test]
fn bad_files_and_codes_fall_back_to_english() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("de.json"), "{").unwrap();
let (c, problem) = Catalogue::load(dir.path(), "de");
assert!(problem.unwrap().contains("de.json"));
assert_eq!(c.text("queue.main", &[]), "Main");
assert_eq!(Catalogue::load(dir.path(), "../../etc/x").0.language(), "en");
}
#[test]
fn plural_rules() {
assert_eq!(plural("pl", 22), "few");
assert_eq!(plural("pl", 21), "many");
assert_eq!(plural("pt_BR", 0), "one");
assert_eq!(plural("fr", 2), "other");
assert_eq!(plural("cs", 1), "one");
assert_eq!(plural("ro", 101), "few");
assert_eq!(plural("ar", 103), "few");
assert_eq!(plural("ja", 1), "other");
}
}