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