opentui_rust 0.2.1

High-performance terminal UI rendering engine with alpha blending and diffed buffers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Terminal capability detection.

use crate::unicode::WidthMethod;
use std::env;

/// Color support level.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColorSupport {
    /// No color support.
    #[default]
    None,
    /// 16 colors (basic ANSI).
    Basic,
    /// 256 colors.
    Extended,
    /// True color (16 million colors).
    TrueColor,
}

/// Detected terminal capabilities.
#[derive(Clone, Debug)]
pub struct Capabilities {
    /// Color support level.
    pub color: ColorSupport,
    /// Terminal supports Unicode.
    pub unicode: bool,
    /// Preferred width calculation method.
    pub width_method: WidthMethod,
    /// Terminal supports hyperlinks (OSC 8).
    pub hyperlinks: bool,
    /// Terminal supports synchronized output.
    pub sync_output: bool,
    /// Terminal supports mouse tracking.
    pub mouse: bool,
    /// Terminal supports focus events.
    pub focus: bool,
    /// Terminal supports bracketed paste.
    pub bracketed_paste: bool,
    /// Kitty keyboard protocol.
    pub kitty_keyboard: bool,
    /// Kitty graphics protocol.
    pub kitty_graphics: bool,
    /// SGR pixel mouse mode.
    pub sgr_pixels: bool,
    /// Terminal supports dynamic color scheme updates.
    pub color_scheme_updates: bool,
    /// Terminal supports explicit width reporting.
    pub explicit_width: bool,
    /// Terminal supports scaled text.
    pub scaled_text: bool,
    /// Sixel graphics support.
    pub sixel: bool,
    /// Terminal supports explicit cursor positioning (DECCRA).
    pub explicit_cursor_positioning: bool,
    /// Terminal name if known.
    pub term_name: Option<String>,
}

impl Default for Capabilities {
    /// Returns conservative defaults suitable for unknown/basic terminals.
    ///
    /// This ensures that if capability detection fails or is skipped, the
    /// terminal won't receive escape sequences it can't handle. Use
    /// [`Capabilities::detect()`] to probe the actual terminal capabilities.
    fn default() -> Self {
        Self {
            // Conservative: assume basic color until detected
            color: ColorSupport::Basic,
            // Conservative: don't assume Unicode support
            unicode: false,
            width_method: WidthMethod::default(),
            // Conservative: disable advanced features by default
            hyperlinks: false,
            sync_output: false,
            mouse: false,
            focus: false,
            bracketed_paste: false,
            kitty_keyboard: false,
            kitty_graphics: false,
            sgr_pixels: false,
            color_scheme_updates: false,
            explicit_width: false,
            scaled_text: false,
            sixel: false,
            // Conservative: DECCRA is widely supported but not universal
            explicit_cursor_positioning: false,
            term_name: None,
        }
    }
}

impl Capabilities {
    /// Detect terminal capabilities from environment.
    ///
    /// Probes environment variables (TERM, COLORTERM, TERM_PROGRAM, etc.)
    /// to determine terminal capabilities. Starts from conservative defaults
    /// and enables features only when detection confirms support.
    #[must_use]
    pub fn detect() -> Self {
        let term = env::var("TERM").unwrap_or_default();
        let colorterm = env::var("COLORTERM").unwrap_or_default();
        let term_program = env::var("TERM_PROGRAM").unwrap_or_default();
        let kitty_window_id = env::var("KITTY_WINDOW_ID").ok();

        let color = Self::detect_color(&term, &colorterm);
        let unicode = Self::detect_unicode();
        let kitty_present = kitty_window_id.is_some();
        let hyperlinks = Self::detect_hyperlinks(&term, &term_program, kitty_present);
        let sync_output = Self::detect_sync(&term, &term_program, kitty_present);
        let kitty_keyboard = kitty_present;
        let kitty_graphics = kitty_present;

        // Detect basic terminal features based on TERM value
        // These features are widely supported in any xterm-compatible terminal
        let is_xterm_compatible = Self::is_xterm_compatible(&term);

        Self {
            color,
            unicode,
            width_method: WidthMethod::default(),
            hyperlinks,
            sync_output,
            // Mouse/focus/bracketed-paste require xterm compatibility
            mouse: is_xterm_compatible,
            focus: is_xterm_compatible,
            bracketed_paste: is_xterm_compatible,
            kitty_keyboard,
            kitty_graphics,
            sgr_pixels: false,
            color_scheme_updates: false,
            explicit_width: false,
            scaled_text: false,
            sixel: term.contains("sixel"),
            // DECCRA (explicit cursor positioning) is widely supported in modern terminals
            explicit_cursor_positioning: is_xterm_compatible,
            term_name: if term.is_empty() { None } else { Some(term) },
        }
    }

