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
use crossterm::terminal;
use std::env;
use std::io::{self, Write};
use std::time::{Duration, Instant};
use thiserror::Error;
#[cfg(target_os = "windows")]
use winapi::um::wincon;

/// Terminal
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Terminal {
    Screen,
    Tmux,
    XtermCompatible,
    Windows,
    VSCode,
    Emacs,
}

/// 16bit RGB color
#[derive(Copy, Clone, Debug)]
pub struct Rgb {
    pub r: u16,
    pub g: u16,
    pub b: u16,
}

/// Background theme
#[derive(Copy, Clone, Debug)]
pub enum Theme {
    Light,
    Dark,
}

/// Error
#[derive(Error, Debug)]
pub enum Error {
    #[error("terminal error")]
    Terminal {
        #[from]
        source: crossterm::ErrorKind,
    },
    #[error("io error")]
    Io {
        #[from]
        source: std::io::Error,
    },
    #[error("parse error")]
    Parse(String),
    #[error("unsupported")]
    Unsupported,
}

/// get detected termnial
#[cfg(not(target_os = "windows"))]
pub fn terminal() -> Terminal {
    if let Ok(term_program) = env::var("TERM_PROGRAM") {
        if term_program == "vscode" {
            return Terminal::VSCode;
        }
    }

    if env::var("INSIDE_EMACS").is_ok() {
        return Terminal::Emacs;
    }

    if env::var("TMUX").is_ok() {
        Terminal::Tmux
    } else {
        let is_screen = if let Ok(term) = env::var("TERM") {
            term.starts_with("screen")
        } else {
            false
        };
        if is_screen {
            Terminal::Screen
        } else {
            Terminal::XtermCompatible
        }
    }
}

/// get detected termnial
#[cfg(target_os = "windows")]
pub fn terminal() -> Terminal {
    if let Ok(term_program) = env::var("TERM_PROGRAM") {
        if term_program == "vscode" {
            return Terminal::VSCode;
        }
    }

    if env::var("INSIDE_EMACS").is_ok() {
        return Terminal::Emacs;
    }

    // Windows Terminal is Xterm-compatible
    // https://github.com/microsoft/terminal/issues/3718
    if env::var("WT_SESSION").is_ok() {
        Terminal::XtermCompatible
    } else {
        Terminal::Windows
    }
}

/// get background color by `RGB`
#[cfg(not(target_os = "windows"))]
pub fn rgb(timeout: Duration) -> Result<Rgb, Error> {
    let term = terminal();
    match term {
        Terminal::VSCode => Err(Error::Unsupported),
        Terminal::Emacs => Err(Error::Unsupported),
        _ => from_xterm(term, timeout),
    }
}

/// get background color by `RGB`
#[cfg(target_os = "windows")]
pub fn rgb(timeout: Duration) -> Result<Rgb, Error> {
    let term = terminal();
    match term {
        Terminal::VSCode => Err(Error::Unsupported),
        Terminal::Emacs => Err(Error::Unsupported),
        Terminal::XtermCompatible => from_xterm(term, timeout),
        _ => from_winapi(),
    }
}

/// get background color by `RGB`
#[cfg(not(target_os = "windows"))]
pub fn latency(timeout: Duration) -> Result<Duration, Error> {
    let term = terminal();
    match term {
        Terminal::VSCode => Ok(Duration::from_millis(0)),
        Terminal::Emacs => Ok(Duration::from_millis(0)),
        _ => xterm_latency(timeout),
    }
}

/// get background color by `RGB`
#[cfg(target_os = "windows")]
pub fn latency(timeout: Duration) -> Result<Duration, Error> {
    let term = terminal();
    match term {
        Terminal::VSCode => Ok(Duration::from_millis(0)),
        Terminal::Emacs => Ok(Duration::from_millis(0)),
        Terminal::XtermCompatible => xterm_latency(timeout),
        _ => Ok(Duration::from_millis(0)),
    }
}

/// get background color by `Theme`
pub fn theme(timeout: Duration) -> Result<Theme, Error> {
    let rgb = rgb(timeout)?;

    // ITU-R BT.601
    let y = rgb.r as f64 * 0.299 + rgb.g as f64 * 0.587 + rgb.b as f64 * 0.114;

    if y > 32768.0 {
        Ok(Theme::Light)
    } else {
        Ok(Theme::Dark)
    }
}

fn from_xterm(term: Terminal, timeout: Duration) -> Result<Rgb, Error> {
    // Query by XTerm control sequence
    let query = if term == Terminal::Tmux {
        "\x1bPtmux;\x1b\x1b]11;?\x07\x1b\\\x03"
    } else if term == Terminal::Screen {
        "\x1bP\x1b]11;?\x07\x1b\\\x03"
    } else {
        "\x1b]11;?\x1b\\"
    };

    let mut stderr = io::stderr();
    terminal::enable_raw_mode()?;
    write!(stderr, "{}", query)?;
    stderr.flush()?;

    let buffer = async_std::task::block_on(async_std::io::timeout(timeout, async {
        use async_std::io::ReadExt;
        let mut buffer = Vec::new();
        let mut stdin = async_std::io::stdin();
        let mut buf = [0; 1];
        let mut start = false;
        loop {
            let _ = stdin.read_exact(&mut buf).await?;
            // response terminated by BEL(0x7)
            if start && (buf[0] == 0x7) {
                break;
            }
            // response terminated by ST(0x1b 0x5c)
            if start && (buf[0] == 0x1b) {
                // consume last 0x5c
                let _ = stdin.read_exact(&mut buf).await?;
                debug_assert_eq!(buf[0], 0x5c);
                break;
            }
            if start {
                buffer.push(buf[0]);
            }
            if buf[0] == b':' {
                start = true;
            }
        }
        Ok(buffer)
    }));

    terminal::disable_raw_mode()?;

    // Should return by error after disable_raw_mode
    let buffer = buffer?;

    let s = String::from_utf8_lossy(&buffer);
    let (r, g, b) = decode_x11_color(&*s)?;
    Ok(Rgb { r, g, b })
}

