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)
59 tcsetattr(ttyfd, TCSAFLUSH, &saved_term);
64 void term_getsize(int *width, int *height)
67 *height = term_height;
70 void term_resize_func(void (*func)(int, int))
76 static char termbuf[1024];
77 static int termbuf_len;
79 void term_send(const char *s, int size)
81 if(size >= sizeof termbuf) {
82 /* too large, just flush the buffer and write directly to the tty */
84 write(ttyfd, s, size);
86 if(size >= sizeof termbuf - termbuf_len) {
89 memcpy(termbuf + termbuf_len, s, size);
94 void term_putchar(char c)
99 void term_puts(const char *s)
101 term_send(s, strlen(s));
104 void term_printf(const char *fmt, ...)
113 if(!(buf = malloc(bufsz))) {
120 len = vsnprintf(buf, bufsz, fmt, ap);
123 if(len < bufsz) break;
127 if(!(tmp = realloc(buf, n))) {
128 break; /* if realloc fails, will result in truncated output */
136 void term_flush(void)
138 if(termbuf_len > 0) {
139 write(ttyfd, termbuf, termbuf_len);
144 void term_clear(void)
146 term_puts("\033[2J");
149 void term_cursor(int show)
151 term_printf("\033[?25%c", show ? 'h' : 'l');
154 void term_setcursor(int row, int col)
156 term_printf("\033[%d;%dH", row + 1, col + 1);
159 int term_getchar(void)
163 while((res = read(ttyfd, &c, 1)) < 0 && errno == EINTR);
164 if(res <= 0) return -1;
169 static void sighandler(int s)
171 struct winsize winsz;
173 signal(s, sighandler);
177 ioctl(1, TIOCGWINSZ, &winsz);
178 term_width = winsz.ws_col;
179 term_height = winsz.ws_row;