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