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