app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
[package]
name = "rune-i18n"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Message catalogs for Rune apps: keys checked at compile time, catalogs generated from JSON at build time, CLDR plurals, numbers and lists, and the system's preferred languages."
publish = false
autotests = false
[features]
default = []
# `rune_i18n::codegen`: turns a folder of JSON catalogs into Rust for an app's build script.
codegen = []
[dependencies]
fixed_decimal = { version = "0.7", features = ["ryu"] }
icu_decimal = "2"
icu_list = "2"
icu_locale = "2"
icu_plurals = "2"
# Thread-safe data payloads, so one translator serves every window.
icu_provider = { version = "2", features = ["sync"] }
writeable = "0.6"
# Catalogs read from JSON: at build time (`codegen`), and at run time on the web.
serde_json = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { workspace = true, features = ["Win32_Foundation", "Win32_Globalization"] }
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
objc2-foundation = { workspace = true, features = ["std", "NSArray", "NSEnumerator", "NSLocale", "NSString"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { workspace = true }
web-sys = { workspace = true, features = ["Navigator", "Window"] }
[[test]]
name = "locale"
[lints]
workspace = true
+246
View File
@@ -0,0 +1,246 @@
//! The generated catalog: sorted key names, plural bases with their per-category keys, the
//! locales, and one text blob plus span table per locale.
use core::cmp::Ordering;
use std::sync::OnceLock;
/// One supported locale: the app's id for it (`zht`), its BCP 47 tag (`zh-Hant`), the name it
/// shows in a language picker, in its own language (`繁體中文`), and whether it reads right to left.
#[derive(Clone, Copy, Debug)]
pub struct LocaleInfo {
id: &'static str,
tag: &'static str,
label: &'static str,
rtl: bool,
}
impl LocaleInfo {
pub const fn new(id: &'static str, tag: &'static str, label: &'static str, rtl: bool) -> Self {
Self { id, tag, label, rtl }
}
pub const fn id(&self) -> &'static str {
self.id
}
pub const fn tag(&self) -> &'static str {
self.tag
}
pub const fn label(&self) -> &'static str {
self.label
}
pub const fn rtl(&self) -> bool {
self.rtl
}
}
/// One locale's messages: every present message concatenated into `text`, and `spans` holding
/// a little-endian `(start, len)` pair of `u32`s per key, `start = u32::MAX` where the locale has
/// no message for the key.
///
/// A locale's messages are in the program ([`Messages::new`]) or come at run time
/// ([`Messages::later`], [`Catalog::load_json`]): a web build keeps only the source locale's in
/// its module and fetches the one a page shows.
#[derive(Debug)]
pub struct Messages {
embedded: Option<(&'static str, &'static [u8])>,
loaded: OnceLock<(&'static str, &'static [u8])>,
}
impl Messages {
pub const fn new(text: &'static str, spans: &'static [u8]) -> Self {
Self { embedded: Some((text, spans)), loaded: OnceLock::new() }
}
/// A locale whose messages come at run time: until then it has none, so every lookup falls
/// back to the source locale.
pub const fn later() -> Self {
Self { embedded: None, loaded: OnceLock::new() }
}
/// Whether the messages are here: in the program, or loaded.
pub fn present(&self) -> bool {
self.embedded.is_some() || self.loaded.get().is_some()
}
/// The message for key index `key`, or `None` when this locale lacks it.
pub fn get(&self, key: usize) -> Option<&'static str> {
let (text, spans) = self.embedded.or_else(|| self.loaded.get().copied())?;
let at = key * 8;
let span = spans.get(at..at + 8)?;
let start = u32::from_le_bytes([span[0], span[1], span[2], span[3]]);
if start == u32::MAX {
return None;
}
let len = u32::from_le_bytes([span[4], span[5], span[6], span[7]]);
text.get(start as usize..(start + len) as usize)
}
}
/// The messages for `keys` concatenated, and a `(start, len)` little-endian `u32` pair per key,
/// `start = u32::MAX` for a key `message` has none for: a locale's blob, made the same way at
/// build time (`codegen`) and at run time (`Catalog::load_json`). With `isolate`, a key the
/// locale lacks takes that locale's message between LRI and PDI instead: the message the lookup
/// falls back to (a missing plural category included, which `I18n::plural_form` takes from the
/// source before the locale's `other`).
pub(crate) fn blob<'m, 's>(keys: &[&str], message: impl Fn(&str) -> Option<&'m str>,
isolate: Option<&dyn Fn(&str) -> Option<&'s str>>) -> (String, Vec<u8>) {
let mut text = String::new();
let mut spans = Vec::with_capacity(keys.len() * 8);
for key in keys {
let own = message(key);
let isolated = isolate.filter(|_| own.is_none()).and_then(|source| source(key)).map(|m| format!("\u{2066}{m}\u{2069}"));
let (start, len) = match own.or(isolated.as_deref()) {
Some(message) => {
let start = text.len() as u32;
text.push_str(message);
(start, message.len() as u32)
}
None => (u32::MAX, 0),
};
spans.extend_from_slice(&start.to_le_bytes());
spans.extend_from_slice(&len.to_le_bytes());
}
(text, spans)
}
/// Everything [`crate::codegen::generate`] emits, in one static.
#[derive(Debug)]
pub struct Catalog {
keys: &'static [&'static str],
plurals: &'static [&'static str],
plural_forms: &'static [[u32; 6]],
locales: &'static [LocaleInfo],
messages: &'static [Messages],
}
impl Catalog {
pub const fn new(
keys: &'static [&'static str],
plurals: &'static [&'static str],
plural_forms: &'static [[u32; 6]],
locales: &'static [LocaleInfo],
messages: &'static [Messages],
) -> Self {
Self { keys, plurals, plural_forms, locales, messages }
}
pub const fn keys(&self) -> &'static [&'static str] {
self.keys
}
pub const fn locales(&self) -> &'static [LocaleInfo] {
self.locales
}
pub(crate) fn messages(&self, locale: usize) -> Option<&'static Messages> {
self.messages.get(locale)
}
/// Whether `locale`'s messages are here (in the program, or loaded).
pub fn present(&self, locale: usize) -> bool {
self.messages.get(locale).is_some_and(Messages::present)
}
/// Fills a locale the build left for run time (`Messages::later`) from its messages as one
/// JSON object of key to message (the locale's layers merged, a later layer winning). Keys
/// the program doesn't have are skipped, and a key the object lacks falls back to the source
/// locale as ever. A locale that's here already is left as it is.
pub fn load_json(&self, locale: usize, json: &str) -> Result<(), String> {
let Some(messages) = self.messages.get(locale) else { return Err(format!("no locale {locale}")) };
if messages.present() { return Ok(()); }
let serde_json::Value::Object(map) = serde_json::from_str(json).map_err(|e| e.to_string())? else {
return Err("not a JSON object".into());
};
// As the build makes a right-to-left locale's blob: its missing messages are the
// source's, isolated.
let source = |key: &str| find(self.keys, key).and_then(|k| self.messages.first()?.get(k));
let rtl = self.locales.get(locale).is_some_and(LocaleInfo::rtl) && !self.locales.first().is_some_and(LocaleInfo::rtl);
let isolate: Option<&dyn Fn(&str) -> Option<&'static str>> = if rtl { Some(&source) } else { None };
let (text, spans) = blob(self.keys, |key| map.get(key).and_then(serde_json::Value::as_str), isolate);
messages.loaded.set((Box::leak(text.into_boxed_str()), Box::leak(spans.into_boxed_slice()))).ok();
Ok(())
}
/// The key index for each CLDR category of a plural base, in [`crate::PluralCategory`] order.
pub(crate) fn plural_forms(&self, key: PluralKey) -> [Option<usize>; 6] {
let forms = self.plural_forms.get(key.0 as usize).copied().unwrap_or([u32::MAX; 6]);
forms.map(|k| (k != u32::MAX).then_some(k as usize))
}
pub(crate) fn plural_name(&self, key: PluralKey) -> &'static str {
self.plurals.get(key.0 as usize).copied().unwrap_or("")
}
}
/// A message key: an index into the catalog's sorted key list.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Key(pub(crate) u32);
impl Key {
/// The key called `name` in `keys`, the generated sorted key list. Called in a `const`, a name
/// missing from the catalog fails the build.
pub const fn named(keys: &[&str], name: &str) -> Key {
match find(keys, name) {
Some(index) => Key(index as u32),
None => panic!("unknown i18n key"),
}
}
pub const fn index(self) -> usize {
self.0 as usize
}
}
/// A plural base: `base` names the messages `base.one`, `base.other` and the locale's other
/// CLDR categories.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PluralKey(pub(crate) u32);
impl PluralKey {
/// The plural base `name` in `plurals`, the generated sorted base list. Called in a `const`,
/// a base without `.one` and `.other` messages fails the build.
pub const fn named(plurals: &[&str], name: &str) -> PluralKey {
match find(plurals, name) {
Some(index) => PluralKey(index as u32),
None => panic!("unknown i18n plural key"),
}
}
}
/// Binary search for `name` in byte-sorted `keys`, usable in `const`.
pub const fn find(keys: &[&str], name: &str) -> Option<usize> {
let (mut lo, mut hi) = (0, keys.len());
while lo < hi {
let mid = (lo + hi) / 2;
match compare(keys[mid].as_bytes(), name.as_bytes()) {
Ordering::Less => lo = mid + 1,
Ordering::Greater => hi = mid,
Ordering::Equal => return Some(mid),
}
}
None
}
const fn compare(a: &[u8], b: &[u8]) -> Ordering {
let mut i = 0;
while i < a.len() && i < b.len() {
if a[i] < b[i] {
return Ordering::Less;
}
if a[i] > b[i] {
return Ordering::Greater;
}
i += 1;
}
if a.len() < b.len() {
return Ordering::Less;
}
if a.len() > b.len() {
return Ordering::Greater;
}
Ordering::Equal
}
+169
View File
@@ -0,0 +1,169 @@
//! Build-time generation of a [`crate::Catalog`] from JSON (feature `codegen`).
//!
//! The folder holds `locales.json` and one subfolder per layer:
//!
//! ```json
//! { "layers": ["upstream", "app"],
//! "locales": [{ "id": "en", "tag": "en", "label": "English" },
//! { "id": "ar", "tag": "ar", "label": "العربية", "rtl": true }] }
//! ```
//!
//! `<layer>/<id>.json` is a flat object of key to message; a later layer's message replaces an
//! earlier one's, and a missing file is a locale with no messages in that layer. The first locale
//! is the source: its keys are the catalog's keys. A base whose source has `base.one` and
//! `base.other` is a plural, and every locale's `base.<category>` messages join the catalog.
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::{fs, io};
use serde_json::Value;
use crate::PluralCategory;
/// Reads the catalogs in `dir` and writes `i18n.rs` to `out_dir`, with each locale's text blob
/// and span table beside it in `out_dir/i18n/`. Include the result with
/// `include!(concat!(env!("OUT_DIR"), "/i18n.rs"))`; it defines `KEYS`, `PLURALS` and `CATALOG`.
/// Prints `cargo:rerun-if-changed` for `dir`, so a new or edited catalog rebuilds.
pub fn generate(dir: &Path, out_dir: &Path) -> io::Result<()> {
println!("cargo:rerun-if-changed={}", dir.display());
let manifest = read_json(&dir.join("locales.json"))?;
let layers: Vec<&str> = manifest["layers"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let locales = locales(&manifest)?;
let messages: Vec<BTreeMap<String, String>> = locales
.iter()
.map(|locale| {
let mut merged = BTreeMap::new();
for layer in &layers {
let path = dir.join(layer).join(format!("{}.json", locale.id));
if !path.exists() {
continue;
}
let Value::Object(map) = read_json(&path)? else {
return Err(invalid(format!("{} is not a JSON object", path.display())));
};
merged.extend(map.into_iter().filter_map(|(key, value)| Some((key, value.as_str()?.to_owned()))));
}
Ok(merged)
})
.collect::<io::Result<_>>()?;
let source = &messages[0];
let mut plurals: Vec<&str> = source
.keys()
.filter_map(|key| key.strip_suffix(".other"))
.filter(|base| source.contains_key(&format!("{base}.one")))
.collect();
plurals.sort_unstable();
let mut keys: BTreeSet<&str> = source.keys().map(String::as_str).collect();
for locale in &messages {
keys.extend(locale.keys().map(String::as_str).filter(|key| {
key.rsplit_once('.').is_some_and(|(base, category)| {
plurals.binary_search(&base).is_ok() && PluralCategory::ALL.iter().any(|c| c.suffix() == category)
})
}));
}
let keys: Vec<&str> = keys.into_iter().collect();
let blobs = out_dir.join("i18n");
fs::create_dir_all(&blobs)?;
for (locale, map) in locales.iter().zip(&messages) {
// A right-to-left locale's missing message is the source's left-to-right one, isolated, so an
// untranslated English sentence keeps its words and its full stop in order in an Arabic row.
let isolate = (locale.rtl && !locales[0].rtl).then_some(source);
let (text, spans) = blob(&keys, map, isolate);
fs::write(blobs.join(format!("{}.txt", locale.id)), text)?;
fs::write(blobs.join(format!("{}.spans", locale.id)), spans)?;
}
fs::write(out_dir.join("i18n.rs"), source_file(&keys, &plurals, &locales))
}
struct Locale {
id: String,
tag: String,
label: String,
rtl: bool,
}
fn locales(manifest: &Value) -> io::Result<Vec<Locale>> {
let list = manifest["locales"].as_array().filter(|list| !list.is_empty());
let list = list.ok_or_else(|| invalid("locales.json lists no locales".into()))?;
list.iter()
.map(|entry| {
let field = |name: &str| entry[name].as_str().map(str::to_owned);
let id = field("id").filter(|id| id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
let id = id.ok_or_else(|| invalid(format!("locale entry {entry} needs an id of letters, digits, - or _")))?;
Ok(Locale {
tag: field("tag").unwrap_or_else(|| id.clone()),
label: field("label").unwrap_or_else(|| id.clone()),
rtl: entry["rtl"].as_bool().unwrap_or(false),
id,
})
})
.collect()
}
fn blob<'a>(keys: &[&str], map: &BTreeMap<String, String>, isolate: Option<&'a BTreeMap<String, String>>) -> (String, Vec<u8>) {
let source = |key: &str| isolate.and_then(|source| source.get(key)).map(String::as_str);
crate::catalog::blob(keys, |key| map.get(key).map(String::as_str), isolate.map(|_| &source as &dyn Fn(&str) -> Option<&'a str>))
}
macro_rules! ln {
($($arg:tt)*) => {
format!("{}\n", format_args!($($arg)*))
};
}
fn source_file(keys: &[&str], plurals: &[&str], locales: &[Locale]) -> String {
let mut out = String::from("// Generated by rune_i18n::codegen. Do not edit.\n\n");
out += &ln!("pub const KEYS: &[&str] = &[");
for key in keys {
out += &ln!(" {key:?},");
}
out += &ln!("];\n\npub const PLURALS: &[&str] = &[");
for base in plurals {
out += &ln!(" {base:?},");
}
out += &ln!("];\n\nstatic PLURAL_FORMS: [[u32; 6]; {}] = [", plurals.len());
for base in plurals {
let forms = PluralCategory::ALL.map(|category| {
let key = format!("{base}.{}", category.suffix());
keys.binary_search(&key.as_str()).map_or(u32::MAX, |index| index as u32)
});
out += &ln!(" {forms:?},");
}
out += &ln!("];\n\nstatic LOCALES: [::rune_i18n::LocaleInfo; {}] = [", locales.len());
for locale in locales {
out += &ln!(" ::rune_i18n::LocaleInfo::new({:?}, {:?}, {:?}, {}),",
locale.id, locale.tag, locale.label, locale.rtl
);
}
out += &ln!("];\n\nstatic MESSAGES: [::rune_i18n::Messages; {}] = [", locales.len());
// A web build keeps the source locale's messages in its module and loads the one a page shows
// at run time (`Catalog::load_json`).
let web = std::env::var_os("CARGO_CFG_TARGET_ARCH").is_some_and(|arch| arch == "wasm32");
for (i, locale) in locales.iter().enumerate() {
if web && i > 0 {
out += &ln!(" ::rune_i18n::Messages::later(),");
continue;
}
out += &ln!(" ::rune_i18n::Messages::new(include_str!(concat!(env!(\"OUT_DIR\"), \"/i18n/{0}.txt\")), \
include_bytes!(concat!(env!(\"OUT_DIR\"), \"/i18n/{0}.spans\"))),",
locale.id
);
}
out += &ln!("];\n\npub static CATALOG: ::rune_i18n::Catalog = \
::rune_i18n::Catalog::new(KEYS, PLURALS, &PLURAL_FORMS, &LOCALES, &MESSAGES);"
);
out
}
fn read_json(path: &Path) -> io::Result<Value> {
let text = fs::read_to_string(path).map_err(|e| io::Error::new(e.kind(), format!("{}: {e}", path.display())))?;
serde_json::from_str(&text).map_err(|e| invalid(format!("{}: {e}", path.display())))
}
fn invalid(message: String) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
+126
View File
@@ -0,0 +1,126 @@
//! CLDR formatting for one locale from ICU4X's compiled data, each formatter built on first use.
use std::sync::OnceLock;
use fixed_decimal::{Decimal, FloatPrecision, SignedRoundingMode, UnsignedRoundingMode};
use icu_decimal::options::DecimalFormatterOptions;
use icu_decimal::DecimalFormatter;
use icu_list::ListFormatter;
use icu_list::options::{ListFormatterOptions, ListLength};
use icu_locale::Locale;
use icu_plurals::PluralRules;
use writeable::Writeable;
/// A CLDR plural category, in the order the generated plural tables use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PluralCategory {
Zero,
One,
Two,
Few,
Many,
Other,
}
impl PluralCategory {
pub const ALL: [PluralCategory; 6] = [Self::Zero, Self::One, Self::Two, Self::Few, Self::Many, Self::Other];
/// The suffix a catalog key carries for this category (`one` in `files.one`).
pub const fn suffix(self) -> &'static str {
match self {
Self::Zero => "zero",
Self::One => "one",
Self::Two => "two",
Self::Few => "few",
Self::Many => "many",
Self::Other => "other",
}
}
pub(crate) const fn index(self) -> usize {
self as usize
}
fn from_icu(category: icu_plurals::PluralCategory) -> Self {
match category {
icu_plurals::PluralCategory::Zero => Self::Zero,
icu_plurals::PluralCategory::One => Self::One,
icu_plurals::PluralCategory::Two => Self::Two,
icu_plurals::PluralCategory::Few => Self::Few,
icu_plurals::PluralCategory::Many => Self::Many,
icu_plurals::PluralCategory::Other => Self::Other,
}
}
}
/// One locale's formatters. A formatter whose data is missing for the locale falls back to the
/// root locale's; without either, plurals read `other`, numbers show ASCII digits and lists join
/// with commas.
pub(crate) struct Formats {
locale: Locale,
plurals: OnceLock<Option<PluralRules>>,
decimal: OnceLock<Option<DecimalFormatter>>,
list: OnceLock<Option<ListFormatter>>,
}
impl Formats {
pub(crate) fn new(tag: &str) -> Self {
Self {
locale: Locale::try_from_str(tag).unwrap_or(Locale::UNKNOWN),
plurals: OnceLock::new(),
decimal: OnceLock::new(),
list: OnceLock::new(),
}
}
pub(crate) fn plural(&self, count: u64) -> PluralCategory {
let rules = self.plurals.get_or_init(|| {
PluralRules::try_new_cardinal((&self.locale).into())
.or_else(|_| PluralRules::try_new_cardinal(Locale::UNKNOWN.into()))
.ok()
});
rules.as_ref().map_or(PluralCategory::Other, |rules| PluralCategory::from_icu(rules.category_for(count)))
}
/// `n` with the locale's digits and grouping, as `Intl.NumberFormat(locale)` shows an integer.
pub(crate) fn integer(&self, n: i64) -> String {
self.format(&Decimal::from(n))
}
/// `n` rounded half away from zero to at most `max_fraction` digits, trailing zeros dropped,
/// as `Intl.NumberFormat(locale, { maximumFractionDigits })` shows it.
pub(crate) fn decimal_to(&self, n: f64, max_fraction: u8) -> String {
let Ok(mut value) = Decimal::try_from_f64(n, FloatPrecision::RoundTrip) else {
return format!("{n}");
};
value.round_with_mode(-i16::from(max_fraction), SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfExpand));
value.absolute.trim_end();
self.format(&value)
}
/// The items joined as the locale's long conjunction (`a, b and c`, `a, b und c`).
pub(crate) fn list<'a>(&self, items: impl Iterator<Item = &'a str> + Clone) -> String {
let formatter = self.list.get_or_init(|| {
let options = ListFormatterOptions::default().with_length(ListLength::Wide);
ListFormatter::try_new_and((&self.locale).into(), options)
.or_else(|_| ListFormatter::try_new_and(Locale::UNKNOWN.into(), options))
.ok()
});
match formatter {
Some(formatter) => formatter.format(items).write_to_string().into_owned(),
None => items.collect::<Vec<_>>().join(", "),
}
}
fn format(&self, value: &Decimal) -> String {
let formatter = self.decimal.get_or_init(|| {
DecimalFormatter::try_new((&self.locale).into(), DecimalFormatterOptions::default())
.or_else(|_| DecimalFormatter::try_new(Locale::UNKNOWN.into(), DecimalFormatterOptions::default()))
.ok()
});
match formatter {
Some(formatter) => formatter.format(value).write_to_string().into_owned(),
None => value.to_string(),
}
}
}
+132
View File
@@ -0,0 +1,132 @@
//! The app-wide translator over a generated [`Catalog`].
use core::fmt::Display;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::catalog::{Catalog, Key, LocaleInfo, PluralKey};
use crate::format::{Formats, PluralCategory};
/// A translator: the catalog, the current locale, and each locale's formatters once used. Apps
/// keep one in a `static` and wrap it in macros that resolve keys at compile time.
///
/// Locale 0 is the source locale: every key has a message there, and a lookup the current locale
/// lacks falls back to it.
pub struct I18n {
catalog: &'static Catalog,
current: AtomicUsize,
formats: OnceLock<Box<[Formats]>>,
}
impl I18n {
pub const fn new(catalog: &'static Catalog) -> Self {
Self { catalog, current: AtomicUsize::new(0), formats: OnceLock::new() }
}
pub fn catalog(&self) -> &'static Catalog {
self.catalog
}
pub fn locales(&self) -> &'static [LocaleInfo] {
self.catalog.locales()
}
/// The current locale's index into [`I18n::locales`].
pub fn locale(&self) -> usize {
self.current.load(Ordering::Relaxed)
}
pub fn info(&self) -> LocaleInfo {
self.locales()[self.locale()]
}
/// The index of the locale whose id is `id`.
pub fn find_locale(&self, id: &str) -> Option<usize> {
self.locales().iter().position(|locale| locale.id() == id)
}
/// Makes `locale` current for every later lookup. Returns whether it changed; an index past the
/// locales is ignored.
pub fn set_locale(&self, locale: usize) -> bool {
if locale >= self.locales().len() {
return false;
}
self.current.swap(locale, Ordering::Relaxed) != locale
}
/// The supported locale that best matches `preferred` (see [`crate::negotiate`]), or the source
/// locale.
pub fn negotiate<'a>(&self, preferred: impl IntoIterator<Item = &'a str>) -> usize {
let tags: Vec<&str> = self.locales().iter().map(LocaleInfo::tag).collect();
crate::negotiate(preferred, &tags).unwrap_or(0)
}
/// The current locale's message for `key`, else the source locale's.
pub fn text(&self, key: Key) -> &'static str {
self.text_in(self.locale(), key)
}
pub fn text_in(&self, locale: usize, key: Key) -> &'static str {
self.get(locale, key.index()).unwrap_or_else(|| self.catalog.keys().get(key.index()).copied().unwrap_or(""))
}
/// The message for `key` with its `{{name}}` placeholders filled from `args`.
pub fn format(&self, key: Key, args: &[(&str, &dyn Display)]) -> String {
crate::render(self.text(key), args)
}
/// The message of plural base `key` for `count`'s CLDR category in the current locale: the
/// category's message, else `other`'s (each from the current locale, else the source locale).
/// Its placeholders are left for the caller, which usually passes `count` too.
pub fn plural(&self, key: PluralKey, count: u64) -> &'static str {
self.plural_form(key, self.plural_category(count))
}
pub fn plural_form(&self, key: PluralKey, category: PluralCategory) -> &'static str {
let forms = self.catalog.plural_forms(key);
let locale = self.locale();
let pick = |category: PluralCategory| forms[category.index()].and_then(|k| self.get(locale, k));
pick(category).or_else(|| pick(PluralCategory::Other)).unwrap_or_else(|| self.catalog.plural_name(key))
}
/// The plural message for `count` with `{{count}}` and `args` filled in.
pub fn plural_format(&self, key: PluralKey, count: u64, args: &[(&str, &dyn Display)]) -> String {
let template = self.plural(key, count);
if args.is_empty() {
return crate::render(template, &[("count", &count)]);
}
let mut all: Vec<(&str, &dyn Display)> = Vec::with_capacity(args.len() + 1);
all.extend_from_slice(args);
all.push(("count", &count));
crate::render(template, &all)
}
pub fn plural_category(&self, count: u64) -> PluralCategory {
self.formats().plural(count)
}
/// `n` with the current locale's digits and grouping (`1,234`, `1.234`, `१,२३४`).
pub fn integer(&self, n: i64) -> String {
self.formats().integer(n)
}
/// `n` with at most `max_fraction` fraction digits in the current locale (`1.5`, `1,5`).
pub fn decimal(&self, n: f64, max_fraction: u8) -> String {
self.formats().decimal_to(n, max_fraction)
}
/// `items` as the current locale's long conjunction list (`a, b, and c`, `a, b und c`).
pub fn list<S: AsRef<str>>(&self, items: &[S]) -> String {
self.formats().list(items.iter().map(AsRef::as_ref))
}
fn get(&self, locale: usize, key: usize) -> Option<&'static str> {
let local = self.catalog.messages(locale).and_then(|messages| messages.get(key));
local.or_else(|| self.catalog.messages(0).and_then(|messages| messages.get(key)))
}
fn formats(&self) -> &Formats {
let all = self.formats.get_or_init(|| self.locales().iter().map(|locale| Formats::new(locale.tag())).collect());
&all[self.locale().min(all.len().saturating_sub(1))]
}
}
+45
View File
@@ -0,0 +1,45 @@
//! # rune-i18n
//!
//! Message catalogs for Rune apps, laid out for lookups that cost an index:
//!
//! - **Catalogs are data generated at build time.** An app keeps its catalogs as flat JSON files,
//! one per locale and layer, and its build script runs [`codegen::generate`] (feature
//! `codegen`). Each locale becomes one text blob plus a span table that `include_str!` and
//! `include_bytes!` embed, so nothing parses, allocates or relocates at launch, and a locale
//! added to the folder is in the next build.
//! - **Keys are checked at compile time.** [`Key::named`] and [`PluralKey::named`] are `const fn`s
//! that binary-search the generated key list, so an app macro turns a key name into an index in a
//! `const` and a typo fails the build.
//! - **[`I18n`]** holds the current locale in an atomic: [`I18n::text`] reads a slice of the
//! locale's blob and falls back to the first (source) locale, [`I18n::set_locale`] switches every
//! later lookup at once.
//! - **Templates** use `{{name}}` placeholders ([`render`], [`parts`]); plurals pick the key for the
//! CLDR category of a count (`base.one`, `base.few`, `base.other`, ...).
//! - **Formatting** comes from ICU4X's CLDR data, built per locale on first use: plural rules,
//! grouped and compact numbers, and conjunction lists.
//! - **Locale detection**: [`system_languages`] reads the OS's preferred languages and
//! [`negotiate`] matches them to the supported locales by language and likely script.
mod catalog;
#[cfg(feature = "codegen")]
pub mod codegen;
mod format;
mod i18n;
mod locale;
mod system;
mod template;
pub use catalog::Catalog;
pub use catalog::Key;
pub use catalog::LocaleInfo;
pub use catalog::Messages;
pub use catalog::PluralKey;
pub use catalog::find;
pub use format::PluralCategory;
pub use i18n::I18n;
pub use locale::negotiate;
pub use system::posix_languages;
pub use system::system_languages;
pub use template::Part;
pub use template::parts;
pub use template::render;
+32
View File
@@ -0,0 +1,32 @@
//! Matching preferred languages to supported locales.
use icu_locale::{LanguageIdentifier, Locale, LocaleExpander, subtags::Language};
/// The first supported locale that one of `preferred` (BCP 47 tags, most wanted first) names, by
/// language and likely script: `de-AT` picks `de`, `zh-TW` picks `zh-Hant` over `zh-Hans`, `pa-PK`
/// picks `pa-Arab-PK` and `pa-IN` does not. Norwegian `no`, `nb` and `nn` match one another.
/// Returns the index into `supported`, or `None` when nothing matches.
pub fn negotiate<'a>(preferred: impl IntoIterator<Item = &'a str>, supported: &[&str]) -> Option<usize> {
let expander = LocaleExpander::new_extended();
let maximize = |tag: &str| {
let mut id = Locale::try_from_str(&tag.replace('_', "-")).ok()?.id;
expander.maximize(&mut id);
Some(id)
};
let targets: Vec<Option<LanguageIdentifier>> = supported.iter().map(|tag| maximize(tag)).collect();
preferred.into_iter().filter_map(maximize).find_map(|source| {
let norwegian = is_norwegian(source.language);
targets.iter().position(|target| {
target.as_ref().is_some_and(|target| {
if norwegian {
return is_norwegian(target.language);
}
target.language == source.language && target.script == source.script
})
})
})
}
fn is_norwegian(language: Language) -> bool {
matches!(language.as_str(), "no" | "nb" | "nn")
}
+62
View File
@@ -0,0 +1,62 @@
//! The languages the user prefers, most wanted first, as BCP 47 tags.
/// The OS's preferred languages: Windows' user UI languages (`GetUserPreferredUILanguages`),
/// macOS' and iOS' `NSLocale.preferredLanguages`, the browser's `navigator.languages`, and the
/// POSIX locale variables elsewhere ([`posix_languages`]).
pub fn system_languages() -> Vec<String> {
platform()
}
/// The languages POSIX locale variables name, read through `var`: `LANGUAGE`'s colon list, then
/// `LC_ALL`, `LC_MESSAGES` and `LANG`, each turned from `de_AT.UTF-8@euro` into `de-AT`, without
/// `C`, `POSIX` and repeats.
pub fn posix_languages(var: impl Fn(&str) -> Option<String>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let names = var("LANGUAGE").unwrap_or_default();
let singles = ["LC_ALL", "LC_MESSAGES", "LANG"].map(|name| var(name).unwrap_or_default());
for value in names.split(':').chain(singles.iter().map(String::as_str)) {
let tag = value.split(['.', '@']).next().unwrap_or("").replace('_', "-");
if tag.is_empty() || tag == "C" || tag == "POSIX" || out.contains(&tag) {
continue;
}
out.push(tag);
}
out
}
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
fn platform() -> Vec<String> {
use windows::Win32::Globalization::{GetUserPreferredUILanguages, MUI_LANGUAGE_NAME};
use windows::core::PWSTR;
let (mut count, mut len) = (0u32, 0u32);
// SAFETY: the first call only writes the count and the buffer length it needs.
if unsafe { GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, None, &mut len) }.is_err() || len == 0 {
return Vec::new();
}
let mut buffer = vec![0u16; len as usize];
// SAFETY: `buffer` holds the `len` UTF-16 units the first call asked for.
if unsafe { GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, Some(PWSTR(buffer.as_mut_ptr())), &mut len) }
.is_err()
{
return Vec::new();
}
buffer.split(|&unit| unit == 0).filter(|name| !name.is_empty()).map(String::from_utf16_lossy).collect()
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn platform() -> Vec<String> {
objc2_foundation::NSLocale::preferredLanguages().iter().map(|tag| tag.to_string()).collect()
}
#[cfg(target_arch = "wasm32")]
fn platform() -> Vec<String> {
let Some(window) = web_sys::window() else { return Vec::new() };
window.navigator().languages().iter().filter_map(|tag| tag.as_string()).collect()
}
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios", target_arch = "wasm32")))]
fn platform() -> Vec<String> {
posix_languages(|name| std::env::var_os(name).and_then(|value| value.into_string().ok()))
}
+73
View File
@@ -0,0 +1,73 @@
//! `{{name}}` placeholders: whitespace inside the braces is ignored, and a name with no argument
//! renders as nothing.
use core::fmt::Display;
/// One piece of a template: literal text or a placeholder's name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part<'a> {
Text(&'a str),
Arg(&'a str),
}
/// The template's literal runs and placeholders in order, borrowed from it, for templates whose
/// arguments render as their own elements (a bold name, a key chip).
pub fn parts(template: &str) -> impl Iterator<Item = Part<'_>> {
let mut rest = template;
let mut pending: Option<&str> = None;
core::iter::from_fn(move || {
if let Some(arg) = pending.take() {
return Some(Part::Arg(arg));
}
if rest.is_empty() {
return None;
}
match placeholder(rest) {
Some((0, name, end)) => {
rest = &rest[end..];
Some(Part::Arg(name))
}
Some((start, name, end)) => {
let text = &rest[..start];
rest = &rest[end..];
pending = Some(name);
Some(Part::Text(text))
}
None => {
let text = rest;
rest = "";
Some(Part::Text(text))
}
}
})
}
/// The template with each `{{name}}` replaced by its argument's `Display`.
pub fn render(template: &str, args: &[(&str, &dyn Display)]) -> String {
let mut out = String::with_capacity(template.len() + 16);
for part in parts(template) {
match part {
Part::Text(text) => out.push_str(text),
Part::Arg(name) => {
if let Some((_, value)) = args.iter().find(|(n, _)| *n == name) {
out += &value.to_string();
}
}
}
}
out
}
/// The next `{{ name }}` in `text`: its start, its trimmed name and the end just past `}}`.
fn placeholder(text: &str) -> Option<(usize, &str, usize)> {
let mut from = 0;
loop {
let open = from + text[from..].find("{{")?;
let inner = open + 2;
let close = inner + text[inner..].find('}')?;
if close > inner && text[close..].starts_with("}}") {
return Some((open, text[inner..close].trim(), close + 2));
}
from = open + 1;
}
}
+12
View File
@@ -0,0 +1,12 @@
use rune_i18n::negotiate;
#[test]
fn preferred_tags_keep_their_language_and_script_with_extensions() {
let supported = ["en", "zh-Hans", "zh-Hant"];
assert_eq!(negotiate(["zh-TW-u-nu-hanidec", "en"], &supported), Some(2));
}
#[test]
fn supported_tags_can_specify_formatting_preferences() {
assert_eq!(negotiate(["de-AT"], &["en", "de-DE-u-co-phonebk"]), Some(1));
}