9 #include <sys/select.h>
10 #include <sys/ioctl.h>
19 static int inputmode
= TB_INPUT_ESC
;
21 /* bytebuffer.inl --------------------------------------------------------- */
29 static void bytebuffer_reserve(struct bytebuffer
*b
, int cap
) {
34 // prefer doubling capacity
35 if (b
->cap
* 2 >= cap
) {
39 char *newbuf
= realloc(b
->buf
, cap
);
44 static void bytebuffer_init(struct bytebuffer
*b
, int cap
) {
51 b
->buf
= malloc(cap
); // just assume malloc works always
55 static void bytebuffer_free(struct bytebuffer
*b
) {
60 static void bytebuffer_clear(struct bytebuffer
*b
) {
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
);
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
);
79 static void bytebuffer_flush(struct bytebuffer
*b
, int fd
) {
80 (void)write(fd
, b
->buf
, b
->len
);
84 static void bytebuffer_truncate(struct bytebuffer
*b
, int n
) {
89 const int nmove
= b
->len
- n
;
90 memmove(b
->buf
, b
->buf
+n
, nmove
);
94 /* term.inl --------------------------------------------------------------- */
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
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
,
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", "", "", "", "",
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
,
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
,
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", "", "", "", "",
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
,
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
},
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
)) {
193 return EUNSUPPORTED_TERM
;
196 static int init_term_builtin(void)
199 const char *term
= getenv("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
;
210 /* let's do some heuristic, maybe it's a compatible terminal */
211 if (try_compatible(term
, "xterm", xterm_keys
, xterm_funcs
) == 0)
213 if (try_compatible(term
, "rxvt", rxvt_unicode_keys
, rxvt_unicode_funcs
) == 0)
215 if (try_compatible(term
, "linux", linux_keys
, linux_funcs
) == 0)
217 if (try_compatible(term
, "Eterm", eterm_keys
, eterm_funcs
) == 0)
219 if (try_compatible(term
, "screen", screen_keys
, screen_funcs
) == 0)
221 if (try_compatible(term
, "tmux", screen_keys
, screen_funcs
) == 0)
223 /* let's assume that 'cygwin' is xterm compatible */
224 if (try_compatible(term
, "cygwin", xterm_keys
, xterm_funcs
) == 0)
228 return EUNSUPPORTED_TERM
;
231 //----------------------------------------------------------------------
233 //----------------------------------------------------------------------
235 static char *read_file(const char *file
) {
236 FILE *f
= fopen(file
, "rb");
241 if (fstat(fileno(f
), &st
) != 0) {
246 char *data
= malloc(st
.st_size
);
252 if (fread(data
, 1, st
.st_size
, f
) != (size_t)st
.st_size
) {
262 static char *terminfo_try_path(const char *path
, const char *term
) {
264 snprintf(tmp
, sizeof(tmp
), "%s/%c/%s", path
, term
[0], term
);
265 tmp
[sizeof(tmp
)-1] = '\0';
266 char *data
= read_file(tmp
);
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) {
279 const char *term
= getenv("TERM");
284 // if TERMINFO is set, no other directory should be searched
285 const char *terminfo
= getenv("TERMINFO");
287 return terminfo_try_path(terminfo
, term
);
290 // next, consider ~/.terminfo
291 const char *home
= getenv("HOME");
293 snprintf(tmp
, sizeof(tmp
), "%s/.terminfo", home
);
294 tmp
[sizeof(tmp
)-1] = '\0';
295 char *data
= terminfo_try_path(tmp
, term
);
300 // next, TERMINFO_DIRS
301 const char *dirs
= getenv("TERMINFO_DIRS");
303 snprintf(tmp
, sizeof(tmp
), "%s", dirs
);
304 tmp
[sizeof(tmp
)-1] = '\0';
305 char *dir
= strtok(tmp
, ":");
307 const char *cdir
= dir
;
308 if (strcmp(cdir
, "") == 0) {
309 cdir
= "/usr/share/terminfo";
311 char *data
= terminfo_try_path(cdir
, term
);
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);
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,
346 static int init_term(void) {
348 char *data
= load_terminfo();
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
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;
390 static void shutdown_term(void) {
391 if (init_from_terminfo
) {
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
399 for (i
= 0; i
< T_FUNCS_NUM
-2; i
++) {
400 free((void*)funcs
[i
]);
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
)
415 while (*s2
&& n
< len
) {
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
429 for (i
= 0; keys
[i
]; i
++) {
430 if (starts_with(buf
, len
, keys
[i
])) {
432 event
->key
= 0xFFFF-i
;
433 return strlen(keys
[i
]);
439 static bool extract_event(struct tb_event
*event
, struct bytebuffer
*inbuf
)
441 const char *buf
= inbuf
->buf
;
442 const int len
= inbuf
->len
;
446 if (buf
[0] == '\033') {
447 int n
= parse_escape_seq(event
, buf
, len
);
454 bytebuffer_truncate(inbuf
, n
);
457 // it's not escape sequence, then it's ALT or ESC,
459 if (inputmode
&TB_INPUT_ESC
) {
460 // if we're in escape mode, fill ESC event, pop
461 // buffer, return success
463 event
->key
= TB_KEY_ESC
;
465 bytebuffer_truncate(inbuf
, 1);
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 */
487 event
->key
= (uint16_t)buf
[0];
488 bytebuffer_truncate(inbuf
, 1);
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
);
499 bytebuffer_truncate(inbuf
, tb_utf8_char_length(buf
[0]));
503 // event isn't recognized, perhaps there is not enough bytes in utf8
508 /* -------------------------------------------------------- */
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
;
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_
)
568 return TB_EFAILED_TO_OPEN_TTY
;
571 if (init_term() < 0) {
573 return TB_EUNSUPPORTED_TERMINAL
;
576 if (pipe(winch_fds
) < 0) {
578 return TB_EPIPE_TRAP_ERROR
;
582 memset(&sa
, 0, sizeof(sa
));
583 sa
.sa_handler
= sigwinch_handler
;
585 sigaction(SIGWINCH
, &sa
, 0);
587 tcgetattr(inout
, &orig_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
);
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
]);
611 cellbuf_init(&back_buffer
, termw
, termh
);
612 cellbuf_init(&front_buffer
, termw
, termh
);
613 cellbuf_clear(&back_buffer
);
614 cellbuf_clear(&front_buffer
);
619 int tb_init_file(const char* name
){
620 return tb_init_fd(open(name
, O_RDWR
));
625 return tb_init_file("/dev/tty");
628 void tb_shutdown(void)
631 fputs("tb_shutdown() should not be called twice.", stderr
);
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
);
649 cellbuf_free(&back_buffer
);
650 cellbuf_free(&front_buffer
);
651 bytebuffer_free(&output_buffer
);
652 bytebuffer_free(&input_buffer
);
656 void tb_present(void)
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
) {
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
);
676 if (memcmp(back
, front
, sizeof(struct tb_cell
)) == 0) {
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
, ' ');
688 send_char(x
, y
, back
->ch
);
689 for (i
= 1; i
< w
; ++i
) {
690 front
= &CELL(&front_buffer
, x
+ i
, y
);
692 front
->fg
= back
->fg
;
693 front
->bg
= back
->bg
;
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
]);
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
)
722 if ((unsigned)y
>= (unsigned)back_buffer
.height
)
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
)
737 if (y
+ h
< 0 || y
>= back_buffer
.height
)
739 int xo
= 0, yo
= 0, ww
= w
, hh
= h
;
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
;
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
;
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
)
780 tv
.tv_sec
= timeout
/ 1000;
781 tv
.tv_usec
= (timeout
- (tv
.tv_sec
* 1000)) * 1000;
782 return wait_fill_event(event
, &tv
);
797 if (buffer_size_change_request
) {
799 buffer_size_change_request
= 0;
801 cellbuf_clear(&back_buffer
);
804 int tb_select_input_mode(int 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
;
816 if (mode
&TB_INPUT_MOUSE
) {
817 bytebuffer_puts(&output_buffer
, funcs
[T_ENTER_MOUSE
]);
818 bytebuffer_flush(&output_buffer
, inout
);
820 bytebuffer_puts(&output_buffer
, funcs
[T_EXIT_MOUSE
]);
821 bytebuffer_flush(&output_buffer
, inout
);
827 int tb_select_output_mode(int mode
)
834 void tb_set_clear_attributes(uint16_t fg
, uint16_t bg
)
840 /* -------------------------------------------------------- */
842 static int convertnum(uint32_t num
, char* buf
) {
846 buf
[l
++] = '0' + (num
% 10);
849 for(i
= 0; i
< l
/ 2; i
++) {
851 buf
[i
] = buf
[l
- 1 - i
];
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
) {
862 WRITE_LITERAL("\033[");
869 static void write_sgr(uint16_t fg
, uint16_t bg
) {
872 if (fg
== TB_DEFAULT
&& bg
== TB_DEFAULT
)
875 switch (outputmode
) {
878 case TB_OUTPUT_GRAYSCALE
:
879 WRITE_LITERAL("\033[");
880 if (fg
!= TB_DEFAULT
) {
881 WRITE_LITERAL("38;5;");
883 if (bg
!= TB_DEFAULT
) {
887 if (bg
!= TB_DEFAULT
) {
888 WRITE_LITERAL("48;5;");
893 case TB_OUTPUT_NORMAL
:
895 WRITE_LITERAL("\033[");
896 if (fg
!= TB_DEFAULT
) {
899 if (bg
!= TB_DEFAULT
) {
903 if (bg
!= TB_DEFAULT
) {
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
);
917 buf
->height
= height
;
920 static void cellbuf_resize(struct cellbuf
*buf
, int width
, int height
)
922 if (buf
->width
== width
&& buf
->height
== height
)
925 int oldw
= buf
->width
;
926 int oldh
= buf
->height
;
927 struct tb_cell
*oldcells
= buf
->cells
;
929 cellbuf_init(buf
, width
, height
);
932 int minw
= (width
< oldw
) ? width
: oldw
;
933 int minh
= (height
< oldh
) ? height
: oldh
;
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
);
945 static void cellbuf_clear(struct cellbuf
*buf
)
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
)
962 static void get_term_size(int *w
, int *h
)
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)
976 memset(&sz
, 0, sizeof(sz
));
978 ioctl(inout
, TIOCGWINSZ
, &sz
);
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
]);
994 switch (outputmode
) {
1001 fgcol
= fg
& 0xFF; if (fgcol
> 215) fgcol
= 7;
1002 bgcol
= bg
& 0xFF; if (bgcol
> 215) bgcol
= 0;
1007 case TB_OUTPUT_GRAYSCALE
:
1008 fgcol
= fg
& 0xFF; if (fgcol
> 23) fgcol
= 23;
1009 bgcol
= bg
& 0xFF; if (bgcol
> 23) bgcol
= 0;
1014 case TB_OUTPUT_NORMAL
:
1021 bytebuffer_puts(&output_buffer
, funcs
[T_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
);
1036 static void send_char(int x
, int y
, uint32_t c
)
1039 int bw
= tb_utf8_unicode_to_char(buf
, c
);
1040 if (x
-1 != lastx
|| y
!= lasty
)
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
1060 lastx
= LAST_COORD_INIT
;
1061 lasty
= LAST_COORD_INIT
;
1064 static void sigwinch_handler(int xxx
)
1068 (void)write(winch_fds
[1], &zzz
, sizeof(int));
1071 static void update_size(void)
1074 cellbuf_resize(&back_buffer
, termw
, termh
);
1075 cellbuf_resize(&front_buffer
, termw
, termh
);
1076 cellbuf_clear(&front_buffer
);
1080 static int read_up_to(int n
) {
1082 const int prevlen
= input_buffer
.len
;
1083 bytebuffer_resize(&input_buffer
, prevlen
+ n
);
1086 while (read_n
<= n
) {
1089 r
= read(inout
, input_buffer
.buf
+ prevlen
+ read_n
, n
- read_n
);
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
1099 // EAGAIN / EWOULDBLOCK shouldn't occur here
1100 assert(errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
);
1105 bytebuffer_resize(&input_buffer
, prevlen
+ read_n
);
1109 assert(!"unreachable");
1113 static int wait_fill_event(struct tb_event
*event
, struct timeval
*timeout
)
1116 #define ENOUGH_DATA_FOR_PARSING 64
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
))
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
);
1130 if (n
> 0 && extract_event(event
, &input_buffer
))
1133 // n == 0, or not enough data, let's go to select
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
);
1143 if (FD_ISSET(inout
, &events
)) {
1144 event
->type
= TB_EVENT_KEY
;
1145 n
= read_up_to(ENOUGH_DATA_FOR_PARSING
);
1152 if (extract_event(event
, &input_buffer
))
1155 if (FD_ISSET(winch_fds
[0], &events
)) {
1156 event
->type
= TB_EVENT_RESIZE
;
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
;