fn xterm_latency(timeout: Duration) -> Result<Duration, Error> {
    // Query by XTerm control sequence
    let query = "\x1b[5n";

    let mut stderr = io::stderr();
    terminal::enable_raw_mode()?;
    write!(stderr, "{}", query)?;
    stderr.flush()?;

    let start = Instant::now();

    let _ = async_std::task::block_on(async_std::io::timeout(timeout, async {
        use async_std::io::ReadExt;
        let mut stdin = async_std::io::stdin();
        let mut buf = [0; 1];
        loop {
            let _ = stdin.read_exact(&mut buf).await?;
            // response terminated by 'n'
            if buf[0] == b'n' {
                break;
            }
        }
        Ok(())
    }));

    let end = start.elapsed();

    terminal::disable_raw_mode()?;

    Ok(end)
}

fn decode_x11_color(s: &str) -> Result<(u16, u16, u16), Error> {
    fn decode_hex(s: &str) -> Result<u16, Error> {
        let len = s.len() as u32;
        let mut ret = u16::from_str_radix(s, 16).map_err(|_| Error::Parse(String::from(s)))?;
        ret = ret << ((4 - len) * 4);
        Ok(ret)
    }

    let rgb: Vec<_> = s.split("/").collect();

    let r = rgb
        .get(0)
        .ok_or_else(|| Error::Parse(String::from(s.clone())))?;
    let g = rgb
        .get(1)
        .ok_or_else(|| Error::Parse(String::from(s.clone())))?;
    let b = rgb
        .get(2)
        .ok_or_else(|| Error::Parse(String::from(s.clone())))?;
    let r = decode_hex(r)?;
    let g = decode_hex(g)?;
    let b = decode_hex(b)?;

    Ok((r, g, b))
}

#[cfg(target_os = "windows")]
fn from_winapi() -> Result<Rgb, Error> {
    let info = unsafe {
        let handle = winapi::um::processenv::GetStdHandle(winapi::um::winbase::STD_OUTPUT_HANDLE);
        let mut info: wincon::CONSOLE_SCREEN_BUFFER_INFO = Default::default();
        wincon::GetConsoleScreenBufferInfo(handle, &mut info);
        info
    };

    let r = (wincon::BACKGROUND_RED & info.wAttributes) != 0;
    let g = (wincon::BACKGROUND_GREEN & info.wAttributes) != 0;
    let b = (wincon::BACKGROUND_BLUE & info.wAttributes) != 0;
    let i = (wincon::BACKGROUND_INTENSITY & info.wAttributes) != 0;

    let r: u8 = r as u8;
    let g: u8 = g as u8;
    let b: u8 = b as u8;
    let i: u8 = i as u8;

    let (r, g, b) = match (r, g, b, i) {
        (0, 0, 0, 0) => (0, 0, 0),
        (1, 0, 0, 0) => (128, 0, 0),
        (0, 1, 0, 0) => (0, 128, 0),
        (1, 1, 0, 0) => (128, 128, 0),
        (0, 0, 1, 0) => (0, 0, 128),
        (1, 0, 1, 0) => (128, 0, 128),
        (0, 1, 1, 0) => (0, 128, 128),
        (1, 1, 1, 0) => (192, 192, 192),
        (0, 0, 0, 1) => (128, 128, 128),
        (1, 0, 0, 1) => (255, 0, 0),
        (0, 1, 0, 1) => (0, 255, 0),
        (1, 1, 0, 1) => (255, 255, 0),
        (0, 0, 1, 1) => (0, 0, 255),
        (1, 0, 1, 1) => (255, 0, 255),
        (0, 1, 1, 1) => (0, 255, 255),
        (1, 1, 1, 1) => (255, 255, 255),
        _ => unreachable!(),
    };

    Ok(Rgb {
        r: r * 256,
        g: g * 256,
        b: b * 256,
    })
}

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

    #[test]
    fn test_decode_x11_color() {
        let s = "0000/0000/0000";
        assert_eq!((0, 0, 0), decode_x11_color(s).unwrap());

        let s = "1111/2222/3333";
        assert_eq!((0x1111, 0x2222, 0x3333), decode_x11_color(s).unwrap());

        let s = "111/222/333";
        assert_eq!((0x1110, 0x2220, 0x3330), decode_x11_color(s).unwrap());

        let s = "11/22/33";
        assert_eq!((0x1100, 0x2200, 0x3300), decode_x11_color(s).unwrap());

        let s = "1/2/3";
        assert_eq!((0x1000, 0x2000, 0x3000), decode_x11_color(s).unwrap());
    }
}