more refactoring
[apps/madtty.git] / madtty / madtty.c
index 3121367..e6d9dde 100644 (file)
     Copyright © 2006 Pierre Habouzit
  */
 
-#include <stdlib.h>
-#ifdef USE_PTY
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <locale.h>
 #include <pty.h>
-#endif
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/ioctl.h>
 
 #include "madtty.h"
-#include "roteprivate.h"
 
-#define ROTE_VT_UPDATE_ITERATIONS 5
-
-RoteTerm *rote_vt_create(int rows, int cols)
+static void clamp_cursor_to_bounds(madtty_t *rt)
 {
-    RoteTerm *rt;
-    int i, j;
+    if (rt->curs_row < 0) {
+        rt->curs_row = 0;
+    }
+    if (rt->curs_col < 0) {
+        rt->curs_col = 0;
+    }
 
-    if (rows <= 0 || cols <= 0) return NULL;
+    if (rt->curs_row >= rt->rows) {
+        rt->curs_row = rt->rows - 1;
+    }
+    if (rt->curs_col >= rt->cols) {
+        rt->curs_col = rt->cols - 1;
+    }
+}
 
-    if (! (rt = (RoteTerm*) malloc(sizeof(RoteTerm))) ) return NULL;
-    memset(rt, 0, sizeof(RoteTerm));
+static void cursor_line_down(madtty_t *rt)
+{
+    int i;
 
-    /* record dimensions */
-    rt->rows = rows;
-    rt->cols = cols;
+    rt->curs_row++;
+    if (rt->curs_row <= rt->scrollbottom)
+        return;
 
-    /* default mode is replace */
-    rt->insert = false; 
+    /* must scroll the scrolling region up by 1 line, and put cursor on
+     * last line of it */
+    rt->curs_row = rt->scrollbottom;
 
-    /* create the cell matrix */
-    rt->cells = (RoteCell**) malloc(sizeof(RoteCell*) * rt->rows);
-    for (i = 0; i < rt->rows; i++) {
-        /* create row */
-        rt->cells[i] = (RoteCell*) malloc(sizeof(RoteCell) * rt->cols);
+    for (i = rt->scrolltop; i < rt->scrollbottom; i++) {
+        memcpy(rt->cells[i], rt->cells[i+1], sizeof(RoteCell) * rt->cols);
+    }
 
-        /* fill row with spaces */
-        for (j = 0; j < rt->cols; j++) {
-            rt->cells[i][j].ch = 0x20;    /* a space */
-            rt->cells[i][j].attr = 0x70;  /* white text, black background */
-        }
+    /* clear last row of the scrolling region */
+    for (i = 0; i < rt->cols; i++) {
+        rt->cells[rt->scrollbottom][i].s[0]  = 0x20;
+        rt->cells[rt->scrollbottom][i].len   = 1;
+        rt->cells[rt->scrollbottom][i].attrs = A_NORMAL;
     }
+}
 
-    /* allocate dirtiness array */
-    rt->line_dirty = (bool*) malloc(sizeof(bool) * rt->rows);
+static void cursor_line_up(madtty_t *rt)
+{
+    int i;
 
-    /* initialization of other public fields */
-    rt->crow = rt->ccol = 0;
-    rt->curattr = 0x70;  /* white text over black background */
+    rt->curs_row--;
+    if (rt->curs_row >= rt->scrolltop)
+        return;
 
-    /* allocate private data */
-    rt->pd = (RoteTermPrivate*) malloc(sizeof(RoteTermPrivate));
-    memset(rt->pd, 0, sizeof(RoteTermPrivate));
+    /* must scroll the scrolling region up by 1 line, and put cursor on
+     * first line of it */
+    rt->curs_row = rt->scrolltop;
 
-    rt->pd->pty = -1;  /* no pty for now */
+    for (i = rt->scrollbottom; i > rt->scrolltop; i--) {
+        memcpy(rt->cells[i], rt->cells[i-1], sizeof(RoteCell) * rt->cols);
+    }
 
-    /* initial scrolling area is the whole window */
-    rt->pd->scrolltop = 0;
-    rt->pd->scrollbottom = rt->rows - 1;
+    /* clear first row of the scrolling region */
+    for (i = 0; i < rt->cols; i++) {
+        rt->cells[rt->scrolltop][i].s[0]  = 0x20;
+        rt->cells[rt->scrolltop][i].len   = 1;
+        rt->cells[rt->scrolltop][i].attrs = A_NORMAL;
+    }
+}
 
-#ifdef DEBUG
-    fprintf(stderr, "Created a %d x %d terminal.\n", rt->rows, rt->cols);
-#endif
+static void put_normal_char(madtty_t *rt, const char *s, int len)
+{
+    if (rt->curs_col >= rt->cols) {
+        rt->curs_col = 0;
+        cursor_line_down(rt);
+    }
 
-    return rt;
+    if (rt->insert) {
+        int i;
+
+        for (i = rt->cols - 1; i >= rt->curs_col+1; i--) {
+            rt->cells[rt->curs_row][i] = rt->cells[rt->curs_row][i-1];
+        }
+    }
+
+    memcpy(rt->cells[rt->curs_row][rt->curs_col].s, s, len);
+    rt->cells[rt->curs_row][rt->curs_col].len   = len;
+    rt->cells[rt->curs_row][rt->curs_col].attrs = rt->curattrs;
+    rt->curs_col++;
 }
 
-void rote_vt_destroy(RoteTerm *rt)
+static void put_graphmode_char(madtty_t *rt, int c)
 {
-    int i;
-    if (!rt) return;
+    char nc;
+    /* do some very pitiful translation to regular ascii chars */
+    switch (c) {
+      case 'j': case 'k': case 'l': case 'm': case 'n': case 't':
+      case 'u': case 'v': case 'w':
+        nc = '+'; break;
+      case 'x':
+        nc = '|'; break;
+      default:
+        nc = '%';
+    }
 
-    free(rt->pd);
-    free(rt->line_dirty);
-    for (i = 0; i < rt->rows; i++) free(rt->cells[i]);
-    free(rt->cells);
-    free(rt);
+    put_normal_char(rt, &nc, 1);
 }
 
-#ifdef USE_NCURSES
+static void new_escape_sequence(madtty_t *rt)
+{
+    rt->escaped = true;
+    rt->esbuf_len = 0;
+    rt->esbuf[0] = '\0';
+}
 
-static void default_cur_set_attr(WINDOW *win, unsigned char attr)
+static void cancel_escape_sequence(madtty_t *rt)
 {
-    int cp = ROTE_ATTR_BG(attr) * 8 + 7 - ROTE_ATTR_FG(attr);
-    if (!cp) wattrset(win, A_NORMAL);
-    else     wattrset(win, COLOR_PAIR(cp));
+    rt->escaped = false;
+    rt->esbuf_len = 0;
+    rt->esbuf[0] = '\0';
+}
 
-    if (ROTE_ATTR_BOLD(attr))     wattron(win, A_BOLD);
-    if (ROTE_ATTR_BLINK(attr))    wattron(win, A_BLINK);
+static void handle_control_char(madtty_t *rt, int c)
+{
+    switch (c) {
+      case '\r':  /* carriage return */
+        rt->curs_col = 0;
+        break;
+
+      case '\n':  /* line feed */
+        rt->curs_col = 0;
+        cursor_line_down(rt);
+        break;
+
+      case '\b': /* backspace */
+        if (rt->curs_col > 0)
+            rt->curs_col--;
+        break;
+
+      case '\t': /* tab */
+        rt->curs_col = (rt->curs_col + 8) & ~7;
+        clamp_cursor_to_bounds(rt);
+        break;
+
+      case '\x1b': /* begin escape sequence (aborting previous one if any) */
+        new_escape_sequence(rt);
+        break;
+
+      case '\x0e': /* enter graphical character mode */
+        rt->graphmode = true;
+        break;
+
+      case '\x0f': /* exit graphical character mode */
+        rt->graphmode = false;
+        break;
+
+      case '\x9b': /* CSI character. Equivalent to ESC [ */
+        new_escape_sequence(rt);
+        rt->esbuf[rt->esbuf_len++] = '[';
+        break;
+
+      case '\x18':
+      case '\x1a': /* these interrupt escape sequences */
+        cancel_escape_sequence(rt);
+        break;
+
+      case '\a': /* bell */
+        /* do nothing for now... maybe a visual bell would be nice? */
+        break;
+    }
 }
 
-#endif
+static bool is_valid_csi_ender(int c)
+{
+    return (c >= 'a' && c <= 'z')
+        || (c >= 'A' && c <= 'Z')
+        || (c == '@' || c == '`');
+}
 
-static inline unsigned char ensure_printable(unsigned char ch) 
-{ return ch >= 32 ? ch : 32; }
+/* interprets a 'set attribute' (SGR) CSI escape sequence */
+static void interpret_csi_SGR(madtty_t *rt, int param[], int pcount)
+{
+    int i;
 
-#ifdef USE_NCURSES
+    if (pcount == 0) {
+        /* special case: reset attributes */
+        rt->curattrs = A_NORMAL;
+        return;
+    }
 
-void rote_vt_draw(RoteTerm *rt, WINDOW *win, int srow, int scol, 
-                  void (*cur_set_attr)(WINDOW*,unsigned char)) {
+    for (i = 0; i < pcount; i++) {
+
+        // From http://vt100.net/docs/vt510-rm/SGR table 5-16
+        // 0   All attributes off
+        // 1   Bold
+        // 4   Underline
+        // 5   Blinking
+        // 7   Negative image
+        // 8   Invisible image
+        // 10  The ASCII character set is the current 7-bit
+        //     display character set (default) - SCO Console only.
+        // 11  Map Hex 00-7F of the PC character set codes
+        //     to the current 7-bit display character set
+        //     - SCO Console only.
+        // 12  Map Hex 80-FF of the current character set to
+        //     the current 7-bit display character set - SCO
+        //     Console only.
+        // 22  Bold off
+        // 24  Underline off
+        // 25  Blinking off
+        // 27  Negative image off
+        // 28  Invisible image off
+
+        switch (param[i]) {
+#define CASE(x, op)  case x: op; break
+            CASE(0,  rt->curattrs = A_NORMAL);
+            CASE(1,  rt->curattrs |= A_BOLD);
+            CASE(4,  rt->curattrs |= A_UNDERLINE);
+            CASE(5,  rt->curattrs |= A_BLINK);
+            CASE(7,  rt->curattrs |= A_REVERSE);
+            CASE(8,  rt->curattrs |= A_INVIS);
+            CASE(22, rt->curattrs &= ~A_BOLD);
+            CASE(24, rt->curattrs &= ~A_UNDERLINE);
+            CASE(25, rt->curattrs &= ~A_BLINK);
+            CASE(27, rt->curattrs &= ~A_REVERSE);
+            CASE(28, rt->curattrs &= ~A_INVIS);
+
+          case 30 ... 37:
+            rt->curattrs &= ~070;
+            rt->curattrs |= (param[i] - 30) << 3;
+            break;
+
+          case 40 ... 47:
+            rt->curattrs &= ~007;
+            rt->curattrs |= (param[i] - 40);
+            break;
+
+          case 39:
+            rt->curattrs &= ~070;
+            break;
+
+          case 49:
+            rt->curattrs &= ~007;
+            break;
+
+          default:
+            break;
+        }
+    }
+}
 
-    int i, j;
-    rote_vt_update(rt);
+/* interprets an 'erase display' (ED) escape sequence */
+static void interpret_csi_ED(madtty_t *rt, int param[], int pcount)
+{
+    int r, c;
+    int start_row, start_col, end_row, end_col;
+
+    /* decide range */
+    if (pcount && param[0] == 2) {
+        start_row = 0;
+        start_col = 0;
+        end_row = rt->rows - 1;
+        end_col = rt->cols - 1;
+    } else
+    if (pcount && param[0] == 1) {
+        start_row = 0;
+        start_col = 0;
+        end_row = rt->curs_row;
+        end_col = rt->curs_col;
+    } else {
+        start_row = rt->curs_row;
+        start_col = rt->curs_col;
+        end_row = rt->rows - 1;
+        end_col = rt->cols - 1;
+    }
 
-    if (!cur_set_attr) cur_set_attr = default_cur_set_attr;
-    for (i = 0; i < rt->rows; i++) {
-        wmove(win, srow + i, scol);
-        for (j = 0; j < rt->cols; j++) {
-            (*cur_set_attr)(win, rt->cells[i][j].attr);
-            waddch(win, ensure_printable(rt->cells[i][j].ch));
+    /* clean range */
+    for (r = start_row; r <= end_row; r++) {
+        for (c = (r == start_row ? start_col : 0);
+             c <= (r == end_row ? end_col : rt->cols - 1);
+             c++)
+        {
+            rt->cells[r][c].s[0]  = 0x20;
+            rt->cells[r][c].len   = 1;
+            rt->cells[r][c].attrs = rt->curattrs;
         }
     }
+}
+
+/* interprets a 'move cursor' (CUP) escape sequence */
+static void interpret_csi_CUP(madtty_t *rt, int param[], int pcount)
+{
+    if (pcount == 0) {
+        /* special case */
+        rt->curs_row = rt->curs_col = 0;
+        return;
+    } else
+    if (pcount < 2) {
+        return;  /* malformed */
+    }
 
-    wmove(win, srow + rt->crow, scol + rt->ccol);
+    rt->curs_row = param[0] - 1;  /* convert from 1-based to 0-based */
+    rt->curs_col = param[1] - 1;  /* convert from 1-based to 0-based */
+
+    clamp_cursor_to_bounds(rt);
 }
 
-#endif
+/* Interpret the 'relative mode' sequences: CUU, CUD, CUF, CUB, CNL,
+ * CPL, CHA, HPR, VPA, VPR, HPA */
+static void interpret_csi_C(madtty_t *rt, char verb, int param[], int pcount)
+{
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+
+    switch (verb) {
+      case 'A':           rt->curs_row -= n; break;
+      case 'B': case 'e': rt->curs_row += n; break;
+      case 'C': case 'a': rt->curs_col += n; break;
+      case 'D':           rt->curs_col -= n; break;
+      case 'E':           rt->curs_row += n; rt->curs_col = 0; break;
+      case 'F':           rt->curs_row -= n; rt->curs_col = 0; break;
+      case 'G': case '`': rt->curs_col  = param[0] - 1; break;
+      case 'd':           rt->curs_row  = param[0] - 1; break;
+    }
 
-#ifdef USE_PTY
+    clamp_cursor_to_bounds(rt);
+}
 
-pid_t rote_vt_forkpty(RoteTerm *rt, const char *command)
+/* Interpret the 'erase line' escape sequence */
+static void interpret_csi_EL(madtty_t *rt, int param[], int pcount)
 {
-    struct winsize ws;
-    pid_t childpid;
+    int erase_start, erase_end, i;
+    int cmd = pcount ? param[0] : 0;
 
-    ws.ws_row = rt->rows;
-    ws.ws_col = rt->cols;
-    ws.ws_xpixel = ws.ws_ypixel = 0;
+    switch (cmd) {
+      case 1:  erase_start = 0;        erase_end = rt->curs_col;     break;
+      case 2:  erase_start = 0;        erase_end = rt->cols - 1; break;
+      default: erase_start = rt->curs_col; erase_end = rt->cols - 1; break;
+    }
 
-    childpid = forkpty(&rt->pd->pty, NULL, NULL, &ws);
-    if (childpid < 0) return -1;
+    for (i = erase_start; i <= erase_end; i++) {
+        rt->cells[rt->curs_row][i].s[0]  = 0x20;
+        rt->cells[rt->curs_row][i].len   = 1;
+        rt->cells[rt->curs_row][i].attrs = rt->curattrs;
+    }
+}
 
-    if (childpid == 0) {
-        /* we are the child, running under the slave side of the pty. */
+/* Interpret the 'insert blanks' sequence (ICH) */
+static void interpret_csi_ICH(madtty_t *rt, int param[], int pcount)
+{
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+    int i;
 
-        /* Cajole application into using linux-console-compatible escape
-         * sequences (which is what we are prepared to interpret) */
-        setenv("TERM", "linux", 1);
+    for (i = rt->cols - 1; i >= rt->curs_col + n; i--) {
+        rt->cells[rt->curs_row][i] = rt->cells[rt->curs_row][i - n];
+    }
+
+    for (i = rt->curs_col; i < rt->curs_col + n; i++) {
+        rt->cells[rt->curs_row][i].s[0]  = 0x20;
+        rt->cells[rt->curs_row][i].len   = 1;
+        rt->cells[rt->curs_row][i].attrs = rt->curattrs;
+    }
+}
+
+/* Interpret the 'delete chars' sequence (DCH) */
+static void interpret_csi_DCH(madtty_t *rt, int param[], int pcount)
+{
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+    int i;
+
+    for (i = rt->curs_col; i < rt->cols; i++) {
+        if (i + n < rt->cols) {
+            rt->cells[rt->curs_row][i] = rt->cells[rt->curs_row][i + n];
+        } else {
+            rt->cells[rt->curs_row][i].s[0]  = 0x20;
+            rt->cells[rt->curs_row][i].len   = 1;
+            rt->cells[rt->curs_row][i].attrs = rt->curattrs;
+        }
+    }
+}
+
+/* Interpret an 'insert line' sequence (IL) */
+static void interpret_csi_IL(madtty_t *rt, int param[], int pcount)
+{
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+    int i, j;
 
-        /* Now we will exec /bin/sh -c command. */
-        execl("/bin/sh", "/bin/sh", "-c", command, NULL);
+    for (i = rt->scrollbottom; i >= rt->curs_row + n; i--) {
+        memcpy(rt->cells[i], rt->cells[i - n], sizeof(RoteCell) * rt->cols);
+    }
 
-        fprintf(stderr, "\nexecl() failed.\nCommand: '%s'\n", command);
-        exit(127);  /* error exec'ing */
+    for (i = rt->curs_row; i < rt->curs_row + n && i <= rt->scrollbottom; i++) {
+        for (j = 0; j < rt->cols; j++) {
+            rt->cells[i][j].s[0]  = 0x20;
+            rt->cells[i][j].len   = 1;
+            rt->cells[i][j].attrs = rt->curattrs;
+        }
     }
 
-    /* if we got here we are the parent process */
-    rt->childpid = childpid;
-    return childpid;
 }
 
-void rote_vt_forsake_child(RoteTerm *rt)
+/* Interpret a 'delete line' sequence (DL) */
+static void interpret_csi_DL(madtty_t *rt, int param[], int pcount)
 {
-    if (rt->pd->pty >= 0) close(rt->pd->pty);
-    rt->pd->pty = -1;
-    rt->childpid = 0;
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+    int i, j;
+
+    for (i = rt->curs_row; i <= rt->scrollbottom; i++) {
+        if (i + n <= rt->scrollbottom) {
+            memcpy(rt->cells[i], rt->cells[i+n], sizeof(RoteCell) * rt->cols);
+        } else {
+            for (j = 0; j < rt->cols; j++) {
+                rt->cells[i][j].s[0]  = 0x20;
+                rt->cells[i][j].len   = 1;
+                rt->cells[i][j].attrs = rt->curattrs;
+            }
+        }
+    }
 }
 
-#endif
+/* Interpret an 'erase characters' (ECH) sequence */
+static void interpret_csi_ECH(madtty_t *rt, int param[], int pcount)
+{
+    int n = (pcount && param[0] > 0) ? param[0] : 1;
+    int i;
+
+    for (i = rt->curs_col; i < rt->curs_col + n && i < rt->cols; i++) {
+        rt->cells[rt->curs_row][i].s[0]  = 0x20;
+        rt->cells[rt->curs_row][i].len   = 1;
+        rt->cells[rt->curs_row][i].attrs = rt->curattrs;
+    }
+}
 
-void rote_vt_update(RoteTerm *rt)
+/* Interpret a 'set scrolling region' (DECSTBM) sequence */
+static void interpret_csi_DECSTBM(madtty_t *rt, int param[], int pcount)
 {
-    fd_set ifs;
-    struct timeval tvzero;
-    char buf[512];
-    int bytesread;
-    int n = ROTE_VT_UPDATE_ITERATIONS;
-    if (rt->pd->pty < 0) return;  /* nothing to pump */
-
-    while (n--) { /* iterate at most ROVE_VT_UPDATE_ITERATIONS times.
-                   * As Phil Endecott pointed out, if we don't restrict this,
-                   * a program that floods the terminal with output
-                   * could cause this loop to iterate forever, never
-                   * being able to catch up. So we'll rely on the client
-                   * calling rote_vt_update often, as the documentation
-                   * recommends :-) */
-
-        /* check if pty has something to say */
-        FD_ZERO(&ifs); FD_SET(rt->pd->pty, &ifs);
-        tvzero.tv_sec = 0; tvzero.tv_usec = 0;
-
-        if (select(rt->pd->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
-            return; /* nothing to read, or select() failed */
-
-        /* read what we can. This is guaranteed not to block, since
-         * select() told us there was something to read. */
-        bytesread = read(rt->pd->pty, buf, 512);
-        if (bytesread <= 0) return;   
-
-        /* inject the data into the terminal */
-        rote_vt_inject(rt, buf, bytesread);
+    int newtop, newbottom;
+
+    if (!pcount) {
+        newtop = 0;
+        newbottom = rt->rows - 1;
+    } else
+    if (pcount < 2) {
+        return; /* malformed */
     }
+
+    newtop = param[0] - 1;
+    newbottom = param[1] - 1;
+
+    /* clamp to bounds */
+    if (newtop < 0)
+        newtop = 0;
+    if (newtop >= rt->rows)
+        newtop = rt->rows - 1;
+    if (newbottom < 0)
+        newbottom = 0;
+    if (newbottom >= rt->rows)
+        newbottom = rt->rows - 1;
+
+    /* check for range validity */
+    if (newtop > newbottom)
+        return;
+    rt->scrolltop = newtop;
+    rt->scrollbottom = newbottom;
 }
 
-void rote_vt_write(RoteTerm *rt, const char *data, int len)
+static void es_interpret_csi(madtty_t *rt)
 {
-    if (rt->pd->pty < 0) {
-        /* no pty, so just inject the data plain and simple */
-        rote_vt_inject(rt, data, len);
+    static int csiparam[MAX_CSI_ES_PARAMS];
+    int param_count = 0;
+    const char *p = rt->esbuf + 1;
+    char verb = rt->esbuf[rt->esbuf_len - 1];
+
+    if (!strncmp(rt->esbuf, "[?", 2)) { /* private-mode CSI, ignore */
         return;
     }
 
-    /* write data to pty. Keep calling write() until we have written
-     * everything. */
-    while (len > 0) {
-        int byteswritten = write(rt->pd->pty, data, len);
-        if (byteswritten < 0) {
-            /* very ugly way to inform the error. Improvements welcome! */
-            static char errormsg[] = "\n(ROTE: pty write() error)\n";
-            rote_vt_inject(rt, errormsg, strlen(errormsg));
-            return;
+    /* parse numeric parameters */
+    while (isdigit((unsigned char)*p) || *p == ';') {
+        if (*p == ';') {
+            if (param_count >= MAX_CSI_ES_PARAMS) return; /* too long! */
+            csiparam[param_count++] = 0;
+        } else {
+            if (param_count == 0) csiparam[param_count++] = 0;
+            csiparam[param_count - 1] *= 10;
+            csiparam[param_count - 1] += *p - '0';
         }
 
-        data += byteswritten;
-        len  -= byteswritten;
+        p++;
+    }
+
+    /* delegate handling depending on command character (verb) */
+    switch (verb) {
+      case 'h':
+        if (param_count == 1 && csiparam[0] == 4) /* insert mode */
+            rt->insert = true;
+        break;
+      case 'l':
+        if (param_count == 1 && csiparam[0] == 4) /* replace mode */
+            rt->insert = false;
+        break;
+      case 'm': /* it's a 'set attribute' sequence */
+        interpret_csi_SGR(rt, csiparam, param_count); break;
+      case 'J': /* it's an 'erase display' sequence */
+        interpret_csi_ED(rt, csiparam, param_count); break;
+      case 'H': case 'f': /* it's a 'move cursor' sequence */
+        interpret_csi_CUP(rt, csiparam, param_count); break;
+      case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
+      case 'e': case 'a': case 'd': case '`':
+        /* it is a 'relative move' */
+        interpret_csi_C(rt, verb, csiparam, param_count); break;
+      case 'K': /* erase line */
+        interpret_csi_EL(rt, csiparam, param_count); break;
+      case '@': /* insert characters */
+        interpret_csi_ICH(rt, csiparam, param_count); break;
+      case 'P': /* delete characters */
+        interpret_csi_DCH(rt, csiparam, param_count); break;
+      case 'L': /* insert lines */
+        interpret_csi_IL(rt, csiparam, param_count); break;
+      case 'M': /* delete lines */
+        interpret_csi_DL(rt, csiparam, param_count); break;
+      case 'X': /* erase chars */
+        interpret_csi_ECH(rt, csiparam, param_count); break;
+      case 'r': /* set scrolling region */
+        interpret_csi_DECSTBM(rt, csiparam, param_count); break;
+      case 's': /* save cursor location */
+        rt->curs_srow = rt->curs_col;
+        rt->curs_scol = rt->curs_row;
+        break;
+      case 'u': /* restore cursor location */
+        rt->curs_col = rt->curs_srow;
+        rt->curs_row = rt->curs_scol;
+        break;
+      default:
+        break;
     }
 }
 
-void rote_vt_install_handler(RoteTerm *rt, rote_es_handler_t handler)
+static void try_interpret_escape_seq(madtty_t *rt)
 {
-    rt->pd->handler = handler;
+    char firstchar = rt->esbuf[0];
+    char lastchar  = rt->esbuf[rt->esbuf_len-1];
+
+    if (!firstchar)
+        return;  /* too early to do anything */
+
+    /* interpret ESC-M as reverse line-feed */
+    if (firstchar == 'M') {
+        cursor_line_up(rt);
+        cancel_escape_sequence(rt);
+        return;
+    }
+
+    if (firstchar != '[' && firstchar != ']') {
+        /* unrecognized escape sequence. Let's forget about it. */
+        cancel_escape_sequence(rt);
+        return;
+    }
+
+    if (firstchar == '[' && is_valid_csi_ender(lastchar)) {
+        es_interpret_csi(rt);
+        cancel_escape_sequence(rt);
+    } else if (firstchar == ']' && lastchar == '\a') {
+        /* we have an xterm escape sequence: interpret it */
+
+        /* es_interpret_xterm_es(rt);     -- TODO!*/
+        cancel_escape_sequence(rt);
+    }
+
+    /* if the escape sequence took up all available space and could
+     * not yet be parsed, abort it */
+    if (rt->esbuf_len + 1 >= ESEQ_BUF_SIZE)
+        cancel_escape_sequence(rt);
 }
 
-void *rote_vt_take_snapshot(RoteTerm *rt)
+int madtty_inject(madtty_t *rt, const char *data, int len)
 {
-    int i;
-    int bytes_per_row = sizeof(RoteCell) * rt->cols;
-    void *buf = malloc(bytes_per_row * rt->rows);
-    void *ptr = buf;
+    int pos;
+
+    for (pos = 0; pos < len; pos++) {
+        if ((unsigned char)data[pos] <= 31) {
+            handle_control_char(rt, data[pos]);
+            continue;
+        }
+
+        if (rt->escaped && rt->esbuf_len < ESEQ_BUF_SIZE) {
+            /* append character to ongoing escape sequence */
+            rt->esbuf[rt->esbuf_len] = data[pos];
+            rt->esbuf[++rt->esbuf_len] = 0;
 
-    for (i = 0; i < rt->rows; i++, ptr += bytes_per_row)
-        memcpy(ptr, rt->cells[i], bytes_per_row);
+            try_interpret_escape_seq(rt);
+        } else
+        if (rt->graphmode) {
+            put_graphmode_char(rt, data[pos]);
+        } else {
+            static int8_t const lens[5] = { 1, -1, 2, 3, 4 };
+            int bsf = __builtin_clz(~((unsigned char)data[pos] << 24));
 
-    return buf;
+            if (pos + lens[bsf] > len)
+                return pos;
+
+            put_normal_char(rt, data + pos, lens[bsf]);
+            pos += lens[bsf] - 1;
+        }
+    }
+
+    return len;
 }
 
-void rote_vt_restore_snapshot(RoteTerm *rt, void *snapbuf)
+madtty_t *madtty_create(int rows, int cols)
 {
+    madtty_t *rt;
     int i;
-    int bytes_per_row = sizeof(RoteCell) * rt->cols;
 
-    for (i = 0; i < rt->rows; i++, snapbuf += bytes_per_row) {
-        rt->line_dirty[i] = true;
-        memcpy(rt->cells[i], snapbuf, bytes_per_row);
+    if (rows <= 0 || cols <= 0)
+        return NULL;
+
+    rt = (madtty_t*)calloc(sizeof(madtty_t), 1);
+    if (!rt)
+        return NULL;
+
+    /* record dimensions */
+    rt->rows = rows;
+    rt->cols = cols;
+
+    /* default mode is replace */
+    rt->insert = false; 
+
+    /* create the cell matrix */
+    rt->cells = (RoteCell**)calloc(sizeof(RoteCell*), rt->rows);
+    for (i = 0; i < rt->rows; i++) {
+        rt->cells[i] = (RoteCell*)calloc(sizeof(RoteCell), rt->cols);
     }
+
+    /* initialization of other public fields */
+    rt->curs_row = rt->curs_col = 0;
+    rt->curattrs = A_NORMAL;  /* white text over black background */
+
+    rt->pty = -1;  /* no pty for now */
+
+    /* initial scrolling area is the whole window */
+    rt->scrolltop = 0;
+    rt->scrollbottom = rt->rows - 1;
+
+    return rt;
 }
 
-int rote_vt_get_pty_fd(RoteTerm *rt)
+void madtty_destroy(madtty_t *rt)
 {
-    return rt->pd->pty;
+    int i;
+    if (!rt)
+        return;
+
+    for (i = 0; i < rt->rows; i++) {
+        free(rt->cells[i]);
+    }
+    free(rt->cells);
+    free(rt);
 }
 
-static const char *keytable[KEY_MAX+1];
-static int initialized = 0;
+void madtty_draw(madtty_t *rt, WINDOW *win, int srow, int scol)
+{
+    int i, j;
+
+    for (i = 0; i < rt->rows; i++) {
+        wmove(win, srow + i, scol);
+        for (j = 0; j < rt->cols; j++) {
+            wattrset(win, (rt->cells[i][j].attrs & ~077) | COLOR_PAIR(rt->cells[i][j].attrs & 077));
+            if (rt->cells[i][j].len && rt->cells[i][j].s[0] >= ' ') {
+                waddnstr(win, rt->cells[i][j].s, rt->cells[i][j].len);
+            } else {
+                waddch(win, ' ');
+            }
+        }
+    }
+
+    wmove(win, srow + rt->curs_row, scol + rt->curs_col);
+}
 
-static void keytable_init();
+/******************************************************/
 
-void rote_vt_keypress(RoteTerm *rt, int keycode)
+pid_t madtty_forkpty(madtty_t *rt, const char *path, const char *argv[])
 {
-    char c = (char) keycode;
+    struct winsize ws;
+    pid_t pid;
+
+    ws.ws_row    = rt->rows;
+    ws.ws_col    = rt->cols;
+    ws.ws_xpixel = ws.ws_ypixel = 0;
 
-    if (!initialized) keytable_init();
+    pid = forkpty(&rt->pty, NULL, NULL, &ws);
+    if (pid < 0)
+        return -1;
 
-    if (keycode >= 0 && keycode < KEY_MAX && keytable[keycode])
-        rote_vt_write(rt, keytable[keycode], strlen(keytable[keycode]));
-    else
-        rote_vt_write(rt, &c, 1); /* not special, just write it */
+    if (pid == 0) {
+        setsid();
+
+        setenv("TERM", "linux", 1);
+        execv(path, (char *const*)argv);
+        fprintf(stderr, "\nexecv() failed.\nCommand: '%s'\n", argv[0]);
+        exit(1);
+    }
+
+    return rt->childpid = pid;
+}
+
+int madtty_read(madtty_t *rt, char *buf, int buflen)
+{
+    if (rt->pty < 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    return read(rt->pty, buf, buflen);
 }
 
-static void keytable_init()
+int madtty_write(madtty_t *rt, const char *data, int len)
 {
-    initialized = 1;
-    memset(keytable, 0, KEY_MAX+1 * sizeof(const char*));
-
-    keytable['\n']          = "\r";
-    keytable[KEY_UP]        = "\e[A";
-    keytable[KEY_DOWN]      = "\e[B";
-    keytable[KEY_RIGHT]     = "\e[C";
-    keytable[KEY_LEFT]      = "\e[D";
-    keytable[KEY_BACKSPACE] = "\b";
-    keytable[KEY_HOME]      = "\e[1~";
-    keytable[KEY_IC]        = "\e[2~";
-    keytable[KEY_DC]        = "\e[3~";
-    keytable[KEY_END]       = "\e[4~";
-    keytable[KEY_PPAGE]     = "\e[5~";
-    keytable[KEY_NPAGE]     = "\e[6~";
-    keytable[KEY_SUSPEND]   = "\x1A";  /* Ctrl+Z gets mapped to this */
-    keytable[KEY_F(1)]      = "\e[[A";
-    keytable[KEY_F(2)]      = "\e[[B";
-    keytable[KEY_F(3)]      = "\e[[C";
-    keytable[KEY_F(4)]      = "\e[[D";
-    keytable[KEY_F(5)]      = "\e[[E";
-    keytable[KEY_F(6)]      = "\e[17~";
-    keytable[KEY_F(7)]      = "\e[18~";
-    keytable[KEY_F(8)]      = "\e[19~";
-    keytable[KEY_F(9)]      = "\e[20~";
-    keytable[KEY_F(10)]     = "\e[21~";
+    int res;
+
+    if (rt->pty < 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+again:
+    res = write(rt->pty, data, len);
+    if (res < 0) {
+        if (errno == EINTR || errno == EAGAIN)
+            goto again;
+    }
+
+    return res;
 }
 
+static char const * const keytable[KEY_MAX+1] = {
+    ['\n']          = "\r",
+    [KEY_UP]        = "\e[A",
+    [KEY_DOWN]      = "\e[B",
+    [KEY_RIGHT]     = "\e[C",
+    [KEY_LEFT]      = "\e[D",
+    [KEY_BACKSPACE] = "\b",
+    [KEY_HOME]      = "\e[1~",
+    [KEY_IC]        = "\e[2~",
+    [KEY_DC]        = "\e[3~",
+    [KEY_END]       = "\e[4~",
+    [KEY_PPAGE]     = "\e[5~",
+    [KEY_NPAGE]     = "\e[6~",
+    [KEY_SUSPEND]   = "\x1A",  /* Ctrl+Z gets mapped to this */
+    [KEY_F(1)]      = "\e[[A",
+    [KEY_F(2)]      = "\e[[B",
+    [KEY_F(3)]      = "\e[[C",
+    [KEY_F(4)]      = "\e[[D",
+    [KEY_F(5)]      = "\e[[E",
+    [KEY_F(6)]      = "\e[17~",
+    [KEY_F(7)]      = "\e[18~",
+    [KEY_F(8)]      = "\e[19~",
+    [KEY_F(9)]      = "\e[20~",
+    [KEY_F(10)]     = "\e[21~",
+};
+
+void madtty_keypress(madtty_t *rt, int keycode)
+{
+    char c = (char)keycode;
+    const char *buf;
+    int len;
+
+    if (keycode >= 0 && keycode < KEY_MAX && keytable[keycode]) {
+        buf = keytable[keycode];
+        len = strlen(keytable[keycode]);
+    } else {
+        buf = &c;
+        len = 1;
+    }
+
+    while (len > 0) {
+        int res = madtty_write(rt, buf, len);
+        if (res < 0)
+            return;
+
+        buf += res;
+        len -= res;
+    }
+}
 
+void madtty_initialize(void)
+{
+    setlocale(LC_ALL, "");
+    initscr();
+    noecho();
+    start_color();
+    raw();
+    nodelay(stdscr, TRUE);
+    keypad(stdscr, TRUE);
+
+    for (int i = 0; i < 8 * 8; i++)
+        init_pair(i, i >> 3, i & 7);
+}