//! The person's language, and how dates and numbers are written in it. //! //! The system's texts are written in English in the programs, each passed //! through [`t`], which gives it in the language chosen in Settings: the //! English text is the key, so a program reads as it always did and a //! text with no translation yet shows in English. A text with blanks to //! fill (`"{} free of {}"`) is translated whole and then filled //! ([`fill`]), since the order of the parts differs between languages. //! //! The language is a file, `system:/locale/language` (`en` or `nl`), which //! Settings writes and every program may read; the display server tells //! the apps with a window when it changes, and they draw again. //! //! Dates are written as each language writes them (`zondag 29 november //! 2026`, `Sunday 29 November 2026`), times on the 24-hour clock in both, //! numbers with the language's separators (`1.234,5` and `1,234.5`). #![no_std] extern crate alloc; mod nl; use alloc::string::String; use core::sync::atomic::{AtomicU8, Ordering}; /// Where the language is kept. pub const LANGUAGE_PATH: &str = "system:/locale/language"; #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(u8)] pub enum Language { English, Dutch, } impl Language { pub const ALL: [Language; 2] = [Language::English, Language::Dutch]; /// Its code, as the file keeps it. pub fn code(self) -> &'static str { match self { Language::English => "en", Language::Dutch => "nl", } } pub fn from_code(code: &str) -> Option { match code.trim() { "en" => Some(Language::English), "nl" => Some(Language::Dutch), _ => None, } } /// Its name in itself, as a list of languages shows it. pub fn name(self) -> &'static str { match self { Language::English => "English", Language::Dutch => "Nederlands", } } } static CURRENT: AtomicU8 = AtomicU8::new(Language::English as u8); /// The language texts are given in. pub fn current() -> Language { match CURRENT.load(Ordering::Relaxed) { 1 => Language::Dutch, _ => Language::English, } } /// Sets the language for this program; returns whether it changed. pub fn set(language: Language) -> bool { CURRENT.swap(language as u8, Ordering::Relaxed) != language as u8 } /// `text` in the current language: its translation, or itself when there /// is none. pub fn t(text: &'static str) -> &'static str { in_language(current(), text) } /// A text that came at run time (an app's title from its manifest) in the /// current language, when it is one of the system's: itself otherwise. /// What only this finds is not checked by the tests: list such texts in /// [`RUN_TIME`] so that they are. pub fn tr(text: &str) -> &str { match current() { Language::English => text, Language::Dutch => lookup(&nl::TEXTS, text).unwrap_or(text), } } /// The texts programs translate at run time with [`tr`]: the titles of /// the apps the system comes with, as their manifests and windows say /// them, and what the Wi-Fi crate names its protections and failures. The /// tests check each has its Dutch. pub const RUN_TIME: &[&str] = &[ "About", "Bluetooth", "Calculator", "Calls", "Clock", "Contacts", "Could not join", "Files", "Messages", "Notes", "Open", "Paint", "Phone", "Settings", "Store", "Terminal", "The network did not answer", "The network is out of reach", ]; /// `text` in `language`. pub fn in_language(language: Language, text: &'static str) -> &'static str { match language { Language::English => text, Language::Dutch => lookup(&nl::TEXTS, text).unwrap_or(text), } } fn lookup(table: &'static [(&'static str, &'static str)], text: &str) -> Option<&'static str> { table .binary_search_by(|(en, _)| (*en).cmp(text)) .ok() .map(|i| table[i].1) } /// `template` with each `{}` replaced by the next of `parts`, in order. pub fn fill(template: &str, parts: &[&str]) -> String { let mut out = String::with_capacity(template.len() + parts.iter().map(|p| p.len()).sum::()); let mut parts = parts.iter(); let mut rest = template; while let Some(at) = rest.find("{}") { out.push_str(&rest[..at]); out.push_str(parts.next().copied().unwrap_or("")); rest = &rest[at + 2..]; } out.push_str(rest); out } /// [`t`] then [`fill`]. pub fn tf(template: &'static str, parts: &[&str]) -> String { fill(t(template), parts) } const MONTHS: [[&str; 12]; 2] = [ [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ], [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december", ], ]; const WEEKDAYS: [[&str; 7]; 2] = [ [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ], [ "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag", "zondag", ], ]; /// A day on the calendar. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Date { pub year: i64, /// 1–12. pub month: u32, /// 1–31. pub day: u32, } impl Date { /// The day `days` after 1 January 1970 (Howard Hinnant's /// civil-from-days). pub fn from_days(days: i64) -> Date { let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = (doy - (153 * mp + 2) / 5 + 1) as u32; let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; Date { year: yoe + era * 400 + i64::from(month <= 2), month, day, } } /// Days since 1 January 1970. pub fn days(self) -> i64 { let y = self.year - i64::from(self.month <= 2); let era = y.div_euclid(400); let yoe = y.rem_euclid(400); let m = i64::from(self.month); let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(self.day) - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe - 719_468 } /// 0 for Monday to 6 for Sunday. pub fn weekday(self) -> usize { // 1 January 1970 was a Thursday. (self.days() + 3).rem_euclid(7) as usize } } fn index(language: Language) -> usize { language as usize } pub fn month_name(month: u32) -> &'static str { MONTHS[index(current())][(month.clamp(1, 12) - 1) as usize] } pub fn weekday_name(weekday: usize) -> &'static str { WEEKDAYS[index(current())][weekday % 7] } /// "29 November 2026", "29 november 2026". pub fn date(d: Date) -> String { alloc::format!("{} {} {}", d.day, month_name(d.month), d.year) } /// "Sunday 29 November 2026", "zondag 29 november 2026". pub fn date_long(d: Date) -> String { alloc::format!("{} {}", weekday_name(d.weekday()), date(d)) } /// "29 Nov", "29 nov": the month's first three letters. pub fn date_short(d: Date) -> String { let month: String = month_name(d.month).chars().take(3).collect(); alloc::format!("{} {month}", d.day) } /// "07:05", on the 24-hour clock in both languages. pub fn time(hour: u32, minute: u32) -> String { alloc::format!("{hour:02}:{minute:02}") } /// What separates thousands, and what the decimals. fn separators() -> (char, char) { match current() { Language::English => (',', '.'), Language::Dutch => ('.', ','), } } /// An integer with its thousands separated: "1,234,567", "1.234.567". /// Four digits are not separated ("2026", "1234"), as both languages print /// them in running text. pub fn number(n: i64) -> String { let digits = alloc::format!("{}", n.unsigned_abs()); let mut out = String::new(); if n < 0 { out.push('-'); } if digits.len() <= 4 { out.push_str(&digits); return out; } let (thousands, _) = separators(); for (i, c) in digits.chars().enumerate() { if i > 0 && (digits.len() - i) % 3 == 0 { out.push(thousands); } out.push(c); } out } /// A number with `places` decimals: "3.14", "3,14". pub fn decimal(value: f64, places: usize) -> String { let scale = (0..places).fold(1i64, |s, _| s * 10); let negative = value < 0.0; let v = if negative { -value } else { value }; let fixed = (v * scale as f64 + 0.5) as i64; let whole = fixed / scale; let mut out = number(if negative { -whole } else { whole }); if negative && whole == 0 && fixed != 0 { out.insert(0, '-'); } if places > 0 { out.push(separators().1); out.push_str(&alloc::format!("{:0places$}", fixed % scale)); } out } /// Turns `.` decimal points in a number written by a program (`3.5`) /// into the language's, and `,` thousands likewise: for numbers that come /// already formatted, as a calculator's do. pub fn localise_number(text: &str) -> String { let (thousands, point) = separators(); text.chars() .map(|c| match c { '.' => point, ',' => thousands, c => c, }) .collect() } #[cfg(test)] mod tests { extern crate std; use super::*; use std::string::ToString; use std::vec::Vec; /// Only one test changes the language, as the language is the /// program's. #[test] fn texts_dates_and_numbers() { set(Language::English); assert_eq!(t("Settings"), "Settings"); assert_eq!(tf("{} free of {}", &["3 MiB", "8 MiB"]), "3 MiB free of 8 MiB"); let d = Date::from_days(20_786); assert_eq!( d, Date { year: 2026, month: 11, day: 29 } ); assert_eq!(d.days(), 20_786); assert_eq!(d.weekday(), 6); assert_eq!(date_long(d), "Sunday 29 November 2026"); assert_eq!(date_short(d), "29 Nov"); assert_eq!(number(1_234_567), "1,234,567"); assert_eq!(number(2026), "2026"); assert_eq!(decimal(3.14159, 2), "3.14"); assert_eq!(decimal(-0.5, 1), "-0.5"); assert!(set(Language::Dutch)); assert_eq!(t("Settings"), "Instellingen"); assert_eq!(t("A text nobody translated"), "A text nobody translated"); assert_eq!(tf("{} free of {}", &["3 MiB", "8 MiB"]), "3 MiB vrij van 8 MiB"); assert_eq!(date_long(d), "zondag 29 november 2026"); assert_eq!(date_short(d), "29 nov"); assert_eq!(number(1_234_567), "1.234.567"); assert_eq!(decimal(1234.5, 1), "1234,5"); assert_eq!(decimal(12_345.25, 2), "12.345,25"); assert_eq!(localise_number("3.5"), "3,5"); set(Language::English); } #[test] fn the_dutch_texts_are_sorted_and_whole() { for pair in nl::TEXTS.windows(2) { assert!( pair[0].0 < pair[1].0, "not sorted or twice: {:?} {:?}", pair[0].0, pair[1].0 ); } for (en, nl) in nl::TEXTS.iter() { assert_eq!( en.matches("{}").count(), nl.matches("{}").count(), "blanks differ: {en:?} → {nl:?}" ); assert!(!nl.is_empty(), "{en:?}"); } } #[test] fn the_run_time_texts_are_translated() { for text in RUN_TIME { assert!(lookup(&nl::TEXTS, text).is_some(), "no Dutch for {text:?}"); } } /// Every text a program passes to `t` or `tf` has its Dutch: a text /// added in English without one fails here, not in front of a Dutch /// reader. #[test] fn every_text_the_programs_ask_for_is_translated() { let root = concat!(env!("CARGO_MANIFEST_DIR"), "/.."); let mut missing = Vec::new(); for dir in ["programs/src/bin", "ui/src", "view/src"] { let Ok(entries) = std::fs::read_dir(std::format!("{root}/{dir}")) else { continue; }; for entry in entries.flatten() { let path = entry.path(); if path.extension().is_none_or(|e| e != "rs") { continue; } let source = std::fs::read_to_string(&path).unwrap(); for text in asked(&source) { if lookup(&nl::TEXTS, &text).is_none() { missing.push(std::format!( "{}: {text:?}", path.file_name().unwrap().to_string_lossy() )); } } } } missing.sort(); missing.dedup(); assert!(missing.is_empty(), "no Dutch for:\n{}", missing.join("\n")); } /// Counted texts whose count is never 1, so they need no singular. const NEVER_ONE: [&str; 1] = [ // Settings names one or two contacts, and counts from three. "{} contacts", ]; /// Counted texts that can still say "1 apps": each to be given its /// singular, then taken off this list. const NO_SINGULAR_YET: [&str; 2] = ["{} apps installed", "{} devices"]; /// A text that counts ("{} notes") has its singular beside it ("1 /// note", "One line", "the one thing"), which the program picks with a /// `match` on the count, so nobody reads "the 1 things" (s948). #[test] fn every_counted_text_has_a_singular() { let keys: Vec<&str> = nl::TEXTS.iter().map(|(en, _)| *en).collect(); let mut without: Vec<&str> = Vec::new(); for &text in &keys { if NEVER_ONE.contains(&text) { continue; } for (at, _) in text.match_indices("{} ") { let word = text[at + 3..] .split(|c: char| !c.is_ascii_alphabetic()) .next() .unwrap_or(""); // A plural noun after the count, not a verb ("{} is", "{} was"). if word.len() < 3 || !word.ends_with('s') || ["has", "was", "does"].contains(&word) { continue; } let (before, after) = (&text[..at], &text[at + 3 + word.len()..]); let singular = &word[..word.len() - 1]; let has = ["1 ", "one ", "One "].iter().any(|one| { let form = std::format!("{before}{one}{singular}{after}"); keys.contains(&form.as_str()) }); if !has { without.push(text); } } } without.sort(); without.dedup(); assert_eq!( without, NO_SINGULAR_YET, "counted texts with no singular beside them: add one (\"1 note\" beside \"{{}} notes\") \ and pick it by the count, as notes.rs does" ); } /// The string literals in `source` given to `t(`, `tf(` or `locale::t(`. fn asked(source: &str) -> Vec { let mut out = Vec::new(); for marker in ["t(\"", "tf(\""] { let mut rest = source; while let Some(at) = rest.find(marker) { let before = rest[..at].chars().last(); rest = &rest[at + marker.len()..]; // `t(` must be the whole name: not `set(` or `at(`. if before.is_some_and(|c| c.is_alphanumeric() || c == '_') { continue; } let mut text = std::string::String::new(); let mut chars = rest.chars(); while let Some(c) = chars.next() { match c { '"' => break, '\\' => match chars.next() { Some('n') => text.push('\n'), Some(c) => text.push(c), None => {} }, c => text.push(c), } } out.push(text.to_string()); } } out } }