Replace ukbhit by kbd_enter_pressed, not requiring tcgetattr:

Note that it behaves differently now
* it looks for Enter key only, not any key
* it "eats" the input, no need for (void)getchar() after it
* it works the same no matter the value of ICANON
* the mingw version has been adapted to act the similarly

This should fix its usage on Android where tcgetattr always returns -1
This commit is contained in:
Philippe Teuwen 2019-07-11 13:01:34 +02:00
commit 844d732297
27 changed files with 90 additions and 126 deletions

View file

@ -26,38 +26,46 @@ uint8_t g_debugMode = 0;
#define MAX_BIN_BREAK_LENGTH (3072+384+1)
#ifndef _WIN32
#include <termios.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
int ukbhit(void) {
int cnt = 0;
int error;
static struct termios Otty, Ntty;
if (tcgetattr(STDIN_FILENO, &Otty) == -1) return -1;
Ntty = Otty;
Ntty.c_iflag = 0x0000; // input mode
Ntty.c_oflag = 0x0000; // output mode
Ntty.c_lflag &= ~ICANON; // control mode = raw
Ntty.c_cc[VMIN] = 1; // return if at least 1 character is in the queue
Ntty.c_cc[VTIME] = 0; // no timeout. Wait forever
if (0 == (error = tcsetattr(STDIN_FILENO, TCSANOW, &Ntty))) { // set new attributes
error += ioctl(STDIN_FILENO, FIONREAD, &cnt); // get number of characters available
error += tcsetattr(STDIN_FILENO, TCSANOW, &Otty); // reset attributes
int kbd_enter_pressed(void) {
int flags;
if ((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0) {
PrintAndLogEx(ERR, "fcntl failed in kbd_enter_pressed");
return -1;
}
return (error == 0 ? cnt : -1);
//non-blocking
flags |= O_NONBLOCK;
if (fcntl(STDIN_FILENO, F_SETFL, flags) < 0) {
PrintAndLogEx(ERR, "fcntl failed in kbd_enter_pressed");
return -1;
}
int c;
int ret = 0;
do { //get all available chars
c = getchar();
ret |= c == '\n';
} while (c != EOF);
//blocking
flags &= ~O_NONBLOCK;
if (fcntl(STDIN_FILENO, F_SETFL, flags) < 0) {
PrintAndLogEx(ERR, "fcntl failed in kbd_enter_pressed");
return -1;
}
return ret;
}
#else
#include <conio.h>
int ukbhit(void) {
return kbhit();
int kbd_enter_pressed(void) {
int ret = 0;
while(kbhit())
{
ret |= getch() == '\r';
}
return ret;
}
#endif