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