even better
[apps/madtty.git] / madtty / rote.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 <stdlib.h>
23 #ifdef USE_PTY
24 #include <pty.h>
25 #endif
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "madtty.h"
30 #include "roteprivate.h"
31
32 #define ROTE_VT_UPDATE_ITERATIONS 5
33
34 RoteTerm *rote_vt_create(int rows, int cols) {
35    RoteTerm *rt;
36    int i, j;
37
38    if (rows <= 0 || cols <= 0) return NULL;
39
40    if (! (rt = (RoteTerm*) malloc(sizeof(RoteTerm))) ) return NULL;
41    memset(rt, 0, sizeof(RoteTerm));
42
43    /* record dimensions */
44    rt->rows = rows;
45    rt->cols = cols;
46
47    /* default mode is replace */
48    rt->insert = false; 
49
50    /* create the cell matrix */
51    rt->cells = (RoteCell**) malloc(sizeof(RoteCell*) * rt->rows);
52    for (i = 0; i < rt->rows; i++) {
53       /* create row */
54       rt->cells[i] = (RoteCell*) malloc(sizeof(RoteCell) * rt->cols);
55
56       /* fill row with spaces */
57       for (j = 0; j < rt->cols; j++) {
58          rt->cells[i][j].ch = 0x20;    /* a space */
59          rt->cells[i][j].attr = 0x70;  /* white text, black background */
60       }
61    }
62    
63    /* allocate dirtiness array */
64    rt->line_dirty = (bool*) malloc(sizeof(bool) * rt->rows);
65
66    /* initialization of other public fields */
67    rt->crow = rt->ccol = 0;
68    rt->curattr = 0x70;  /* white text over black background */
69
70    /* allocate private data */
71    rt->pd = (RoteTermPrivate*) malloc(sizeof(RoteTermPrivate));
72    memset(rt->pd, 0, sizeof(RoteTermPrivate));
73
74    rt->pd->pty = -1;  /* no pty for now */
75
76    /* initial scrolling area is the whole window */
77    rt->pd->scrolltop = 0;
78    rt->pd->scrollbottom = rt->rows - 1;
79
80    #ifdef DEBUG
81    fprintf(stderr, "Created a %d x %d terminal.\n", rt->rows, rt->cols);
82    #endif
83    
84    return rt;
85 }
86
87 void rote_vt_destroy(RoteTerm *rt) {
88    int i;
89    if (!rt) return;
90
91    free(rt->pd);
92    free(rt->line_dirty);
93    for (i = 0; i < rt->rows; i++) free(rt->cells[i]);
94    free(rt->cells);
95    free(rt);
96 }
97
98 #ifdef USE_NCURSES
99
100 static void default_cur_set_attr(WINDOW *win, unsigned char attr) {
101    int cp = ROTE_ATTR_BG(attr) * 8 + 7 - ROTE_ATTR_FG(attr);
102    if (!cp) wattrset(win, A_NORMAL);
103    else     wattrset(win, COLOR_PAIR(cp));
104
105    if (ROTE_ATTR_BOLD(attr))     wattron(win, A_BOLD);
106    if (ROTE_ATTR_BLINK(attr))    wattron(win, A_BLINK);
107 }
108
109 #endif
110
111 static inline unsigned char ensure_printable(unsigned char ch) 
112                                         { return ch >= 32 ? ch : 32; }
113
114 #ifdef USE_NCURSES
115
116 void rote_vt_draw(RoteTerm *rt, WINDOW *win, int srow, int scol, 
117                                 void (*cur_set_attr)(WINDOW*,unsigned char)) {
118
119    int i, j;
120    rote_vt_update(rt);
121    
122    if (!cur_set_attr) cur_set_attr = default_cur_set_attr;
123    for (i = 0; i < rt->rows; i++) {
124       wmove(win, srow + i, scol);
125       for (j = 0; j < rt->cols; j++) {
126          (*cur_set_attr)(win, rt->cells[i][j].attr);
127          waddch(win, ensure_printable(rt->cells[i][j].ch));
128       }
129    }
130
131    wmove(win, srow + rt->crow, scol + rt->ccol);
132 }
133
134 #endif
135
136 #ifdef USE_PTY
137
138 pid_t rote_vt_forkpty(RoteTerm *rt, const char *command) {
139    struct winsize ws;
140    pid_t childpid;
141    
142    ws.ws_row = rt->rows;
143    ws.ws_col = rt->cols;
144    ws.ws_xpixel = ws.ws_ypixel = 0;
145
146    childpid = forkpty(&rt->pd->pty, NULL, NULL, &ws);
147    if (childpid < 0) return -1;
148
149    if (childpid == 0) {
150       /* we are the child, running under the slave side of the pty. */
151
152       /* Cajole application into using linux-console-compatible escape
153        * sequences (which is what we are prepared to interpret) */
154       setenv("TERM", "linux", 1);
155
156       /* Now we will exec /bin/sh -c command. */
157       execl("/bin/sh", "/bin/sh", "-c", command, NULL);
158
159       fprintf(stderr, "\nexecl() failed.\nCommand: '%s'\n", command);
160       exit(127);  /* error exec'ing */
161    }
162
163    /* if we got here we are the parent process */
164    rt->childpid = childpid;
165    return childpid;
166 }
167
168 void rote_vt_forsake_child(RoteTerm *rt) {
169    if (rt->pd->pty >= 0) close(rt->pd->pty);
170    rt->pd->pty = -1;
171    rt->childpid = 0;
172 }
173
174 #endif
175
176 void rote_vt_update(RoteTerm *rt) {
177    fd_set ifs;
178    struct timeval tvzero;
179    char buf[512];
180    int bytesread;
181    int n = ROTE_VT_UPDATE_ITERATIONS;
182    if (rt->pd->pty < 0) return;  /* nothing to pump */
183
184    while (n--) { /* iterate at most ROVE_VT_UPDATE_ITERATIONS times.
185                   * As Phil Endecott pointed out, if we don't restrict this,
186                   * a program that floods the terminal with output
187                   * could cause this loop to iterate forever, never
188                   * being able to catch up. So we'll rely on the client
189                   * calling rote_vt_update often, as the documentation
190                   * recommends :-) */
191
192       /* check if pty has something to say */
193       FD_ZERO(&ifs); FD_SET(rt->pd->pty, &ifs);
194       tvzero.tv_sec = 0; tvzero.tv_usec = 0;
195    
196       if (select(rt->pd->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
197          return; /* nothing to read, or select() failed */
198
199       /* read what we can. This is guaranteed not to block, since
200        * select() told us there was something to read. */
201       bytesread = read(rt->pd->pty, buf, 512);
202       if (bytesread <= 0) return;   
203
204       /* inject the data into the terminal */
205       rote_vt_inject(rt, buf, bytesread);
206    }
207 }
208
209 void rote_vt_write(RoteTerm *rt, const char *data, int len) {
210    if (rt->pd->pty < 0) {
211       /* no pty, so just inject the data plain and simple */
212       rote_vt_inject(rt, data, len);
213       return;
214    }
215
216    /* write data to pty. Keep calling write() until we have written
217     * everything. */
218    while (len > 0) {
219       int byteswritten = write(rt->pd->pty, data, len);
220       if (byteswritten < 0) {
221          /* very ugly way to inform the error. Improvements welcome! */
222          static char errormsg[] = "\n(ROTE: pty write() error)\n";
223          rote_vt_inject(rt, errormsg, strlen(errormsg));
224          return;
225       }
226
227       data += byteswritten;
228       len  -= byteswritten;
229    }
230 }
231
232 void rote_vt_install_handler(RoteTerm *rt, rote_es_handler_t handler) {
233    rt->pd->handler = handler;
234 }
235
236 void *rote_vt_take_snapshot(RoteTerm *rt) {
237    int i;
238    int bytes_per_row = sizeof(RoteCell) * rt->cols;
239    void *buf = malloc(bytes_per_row * rt->rows);
240    void *ptr = buf;
241
242    for (i = 0; i < rt->rows; i++, ptr += bytes_per_row)
243       memcpy(ptr, rt->cells[i], bytes_per_row);
244
245    return buf;
246 }
247
248 void rote_vt_restore_snapshot(RoteTerm *rt, void *snapbuf) {
249    int i;
250    int bytes_per_row = sizeof(RoteCell) * rt->cols;
251
252    for (i = 0; i < rt->rows; i++, snapbuf += bytes_per_row) {
253       rt->line_dirty[i] = true;
254       memcpy(rt->cells[i], snapbuf, bytes_per_row);
255    }
256 }
257
258 int rote_vt_get_pty_fd(RoteTerm *rt) {
259    return rt->pd->pty;
260 }
261