    /// Check if the terminal is xterm-compatible (supports basic features).
    ///
    /// Returns true for terminals that support common features like mouse tracking,
    /// focus events, and bracketed paste mode.
    fn is_xterm_compatible(term: &str) -> bool {
        if term.is_empty() {
            return false;
        }

        // Known compatible terminal types
        let compatible_prefixes = [
            "xterm", "screen", "tmux", "rxvt", "vt100", "vt102", "vt220", "linux",
        ];

        let compatible_names = [
            "alacritty",
            "kitty",
            "wezterm",
            "ghostty",
            "konsole",
            "gnome",
            "gnome-terminal",
            "mate-terminal",
            "xfce4-terminal",
        ];

        let term_lower = term.to_lowercase();

        // Check prefixes (e.g., "xterm-256color", "screen-256color")
        if compatible_prefixes
            .iter()
            .any(|p| term_lower.starts_with(p))
        {
            return true;
        }

        // Check exact matches or contains for known terminals
        compatible_names.iter().any(|n| term_lower.contains(n))
    }

    /// Apply a best-effort capability response (from query output).
    pub fn apply_query_response(&mut self, response: &str) {
        if response.contains("[?u") {
            self.kitty_keyboard = true;
        }

        if let Some((width, height)) = parse_pixel_resolution(response) {
            if width > 0 && height > 0 {
                self.explicit_width = true;
                self.sgr_pixels = true;
            }
        }

        let lower = response.to_lowercase();
        if lower.contains("kitty") {
            self.kitty_graphics = true;
            self.kitty_keyboard = true;
        } else if lower.contains("wezterm") || lower.contains("alacritty") {
            self.sync_output = true;
        }
    }

    fn detect_color(term: &str, colorterm: &str) -> ColorSupport {
        // Check for explicit true color support
        if colorterm.eq_ignore_ascii_case("truecolor") || colorterm.eq_ignore_ascii_case("24bit") {
            return ColorSupport::TrueColor;
        }

        // Check term for true color indicators
        if term.contains("256color") || term.contains("24bit") || term.contains("truecolor") {
            return ColorSupport::TrueColor;
        }

        // Known true color terminals
        let truecolor_terms = [
            "xterm-256color",
            "screen-256color",
            "tmux-256color",
            "alacritty",
            "kitty",
            "wezterm",
            "ghostty",
        ];

        if truecolor_terms.iter().any(|t| term.contains(t)) {
            return ColorSupport::TrueColor;
        }

        // 256 color
        if term.contains("256") {
            return ColorSupport::Extended;
        }

        // Basic color
        if term.starts_with("xterm") || term.starts_with("screen") || term.starts_with("vt100") {
            return ColorSupport::Basic;
        }

        // Assume basic color if TERM is set
        if !term.is_empty() {
            return ColorSupport::Basic;
        }

        ColorSupport::None
    }

    fn detect_unicode() -> bool {
        // Check locale for UTF-8
        let lang = env::var("LANG").unwrap_or_default();
        let lc_all = env::var("LC_ALL").unwrap_or_default();
        let lc_ctype = env::var("LC_CTYPE").unwrap_or_default();

        lang.to_lowercase().contains("utf")
            || lc_all.to_lowercase().contains("utf")
            || lc_ctype.to_lowercase().contains("utf")
    }

    /// Detect hyperlink support from multiple signals.
    ///
    /// Considers:
    /// - `TERM_PROGRAM`: WezTerm, Alacritty, kitty, ghostty, iTerm.app, Apple_Terminal, Hyper
    /// - `TERM`: kitty, ghostty, wezterm, alacritty, xterm-kitty
    /// - `KITTY_WINDOW_ID` presence
    fn detect_hyperlinks(term: &str, term_program: &str, kitty_present: bool) -> bool {
        // KITTY_WINDOW_ID present -> kitty features supported
        if kitty_present {
            return true;
        }

        // Known terminals with hyperlink support via TERM_PROGRAM
        let supported_programs = [
            "iTerm.app",
            "Apple_Terminal",
            "WezTerm",
            "Hyper",
            "Alacritty",
            "kitty",
            "ghostty",
        ];
        if supported_programs
            .iter()
            .any(|t| term_program.eq_ignore_ascii_case(t) || term_program.contains(t))
        {
            return true;
        }

        // Known terminals via TERM value
        let term_lower = term.to_lowercase();
        let supported_terms = ["kitty", "ghostty", "wezterm", "alacritty"];
        supported_terms.iter().any(|t| term_lower.contains(t))
    }

