From 497ea85b6ae9c6be4bfd90ea9ad4e353bcdaaf14 Mon Sep 17 00:00:00 2001 From: Ben Fox Date: Sat, 7 May 2022 14:39:39 +1200 Subject: [PATCH] read_char: Handle non-tty terminals explicitly `Key::Unknown` is produced only when: - A keycode is not recognized by the `key_from_key_code` function under Windows - `read_key` is invoked on a non-tty terminal The two places in the code which explicitly handled `Key::Unknown` were treating it as a proxy for an "unattended terminal" check. Since this is only 100% valid to do when running under *nix I've replaced these handlers with an explicit `!self.is_tty` check instead, which is a common pattern in the Term code. `Key::Unknown` is now assumed to represent an unprintable / control key and skipped when being evaluated. --- src/term.rs | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/term.rs b/src/term.rs index 350a7894..888dfd75 100644 --- a/src/term.rs +++ b/src/term.rs @@ -245,8 +245,15 @@ impl Term { /// Read a single character from the terminal. /// /// This does not echo the character and blocks until a single character - /// is entered. + /// or complete key chord is entered. If the terminal is not user attended + /// the return value will be an error. pub fn read_char(&self) -> io::Result { + if !self.is_tty { + return Err(io::Error::new( + io::ErrorKind::NotConnected, + "Not a terminal", + )); + } loop { match self.read_key()? { Key::Char(c) => { @@ -255,12 +262,6 @@ impl Term { Key::Enter => { return Ok('\n'); } - Key::Unknown => { - return Err(io::Error::new( - io::ErrorKind::NotConnected, - "Not a terminal", - )) - } _ => {} } } @@ -324,12 +325,6 @@ impl Term { self.write_line("")?; break; } - Key::Unknown => { - return Err(io::Error::new( - io::ErrorKind::NotConnected, - "Not a terminal", - )) - } _ => (), } }