37406a0d3206d802c1502e659220cde9be4a0eb2
[visor] / visor / src / main_unix.c
1 #include <stdio.h>
2 #include <signal.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <termios.h>
7 #include <sys/ioctl.h>
8
9 static int init(void);
10 static void cleanup(void);
11 static void sighandler(int s);
12
13 int term_width, term_height;
14 int ttyfd;
15 struct termios saved_term;
16
17 int main(int argc, char **argv)
18 {
19         int res;
20         char c;
21
22         if(init() == -1) {
23                 return 1;
24         }
25
26         for(;;) {
27                 if((res = read(ttyfd, &c, 1)) == 0 || (res < 0 && errno != EINTR)) {
28                         break;
29                 }
30                 /* proc input */
31         }
32
33         cleanup();
34         return 0;
35 }
36
37 static int init(void)
38 {
39         struct termios term;
40         struct winsize winsz;
41
42         if((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
43                 perror("failed to open /dev/tty");
44                 return -1;
45         }
46         if(tcgetattr(ttyfd, &term) == -1) {
47                 perror("failed to get terminal attr");
48                 return -1;
49         }
50         saved_term = term;
51         term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
52         term.c_oflag &= ~OPOST;
53         term.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
54         term.c_cflag = (term.c_cflag & ~(CSIZE | PARENB)) | CS8;
55
56         if(tcsetattr(ttyfd, TCSAFLUSH, &term) == -1) {
57                 perror("failed to change terminal attributes");
58                 return -1;
59         }
60
61         ioctl(1, TIOCGWINSZ, &winsz);
62         term_width = winsz.ws_col;
63         term_height = winsz.ws_row;
64
65         signal(SIGWINCH, sighandler);
66
67         write(ttyfd, "\033[2J", 4);
68
69         return 0;
70 }
71
72 static void cleanup(void)
73 {
74         tcsetattr(ttyfd, TCSAFLUSH, &saved_term);
75         close(ttyfd);
76 }
77
78 static void sighandler(int s)
79 {
80         struct winsize winsz;
81
82         signal(s, sighandler);
83
84         switch(s) {
85         case SIGWINCH:
86                 ioctl(1, TIOCGWINSZ, &winsz);
87                 term_width = winsz.ws_col;
88                 term_height = winsz.ws_row;
89                 /* redraw */
90                 break;
91
92         default:
93                 break;
94         }
95 }