diff --git a/examples/hello.rs b/examples/hello.rs index 096c7c8a2..ae9b11821 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -5,15 +5,15 @@ use failure::Error; use termwiz::caps::Capabilities; use termwiz::cell::AttributeChange; use termwiz::color::AnsiColor; +use termwiz::input::{InputEvent, KeyCode, KeyEvent}; use termwiz::surface::{Change, Position, Surface}; use termwiz::terminal::buffered::BufferedTerminal; -use termwiz::terminal::{new_terminal, Terminal}; +use termwiz::terminal::{new_terminal, Blocking, Terminal}; fn main() -> Result<(), Error> { let caps = Capabilities::new_from_env()?; - let mut terminal = new_terminal(caps)?; - terminal.set_raw_mode()?; + let terminal = new_terminal(caps)?; let mut buf = BufferedTerminal::new(terminal)?; @@ -36,5 +36,27 @@ fn main() -> Result<(), Error> { buf.flush()?; + buf.terminal().set_raw_mode()?; + loop { + match buf.terminal().poll_input(Blocking::Yes) { + Ok(Some(input)) => match input { + InputEvent::Key(KeyEvent { + key: KeyCode::Char('q'), + .. + }) => { + break; + } + _ => { + print!("{:?}\r\n", input); + } + }, + Ok(None) => {} + Err(e) => { + print!("{:?}\r\n", e); + break; + } + } + } + Ok(()) } diff --git a/src/input.rs b/src/input.rs index 6e88ce767..a869b6596 100644 --- a/src/input.rs +++ b/src/input.rs @@ -176,185 +176,211 @@ mod windows { mods } - - fn decode_key_record(event: &KEY_EVENT_RECORD, callback: &mut F) { - // TODO: do we want downs instead of ups? - if event.bKeyDown == 0 { - return; - } - - let key_code = match std::char::from_u32(*unsafe { event.uChar.UnicodeChar() } as u32) { - Some(unicode) if unicode != '\x00' => KeyCode::Char(unicode), - _ => match event.wVirtualKeyCode as i32 { - winuser::VK_CANCEL => KeyCode::Cancel, - winuser::VK_BACK => KeyCode::Backspace, - winuser::VK_TAB => KeyCode::Tab, - winuser::VK_CLEAR => KeyCode::Clear, - winuser::VK_RETURN => KeyCode::Enter, - winuser::VK_SHIFT => KeyCode::Shift, - winuser::VK_CONTROL => KeyCode::Control, - winuser::VK_MENU => KeyCode::Menu, - winuser::VK_PAUSE => KeyCode::Pause, - winuser::VK_CAPITAL => KeyCode::CapsLock, - winuser::VK_ESCAPE => KeyCode::Escape, - winuser::VK_PRIOR => KeyCode::PageUp, - winuser::VK_NEXT => KeyCode::PageDown, - winuser::VK_END => KeyCode::End, - winuser::VK_HOME => KeyCode::Home, - winuser::VK_LEFT => KeyCode::LeftArrow, - winuser::VK_RIGHT => KeyCode::RightArrow, - winuser::VK_UP => KeyCode::UpArrow, - winuser::VK_DOWN => KeyCode::DownArrow, - winuser::VK_SELECT => KeyCode::Select, - winuser::VK_PRINT => KeyCode::Print, - winuser::VK_EXECUTE => KeyCode::Execute, - winuser::VK_SNAPSHOT => KeyCode::PrintScreen, - winuser::VK_INSERT => KeyCode::Insert, - winuser::VK_DELETE => KeyCode::Delete, - winuser::VK_HELP => KeyCode::Help, - winuser::VK_LWIN => KeyCode::LeftWindows, - winuser::VK_RWIN => KeyCode::RightWindows, - winuser::VK_APPS => KeyCode::Applications, - winuser::VK_SLEEP => KeyCode::Sleep, - winuser::VK_NUMPAD0 => KeyCode::Numpad0, - winuser::VK_NUMPAD1 => KeyCode::Numpad1, - winuser::VK_NUMPAD2 => KeyCode::Numpad2, - winuser::VK_NUMPAD3 => KeyCode::Numpad3, - winuser::VK_NUMPAD4 => KeyCode::Numpad4, - winuser::VK_NUMPAD5 => KeyCode::Numpad5, - winuser::VK_NUMPAD6 => KeyCode::Numpad6, - winuser::VK_NUMPAD7 => KeyCode::Numpad7, - winuser::VK_NUMPAD8 => KeyCode::Numpad8, - winuser::VK_NUMPAD9 => KeyCode::Numpad9, - winuser::VK_MULTIPLY => KeyCode::Multiply, - winuser::VK_ADD => KeyCode::Add, - winuser::VK_SEPARATOR => KeyCode::Separator, - winuser::VK_SUBTRACT => KeyCode::Subtract, - winuser::VK_DECIMAL => KeyCode::Decimal, - winuser::VK_DIVIDE => KeyCode::Divide, - winuser::VK_F1 => KeyCode::Function(1), - winuser::VK_F2 => KeyCode::Function(2), - winuser::VK_F3 => KeyCode::Function(3), - winuser::VK_F4 => KeyCode::Function(4), - winuser::VK_F5 => KeyCode::Function(5), - winuser::VK_F6 => KeyCode::Function(6), - winuser::VK_F7 => KeyCode::Function(7), - winuser::VK_F8 => KeyCode::Function(8), - winuser::VK_F9 => KeyCode::Function(9), - winuser::VK_F10 => KeyCode::Function(10), - winuser::VK_F11 => KeyCode::Function(11), - winuser::VK_F12 => KeyCode::Function(12), - winuser::VK_F13 => KeyCode::Function(13), - winuser::VK_F14 => KeyCode::Function(14), - winuser::VK_F15 => KeyCode::Function(15), - winuser::VK_F16 => KeyCode::Function(16), - winuser::VK_F17 => KeyCode::Function(17), - winuser::VK_F18 => KeyCode::Function(18), - winuser::VK_F19 => KeyCode::Function(19), - winuser::VK_F20 => KeyCode::Function(20), - winuser::VK_F21 => KeyCode::Function(21), - winuser::VK_F22 => KeyCode::Function(22), - winuser::VK_F23 => KeyCode::Function(23), - winuser::VK_F24 => KeyCode::Function(24), - winuser::VK_NUMLOCK => KeyCode::NumLock, - winuser::VK_SCROLL => KeyCode::ScrollLock, - winuser::VK_LSHIFT => KeyCode::LeftShift, - winuser::VK_RSHIFT => KeyCode::RightShift, - winuser::VK_LCONTROL => KeyCode::LeftControl, - winuser::VK_RCONTROL => KeyCode::RightControl, - winuser::VK_LMENU => KeyCode::LeftMenu, - winuser::VK_RMENU => KeyCode::RightMenu, - winuser::VK_BROWSER_BACK => KeyCode::BrowserBack, - winuser::VK_BROWSER_FORWARD => KeyCode::BrowserForward, - winuser::VK_BROWSER_REFRESH => KeyCode::BrowserRefresh, - winuser::VK_BROWSER_STOP => KeyCode::BrowserStop, - winuser::VK_BROWSER_SEARCH => KeyCode::BrowserSearch, - winuser::VK_BROWSER_FAVORITES => KeyCode::BrowserFavorites, - winuser::VK_BROWSER_HOME => KeyCode::BrowserHome, - winuser::VK_VOLUME_MUTE => KeyCode::VolumeMute, - winuser::VK_VOLUME_DOWN => KeyCode::VolumeDown, - winuser::VK_VOLUME_UP => KeyCode::VolumeUp, - winuser::VK_MEDIA_NEXT_TRACK => KeyCode::MediaNextTrack, - winuser::VK_MEDIA_PREV_TRACK => KeyCode::MediaPrevTrack, - winuser::VK_MEDIA_STOP => KeyCode::MediaStop, - winuser::VK_MEDIA_PLAY_PAUSE => KeyCode::MediaPlayPause, - _ => return, - }, - }; - let modifiers = modifiers_from_ctrl_key_state(event.dwControlKeyState); - - let input_event = InputEvent::Key(KeyEvent { - key: key_code, - modifiers, - }); - for _ in 0..event.wRepeatCount { - callback(input_event.clone()); - } - } - - fn decode_mouse_record(event: &MOUSE_EVENT_RECORD, callback: &mut F) { - use winapi::um::wincon::*; - let mut buttons = MouseButtons::NONE; - - if (event.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) != 0 { - buttons |= MouseButtons::LEFT; - } - if (event.dwButtonState & RIGHTMOST_BUTTON_PRESSED) != 0 { - buttons |= MouseButtons::RIGHT; - } - if (event.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED) != 0 { - buttons |= MouseButtons::MIDDLE; - } - - let modifiers = modifiers_from_ctrl_key_state(event.dwControlKeyState); - - if (event.dwEventFlags & MOUSE_WHEELED) != 0 { - buttons |= MouseButtons::VERT_WHEEL; - if (event.dwButtonState >> 8) != 0 { - buttons |= MouseButtons::WHEEL_POSITIVE; + impl InputParser { + fn decode_key_record( + &self, + event: &KEY_EVENT_RECORD, + callback: &mut F, + ) { + // TODO: do we want downs instead of ups? + if event.bKeyDown == 0 { + return; } - } else if (event.dwEventFlags & MOUSE_HWHEELED) != 0 { - buttons |= MouseButtons::HORZ_WHEEL; - if (event.dwButtonState >> 8) != 0 { - buttons |= MouseButtons::WHEEL_POSITIVE; - } - } - let mouse = InputEvent::Mouse(MouseEvent { - x: event.dwMousePosition.X as u16, - y: event.dwMousePosition.Y as u16, - mouse_buttons: buttons, - modifiers, - }); + let key_code = match std::char::from_u32(*unsafe { event.uChar.UnicodeChar() } as u32) { + Some(unicode) if unicode > '\x00' => { + let mut buf = [0u8; 4]; - if (event.dwEventFlags & DOUBLE_CLICK) != 0 { - callback(mouse.clone()); + match self.key_map.lookup(unicode.encode_utf8(&mut buf)) { + Found::Exact(_, event) | Found::Ambiguous(_, event) => { + callback(event.clone()); + return; + } + _ => KeyCode::Char(unicode), + } + } + _ => match event.wVirtualKeyCode as i32 { + winuser::VK_CANCEL => KeyCode::Cancel, + winuser::VK_BACK => KeyCode::Backspace, + winuser::VK_TAB => KeyCode::Tab, + winuser::VK_CLEAR => KeyCode::Clear, + winuser::VK_RETURN => KeyCode::Enter, + winuser::VK_SHIFT => KeyCode::Shift, + winuser::VK_CONTROL => KeyCode::Control, + winuser::VK_MENU => KeyCode::Menu, + winuser::VK_PAUSE => KeyCode::Pause, + winuser::VK_CAPITAL => KeyCode::CapsLock, + winuser::VK_ESCAPE => KeyCode::Escape, + winuser::VK_PRIOR => KeyCode::PageUp, + winuser::VK_NEXT => KeyCode::PageDown, + winuser::VK_END => KeyCode::End, + winuser::VK_HOME => KeyCode::Home, + winuser::VK_LEFT => KeyCode::LeftArrow, + winuser::VK_RIGHT => KeyCode::RightArrow, + winuser::VK_UP => KeyCode::UpArrow, + winuser::VK_DOWN => KeyCode::DownArrow, + winuser::VK_SELECT => KeyCode::Select, + winuser::VK_PRINT => KeyCode::Print, + winuser::VK_EXECUTE => KeyCode::Execute, + winuser::VK_SNAPSHOT => KeyCode::PrintScreen, + winuser::VK_INSERT => KeyCode::Insert, + winuser::VK_DELETE => KeyCode::Delete, + winuser::VK_HELP => KeyCode::Help, + winuser::VK_LWIN => KeyCode::LeftWindows, + winuser::VK_RWIN => KeyCode::RightWindows, + winuser::VK_APPS => KeyCode::Applications, + winuser::VK_SLEEP => KeyCode::Sleep, + winuser::VK_NUMPAD0 => KeyCode::Numpad0, + winuser::VK_NUMPAD1 => KeyCode::Numpad1, + winuser::VK_NUMPAD2 => KeyCode::Numpad2, + winuser::VK_NUMPAD3 => KeyCode::Numpad3, + winuser::VK_NUMPAD4 => KeyCode::Numpad4, + winuser::VK_NUMPAD5 => KeyCode::Numpad5, + winuser::VK_NUMPAD6 => KeyCode::Numpad6, + winuser::VK_NUMPAD7 => KeyCode::Numpad7, + winuser::VK_NUMPAD8 => KeyCode::Numpad8, + winuser::VK_NUMPAD9 => KeyCode::Numpad9, + winuser::VK_MULTIPLY => KeyCode::Multiply, + winuser::VK_ADD => KeyCode::Add, + winuser::VK_SEPARATOR => KeyCode::Separator, + winuser::VK_SUBTRACT => KeyCode::Subtract, + winuser::VK_DECIMAL => KeyCode::Decimal, + winuser::VK_DIVIDE => KeyCode::Divide, + winuser::VK_F1 => KeyCode::Function(1), + winuser::VK_F2 => KeyCode::Function(2), + winuser::VK_F3 => KeyCode::Function(3), + winuser::VK_F4 => KeyCode::Function(4), + winuser::VK_F5 => KeyCode::Function(5), + winuser::VK_F6 => KeyCode::Function(6), + winuser::VK_F7 => KeyCode::Function(7), + winuser::VK_F8 => KeyCode::Function(8), + winuser::VK_F9 => KeyCode::Function(9), + winuser::VK_F10 => KeyCode::Function(10), + winuser::VK_F11 => KeyCode::Function(11), + winuser::VK_F12 => KeyCode::Function(12), + winuser::VK_F13 => KeyCode::Function(13), + winuser::VK_F14 => KeyCode::Function(14), + winuser::VK_F15 => KeyCode::Function(15), + winuser::VK_F16 => KeyCode::Function(16), + winuser::VK_F17 => KeyCode::Function(17), + winuser::VK_F18 => KeyCode::Function(18), + winuser::VK_F19 => KeyCode::Function(19), + winuser::VK_F20 => KeyCode::Function(20), + winuser::VK_F21 => KeyCode::Function(21), + winuser::VK_F22 => KeyCode::Function(22), + winuser::VK_F23 => KeyCode::Function(23), + winuser::VK_F24 => KeyCode::Function(24), + winuser::VK_NUMLOCK => KeyCode::NumLock, + winuser::VK_SCROLL => KeyCode::ScrollLock, + winuser::VK_LSHIFT => KeyCode::LeftShift, + winuser::VK_RSHIFT => KeyCode::RightShift, + winuser::VK_LCONTROL => KeyCode::LeftControl, + winuser::VK_RCONTROL => KeyCode::RightControl, + winuser::VK_LMENU => KeyCode::LeftMenu, + winuser::VK_RMENU => KeyCode::RightMenu, + winuser::VK_BROWSER_BACK => KeyCode::BrowserBack, + winuser::VK_BROWSER_FORWARD => KeyCode::BrowserForward, + winuser::VK_BROWSER_REFRESH => KeyCode::BrowserRefresh, + winuser::VK_BROWSER_STOP => KeyCode::BrowserStop, + winuser::VK_BROWSER_SEARCH => KeyCode::BrowserSearch, + winuser::VK_BROWSER_FAVORITES => KeyCode::BrowserFavorites, + winuser::VK_BROWSER_HOME => KeyCode::BrowserHome, + winuser::VK_VOLUME_MUTE => KeyCode::VolumeMute, + winuser::VK_VOLUME_DOWN => KeyCode::VolumeDown, + winuser::VK_VOLUME_UP => KeyCode::VolumeUp, + winuser::VK_MEDIA_NEXT_TRACK => KeyCode::MediaNextTrack, + winuser::VK_MEDIA_PREV_TRACK => KeyCode::MediaPrevTrack, + winuser::VK_MEDIA_STOP => KeyCode::MediaStop, + winuser::VK_MEDIA_PLAY_PAUSE => KeyCode::MediaPlayPause, + _ => return, + }, + }; + let modifiers = modifiers_from_ctrl_key_state(event.dwControlKeyState); + + let input_event = InputEvent::Key(KeyEvent { + key: key_code, + modifiers, + }); + for _ in 0..event.wRepeatCount { + callback(input_event.clone()); + } } - callback(mouse); - } - - fn decode_resize_record( - event: &WINDOW_BUFFER_SIZE_RECORD, - callback: &mut F, - ) { - callback(InputEvent::Resized { - rows: event.dwSize.Y as u16, - cols: event.dwSize.X as u16, - }); - } - - pub(crate) fn decode_input_records( - records: &[INPUT_RECORD], - callback: &mut F, - ) { - for record in records { - match record.EventType { - KEY_EVENT => decode_key_record(unsafe { record.Event.KeyEvent() }, callback), - MOUSE_EVENT => decode_mouse_record(unsafe { record.Event.MouseEvent() }, callback), - WINDOW_BUFFER_SIZE_EVENT => { - decode_resize_record(unsafe { record.Event.WindowBufferSizeEvent() }, callback) + + fn decode_mouse_record( + &self, + event: &MOUSE_EVENT_RECORD, + callback: &mut F, + ) { + use winapi::um::wincon::*; + let mut buttons = MouseButtons::NONE; + + if (event.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) != 0 { + buttons |= MouseButtons::LEFT; + } + if (event.dwButtonState & RIGHTMOST_BUTTON_PRESSED) != 0 { + buttons |= MouseButtons::RIGHT; + } + if (event.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED) != 0 { + buttons |= MouseButtons::MIDDLE; + } + + let modifiers = modifiers_from_ctrl_key_state(event.dwControlKeyState); + + if (event.dwEventFlags & MOUSE_WHEELED) != 0 { + buttons |= MouseButtons::VERT_WHEEL; + if (event.dwButtonState >> 8) != 0 { + buttons |= MouseButtons::WHEEL_POSITIVE; + } + } else if (event.dwEventFlags & MOUSE_HWHEELED) != 0 { + buttons |= MouseButtons::HORZ_WHEEL; + if (event.dwButtonState >> 8) != 0 { + buttons |= MouseButtons::WHEEL_POSITIVE; + } + } + + let mouse = InputEvent::Mouse(MouseEvent { + x: event.dwMousePosition.X as u16, + y: event.dwMousePosition.Y as u16, + mouse_buttons: buttons, + modifiers, + }); + + if (event.dwEventFlags & DOUBLE_CLICK) != 0 { + callback(mouse.clone()); + } + callback(mouse); + } + + fn decode_resize_record( + &self, + event: &WINDOW_BUFFER_SIZE_RECORD, + callback: &mut F, + ) { + callback(InputEvent::Resized { + rows: event.dwSize.Y as u16, + cols: event.dwSize.X as u16, + }); + } + + pub fn decode_input_records( + &self, + records: &[INPUT_RECORD], + callback: &mut F, + ) { + for record in records { + match record.EventType { + KEY_EVENT => { + self.decode_key_record(unsafe { record.Event.KeyEvent() }, callback) + } + MOUSE_EVENT => { + self.decode_mouse_record(unsafe { record.Event.MouseEvent() }, callback) + } + WINDOW_BUFFER_SIZE_EVENT => self.decode_resize_record( + unsafe { record.Event.WindowBufferSizeEvent() }, + callback, + ), + _ => {} } - _ => {} } } } @@ -421,6 +447,26 @@ impl InputParser { modifiers: Modifiers::NONE, }), ); + + // TODO: check compat; this happens to match up to iterm in my setup + for (suffix, modifiers) in &[ + (";2", Modifiers::SHIFT), + (";3", Modifiers::ALT), + (";4", Modifiers::ALT | Modifiers::SHIFT), + (";5", Modifiers::CTRL), + (";6", Modifiers::CTRL | Modifiers::SHIFT), + (";7", Modifiers::CTRL | Modifiers::ALT), + (";8", Modifiers::CTRL | Modifiers::ALT | Modifiers::SHIFT), + ] { + let key = format!("\x1b[1{}{}", suffix, *dir as char); + map.insert( + key, + InputEvent::Key(KeyEvent { + key: keycode.clone(), + modifiers: modifiers.clone(), + }), + ); + } } // Function keys 1-4 with no modifiers encoded using SS3 @@ -481,24 +527,53 @@ impl InputParser { ); } - let del = [0x7f]; map.insert( - &del, + &[0x7f], InputEvent::Key(KeyEvent { key: KeyCode::Delete, modifiers: Modifiers::NONE, }), ); - let esc = [0x1b]; map.insert( - &esc, + &[0x8], + InputEvent::Key(KeyEvent { + key: KeyCode::Backspace, + modifiers: Modifiers::NONE, + }), + ); + + map.insert( + &[0x1b], InputEvent::Key(KeyEvent { key: KeyCode::Escape, modifiers: Modifiers::NONE, }), ); + map.insert( + &[b'\t'], + InputEvent::Key(KeyEvent { + key: KeyCode::Tab, + modifiers: Modifiers::NONE, + }), + ); + + map.insert( + &[b'\r'], + InputEvent::Key(KeyEvent { + key: KeyCode::Enter, + modifiers: Modifiers::NONE, + }), + ); + map.insert( + &[b'\n'], + InputEvent::Key(KeyEvent { + key: KeyCode::Enter, + modifiers: Modifiers::NONE, + }), + ); + map } @@ -618,15 +693,6 @@ impl InputParser { result } - #[cfg(windows)] - pub fn decode_input_records( - &mut self, - records: &[INPUT_RECORD], - callback: &mut F, - ) { - windows::decode_input_records(records, callback); - } - #[cfg(windows)] pub fn decode_input_records_as_vec(&mut self, records: &[INPUT_RECORD]) -> Vec { let mut result = Vec::new(); diff --git a/src/render/terminfo.rs b/src/render/terminfo.rs index 2a8811d4f..b507e0602 100644 --- a/src/render/terminfo.rs +++ b/src/render/terminfo.rs @@ -494,12 +494,13 @@ mod test { use escape::parser::Parser; use escape::{Action, Esc, EscCode}; use failure::Error; + use input::InputEvent; use libc::winsize; use std::io::{Error as IoError, ErrorKind, Read, Result as IoResult, Write}; use std::mem; use terminal::unix::{Purge, SetAttributeWhen, UnixTty}; use terminal::ScreenSize; - use terminal::{cast, Terminal}; + use terminal::{cast, Blocking, Terminal}; use terminfo; use termios::Termios; @@ -648,6 +649,10 @@ mod test { fn flush(&mut self) -> Result<(), Error> { Ok(()) } + + fn poll_input(&mut self, _blocking: Blocking) -> Result, Error> { + bail!("not implemented"); + } } #[test] diff --git a/src/terminal/mod.rs b/src/terminal/mod.rs index 9056cf450..ed3bdc705 100644 --- a/src/terminal/mod.rs +++ b/src/terminal/mod.rs @@ -6,6 +6,7 @@ use caps::Capabilities; use failure::Error; +use input::InputEvent; use num::{self, NumCast}; use std::fmt::Display; use surface::Change; @@ -42,6 +43,12 @@ pub struct ScreenSize { pub ypixel: usize, } +#[derive(Debug, Clone, Copy)] +pub enum Blocking { + No, + Yes, +} + /// `Terminal` abstracts over some basic terminal capabilities. /// If the `set_raw_mode` or `set_cooked_mode` functions are used in /// any combination, the implementation is required to restore the @@ -65,11 +72,17 @@ pub trait Terminal { /// Flush any buffered output fn flush(&mut self) -> Result<(), Error>; - /* - /// Sets the terminal to cooked mode, which is essentially the opposite - /// to raw mode: input and output processing are enabled. - fn set_cooked_mode(&mut self) -> Result<(), Error>; -*/ + /// Check for a parsed input event. + /// `blocking` indicates the behavior in the case that no input is + /// immediately available. If blocking == `Blocking::Yes` then + /// `poll_input` will not return until an event is available. + /// If blocking == `Blocking:No` then `poll_input` will return + /// immediately with a value of `Ok(None)`. + /// + /// The possible values returned as `InputEvent`s depend on the + /// mode of the terminal. Most modes are not returned unless + /// the terminal is set to raw mode. + fn poll_input(&mut self, blocking: Blocking) -> Result, Error>; } /// `SystemTerminal` is a concrete implementation of `Terminal`. diff --git a/src/terminal/unix.rs b/src/terminal/unix.rs index 985162629..d0da906ba 100644 --- a/src/terminal/unix.rs +++ b/src/terminal/unix.rs @@ -1,6 +1,7 @@ use failure::Error; use istty::IsTty; use libc::{self, winsize}; +use std::collections::VecDeque; use std::fs::OpenOptions; use std::io::{stdin, stdout, Error as IOError, ErrorKind, Read, Write}; use std::mem; @@ -12,9 +13,10 @@ use termios::{ }; use caps::Capabilities; +use input::{InputEvent, InputParser}; use render::terminfo::TerminfoRenderer; use surface::Change; -use terminal::{cast, ScreenSize, Terminal}; +use terminal::{cast, Blocking, ScreenSize, Terminal}; const BUF_SIZE: usize = 128; @@ -89,6 +91,17 @@ impl TtyReadHandle { fn new(fd: Fd) -> Self { Self { fd } } + + fn set_blocking(&mut self, blocking: Blocking) -> Result<(), Error> { + let value: libc::c_int = match blocking { + Blocking::Yes => 0, + Blocking::No => 1, + }; + if unsafe { libc::ioctl(*self.fd, libc::FIONBIO, &value as *const _) } != 0 { + bail!("failed to ioctl(FIONBIO): {:?}", IOError::last_os_error()); + } + Ok(()) + } } impl Read for TtyReadHandle { @@ -206,6 +219,8 @@ pub struct UnixTerminal { write: TtyWriteHandle, saved_termios: Termios, renderer: TerminfoRenderer, + input_parser: InputParser, + input_queue: Option>, } impl UnixTerminal { @@ -227,12 +242,16 @@ impl UnixTerminal { let mut write = TtyWriteHandle::new(Fd::new(write)?); let saved_termios = write.get_termios()?; let renderer = TerminfoRenderer::new(caps); + let input_parser = InputParser::new(); + let input_queue = None; Ok(UnixTerminal { read, write, saved_termios, renderer, + input_parser, + input_queue, }) } @@ -284,6 +303,37 @@ impl Terminal for UnixTerminal { .flush() .map_err(|e| format_err!("flush failed: {}", e)) } + + fn poll_input(&mut self, blocking: Blocking) -> Result, Error> { + if let Some(ref mut queue) = self.input_queue { + if let Some(event) = queue.pop_front() { + return Ok(Some(event)); + } + } + + self.read.set_blocking(blocking)?; + + let mut buf = [0u8; 64]; + match self.read.read(&mut buf) { + Ok(n) => { + // A little bit of a dance with moving the queue out of self + // to appease the borrow checker. We'll need to be sure to + // move it back before we return! + let mut queue = match self.input_queue.take() { + Some(queue) => queue, + None => VecDeque::new(), + }; + self.input_parser + .parse(&buf[0..n], |evt| queue.push_back(evt), n == buf.len()); + let result = queue.pop_front(); + // Move the queue back into self before we leave this scope + self.input_queue = Some(queue); + Ok(result) + } + Err(ref e) if e.kind() == ErrorKind::WouldBlock => Ok(None), + Err(e) => Err(format_err!("failed to read input {}", e)), + } + } } impl Drop for UnixTerminal { diff --git a/src/terminal/windows.rs b/src/terminal/windows.rs index 7ee0dd512..70503638d 100644 --- a/src/terminal/windows.rs +++ b/src/terminal/windows.rs @@ -1,5 +1,6 @@ use failure::Error; use istty::IsTty; +use std::collections::VecDeque; use std::fs::OpenOptions; use std::io::{stdin, stdout, Error as IOError, Read, Result as IOResult, Write}; use std::os::windows::io::{AsRawHandle, RawHandle}; @@ -13,20 +14,23 @@ use winapi::um::wincon::{ SetConsoleCursorPosition, SetConsoleScreenBufferSize, SetConsoleTextAttribute, SetConsoleWindowInfo, CONSOLE_SCREEN_BUFFER_INFO, COORD, DISABLE_NEWLINE_AUTO_RETURN, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT, ENABLE_VIRTUAL_TERMINAL_INPUT, - ENABLE_VIRTUAL_TERMINAL_PROCESSING, SMALL_RECT, + ENABLE_VIRTUAL_TERMINAL_PROCESSING, INPUT_RECORD, SMALL_RECT, }; use winapi::um::winnt::DUPLICATE_SAME_ACCESS; use caps::Capabilities; +use input::{InputEvent, InputParser}; use render::windows::WindowsConsoleRenderer; use surface::Change; -use terminal::{cast, ScreenSize, Terminal}; +use terminal::{cast, Blocking, ScreenSize, Terminal}; const BUF_SIZE: usize = 128; pub trait ConsoleInputHandle { fn set_input_mode(&mut self, mode: u32) -> Result<(), Error>; fn get_input_mode(&mut self) -> Result; + fn get_number_of_input_events(&mut self) -> Result; + fn read_console_input(&mut self, num_events: usize) -> Result, Error>; } pub trait ConsoleOutputHandle { @@ -106,6 +110,40 @@ impl ConsoleInputHandle for InputHandle { } Ok(mode) } + + fn get_number_of_input_events(&mut self) -> Result { + let mut num = 0; + if unsafe { consoleapi::GetNumberOfConsoleInputEvents(self.handle, &mut num) } == 0 { + bail!( + "GetNumberOfConsoleInputEvents failed: {}", + IOError::last_os_error() + ); + } + Ok(num as usize) + } + + fn read_console_input(&mut self, num_events: usize) -> Result, Error> { + let mut res = Vec::with_capacity(num_events); + let empty_record: INPUT_RECORD = unsafe { mem::zeroed() }; + res.resize(num_events, empty_record); + + let mut num = 0; + + if unsafe { + consoleapi::ReadConsoleInputW( + self.handle, + res.as_mut_ptr(), + num_events as u32, + &mut num, + ) + } == 0 + { + bail!("ReadConsoleInput failed: {}", IOError::last_os_error()); + } + + unsafe { res.set_len(num as usize) }; + Ok(res) + } } struct OutputHandle { @@ -269,6 +307,8 @@ pub struct WindowsTerminal { saved_input_mode: u32, saved_output_mode: u32, renderer: WindowsConsoleRenderer, + input_parser: InputParser, + input_queue: Option>, } impl Drop for WindowsTerminal { @@ -310,6 +350,7 @@ impl WindowsTerminal { let saved_input_mode = input_handle.get_input_mode()?; let saved_output_mode = output_handle.get_output_mode()?; let renderer = WindowsConsoleRenderer::new(caps); + let input_parser = InputParser::new(); Ok(Self { input_handle, @@ -317,6 +358,8 @@ impl WindowsTerminal { saved_input_mode, saved_output_mode, renderer, + input_parser, + input_queue: None, }) } @@ -397,4 +440,35 @@ impl Terminal for WindowsTerminal { .flush() .map_err(|e| format_err!("flush failed: {}", e)) } + + fn poll_input(&mut self, blocking: Blocking) -> Result, Error> { + if let Some(ref mut queue) = self.input_queue { + if let Some(event) = queue.pop_front() { + return Ok(Some(event)); + } + } + + let pending = match (self.input_handle.get_number_of_input_events()?, blocking) { + (0, Blocking::No) => return Ok(None), + (0, Blocking::Yes) => 1, + (pending, _) => pending, + }; + + let records = self.input_handle.read_console_input(pending)?; + + // A little bit of a dance with moving the queue out of self + // to appease the borrow checker. We'll need to be sure to + // move it back before we return! + let mut queue = match self.input_queue.take() { + Some(queue) => queue, + None => VecDeque::new(), + }; + + self.input_parser + .decode_input_records(&records, &mut |evt| queue.push_back(evt)); + + let result = queue.pop_front(); + self.input_queue = Some(queue); + Ok(result) + } }