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
use Handle;
#[cfg(windows)]
use winapi;
#[cfg(windows)]
use kernel32;

// Based on https://github.com/dtolnay/isatty.

/// The type of terminal, if any, for a standard stream handle.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TerminalMode {
    /// Not connected to a terminal or console.
    Redir,
    /// A terminal emulator.
    Term,
    /// A Cygwin or MSYS2 terminal.
    #[cfg(windows)]
    Cygwin,
    /// A legacy console buffer.
    #[cfg(windows)]
    Console,
    /// A Windows 10 console buffer that supports Console Virtual
    /// Terminal Sequences.
    #[cfg(windows)]
    Win10,
}

impl TerminalMode {
    #[cfg(not(windows))]
    pub(super) fn from_handle(handle: Handle) -> TerminalMode {
        match unsafe { ::libc::isatty(handle.fd()) } {
            0 => TerminalMode::Redir,
            _ => TerminalMode::Term,
        }
    }

    #[cfg(windows)]
    pub(super) fn from_handle(handle: Handle) -> TerminalMode {
        match handle.console_mode() {
            ConsoleMode::Legacy => return TerminalMode::Console,
            ConsoleMode::Win10 => return TerminalMode::Win10,
            ConsoleMode::None => (),
        }

        let hndl = unsafe { kernel32::GetStdHandle(handle as winapi::DWORD) };
        match msys_cygwin(hndl) {
            Some(true) => TerminalMode::Cygwin,
            _ => TerminalMode::Redir,
        }
    }
}

// Assumes console_mode(hndl) has already returned None.
#[cfg(windows)]
fn msys_cygwin(hndl: winapi::HANDLE) -> Option<bool> {
    use std::os::windows::ffi::OsStringExt;

    let sz = ::std::mem::size_of::<winapi::FILE_NAME_INFO>();
    let mut raw_info = vec![0u8; sz + winapi::MAX_PATH];

    let ok = unsafe {
        kernel32::GetFileInformationByHandleEx(
            hndl,
            winapi::FILE_INFO_BY_HANDLE_CLASS(2),
            raw_info.as_mut_ptr() as winapi::LPVOID,
            raw_info.len() as winapi::DWORD,
        )
    };
    if ok == 0 {
        return None;
    }

    let file_info =
        unsafe { *(raw_info[0..sz].as_ptr() as *const winapi::FILE_NAME_INFO) };
    let name = &raw_info[sz..sz + file_info.FileNameLength as usize];
    let name = unsafe {
        ::std::slice::from_raw_parts(
            name.as_ptr() as *const winapi::WCHAR,
            name.len() / 2,
        )
    };
    let name = ::std::ffi::OsString::from_wide(name);
    let name = name.to_string_lossy();

    if name.starts_with("\\cygwin-") || name.starts_with("\\msys-") {
        Some(true)
    } else {
        Some(false)
    }
}

/// The type of console buffer, if any, for a standard stream handle.
#[cfg(windows)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConsoleMode {
    /// No console buffer.
    None,
    /// A legacy console buffer.
    Legacy,
    /// A Windows 10 console buffer that supports Console Virtual
    /// Terminal Sequences.
    Win10,
}

#[cfg(windows)]
impl Default for ConsoleMode {
    fn default() -> ConsoleMode {
        ConsoleMode::None
    }
}

// winapi-rs omits these
#[cfg(windows)]
const ENABLE_VIRTUAL_TERMINAL_PROCESSING: winapi::DWORD = 0x0004;
#[cfg(windows)]
const ENABLE_VIRTUAL_TERMINAL_INPUT: winapi::DWORD = 0x0200;

#[cfg(windows)]
impl ConsoleMode {
    pub(super) fn from_out_handle(hndl: winapi::HANDLE) -> ConsoleMode {
        if hndl == winapi::INVALID_HANDLE_VALUE {
            return ConsoleMode::None;
        }
        unsafe {
            let mut mode: winapi::DWORD = 0;
            if 0 == kernel32::GetConsoleMode(hndl, &mut mode) {
                return ConsoleMode::None;
            }
            if (mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0 {
                return ConsoleMode::Win10;
            }
            mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
            if 0 == kernel32::SetConsoleMode(hndl, mode) {
                ConsoleMode::Legacy
            } else {
                ConsoleMode::Win10
            }
        }
    }

    pub(super) fn from_in_handle(hndl: winapi::HANDLE) -> ConsoleMode {
        if hndl == winapi::INVALID_HANDLE_VALUE {
            return ConsoleMode::None;
        }
        unsafe {
            let mut mode: winapi::DWORD = 0;
            if 0 == kernel32::GetConsoleMode(hndl, &mut mode) {
                return ConsoleMode::None;
            }
            if (mode & ENABLE_VIRTUAL_TERMINAL_INPUT) != 0 {
                return ConsoleMode::Win10;
            }
            let newmode = mode | ENABLE_VIRTUAL_TERMINAL_INPUT;
            if 0 == kernel32::SetConsoleMode(hndl, newmode) {
                kernel32::SetConsoleMode(hndl, mode);
                ConsoleMode::Legacy
            } else {
                kernel32::SetConsoleMode(hndl, mode);
                ConsoleMode::Win10
            }
        }
    }
}