Skip to content

read_char: Handle non-tty terminals explicitly#124

Merged
mitsuhiko merged 1 commit intoconsole-rs:masterfrom
deadalusai:master--read-char-handle-non-tty
Jan 14, 2023
Merged

read_char: Handle non-tty terminals explicitly#124
mitsuhiko merged 1 commit intoconsole-rs:masterfrom
deadalusai:master--read-char-handle-non-tty

Conversation

@deadalusai
Copy link
Copy Markdown
Contributor

@deadalusai deadalusai commented May 7, 2022

Key::Unknown is produced only when:

The two places in the code which explicitly handled Key::Unknown were treating it as a proxy for an "unattended terminal" check:

console/src/term.rs

Lines 258 to 263 in b3ecb7d

Key::Unknown => {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"Not a terminal",
))
}

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.

I found this issue when pressing the Ctrl key while using the read_key function, which causes it to return Err(Not a terminal) under Windows (but works fine on Linux). In this case, I was in the process of pressing Ctrl + C in order to terminate the program.
It looks like this issue also occurred previously for the Shift and Alt keys under Windows - rather than extend the Keys enum further to support the Ctrl key I think the proposed fix is a little more future proof (though you may like to add support for VK_CONTROL for the sake of completeness anyway).

`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.
@deadalusai
Copy link
Copy Markdown
Contributor Author

Related PR on dialoguer: console-rs/dialoguer#192

@ejpcmac
Copy link
Copy Markdown

ejpcmac commented Aug 23, 2022

Pressing AltGr also triggers this behaviour on Windows, which can be more preblematic to enter special characters.

benesch pushed a commit to benesch/console that referenced this pull request Dec 4, 2022
@mitsuhiko mitsuhiko merged commit ac6f2e3 into console-rs:master Jan 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants