1use lingokit::{FluentArgs, FluentValue, LanguageIdentifier, Localizer};
26use pikopiko::compiler::diagnostic::{DiagArg, Diagnostic};
27use pikopiko::lang::Arg;
28use pikopiko::text::{Localized, TextArg};
29use pikopiko::SynthSpec;
30
31use crate::LOCALES;
32
33pub fn requested(cli_lang: Option<&str>) -> Vec<LanguageIdentifier> {
37 if let Some(tag) = cli_lang.and_then(pikopiko::lang::lookup) {
38 if let Ok(id) = tag.parse() {
39 return vec![id];
40 }
41 }
42 let mut langs = lingokit::locale::resolve(LOCALES.env_prefix, None);
43 if langs.is_empty() {
44 if let Some(os) = sys_locale::get_locale().and_then(|s| lingokit::locale::parse_posix(&s)) {
45 langs.push(os);
46 }
47 }
48 langs
49}
50
51pub fn detect_lang() -> &'static str {
53 Texts::new(Localizer::new(&LOCALES, &requested(None))).lang()
54}
55
56pub fn parse_lang(v: &str) -> Result<&'static str, String> {
59 pikopiko::lang::lookup(v).ok_or_else(supported_list)
60}
61
62pub fn supported_list() -> String {
64 pikopiko::lang::LANGUAGES
65 .iter()
66 .map(|(t, _)| *t)
67 .collect::<Vec<_>>()
68 .join(", ")
69}
70
71pub struct Texts {
76 loc: Localizer,
77 tag: &'static str,
78}
79
80impl std::fmt::Debug for Texts {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("Texts").field("lang", &self.tag).finish()
83 }
84}
85
86impl Texts {
87 pub fn new(loc: Localizer) -> Self {
89 let tag = pikopiko::lang::resolve(loc.lang().language.as_str());
90 Texts { loc, tag }
91 }
92
93 pub fn for_lang(tag: &str) -> Self {
95 let id: Vec<LanguageIdentifier> = tag.parse().into_iter().collect();
96 Self::new(Localizer::new(&LOCALES, &id))
97 }
98
99 pub fn localizer(&self) -> &Localizer {
101 &self.loc
102 }
103
104 pub fn lang(&self) -> &'static str {
106 self.tag
107 }
108
109 pub fn tr(&self, key: &str) -> String {
111 self.loc.fmt(key, None)
112 }
113
114 pub fn tr_args(&self, key: &str, args: &[(&str, Arg)]) -> String {
116 self.loc.fmt(key, Some(&fluent_args(args)))
117 }
118
119 pub fn has(&self, key: &str) -> bool {
121 self.loc.has_own(key)
122 }
123
124 pub fn override_text(&self, key: &str) -> Option<String> {
127 self.own(key, &[])
128 }
129
130 fn own(&self, key: &str, args: &[(&str, Arg)]) -> Option<String> {
131 if !self.loc.has_own(key) {
132 return None;
133 }
134 self.loc.get(key, Some(&fluent_args(args)))
135 }
136
137 fn term(&self, key: &str, text: &str, texts: &[pikopiko::text::Catalog]) -> String {
140 if let Some(s) = self.override_text(key) {
141 return s;
142 }
143 if let Some(segs) = pikopiko::text::find(texts, self.tag, key) {
144 return plain(segs);
145 }
146 if let Some(segs) = pikopiko::compiler::diagnostic::lookup(self.tag, key) {
147 return plain(segs);
148 }
149 text.to_string()
150 }
151
152 pub fn diagnostic(&self, d: &Diagnostic) -> String {
155 let key = format!("diag-{}", d.key);
156 if !d.key.is_empty() && self.loc.has_own(&key) {
157 let args: Vec<(&str, Arg)> = d
158 .args
159 .iter()
160 .map(|(n, v)| {
161 let a = match v {
162 DiagArg::Str(s) => Arg::Str(s.clone()),
163 DiagArg::Int(n) => Arg::Num(*n as f64),
164 DiagArg::Term { key, text, texts } => Arg::Str(self.term(key, text, texts)),
165 };
166 (*n, a)
167 })
168 .collect();
169 if let Some(s) = self.own(&key, &args) {
170 return s;
171 }
172 }
173 d.message_in_with(self.tag, &mut |k| self.override_text(k))
174 }
175
176 pub fn error<E: Localized + ?Sized>(&self, e: &E) -> String {
179 if self.loc.has_own(e.text_key()) {
180 let mut args: Vec<(&str, Arg)> = Vec::new();
181 e.text_args(&mut |name, v| {
182 args.push((
183 name,
184 match v {
185 TextArg::Str(s) => Arg::Str(s.to_string()),
186 TextArg::Int(n) => Arg::Num(n as f64),
187 },
188 ))
189 });
190 if let Some(s) = self.own(e.text_key(), &args) {
191 return s;
192 }
193 }
194 pikopiko::text::InLang(e, self.tag).to_string()
195 }
196
197 pub fn synth_text(&self, spec: &SynthSpec, key: &str) -> String {
200 self.override_text(key)
201 .unwrap_or_else(|| spec.text(key, self.tag).to_string())
202 }
203
204 pub fn io_error(&self, e: &std::io::Error) -> String {
207 let key = pikopiko::lang::io_error_key(e);
208 self.own(key, &[("detail", e.to_string().into())])
209 .unwrap_or_else(|| pikopiko::lang::io_error(e, self.tag))
210 }
211}
212
213fn plain(segs: &[pikopiko::text::Seg]) -> String {
215 let mut out = String::new();
216 let _ = pikopiko::text::write_segs(&mut out, segs, &mut |_, _| Ok(()));
217 out
218}
219
220fn fluent_args(args: &[(&str, Arg)]) -> FluentArgs<'static> {
221 let mut fa = FluentArgs::new();
222 for (name, v) in args {
223 match v {
224 Arg::Str(s) => fa.set(name.to_string(), FluentValue::from(s.clone())),
225 Arg::Num(n) => fa.set(name.to_string(), FluentValue::from(*n)),
226 }
227 }
228 fa
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn lang_option_takes_precedence_only_when_supported() {
237 assert_eq!(requested(Some("ja-JP"))[0].to_string(), "ja");
238 assert_eq!(requested(Some("en_US.UTF-8"))[0].to_string(), "en");
239 assert!(requested(Some("fr"))
241 .iter()
242 .all(|l| l.language.as_str() != "fr"));
243 }
244
245 #[test]
246 fn texts_follow_the_language() {
247 assert_eq!(Texts::for_lang("ja").lang(), "ja");
248 assert_eq!(Texts::for_lang("ja-JP").lang(), "ja");
249 assert_eq!(Texts::for_lang("fr").lang(), "en");
250 assert_eq!(parse_lang("ja_JP.UTF-8"), Ok("ja"));
251 assert!(parse_lang("fr").is_err());
252 }
253}