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