Skip to main content

fire_cli_rs/
input.rs

1#[inline(always)]
2pub fn check_input() -> bool {
3    #[cfg(unix)]
4    {
5        let mut fds: libc::fd_set = unsafe { std::mem::zeroed() };
6        unsafe { libc::FD_ZERO(&mut fds) };
7        unsafe { libc::FD_SET(0, &mut fds) };
8        let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
9        let ret = unsafe { libc::select(1, &mut fds, std::ptr::null_mut(), std::ptr::null_mut(), &mut tv) };
10        if ret > 0 {
11            let mut buf = [0u8; 32];
12            let n = unsafe { libc::read(0, buf.as_mut_ptr() as *mut _, 32) };
13            if n > 0 {
14                if buf[0] == 3 {
15                        return true;
16                }
17                if buf[0] == 27 {
18                    if n == 1 {
19                        return true;
20                    }
21                    if n >= 3 && buf[1] == b'[' {
22                        return false; 
23                   }
24                    if n >= 2 && buf[1] != b'[' {
25                        return true;
26                }
27            }
28        }
29   }
30}
31    #[cfg(windows)]
32    {
33        use std::io;
34        use std::os::windows::io::AsRawHandle;
35        let handle = io::stdin().as_raw_handle();
36        let mut num: u32 = 0;
37        if unsafe { winapi::um::consoleapi::GetNumberOfConsoleInputEvents(handle as _, &mut num) } != 0 && num > 0 {
38            let mut rec: winapi::um::wincon::INPUT_RECORD = unsafe { std::mem::zeroed() };
39            let mut read = 0;
40            if unsafe { winapi::um::consoleapi::ReadConsoleInputW(handle as _, &mut rec, 1, &mut read) } != 0 {
41                if rec.EventType == 1 {
42                    let key = unsafe { rec.Event.KeyEvent() };
43                    if key.bKeyDown != 0 {
44                        let ch = unsafe { *key.uChar.UnicodeChar() };
45                        return ch == 27 || ch == 3;
46                    }
47                }
48            }
49        }
50    }
51    false
52}