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