fix regression
[apps/madtty.git] / madtty / madtty.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 <errno.h>
23 #include <stdlib.h>
24 #include <fcntl.h>
25 #ifdef USE_PTY
26 #include <pty.h>
27 #endif
28 #include <stdio.h>
29 #include <string.h>
30
31 #include "madtty.h"
32 #include "roteprivate.h"
33
34 #define ROTE_VT_UPDATE_ITERATIONS 5
35
36 RoteTerm *rote_vt_create(int rows, int cols)
37 {
38     RoteTerm *rt;
39     int i, j;
40
41     if (rows <= 0 || cols <= 0)
42         return NULL;
43
44     rt = (RoteTerm*)calloc(sizeof(RoteTerm), 1);
45     if (!rt)
46         return NULL;
47
48     /* record dimensions */
49     rt->rows = rows;
50     rt->cols = cols;
51
52     /* default mode is replace */
53     rt->insert = false; 
54
55     /* create the cell matrix */
56     rt->cells = (RoteCell**) malloc(sizeof(RoteCell*) * rt->rows);
57     for (i = 0; i < rt->rows; i++) {
58         /* create row */
59         rt->cells[i] = (RoteCell*) malloc(sizeof(RoteCell) * rt->cols);
60
61         /* fill row with spaces */
62         for (j = 0; j < rt->cols; j++) {
63             rt->cells[i][j].ch   = 0x20;  /* a space */
64             rt->cells[i][j].attr = 0x70;  /* white text, black background */
65         }
66     }
67
68     /* allocate dirtiness array */
69     rt->line_dirty = (bool*)calloc(sizeof(bool), rt->rows);
70
71     /* initialization of other public fields */
72     rt->crow = rt->ccol = 0;
73     rt->curattr = 0x70;  /* white text over black background */
74
75     /* allocate private data */
76     rt->pd = (RoteTermPrivate*)calloc(sizeof(RoteTermPrivate), 1);
77
78     rt->pd->pty = -1;  /* no pty for now */
79
80     /* initial scrolling area is the whole window */
81     rt->pd->scrolltop = 0;
82     rt->pd->scrollbottom = rt->rows - 1;
83
84     return rt;
85 }
86
87 void rote_vt_destroy(RoteTerm *rt)
88 {
89     int i;
90     if (!rt)
91         return;
92
93     free(rt->pd);
94     free(rt->line_dirty);
95     for (i = 0; i < rt->rows; i++) {
96         free(rt->cells[i]);
97     }
98     free(rt->cells);
99     free(rt);
100 }
101
102 #ifdef USE_NCURSES
103
104 static void default_cur_set_attr(WINDOW *win, unsigned char attr)
105 {
106     int cp = ROTE_ATTR_BG(attr) * 8 + 7 - ROTE_ATTR_FG(attr);
107     if (!cp) wattrset(win, A_NORMAL);
108     else     wattrset(win, COLOR_PAIR(cp));
109
110     if (ROTE_ATTR_BOLD(attr))     wattron(win, A_BOLD);
111     if (ROTE_ATTR_BLINK(attr))    wattron(win, A_BLINK);
112 }
113
114 static inline unsigned char ensure_printable(unsigned char ch)
115 {
116     return ch >= 32 ? ch : 32;
117 }
118
119 void rote_vt_draw(RoteTerm *rt, WINDOW *win, int srow, int scol, 
120                   void (*cur_set_attr)(WINDOW*,unsigned char)) {
121
122     int i, j;
123     rote_vt_update(rt);
124
125     if (!cur_set_attr) cur_set_attr = default_cur_set_attr;
126     for (i = 0; i < rt->rows; i++) {
127         wmove(win, srow + i, scol);
128         for (j = 0; j < rt->cols; j++) {
129             (*cur_set_attr)(win, rt->cells[i][j].attr);
130             waddch(win, ensure_printable(rt->cells[i][j].ch));
131         }
132     }
133
134     wmove(win, srow + rt->crow, scol + rt->ccol);
135 }
136
137 #endif
138
139 /******************************************************/
140
141 #define PTYCHAR1 "pqrstuvwxyz"
142 #define PTYCHAR2 "0123456789abcdef"
143
144 /* allocate one pty/tty pair */
145 static int get_pty(char *tty_str)
146 {
147    int fd;
148    char ptydev[] = "/dev/pty??";
149    char ttydev[] = "/dev/tty??";
150    int len = strlen(ttydev);
151    const char *c1, *c2;
152
153    for (c1 = PTYCHAR1; *c1; c1++) {
154        ptydev[len-2] = ttydev[len-2] = *c1;
155        for (c2 = PTYCHAR2; *c2; c2++) {
156            ptydev[len-1] = ttydev[len-1] = *c2;
157            if ((fd = open(ptydev, O_RDWR)) >= 0) {
158                if (access(ttydev, R_OK|W_OK) == 0) {
159                    strcpy(tty_str, ttydev);
160                    return fd;
161                }
162                close(fd);
163            }
164        }
165    }
166    return -1;
167 }
168
169 static int
170 run_process(const char *path, const char **argv, int *fd_ptr, int *pid_ptr)
171 {
172     int pty_fd, pid, i, nb_fds;
173     char tty_name[32];
174     struct winsize ws;
175
176     pty_fd = get_pty(tty_name);
177     if (pty_fd < 0)
178         return -1;
179
180     fcntl(pty_fd, F_SETFL, O_NONBLOCK);
181
182     /* set dummy screen size */
183     ws.ws_col = 80;
184     ws.ws_row = 25;
185     ws.ws_xpixel = ws.ws_col;
186     ws.ws_ypixel = ws.ws_row;
187     ioctl(pty_fd, TIOCSWINSZ, &ws);
188
189     pid = fork();
190     if (pid < 0)
191         return -1;
192
193     if (pid == 0) {
194         /* child process */
195         nb_fds = getdtablesize();
196         for (i = 0; i < nb_fds; i++)
197             close(i);
198         /* open pseudo tty for standard i/o */
199         open(tty_name, O_RDWR);
200         dup(0);
201         dup(0);
202
203         setsid();
204
205         setenv("TERM", "linux", 1);
206         execv(path, (char *const*)argv);
207         fprintf(stderr, "\nexecv() failed.\nCommand: '%s'\n", argv[0]);
208         exit(1);
209     }
210     /* return file info */
211     *fd_ptr = pty_fd;
212     *pid_ptr = pid;
213     return 0;
214 }
215
216
217 #ifdef USE_PTY
218
219 pid_t rote_vt_forkpty(RoteTerm *rt, const char *path, const char *argv[])
220 {
221     struct winsize ws;
222
223     ws.ws_row = rt->rows;
224     ws.ws_col = rt->cols;
225     ws.ws_xpixel = ws.ws_ypixel = 0;
226
227     if (run_process(path, argv, &rt->pd->pty, &rt->childpid)) {
228         return -1;
229     }
230
231     ioctl(rt->pd->pty, TIOCSWINSZ, &ws);
232     return rt->childpid;
233 }
234
235 void rote_vt_forsake_child(RoteTerm *rt)
236 {
237     if (rt->pd->pty >= 0)
238         close(rt->pd->pty);
239     rt->pd->pty  = -1;
240     rt->childpid = 0;
241 }
242
243 #endif
244
245 void rote_vt_update(RoteTerm *rt)
246 {
247     char buf[512];
248     int nbread;
249     int n = ROTE_VT_UPDATE_ITERATIONS;
250
251     while (n--) { /* iterate at most ROVE_VT_UPDATE_ITERATIONS times.
252                    * As Phil Endecott pointed out, if we don't restrict this,
253                    * a program that floods the terminal with output
254                    * could cause this loop to iterate forever, never
255                    * being able to catch up. So we'll rely on the client
256                    * calling rote_vt_update often, as the documentation
257                    * recommends :-) */
258
259         nbread = rote_vt_read(rt, buf, sizeof(buf));
260         if (nbread <= 0)
261             return;
262
263         /* inject the data into the terminal */
264         rote_vt_inject(rt, buf, nbread);
265     }
266 }
267
268 int rote_vt_read(RoteTerm *rt, char *buf, int buflen)
269 {
270     if (rt->pd->pty < 0) {
271         errno = EINVAL;
272         return -1;
273     }
274
275     return read(rt->pd->pty, buf, buflen);
276 }
277
278 void rote_vt_write(RoteTerm *rt, const char *data, int len)
279 {
280     if (rt->pd->pty < 0) {
281         /* no pty, so just inject the data plain and simple */
282         rote_vt_inject(rt, data, len);
283         return;
284     }
285
286     /* write data to pty. Keep calling write() until we have written
287      * everything. */
288     while (len > 0) {
289         int byteswritten = write(rt->pd->pty, data, len);
290         if (byteswritten < 0) {
291             /* very ugly way to inform the error. Improvements welcome! */
292             static char errormsg[] = "\n(ROTE: pty write() error)\n";
293             rote_vt_inject(rt, errormsg, strlen(errormsg));
294             return;
295         }
296
297         data += byteswritten;
298         len  -= byteswritten;
299     }
300 }
301
302 void *rote_vt_take_snapshot(RoteTerm *rt)
303 {
304     const int bytes_per_row = sizeof(RoteCell) * rt->cols;
305     void *buf = malloc(bytes_per_row * rt->rows);
306     void *ptr = buf;
307     int i;
308
309     for (i = 0; i < rt->rows; i++, ptr += bytes_per_row)
310         memcpy(ptr, rt->cells[i], bytes_per_row);
311
312     return buf;
313 }
314
315 void rote_vt_restore_snapshot(RoteTerm *rt, void *snapbuf)
316 {
317     const int bytes_per_row = sizeof(RoteCell) * rt->cols;
318
319     int i;
320
321     for (i = 0; i < rt->rows; i++, snapbuf += bytes_per_row) {
322         rt->line_dirty[i] = true;
323         memcpy(rt->cells[i], snapbuf, bytes_per_row);
324     }
325 }
326
327 int rote_vt_get_pty_fd(RoteTerm *rt)
328 {
329     return rt->pd->pty;
330 }
331
332 static const char *keytable[KEY_MAX+1];
333
334 static void keytable_init()
335 {
336     memset(keytable, 0, KEY_MAX+1 * sizeof(const char*));
337
338     keytable['\n']          = "\r";
339     keytable[KEY_UP]        = "\e[A";
340     keytable[KEY_DOWN]      = "\e[B";
341     keytable[KEY_RIGHT]     = "\e[C";
342     keytable[KEY_LEFT]      = "\e[D";
343     keytable[KEY_BACKSPACE] = "\b";
344     keytable[KEY_HOME]      = "\e[1~";
345     keytable[KEY_IC]        = "\e[2~";
346     keytable[KEY_DC]        = "\e[3~";
347     keytable[KEY_END]       = "\e[4~";
348     keytable[KEY_PPAGE]     = "\e[5~";
349     keytable[KEY_NPAGE]     = "\e[6~";
350     keytable[KEY_SUSPEND]   = "\x1A";  /* Ctrl+Z gets mapped to this */
351     keytable[KEY_F(1)]      = "\e[[A";
352     keytable[KEY_F(2)]      = "\e[[B";
353     keytable[KEY_F(3)]      = "\e[[C";
354     keytable[KEY_F(4)]      = "\e[[D";
355     keytable[KEY_F(5)]      = "\e[[E";
356     keytable[KEY_F(6)]      = "\e[17~";
357     keytable[KEY_F(7)]      = "\e[18~";
358     keytable[KEY_F(8)]      = "\e[19~";
359     keytable[KEY_F(9)]      = "\e[20~";
360     keytable[KEY_F(10)]     = "\e[21~";
361 }
362
363 void rote_vt_keypress(RoteTerm *rt, int keycode)
364 {
365     char c = (char) keycode;
366
367     if (keytable['\n'] == NULL)
368         keytable_init();
369
370     if (keycode >= 0 && keycode < KEY_MAX && keytable[keycode]) {
371         rote_vt_write(rt, keytable[keycode], strlen(keytable[keycode]));
372     } else {
373         rote_vt_write(rt, &c, 1); /* not special, just write it */
374     }
375 }
376