-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrawmode.c
100 lines (95 loc) · 3.15 KB
/
rawmode.c
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
#include "headers.h"
void die(const char *s) {
perror(s);
exit(1);
}
struct termios orig_termios;
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
die("tcsetattr");
}
/**
* Enable row mode for the terminal
* The ECHO feature causes each key you type to be printed to the terminal, so you can see what you’re typing.
* Terminal attributes can be read into a termios struct by tcgetattr().
* After modifying them, you can then apply them to the terminal using tcsetattr().
* The TCSAFLUSH argument specifies when to apply the change: in this case, it waits for all pending output to be written to the terminal, and also discards any input that hasn’t been read.
* The c_lflag field is for “local flags”
*/
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) die("tcgetattr");
atexit(disableRawMode);
struct termios raw = orig_termios;
raw.c_lflag &= ~(ICANON | ECHO | ISIG);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}
/**
* stdout and stdin are buffered we disable buffering on that
* After entering in raw mode we read characters one by one
* Up arrow keys and down arrow keys are represented by 3 byte escape codes
* starting with ascii number 27 i.e. ESC key
* This way we interpret arrow keys
* Tabs are usually handled by the term, but here we are simulating tabs for the sake of simplicity
* Backspace move the cursor one control character to the left
* @return
*/
char* set_raw() {
char *inp = malloc(sizeof(char) * 1024);
char c;
setbuf(stdout, NULL);
enableRawMode();
// printf("Prompt>");
memset(inp, '\0', 1024);
int pt = 0;
while (read(STDIN_FILENO, &c, 1) == 1) {
if (iscntrl(c)) {
if(c == 3)
{
printf("\n");
break;
}
else if (c == 10)
{
printf("\n");
break;
}
else if(c == 26)
{
continue;
}
else if (c == 27) {
char buf[3];
buf[2] = 0;
if (read(STDIN_FILENO, buf, 2) == 2) { // length of escape code
// printf("\rarrow key: %s", buf);
}
} else if (c == 127) { // backspace
if (pt > 0) {
if (inp[pt-1] == 9) {
for (int i = 0; i < 7; i++) {
printf("\b");
}
}
inp[--pt] = '\0';
printf("\b \b");
}
} else if (c == 9) { // TAB character
inp[pt++] = c;
for (int i = 0; i < 8; i++) { // TABS should be 8 spaces
printf(" ");
}
} else if (c == 4) {
kill_all();
fflush(stdout);
exit(0);
} else {
printf("%d\n", c);
}
} else {
inp[pt++] = c;
printf("%c", c);
}
}
disableRawMode();
return inp;
}