1#![forbid(unsafe_code)]
2
3use crate::reactive::{Observable, Subscription};
10pub use ftui_i18n::catalog::Locale;
11pub use ftui_i18n::format::{
12 Date, DateFormatStyle, DateTime, DateTimeError, DateTimeFormatter, FormattingError,
13 NumberFormat, NumberFormatter, NumberStyle, NumberingSystem, RoundingMode, Time,
14 TimeFormatStyle,
15};
16use std::cell::RefCell;
17use std::env;
18use std::rc::Rc;
19
20thread_local! {
21 static GLOBAL_CONTEXT: LocaleContext = LocaleContext::system();
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
26pub enum TextDirection {
27 #[default]
29 Ltr,
30 Rtl,
32}
33
34impl TextDirection {
35 #[inline]
37 #[must_use]
38 pub const fn is_ltr(self) -> bool {
39 matches!(self, Self::Ltr)
40 }
41
42 #[inline]
44 #[must_use]
45 pub const fn is_rtl(self) -> bool {
46 matches!(self, Self::Rtl)
47 }
48
49 #[must_use]
55 pub fn for_locale(locale: &str) -> Self {
56 let tag = locale.trim();
57 if tag.is_empty() {
58 return Self::Ltr;
59 }
60
61 let parts: Vec<&str> = tag.split(['-', '_']).collect();
62 if let Some(base) = parts.first() {
63 let base_lower = base.to_ascii_lowercase();
64 const RTL_LANGS: &[&str] =
65 &["ar", "he", "fa", "ur", "yi", "ps", "sd", "ug", "dv", "ckb"];
66 if RTL_LANGS.contains(&base_lower.as_str()) {
67 return Self::Rtl;
68 }
69 }
70
71 for part in &parts[1..] {
72 if part.eq_ignore_ascii_case("arab") || part.eq_ignore_ascii_case("hebr") {
73 return Self::Rtl;
74 }
75 }
76
77 Self::Ltr
78 }
79}
80
81impl From<TextDirection> for ftui_render::TextDirection {
82 fn from(dir: TextDirection) -> Self {
83 match dir {
84 TextDirection::Ltr => ftui_render::TextDirection::Ltr,
85 TextDirection::Rtl => ftui_render::TextDirection::Rtl,
86 }
87 }
88}
89
90impl From<ftui_render::TextDirection> for TextDirection {
91 fn from(dir: ftui_render::TextDirection) -> Self {
92 match dir {
93 ftui_render::TextDirection::Ltr => TextDirection::Ltr,
94 ftui_render::TextDirection::Rtl => TextDirection::Rtl,
95 }
96 }
97}
98
99#[derive(Clone, Debug)]
101pub struct LocaleContext {
102 current: Observable<Locale>,
103 overrides: Rc<RefCell<Vec<Locale>>>,
104 direction_override: Observable<Option<TextDirection>>,
105}
106
107impl LocaleContext {
108 #[must_use]
110 pub fn new(locale: impl Into<Locale>) -> Self {
111 let locale = normalize_locale(locale.into());
112 Self {
113 current: Observable::new(locale),
114 overrides: Rc::new(RefCell::new(Vec::new())),
115 direction_override: Observable::new(None),
116 }
117 }
118
119 #[must_use]
121 pub fn system() -> Self {
122 Self::new(detect_system_locale())
123 }
124
125 #[must_use]
127 pub fn global() -> Self {
128 GLOBAL_CONTEXT.with(Clone::clone)
129 }
130
131 #[must_use]
133 pub fn current_locale(&self) -> Locale {
134 if let Some(locale) = self.overrides.borrow().last() {
135 locale.clone()
136 } else {
137 self.current.get()
138 }
139 }
140
141 #[must_use]
143 pub fn base_locale(&self) -> Locale {
144 self.current.get()
145 }
146
147 pub fn set_locale(&self, locale: impl Into<Locale>) {
149 let old_dir = self.direction();
150 let locale = normalize_locale(locale.into());
151 self.current.set(locale);
152 let new_dir = self.direction();
153 if new_dir != old_dir {
154 tracing::info!(
155 target: crate::telemetry_schema::TARGET_LOCALE,
156 locale = %self.current_locale(),
157 direction = ?new_dir,
158 source = "locale",
159 "text direction changed"
160 );
161 }
162 }
163
164 #[must_use]
166 pub fn direction(&self) -> TextDirection {
167 if let Some(dir) = self.direction_override.get() {
168 dir
169 } else {
170 TextDirection::for_locale(&self.current_locale())
171 }
172 }
173
174 pub fn set_direction(&self, direction: Option<TextDirection>) {
176 let old_dir = self.direction();
177 self.direction_override.set(direction);
178 let new_dir = self.direction();
179 if new_dir != old_dir {
180 tracing::info!(
181 target: crate::telemetry_schema::TARGET_LOCALE,
182 locale = %self.current_locale(),
183 direction = ?new_dir,
184 source = "override",
185 "text direction changed"
186 );
187 }
188 }
189
190 pub fn subscribe(&self, callback: impl Fn(&Locale) + 'static) -> Subscription {
192 let rc_cb = Rc::new(callback);
193 let cb1 = Rc::clone(&rc_cb);
194 let sub1 = self.current.subscribe(move |loc| cb1(loc));
195 let current = self.current.clone();
196 let cb2 = Rc::clone(&rc_cb);
197 let sub2 = self.direction_override.subscribe(move |_| {
198 let loc = current.get();
199 cb2(&loc);
200 });
201 Subscription::composite(vec![sub1, sub2])
202 }
203
204 #[must_use = "dropping this guard clears the locale override"]
206 pub fn push_override(&self, locale: impl Into<Locale>) -> LocaleOverride {
207 let locale = normalize_locale(locale.into());
208 self.overrides.borrow_mut().push(locale.clone());
209 LocaleOverride {
210 stack: Rc::clone(&self.overrides),
211 locale,
212 }
213 }
214
215 #[must_use]
217 pub fn version(&self) -> u64 {
218 self.current
219 .version()
220 .saturating_add(self.direction_override.version())
221 }
222
223 pub fn number_formatter(&self) -> Result<NumberFormatter, FormattingError> {
228 NumberFormatter::for_locale(&self.current_locale())
229 }
230
231 pub fn number_formatter_with_config(
236 &self,
237 config: NumberFormat,
238 ) -> Result<NumberFormatter, FormattingError> {
239 NumberFormatter::with_config(&self.current_locale(), config)
240 }
241
242 pub fn datetime_formatter(&self) -> Result<DateTimeFormatter, FormattingError> {
247 DateTimeFormatter::for_locale(&self.current_locale())
248 }
249
250 pub fn format_int<I: Into<i128>>(&self, val: I) -> Result<String, FormattingError> {
255 let fmt = self.number_formatter()?;
256 Ok(fmt.format_int(val))
257 }
258
259 pub fn format_number(&self, val: f64) -> Result<String, FormattingError> {
264 let fmt = self.number_formatter()?;
265 fmt.format_float(val)
266 }
267
268 pub fn format_date(
273 &self,
274 date: &Date,
275 style: DateFormatStyle,
276 ) -> Result<String, FormattingError> {
277 let fmt = self.datetime_formatter()?;
278 Ok(fmt.format_date(date, style))
279 }
280
281 pub fn format_datetime(
286 &self,
287 dt: &DateTime,
288 date_style: DateFormatStyle,
289 time_style: TimeFormatStyle,
290 ) -> Result<String, FormattingError> {
291 let fmt = self.datetime_formatter()?;
292 Ok(fmt.format_datetime(dt, date_style, time_style))
293 }
294}
295
296#[must_use = "dropping this guard clears the locale override"]
298pub struct LocaleOverride {
299 stack: Rc<RefCell<Vec<Locale>>>,
300 locale: Locale,
301}
302
303impl Drop for LocaleOverride {
304 fn drop(&mut self) {
305 let popped = self.stack.borrow_mut().pop();
306 if let Some(popped) = popped {
307 debug_assert_eq!(popped, self.locale);
308 }
309 }
310}
311
312#[must_use]
316pub fn detect_system_locale() -> Locale {
317 let lc_all = env::var("LC_ALL").ok();
318 let lang = env::var("LANG").ok();
319 detect_system_locale_from(lc_all.as_deref(), lang.as_deref())
320}
321
322pub fn set_locale(locale: impl Into<Locale>) {
324 LocaleContext::global().set_locale(locale);
325}
326
327#[must_use]
329pub fn current_locale() -> Locale {
330 LocaleContext::global().current_locale()
331}
332
333#[must_use]
335pub fn direction() -> TextDirection {
336 LocaleContext::global().direction()
337}
338
339pub fn set_direction(direction: Option<TextDirection>) {
341 LocaleContext::global().set_direction(direction);
342}
343
344pub fn format_int<I: Into<i128>>(val: I) -> Result<String, FormattingError> {
346 LocaleContext::global().format_int(val)
347}
348
349pub fn format_number(val: f64) -> Result<String, FormattingError> {
351 LocaleContext::global().format_number(val)
352}
353
354pub fn format_date(date: &Date, style: DateFormatStyle) -> Result<String, FormattingError> {
356 LocaleContext::global().format_date(date, style)
357}
358
359pub fn format_datetime(
361 dt: &DateTime,
362 date_style: DateFormatStyle,
363 time_style: TimeFormatStyle,
364) -> Result<String, FormattingError> {
365 LocaleContext::global().format_datetime(dt, date_style, time_style)
366}
367
368fn normalize_locale(mut locale: Locale) -> Locale {
369 normalize_locale_raw(&locale).unwrap_or_else(|| {
370 locale.clear();
371 locale.push_str("en");
372 locale
373 })
374}
375
376fn detect_system_locale_from(lc_all: Option<&str>, lang: Option<&str>) -> Locale {
377 lc_all
378 .and_then(normalize_locale_raw)
379 .or_else(|| lang.and_then(normalize_locale_raw))
380 .unwrap_or_else(|| "en".to_string())
381}
382
383fn normalize_locale_raw(raw: &str) -> Option<Locale> {
384 let raw = raw.trim();
385 if raw.is_empty() {
386 return None;
387 }
388 let raw = raw.split('@').next().unwrap_or(raw);
389 let raw = raw.split('.').next().unwrap_or(raw);
390 let raw = raw.trim();
391 if raw.is_empty() {
392 return None;
393 }
394 let mut normalized = raw.replace('_', "-");
395 if normalized.eq_ignore_ascii_case("c") || normalized.eq_ignore_ascii_case("posix") {
396 normalized.clear();
397 normalized.push_str("en");
398 }
399 Some(normalized)
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use proptest::prelude::*;
406 use std::cell::Cell;
407
408 #[test]
423 fn detect_system_locale_prefers_lc_all() {
424 let locale = detect_system_locale_from(Some("fr_FR.UTF-8"), Some("en_US.UTF-8"));
425 assert_eq!(locale, "fr-FR");
426 }
427
428 #[test]
429 fn detect_system_locale_uses_lang_when_lc_all_missing() {
430 let locale = detect_system_locale_from(None, Some("en_US.UTF-8"));
431 assert_eq!(locale, "en-US");
432 }
433
434 #[test]
435 fn detect_system_locale_defaults_to_en() {
436 let locale = detect_system_locale_from(None, None);
437 assert_eq!(locale, "en");
438 }
439
440 #[test]
441 fn locale_context_switching_updates_version() {
442 let ctx = LocaleContext::new("en");
443 let v0 = ctx.version();
444 ctx.set_locale("en");
445 assert_eq!(ctx.version(), v0);
446 ctx.set_locale("es");
447 assert!(ctx.version() > v0);
448 assert_eq!(ctx.current_locale(), "es");
449 }
450
451 #[test]
452 fn locale_override_is_scoped() {
453 let ctx = LocaleContext::new("en");
454 assert_eq!(ctx.current_locale(), "en");
455 let guard = ctx.push_override("fr");
456 assert_eq!(ctx.current_locale(), "fr");
457 drop(guard);
458 assert_eq!(ctx.current_locale(), "en");
459 }
460
461 #[test]
462 fn locale_override_is_lifo() {
463 let ctx = LocaleContext::new("en");
464 let _outer = ctx.push_override("fr");
465 assert_eq!(ctx.current_locale(), "fr");
466 {
467 let _inner = ctx.push_override("es");
468 assert_eq!(ctx.current_locale(), "es");
469 }
470 assert_eq!(ctx.current_locale(), "fr");
471 }
472
473 #[test]
474 fn normalize_locale_handles_c_and_posix() {
475 let c_locale = normalize_locale_raw("C");
476 let posix_locale = normalize_locale_raw("POSIX");
477 assert_eq!(c_locale.as_deref(), Some("en"));
478 assert_eq!(posix_locale.as_deref(), Some("en"));
479 }
480
481 #[test]
482 fn normalize_locale_strips_codeset_and_modifier() {
483 let locale = normalize_locale_raw("en_US.UTF-8@latin");
484 assert_eq!(locale.as_deref(), Some("en-US"));
485 }
486
487 #[test]
488 fn locale_override_does_not_mutate_base_locale() {
489 let ctx = LocaleContext::new("en");
490 let v0 = ctx.version();
491 let _guard = ctx.push_override("fr");
492 assert_eq!(ctx.base_locale(), "en");
493 assert_eq!(ctx.version(), v0);
494 }
495
496 #[test]
497 fn normalize_empty_falls_back_to_en() {
498 let locale = normalize_locale("".to_string());
499 assert_eq!(locale, "en");
500 }
501
502 #[test]
503 fn normalize_whitespace_only_falls_back_to_en() {
504 let locale = normalize_locale(" ".to_string());
505 assert_eq!(locale, "en");
506 }
507
508 #[test]
509 fn subscribe_fires_on_change() {
510 use std::cell::Cell;
511 use std::rc::Rc;
512
513 let ctx = LocaleContext::new("en");
514 let fired = Rc::new(Cell::new(false));
515 let fired_clone = Rc::clone(&fired);
516 let _sub = ctx.subscribe(move |_| {
517 fired_clone.set(true);
518 });
519 ctx.set_locale("de");
520 assert!(fired.get());
521 }
522
523 #[test]
524 fn detect_system_locale_empty_lc_all_uses_lang() {
525 let locale = detect_system_locale_from(Some(""), Some("ja_JP.UTF-8"));
526 assert_eq!(locale, "ja-JP");
527 }
528
529 proptest! {
530 #[test]
531 fn normalize_locale_raw_sanitizes_segments(raw in "[A-Za-z0-9_@.\\-]{1,32}") {
532 let normalized = normalize_locale_raw(&raw);
533 if let Some(locale) = normalized {
534 prop_assert!(!locale.trim().is_empty());
535 prop_assert!(!locale.contains('@'));
536 prop_assert!(!locale.contains('.'));
537 prop_assert!(!locale.contains('_'));
538 }
539 }
540
541 #[test]
542 fn overrides_are_lifo(locales in proptest::collection::vec("[a-z]{2}(-[A-Z]{2})?", 1..6)) {
543 let ctx = LocaleContext::new("en");
544 let mut guards = Vec::new();
545 for locale in &locales {
546 guards.push(ctx.push_override(locale));
547 }
548 prop_assert_eq!(ctx.current_locale(), locales.last().unwrap().as_str());
549 guards.pop();
550 if locales.len() >= 2 {
551 let prev = &locales[locales.len() - 2];
552 prop_assert_eq!(ctx.current_locale(), prev.as_str());
553 } else {
554 prop_assert_eq!(ctx.current_locale(), "en");
555 }
556 while guards.pop().is_some() {}
559 }
560 }
561
562 #[test]
563 fn direction_for_locale_table() {
564 let cases = [
565 ("ar", TextDirection::Rtl),
566 ("ar-EG", TextDirection::Rtl),
567 ("he-IL", TextDirection::Rtl),
568 ("fa", TextDirection::Rtl),
569 ("ur", TextDirection::Rtl),
570 ("ckb", TextDirection::Rtl),
571 ("ku-Arab", TextDirection::Rtl),
572 ("en", TextDirection::Ltr),
573 ("de-DE", TextDirection::Ltr),
574 ("ja", TextDirection::Ltr),
575 ("", TextDirection::Ltr),
576 ("AR_sa", TextDirection::Rtl),
577 ];
578 for (tag, expected) in cases {
579 assert_eq!(
580 TextDirection::for_locale(tag),
581 expected,
582 "Failed direction inference for locale tag {tag:?}"
583 );
584 }
585 }
586
587 #[test]
588 fn set_direction_override_wins_and_bumps_version() {
589 let ctx = LocaleContext::new("en");
590 assert_eq!(ctx.direction(), TextDirection::Ltr);
591 let v0 = ctx.version();
592
593 let call_count = Rc::new(Cell::new(0));
594 let call_count_clone = Rc::clone(&call_count);
595 let _sub = ctx.subscribe(move |_| {
596 call_count_clone.set(call_count_clone.get() + 1);
597 });
598
599 ctx.set_direction(Some(TextDirection::Rtl));
600 assert_eq!(ctx.direction(), TextDirection::Rtl);
601 assert!(ctx.version() > v0);
602 assert_eq!(call_count.get(), 1);
603
604 let v1 = ctx.version();
605 ctx.set_direction(None);
606 assert_eq!(ctx.direction(), TextDirection::Ltr);
607 assert!(ctx.version() > v1);
608 assert_eq!(call_count.get(), 2);
609 }
610
611 #[test]
612 fn push_override_changes_direction() {
613 let ctx = LocaleContext::new("en");
614 assert_eq!(ctx.direction(), TextDirection::Ltr);
615 {
616 let _guard = ctx.push_override("ar");
617 assert_eq!(ctx.direction(), TextDirection::Rtl);
618 }
619 assert_eq!(ctx.direction(), TextDirection::Ltr);
620 }
621
622 #[test]
623 fn subscribe_fires_on_direction_change() {
624 let ctx = LocaleContext::new("en");
625 let fired = Rc::new(Cell::new(false));
626 let fired_clone = Rc::clone(&fired);
627 let _sub = ctx.subscribe(move |_| {
628 fired_clone.set(true);
629 });
630 ctx.set_direction(Some(TextDirection::Rtl));
631 assert!(fired.get());
632 }
633
634 #[test]
635 fn render_text_direction_conversion() {
636 assert_eq!(
637 ftui_render::TextDirection::from(TextDirection::Ltr),
638 ftui_render::TextDirection::Ltr
639 );
640 assert_eq!(
641 ftui_render::TextDirection::from(TextDirection::Rtl),
642 ftui_render::TextDirection::Rtl
643 );
644 assert_eq!(
645 TextDirection::from(ftui_render::TextDirection::Ltr),
646 TextDirection::Ltr
647 );
648 assert_eq!(
649 TextDirection::from(ftui_render::TextDirection::Rtl),
650 TextDirection::Rtl
651 );
652 }
653
654 #[test]
655 fn locale_context_formatting_reflects_active_locale() {
656 let ctx = LocaleContext::new("en");
657 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
658
659 ctx.set_locale("de");
660 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1.234.567");
661
662 ctx.set_locale("fr");
663 assert_eq!(
664 ctx.format_int(1_234_567).unwrap(),
665 "1\u{202f}234\u{202f}567"
666 );
667
668 ctx.set_locale("ru");
669 assert_eq!(
670 ctx.format_int(1_234_567).unwrap(),
671 "1\u{00a0}234\u{00a0}567"
672 );
673 }
674
675 #[test]
676 fn locale_context_formatting_respects_scoped_override() {
677 let ctx = LocaleContext::new("en");
678 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
679
680 {
681 let _guard = ctx.push_override("de");
682 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1.234.567");
683 }
684
685 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
686 }
687
688 #[test]
689 fn locale_context_date_formatting() {
690 let ctx = LocaleContext::new("en");
691 let date = Date::from_ymd(2026, 9, 19).unwrap();
692
693 assert_eq!(
694 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
695 "09/19/2026"
696 );
697
698 ctx.set_locale("de");
699 assert_eq!(
700 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
701 "19.09.2026"
702 );
703
704 ctx.set_locale("ja");
705 assert_eq!(
706 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
707 "2026/09/19"
708 );
709 }
710
711 #[test]
712 fn locale_context_unsupported_locale_error() {
713 let ctx = LocaleContext::new("unknown-xyz");
714 assert!(matches!(
715 ctx.format_int(100),
716 Err(FormattingError::UnsupportedLocale(_))
717 ));
718 }
719}