[ref] statusbar, rm get_finfo(), MAX macros
[sfm.git] / termbox.c
blob71529c5291f11e59a7dd2a5e7ccb16b1cbbe3b16
1 #include <assert.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <stdbool.h>
9 #include <sys/select.h>
10 #include <sys/ioctl.h>
11 #include <sys/time.h>
12 #include <sys/stat.h>
13 #include <termios.h>
14 #include <unistd.h>
15 #include <wchar.h>
17 #include "termbox.h"
19 static int inputmode = TB_INPUT_ESC;
21 /* bytebuffer.inl --------------------------------------------------------- */
23 struct bytebuffer {
24 char *buf;
25 int len;
26 int cap;
29 static void bytebuffer_reserve(struct bytebuffer *b, int cap) {
30 if (b->cap >= cap) {
31 return;
34 // prefer doubling capacity
35 if (b->cap * 2 >= cap) {
36 cap = b->cap * 2;
39 char *newbuf = realloc(b->buf, cap);
40 b->buf = newbuf;
41 b->cap = cap;
44 static void bytebuffer_init(struct bytebuffer *b, int cap) {
45 b->cap = 0;
46 b->len = 0;
47 b->buf = 0;
49 if (cap > 0) {
50 b->cap = cap;
51 b->buf = malloc(cap); // just assume malloc works always
55 static void bytebuffer_free(struct bytebuffer *b) {
56 if (b->buf)
57 free(b->buf);
60 static void bytebuffer_clear(struct bytebuffer *b) {
61 b->len = 0;
64 static void bytebuffer_append(struct bytebuffer *b, const char *data, int len) {
65 bytebuffer_reserve(b, b->len + len);
66 memcpy(b->buf + b->len, data, len);
67 b->len += len;
70 static void bytebuffer_puts(struct bytebuffer *b, const char *str) {
71 bytebuffer_append(b, str, strlen(str));
74 static void bytebuffer_resize(struct bytebuffer *b, int len) {
75 bytebuffer_reserve(b, len);
76 b->len = len;
79 static void bytebuffer_flush(struct bytebuffer *b, int fd) {
80 (void)write(fd, b->buf, b->len);
81 bytebuffer_clear(b);
84 static void bytebuffer_truncate(struct bytebuffer *b, int n) {
85 if (n <= 0)
86 return;
87 if (n > b->len)
88 n = b->len;
89 const int nmove = b->len - n;
90 memmove(b->buf, b->buf+n, nmove);
91 b->len -= n;
94 /* term.inl --------------------------------------------------------------- */
95 enum {
96 T_ENTER_CA,
97 T_EXIT_CA,
98 T_SHOW_CURSOR,
99 T_HIDE_CURSOR,
100 T_CLEAR_SCREEN,
101 T_SGR0,
102 T_UNDERLINE,
103 T_BOLD,
104 T_BLINK,
105 T_REVERSE,
106 T_ENTER_KEYPAD,
107 T_EXIT_KEYPAD,
108 T_ENTER_MOUSE,
109 T_EXIT_MOUSE,
110 T_FUNCS_NUM,
113 #define ENTER_MOUSE_SEQ "\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h"
114 #define EXIT_MOUSE_SEQ "\x1b[?1006l\x1b[?1015l\x1b[?1002l\x1b[?1000l"
116 #define EUNSUPPORTED_TERM -1
118 // rxvt-256color
119 static const char *rxvt_256color_keys[] = {
120 "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0
122 static const char *rxvt_256color_funcs[] = {
123 "\0337\033[?47h", "\033[2J\033[?47l\0338", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033=", "\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ,
126 // Eterm
127 static const char *eterm_keys[] = {
128 "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0
130 static const char *eterm_funcs[] = {
131 "\0337\033[?47h", "\033[2J\033[?47l\0338", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "", "", "", "",
134 // screen
135 static const char *screen_keys[] = {
136 "\033OP","\033OQ","\033OR","\033OS","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[1~","\033[4~","\033[5~","\033[6~","\033OA","\033OB","\033OD","\033OC", 0
138 static const char *screen_funcs[] = {
139 "\033[?1049h", "\033[?1049l", "\033[34h\033[?25h", "\033[?25l", "\033[H\033[J", "\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033[?1h\033=", "\033[?1l\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ,
142 // rxvt-unicode
143 static const char *rxvt_unicode_keys[] = {
144 "\033[11~","\033[12~","\033[13~","\033[14~","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[7~","\033[8~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0
146 static const char *rxvt_unicode_funcs[] = {
147 "\033[?1049h", "\033[r\033[?1049l", "\033[?25h", "\033[?25l", "\033[H\033[2J", "\033[m\033(B", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033=", "\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ,
150 // linux
151 static const char *linux_keys[] = {
152 "\033[[A","\033[[B","\033[[C","\033[[D","\033[[E","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033[1~","\033[4~","\033[5~","\033[6~","\033[A","\033[B","\033[D","\033[C", 0
154 static const char *linux_funcs[] = {
155 "", "", "\033[?25h\033[?0c", "\033[?25l\033[?1c", "\033[H\033[J", "\033[0;10m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "", "", "", "",
158 // xterm
159 static const char *xterm_keys[] = {
160 "\033OP","\033OQ","\033OR","\033OS","\033[15~","\033[17~","\033[18~","\033[19~","\033[20~","\033[21~","\033[23~","\033[24~","\033[2~","\033[3~","\033OH","\033OF","\033[5~","\033[6~","\033OA","\033OB","\033OD","\033OC", 0
162 static const char *xterm_funcs[] = {
163 "\033[?1049h", "\033[?1049l", "\033[?12l\033[?25h", "\033[?25l", "\033[H\033[2J", "\033(B\033[m", "\033[4m", "\033[1m", "\033[5m", "\033[7m", "\033[?1h\033=", "\033[?1l\033>", ENTER_MOUSE_SEQ, EXIT_MOUSE_SEQ,
166 static struct term {
167 const char *name;
168 const char **keys;
169 const char **funcs;
170 } terms[] = {
171 {"rxvt-256color", rxvt_256color_keys, rxvt_256color_funcs},
172 {"Eterm", eterm_keys, eterm_funcs},
173 {"screen", screen_keys, screen_funcs},
174 {"rxvt-unicode", rxvt_unicode_keys, rxvt_unicode_funcs},
175 {"linux", linux_keys, linux_funcs},
176 {"xterm", xterm_keys, xterm_funcs},
177 {0, 0, 0},
180 static bool init_from_terminfo = false;
181 static const char **keys;
182 static const char **funcs;
184 static int try_compatible(const char *term, const char *name,
185 const char **tkeys, const char **tfuncs)
187 if (strstr(term, name)) {
188 keys = tkeys;
189 funcs = tfuncs;
190 return 0;
193 return EUNSUPPORTED_TERM;
196 static int init_term_builtin(void)
198 int i;
199 const char *term = getenv("TERM");
201 if (term) {
202 for (i = 0; terms[i].name; i++) {
203 if (!strcmp(terms[i].name, term)) {
204 keys = terms[i].keys;
205 funcs = terms[i].funcs;
206 return 0;
210 /* let's do some heuristic, maybe it's a compatible terminal */
211 if (try_compatible(term, "xterm", xterm_keys, xterm_funcs) == 0)
212 return 0;
213 if (try_compatible(term, "rxvt", rxvt_unicode_keys, rxvt_unicode_funcs) == 0)
214 return 0;
215 if (try_compatible(term, "linux", linux_keys, linux_funcs) == 0)
216 return 0;
217 if (try_compatible(term, "Eterm", eterm_keys, eterm_funcs) == 0)
218 return 0;
219 if (try_compatible(term, "screen", screen_keys, screen_funcs) == 0)
220 return 0;
221 if (try_compatible(term, "tmux", screen_keys, screen_funcs) == 0)
222 return 0;
223 /* let's assume that 'cygwin' is xterm compatible */
224 if (try_compatible(term, "cygwin", xterm_keys, xterm_funcs) == 0)
225 return 0;
228 return EUNSUPPORTED_TERM;
231 //----------------------------------------------------------------------
232 // terminfo
233 //----------------------------------------------------------------------
235 static char *read_file(const char *file) {
236 FILE *f = fopen(file, "rb");
237 if (!f)
238 return 0;
240 struct stat st;
241 if (fstat(fileno(f), &st) != 0) {
242 fclose(f);
243 return 0;
246 char *data = malloc(st.st_size);
247 if (!data) {
248 fclose(f);
249 return 0;
252 if (fread(data, 1, st.st_size, f) != (size_t)st.st_size) {
253 fclose(f);
254 free(data);
255 return 0;
258 fclose(f);
259 return data;
262 static char *terminfo_try_path(const char *path, const char *term) {
263 char tmp[4096];
264 snprintf(tmp, sizeof(tmp), "%s/%c/%s", path, term[0], term);
265 tmp[sizeof(tmp)-1] = '\0';
266 char *data = read_file(tmp);
267 if (data) {
268 return data;
271 // fallback to darwin specific dirs structure
272 snprintf(tmp, sizeof(tmp), "%s/%x/%s", path, term[0], term);
273 tmp[sizeof(tmp)-1] = '\0';
274 return read_file(tmp);
277 static char *load_terminfo(void) {
278 char tmp[4096];
279 const char *term = getenv("TERM");
280 if (!term) {
281 return 0;
284 // if TERMINFO is set, no other directory should be searched
285 const char *terminfo = getenv("TERMINFO");
286 if (terminfo) {
287 return terminfo_try_path(terminfo, term);
290 // next, consider ~/.terminfo
291 const char *home = getenv("HOME");
292 if (home) {
293 snprintf(tmp, sizeof(tmp), "%s/.terminfo", home);
294 tmp[sizeof(tmp)-1] = '\0';
295 char *data = terminfo_try_path(tmp, term);
296 if (data)
297 return data;
300 // next, TERMINFO_DIRS
301 const char *dirs = getenv("TERMINFO_DIRS");
302 if (dirs) {
303 snprintf(tmp, sizeof(tmp), "%s", dirs);
304 tmp[sizeof(tmp)-1] = '\0';
305 char *dir = strtok(tmp, ":");
306 while (dir) {
307 const char *cdir = dir;
308 if (strcmp(cdir, "") == 0) {
309 cdir = "/usr/share/terminfo";
311 char *data = terminfo_try_path(cdir, term);
312 if (data)
313 return data;
314 dir = strtok(0, ":");
318 // fallback to /usr/share/terminfo
319 return terminfo_try_path("/usr/share/terminfo", term);
322 #define TI_MAGIC 0432
323 #define TI_ALT_MAGIC 542
324 #define TI_HEADER_LENGTH 12
325 #define TB_KEYS_NUM 22
327 static const char *terminfo_copy_string(char *data, int str, int table) {
328 const int16_t off = *(int16_t*)(data + str);
329 const char *src = data + table + off;
330 int len = strlen(src);
331 char *dst = malloc(len+1);
332 strcpy(dst, src);
333 return dst;
336 static const int16_t ti_funcs[] = {
337 28, 40, 16, 13, 5, 39, 36, 27, 26, 34, 89, 88,
340 static const int16_t ti_keys[] = {
341 66, 68 /* apparently not a typo; 67 is F10 for whatever reason */, 69,
342 70, 71, 72, 73, 74, 75, 67, 216, 217, 77, 59, 76, 164, 82, 81, 87, 61,
343 79, 83,
346 static int init_term(void) {
347 int i;
348 char *data = load_terminfo();
349 if (!data) {
350 init_from_terminfo = false;
351 return init_term_builtin();
354 int16_t *header = (int16_t*)data;
356 const int number_sec_len = header[0] == TI_ALT_MAGIC ? 4 : 2;
358 if ((header[1] + header[2]) % 2) {
359 // old quirk to align everything on word boundaries
360 header[2] += 1;
363 const int str_offset = TI_HEADER_LENGTH +
364 header[1] + header[2] + number_sec_len * header[3];
365 const int table_offset = str_offset + 2 * header[4];
367 keys = malloc(sizeof(const char*) * (TB_KEYS_NUM+1));
368 for (i = 0; i < TB_KEYS_NUM; i++) {
369 keys[i] = terminfo_copy_string(data,
370 str_offset + 2 * ti_keys[i], table_offset);
372 keys[TB_KEYS_NUM] = 0;
374 funcs = malloc(sizeof(const char*) * T_FUNCS_NUM);
375 // the last two entries are reserved for mouse. because the table offset is
376 // not there, the two entries have to fill in manually
377 for (i = 0; i < T_FUNCS_NUM-2; i++) {
378 funcs[i] = terminfo_copy_string(data,
379 str_offset + 2 * ti_funcs[i], table_offset);
382 funcs[T_FUNCS_NUM-2] = ENTER_MOUSE_SEQ;
383 funcs[T_FUNCS_NUM-1] = EXIT_MOUSE_SEQ;
385 init_from_terminfo = true;
386 free(data);
387 return 0;
390 static void shutdown_term(void) {
391 if (init_from_terminfo) {
392 int i;
393 for (i = 0; i < TB_KEYS_NUM; i++) {
394 free((void*)keys[i]);
396 // the last two entries are reserved for mouse. because the table offset
397 // is not there, the two entries have to fill in manually and do not
398 // need to be freed.
399 for (i = 0; i < T_FUNCS_NUM-2; i++) {
400 free((void*)funcs[i]);
402 free(keys);
403 free(funcs);
407 /* input.inl -------------------------------------------------------------- */
409 // if s1 starts with s2 returns true, else false
410 // len is the length of s1
411 // s2 should be null-terminated
412 static bool starts_with(const char *s1, int len, const char *s2)
414 int n = 0;
415 while (*s2 && n < len) {
416 if (*s1++ != *s2++)
417 return false;
418 n++;
420 return *s2 == 0;
423 // convert escape sequence to event, and return consumed bytes on success (failure == 0)
424 static int parse_escape_seq(struct tb_event *event, const char *buf, int len)
426 // it's pretty simple here, find 'starts_with' match and return
427 // success, else return failure
428 int i;
429 for (i = 0; keys[i]; i++) {
430 if (starts_with(buf, len, keys[i])) {
431 event->ch = 0;
432 event->key = 0xFFFF-i;
433 return strlen(keys[i]);
436 return 0;
439 static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf)
441 const char *buf = inbuf->buf;
442 const int len = inbuf->len;
443 if (len == 0)
444 return false;
446 if (buf[0] == '\033') {
447 int n = parse_escape_seq(event, buf, len);
448 if (n != 0) {
449 bool success = true;
450 if (n < 0) {
451 success = false;
452 n = -n;
454 bytebuffer_truncate(inbuf, n);
455 return success;
456 } else {
457 // it's not escape sequence, then it's ALT or ESC,
458 // check inputmode
459 if (inputmode&TB_INPUT_ESC) {
460 // if we're in escape mode, fill ESC event, pop
461 // buffer, return success
462 event->ch = 0;
463 event->key = TB_KEY_ESC;
464 event->mod = 0;
465 bytebuffer_truncate(inbuf, 1);
466 return true;
467 } else if (inputmode&TB_INPUT_ALT) {
468 // if we're in alt mode, set ALT modifier to
469 // event and redo parsing
470 event->mod = TB_MOD_ALT;
471 bytebuffer_truncate(inbuf, 1);
472 return extract_event(event, inbuf);
474 assert(!"never got here");
478 // if we're here, this is not an escape sequence and not an alt sequence
479 // so, it's a FUNCTIONAL KEY or a UNICODE character
481 // first of all check if it's a functional key
482 if ((unsigned char)buf[0] <= TB_KEY_SPACE ||
483 (unsigned char)buf[0] == TB_KEY_BACKSPACE2)
485 // fill event, pop buffer, return success */
486 event->ch = 0;
487 event->key = (uint16_t)buf[0];
488 bytebuffer_truncate(inbuf, 1);
489 return true;
492 // feh... we got utf8 here
494 // check if there is all bytes
495 if (len >= tb_utf8_char_length(buf[0])) {
496 /* everything ok, fill event, pop buffer, return success */
497 tb_utf8_char_to_unicode(&event->ch, buf);
498 event->key = 0;
499 bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0]));
500 return true;
503 // event isn't recognized, perhaps there is not enough bytes in utf8
504 // sequence
505 return false;
508 /* -------------------------------------------------------- */
510 struct cellbuf {
511 int width;
512 int height;
513 struct tb_cell *cells;
516 #define CELL(buf, x, y) (buf)->cells[(y) * (buf)->width + (x)]
517 #define IS_CURSOR_HIDDEN(cx, cy) (cx == -1 || cy == -1)
518 #define LAST_COORD_INIT -1
520 static struct termios orig_tios;
522 static struct cellbuf back_buffer;
523 static struct cellbuf front_buffer;
524 static struct bytebuffer output_buffer;
525 static struct bytebuffer input_buffer;
527 static int termw = -1;
528 static int termh = -1;
530 static int outputmode = TB_OUTPUT_NORMAL;
532 static int inout;
533 static int winch_fds[2];
535 static int lastx = LAST_COORD_INIT;
536 static int lasty = LAST_COORD_INIT;
537 static int cursor_x = -1;
538 static int cursor_y = -1;
540 static uint16_t background = TB_DEFAULT;
541 static uint16_t foreground = TB_DEFAULT;
543 static void write_cursor(int x, int y);
544 static void write_sgr(uint16_t fg, uint16_t bg);
546 static void cellbuf_init(struct cellbuf *buf, int width, int height);
547 static void cellbuf_resize(struct cellbuf *buf, int width, int height);
548 static void cellbuf_clear(struct cellbuf *buf);
549 static void cellbuf_free(struct cellbuf *buf);
551 static void update_size(void);
552 static void update_term_size(void);
553 static void send_attr(uint16_t fg, uint16_t bg);
554 static void send_char(int x, int y, uint32_t c);
555 static void send_clear(void);
556 static void sigwinch_handler(int xxx);
557 static int wait_fill_event(struct tb_event *event, struct timeval *timeout);
559 /* may happen in a different thread */
560 static volatile int buffer_size_change_request;
562 /* -------------------------------------------------------- */
564 int tb_init_fd(int inout_)
566 inout = inout_;
567 if (inout == -1) {
568 return TB_EFAILED_TO_OPEN_TTY;
571 if (init_term() < 0) {
572 close(inout);
573 return TB_EUNSUPPORTED_TERMINAL;
576 if (pipe(winch_fds) < 0) {
577 close(inout);
578 return TB_EPIPE_TRAP_ERROR;
581 struct sigaction sa;
582 memset(&sa, 0, sizeof(sa));
583 sa.sa_handler = sigwinch_handler;
584 sa.sa_flags = 0;
585 sigaction(SIGWINCH, &sa, 0);
587 tcgetattr(inout, &orig_tios);
589 struct termios tios;
590 memcpy(&tios, &orig_tios, sizeof(tios));
592 tios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
593 | INLCR | IGNCR | ICRNL | IXON);
594 tios.c_oflag &= ~OPOST;
595 tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
596 tios.c_cflag &= ~(CSIZE | PARENB);
597 tios.c_cflag |= CS8;
598 tios.c_cc[VMIN] = 0;
599 tios.c_cc[VTIME] = 0;
600 tcsetattr(inout, TCSAFLUSH, &tios);
602 bytebuffer_init(&input_buffer, 128);
603 bytebuffer_init(&output_buffer, 32 * 1024);
605 bytebuffer_puts(&output_buffer, funcs[T_ENTER_CA]);
606 bytebuffer_puts(&output_buffer, funcs[T_ENTER_KEYPAD]);
607 bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]);
608 send_clear();
610 update_term_size();
611 cellbuf_init(&back_buffer, termw, termh);
612 cellbuf_init(&front_buffer, termw, termh);
613 cellbuf_clear(&back_buffer);
614 cellbuf_clear(&front_buffer);
616 return 0;
619 int tb_init_file(const char* name){
620 return tb_init_fd(open(name, O_RDWR));
623 int tb_init(void)
625 return tb_init_file("/dev/tty");
628 void tb_shutdown(void)
630 if (termw == -1) {
631 fputs("tb_shutdown() should not be called twice.", stderr);
632 abort();
635 bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]);
636 bytebuffer_puts(&output_buffer, funcs[T_SGR0]);
637 bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]);
638 bytebuffer_puts(&output_buffer, funcs[T_EXIT_CA]);
639 bytebuffer_puts(&output_buffer, funcs[T_EXIT_KEYPAD]);
640 bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]);
641 bytebuffer_flush(&output_buffer, inout);
642 tcsetattr(inout, TCSAFLUSH, &orig_tios);
644 shutdown_term();
645 close(inout);
646 close(winch_fds[0]);
647 close(winch_fds[1]);
649 cellbuf_free(&back_buffer);
650 cellbuf_free(&front_buffer);
651 bytebuffer_free(&output_buffer);
652 bytebuffer_free(&input_buffer);
653 termw = termh = -1;
656 void tb_present(void)
658 int x,y,w,i;
659 struct tb_cell *back, *front;
661 /* invalidate cursor position */
662 lastx = LAST_COORD_INIT;
663 lasty = LAST_COORD_INIT;
665 if (buffer_size_change_request) {
666 update_size();
667 buffer_size_change_request = 0;
670 for (y = 0; y < front_buffer.height; ++y) {
671 for (x = 0; x < front_buffer.width; ) {
672 back = &CELL(&back_buffer, x, y);
673 front = &CELL(&front_buffer, x, y);
674 w = wcwidth(back->ch);
675 if (w < 1) w = 1;
676 if (memcmp(back, front, sizeof(struct tb_cell)) == 0) {
677 x += w;
678 continue;
680 memcpy(front, back, sizeof(struct tb_cell));
681 send_attr(back->fg, back->bg);
682 if (w > 1 && x >= front_buffer.width - (w - 1)) {
683 // Not enough room for wide ch, so send spaces
684 for (i = x; i < front_buffer.width; ++i) {
685 send_char(i, y, ' ');
687 } else {
688 send_char(x, y, back->ch);
689 for (i = 1; i < w; ++i) {
690 front = &CELL(&front_buffer, x + i, y);
691 front->ch = 0;
692 front->fg = back->fg;
693 front->bg = back->bg;
696 x += w;
699 if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
700 write_cursor(cursor_x, cursor_y);
701 bytebuffer_flush(&output_buffer, inout);
704 void tb_set_cursor(int cx, int cy)
706 if (IS_CURSOR_HIDDEN(cursor_x, cursor_y) && !IS_CURSOR_HIDDEN(cx, cy))
707 bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]);
709 if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y) && IS_CURSOR_HIDDEN(cx, cy))
710 bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]);
712 cursor_x = cx;
713 cursor_y = cy;
714 if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
715 write_cursor(cursor_x, cursor_y);
718 void tb_put_cell(int x, int y, const struct tb_cell *cell)
720 if ((unsigned)x >= (unsigned)back_buffer.width)
721 return;
722 if ((unsigned)y >= (unsigned)back_buffer.height)
723 return;
724 CELL(&back_buffer, x, y) = *cell;
727 void tb_change_cell(int x, int y, uint32_t ch, uint16_t fg, uint16_t bg)
729 struct tb_cell c = {ch, fg, bg};
730 tb_put_cell(x, y, &c);
733 void tb_blit(int x, int y, int w, int h, const struct tb_cell *cells)
735 if (x + w < 0 || x >= back_buffer.width)
736 return;
737 if (y + h < 0 || y >= back_buffer.height)
738 return;
739 int xo = 0, yo = 0, ww = w, hh = h;
740 if (x < 0) {
741 xo = -x;
742 ww -= xo;
743 x = 0;
745 if (y < 0) {
746 yo = -y;
747 hh -= yo;
748 y = 0;
750 if (ww > back_buffer.width - x)
751 ww = back_buffer.width - x;
752 if (hh > back_buffer.height - y)
753 hh = back_buffer.height - y;
755 int sy;
756 struct tb_cell *dst = &CELL(&back_buffer, x, y);
757 const struct tb_cell *src = cells + yo * w + xo;
758 size_t size = sizeof(struct tb_cell) * ww;
760 for (sy = 0; sy < hh; ++sy) {
761 memcpy(dst, src, size);
762 dst += back_buffer.width;
763 src += w;
767 struct tb_cell *tb_cell_buffer(void)
769 return back_buffer.cells;
772 int tb_poll_event(struct tb_event *event)
774 return wait_fill_event(event, 0);
777 int tb_peek_event(struct tb_event *event, int timeout)
779 struct timeval tv;
780 tv.tv_sec = timeout / 1000;
781 tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000;
782 return wait_fill_event(event, &tv);
785 int tb_width(void)
787 return termw;
790 int tb_height(void)
792 return termh;
795 void tb_clear(void)
797 if (buffer_size_change_request) {
798 update_size();
799 buffer_size_change_request = 0;
801 cellbuf_clear(&back_buffer);
804 int tb_select_input_mode(int mode)
806 if (mode) {
807 if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == 0)
808 mode |= TB_INPUT_ESC;
810 /* technically termbox can handle that, but let's be nice and show here
811 what mode is actually used */
812 if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == (TB_INPUT_ESC | TB_INPUT_ALT))
813 mode &= ~TB_INPUT_ALT;
815 inputmode = mode;
816 if (mode&TB_INPUT_MOUSE) {
817 bytebuffer_puts(&output_buffer, funcs[T_ENTER_MOUSE]);
818 bytebuffer_flush(&output_buffer, inout);
819 } else {
820 bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]);
821 bytebuffer_flush(&output_buffer, inout);
824 return inputmode;
827 int tb_select_output_mode(int mode)
829 if (mode)
830 outputmode = mode;
831 return outputmode;
834 void tb_set_clear_attributes(uint16_t fg, uint16_t bg)
836 foreground = fg;
837 background = bg;
840 /* -------------------------------------------------------- */
842 static int convertnum(uint32_t num, char* buf) {
843 int i, l = 0;
844 int ch;
845 do {
846 buf[l++] = '0' + (num % 10);
847 num /= 10;
848 } while (num);
849 for(i = 0; i < l / 2; i++) {
850 ch = buf[i];
851 buf[i] = buf[l - 1 - i];
852 buf[l - 1 - i] = ch;
854 return l;
857 #define WRITE_LITERAL(X) bytebuffer_append(&output_buffer, (X), sizeof(X)-1)
858 #define WRITE_INT(X) bytebuffer_append(&output_buffer, buf, convertnum((X), buf))
860 static void write_cursor(int x, int y) {
861 char buf[32];
862 WRITE_LITERAL("\033[");
863 WRITE_INT(y+1);
864 WRITE_LITERAL(";");
865 WRITE_INT(x+1);
866 WRITE_LITERAL("H");
869 static void write_sgr(uint16_t fg, uint16_t bg) {
870 char buf[32];
872 if (fg == TB_DEFAULT && bg == TB_DEFAULT)
873 return;
875 switch (outputmode) {
876 case TB_OUTPUT_256:
877 case TB_OUTPUT_216:
878 case TB_OUTPUT_GRAYSCALE:
879 WRITE_LITERAL("\033[");
880 if (fg != TB_DEFAULT) {
881 WRITE_LITERAL("38;5;");
882 WRITE_INT(fg);
883 if (bg != TB_DEFAULT) {
884 WRITE_LITERAL(";");
887 if (bg != TB_DEFAULT) {
888 WRITE_LITERAL("48;5;");
889 WRITE_INT(bg);
891 WRITE_LITERAL("m");
892 break;
893 case TB_OUTPUT_NORMAL:
894 default:
895 WRITE_LITERAL("\033[");
896 if (fg != TB_DEFAULT) {
897 WRITE_LITERAL("3");
898 WRITE_INT(fg - 1);
899 if (bg != TB_DEFAULT) {
900 WRITE_LITERAL(";");
903 if (bg != TB_DEFAULT) {
904 WRITE_LITERAL("4");
905 WRITE_INT(bg - 1);
907 WRITE_LITERAL("m");
908 break;
912 static void cellbuf_init(struct cellbuf *buf, int width, int height)
914 buf->cells = (struct tb_cell*)malloc(sizeof(struct tb_cell) * width * height);
915 assert(buf->cells);
916 buf->width = width;
917 buf->height = height;
920 static void cellbuf_resize(struct cellbuf *buf, int width, int height)
922 if (buf->width == width && buf->height == height)
923 return;
925 int oldw = buf->width;
926 int oldh = buf->height;
927 struct tb_cell *oldcells = buf->cells;
929 cellbuf_init(buf, width, height);
930 cellbuf_clear(buf);
932 int minw = (width < oldw) ? width : oldw;
933 int minh = (height < oldh) ? height : oldh;
934 int i;
936 for (i = 0; i < minh; ++i) {
937 struct tb_cell *csrc = oldcells + (i * oldw);
938 struct tb_cell *cdst = buf->cells + (i * width);
939 memcpy(cdst, csrc, sizeof(struct tb_cell) * minw);
942 free(oldcells);
945 static void cellbuf_clear(struct cellbuf *buf)
947 int i;
948 int ncells = buf->width * buf->height;
950 for (i = 0; i < ncells; ++i) {
951 buf->cells[i].ch = ' ';
952 buf->cells[i].fg = foreground;
953 buf->cells[i].bg = background;
957 static void cellbuf_free(struct cellbuf *buf)
959 free(buf->cells);
962 static void get_term_size(int *w, int *h)
964 struct winsize sz;
965 memset(&sz, 0, sizeof(sz));
967 ioctl(inout, TIOCGWINSZ, &sz);
969 if (w) *w = sz.ws_col;
970 if (h) *h = sz.ws_row;
973 static void update_term_size(void)
975 struct winsize sz;
976 memset(&sz, 0, sizeof(sz));
978 ioctl(inout, TIOCGWINSZ, &sz);
980 termw = sz.ws_col;
981 termh = sz.ws_row;
984 static void send_attr(uint16_t fg, uint16_t bg)
986 #define LAST_ATTR_INIT 0xFFFF
987 static uint16_t lastfg = LAST_ATTR_INIT, lastbg = LAST_ATTR_INIT;
988 if (fg != lastfg || bg != lastbg) {
989 bytebuffer_puts(&output_buffer, funcs[T_SGR0]);
991 uint16_t fgcol;
992 uint16_t bgcol;
994 switch (outputmode) {
995 case TB_OUTPUT_256:
996 fgcol = fg & 0xFF;
997 bgcol = bg & 0xFF;
998 break;
1000 case TB_OUTPUT_216:
1001 fgcol = fg & 0xFF; if (fgcol > 215) fgcol = 7;
1002 bgcol = bg & 0xFF; if (bgcol > 215) bgcol = 0;
1003 fgcol += 0x10;
1004 bgcol += 0x10;
1005 break;
1007 case TB_OUTPUT_GRAYSCALE:
1008 fgcol = fg & 0xFF; if (fgcol > 23) fgcol = 23;
1009 bgcol = bg & 0xFF; if (bgcol > 23) bgcol = 0;
1010 fgcol += 0xe8;
1011 bgcol += 0xe8;
1012 break;
1014 case TB_OUTPUT_NORMAL:
1015 default:
1016 fgcol = fg & 0x0F;
1017 bgcol = bg & 0x0F;
1020 if (fg & TB_BOLD)
1021 bytebuffer_puts(&output_buffer, funcs[T_BOLD]);
1022 if (bg & TB_BOLD)
1023 bytebuffer_puts(&output_buffer, funcs[T_BLINK]);
1024 if (fg & TB_UNDERLINE)
1025 bytebuffer_puts(&output_buffer, funcs[T_UNDERLINE]);
1026 if ((fg & TB_REVERSE) || (bg & TB_REVERSE))
1027 bytebuffer_puts(&output_buffer, funcs[T_REVERSE]);
1029 write_sgr(fgcol, bgcol);
1031 lastfg = fg;
1032 lastbg = bg;
1036 static void send_char(int x, int y, uint32_t c)
1038 char buf[7];
1039 int bw = tb_utf8_unicode_to_char(buf, c);
1040 if (x-1 != lastx || y != lasty)
1041 write_cursor(x, y);
1042 lastx = x; lasty = y;
1043 if(!c) buf[0] = ' '; // replace 0 with whitespace
1044 bytebuffer_append(&output_buffer, buf, bw);
1047 static void send_clear(void)
1049 send_attr(foreground, background);
1050 bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]);
1051 if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
1052 write_cursor(cursor_x, cursor_y);
1053 bytebuffer_flush(&output_buffer, inout);
1055 /* we need to invalidate cursor position too and these two vars are
1056 * used only for simple cursor positioning optimization, cursor
1057 * actually may be in the correct place, but we simply discard
1058 * optimization once and it gives us simple solution for the case when
1059 * cursor moved */
1060 lastx = LAST_COORD_INIT;
1061 lasty = LAST_COORD_INIT;
1064 static void sigwinch_handler(int xxx)
1066 (void) xxx;
1067 const int zzz = 1;
1068 (void)write(winch_fds[1], &zzz, sizeof(int));
1071 static void update_size(void)
1073 update_term_size();
1074 cellbuf_resize(&back_buffer, termw, termh);
1075 cellbuf_resize(&front_buffer, termw, termh);
1076 cellbuf_clear(&front_buffer);
1077 send_clear();
1080 static int read_up_to(int n) {
1081 assert(n > 0);
1082 const int prevlen = input_buffer.len;
1083 bytebuffer_resize(&input_buffer, prevlen + n);
1085 int read_n = 0;
1086 while (read_n <= n) {
1087 ssize_t r = 0;
1088 if (read_n < n) {
1089 r = read(inout, input_buffer.buf + prevlen + read_n, n - read_n);
1091 #ifdef __CYGWIN__
1092 // While linux man for tty says when VMIN == 0 && VTIME == 0, read
1093 // should return 0 when there is nothing to read, cygwin's read returns
1094 // -1. Not sure why and if it's correct to ignore it, but let's pretend
1095 // it's zero.
1096 if (r < 0) r = 0;
1097 #endif
1098 if (r < 0) {
1099 // EAGAIN / EWOULDBLOCK shouldn't occur here
1100 assert(errno != EAGAIN && errno != EWOULDBLOCK);
1101 return -1;
1102 } else if (r > 0) {
1103 read_n += r;
1104 } else {
1105 bytebuffer_resize(&input_buffer, prevlen + read_n);
1106 return read_n;
1109 assert(!"unreachable");
1110 return 0;
1113 static int wait_fill_event(struct tb_event *event, struct timeval *timeout)
1115 // ;-)
1116 #define ENOUGH_DATA_FOR_PARSING 64
1117 fd_set events;
1118 memset(event, 0, sizeof(struct tb_event));
1120 // try to extract event from input buffer, return on success
1121 event->type = TB_EVENT_KEY;
1122 if (extract_event(event, &input_buffer))
1123 return event->type;
1125 // it looks like input buffer is incomplete, let's try the short path,
1126 // but first make sure there is enough space
1127 int n = read_up_to(ENOUGH_DATA_FOR_PARSING);
1128 if (n < 0)
1129 return -1;
1130 if (n > 0 && extract_event(event, &input_buffer))
1131 return event->type;
1133 // n == 0, or not enough data, let's go to select
1134 while (1) {
1135 FD_ZERO(&events);
1136 FD_SET(inout, &events);
1137 FD_SET(winch_fds[0], &events);
1138 int maxfd = (winch_fds[0] > inout) ? winch_fds[0] : inout;
1139 int result = select(maxfd+1, &events, 0, 0, timeout);
1140 if (!result)
1141 return 0;
1143 if (FD_ISSET(inout, &events)) {
1144 event->type = TB_EVENT_KEY;
1145 n = read_up_to(ENOUGH_DATA_FOR_PARSING);
1146 if (n < 0)
1147 return -1;
1149 if (n == 0)
1150 continue;
1152 if (extract_event(event, &input_buffer))
1153 return event->type;
1155 if (FD_ISSET(winch_fds[0], &events)) {
1156 event->type = TB_EVENT_RESIZE;
1157 int zzz = 0;
1158 (void)read(winch_fds[0], &zzz, sizeof(int));
1159 buffer_size_change_request = 1;
1160 get_term_size(&event->w, &event->h);
1161 return TB_EVENT_RESIZE;