rosier 0.3.0

A fast picture and video viewer for large folders
//! Translations, in Project Fluent: one `locales/<code>.ftl` per language,
//! compiled in. Fluent picks plural forms by each language's CLDR rules.
//! The language is the one chosen in the sidebar, or else the system's (see
//! `init`), and can be switched while running. A message missing from a
//! catalog falls back to English, then to its key.

use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};

use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentArgs, FluentResource, FluentValue};

/// Every language: its code, its own name, and its catalog. English first.
pub const LANGS: &[(&str, &str, &str)] = &[
    ("en", "English", include_str!("../locales/en.ftl")),
    ("ja", "日本語", include_str!("../locales/ja.ftl")),
    ("zh-CN", "简体中文", include_str!("../locales/zh-CN.ftl")),
    ("zh-TW", "繁體中文", include_str!("../locales/zh-TW.ftl")),
    ("ko", "한국어", include_str!("../locales/ko.ftl")),
    ("es", "Español", include_str!("../locales/es.ftl")),
    ("pt-BR", "Português (Brasil)", include_str!("../locales/pt-BR.ftl")),
    ("fr", "Français", include_str!("../locales/fr.ftl")),
    ("de", "Deutsch", include_str!("../locales/de.ftl")),
    ("it", "Italiano", include_str!("../locales/it.ftl")),
    ("ru", "Русский", include_str!("../locales/ru.ftl")),
];

type Bundle = FluentBundle<FluentResource>;

fn bundle(code: &str, src: &str) -> Bundle {
    let lang = code.parse().unwrap_or_default();
    let mut b = FluentBundle::new_concurrent(vec![lang]);
    // Unicode isolation marks around values would show up as stray glyphs.
    b.set_use_isolating(false);
    // A broken catalog is caught by the tests; at run time keep what parsed.
    let res = FluentResource::try_new(src.to_string()).unwrap_or_else(|(res, _)| res);
    let _ = b.add_resource(res);
    b
}

fn bundles() -> &'static [Bundle] {
    static B: OnceLock<Vec<Bundle>> = OnceLock::new();
    B.get_or_init(|| LANGS.iter().map(|(code, _, src)| bundle(code, src)).collect())
}

/// Message ids use dashes (Fluent's style); callers write keys with dots or
/// underscores.
fn id(key: &str) -> String {
    key.replace(['.', '_'], "-")
}

/// Formats `key` in `lang`, falling back to English. None when neither
/// catalog has it; callers then show the key.
fn format(lang: usize, key: &str, args: Option<&FluentArgs>) -> Option<Cow<'static, str>> {
    let id = id(key);
    let b = bundles();
    [lang, 0].into_iter().find_map(|l| {
        let bundle = b.get(l)?;
        let pattern = bundle.get_message(&id)?.value()?;
        let mut errors = Vec::new();
        Some(bundle.format_pattern(pattern, args, &mut errors))
    })
}

/// Index into LANGS for a code like "ja", "ja_JP.UTF-8", "zh_TW" or "pt-BR".
fn from_code(v: &str) -> Option<usize> {
    let v = v.trim();
    if v.is_empty() || v == "C" || v == "POSIX" {
        return None;
    }
    let norm = v.split(['.', '@']).next().unwrap_or(v).replace('_', "-").to_ascii_lowercase();
    if let Some(i) = LANGS.iter().position(|(c, _, _)| c.to_ascii_lowercase() == norm) {
        return Some(i);
    }
    let base = norm.split('-').next().unwrap_or("");
    let code = match (base, norm.as_str()) {
        ("zh", "zh-tw" | "zh-hk" | "zh-mo" | "zh-hant") => "zh-TW",
        ("zh", _) => "zh-CN",
        ("pt", _) => "pt-BR",
        (b, _) => b,
    };
    Some(LANGS.iter().position(|(c, _, _)| *c == code).unwrap_or(0))
}

static CURRENT: AtomicUsize = AtomicUsize::new(0);

/// Picks the starting language: the choice saved from the sidebar, then the
/// system's: LANGUAGE (a `:` list, as gettext reads it), LC_ALL,
/// LC_MESSAGES and LANG on Linux and BSD; the user's language setting on
/// Windows and macOS. English otherwise.
pub fn init(saved: Option<&str>) {
    set(saved.and_then(from_code).or_else(system).unwrap_or(0));
}

