Skip to main content

crabshell_services/
locale.rs

1//! Month and day names for the user's locale, from glibc's own data:
2//! `locale -k LC_TIME`, run once on a thread of its own.
3
4use std::future::poll_fn;
5use std::io::Read;
6use std::process::{Command, Stdio};
7use std::rc::Rc;
8use std::sync::{Arc, Mutex, PoisonError};
9use std::task::{Poll, Waker};
10
11use crabshell_reactive::{ReadSignal, Signal};
12use crabshell_ui::Cx;
13use jiff::Zoned;
14use jiff::civil::{Date, Weekday};
15
16use crate::Shared;
17
18#[cfg(test)]
19mod tests;
20
21/// The most `locale` may print. glibc's `LC_TIME` is about 2 KiB.
22const MAX_OUTPUT: u64 = 64 * 1024;
23
24/// The most of `locale`'s warnings kept; the rest is read and dropped.
25const MAX_WARNINGS: u64 = 4096;
26
27/// The names dates are written with in a locale.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct Locale {
30  /// January first, as `%B` writes them: the form used inside a date,
31  /// genitive in Polish, Russian, Ukrainian, Czech and others, so a
32  /// calendar's header uses [`months_standalone`](Self::months_standalone).
33  pub months: [String; 12],
34  /// January first, as a month is named on its own, from glibc's
35  /// `alt_mon`; the same as `months` in a locale without it.
36  pub months_standalone: [String; 12],
37  /// January first, as `%b` writes them.
38  pub months_short: [String; 12],
39  /// Monday first, as `%A` writes them.
40  pub weekdays: [String; 7],
41  /// Monday first, as `%a` writes them.
42  pub weekdays_short: [String; 7],
43  /// Before and after noon, as `%p` writes them. Empty in a locale that
44  /// writes 24-hour time.
45  pub am_pm: [String; 2],
46  /// The day a calendar's week starts on.
47  pub first_weekday: Weekday,
48}
49
50impl Default for Locale {
51  /// English, as the C locale writes it.
52  fn default() -> Locale {
53    let names = |list: &str| list.split(';').map(str::to_owned).collect::<Vec<_>>();
54    let months: [String; 12] = array(names(
55      "January;February;March;April;May;June;July;August;September;October;November;December",
56    ));
57    Locale {
58      months_standalone: months.clone(),
59      months,
60      months_short: array(names("Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec")),
61      weekdays: array(names(
62        "Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday",
63      )),
64      weekdays_short: array(names("Mon;Tue;Wed;Thu;Fri;Sat;Sun")),
65      am_pm: array(names("AM;PM")),
66      first_weekday: Weekday::Sunday,
67    }
68  }
69}
70
71impl Locale {
72  /// `time` written as `format` says, as jiff's `strftime` does, with
73  /// `%a`, `%A`, `%b`, `%h`, `%B` and `%p` in this locale. Before those,
74  /// `^` uppercases the name, `#` changes its case as glibc's does, and
75  /// other flags and a width are ignored. A format jiff can't write is
76  /// logged and gives an empty string.
77  pub fn strftime(&self, time: &Zoned, format: &str) -> String {
78    let mut filled = String::with_capacity(format.len());
79    let mut chars = format.chars();
80    while let Some(c) = chars.next() {
81      if c != '%' {
82        filled.push(c);
83        continue;
84      }
85      // jiff's flags and a width may come first.
86      let mut spec = String::new();
87      let conversion = loop {
88        match chars.next() {
89          Some(flag @ ('-' | '_' | '^' | '#' | '0'..='9')) => spec.push(flag),
90          other => break other,
91        }
92      };
93      let weekday = time.weekday().to_monday_zero_offset() as usize;
94      let month = (time.month() - 1) as usize;
95      let name = match conversion {
96        Some('a') => &self.weekdays_short[weekday],
97        Some('A') => &self.weekdays[weekday],
98        Some('b' | 'h') => &self.months_short[month],
99        Some('B') => &self.months[month],
100        Some('p') => &self.am_pm[usize::from(time.hour() >= 12)],
101        other => {
102          filled.push('%');
103          filled.push_str(&spec);
104          filled.extend(other);
105          continue;
106        }
107      };
108      // `^` uppercases a name, and `#` does too, but lowercases `%p`, as
109      // glibc's do; padding is dropped.
110      let name = if spec.contains('#') && conversion == Some('p') {
111        name.to_lowercase()
112      } else if spec.contains(['^', '#']) {
113        name.to_uppercase()
114      } else {
115        name.clone()
116      };
117      // Names go to jiff as literal text.
118      filled.push_str(&name.replace('%', "%%"));
119    }
120    jiff::fmt::strtime::format(filled, time).unwrap_or_else(|error| {
121      tracing::warn!(format, %error, "couldn't write a time");
122      String::new()
123    })
124  }
125
126  /// The names in what `locale -k LC_TIME` printed, English for any it
127  /// left out or that don't parse.
128  pub(crate) fn parse(output: &str) -> Locale {
129    let mut locale = Locale::default();
130    let (mut start, mut first) = (Weekday::Sunday, 1_i64);
131    let mut standalone = None;
132    for line in output.lines() {
133      let Some((key, value)) = line.split_once('=') else {
134        continue;
135      };
136      let value = value.trim_matches('"');
137      let names = || value.split(';').map(str::to_owned).collect::<Vec<_>>();
138      let sunday_first = |names: Vec<String>| (names.len() == 7).then(|| monday_first(names));
139      match key {
140        "mon" => locale.months = array_or(names(), locale.months),
141        "alt_mon" => standalone = names().try_into().ok(),
142        "abmon" => locale.months_short = array_or(names(), locale.months_short),
143        "day" => locale.weekdays = sunday_first(names()).unwrap_or(locale.weekdays),
144        "abday" => locale.weekdays_short = sunday_first(names()).unwrap_or(locale.weekdays_short),
145        "am_pm" => locale.am_pm = array_or(names(), locale.am_pm),
146        // glibc counts the first weekday from 1, the weekday of the date
147        // `week-1stday` names.
148        "week-1stday" => {
149          start = value
150            .parse::<i64>()
151            .ok()
152            .and_then(|day| {
153              let part = |divisor: i64| i8::try_from(day / divisor % 100).ok();
154              Date::new(i16::try_from(day / 10_000).ok()?, part(100)?, part(1)?).ok()
155            })
156            .map_or(Weekday::Sunday, |date| date.weekday());
157        }
158        "first_weekday" => first = value.parse().unwrap_or(1).clamp(1, 7),
159        _ => {}
160      }
161    }
162    locale.first_weekday = start.wrapping_add(first - 1);
163    locale.months_standalone = standalone.unwrap_or_else(|| locale.months.clone());
164    locale
165  }
166}
167
168/// Seven names from Sunday, from Monday.
169fn monday_first(mut names: Vec<String>) -> [String; 7] {
170  names.rotate_left(1);
171  array(names)
172}
173
174/// `names` as an array, or `or` if there are more or fewer.
175fn array_or<const N: usize>(names: Vec<String>, or: [String; N]) -> [String; N] {
176  names.try_into().unwrap_or(or)
177}
178
179fn array<const N: usize>(names: Vec<String>) -> [String; N] {
180  names.try_into().expect("a built-in list has its length")
181}
182
183/// The user's locale for dates, shared by every caller.
184struct Shown(Signal<Locale>);
185
186/// `cx.locale()`.
187pub(crate) fn locale(cx: &Cx) -> ReadSignal<Locale> {
188  if let Some(shown) = cx.service::<Shown>() {
189    return shown.0.read_only();
190  }
191  let var = |name| std::env::var(name).ok().filter(|value| !value.is_empty());
192  let name = var("LC_ALL")
193    .or_else(|| var("LC_TIME"))
194    .or_else(|| var("LANG"));
195  let shared = cx
196    .service::<crate::process::Processes>()
197    .map(|processes| Rc::clone(&processes.shared));
198  let signal = match &shared {
199    Some(shared) => shared.root.signal(Locale::default()),
200    None => cx.signal(Locale::default()),
201  };
202  cx.provide(Shown(signal));
203  if let (Some(shared), Some(name)) = (shared, name) {
204    read(&shared, name, signal);
205  }
206  signal.read_only()
207}
208
209/// What `locale` printed, once its thread is done, and who waits for it.
210type Answer = (Option<Result<String, String>>, Option<Waker>);
211
212/// Sets `signal` to locale `name`'s names, read on a thread of its own.
213/// C and POSIX stay English, and so does a locale `locale` can't read,
214/// which is logged.
215pub(crate) fn read(shared: &Shared, name: String, signal: Signal<Locale>) {
216  let base = name.split(['.', '@']).next().unwrap_or_default();
217  if base == "C" || base == "POSIX" {
218    return;
219  }
220  let answer: Arc<Mutex<Answer>> = Arc::default();
221  let filled = Arc::clone(&answer);
222  let spawned = std::thread::Builder::new()
223    .name(String::from("crabshell-locale"))
224    .spawn(move || {
225      let output = run_locale(&name);
226      let mut answer = filled.lock().unwrap_or_else(PoisonError::into_inner);
227      answer.0 = Some(output);
228      if let Some(waker) = answer.1.take() {
229        waker.wake();
230      }
231    });
232  if let Err(error) = spawned {
233    return tracing::warn!(%error, "couldn't read the locale's names, so dates are in English");
234  }
235  shared.spawn(async move {
236    let output = poll_fn(|context| {
237      let mut answer = answer.lock().unwrap_or_else(PoisonError::into_inner);
238      match answer.0.take() {
239        Some(output) => Poll::Ready(output),
240        None => {
241          answer.1 = Some(context.waker().clone());
242          Poll::Pending
243        }
244      }
245    })
246    .await;
247    match output {
248      Ok(output) => {
249        signal.try_set(Locale::parse(&output));
250      }
251      Err(why) => tracing::warn!(
252        why,
253        "couldn't read the locale's names, so dates are in English"
254      ),
255    }
256  });
257}
258
259/// What `locale -k LC_TIME` prints with `LC_ALL` set to `name`.
260fn run_locale(name: &str) -> Result<String, String> {
261  let mut child = Command::new("locale")
262    .args(["-k", "LC_TIME"])
263    .env("LC_ALL", name)
264    .stdin(Stdio::null())
265    .stdout(Stdio::piped())
266    .stderr(Stdio::piped())
267    .spawn()
268    .map_err(|error| format!("locale didn't start: {error}"))?;
269  // Read on a thread of its own, so a full pipe of either never stops
270  // the other. glibc warns there when the locale isn't installed, and
271  // prints C's.
272  let mut stderr = child.stderr.take().expect("stderr is piped");
273  let warnings = std::thread::spawn(move || {
274    let mut kept = Vec::new();
275    let _ = (&mut stderr).take(MAX_WARNINGS).read_to_end(&mut kept);
276    let _ = std::io::copy(&mut stderr, &mut std::io::sink());
277    String::from_utf8_lossy(&kept).into_owned()
278  });
279  let mut output = String::new();
280  let read = child
281    .stdout
282    .take()
283    .expect("stdout is piped")
284    .take(MAX_OUTPUT + 1)
285    .read_to_string(&mut output);
286  if read.is_err() || output.len() as u64 > MAX_OUTPUT {
287    let _ = child.kill();
288  }
289  let warning = warnings.join().unwrap_or_default();
290  let status = child.wait().map_err(|error| error.to_string())?;
291  if let Some(line) = warning.lines().next() {
292    return Err(line.to_owned());
293  }
294  read.map_err(|error| format!("locale printed something unreadable: {error}"))?;
295  if output.len() as u64 > MAX_OUTPUT {
296    return Err("locale printed over 64 KiB".into());
297  }
298  if !status.success() {
299    return Err(format!("locale failed: {status}"));
300  }
301  Ok(output)
302}