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