Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

read only one byte in read_single_key unless we find an escape sequence #62

Merged
merged 2 commits into from
May 8, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion src/unix_term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,61 @@ pub fn read_single_key() -> io::Result<Key> {
termios::cfmakeraw(&mut termios);
termios::tcsetattr(fd, termios::TCSADRAIN, &termios)?;
let rv = unsafe {
let read = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 20);
let read = libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 1);
if read < 0 {
Err(io::Error::last_os_error())
} else if buf[0] == b'\x1b' {
// read 19 more bytes if the first byte was the ESC code
let read = libc::read(fd, buf[1..].as_mut_ptr() as *mut libc::c_void, 19);
if read < 0 {
Err(io::Error::last_os_error())
} else if buf[1] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"read interrupted",
))
} else {
Ok(key_from_escape_codes(&buf[..(read+1) as usize]))
}
} else if buf[0] & 224u8 == 192u8 {
// a two byte unicode character
let read = libc::read(fd, buf[1..].as_mut_ptr() as *mut libc::c_void, 1);
if read < 0 {
Err(io::Error::last_os_error())
} else if buf[1] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"read interrupted",
))
} else {
Ok(key_from_escape_codes(&buf[..2 as usize]))
}
} else if buf[0] & 240u8 == 224u8 {
// a three byte unicode character
let read = libc::read(fd, buf[1..].as_mut_ptr() as *mut libc::c_void, 2);
if read < 0 {
Err(io::Error::last_os_error())
} else if buf[1] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"read interrupted",
))
} else {
Ok(key_from_escape_codes(&buf[..3 as usize]))
}
} else if buf[0] & 248u8 == 240u8 {
// a four byte unicode character
let read = libc::read(fd, buf[1..].as_mut_ptr() as *mut libc::c_void, 3);
if read < 0 {
Err(io::Error::last_os_error())
} else if buf[1] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"read interrupted",
))
} else {
Ok(key_from_escape_codes(&buf[..4 as usize]))
}
} else if buf[0] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
Expand Down