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