    /// Detect synchronized output support from multiple signals.
    ///
    /// Considers:
    /// - `TERM_PROGRAM`: kitty, Alacritty, WezTerm, ghostty
    /// - `TERM`: kitty, ghostty, wezterm, alacritty
    /// - `KITTY_WINDOW_ID` presence
    fn detect_sync(term: &str, term_program: &str, kitty_present: bool) -> bool {
        // KITTY_WINDOW_ID present -> kitty features supported
        if kitty_present {
            return true;
        }

        // Terminals known to support synchronized output via TERM_PROGRAM
        let supported_programs = ["kitty", "Alacritty", "WezTerm", "ghostty"];
        if supported_programs
            .iter()
            .any(|t| term_program.eq_ignore_ascii_case(t) || term_program.contains(t))
        {
            return true;
        }

        // Known terminals via TERM value
        let term_lower = term.to_lowercase();
        let supported_terms = ["kitty", "ghostty", "wezterm", "alacritty"];
        supported_terms.iter().any(|t| term_lower.contains(t))
    }

    /// Check if true color is supported.
    #[must_use]
    pub fn has_true_color(&self) -> bool {
        self.color >= ColorSupport::TrueColor
    }

    /// Check if 256 colors are supported.
    #[must_use]
    pub fn has_256_colors(&self) -> bool {
        self.color >= ColorSupport::Extended
    }
}