fn system() -> Option<usize> {
    let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
    // gettext ignores LANGUAGE when the locale is plain C.
    let locale = ["LC_ALL", "LC_MESSAGES", "LANG"].iter().find_map(|k| var(k));
    let c_locale = locale.as_deref().is_some_and(|l| l == "C" || l == "POSIX");
    if !c_locale && let Some(list) = var("LANGUAGE") {
        // First entry we have a catalog for; English only when asked for.
        if let Some(i) = list
            .split(':')
            .filter_map(|v| from_code(v).map(|i| (i, v)))
            .find_map(|(i, v)| (i != 0 || v.to_ascii_lowercase().starts_with("en")).then_some(i))
        {
            return Some(i);
        }
    }
    if let Some(l) = locale {
        return from_code(&l);
    }
    // Windows and macOS keep the language in system settings, not variables.
    sys_locale::get_locales().find_map(|l| from_code(&l))
}

/// Index into LANGS of the language in use.
pub fn current() -> usize {
    CURRENT.load(Ordering::Relaxed)
}

pub fn set(lang: usize) {
    CURRENT.store(lang.min(LANGS.len() - 1), Ordering::Relaxed);
}

/// Looks up `key` in language `lang` (an index into LANGS), falling back
/// to English, then to the key.
pub fn t_in(lang: usize, key: &'static str) -> &'static str {
    match format(lang, key, None) {
        Some(Cow::Borrowed(s)) => s,
        Some(Cow::Owned(s)) => intern(s),
        None => key,
    }
}

/// Keeps a formatted string alive for the rest of the run. Only messages
/// that Fluent had to build (rare without arguments) end up here.
fn intern(s: String) -> &'static str {
    static SEEN: OnceLock<Mutex<HashMap<String, &'static str>>> = OnceLock::new();
    let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
    if let Some(v) = seen.get(&s) {
        return v;
    }
    let leaked: &'static str = Box::leak(s.clone().into_boxed_str());
    seen.insert(s, leaked);
    leaked
}

