10 #include <sys/ioctl.h>
13 static void sighandler(int s);
15 static int term_width, term_height;
16 static int ttyfd = -1;
17 static int selfpipe[2];
18 static struct termios saved_term;
20 static void (*cb_resized)(int, int);
23 int term_init(const char *ttypath)
28 if((ttyfd = open(ttypath ? ttypath : "/dev/tty", O_RDWR)) == -1) {
29 perror("failed to open /dev/tty");
32 if(tcgetattr(ttyfd, &term) == -1) {
33 perror("failed to get terminal attr");
37 term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
38 term.c_oflag &= ~OPOST;
39 term.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
40 term.c_cflag = (term.c_cflag & ~(CSIZE | PARENB)) | CS8;
42 if(tcsetattr(ttyfd, TCSAFLUSH, &term) == -1) {
43 perror("failed to change terminal attributes");
47 ioctl(1, TIOCGWINSZ, &winsz);
48 term_width = winsz.ws_col;
49 term_height = winsz.ws_row;
53 signal(SIGWINCH, sighandler);
57 void term_cleanup(void)
62 tcsetattr(ttyfd, TCSAFLUSH, &saved_term);
73 void term_getsize(int *width, int *height)
76 *height = term_height;
79 void term_resize_func(void (*func)(int, int))
85 static char termbuf[1024];
86 static int termbuf_len;
88 void term_send(const char *s, int size)
90 if(size >= sizeof termbuf) {
91 /* too large, just flush the buffer and write directly to the tty */
93 write(ttyfd, s, size);
95 if(size >= sizeof termbuf - termbuf_len) {
98 memcpy(termbuf + termbuf_len, s, size);
103 void term_putchar(char c)
108 void term_puts(const char *s)
110 term_send(s, strlen(s));
113 void term_printf(const char *fmt, ...)
122 if(!(buf = malloc(bufsz))) {
129 len = vsnprintf(buf, bufsz, fmt, ap);
132 if(len < bufsz) break;
136 if(!(tmp = realloc(buf, n))) {
137 break; /* if realloc fails, will result in truncated output */
145 void term_flush(void)
147 if(termbuf_len > 0) {
148 write(ttyfd, termbuf, termbuf_len);
153 void term_clear(void)
155 term_puts("\033[2J");
158 void term_cursor(int show)
160 term_printf("\033[?25%c", show ? 'h' : 'l');
163 void term_setcursor(int row, int col)
165 term_printf("\033[%d;%dH", row + 1, col + 1);
168 int term_getchar(void)
172 while((res = read(ttyfd, &c, 1)) < 0 && errno == EINTR);
173 if(res <= 0) return -1;
178 static void sighandler(int s)
180 struct winsize winsz;
182 signal(s, sighandler);
186 ioctl(1, TIOCGWINSZ, &winsz);
187 term_width = winsz.ws_col;
188 term_height = winsz.ws_row;