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