/// Looks up `key`.
pub fn t(key: &'static str) -> &'static str {
    t_in(current(), key)
}

/// Digit grouping and decimal mark for language `lang`.
fn number_seps(lang: usize) -> (char, char) {
    match LANGS[lang].0 {
        "de" | "es" | "it" | "pt-BR" => ('.', ','),
        // Narrow no-break space, as French and Russian typography use.
        "fr" | "ru" => ('\u{202f}', ','),
        _ => (',', '.'),
    }
}

/// `n` with the reader's digit grouping: 1,234 / 1.234 / 1 234.
pub fn thousands(n: usize) -> String {
    thousands_in(current(), n)
}

fn thousands_in(lang: usize, n: usize) -> String {
    let sep = number_seps(lang).0;
    let s = n.to_string();
    let mut out = String::new();
    for (k, ch) in s.chars().enumerate() {
        if k > 0 && (s.len() - k).is_multiple_of(3) {
            out.push(sep);
        }
        out.push(ch);
    }
    out
}

/// File size with the reader's decimal mark: 1.5 MB / 1,5 MB.
pub fn human_size(bytes: u64) -> String {
    human_size_in(current(), bytes)
}

fn human_size_in(lang: usize, bytes: u64) -> String {
    let b = bytes as f64;
    let (v, unit) = if b >= 1e9 {
        (format!("{:.1}", b / 1e9), "GB")
    } else if b >= 1e6 {
        (format!("{:.1}", b / 1e6), "MB")
    } else {
        (format!("{:.0}", b / 1e3), "KB")
    };
    format!("{}\u{a0}{unit}", v.replace('.', &number_seps(lang).1.to_string()))
}

fn args_of<'a>(args: &'a [(&'a str, String)]) -> FluentArgs<'a> {
    let mut fa = FluentArgs::new();
    for (k, v) in args {
        fa.set(*k, FluentValue::from(v.as_str()));
    }
    fa
}

/// Looks up `key` and fills its `{ $name }` placeholders.
pub fn tf(key: &'static str, args: &[(&str, String)]) -> String {
    let fa = args_of(args);
    format(current(), key, Some(&fa)).map_or_else(|| key.to_string(), Cow::into_owned)
}

/// Like `tf` for a message about `count` things: the catalog picks the
/// plural form from `$count` (one, few, many, other, as the language has).
pub fn tn(key: &'static str, count: usize, args: &[(&str, String)]) -> String {
    let mut fa = args_of(args);
    fa.set("count", FluentValue::from(count));
    format(current(), key, Some(&fa)).map_or_else(|| key.to_string(), Cow::into_owned)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Message ids and the variables each one uses, read from the source.
    fn messages(src: &str) -> HashMap<String, Vec<String>> {
        let res = FluentResource::try_new(src.to_string()).expect("catalog parses");
        let mut out = HashMap::new();
        let mut current = None;
        for line in src.lines() {
            if let Some((name, _)) = line.split_once(" = ").filter(|_| !line.starts_with([' ', '#'])) {
                current = Some(name.trim().to_string());
                out.insert(name.trim().to_string(), Vec::new());
            }
            if let Some(name) = &current {
                let vars = out.get_mut(name).unwrap();
                for part in line.split('$').skip(1) {
                    let v: String = part.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
                    if v != "count" && !vars.contains(&v) {
                        vars.push(v);
                    }
                }
                vars.sort();
            }
        }
        assert_eq!(res.entries().count(), out.len(), "every message is one `id = ...` line");
        out
    }

    #[test]
    fn every_catalog_has_the_english_messages_and_variables() {
        let en = messages(LANGS[0].2);
        for (code, _, src) in &LANGS[1..] {
            let other = messages(src);
            let mut missing: Vec<_> = en.keys().filter(|k| !other.contains_key(*k)).collect();
            missing.sort();
            assert!(missing.is_empty(), "missing in {code}.ftl: {missing:?}");
            let mut extra: Vec<_> = other.keys().filter(|k| !en.contains_key(*k)).collect();
            extra.sort();
            assert!(extra.is_empty(), "only in {code}.ftl: {extra:?}");
            for (k, vars) in &en {
                assert_eq!(vars, &other[k], "variables differ for {k} in {code}");
            }
        }
    }

    #[test]
    fn every_message_formats_without_errors() {
        for (i, (code, _, src)) in LANGS.iter().enumerate() {
            let b = &bundles()[i];
            for (id, vars) in messages(src) {
                let mut args = FluentArgs::new();
                for v in &vars {
                    args.set(v.as_str(), "x");
                }
                args.set("count", 2);
                let pattern = b.get_message(&id).and_then(|m| m.value()).expect("message has a value");
                let mut errors = Vec::new();
                let text = b.format_pattern(pattern, Some(&args), &mut errors);
                assert!(errors.is_empty(), "{code} {id}: {errors:?}");
                assert!(!text.contains('{'), "{code} {id}: unfilled placeholder in {text:?}");
            }
        }
    }

    #[test]
    fn russian_counts_take_three_forms() {
        let b = &bundles()[LANGS.iter().position(|l| l.0 == "ru").unwrap()];
        let say = |n: usize| {
            let mut args = FluentArgs::new();
            args.set("count", n);
            args.set("n", n.to_string());
            let p = b.get_message("grid-items").unwrap().value().unwrap();
            b.format_pattern(p, Some(&args), &mut Vec::new()).into_owned()
        };
        assert_eq!(say(1), "1 файл");
        assert_eq!(say(3), "3 файла");
        assert_eq!(say(5), "5 файлов");
        assert_eq!(say(21), "21 файл");
    }

    #[test]
    fn locale_codes_map_to_languages() {
        let code = |v: &str| from_code(v).map(|i| LANGS[i].0);
        assert_eq!(code("ja_JP.UTF-8"), Some("ja"));
        assert_eq!(code("zh_TW.UTF-8"), Some("zh-TW"));
        assert_eq!(code("zh_HK"), Some("zh-TW"));
        assert_eq!(code("zh_CN.UTF-8"), Some("zh-CN"));
        assert_eq!(code("pt_PT"), Some("pt-BR"));
        assert_eq!(code("de_AT.UTF-8"), Some("de"));
        assert_eq!(code("sv_SE.UTF-8"), Some("en"));
        assert_eq!(code("C"), None);
        assert_eq!(code(""), None);
    }

    #[test]
    fn numbers_use_the_languages_separators() {
        let lang = |code: &str| LANGS.iter().position(|l| l.0 == code).unwrap();
        assert_eq!(thousands_in(lang("en"), 1234567), "1,234,567");
        assert_eq!(thousands_in(lang("de"), 1234), "1.234");
        assert_eq!(thousands_in(lang("fr"), 1234), "1\u{202f}234");
        assert_eq!(thousands_in(lang("en"), 999), "999");
        assert_eq!(human_size_in(lang("en"), 1_500_000), "1.5\u{a0}MB");
        assert_eq!(human_size_in(lang("de"), 2_260_000_000), "2,3\u{a0}GB");
        assert_eq!(human_size_in(lang("ja"), 2_400), "2\u{a0}KB");
    }
}