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