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