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