Import madtty, use it to deal with colors from now on as it needs to know what is...
[apps/madmutt.git] / lib-ui / madtty.c
1 /*
2     LICENSE INFORMATION:
3     This program is free software; you can redistribute it and/or
4     modify it under the terms of the GNU Lesser General Public
5     License (LGPL) as published by the Free Software Foundation.
6
7     Please refer to the COPYING file for more information.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12     General Public License for more details.
13
14     You should have received a copy of the GNU Lesser General Public
15     License along with this program; if not, write to the Free Software
16     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17
18     Copyright © 2004 Bruno T. C. de Oliveira
19     Copyright © 2006 Pierre Habouzit
20  */
21
22 #include <assert.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <pty.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <sys/types.h>
33 #include <termios.h>
34 #include <wchar.h>
35
36 #include "madtty.h"
37
38 #define IS_CONTROL(ch) !((ch) & 0xffffff60UL)
39
40 static int has_default = 0;
41
42 enum {
43     C0_NUL = 0x00,
44             C0_SOH, C0_STX, C0_ETX, C0_EOT, C0_ENQ, C0_ACK, C0_BEL,
45     C0_BS , C0_HT , C0_LF , C0_VT , C0_FF , C0_CR , C0_SO , C0_SI ,
46     C0_DLE, C0_DC1, C0_DC2, D0_DC3, C0_DC4, C0_NAK, C0_SYN, C0_ETB,
47     C0_CAN, C0_EM , C0_SUB, C0_ESC, C0_IS4, C0_IS3, C0_IS2, C0_IS1,
48 };
49
50 enum {
51     C1_40 = 0x40,
52             C1_41 , C1_BPH, C1_NBH, C1_44 , C1_NEL, C1_SSA, C1_ESA,
53     C1_HTS, C1_HTJ, C1_VTS, C1_PLD, C1_PLU, C1_RI , C1_SS2, C1_SS3,
54     C1_DCS, C1_PU1, C1_PU2, C1_STS, C1_CCH, C1_MW , C1_SPA, C1_EPA,
55     C1_SOS, C1_59 , C1_SCI, C1_CSI, CS_ST , C1_OSC, C1_PM , C1_APC,
56 };
57
58 enum {
59     CSI_ICH = 0x40,
60              CSI_CUU, CSI_CUD, CSI_CUF, CSI_CUB, CSI_CNL, CSI_CPL, CSI_CHA,
61     CSI_CUP, CSI_CHT, CSI_ED , CSI_EL , CSI_IL , CSI_DL , CSI_EF , CSI_EA ,
62     CSI_DCH, CSI_SEE, CSI_CPR, CSI_SU , CSI_SD , CSI_NP , CSI_PP , CSI_CTC,
63     CSI_ECH, CSI_CVT, CSI_CBT, CSI_SRS, CSI_PTX, CSI_SDS, CSI_SIMD, CSI_5F,
64     CSI_HPA, CSI_HPR, CSI_REP, CSI_DA , CSI_VPA, CSI_VPR, CSI_HVP, CSI_TBC,
65     CSI_SM , CSI_MC , CSI_HPB, CSI_VPB, CSI_RM , CSI_SGR, CSI_DSR, CSI_DAQ,
66     CSI_70 , CSI_71 , CSI_72 , CSI_73 , CSI_74 , CSI_75 , CSI_76 , CSI_77 ,
67     CSI_78 , CSI_79 , CSI_7A , CSI_7B , CSI_7C , CSI_7D , CSI_7E , CSI_7F
68 };
69
70 struct madtty_t {
71     int   pty;
72     pid_t childpid;
73
74     /* flags */
75     unsigned seen_input : 1;
76     unsigned insert     : 1;
77     unsigned escaped    : 1;
78     unsigned graphmode  : 1;
79     unsigned curshid    : 1;
80
81     /* geometry */
82     int rows, cols;
83     unsigned curattrs;
84
85     struct t_row_t *lines;
86     struct t_row_t *scroll_top;
87     struct t_row_t *scroll_bot;
88
89     /* cursor */
90     struct t_row_t *curs_row;
91     int curs_col, curs_srow, curs_scol;
92
93     /* buffers and parsing state */
94     mbstate_t ps;
95     char rbuf[BUFSIZ];
96     char ebuf[BUFSIZ];
97     int  rlen, elen;
98 };
99
100 typedef struct t_row_t {
101     wchar_t  *text;
102     uint16_t *attr;
103     unsigned dirty : 1;
104 } t_row_t;
105
106 static char const * const keytable[KEY_MAX+1] = {
107     ['\n']          = "\r",
108     [KEY_UP]        = "\e[A",
109     [KEY_DOWN]      = "\e[B",
110     [KEY_RIGHT]     = "\e[C",
111     [KEY_LEFT]      = "\e[D",
112     [KEY_BACKSPACE] = "\177",
113     [KEY_HOME]      = "\e[1~",
114     [KEY_IC]        = "\e[2~",
115     [KEY_DC]        = "\e[3~",
116     [KEY_END]       = "\e[4~",
117     [KEY_PPAGE]     = "\e[5~",
118     [KEY_NPAGE]     = "\e[6~",
119     [KEY_SUSPEND]   = "\x1A",  /* Ctrl+Z gets mapped to this */
120     [KEY_F(1)]      = "\e[[A",
121     [KEY_F(2)]      = "\e[[B",
122     [KEY_F(3)]      = "\e[[C",
123     [KEY_F(4)]      = "\e[[D",
124     [KEY_F(5)]      = "\e[[E",
125     [KEY_F(6)]      = "\e[17~",
126     [KEY_F(7)]      = "\e[18~",
127     [KEY_F(8)]      = "\e[19~",
128     [KEY_F(9)]      = "\e[20~",
129     [KEY_F(10)]     = "\e[21~",
130 };
131
132 static void t_row_set(t_row_t *row, int start, int len, uint16_t attr)
133 {
134     row->dirty = true;
135     wmemset(row->text + start, 0, len);
136     for (int i = start; i < len + start; i++) {
137         row->attr[i] = attr;
138     }
139 }
140
141 static void t_row_roll(t_row_t *start, t_row_t *end, int count)
142 {
143     int n = end - start;
144
145     count %= n;
146     if (count < 0)
147         count += n;
148
149     if (count) {
150         t_row_t *buf = alloca(count * sizeof(t_row_t));
151
152         memcpy(buf, start, count * sizeof(t_row_t));
153         memmove(start, start + count, (n - count) * sizeof(t_row_t));
154         memcpy(end - count, buf, count * sizeof(t_row_t));
155         for (t_row_t *row = start; row < end; row++) {
156             row->dirty = true;
157         }
158     }
159 }
160
161 static void clamp_cursor_to_bounds(madtty_t *t)
162 {
163     if (t->curs_row < t->lines) {
164         t->curs_row = t->lines;
165     }
166     if (t->curs_row >= t->lines + t->rows) {
167         t->curs_row = t->lines + t->rows - 1;
168     }
169
170     if (t->curs_col < 0) {
171         t->curs_col = 0;
172     }
173     if (t->curs_col >= t->cols) {
174         t->curs_col = t->cols - 1;
175     }
176 }
177
178 static void cursor_line_down(madtty_t *t)
179 {
180     t->curs_row++;
181     if (t->curs_row < t->scroll_bot)
182         return;
183
184     t->curs_row = t->scroll_bot - 1;
185     t_row_roll(t->scroll_top, t->scroll_bot, 1);
186     t_row_set(t->curs_row, 0, t->cols, 0);
187 }
188
189 __attribute__((const))
190 static uint16_t build_attrs(unsigned curattrs)
191 {
192     return ((curattrs & ~A_COLOR) | COLOR_PAIR(curattrs & 0xff))
193         >> NCURSES_ATTR_SHIFT;
194 }
195
196 static void new_escape_sequence(madtty_t *t)
197 {
198     t->escaped = true;
199     t->elen    = 0;
200     t->ebuf[0] = '\0';
201 }
202
203 static void cancel_escape_sequence(madtty_t *t)
204 {
205     t->escaped = false;
206     t->elen    = 0;
207     t->ebuf[0] = '\0';
208 }
209
210 static bool is_valid_csi_ender(int c)
211 {
212     return (c >= 'a' && c <= 'z')
213         || (c >= 'A' && c <= 'Z')
214         || (c == '@' || c == '`');
215 }
216
217 /* interprets a 'set attribute' (SGR) CSI escape sequence */
218 static void interpret_csi_SGR(madtty_t *t, int param[], int pcount)
219 {
220     int i;
221
222     if (pcount == 0) {
223         /* special case: reset attributes */
224         t->curattrs = A_NORMAL;
225         return;
226     }
227
228     for (i = 0; i < pcount; i++) {
229         switch (param[i]) {
230 #define CASE(x, op)  case x: op; break
231             CASE(0,  t->curattrs = A_NORMAL);
232             CASE(1,  t->curattrs |= A_BOLD);
233             CASE(4,  t->curattrs |= A_UNDERLINE);
234             CASE(5,  t->curattrs |= A_BLINK);
235             CASE(6,  t->curattrs |= A_BLINK);
236             CASE(7,  t->curattrs |= A_REVERSE);
237             CASE(8,  t->curattrs |= A_INVIS);
238             CASE(22, t->curattrs &= ~A_BOLD);
239             CASE(24, t->curattrs &= ~A_UNDERLINE);
240             CASE(25, t->curattrs &= ~A_BLINK);
241             CASE(27, t->curattrs &= ~A_REVERSE);
242             CASE(28, t->curattrs &= ~A_INVIS);
243
244           case 30 ... 37: /* fg */
245             if (has_default) {
246                 t->curattrs &= ~0xf0;
247                 t->curattrs |= (param[i] + 1 - 30) << 4;
248             } else {
249                 t->curattrs &= ~070;
250                 t->curattrs |= (7 - (param[i] - 30)) << 3;
251             }
252             break;
253
254           case 39:
255             t->curattrs &= has_default ? ~0xf0 : ~070;
256             break;
257
258           case 40 ... 47: /* bg */
259             if (has_default) {
260                 t->curattrs &= ~0x0f;
261                 t->curattrs |= (param[i] + 1 - 40);
262             } else {
263                 t->curattrs &= ~007;
264                 t->curattrs |= (param[i] - 40);
265             }
266             break;
267
268           case 49:
269             t->curattrs &= has_default ? ~0x0f : ~007;
270             break;
271
272           default:
273             break;
274         }
275     }
276 }
277
278 /* interprets an 'erase display' (ED) escape sequence */
279 static void interpret_csi_ED(madtty_t *t, int param[], int pcount)
280 {
281     t_row_t *row, *start, *end;
282     attr_t attr = build_attrs(t->curattrs);
283
284     /* decide range */
285     if (pcount && param[0] == 2) {
286         start = t->lines;
287         end   = t->lines + t->rows;
288     } else
289     if (pcount && param[0] == 1) {
290         start = t->lines;
291         end   = t->curs_row;
292         t_row_set(t->curs_row, 0, t->curs_col + 1, attr);
293     } else {
294         t_row_set(t->curs_row, t->curs_col,
295                      t->cols - t->curs_col, attr);
296         start = t->curs_row + 1;
297         end   = t->lines + t->rows;
298     }
299
300     for (row = start; row < end; row++) {
301         t_row_set(row, 0, t->cols, attr);
302     }
303 }
304
305 /* interprets a 'move cursor' (CUP) escape sequence */
306 static void interpret_csi_CUP(madtty_t *t, int param[], int pcount)
307 {
308     if (pcount == 0) {
309         /* special case */
310         t->curs_row = t->lines;
311         t->curs_col = 0;
312         return;
313     } else
314     if (pcount < 2) {
315         return;  /* malformed */
316     }
317
318     t->curs_row = t->lines + param[0] - 1;
319     t->curs_col = param[1] - 1;
320
321     clamp_cursor_to_bounds(t);
322 }
323
324 /* Interpret the 'relative mode' sequences: CUU, CUD, CUF, CUB, CNL,
325  * CPL, CHA, HPR, VPA, VPR, HPA */
326 static void
327 interpret_csi_C(madtty_t *t, char verb, int param[], int pcount)
328 {
329     int n = (pcount && param[0] > 0) ? param[0] : 1;
330
331     switch (verb) {
332       case 'A':           t->curs_row -= n; break;
333       case 'B': case 'e': t->curs_row += n; break;
334       case 'C': case 'a': t->curs_col += n; break;
335       case 'D':           t->curs_col -= n; break;
336       case 'E':           t->curs_row += n; t->curs_col = 0; break;
337       case 'F':           t->curs_row -= n; t->curs_col = 0; break;
338       case 'G': case '`': t->curs_col  = param[0] - 1; break;
339       case 'd':           t->curs_row  = t->lines + param[0] - 1; break;
340     }
341
342     clamp_cursor_to_bounds(t);
343 }
344
345 /* Interpret the 'erase line' escape sequence */
346 static void interpret_csi_EL(madtty_t *t, int param[], int pcount)
347 {
348     attr_t attr = build_attrs(t->curattrs);
349
350     switch (pcount ? param[0] : 0) {
351       case 1:
352         t_row_set(t->curs_row, 0, t->curs_col + 1, attr);
353         break;
354       case 2:
355         t_row_set(t->curs_row, 0, t->cols, attr);
356         break;
357       default:
358         t_row_set(t->curs_row, t->curs_col, t->cols - t->curs_col,
359                      attr);
360         break;
361     }
362 }
363
364 /* Interpret the 'insert blanks' sequence (ICH) */
365 static void interpret_csi_ICH(madtty_t *t, int param[], int pcount)
366 {
367     t_row_t *row = t->curs_row;
368     int n = (pcount && param[0] > 0) ? param[0] : 1;
369     int i;
370
371     if (t->curs_col + n > t->cols) {
372         n = t->cols - t->curs_col;
373     }
374
375     for (i = t->cols - 1; i >= t->curs_col + n; i--) {
376         row->text[i] = row->text[i - n];
377         row->attr[i] = row->attr[i - n];
378     }
379
380     t_row_set(row, t->curs_col, n, build_attrs(t->curattrs));
381 }
382
383 /* Interpret the 'delete chars' sequence (DCH) */
384 static void interpret_csi_DCH(madtty_t *t, int param[], int pcount)
385 {
386     t_row_t *row = t->curs_row;
387     int n = (pcount && param[0] > 0) ? param[0] : 1;
388     int i;
389
390     if (t->curs_col + n > t->cols) {
391         n = t->cols - t->curs_col;
392     }
393
394     for (i = t->curs_col; i < t->cols - n; i++) {
395         row->text[i] = row->text[i + n];
396         row->attr[i] = row->attr[i + n];
397     }
398
399     t_row_set(row, t->cols - n, n, build_attrs(t->curattrs));
400 }
401
402 /* Interpret a 'scroll reverse' (SR) */
403 static void interpret_csi_SR(madtty_t *t)
404 {
405     t_row_roll(t->scroll_top, t->scroll_bot, -1);
406     t_row_set(t->scroll_top, 0, t->cols, build_attrs(t->curattrs));
407 }
408
409 /* Interpret an 'insert line' sequence (IL) */
410 static void interpret_csi_IL(madtty_t *t, int param[], int pcount)
411 {
412     int n = (pcount && param[0] > 0) ? param[0] : 1;
413
414     if (t->curs_row + n >= t->scroll_bot) {
415         for (t_row_t *row = t->curs_row; row < t->scroll_bot; row++) {
416             t_row_set(row, 0, t->cols, build_attrs(t->curattrs));
417         }
418     } else {
419         t_row_roll(t->curs_row, t->scroll_bot, -n);
420         for (t_row_t *row = t->curs_row; row < t->curs_row + n; row++) {
421             t_row_set(row, 0, t->cols, build_attrs(t->curattrs));
422         }
423     }
424 }
425
426 /* Interpret a 'delete line' sequence (DL) */
427 static void interpret_csi_DL(madtty_t *t, int param[], int pcount)
428 {
429     int n = (pcount && param[0] > 0) ? param[0] : 1;
430
431     if (t->curs_row + n >= t->scroll_bot) {
432         for (t_row_t *row = t->curs_row; row < t->scroll_bot; row++) {
433             t_row_set(row, 0, t->cols, build_attrs(t->curattrs));
434         }
435     } else {
436         t_row_roll(t->curs_row, t->scroll_bot, n);
437         for (t_row_t *row = t->scroll_bot - n; row < t->scroll_bot; row++) {
438             t_row_set(row, 0, t->cols, build_attrs(t->curattrs));
439         }
440     }
441 }
442
443 /* Interpret an 'erase characters' (ECH) sequence */
444 static void interpret_csi_ECH(madtty_t *t, int param[], int pcount)
445 {
446     int n = (pcount && param[0] > 0) ? param[0] : 1;
447
448     if (t->curs_col + n < t->cols) {
449         n = t->cols - t->curs_col;
450     }
451     t_row_set(t->curs_row, t->curs_col, n, build_attrs(t->curattrs));
452 }
453
454 /* Interpret a 'set scrolling region' (DECSTBM) sequence */
455 static void interpret_csi_DECSTBM(madtty_t *t, int param[], int pcount)
456 {
457     int new_top, new_bot;
458
459     switch (pcount) {
460       case 0:
461         t->scroll_top = t->lines;
462         t->scroll_bot = t->lines + t->rows;
463         break;
464       default:
465         return; /* malformed */
466
467       case 2:
468         new_top = param[0] - 1;
469         new_bot = param[1];
470
471         /* clamp to bounds */
472         if (new_top < 0)
473             new_top = 0;
474         if (new_top >= t->rows)
475             new_top = t->rows - 1;
476         if (new_bot < 0)
477             new_bot = 0;
478         if (new_bot >= t->rows)
479             new_bot = t->rows;
480
481         /* check for range validity */
482         if (new_top < new_bot) {
483             t->scroll_top = t->lines + new_top;
484             t->scroll_bot = t->lines + new_bot;
485         }
486         break;
487     }
488 }
489
490 static void es_interpret_csi(madtty_t *t)
491 {
492     static int csiparam[BUFSIZ];
493     int param_count = 0;
494     const char *p = t->ebuf + 1;
495     char verb = t->ebuf[t->elen - 1];
496
497     p += t->ebuf[1] == '?'; /* CSI private mode */
498
499     /* parse numeric parameters */
500     while (isdigit((unsigned char)*p) || *p == ';') {
501         if (*p == ';') {
502             if (param_count >= (int)sizeof(csiparam))
503                 return; /* too long! */
504             csiparam[param_count++] = 0;
505         } else {
506             if (param_count == 0) csiparam[param_count++] = 0;
507             csiparam[param_count - 1] *= 10;
508             csiparam[param_count - 1] += *p - '0';
509         }
510
511         p++;
512     }
513
514     if (t->ebuf[1] == '?') {
515         switch (verb) {
516           case 'l':
517             if (csiparam[0] == 25)
518                 t->curshid = true;
519             break;
520
521           case 'h':
522             if (csiparam[0] == 25)
523                 t->curshid = false;
524             break;
525         }
526     }
527
528     /* delegate handling depending on command character (verb) */
529     switch (verb) {
530       case 'h':
531         if (param_count == 1 && csiparam[0] == 4) /* insert mode */
532             t->insert = true;
533         break;
534       case 'l':
535         if (param_count == 1 && csiparam[0] == 4) /* replace mode */
536             t->insert = false;
537         break;
538       case 'm': /* it's a 'set attribute' sequence */
539         interpret_csi_SGR(t, csiparam, param_count); break;
540       case 'J': /* it's an 'erase display' sequence */
541         interpret_csi_ED(t, csiparam, param_count); break;
542       case 'H': case 'f': /* it's a 'move cursor' sequence */
543         interpret_csi_CUP(t, csiparam, param_count); break;
544       case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
545       case 'e': case 'a': case 'd': case '`':
546         /* it is a 'relative move' */
547         interpret_csi_C(t, verb, csiparam, param_count); break;
548       case 'K': /* erase line */
549         interpret_csi_EL(t, csiparam, param_count); break;
550       case '@': /* insert characters */
551         interpret_csi_ICH(t, csiparam, param_count); break;
552       case 'P': /* delete characters */
553         interpret_csi_DCH(t, csiparam, param_count); break;
554       case 'L': /* insert lines */
555         interpret_csi_IL(t, csiparam, param_count); break;
556       case 'M': /* delete lines */
557         interpret_csi_DL(t, csiparam, param_count); break;
558       case 'X': /* erase chars */
559         interpret_csi_ECH(t, csiparam, param_count); break;
560       case 'r': /* set scrolling region */
561         interpret_csi_DECSTBM(t, csiparam, param_count); break;
562       case 's': /* save cursor location */
563         t->curs_srow = t->curs_row - t->lines;
564         t->curs_scol = t->curs_col;
565         break;
566       case 'u': /* restore cursor location */
567         t->curs_row = t->lines + t->curs_srow;
568         t->curs_col = t->curs_scol;
569         clamp_cursor_to_bounds(t);
570         break;
571       default:
572         break;
573     }
574 }
575
576 static void try_interpret_escape_seq(madtty_t *t)
577 {
578     char lastchar  = t->ebuf[t->elen-1];
579
580     switch (*t->ebuf) {
581       case '\0':
582         return;
583
584       case 'M':
585         interpret_csi_SR(t);
586         cancel_escape_sequence(t);
587         return;
588
589       case '(':
590       case ')':
591         if (t->elen == 2)
592             goto cancel;
593         break;
594
595       case ']': /* xterm thing */
596         if (lastchar == '\a')
597             goto cancel;
598         break;
599
600       default:
601         goto cancel;
602
603       case '[':
604         if (is_valid_csi_ender(lastchar)) {
605             es_interpret_csi(t);
606             cancel_escape_sequence(t);
607             return;
608         }
609         break;
610     }
611
612     if (t->elen + 1 >= (int)sizeof(t->ebuf)) {
613 cancel:
614         cancel_escape_sequence(t);
615     }
616 }
617
618 static void madtty_process_nonprinting(madtty_t *t, wchar_t wc)
619 {
620     switch (wc) {
621       case C0_ESC:
622         new_escape_sequence(t);
623         break;
624
625       case C0_BEL:
626         /* do nothing for now... maybe a visual bell would be nice? */
627         break;
628
629       case C0_BS:
630         if (t->curs_col > 0)
631             t->curs_col--;
632         break;
633
634       case C0_HT: /* tab */
635         t->curs_col = (t->curs_col + 8) & ~7;
636         if (t->curs_col >= t->cols)
637             t->curs_col = t->cols - 1;
638         break;
639
640       case C0_CR:
641         t->curs_col = 0;
642         break;
643
644       case C0_VT:
645       case C0_FF:
646       case C0_LF:
647         cursor_line_down(t);
648         break;
649
650       case C0_SO:               /* shift out - acs */
651         t->graphmode = true;
652         break;
653       case C0_SI:               /* shift in - acs */
654         t->graphmode = false;
655         break;
656     }
657 }
658
659 // vt100 special graphics and line drawing
660 // 5f-7e standard vt100
661 // 40-5e rxvt extension for extra curses acs chars
662 static uint16_t const vt100_0[62] = { // 41 .. 7e
663             0x2191, 0x2193, 0x2192, 0x2190, 0x2588, 0x259a, 0x2603, // 41-47 hi mr. snowman!
664          0,      0,      0,      0,      0,      0,      0,      0, // 48-4f
665          0,      0,      0,      0,      0,      0,      0,      0, // 50-57
666          0,      0,      0,      0,      0,      0,      0, 0x0020, // 58-5f
667     0x25c6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, // 60-67
668     0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, // 68-6f
669     0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, // 70-77
670     0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7,         // 78-7e
671 };
672
673 static void madtty_putc(madtty_t *t, wchar_t wc)
674 {
675     int width = 0;
676
677     if (!t->seen_input) {
678         t->seen_input = 1;
679         kill(-t->childpid, SIGWINCH);
680     }
681
682     if (t->escaped) {
683         assert (t->elen + 1 < (int)sizeof(t->ebuf));
684         t->ebuf[t->elen]   = wc;
685         t->ebuf[++t->elen] = '\0';
686         try_interpret_escape_seq(t);
687     } else if (IS_CONTROL(wc)) {
688         madtty_process_nonprinting(t, wc);
689     } else {
690         t_row_t *tmp;
691
692         if (t->graphmode) {
693             if (wc >= 0x41 && wc <= 0x7e && vt100_0[wc - 0x41]) {
694                 wc = vt100_0[wc - 0x41];
695             }
696             width = 1;
697         } else {
698             width = wcwidth(wc) ?: 1;
699         }
700
701         if (width == 2 && t->curs_col == t->cols - 1) {
702             tmp = t->curs_row;
703             tmp->dirty = true;
704             tmp->text[t->curs_col] = 0;
705             tmp->attr[t->curs_col] = build_attrs(t->curattrs);
706             t->curs_col++;
707         }
708
709         if (t->curs_col >= t->cols) {
710             t->curs_col = 0;
711             cursor_line_down(t);
712         }
713
714         tmp = t->curs_row;
715         tmp->dirty = true;
716
717         if (t->insert) {
718             wmemmove(tmp->text + t->curs_col + width, tmp->text + t->curs_col,
719                      (t->cols - t->curs_col - width));
720             memmove(tmp->attr + t->curs_col + width, tmp->attr + t->curs_col,
721                     (t->cols - t->curs_col - width) * sizeof(tmp->attr[0]));
722         }
723
724         tmp->text[t->curs_col] = wc;
725         tmp->attr[t->curs_col] = build_attrs(t->curattrs);
726         t->curs_col++;
727         if (width == 2) {
728             tmp->text[t->curs_col] = 0;
729             tmp->attr[t->curs_col] = build_attrs(t->curattrs);
730             t->curs_col++;
731         }
732     }
733 }
734
735 int madtty_process(madtty_t *t)
736 {
737     int res, pos = 0;
738
739     if (t->pty < 0) {
740         errno = EINVAL;
741         return -1;
742     }
743
744     res = read(t->pty, t->rbuf + t->rlen, sizeof(t->rbuf) - t->rlen);
745     if (res < 0)
746         return -1;
747
748     t->rlen += res;
749     while (pos < t->rlen) {
750         wchar_t wc;
751         ssize_t len;
752
753         len = (ssize_t)mbrtowc(&wc, t->rbuf + pos, t->rlen - pos, &t->ps);
754         if (len == -2) {
755             t->rlen -= pos;
756             memmove(t->rbuf, t->rbuf + pos, t->rlen);
757             return 0;
758         }
759
760         if (len == -1) {
761             len = 1;
762             wc  = t->rbuf[pos];
763         }
764
765         pos += len ? len : 1;
766         madtty_putc(t, wc);
767     }
768
769     t->rlen -= pos;
770     memmove(t->rbuf, t->rbuf + pos, t->rlen);
771     return 0;
772 }
773
774 madtty_t *madtty_create(int rows, int cols)
775 {
776     madtty_t *t;
777     int i;
778
779     if (rows <= 0 || cols <= 0)
780         return NULL;
781
782     t = (madtty_t*)calloc(sizeof(madtty_t), 1);
783     if (!t)
784         return NULL;
785
786     /* record dimensions */
787     t->rows = rows;
788     t->cols = cols;
789
790     /* default mode is replace */
791     t->insert = false;
792
793     /* create the cell matrix */
794     t->lines = (t_row_t*)calloc(sizeof(t_row_t), t->rows);
795     for (i = 0; i < t->rows; i++) {
796         t->lines[i].text = (wchar_t *)calloc(sizeof(wchar_t), t->cols);
797         t->lines[i].attr = (uint16_t *)calloc(sizeof(uint16_t), t->cols);
798     }
799
800     t->pty = -1;  /* no pty for now */
801
802     /* initialization of other public fields */
803     t->curs_row = t->lines;
804     t->curs_col = 0;
805     t->curattrs = A_NORMAL;  /* white text over black background */
806
807     /* initial scrolling area is the whole window */
808     t->scroll_top = t->lines;
809     t->scroll_bot = t->lines + t->rows;
810
811     return t;
812 }
813
814 void madtty_resize(madtty_t *t, int rows, int cols)
815 {
816     struct winsize ws = { .ws_row = rows, .ws_col = cols };
817     t_row_t *lines = t->lines;
818
819     if (rows <= 0 || cols <= 0)
820         return;
821
822     if (t->rows != rows) {
823         while (t->rows > rows) {
824             free(lines[t->rows - 1].text);
825             free(lines[t->rows - 1].attr);
826             t->rows--;
827         }
828
829         lines = realloc(lines, sizeof(t_row_t) * rows);
830     }
831
832     if (t->cols != cols) {
833         for (int row = 0; row < t->rows; row++) {
834             lines[row].text = realloc(lines[row].text, sizeof(wchar_t) * cols);
835             lines[row].attr = realloc(lines[row].attr, sizeof(uint16_t) * cols);
836             if (t->cols < cols)
837                 t_row_set(lines + row, t->cols, cols - t->cols, 0);
838         }
839         t->cols = cols;
840     }
841
842     while (t->rows < rows) {
843         lines[t->rows].text = (wchar_t *)calloc(sizeof(wchar_t), cols);
844         lines[t->rows].attr = (uint16_t *)calloc(sizeof(uint16_t), cols);
845         t->rows++;
846     }
847
848     t->curs_row   += lines - t->lines;
849     t->scroll_top += lines - t->lines;
850     t->scroll_bot += lines - t->lines;
851     if (t->scroll_bot > lines + t->rows)
852         t->scroll_bot = lines + t->rows;
853     t->lines = lines;
854     clamp_cursor_to_bounds(t);
855     ioctl(t->pty, TIOCSWINSZ, &ws);
856     kill(-t->childpid, SIGWINCH);
857 }
858
859 void madtty_destroy(madtty_t *t)
860 {
861     int i;
862     if (!t)
863         return;
864
865     for (i = 0; i < t->rows; i++) {
866         free(t->lines[i].text);
867         free(t->lines[i].attr);
868     }
869     free(t->lines);
870     free(t);
871 }
872
873 void madtty_draw(madtty_t *t, WINDOW *win, int srow, int scol)
874 {
875     curs_set(0);
876     for (int i = 0; i < t->rows; i++) {
877         t_row_t *row = t->lines + i;
878
879
880         if (!row->dirty)
881             continue;
882
883         wmove(win, srow + i, scol);
884         for (int j = 0; j < t->cols; j++) {
885             if (!j || row->attr[j] != row->attr[j - 1])
886                 wattrset(win, (attr_t)row->attr[j] << NCURSES_ATTR_SHIFT);
887             if (row->text[j] >= 128) {
888                 char buf[MB_CUR_MAX + 1];
889                 int len;
890
891                 len = wcrtomb(buf, row->text[j], NULL);
892                 waddnstr(win, buf, len);
893                 if (wcwidth(row->text[j]) > 1)
894                     j++;
895             } else {
896                 waddch(win, row->text[j] > ' ' ? row->text[j] : ' ');
897             }
898         }
899         row->dirty = false;
900     }
901
902     wmove(win, srow + t->curs_row - t->lines, scol + t->curs_col);
903     curs_set(!t->curshid);
904 }
905
906 /******************************************************/
907
908 pid_t madtty_forkpty(madtty_t *t, const char *p, const char *argv[], int *pty)
909 {
910     struct winsize ws;
911     pid_t pid;
912
913     ws.ws_row    = t->rows;
914     ws.ws_col    = t->cols;
915     ws.ws_xpixel = ws.ws_ypixel = 0;
916
917     pid = forkpty(&t->pty, NULL, NULL, &ws);
918     if (pid < 0)
919         return -1;
920
921     if (pid == 0) {
922         setsid();
923         setenv("TERM", "rxvt", 1);
924         execv(p, (char *const*)argv);
925         fprintf(stderr, "\nexecv() failed.\nCommand: '%s'\n", argv[0]);
926         exit(1);
927     }
928
929     if (pty)
930         *pty = t->pty;
931     return t->childpid = pid;
932 }
933
934 int madtty_getpty(madtty_t *t)
935 {
936     return t->pty;
937 }
938
939 void madtty_keypress(madtty_t *t, int keycode)
940 {
941     char c = (char)keycode;
942     const char *buf;
943     int len;
944
945     if (keycode >= 0 && keycode < KEY_MAX && keytable[keycode]) {
946         buf = keytable[keycode];
947         len = strlen(keytable[keycode]);
948     } else {
949         buf = &c;
950         len = 1;
951     }
952
953     while (len > 0) {
954         int res = write(t->pty, buf, len);
955         if (res < 0 && errno != EAGAIN && errno != EINTR)
956             return;
957
958         buf += res;
959         len -= res;
960     }
961 }
962
963 void madtty_init_colors(void)
964 {
965     if (COLORS > 8) {
966         use_default_colors();
967         assume_default_colors(-1, -1);
968         has_default = 1;
969
970         for (int bg = -1; bg < 8; bg++) {
971             for (int fg = -1; fg < 8; fg++) {
972                 init_pair((fg + 1) * 16 + bg + 1, fg, bg);
973             }
974         }
975     } else {
976         for (int bg = 0; bg < 8; bg++) {
977             for (int fg = 0; fg < 8; fg++) {
978                 init_pair((7 - fg) * 8 + bg, fg, bg);
979             }
980         }
981     }
982 }
983
984 int madtty_color_pair(int fg, int bg)
985 {
986     if (fg < -1)
987         fg = -1;
988     if (bg < -1)
989         bg = -1;
990     return COLOR_PAIR(has_default ? (fg + 1) * 16 + bg + 1 : (7 - fg) * 8 + bg);
991 }