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