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