1use std::sync::LazyLock;
24use std::sync::atomic::{AtomicU8, Ordering};
25
26use crate::utils::env_flag_value_enabled;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
30pub enum BoxGlyphTier {
31 #[default]
33 Ascii,
34 Unicode,
36 RichUnicode,
38}
39
40impl BoxGlyphTier {
41 #[must_use]
43 pub fn supports_unicode(self) -> bool {
44 !matches!(self, Self::Ascii)
45 }
46}
47
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct TerminalEnv {
55 pub term: Option<String>,
57 pub term_program: Option<String>,
59 pub lang: Option<String>,
61 pub lc_all: Option<String>,
63 pub lc_ctype: Option<String>,
65 pub no_unicode: Option<String>,
67 pub no_rich_unicode: Option<String>,
69}
70
71impl TerminalEnv {
72 #[must_use]
74 pub fn capture() -> Self {
75 Self {
76 term: std::env::var("TERM").ok(),
77 term_program: std::env::var("TERM_PROGRAM").ok(),
78 lang: std::env::var("LANG").ok(),
79 lc_all: std::env::var("LC_ALL").ok(),
80 lc_ctype: std::env::var("LC_CTYPE").ok(),
81 no_unicode: std::env::var("VTCODE_NO_UNICODE").ok(),
82 no_rich_unicode: std::env::var("VTCODE_NO_RICH_UNICODE").ok(),
83 }
84 }
85
86 #[must_use]
92 pub fn no_unicode_requested(&self) -> bool {
93 env_flag_value_enabled(self.no_unicode.as_deref())
94 }
95
96 #[must_use]
98 pub fn no_rich_unicode_requested(&self) -> bool {
99 env_flag_value_enabled(self.no_rich_unicode.as_deref())
100 }
101
102 #[must_use]
109 pub fn supports_unicode_box_drawing(&self) -> bool {
110 if let Some(term) = self.term.as_deref() {
111 if term_supports_unicode(term) {
112 return true;
113 }
114 if term_lacks_unicode(term) {
115 return false;
116 }
117 }
118
119 [self.lang.as_deref(), self.lc_all.as_deref(), self.lc_ctype.as_deref()]
120 .iter()
121 .flatten()
122 .any(|locale| locale_is_utf8(locale))
123 }
124
125 #[must_use]
130 pub fn supports_rich_box_drawing(&self) -> bool {
131 const RICH_TERMINALS: [&str; 6] = ["ghostty", "wezterm", "iterm", "hyper", "kitty", "alacritty"];
132
133 let term_program = self.term_program.as_deref().unwrap_or_default();
134 let term = self.term.as_deref().unwrap_or_default();
135 RICH_TERMINALS.iter().any(|name| {
136 crate::formatting::contains_ignore_ascii_case(term_program, name)
137 || crate::formatting::contains_ignore_ascii_case(term, name)
138 })
139 }
140}
141
142#[must_use]
148pub fn box_glyph_tier() -> BoxGlyphTier {
149 if ambiguous_width_wide() {
150 return BoxGlyphTier::Ascii;
151 }
152 *BOX_GLYPH_TIER
153}
154
155#[must_use]
157pub fn box_glyph_tier_for(env: &TerminalEnv) -> BoxGlyphTier {
158 if env.no_unicode_requested() {
159 return BoxGlyphTier::Ascii;
160 }
161 if !env.supports_unicode_box_drawing() {
162 return BoxGlyphTier::Ascii;
163 }
164 if env.no_rich_unicode_requested() {
165 return BoxGlyphTier::Unicode;
166 }
167 if env.supports_rich_box_drawing() {
168 return BoxGlyphTier::RichUnicode;
169 }
170 BoxGlyphTier::Unicode
171}
172
173static AMBIGUOUS_WIDTH: AtomicU8 = AtomicU8::new(AMBIGUOUS_WIDTH_UNSET);
182
183const AMBIGUOUS_WIDTH_UNSET: u8 = 0;
184const AMBIGUOUS_WIDTH_NARROW: u8 = 1;
185const AMBIGUOUS_WIDTH_WIDE: u8 = 2;
186
187pub fn set_ambiguous_width(mode: crate::ui_protocol::AmbiguousWidthMode) {
192 let value = match mode {
193 crate::ui_protocol::AmbiguousWidthMode::Narrow => AMBIGUOUS_WIDTH_NARROW,
194 crate::ui_protocol::AmbiguousWidthMode::Wide => AMBIGUOUS_WIDTH_WIDE,
195 };
196 let _applied = AMBIGUOUS_WIDTH.compare_exchange(AMBIGUOUS_WIDTH_UNSET, value, Ordering::Relaxed, Ordering::Relaxed);
198}
199
200#[must_use]
203pub fn ambiguous_width_wide() -> bool {
204 AMBIGUOUS_WIDTH.load(Ordering::Relaxed) == AMBIGUOUS_WIDTH_WIDE
205}
206
207static BOX_GLYPH_TIER: LazyLock<BoxGlyphTier> = LazyLock::new(|| box_glyph_tier_for(&TerminalEnv::capture()));
209
210fn term_supports_unicode(term: &str) -> bool {
212 let term = term.to_ascii_lowercase();
213 term.contains("utf")
214 || term.contains("unicode")
215 || term.contains("256color")
216 || term.contains("truecolor")
217 || term.contains("direct")
218 || term.contains("alacritty")
219 || term.contains("wezterm")
220 || term.contains("kitty")
221 || term.contains("iterm")
222 || term.contains("hyper")
223 || term.contains("ghostty")
224 || term.contains("konsole")
225 || term.contains("contour")
226 || term.contains("foot")
227}
228
229fn term_lacks_unicode(term: &str) -> bool {
231 let term = term.to_ascii_lowercase();
232 term == "dumb" || term == "emacs" || term == "ansi" || term == "cons25" || term == "basic" || term.starts_with("vt")
233}
234
235fn locale_is_utf8(locale: &str) -> bool {
237 locale.to_ascii_lowercase().contains("utf")
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 fn env(term: Option<&str>, term_program: Option<&str>, lang: Option<&str>) -> TerminalEnv {
245 TerminalEnv {
246 term: term.map(str::to_owned),
247 term_program: term_program.map(str::to_owned),
248 lang: lang.map(str::to_owned),
249 ..TerminalEnv::default()
250 }
251 }
252
253 #[test]
254 fn ascii_is_the_fallback_without_evidence() {
255 assert_eq!(box_glyph_tier_for(&TerminalEnv::default()), BoxGlyphTier::Ascii);
256 assert_eq!(box_glyph_tier_for(&env(None, None, None)), BoxGlyphTier::Ascii);
257 }
258
259 #[test]
260 fn term_advertisement_earns_unicode_even_with_a_c_locale() {
261 let tier = box_glyph_tier_for(&env(Some("xterm-256color"), None, Some("C")));
262 assert_eq!(tier, BoxGlyphTier::Unicode);
263 }
264
265 #[test]
266 fn utf8_locale_earns_unicode_when_term_says_nothing() {
267 assert_eq!(box_glyph_tier_for(&env(None, None, Some("en_US.UTF-8"))), BoxGlyphTier::Unicode);
268 assert_eq!(
269 box_glyph_tier_for(&TerminalEnv {
270 lc_ctype: Some("en_US.UTF-8".to_owned()),
271 ..TerminalEnv::default()
272 }),
273 BoxGlyphTier::Unicode
274 );
275 }
276
277 #[test]
278 fn explicitly_non_utf8_locale_stays_ascii() {
279 assert_eq!(box_glyph_tier_for(&env(None, None, Some("C"))), BoxGlyphTier::Ascii);
280 }
281
282 #[test]
283 fn dumb_terminal_stays_ascii_even_with_a_utf8_locale() {
284 assert_eq!(box_glyph_tier_for(&env(Some("dumb"), None, Some("en_US.UTF-8"))), BoxGlyphTier::Ascii);
285 }
286
287 #[test]
288 fn term_program_identifies_rich_terminals_that_share_a_generic_term() {
289 for (program, term) in [
290 ("iTerm.app", "xterm-256color"),
291 ("WezTerm", "xterm-256color"),
292 ("Hyper.app", "xterm-256color"),
293 ("kitty", "xterm-kitty"),
294 ("ghostty", "xterm-ghostty"),
295 ("Alacritty", "alacritty"),
296 ] {
297 let tier = box_glyph_tier_for(&env(Some(term), Some(program), Some("en_US.UTF-8")));
298 assert_eq!(tier, BoxGlyphTier::RichUnicode, "{program} should reach the rich tier");
299 }
300 }
301
302 #[test]
303 fn plain_terminals_stay_on_the_unicode_tier() {
304 assert_eq!(box_glyph_tier_for(&env(Some("xterm-256color"), None, Some("en_US.UTF-8"))), BoxGlyphTier::Unicode);
305 assert_eq!(
306 box_glyph_tier_for(&env(Some("xterm-256color"), Some("Apple_Terminal"), Some("en_US.UTF-8"))),
307 BoxGlyphTier::Unicode
308 );
309 }
310
311 #[test]
312 fn opt_out_flags_use_canonical_flag_semantics() {
313 let base = env(Some("xterm-256color"), Some("WezTerm"), Some("en_US.UTF-8"));
314 assert_eq!(box_glyph_tier_for(&base), BoxGlyphTier::RichUnicode);
315
316 let no_unicode = TerminalEnv { no_unicode: Some("1".to_owned()), ..base.clone() };
317 assert_eq!(box_glyph_tier_for(&no_unicode), BoxGlyphTier::Ascii);
318
319 let no_rich = TerminalEnv {
320 no_rich_unicode: Some("1".to_owned()),
321 ..base.clone()
322 };
323 assert_eq!(box_glyph_tier_for(&no_rich), BoxGlyphTier::Unicode);
324 }
325
326 #[test]
327 fn falsy_opt_out_values_do_not_disable_unicode() {
328 for value in ["0", "false", "off", "no", ""] {
329 let disabled = TerminalEnv {
330 no_unicode: Some(value.to_owned()),
331 no_rich_unicode: Some(value.to_owned()),
332 ..env(Some("xterm-256color"), Some("WezTerm"), Some("en_US.UTF-8"))
333 };
334 assert_eq!(
335 box_glyph_tier_for(&disabled),
336 BoxGlyphTier::RichUnicode,
337 "VTCODE_NO_UNICODE={value:?} must not disable Unicode"
338 );
339 }
340 }
341
342 #[test]
343 fn tier_supports_unicode_matches_the_ladder() {
344 assert!(!BoxGlyphTier::Ascii.supports_unicode());
345 assert!(BoxGlyphTier::Unicode.supports_unicode());
346 assert!(BoxGlyphTier::RichUnicode.supports_unicode());
347 }
348}