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