80db4c6d633f2e9eb061b50acb11a8dbca146ea6
[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 <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 {
36     RoteTerm *rt;
37     int i, j;
38
39     if (rows <= 0 || cols <= 0) return NULL;
40
41     if (! (rt = (RoteTerm*) malloc(sizeof(RoteTerm))) ) return NULL;
42     memset(rt, 0, sizeof(RoteTerm));
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*) malloc(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*) malloc(sizeof(RoteTermPrivate));
73     memset(rt->pd, 0, sizeof(RoteTermPrivate));
74
75     rt->pd->pty = -1;  /* no pty for now */
76
77     /* initial scrolling area is the whole window */
78     rt->pd->scrolltop = 0;
79     rt->pd->scrollbottom = rt->rows - 1;
80
81     return rt;
82 }
83
84 void rote_vt_destroy(RoteTerm *rt)
85 {
86     int i;
87     if (!rt) return;
88
89     free(rt->pd);
90     free(rt->line_dirty);
91     for (i = 0; i < rt->rows; i++) free(rt->cells[i]);
92     free(rt->cells);
93     free(rt);
94 }
95
96 #ifdef USE_NCURSES
97
98 static void default_cur_set_attr(WINDOW *win, unsigned char attr)
99 {
100     int cp = ROTE_ATTR_BG(attr) * 8 + 7 - ROTE_ATTR_FG(attr);
101     if (!cp) wattrset(win, A_NORMAL);
102     else     wattrset(win, COLOR_PAIR(cp));
103
104     if (ROTE_ATTR_BOLD(attr))     wattron(win, A_BOLD);
105     if (ROTE_ATTR_BLINK(attr))    wattron(win, A_BLINK);
106 }
107
108 static inline unsigned char ensure_printable(unsigned char ch)
109 {
110     return ch >= 32 ? ch : 32;
111 }
112
113 void rote_vt_draw(RoteTerm *rt, WINDOW *win, int srow, int scol, 
114                   void (*cur_set_attr)(WINDOW*,unsigned char)) {
115
116     int i, j;
117     rote_vt_update(rt);
118
119     if (!cur_set_attr) cur_set_attr = default_cur_set_attr;
120     for (i = 0; i < rt->rows; i++) {
121         wmove(win, srow + i, scol);
122         for (j = 0; j < rt->cols; j++) {
123             (*cur_set_attr)(win, rt->cells[i][j].attr);
124             waddch(win, ensure_printable(rt->cells[i][j].ch));
125         }
126     }
127
128     wmove(win, srow + rt->crow, scol + rt->ccol);
129 }
130
131 #endif
132
133 #ifdef USE_PTY
134
135 pid_t rote_vt_forkpty(RoteTerm *rt, const char *command)
136 {
137     struct winsize ws;
138     pid_t childpid;
139
140     ws.ws_row = rt->rows;
141     ws.ws_col = rt->cols;
142     ws.ws_xpixel = ws.ws_ypixel = 0;
143
144     childpid = forkpty(&rt->pd->pty, NULL, NULL, &ws);
145     if (childpid < 0) return -1;
146
147     if (childpid == 0) {
148         /* we are the child, running under the slave side of the pty. */
149
150         /* Cajole application into using linux-console-compatible escape
151          * sequences (which is what we are prepared to interpret) */
152         setenv("TERM", "linux", 1);
153
154         /* Now we will exec /bin/sh -c command. */
155         execl("/bin/sh", "/bin/sh", "-c", command, NULL);
156
157         fprintf(stderr, "\nexecl() failed.\nCommand: '%s'\n", command);
158         exit(127);  /* error exec'ing */
159     }
160
161     /* if we got here we are the parent process */
162     rt->childpid = childpid;
163     return childpid;
164 }
165
166 void rote_vt_forsake_child(RoteTerm *rt)
167 {
168     if (rt->pd->pty >= 0) close(rt->pd->pty);
169     rt->pd->pty = -1;
170     rt->childpid = 0;
171 }
172
173 #endif
174
175 void rote_vt_update(RoteTerm *rt)
176 {
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 {
211     if (rt->pd->pty < 0) {
212         /* no pty, so just inject the data plain and simple */
213         rote_vt_inject(rt, data, len);
214         return;
215     }
216
217     /* write data to pty. Keep calling write() until we have written
218      * everything. */
219     while (len > 0) {
220         int byteswritten = write(rt->pd->pty, data, len);
221         if (byteswritten < 0) {
222             /* very ugly way to inform the error. Improvements welcome! */
223             static char errormsg[] = "\n(ROTE: pty write() error)\n";
224             rote_vt_inject(rt, errormsg, strlen(errormsg));
225             return;
226         }
227
228         data += byteswritten;
229         len  -= byteswritten;
230     }
231 }
232
233 void rote_vt_install_handler(RoteTerm *rt, rote_es_handler_t handler)
234 {
235     rt->pd->handler = handler;
236 }
237
238 void *rote_vt_take_snapshot(RoteTerm *rt)
239 {
240     int i;
241     int bytes_per_row = sizeof(RoteCell) * rt->cols;
242     void *buf = malloc(bytes_per_row * rt->rows);
243     void *ptr = buf;
244
245     for (i = 0; i < rt->rows; i++, ptr += bytes_per_row)
246         memcpy(ptr, rt->cells[i], bytes_per_row);
247
248     return buf;
249 }
250
251 void rote_vt_restore_snapshot(RoteTerm *rt, void *snapbuf)
252 {
253     int i;
254     int bytes_per_row = sizeof(RoteCell) * rt->cols;
255
256     for (i = 0; i < rt->rows; i++, snapbuf += bytes_per_row) {
257         rt->line_dirty[i] = true;
258         memcpy(rt->cells[i], snapbuf, bytes_per_row);
259     }
260 }
261
262 int rote_vt_get_pty_fd(RoteTerm *rt)
263 {
264     return rt->pd->pty;
265 }
266
267 static const char *keytable[KEY_MAX+1];
268 static int initialized = 0;
269
270 static void keytable_init();
271
272 void rote_vt_keypress(RoteTerm *rt, int keycode)
273 {
274     char c = (char) keycode;
275
276     if (!initialized) keytable_init();
277
278     if (keycode >= 0 && keycode < KEY_MAX && keytable[keycode])
279         rote_vt_write(rt, keytable[keycode], strlen(keytable[keycode]));
280     else
281         rote_vt_write(rt, &c, 1); /* not special, just write it */
282 }
283
284 static void keytable_init()
285 {
286     initialized = 1;
287     memset(keytable, 0, KEY_MAX+1 * sizeof(const char*));
288
289     keytable['\n']          = "\r";
290     keytable[KEY_UP]        = "\e[A";
291     keytable[KEY_DOWN]      = "\e[B";
292     keytable[KEY_RIGHT]     = "\e[C";
293     keytable[KEY_LEFT]      = "\e[D";
294     keytable[KEY_BACKSPACE] = "\b";
295     keytable[KEY_HOME]      = "\e[1~";
296     keytable[KEY_IC]        = "\e[2~";
297     keytable[KEY_DC]        = "\e[3~";
298     keytable[KEY_END]       = "\e[4~";
299     keytable[KEY_PPAGE]     = "\e[5~";
300     keytable[KEY_NPAGE]     = "\e[6~";
301     keytable[KEY_SUSPEND]   = "\x1A";  /* Ctrl+Z gets mapped to this */
302     keytable[KEY_F(1)]      = "\e[[A";
303     keytable[KEY_F(2)]      = "\e[[B";
304     keytable[KEY_F(3)]      = "\e[[C";
305     keytable[KEY_F(4)]      = "\e[[D";
306     keytable[KEY_F(5)]      = "\e[[E";
307     keytable[KEY_F(6)]      = "\e[17~";
308     keytable[KEY_F(7)]      = "\e[18~";
309     keytable[KEY_F(8)]      = "\e[19~";
310     keytable[KEY_F(9)]      = "\e[20~";
311     keytable[KEY_F(10)]     = "\e[21~";
312 }
313
314