From 44cdad61e0484b42477c0ddf9b1cee21bc01aaf1 Mon Sep 17 00:00:00 2001 From: Kevin Larke Date: Sun, 8 Feb 2015 08:54:53 -0800 Subject: [PATCH] cmKeyboard.h/c : Added cmIsKeyWaiting(). --- cmKeyboard.c | 34 ++++++++++++++++++++++++++++++++++ cmKeyboard.h | 29 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/cmKeyboard.c b/cmKeyboard.c index f5b20d6..b065ec3 100644 --- a/cmKeyboard.c +++ b/cmKeyboard.c @@ -233,3 +233,37 @@ void testKb2() reset_keypress(); } + + +// Based on: // From: http://www.flipcode.com/archives/_kbhit_for_Linux.shtml + +int cmIsKeyWaiting() +{ + static const int STDIN = 0; + static bool initialized = false; + struct timeval timeout; + fd_set rdset; + + if (! initialized) + { + // Use termios to turn off line buffering + struct termios term; + tcgetattr(STDIN, &term); + term.c_lflag &= ~ICANON; + tcsetattr(STDIN, TCSANOW, &term); + setbuf(stdin, NULL); + initialized = true; + } + + + FD_ZERO(&rdset); + FD_SET(STDIN, &rdset); + timeout.tv_sec = 0; + timeout.tv_usec = 0; + + // time out immediately if STDIN is not ready. + return select(STDIN + 1, &rdset, NULL, NULL, &timeout); + +} + + diff --git a/cmKeyboard.h b/cmKeyboard.h index 6d30826..cc2db66 100644 --- a/cmKeyboard.h +++ b/cmKeyboard.h @@ -34,4 +34,33 @@ typedef struct // Set 'p' to NULL if the value of the key is not required. void cmKeyPress( cmKbRecd* p ); + +// Return non-zero if a key is waiting to be read otherwise return 0. +// Use getchar() to pick up the key. +// +// Example: +// while( 1 ) +// { +// if( cmIsKeyWaiting() == 0 ) +// usleep(20000); +// else +// { +// char c = getchar(); +// switch(c) +// { +// .... +// } +// } +// +// } +// +// TODO: Note that this function turns off line-buffering on stdin. +// It should be changed to a three function sequence. +// bool org_state = cmSetStdinLineBuffering(false); +// .... +// cmIsKeyWaiting() +// .... +// cmSetStdinLineBuffering(org_state) +int cmIsKeyWaiting(); + #endif