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