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 use tracing_subscriber::prelude::*;
590
591 #[derive(Clone, Default)]
592 struct LocaleTraceCapture(std::sync::Arc<std::sync::Mutex<Vec<(String, String, String)>>>);
593
594 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LocaleTraceCapture {
595 fn on_event(
596 &self,
597 event: &tracing::Event<'_>,
598 _: tracing_subscriber::layer::Context<'_, S>,
599 ) {
600 if event.metadata().target() == crate::telemetry_schema::TARGET_LOCALE {
601 struct Visitor {
602 locale: String,
603 direction: String,
604 source: String,
605 }
606 impl tracing::field::Visit for Visitor {
607 fn record_debug(
608 &mut self,
609 field: &tracing::field::Field,
610 value: &dyn std::fmt::Debug,
611 ) {
612 let val_str = format!("{value:?}");
613 let val_trimmed = val_str.trim_matches('"').to_string();
614 match field.name() {
615 "locale" => self.locale = val_trimmed,
616 "direction" => self.direction = val_str,
617 "source" => self.source = val_trimmed,
618 _ => {}
619 }
620 }
621 fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
622 match field.name() {
623 "locale" => self.locale = value.to_string(),
624 "source" => self.source = value.to_string(),
625 _ => {}
626 }
627 }
628 }
629 let mut visitor = Visitor {
630 locale: String::new(),
631 direction: String::new(),
632 source: String::new(),
633 };
634 event.record(&mut visitor);
635 self.0.lock().expect("capture lock").push((
636 visitor.locale,
637 visitor.direction,
638 visitor.source,
639 ));
640 }
641 }
642 }
643
644 let capture = LocaleTraceCapture::default();
645 let subscriber = tracing_subscriber::registry().with(capture.clone());
646
647 tracing::subscriber::with_default(subscriber, || {
648 let ctx = LocaleContext::new("en");
649 assert_eq!(ctx.direction(), TextDirection::Ltr);
650 let v0 = ctx.version();
651
652 let call_count = Rc::new(Cell::new(0));
653 let call_count_clone = Rc::clone(&call_count);
654 let _sub = ctx.subscribe(move |_| {
655 call_count_clone.set(call_count_clone.get() + 1);
656 });
657
658 ctx.set_direction(Some(TextDirection::Rtl));
659 assert_eq!(ctx.direction(), TextDirection::Rtl);
660 assert!(ctx.version() > v0);
661 assert_eq!(call_count.get(), 1);
662
663 let v1 = ctx.version();
664 ctx.set_direction(None);
665 assert_eq!(ctx.direction(), TextDirection::Ltr);
666 assert!(ctx.version() > v1);
667 assert_eq!(call_count.get(), 2);
668 });
669
670 let events = capture.0.lock().expect("capture lock");
671 assert!(
672 !events.is_empty(),
673 "Expected tracing events from ftui.runtime.locale"
674 );
675 let (loc, dir, src) = &events[0];
676 assert_eq!(loc, "en");
677 assert!(dir.contains("Rtl"));
678 assert_eq!(src, "override");
679 }
680
681 #[test]
682 fn push_override_changes_direction() {
683 let ctx = LocaleContext::new("en");
684 assert_eq!(ctx.direction(), TextDirection::Ltr);
685 {
686 let _guard = ctx.push_override("ar");
687 assert_eq!(ctx.direction(), TextDirection::Rtl);
688 }
689 assert_eq!(ctx.direction(), TextDirection::Ltr);
690 }
691
692 #[test]
693 fn subscribe_fires_on_direction_change() {
694 let ctx = LocaleContext::new("en");
695 let fired = Rc::new(Cell::new(false));
696 let fired_clone = Rc::clone(&fired);
697 let _sub = ctx.subscribe(move |_| {
698 fired_clone.set(true);
699 });
700 ctx.set_direction(Some(TextDirection::Rtl));
701 assert!(fired.get());
702 }
703
704 #[test]
705 fn render_text_direction_conversion() {
706 assert_eq!(
707 ftui_render::TextDirection::from(TextDirection::Ltr),
708 ftui_render::TextDirection::Ltr
709 );
710 assert_eq!(
711 ftui_render::TextDirection::from(TextDirection::Rtl),
712 ftui_render::TextDirection::Rtl
713 );
714 assert_eq!(
715 TextDirection::from(ftui_render::TextDirection::Ltr),
716 TextDirection::Ltr
717 );
718 assert_eq!(
719 TextDirection::from(ftui_render::TextDirection::Rtl),
720 TextDirection::Rtl
721 );
722 }
723
724 #[test]
725 fn locale_context_formatting_reflects_active_locale() {
726 let ctx = LocaleContext::new("en");
727 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
728
729 ctx.set_locale("de");
730 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1.234.567");
731
732 ctx.set_locale("fr");
733 assert_eq!(
734 ctx.format_int(1_234_567).unwrap(),
735 "1\u{202f}234\u{202f}567"
736 );
737
738 ctx.set_locale("ru");
739 assert_eq!(
740 ctx.format_int(1_234_567).unwrap(),
741 "1\u{00a0}234\u{00a0}567"
742 );
743 }
744
745 #[test]
746 fn locale_context_formatting_respects_scoped_override() {
747 let ctx = LocaleContext::new("en");
748 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
749
750 {
751 let _guard = ctx.push_override("de");
752 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1.234.567");
753 }
754
755 assert_eq!(ctx.format_int(1_234_567).unwrap(), "1,234,567");
756 }
757
758 #[test]
759 fn locale_context_date_formatting() {
760 let ctx = LocaleContext::new("en");
761 let date = Date::from_ymd(2026, 9, 19).unwrap();
762
763 assert_eq!(
764 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
765 "09/19/2026"
766 );
767
768 ctx.set_locale("de");
769 assert_eq!(
770 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
771 "19.09.2026"
772 );
773
774 ctx.set_locale("ja");
775 assert_eq!(
776 ctx.format_date(&date, DateFormatStyle::Short).unwrap(),
777 "2026/09/19"
778 );
779 }
780
781 #[test]
782 fn locale_context_unsupported_locale_error() {
783 let ctx = LocaleContext::new("unknown-xyz");
784 assert!(matches!(
785 ctx.format_int(100),
786 Err(FormattingError::UnsupportedLocale(_))
787 ));
788 }
789}