BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / regional.rs

regional.rs

regional.rs 18.0 KiB Download Raw
1//! Regional format: the date and time patterns, clock and week start the app uses.
2//!
3//! It is separate from the app language, as on the OS: English words in Austrian
4//! patterns ("Mon, 16.11.", "14:30") is a normal setup. Teams has no account setting
5//! for it and follows the OS, so the choice is stored locally.
6
7use chrono::Weekday;
8use serde::{Deserialize, Serialize};
9use store::Store;
10
11use crate::format::{self, DateStyle};
12
13const PREFS_KEY: &str = "regional.format";
14const FALLBACK_LOCALE: &str = "en";
15
16/// Regions the date patterns in [`format::date_style`] know. A region decides the
17/// patterns, whatever its language: Austria formats as `de-AT` in an English UI too.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum Region {
21 Australia,
22 Austria,
23 Brazil,
24 Canada,
25 Czechia,
26 Denmark,
27 Finland,
28 France,
29 Germany,
30 India,
31 Ireland,
32 Italy,
33 Japan,
34 Netherlands,
35 Norway,
36 Poland,
37 Spain,
38 Sweden,
39 Switzerland,
40 UnitedKingdom,
41 UnitedStates,
42}
43
44impl Region {
45 pub const ALL: [Region; 21] = [
46 Region::Australia,
47 Region::Austria,
48 Region::Brazil,
49 Region::Canada,
50 Region::Czechia,
51 Region::Denmark,
52 Region::Finland,
53 Region::France,
54 Region::Germany,
55 Region::India,
56 Region::Ireland,
57 Region::Italy,
58 Region::Japan,
59 Region::Netherlands,
60 Region::Norway,
61 Region::Poland,
62 Region::Spain,
63 Region::Sweden,
64 Region::Switzerland,
65 Region::UnitedKingdom,
66 Region::UnitedStates,
67 ];
68
69 /// ISO 3166 region code.
70 pub fn code(self) -> &'static str {
71 match self {
72 Region::Australia => "AU",
73 Region::Austria => "AT",
74 Region::Brazil => "BR",
75 Region::Canada => "CA",
76 Region::Czechia => "CZ",
77 Region::Denmark => "DK",
78 Region::Finland => "FI",
79 Region::France => "FR",
80 Region::Germany => "DE",
81 Region::India => "IN",
82 Region::Ireland => "IE",
83 Region::Italy => "IT",
84 Region::Japan => "JP",
85 Region::Netherlands => "NL",
86 Region::Norway => "NO",
87 Region::Poland => "PL",
88 Region::Spain => "ES",
89 Region::Sweden => "SE",
90 Region::Switzerland => "CH",
91 Region::UnitedKingdom => "GB",
92 Region::UnitedStates => "US",
93 }
94 }
95
96 /// The locale whose patterns the region uses.
97 fn format_locale(self) -> &'static str {
98 match self {
99 Region::Australia => "en-AU",
100 Region::Austria => "de-AT",
101 Region::Brazil => "pt-BR",
102 Region::Canada => "en-CA",
103 Region::Czechia => "cs-CZ",
104 Region::Denmark => "da-DK",
105 Region::Finland => "fi-FI",
106 Region::France => "fr-FR",
107 Region::Germany => "de-DE",
108 Region::India => "en-IN",
109 Region::Ireland => "en-IE",
110 Region::Italy => "it-IT",
111 Region::Japan => "ja-JP",
112 Region::Netherlands => "nl-NL",
113 Region::Norway => "nb-NO",
114 Region::Poland => "pl-PL",
115 Region::Spain => "es-ES",
116 Region::Sweden => "sv-SE",
117 Region::Switzerland => "de-CH",
118 Region::UnitedKingdom => "en-GB",
119 Region::UnitedStates => "en-US",
120 }
121 }
122
123 pub fn from_code(code: &str) -> Option<Region> {
124 Self::ALL
125 .into_iter()
126 .find(|region| region.code().eq_ignore_ascii_case(code))
127 }
128
129 /// The region of a locale tag such as `en-AT`.
130 pub fn of_locale(locale: &str) -> Option<Region> {
131 locale
132 .split(['-', '_'])
133 .skip(1)
134 .find(|part| part.len() == 2)
135 .and_then(Region::from_code)
136 }
137
138 /// Region name in the app language.
139 pub fn label(self) -> String {
140 crate::ui_locale::tr(&format!(
141 "regional.region.{}",
142 self.code().to_ascii_lowercase()
143 ))
144 }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
148#[serde(rename_all = "snake_case")]
149pub enum ClockPreference {
150 /// The region's clock, or the system's when the region follows the system.
151 #[default]
152 Auto,
153 Hours24,
154 Hours12,
155}
156
157impl ClockPreference {
158 pub const ALL: [ClockPreference; 3] = [
159 ClockPreference::Auto,
160 ClockPreference::Hours24,
161 ClockPreference::Hours12,
162 ];
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
166#[serde(default)]
167pub struct RegionalPrefs {
168 /// `None` follows the system.
169 pub region: Option<Region>,
170 pub clock: ClockPreference,
171 /// `None` follows the mailbox language as Outlook does, then the region.
172 pub first_day: Option<Weekday>,
173}
174
175impl RegionalPrefs {
176 /// The same preferences with every field on automatic except the region.
177 pub fn automatic(self) -> RegionalPrefs {
178 RegionalPrefs {
179 region: self.region,
180 ..RegionalPrefs::default()
181 }
182 }
183}
184
185/// `None` when the user never saved a choice.
186pub fn load(store: &Store) -> Option<RegionalPrefs> {
187 let json = store.meta(PREFS_KEY).ok().flatten()?;
188 Some(serde_json::from_str(&json).unwrap_or_default())
189}
190
191pub fn save(store: &Store, prefs: &RegionalPrefs) {
192 let json = serde_json::to_string(prefs).unwrap_or_default();
193 if let Err(error) = store.set_meta(PREFS_KEY, &json) {
194 log::warn!("regional format not saved: {error}");
195 }
196}
197
198/// The OS regional format. Every field is `None` when the OS does not say.
199#[derive(Debug, Clone, Default, PartialEq, Eq)]
200pub struct SystemFormat {
201 /// Format locale such as `en-AT`; on macOS the region override wins over the language's region.
202 pub locale: Option<String>,
203 /// Set only when the user forced a clock on the OS.
204 pub twelve_hour: Option<bool>,
205 /// Set only when the OS has a first day of its own.
206 pub first_day: Option<Weekday>,
207}
208
209impl SystemFormat {
210 pub fn read() -> SystemFormat {
211 platform::read()
212 }
213
214 pub fn region(&self) -> Option<Region> {
215 self.locale.as_deref().and_then(Region::of_locale)
216 }
217}
218
219/// What the regional format falls back to besides the user's choice.
220#[derive(Debug, Clone, Copy)]
221pub struct FormatSources<'a> {
222 pub system: &'a SystemFormat,
223 /// Teams account display language, used when the OS gives no locale.
224 pub display_locale: Option<&'a str>,
225 /// Outlook mailbox language; Outlook takes the default first day from it.
226 pub mailbox_locale: Option<&'a str>,
227}
228
229/// The date style for the preferences. The region decides the patterns; the clock and
230/// first day can be set on their own.
231pub fn resolve(prefs: &RegionalPrefs, sources: FormatSources) -> DateStyle {
232 let follows_system = prefs.region.is_none();
233 let locale = match prefs.region {
234 Some(region) => region.format_locale(),
235 None => sources
236 .system
237 .locale
238 .as_deref()
239 .or(sources.display_locale)
240 .unwrap_or(FALLBACK_LOCALE),
241 };
242 let locale = Region::of_locale(locale).map_or(locale, |region| region.format_locale());
243 let mut style = format::date_style(locale);
244 let twelve_hour = match prefs.clock {
245 ClockPreference::Hours24 => Some(false),
246 ClockPreference::Hours12 => Some(true),
247 ClockPreference::Auto => sources.system.twelve_hour.filter(|_| follows_system),
248 };
249 if let Some(twelve_hour) = twelve_hour {
250 style = style.with_twelve_hour(twelve_hour);
251 }
252 let first_day = prefs
253 .first_day
254 .or(sources.mailbox_locale.map(format::first_day_for_locale))
255 .or(sources.system.first_day.filter(|_| follows_system));
256 if let Some(first_day) = first_day {
257 style = style.with_first_day(first_day);
258 }
259 style
260}
261
262/// `de_AT.UTF-8` and `de-AT` become `de-AT`; `C` and `POSIX` say nothing.
263#[cfg_attr(target_os = "macos", allow(dead_code))]
264fn normalize_locale(raw: &str) -> Option<String> {
265 let tag = raw
266 .split(['.', '@'])
267 .next()
268 .unwrap_or_default()
269 .replace('_', "-");
270 (!tag.is_empty() && tag != "C" && tag != "POSIX").then_some(tag)
271}
272
273/// macOS keeps the region in `AppleLocale`; a region set apart from the language
274/// is an `rg` keyword: `en_US@rg=atzzzz` formats as Austria.
275#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
276fn apple_locale_tag(raw: &str) -> Option<String> {
277 let (base, keywords) = raw.split_once('@').unwrap_or((raw, ""));
278 let mut parts = base.split(['_', '-']).filter(|part| !part.is_empty());
279 let language = parts.next()?;
280 let base_region = parts.find(|part| part.len() == 2);
281 let override_region = keywords
282 .split(';')
283 .find_map(|keyword| keyword.strip_prefix("rg="))
284 .and_then(|value| value.get(..2));
285 Some(match override_region.or(base_region) {
286 Some(region) => format!("{language}-{}", region.to_ascii_uppercase()),
287 None => language.to_owned(),
288 })
289}
290
291#[cfg(target_os = "macos")]
292mod platform {
293 use std::ffi::c_void;
294
295 use chrono::Weekday;
296 use core_foundation::base::{CFType, TCFType};
297 use core_foundation::boolean::CFBoolean;
298 use core_foundation::number::CFNumber;
299 use core_foundation::string::CFString;
300 use core_foundation_sys::dictionary::{CFDictionaryGetTypeID, CFDictionaryGetValue};
301 use core_foundation_sys::preferences::{
302 CFPreferencesCopyAppValue, kCFPreferencesAnyApplication,
303 };
304
305 use super::SystemFormat;
306
307 /// A value of the global preferences domain (`defaults read -g`).
308 fn global(key: &str) -> Option<CFType> {
309 let key = CFString::new(key);
310 // SAFETY: a valid key and the any-application domain; the copy is owned.
311 let value = unsafe {
312 CFPreferencesCopyAppValue(key.as_concrete_TypeRef(), kCFPreferencesAnyApplication)
313 };
314 // SAFETY: non-null values come from a Copy function.
315 (!value.is_null()).then(|| unsafe { CFType::wrap_under_create_rule(value) })
316 }
317
318 fn flag(key: &str) -> bool {
319 global(key)
320 .and_then(|value| value.downcast::<CFBoolean>())
321 .is_some_and(bool::from)
322 }
323
324 /// `AppleFirstWeekday = { gregorian = 2 }`, counted from Sunday as 1.
325 fn first_weekday() -> Option<Weekday> {
326 let dictionary = global("AppleFirstWeekday")?;
327 // SAFETY: plain type id lookup.
328 if dictionary.type_of() != unsafe { CFDictionaryGetTypeID() } {
329 return None;
330 }
331 let key = CFString::new("gregorian");
332 // SAFETY: the dictionary type was checked; the value is borrowed from it.
333 let value = unsafe {
334 CFDictionaryGetValue(
335 dictionary.as_CFTypeRef().cast(),
336 key.as_concrete_TypeRef() as *const c_void,
337 )
338 };
339 if value.is_null() {
340 return None;
341 }
342 // SAFETY: non-null and owned by the dictionary, which outlives this call.
343 let number = unsafe { CFType::wrap_under_get_rule(value) }.downcast::<CFNumber>()?;
344 let from_sunday = number.to_i64().filter(|day| (1..=7).contains(day))?;
345 // chrono counts from Monday as 0.
346 Weekday::try_from(u8::try_from((from_sunday + 5) % 7).ok()?).ok()
347 }
348
349 pub fn read() -> SystemFormat {
350 let locale = global("AppleLocale")
351 .and_then(|value| value.downcast::<CFString>())
352 .and_then(|value| super::apple_locale_tag(&value.to_string()));
353 let twelve_hour = if flag("AppleICUForce24HourTime") {
354 Some(false)
355 } else if flag("AppleICUForce12HourTime") {
356 Some(true)
357 } else {
358 None
359 };
360 SystemFormat {
361 locale,
362 twelve_hour,
363 first_day: first_weekday(),
364 }
365 }
366}
367
368#[cfg(windows)]
369mod platform {
370 use chrono::Weekday;
371 use windows::Win32::Globalization::{
372 GetLocaleInfoEx, GetUserDefaultLocaleName, LOCALE_IFIRSTDAYOFWEEK, LOCALE_ITIME,
373 };
374 use windows::core::PCWSTR;
375
376 use super::SystemFormat;
377
378 const LOCALE_NAME_MAX_LENGTH: usize = 85;
379
380 /// A value of the user's regional format, with the user's overrides applied.
381 fn user_info(kind: u32) -> Option<String> {
382 let mut buffer = [0u16; 8];
383 // SAFETY: a null name reads the user default locale; the buffer is sized for the value.
384 let length = unsafe { GetLocaleInfoEx(PCWSTR::null(), kind, Some(&mut buffer)) };
385 let length = usize::try_from(length).ok()?.checked_sub(1)?;
386 Some(String::from_utf16_lossy(&buffer[..length]))
387 }
388
389 pub fn read() -> SystemFormat {
390 let mut name = [0u16; LOCALE_NAME_MAX_LENGTH];
391 // SAFETY: the buffer has the documented maximum length.
392 let length = unsafe { GetUserDefaultLocaleName(&mut name) };
393 let locale = usize::try_from(length)
394 .ok()
395 .and_then(|length| length.checked_sub(1))
396 .map(|length| String::from_utf16_lossy(&name[..length]))
397 .and_then(|raw| super::normalize_locale(&raw));
398 // `LOCALE_IFIRSTDAYOFWEEK` counts from Monday as 0.
399 let first_day = user_info(LOCALE_IFIRSTDAYOFWEEK)
400 .and_then(|value| value.parse::<u8>().ok())
401 .and_then(|from_monday| Weekday::try_from(from_monday).ok());
402 SystemFormat {
403 locale,
404 twelve_hour: user_info(LOCALE_ITIME).map(|value| value == "0"),
405 first_day,
406 }
407 }
408}
409
410#[cfg(not(any(target_os = "macos", windows)))]
411mod platform {
412 use super::SystemFormat;
413
414 /// `LC_TIME` is the date and time format; `LC_ALL` overrides it, `LANG` is the default.
415 pub fn read() -> SystemFormat {
416 let locale = ["LC_ALL", "LC_TIME", "LANG"]
417 .into_iter()
418 .find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()))
419 .and_then(|raw| super::normalize_locale(&raw));
420 SystemFormat {
421 locale,
422 ..SystemFormat::default()
423 }
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use chrono::NaiveDate;
430
431 use super::*;
432
433 fn system(locale: &str) -> SystemFormat {
434 SystemFormat {
435 locale: Some(locale.to_owned()),
436 ..SystemFormat::default()
437 }
438 }
439
440 fn style(prefs: RegionalPrefs, system: &SystemFormat, mailbox: Option<&str>) -> DateStyle {
441 resolve(
442 &prefs,
443 FormatSources {
444 system,
445 display_locale: None,
446 mailbox_locale: mailbox,
447 },
448 )
449 }
450
451 #[test]
452 fn the_macos_region_override_wins_over_the_language() {
453 assert_eq!(
454 apple_locale_tag("en_US@rg=atzzzz").as_deref(),
455 Some("en-AT")
456 );
457 assert_eq!(apple_locale_tag("de_AT").as_deref(), Some("de-AT"));
458 assert_eq!(apple_locale_tag("zh-Hans_CN").as_deref(), Some("zh-CN"));
459 assert_eq!(apple_locale_tag("en").as_deref(), Some("en"));
460 }
461
462 #[test]
463 fn os_locale_names_become_language_tags() {
464 assert_eq!(normalize_locale("en_GB.UTF-8").as_deref(), Some("en-GB"));
465 assert_eq!(normalize_locale("de_DE@euro").as_deref(), Some("de-DE"));
466 assert_eq!(normalize_locale("C"), None);
467 assert_eq!(normalize_locale(""), None);
468 }
469
470 #[test]
471 fn english_in_austria_formats_as_austria() {
472 let style = style(RegionalPrefs::default(), &system("en-AT"), None);
473 let date = NaiveDate::from_ymd_opt(2026, 3, 9).unwrap();
474 assert_eq!(style.clock(), "%H:%M");
475 assert_eq!(style.first_day(), Weekday::Mon);
476 format::set_date_style(Some(style));
477 assert_eq!(format::date_label(date), "9.3.2026");
478 assert_eq!(format::decimal_label(1.5, 1), "1,5");
479 format::set_date_style(None);
480 }
481
482 #[test]
483 fn a_chosen_region_ignores_the_system_clock_and_first_day() {
484 let forced = SystemFormat {
485 twelve_hour: Some(false),
486 first_day: Some(Weekday::Sat),
487 ..system("de-AT")
488 };
489 let follows = style(RegionalPrefs::default(), &forced, None);
490 assert!(!follows.twelve_hour());
491 assert_eq!(follows.first_day(), Weekday::Sat);
492 let chosen = RegionalPrefs {
493 region: Some(Region::UnitedStates),
494 ..RegionalPrefs::default()
495 };
496 let us = style(chosen, &forced, None);
497 assert!(us.twelve_hour());
498 assert_eq!(us.first_day(), Weekday::Sun);
499 }
500
501 #[test]
502 fn the_first_day_is_the_choice_then_the_mailbox_then_the_region() {
503 let us = system("en-US");
504 assert_eq!(
505 style(RegionalPrefs::default(), &us, None).first_day(),
506 Weekday::Sun
507 );
508 assert_eq!(
509 style(RegionalPrefs::default(), &us, Some("en-AT")).first_day(),
510 Weekday::Mon
511 );
512 let chosen = RegionalPrefs {
513 first_day: Some(Weekday::Sat),
514 ..RegionalPrefs::default()
515 };
516 assert_eq!(style(chosen, &us, Some("en-AT")).first_day(), Weekday::Sat);
517 }
518
519 #[test]
520 fn the_clock_choice_overrides_the_region() {
521 let hours_12 = RegionalPrefs {
522 clock: ClockPreference::Hours12,
523 ..RegionalPrefs::default()
524 };
525 assert_eq!(style(hours_12, &system("de-AT"), None).clock(), "%-I:%M %p");
526 let hours_24 = RegionalPrefs {
527 clock: ClockPreference::Hours24,
528 ..RegionalPrefs::default()
529 };
530 assert_eq!(style(hours_24, &system("en-US"), None).clock(), "%H:%M");
531 // A 12-hour region keeps its own spelling.
532 assert_eq!(style(hours_12, &system("en-AU"), None).clock(), "%-I:%M %P");
533 }
534
535 #[test]
536 fn prefs_are_none_until_saved_and_round_trip() {
537 let store = Store::open_in_memory().unwrap();
538 assert_eq!(load(&store), None);
539 let prefs = RegionalPrefs {
540 region: Some(Region::Austria),
541 clock: ClockPreference::Hours24,
542 first_day: Some(Weekday::Mon),
543 };
544 save(&store, &prefs);
545 assert_eq!(load(&store), Some(prefs));
546 }
547}