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