fn parse_pixel_resolution(response: &str) -> Option<(u32, u32)> {
    let start = response.find("[4;")?;
    let payload = &response[start + 3..];
    let end = payload.find('t')?;
    let payload = &payload[..end];
    let mut parts = payload.split(';');
    let height = parts.next()?.parse::<u32>().ok()?;
    let width = parts.next()?.parse::<u32>().ok()?;
    Some((width, height))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_pixel_resolution() {
        let response = "\x1b[4;900;1440t";
        assert_eq!(parse_pixel_resolution(response), Some((1440, 900)));
    }

    #[test]
    fn test_apply_query_response_flags() {
        let mut caps = Capabilities {
            kitty_keyboard: false,
            explicit_width: false,
            sgr_pixels: false,
            ..Capabilities::default()
        };

        caps.apply_query_response("\x1b[?u");
        caps.apply_query_response("\x1b[4;900;1440t");

        assert!(caps.kitty_keyboard);
        assert!(caps.explicit_width);
        assert!(caps.sgr_pixels);
    }

    #[test]
    fn test_color_support_ordering() {
        assert!(ColorSupport::TrueColor > ColorSupport::Extended);
        assert!(ColorSupport::Extended > ColorSupport::Basic);
        assert!(ColorSupport::Basic > ColorSupport::None);
    }

    #[test]
    fn test_capabilities_default() {
        // Default should be conservative for unknown/basic terminals
        let caps = Capabilities::default();
        assert_eq!(
            caps.color,
            ColorSupport::Basic,
            "Default should assume basic color, not TrueColor"
        );
        assert!(!caps.unicode, "Default should not assume Unicode support");
        assert!(!caps.hyperlinks, "Default should disable hyperlinks");
        assert!(!caps.sync_output, "Default should disable sync output");
        assert!(!caps.mouse, "Default should disable mouse");
        assert!(!caps.focus, "Default should disable focus events");
        assert!(
            !caps.bracketed_paste,
            "Default should disable bracketed paste"
        );
        assert!(
            !caps.explicit_cursor_positioning,
            "Default should disable explicit cursor positioning"
        );
    }

    #[test]
    fn test_is_xterm_compatible() {
        // Compatible terminals
        assert!(Capabilities::is_xterm_compatible("xterm"));
        assert!(Capabilities::is_xterm_compatible("xterm-256color"));
        assert!(Capabilities::is_xterm_compatible("screen"));
        assert!(Capabilities::is_xterm_compatible("screen-256color"));
        assert!(Capabilities::is_xterm_compatible("tmux-256color"));
        assert!(Capabilities::is_xterm_compatible("rxvt-unicode"));
        assert!(Capabilities::is_xterm_compatible("linux"));
        assert!(Capabilities::is_xterm_compatible("alacritty"));
        assert!(Capabilities::is_xterm_compatible("kitty"));
        assert!(Capabilities::is_xterm_compatible("wezterm"));
        assert!(Capabilities::is_xterm_compatible("ghostty"));

        // Not compatible (empty or unknown)
        assert!(!Capabilities::is_xterm_compatible(""));
        assert!(!Capabilities::is_xterm_compatible("dumb"));
        assert!(!Capabilities::is_xterm_compatible("unknown"));
    }

    // === Hyperlink detection tests ===

    #[test]
    fn test_hyperlinks_via_term_program() {
        // WezTerm
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "WezTerm",
            false
        ));
        // Alacritty
        assert!(Capabilities::detect_hyperlinks(
            "alacritty",
            "Alacritty",
            false
        ));
        // kitty
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "kitty",
            false
        ));
        // ghostty
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "ghostty",
            false
        ));
        // iTerm
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "iTerm.app",
            false
        ));
        // Apple Terminal
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "Apple_Terminal",
            false
        ));
        // Hyper
        assert!(Capabilities::detect_hyperlinks(
            "xterm-256color",
            "Hyper",
            false
        ));
    }

    #[test]
    fn test_hyperlinks_via_term() {
        // kitty via TERM (common when TERM_PROGRAM is unset)
        assert!(Capabilities::detect_hyperlinks("xterm-kitty", "", false));
        assert!(Capabilities::detect_hyperlinks("kitty", "", false));
        // ghostty via TERM
        assert!(Capabilities::detect_hyperlinks("ghostty", "", false));
        // wezterm via TERM
        assert!(Capabilities::detect_hyperlinks("wezterm", "", false));
        // alacritty via TERM
        assert!(Capabilities::detect_hyperlinks("alacritty", "", false));
    }

    #[test]
    fn test_hyperlinks_via_kitty_window_id() {
        // KITTY_WINDOW_ID present should enable hyperlinks even with unknown term
        assert!(Capabilities::detect_hyperlinks("xterm-256color", "", true));
        assert!(Capabilities::detect_hyperlinks("linux", "", true));
    }

    #[test]
    fn test_hyperlinks_false_for_unknown() {
        // Unknown terminal with no special env vars
        assert!(!Capabilities::detect_hyperlinks(
            "xterm-256color",
            "",
            false
        ));
        assert!(!Capabilities::detect_hyperlinks(
            "screen-256color",
            "",
            false
        ));
        assert!(!Capabilities::detect_hyperlinks("linux", "", false));
        assert!(!Capabilities::detect_hyperlinks("vt100", "", false));
        // Empty values
        assert!(!Capabilities::detect_hyperlinks("", "", false));
    }

    // === Sync output detection tests ===

    #[test]
    fn test_sync_via_term_program() {
        // kitty
        assert!(Capabilities::detect_sync("xterm-256color", "kitty", false));
        // Alacritty
        assert!(Capabilities::detect_sync(
            "xterm-256color",
            "Alacritty",
            false
        ));
        // WezTerm
        assert!(Capabilities::detect_sync(
            "xterm-256color",
            "WezTerm",
            false
        ));
        // ghostty
        assert!(Capabilities::detect_sync(
            "xterm-256color",
            "ghostty",
            false
        ));
    }

    #[test]
    fn test_sync_via_term() {
        // kitty via TERM
        assert!(Capabilities::detect_sync("xterm-kitty", "", false));
        assert!(Capabilities::detect_sync("kitty", "", false));
        // ghostty via TERM
        assert!(Capabilities::detect_sync("ghostty", "", false));
        // wezterm via TERM
        assert!(Capabilities::detect_sync("wezterm", "", false));
        // alacritty via TERM
        assert!(Capabilities::detect_sync("alacritty", "", false));
    }

    #[test]
    fn test_sync_via_kitty_window_id() {
        // KITTY_WINDOW_ID present should enable sync even with unknown term
        assert!(Capabilities::detect_sync("xterm-256color", "", true));
        assert!(Capabilities::detect_sync("linux", "", true));
    }

    #[test]
    fn test_sync_false_for_unknown() {
        // Unknown terminal with no special env vars
        assert!(!Capabilities::detect_sync("xterm-256color", "", false));
        assert!(!Capabilities::detect_sync("screen-256color", "", false));
        assert!(!Capabilities::detect_sync("tmux-256color", "", false));
        assert!(!Capabilities::detect_sync("linux", "", false));
        // Note: iTerm and Apple_Terminal don't support sync output
        assert!(!Capabilities::detect_sync(
            "xterm-256color",
            "iTerm.app",
            false
        ));
        assert!(!Capabilities::detect_sync(
            "xterm-256color",
            "Apple_Terminal",
            false
        ));
    }

    #[test]
    fn test_case_insensitive_term_matching() {
        // TERM values should match case-insensitively
        assert!(Capabilities::detect_hyperlinks("KITTY", "", false));
        assert!(Capabilities::detect_hyperlinks("Kitty", "", false));
        assert!(Capabilities::detect_sync("ALACRITTY", "", false));
        assert!(Capabilities::detect_sync("Alacritty", "", false));
    }
}