many rewrites, let rote_vt_write be a more simple wrapper around write
[apps/madtty.git] / madtty / inject.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 <string.h>
23 #include <stdio.h>
24 #include <ctype.h>
25
26 #include "madtty.h"
27 #include "madtty_priv.h"
28
29 #define MAX_CSI_ES_PARAMS 32
30
31 static inline void clamp_cursor_to_bounds(RoteTerm *rt)
32 {
33     if (rt->crow < 0) {
34         rt->curpos_dirty = true;
35         rt->crow = 0;
36     }
37     if (rt->ccol < 0) {
38         rt->curpos_dirty = true;
39         rt->ccol = 0;
40     }
41
42     if (rt->crow >= rt->rows) {
43         rt->curpos_dirty = true;
44         rt->crow = rt->rows - 1;
45     }
46     if (rt->ccol >= rt->cols) {
47         rt->curpos_dirty = true;
48         rt->ccol = rt->cols - 1;
49     }
50 }
51
52 static void cursor_line_down(RoteTerm *rt)
53 {
54     int i;
55
56     rt->crow++;
57     rt->curpos_dirty = true;
58     if (rt->crow <= rt->pd->scrollbottom)
59         return;
60
61     /* must scroll the scrolling region up by 1 line, and put cursor on
62      * last line of it */
63     rt->crow = rt->pd->scrollbottom;
64
65     for (i = rt->pd->scrolltop; i < rt->pd->scrollbottom; i++) {
66         rt->line_dirty[i] = true;
67         memcpy(rt->cells[i], rt->cells[i+1], sizeof(RoteCell) * rt->cols);
68     }
69
70     rt->line_dirty[rt->pd->scrollbottom] = true;
71
72     /* clear last row of the scrolling region */
73     for (i = 0; i < rt->cols; i++) {
74         rt->cells[rt->pd->scrollbottom][i].ch   = 0x20;
75         rt->cells[rt->pd->scrollbottom][i].attr = 0x70;
76     }
77 }
78
79 static void cursor_line_up(RoteTerm *rt)
80 {
81     int i;
82
83     rt->crow--;
84     rt->curpos_dirty = true;
85     if (rt->crow >= rt->pd->scrolltop)
86         return;
87
88     /* must scroll the scrolling region up by 1 line, and put cursor on
89      * first line of it */
90     rt->crow = rt->pd->scrolltop;
91
92     for (i = rt->pd->scrollbottom; i > rt->pd->scrolltop; i--) {
93         rt->line_dirty[i] = true;
94         memcpy(rt->cells[i], rt->cells[i-1], sizeof(RoteCell) * rt->cols);
95     }
96
97     rt->line_dirty[rt->pd->scrolltop] = true;
98
99     /* clear first row of the scrolling region */
100     for (i = 0; i < rt->cols; i++) {
101         rt->cells[rt->pd->scrolltop][i].ch   = 0x20;
102         rt->cells[rt->pd->scrolltop][i].attr = 0x70;
103     }
104 }
105
106 static inline void put_normal_char(RoteTerm *rt, int c)
107 {
108     if (rt->ccol >= rt->cols) {
109         rt->ccol = 0;
110         cursor_line_down(rt);
111     }
112
113     if (rt->insert) {
114         int i;
115
116         for(i = rt->cols - 1; i >= rt->ccol+1; i--) {
117             rt->cells[rt->crow][i] = rt->cells[rt->crow][i-1];
118         }
119     }
120
121     rt->cells[rt->crow][rt->ccol].ch   = c;
122     rt->cells[rt->crow][rt->ccol].attr = rt->curattr;
123     rt->ccol++;
124
125     rt->line_dirty[rt->crow] = true;
126     rt->curpos_dirty = true;
127 }
128
129 static inline void put_graphmode_char(RoteTerm *rt, int c)
130 {
131     char nc;
132     /* do some very pitiful translation to regular ascii chars */
133     switch (c) {
134       case 'j': case 'k': case 'l': case 'm': case 'n': case 't':
135       case 'u': case 'v': case 'w':
136         nc = '+'; break;
137       case 'x':
138         nc = '|'; break;
139       default:
140         nc = '%';
141     }
142
143     put_normal_char(rt, nc);
144 }
145
146 static inline void new_escape_sequence(RoteTerm *rt)
147 {
148     rt->pd->escaped = true;
149     rt->pd->esbuf_len = 0;
150     rt->pd->esbuf[0] = '\0';
151 }
152
153 static inline void cancel_escape_sequence(RoteTerm *rt)
154 {
155     rt->pd->escaped = false;
156     rt->pd->esbuf_len = 0;
157     rt->pd->esbuf[0] = '\0';
158 }
159
160 static void handle_control_char(RoteTerm *rt, int c)
161 {
162     switch (c) {
163       case '\r':  /* carriage return */
164         rt->ccol = 0;
165         break;
166
167       case '\n':  /* line feed */
168         rt->ccol = 0;
169         cursor_line_down(rt);
170         rt->curpos_dirty = true;
171         break;
172
173       case '\b': /* backspace */
174         if (rt->ccol > 0)
175             rt->ccol--;
176         rt->curpos_dirty = true;
177         break;
178
179       case '\t': /* tab */
180         rt->ccol = (rt->ccol + 8) & ~7;
181         clamp_cursor_to_bounds(rt);
182         break;
183
184       case '\x1b': /* begin escape sequence (aborting previous one if any) */
185         new_escape_sequence(rt);
186         break;
187
188       case '\x0e': /* enter graphical character mode */
189         rt->pd->graphmode = true;
190         break;
191
192       case '\x0f': /* exit graphical character mode */
193         rt->pd->graphmode = false;
194         break;
195
196       case '\x9b': /* CSI character. Equivalent to ESC [ */
197         new_escape_sequence(rt);
198         rt->pd->esbuf[rt->pd->esbuf_len++] = '[';
199         break;
200
201       case '\x18':
202       case '\x1a': /* these interrupt escape sequences */
203         cancel_escape_sequence(rt);
204         break;
205
206       case '\a': /* bell */
207         /* do nothing for now... maybe a visual bell would be nice? */
208         break;
209     }
210 }
211
212 static inline bool is_valid_csi_ender(int c)
213 {
214     return (c >= 'a' && c <= 'z')
215         || (c >= 'A' && c <= 'Z')
216         || (c == '@' || c == '`');
217 }
218
219 static void try_interpret_escape_seq(RoteTerm *rt)
220 {
221     char firstchar = rt->pd->esbuf[0];
222     char lastchar  = rt->pd->esbuf[rt->pd->esbuf_len-1];
223
224     if (!firstchar)
225         return;  /* too early to do anything */
226
227     /* interpret ESC-M as reverse line-feed */
228     if (firstchar == 'M') {
229         cursor_line_up(rt);
230         cancel_escape_sequence(rt);
231         return;
232     }
233
234     if (firstchar != '[' && firstchar != ']') {
235         /* unrecognized escape sequence. Let's forget about it. */
236         cancel_escape_sequence(rt);
237         return;
238     }
239
240     if (firstchar == '[' && is_valid_csi_ender(lastchar)) {
241         /* we have a csi escape sequence: interpret it */
242         rote_es_interpret_csi(rt);
243         cancel_escape_sequence(rt);
244     } else if (firstchar == ']' && lastchar == '\a') {
245         /* we have an xterm escape sequence: interpret it */
246
247         /* rote_es_interpret_xterm_es(rt);     -- TODO!*/
248         cancel_escape_sequence(rt);
249     }
250
251     /* if the escape sequence took up all available space and could
252      * not yet be parsed, abort it */
253     if (rt->pd->esbuf_len + 1 >= ESEQ_BUF_SIZE)
254         cancel_escape_sequence(rt);
255 }
256
257 int rote_vt_inject(RoteTerm *rt, const char *data, int len)
258 {
259     for (; len-- > 0; data++) {
260         if ((unsigned char)*data <= 31) {
261             handle_control_char(rt, *data);
262             continue;
263         }
264
265         if (rt->pd->escaped && rt->pd->esbuf_len < ESEQ_BUF_SIZE) {
266             /* append character to ongoing escape sequence */
267             rt->pd->esbuf[rt->pd->esbuf_len] = *data;
268             rt->pd->esbuf[++rt->pd->esbuf_len] = 0;
269
270             try_interpret_escape_seq(rt);
271         } else
272         if (rt->pd->graphmode) {
273             put_graphmode_char(rt, *data);
274         } else {
275             put_normal_char(rt, *data);
276         }
277     }
278
279     return 0;
280 }
281
282 /****************************************************************************/
283 /* CSI things                                                               */
284 /****************************************************************************/
285
286 /* interprets a 'set attribute' (SGR) CSI escape sequence */
287 static void interpret_csi_SGR(RoteTerm *rt, int param[], int pcount)
288 {
289     int i;
290
291     if (pcount == 0) {
292         /* special case: reset attributes */
293         rt->curattr = 0x70;
294         return;
295     }
296
297     for (i = 0; i < pcount; i++) {
298
299         // From http://vt100.net/docs/vt510-rm/SGR table 5-16
300         // 0    All attributes off
301         // 1    Bold
302         // 4    Underline
303         // 5    Blinking
304         // 7    Negative image
305         // 8    Invisible image
306         // 10   The ASCII character set is the current 7-bit
307         //      display character set (default) - SCO Console only.
308         // 11   Map Hex 00-7F of the PC character set codes
309         //      to the current 7-bit display character set
310         //      - SCO Console only.
311         // 12   Map Hex 80-FF of the current character set to
312         //      the current 7-bit display character set - SCO
313         //      Console only.
314         // 22   Bold off
315         // 24   Underline off
316         // 25   Blinking off
317         // 27   Negative image off
318         // 28   Invisible image off
319
320         if (param[i] == 0) rt->curattr = 0x70;
321         else if (param[i] == 1 || param[i] == 2 || param[i] == 4)  /* set bold */
322             ROTE_ATTR_MOD_BOLD(rt->curattr,1);
323         else if (param[i] == 5)  /* set blink */
324             ROTE_ATTR_MOD_BLINK(rt->curattr,1);
325         else if (param[i] == 7 || param[i] == 27) { /* reverse video */
326             int fg = ROTE_ATTR_FG(rt->curattr);
327             int bg = ROTE_ATTR_BG(rt->curattr);
328             ROTE_ATTR_MOD_FG(rt->curattr, bg);
329             ROTE_ATTR_MOD_BG(rt->curattr, fg);
330         }
331         else if (param[i] == 8) rt->curattr = 0x0;    /* invisible */
332         else if (param[i] == 22 || param[i] == 24) /* bold off */
333             ROTE_ATTR_MOD_BOLD(rt->curattr,0);
334         else if (param[i] == 25) /* blink off */
335             ROTE_ATTR_MOD_BLINK(rt->curattr,0);
336         else if (param[i] == 28) /* invisible off */
337             rt->curattr = 0x70;
338         else if (param[i] >= 30 && param[i] <= 37)    /* set fg */
339             ROTE_ATTR_MOD_FG(rt->curattr, param[i] - 30);
340         else if (param[i] >= 40 && param[i] <= 47)    /* set bg */
341             ROTE_ATTR_MOD_BG(rt->curattr, param[i] - 40);
342         else if (param[i] == 39)  /* reset foreground to default */
343             ROTE_ATTR_MOD_FG(rt->curattr, 7);
344         else if (param[i] == 49)  /* reset background to default */
345             ROTE_ATTR_MOD_BG(rt->curattr, 0);
346     }
347 }
348
349 /* interprets an 'erase display' (ED) escape sequence */
350 static void interpret_csi_ED(RoteTerm *rt, int param[], int pcount)
351 {
352     int r, c;
353     int start_row, start_col, end_row, end_col;
354
355     /* decide range */
356     if (pcount && param[0] == 2) {
357         start_row = 0;
358         start_col = 0;
359         end_row = rt->rows - 1;
360         end_col = rt->cols - 1;
361     } else
362     if (pcount && param[0] == 1) {
363         start_row = 0;
364         start_col = 0;
365         end_row = rt->crow;
366         end_col = rt->ccol;
367     } else {
368         start_row = rt->crow;
369         start_col = rt->ccol;
370         end_row = rt->rows - 1;
371         end_col = rt->cols - 1;
372     }
373
374     /* clean range */
375     for (r = start_row; r <= end_row; r++) {
376         rt->line_dirty[r] = true;
377
378         for (c = (r == start_row ? start_col : 0);
379              c <= (r == end_row ? end_col : rt->cols - 1);
380              c++)
381         {
382             rt->cells[r][c].ch   = 0x20;
383             rt->cells[r][c].attr = rt->curattr;
384         }
385     }
386 }
387
388 /* interprets a 'move cursor' (CUP) escape sequence */
389 static void interpret_csi_CUP(RoteTerm *rt, int param[], int pcount)
390 {
391     if (pcount == 0) {
392         /* special case */
393         rt->crow = rt->ccol = 0;
394         return;
395     } else
396     if (pcount < 2) {
397         return;  /* malformed */
398     }
399
400     rt->crow = param[0] - 1;  /* convert from 1-based to 0-based */
401     rt->ccol = param[1] - 1;  /* convert from 1-based to 0-based */
402
403     rt->curpos_dirty = true;
404
405     clamp_cursor_to_bounds(rt);
406 }
407
408 /* Interpret the 'relative mode' sequences: CUU, CUD, CUF, CUB, CNL,
409  * CPL, CHA, HPR, VPA, VPR, HPA */
410 static void interpret_csi_C(RoteTerm *rt, char verb, int param[], int pcount)
411 {
412     int n = (pcount && param[0] > 0) ? param[0] : 1;
413
414     switch (verb) {
415       case 'A':           rt->crow -= n; break;
416       case 'B': case 'e': rt->crow += n; break;
417       case 'C': case 'a': rt->ccol += n; break;
418       case 'D':           rt->ccol -= n; break;
419       case 'E':           rt->crow += n; rt->ccol = 0; break;
420       case 'F':           rt->crow -= n; rt->ccol = 0; break;
421       case 'G': case '`': rt->ccol  = param[0] - 1; break;
422       case 'd':           rt->crow  = param[0] - 1; break;
423     }
424
425     rt->curpos_dirty = true;
426     clamp_cursor_to_bounds(rt);
427 }
428
429 /* Interpret the 'erase line' escape sequence */
430 static void interpret_csi_EL(RoteTerm *rt, int param[], int pcount)
431 {
432     int erase_start, erase_end, i;
433     int cmd = pcount ? param[0] : 0;
434
435     switch (cmd) {
436       case 1:  erase_start = 0;        erase_end = rt->ccol;     break;
437       case 2:  erase_start = 0;        erase_end = rt->cols - 1; break;
438       default: erase_start = rt->ccol; erase_end = rt->cols - 1; break;
439     }
440
441     for (i = erase_start; i <= erase_end; i++) {
442         rt->cells[rt->crow][i].ch   = 0x20;
443         rt->cells[rt->crow][i].attr = rt->curattr;
444     }
445
446     rt->line_dirty[rt->crow] = true;
447 }
448
449 /* Interpret the 'insert blanks' sequence (ICH) */
450 static void interpret_csi_ICH(RoteTerm *rt, int param[], int pcount)
451 {
452     int n = (pcount && param[0] > 0) ? param[0] : 1;
453     int i;
454
455     for (i = rt->cols - 1; i >= rt->ccol + n; i--) {
456         rt->cells[rt->crow][i] = rt->cells[rt->crow][i - n];
457     }
458
459     for (i = rt->ccol; i < rt->ccol + n; i++) {
460         rt->cells[rt->crow][i].ch   = 0x20;
461         rt->cells[rt->crow][i].attr = rt->curattr;
462     }
463
464     rt->line_dirty[rt->crow] = true;
465 }
466
467 /* Interpret the 'delete chars' sequence (DCH) */
468 static void interpret_csi_DCH(RoteTerm *rt, int param[], int pcount)
469 {
470     int n = (pcount && param[0] > 0) ? param[0] : 1;
471     int i;
472
473     for (i = rt->ccol; i < rt->cols; i++) {
474         if (i + n < rt->cols) {
475             rt->cells[rt->crow][i] = rt->cells[rt->crow][i + n];
476         } else {
477             rt->cells[rt->crow][i].ch   = 0x20;
478             rt->cells[rt->crow][i].attr = rt->curattr;
479         }
480     }
481
482     rt->line_dirty[rt->crow] = true;
483 }
484
485 /* Interpret an 'insert line' sequence (IL) */
486 static void interpret_csi_IL(RoteTerm *rt, int param[], int pcount)
487 {
488     int n = (pcount && param[0] > 0) ? param[0] : 1;
489     int i, j;
490
491     for (i = rt->pd->scrollbottom; i >= rt->crow + n; i--) {
492         memcpy(rt->cells[i], rt->cells[i - n], sizeof(RoteCell) * rt->cols);
493     }
494
495     for (i = rt->crow; i < rt->crow + n && i <= rt->pd->scrollbottom; i++) {
496         rt->line_dirty[i] = true;
497         for (j = 0; j < rt->cols; j++) {
498             rt->cells[i][j].ch   = 0x20;
499             rt->cells[i][j].attr = rt->curattr;
500         }
501     }
502
503 }
504
505 /* Interpret a 'delete line' sequence (DL) */
506 static void interpret_csi_DL(RoteTerm *rt, int param[], int pcount)
507 {
508     int n = (pcount && param[0] > 0) ? param[0] : 1;
509     int i, j;
510
511     for (i = rt->crow; i <= rt->pd->scrollbottom; i++) {
512         rt->line_dirty[i] = true;
513         if (i + n <= rt->pd->scrollbottom) {
514             memcpy(rt->cells[i], rt->cells[i+n], sizeof(RoteCell) * rt->cols);
515         } else {
516             for (j = 0; j < rt->cols; j++) {
517                 rt->cells[i][j].ch   = 0x20;
518                 rt->cells[i][j].attr = rt->curattr;
519             }
520         }
521     }
522 }
523
524 /* Interpret an 'erase characters' (ECH) sequence */
525 static void interpret_csi_ECH(RoteTerm *rt, int param[], int pcount)
526 {
527     int n = (pcount && param[0] > 0) ? param[0] : 1;
528     int i;
529
530     for (i = rt->ccol; i < rt->ccol + n && i < rt->cols; i++) {
531         rt->cells[rt->crow][i].ch   = 0x20;
532         rt->cells[rt->crow][i].attr = rt->curattr;
533     }
534
535     rt->line_dirty[rt->crow] = true;
536 }
537
538 /* Interpret a 'set scrolling region' (DECSTBM) sequence */
539 static void interpret_csi_DECSTBM(RoteTerm *rt, int param[], int pcount)
540 {
541     int newtop, newbottom;
542
543     if (!pcount) {
544         newtop = 0;
545         newbottom = rt->rows - 1;
546     } else
547     if (pcount < 2) {
548         return; /* malformed */
549     }
550
551     newtop = param[0] - 1;
552     newbottom = param[1] - 1;
553
554     /* clamp to bounds */
555     if (newtop < 0)
556         newtop = 0;
557     if (newtop >= rt->rows)
558         newtop = rt->rows - 1;
559     if (newbottom < 0)
560         newbottom = 0;
561     if (newbottom >= rt->rows)
562         newbottom = rt->rows - 1;
563
564     /* check for range validity */
565     if (newtop > newbottom)
566         return;
567     rt->pd->scrolltop = newtop;
568     rt->pd->scrollbottom = newbottom;
569 }
570
571 static void 
572 interpret_csi_SAVECUR(RoteTerm *rt,
573                       int param[] __attribute__((unused)),
574                       int pcount __attribute__((unused)))
575 {
576     rt->pd->saved_x = rt->ccol;
577     rt->pd->saved_y = rt->crow;
578 }
579
580 static void
581 interpret_csi_RESTORECUR(RoteTerm *rt,
582                          int param[] __attribute__((unused)),
583                          int pcount __attribute__((unused)))
584 {
585     rt->ccol = rt->pd->saved_x;
586     rt->crow = rt->pd->saved_y;
587     rt->curpos_dirty = true;
588 }
589
590 void rote_es_interpret_csi(RoteTerm *rt)
591 {
592     static int csiparam[MAX_CSI_ES_PARAMS];
593     int param_count = 0;
594     const char *p = rt->pd->esbuf + 1;
595     char verb = rt->pd->esbuf[rt->pd->esbuf_len - 1];
596
597     if (!strncmp(rt->pd->esbuf, "[?", 2)) { /* private-mode CSI, ignore */
598         return;
599     }
600
601     /* parse numeric parameters */
602     while (isdigit((unsigned char)*p) || *p == ';') {
603         if (*p == ';') {
604             if (param_count >= MAX_CSI_ES_PARAMS) return; /* too long! */
605             csiparam[param_count++] = 0;
606         } else {
607             if (param_count == 0) csiparam[param_count++] = 0;
608             csiparam[param_count - 1] *= 10;
609             csiparam[param_count - 1] += *p - '0';
610         }
611
612         p++;
613     }
614
615     /* delegate handling depending on command character (verb) */
616     switch (verb) {
617       case 'h':
618         if (param_count == 1 && csiparam[0] == 4) /* insert mode */
619             rt->insert = true;
620         break;
621       case 'l':
622         if (param_count == 1 && csiparam[0] == 4) /* replace mode */
623             rt->insert = false;
624         break;
625       case 'm': /* it's a 'set attribute' sequence */
626         interpret_csi_SGR(rt, csiparam, param_count); break;
627       case 'J': /* it's an 'erase display' sequence */
628         interpret_csi_ED(rt, csiparam, param_count); break;
629       case 'H': case 'f': /* it's a 'move cursor' sequence */
630         interpret_csi_CUP(rt, csiparam, param_count); break;
631       case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
632       case 'e': case 'a': case 'd': case '`':
633         /* it is a 'relative move' */
634         interpret_csi_C(rt, verb, csiparam, param_count); break;
635       case 'K': /* erase line */
636         interpret_csi_EL(rt, csiparam, param_count); break;
637       case '@': /* insert characters */
638         interpret_csi_ICH(rt, csiparam, param_count); break;
639       case 'P': /* delete characters */
640         interpret_csi_DCH(rt, csiparam, param_count); break;
641       case 'L': /* insert lines */
642         interpret_csi_IL(rt, csiparam, param_count); break;
643       case 'M': /* delete lines */
644         interpret_csi_DL(rt, csiparam, param_count); break;
645       case 'X': /* erase chars */
646         interpret_csi_ECH(rt, csiparam, param_count); break;
647       case 'r': /* set scrolling region */
648         interpret_csi_DECSTBM(rt, csiparam, param_count); break;
649       case 's': /* save cursor location */
650         interpret_csi_SAVECUR(rt, csiparam, param_count); break;
651       case 'u': /* restore cursor location */
652         interpret_csi_RESTORECUR(rt, csiparam, param_count); break;
653       default:
654         break;
655     }
656 }
657