-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputHandler.cpp
More file actions
82 lines (75 loc) · 1.81 KB
/
InputHandler.cpp
File metadata and controls
82 lines (75 loc) · 1.81 KB
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
#include "InputHandler.h"
int getch (void)
{
int ch;
struct termios oldt, newt;
if( -1 == tcgetattr(STDIN_FILENO, &oldt)) {
printf("tcgetattr error: %s\n",strerror(errno));
exit(1);
}
memcpy(&newt, &oldt, sizeof(newt));
newt.c_lflag &= ~( ECHO | ICANON | ECHOE | ECHOK |
ECHONL | ECHOPRT | ECHOKE | ICRNL);
if( -1 == tcsetattr(STDIN_FILENO, TCSANOW, &newt)) {
printf("tcgetattr error: %s\n",strerror(errno));
exit(1);
}
ch = getchar();
if( -1 == tcsetattr(STDIN_FILENO, TCSANOW, &oldt)) {
printf("tcgetattr error: %s\n",strerror(errno));
exit(1);
}
return ch;
}
enum KeyTable {
KeyEnter = 10,
KeyTab = 9,
KeyBackSpace = 8
};
string InputHandler::Getline()
{
history.push_back(string());
auto line = history.rbegin();
while(1)
{
int ch = getch();
if(ch == EOF)
return "";
if(ch == KeyEnter) {
putchar('\n');
return *line;
}
if(ch == '\033') {
getch();
ch = getch();
if(ch == 'A') // up
{
if(line+1 != history.rend()) {
putchar('\r');
int length = line->size();
line++;
printf("$ %-*s",length,line->c_str());
for( size_t i = 0 ; i < length - line->size() + 2 ; ++i ) {
putchar('\b');
}
}
}
if(ch == 'B') // down
putchar('B');
if(ch == 'C') // right
putchar('C');
if(ch == 'D') // left
putchar('D');
continue;
}
if(ch != KeyTab && ch != KeyBackSpace) {
putchar(ch);
*line += ch;
}
if(ch == KeyBackSpace) {
printf("\b\033[K");
if(line->size() > 0)
line->pop_back();
}
}
}