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
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include "tty.h"
void tty_reset(tty_t *tty){
tcsetattr(tty->fdin, TCSANOW, &tty->original_termios);
}
void tty_init(tty_t *tty){
tty->fdin = open("/dev/tty", O_RDONLY);
tty->fout = fopen("/dev/tty", "w");
tcgetattr(tty->fdin, &tty->original_termios);
struct termios new_termios = tty->original_termios;
new_termios.c_lflag &= ~(ICANON | ECHO);
tcsetattr(tty->fdin, TCSANOW, &new_termios);
tty_setnormal(tty);
}
char tty_getchar(tty_t *tty){
char ch;
int size = read(tty->fdin, &ch, 1);
if(size < 0){
perror("error reading from tty");
exit(EXIT_FAILURE);
}else if(size == 0){
/* EOF */
exit(EXIT_FAILURE);
}else{
return ch;
}
}
static void tty_sgr(tty_t *tty, int code){
fprintf(tty->fout, "%c%c%im", 0x1b, '[', code);
}
void tty_setfg(tty_t *tty, int fg){
if(tty->fgcolor != fg){
tty_sgr(tty, 30 + fg);
tty->fgcolor = fg;
}
}
void tty_setinvert(tty_t *tty){
tty_sgr(tty, 7);
}
void tty_setnormal(tty_t *tty){
tty_sgr(tty, 0);
tty->fgcolor = 9;
}
|