-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReadKeyboard.cpp
129 lines (89 loc) · 2.06 KB
/
ReadKeyboard.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/// ReadKeyboard.cpp
#if defined(__unix__) || defined(__linux__) || \
defined(BSD) || (defined (__APPLE__) && defined (__MACH__)) || defined(__bsdi__) || \
defined(__minix) || defined(__CYGWIN__) || defined(__FreeBSD__)
#define POSIX 1
#endif
#ifdef POSIX
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/select.h>
#include "ReadKeyboard.h"
namespace utilities {
static struct termios oldt, newt;
int ReadKeyboard::Get()
{
key = 0;
struct timeval tv;
fd_set read_fd;
// Waiting time
tv.tv_sec = 0;
tv.tv_usec = 0;
// Initialize read_fd
FD_ZERO(&read_fd);
// Make select() ask if input is ready
FD_SET(STDIN_FILENO, &read_fd);
int r = select(STDIN_FILENO + 1, &read_fd, NULL /*No writes*/, NULL /*No exceptions*/, &tv);
if(r < 0)
return r; // An error occured
/* read_fd now holds a bit map of files that are
* readable. We test the entry for stdin */
if(FD_ISSET(STDIN_FILENO, &read_fd))
key = getchar();
// If no key has been pressed, key = 0
return key;
}
int ReadKeyboard::Getch()
{
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
void ReadKeyboard::NonBlocking()
{
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
blocking = false;
}
void ReadKeyboard::Blocking()
{
oldt.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
blocking = true;
}
} // utilities
#elif defined _WIN32
#include <conio.h>
#include "ReadKeyboard.h"
namespace utilities {
int ReadKeyboard::Get()
{
if(blocking || _kbhit())
{
return _getch();
}
return 0; // no key pressed
}
int ReadKeyboard::Getch()
{
return _getch();
}
void ReadKeyboard::NonBlocking()
{
blocking = false;
}
void ReadKeyboard::Blocking()
{
blocking = true;
}
} // utilities
#endif // _WIN32