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