JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
working on old repo, merging recent changesets.
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <locale.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <sys/ioctl.h>
14 #include <sys/select.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <unistd.h>
19 #include <X11/Xatom.h>
20 #include <X11/Xlib.h>
21 #include <X11/Xutil.h>
22 #include <X11/cursorfont.h>
23 #include <X11/keysym.h>
24
25 #include <sys/time.h>
26 #include <time.h>
27
28 #if   defined(__linux)
29  #include <pty.h>
30 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
31  #include <util.h>
32 #elif defined(__FreeBSD__) || defined(__DragonFly__)
33  #include <libutil.h>
34 #endif
35
36 #define USAGE \
37         "st-" VERSION ", (c) 2010-2011 st engineers\n" \
38         "usage: st [-t title] [-c class] [-w windowid] [-v] [-e command...]\n"
39
40 /* XEMBED messages */
41 #define XEMBED_FOCUS_IN  4
42 #define XEMBED_FOCUS_OUT 5
43
44 /* Arbitrary sizes */
45 #define ESC_TITLE_SIZ 256
46 #define ESC_BUF_SIZ   256
47 #define ESC_ARG_SIZ   16
48 #define DRAW_BUF_SIZ  1024
49 #define UTF_SIZ       4
50 #define XK_NO_MOD     UINT_MAX
51 #define XK_ANY_MOD    0
52
53 #define SERRNO strerror(errno)
54 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
55 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
56 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
57 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
58 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
59 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
60 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
61 #define IS_SET(flag) (term.mode & (flag))
62 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
63 #define X2COL(x) (((x) - BORDER)/xw.cw)
64 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
65
66 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
67 enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
68 enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
69        CURSOR_SAVE, CURSOR_LOAD };
70 enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
71 enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
72 enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8,
73        MODE_CRLF=16, MODE_MOUSEBTN=32, MODE_MOUSEMOTION=64, MODE_MOUSE=32|64, MODE_REVERSE=128 };
74 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
75 enum { WIN_VISIBLE=1, WIN_REDRAW=2, WIN_FOCUSED=4 };
76
77 #undef B0
78 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
79
80 typedef struct {
81         char c[UTF_SIZ];     /* character code */
82         char mode;  /* attribute flags */
83         int fg;     /* foreground      */
84         int bg;     /* background      */
85         char state; /* state flags     */
86 } Glyph;
87
88 typedef Glyph* Line;
89
90 typedef struct {
91         Glyph attr;      /* current char attributes */
92         int x;
93         int y;
94         char state;
95 } TCursor;
96
97 /* CSI Escape sequence structs */
98 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
99 typedef struct {
100         char buf[ESC_BUF_SIZ]; /* raw string */
101         int len;               /* raw string length */
102         char priv;
103         int arg[ESC_ARG_SIZ];
104         int narg;              /* nb of args */
105         char mode;
106 } CSIEscape;
107
108 /* Internal representation of the screen */
109 typedef struct {
110         int row;        /* nb row */
111         int col;        /* nb col */
112         Line* line;     /* screen */
113         Line* alt;      /* alternate screen */
114         TCursor c;      /* cursor */
115         int top;        /* top    scroll limit */
116         int bot;        /* bottom scroll limit */
117         int mode;       /* terminal mode flags */
118         int esc;        /* escape state flags */
119         char title[ESC_TITLE_SIZ];
120         int titlelen;
121 } Term;
122
123 /* Purely graphic info */
124 typedef struct {
125         Display* dpy;
126         Colormap cmap;
127         Window win;
128         Pixmap buf;
129         Atom xembed;
130         XIM xim;
131         XIC xic;
132         int scr;
133         int w;  /* window width */
134         int h;  /* window height */
135         int bufw; /* pixmap width  */
136         int bufh; /* pixmap height */
137         int ch; /* char height */
138         int cw; /* char width  */
139         char state; /* focus, redraw, visible */
140 } XWindow;
141
142 typedef struct {
143         KeySym k;
144         unsigned int mask;
145         char s[ESC_BUF_SIZ];
146 } Key;
147
148 /* Drawing Context */
149 typedef struct {
150         unsigned long col[256];
151         GC gc;
152         struct {
153                 int ascent;
154                 int descent;
155                 short lbearing;
156                 short rbearing;
157                 XFontSet set;
158         } font, bfont;
159 } DC;
160
161 /* TODO: use better name for vars... */
162 typedef struct {
163         int mode;
164         int bx, by;
165         int ex, ey;
166         struct {int x, y;} b, e;
167         char *clip;
168         Atom xtarget;
169         struct timeval tclick1;
170         struct timeval tclick2;
171 } Selection;
172
173 #include "config.h"
174
175 static void die(const char*, ...);
176 static void draw(void);
177 static void drawregion(int, int, int, int);
178 static void execsh(void);
179 static void sigchld(int);
180 static void run(void);
181
182 static void csidump(void);
183 static void csihandle(void);
184 static void csiparse(void);
185 static void csireset(void);
186
187 static void tclearregion(int, int, int, int);
188 static void tcursor(int);
189 static void tdeletechar(int);
190 static void tdeleteline(int);
191 static void tinsertblank(int);
192 static void tinsertblankline(int);
193 static void tmoveto(int, int);
194 static void tnew(int, int);
195 static void tnewline(int);
196 static void tputtab(void);
197 static void tputc(char*);
198 static void treset(void);
199 static int tresize(int, int);
200 static void tscrollup(int, int);
201 static void tscrolldown(int, int);
202 static void tsetattr(int*, int);
203 static void tsetchar(char*);
204 static void tsetscroll(int, int);
205 static void tswapscreen(void);
206
207 static void ttynew(void);
208 static void ttyread(void);
209 static void ttyresize(int, int);
210 static void ttywrite(const char *, size_t);
211
212 static void xdraws(char *, Glyph, int, int, int, int);
213 static void xhints(void);
214 static void xclear(int, int, int, int);
215 static void xdrawcursor(void);
216 static void xinit(void);
217 static void xloadcols(void);
218 static void xseturgency(int);
219 static void xsetsel(char*);
220 static void xresize(int, int);
221
222 static void expose(XEvent *);
223 static void visibility(XEvent *);
224 static void unmap(XEvent *);
225 static char* kmap(KeySym, unsigned int state);
226 static void kpress(XEvent *);
227 static void cmessage(XEvent *);
228 static void resize(XEvent *);
229 static void focus(XEvent *);
230 static void brelease(XEvent *);
231 static void bpress(XEvent *);
232 static void bmotion(XEvent *);
233 static void selnotify(XEvent *);
234 static void selrequest(XEvent *);
235
236 static void selinit(void);
237 static inline int selected(int, int);
238 static void selcopy(void);
239 static void selpaste();
240
241 static int utf8decode(char *, long *);
242 static int utf8encode(long *, char *);
243 static int utf8size(char *);
244 static int isfullutf8(char *, int);
245
246 static void (*handler[LASTEvent])(XEvent *) = {
247         [KeyPress] = kpress,
248         [ClientMessage] = cmessage,
249         [ConfigureNotify] = resize,
250         [VisibilityNotify] = visibility,
251         [UnmapNotify] = unmap,
252         [Expose] = expose,
253         [FocusIn] = focus,
254         [FocusOut] = focus,
255         [MotionNotify] = bmotion,
256         [ButtonPress] = bpress,
257         [ButtonRelease] = brelease,
258         [SelectionNotify] = selnotify,
259         [SelectionRequest] = selrequest,
260 };
261
262 /* Globals */
263 static DC dc;
264 static XWindow xw;
265 static Term term;
266 static CSIEscape escseq;
267 static int cmdfd;
268 static pid_t pid;
269 static Selection sel;
270 static char **opt_cmd  = NULL;
271 static char *opt_title = NULL;
272 static char *opt_embed = NULL;
273 static char *opt_class = NULL;
274
275 int
276 utf8decode(char *s, long *u) {
277         unsigned char c;
278         int i, n, rtn;
279
280         rtn = 1;
281         c = *s;
282         if(~c&B7) { /* 0xxxxxxx */
283                 *u = c;
284                 return rtn;
285         } else if((c&(B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
286                 *u = c&(B4|B3|B2|B1|B0);
287                 n = 1;
288         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
289                 *u = c&(B3|B2|B1|B0);
290                 n = 2;
291         } else if((c&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
292                 *u = c&(B2|B1|B0);
293                 n = 3;
294         } else
295                 goto invalid;
296         for(i=n,++s; i>0; --i,++rtn,++s) {
297                 c = *s;
298                 if((c&(B7|B6)) != B7) /* 10xxxxxx */
299                         goto invalid;
300                 *u <<= 6;
301                 *u |= c&(B5|B4|B3|B2|B1|B0);
302         }
303         if((n == 1 && *u < 0x80) ||
304            (n == 2 && *u < 0x800) ||
305            (n == 3 && *u < 0x10000) ||
306            (*u >= 0xD800 && *u <= 0xDFFF))
307                 goto invalid;
308         return rtn;
309 invalid:
310         *u = 0xFFFD;
311         return rtn;
312 }
313
314 int
315 utf8encode(long *u, char *s) {
316         unsigned char *sp;
317         unsigned long uc;
318         int i, n;
319
320         sp = (unsigned char*) s;
321         uc = *u;
322         if(uc < 0x80) {
323                 *sp = uc; /* 0xxxxxxx */
324                 return 1;
325         } else if(*u < 0x800) {
326                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
327                 n = 1;
328         } else if(uc < 0x10000) {
329                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
330                 n = 2;
331         } else if(uc <= 0x10FFFF) {
332                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
333                 n = 3;
334         } else {
335                 goto invalid;
336         }
337         for(i=n,++sp; i>0; --i,++sp)
338                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
339         return n+1;
340 invalid:
341         /* U+FFFD */
342         *s++ = '\xEF';
343         *s++ = '\xBF';
344         *s = '\xBD';
345         return 3;
346 }
347
348 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
349    UTF-8 otherwise return 0 */
350 int
351 isfullutf8(char *s, int b) {
352         unsigned char *c1, *c2, *c3;
353
354         c1 = (unsigned char *) s;
355         c2 = (unsigned char *) ++s;
356         c3 = (unsigned char *) ++s;
357         if(b < 1)
358                 return 0;
359         else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
360                 return 0;
361         else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
362             ((b == 1) ||
363             ((b == 2) && (*c2&(B7|B6)) == B7)))
364                 return 0;
365         else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
366             ((b == 1) ||
367             ((b == 2) && (*c2&(B7|B6)) == B7) ||
368             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
369                 return 0;
370         else
371                 return 1;
372 }
373
374 int
375 utf8size(char *s) {
376         unsigned char c = *s;
377
378         if(~c&B7)
379                 return 1;
380         else if((c&(B7|B6|B5)) == (B7|B6))
381                 return 2;
382         else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
383                 return 3;
384         else
385                 return 4;
386 }
387
388 void
389 selinit(void) {
390         sel.tclick1.tv_sec = 0;
391         sel.tclick1.tv_usec = 0;
392         sel.mode = 0;
393         sel.bx = -1;
394         sel.clip = NULL;
395         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
396         if(sel.xtarget == None)
397                 sel.xtarget = XA_STRING;
398 }
399
400 static inline int
401 selected(int x, int y) {
402         if(sel.ey == y && sel.by == y) {
403                 int bx = MIN(sel.bx, sel.ex);
404                 int ex = MAX(sel.bx, sel.ex);
405                 return BETWEEN(x, bx, ex);
406         }
407         return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
408                 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
409 }
410
411 void
412 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
413         if(b)
414                 *b = e->xbutton.button;
415
416         *x = X2COL(e->xbutton.x);
417         *y = Y2ROW(e->xbutton.y);
418         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
419         sel.b.y = MIN(sel.by, sel.ey);
420         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
421         sel.e.y = MAX(sel.by, sel.ey);
422 }
423
424 void
425 mousereport(XEvent *e) {
426         int x = X2COL(e->xbutton.x);
427         int y = Y2ROW(e->xbutton.y);
428         int button = e->xbutton.button;
429         int state = e->xbutton.state;
430         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
431         static int ob, ox, oy;
432         
433         /* from urxvt */
434         if(e->xbutton.type == MotionNotify) {
435                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
436                         return;
437                 button = ob + 32;
438                 ox = x, oy = y;
439         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
440                 button = 3;
441         } else {
442                 button -= Button1;
443                 if(button >= 3)
444                         button += 64 - 3;
445                 if(e->xbutton.type == ButtonPress) {
446                         ob = button;
447                         ox = x, oy = y;
448                 }
449         }
450         
451         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
452                 + (state & Mod4Mask    ? 8  : 0)
453                 + (state & ControlMask ? 16 : 0);
454         
455         ttywrite(buf, sizeof(buf));
456 }
457
458 void
459 bpress(XEvent *e) {
460         if(IS_SET(MODE_MOUSE))
461                 mousereport(e);
462         else if(e->xbutton.button == Button1) {
463                 sel.mode = 1;
464                 sel.ex = sel.bx = X2COL(e->xbutton.x);
465                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
466         }
467 }
468
469 void
470 selcopy(void) {
471         char *str, *ptr;
472         int x, y, sz, sl, ls = 0;
473
474         if(sel.bx == -1)
475                 str = NULL;
476         else {
477                 sz = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
478                 ptr = str = malloc(sz);
479                 for(y = 0; y < term.row; y++) {
480                         for(x = 0; x < term.col; x++)
481                                 if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y))) {
482                                         sl = utf8size(term.line[y][x].c);
483                                         memcpy(ptr, term.line[y][x].c, sl);
484                                         ptr += sl;
485                                 }
486                         if(ls && y < sel.e.y)
487                                 *ptr++ = '\n';
488                 }
489                 *ptr = 0;
490         }
491         xsetsel(str);
492 }
493
494 void
495 selnotify(XEvent *e) {
496         unsigned long nitems, ofs, rem;
497         int format;
498         unsigned char *data;
499         Atom type;
500
501         ofs = 0;
502         do {
503                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
504                                         False, AnyPropertyType, &type, &format,
505                                         &nitems, &rem, &data)) {
506                         fprintf(stderr, "Clipboard allocation failed\n");
507                         return;
508                 }
509                 ttywrite((const char *) data, nitems * format / 8);
510                 XFree(data);
511                 /* number of 32-bit chunks returned */
512                 ofs += nitems * format / 32;
513         } while(rem > 0);
514 }
515
516 void
517 selpaste() {
518         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
519 }
520
521 void
522 selrequest(XEvent *e) {
523         XSelectionRequestEvent *xsre;
524         XSelectionEvent xev;
525         Atom xa_targets;
526
527         xsre = (XSelectionRequestEvent *) e;
528         xev.type = SelectionNotify;
529         xev.requestor = xsre->requestor;
530         xev.selection = xsre->selection;
531         xev.target = xsre->target;
532         xev.time = xsre->time;
533         /* reject */
534         xev.property = None;
535
536         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
537         if(xsre->target == xa_targets) {
538                 /* respond with the supported type */
539                 Atom string = sel.xtarget;
540                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
541                                 XA_ATOM, 32, PropModeReplace,
542                                 (unsigned char *) &string, 1);
543                 xev.property = xsre->property;
544         } else if(xsre->target == sel.xtarget) {
545                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
546                                 xsre->target, 8, PropModeReplace,
547                                 (unsigned char *) sel.clip, strlen(sel.clip));
548                 xev.property = xsre->property;
549         }
550
551         /* all done, send a notification to the listener */
552         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
553                 fprintf(stderr, "Error sending SelectionNotify event\n");
554 }
555
556 void
557 xsetsel(char *str) {
558         /* register the selection for both the clipboard and the primary */
559         Atom clipboard;
560
561         free(sel.clip);
562         sel.clip = str;
563
564         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
565
566         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
567         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
568
569         XFlush(xw.dpy);
570 }
571
572 void
573 brelease(XEvent *e) {
574         if(IS_SET(MODE_MOUSE)) {
575                 mousereport(e);
576                 return;
577         }
578         if(e->xbutton.button == Button2)
579                 selpaste();
580         else if(e->xbutton.button == Button1) {
581                 sel.mode = 0;
582                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
583                 if(sel.bx == sel.ex && sel.by == sel.ey) {
584                         struct timeval now;
585                         sel.bx = -1;
586                         gettimeofday(&now, NULL);
587
588                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
589                                 /* triple click on the line */
590                                 sel.b.x = sel.bx = 0;
591                                 sel.e.x = sel.ex = term.col;
592                                 sel.b.y = sel.e.y = sel.ey;
593                                 selcopy();
594                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
595                                 /* double click to select word */
596                                 sel.bx = sel.ex;
597                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
598                                           term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
599                                 sel.b.x = sel.bx;
600                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
601                                           term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
602                                 sel.e.x = sel.ex;
603                                 sel.b.y = sel.e.y = sel.ey;
604                                 selcopy();
605                         }
606                 } else
607                         selcopy();
608         }
609         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
610         gettimeofday(&sel.tclick1, NULL);
611         draw();
612 }
613
614 void
615 bmotion(XEvent *e) {
616         if(IS_SET(MODE_MOUSE)) {
617                 mousereport(e);
618                 return;
619         }
620         if(sel.mode) {
621                 int oldey = sel.ey, oldex = sel.ex;
622                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
623
624                 if(oldey != sel.ey || oldex != sel.ex) {
625                         int starty = MIN(oldey, sel.ey);
626                         int endy = MAX(oldey, sel.ey);
627                         drawregion(0, (starty > 0 ? starty : 0), term.col, (endy < term.row ? endy+1 : term.row));
628                 }
629         }
630 }
631
632 void
633 die(const char *errstr, ...) {
634         va_list ap;
635
636         va_start(ap, errstr);
637         vfprintf(stderr, errstr, ap);
638         va_end(ap);
639         exit(EXIT_FAILURE);
640 }
641
642 void
643 execsh(void) {
644         char **args;
645         char *envshell = getenv("SHELL");
646
647         DEFAULT(envshell, "sh");
648         putenv("TERM="TNAME);
649         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
650         execvp(args[0], args);
651         exit(EXIT_FAILURE);
652 }
653
654 void
655 sigchld(int a) {
656         int stat = 0;
657         if(waitpid(pid, &stat, 0) < 0)
658                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
659         if(WIFEXITED(stat))
660                 exit(WEXITSTATUS(stat));
661         else
662                 exit(EXIT_FAILURE);
663 }
664
665 void
666 ttynew(void) {
667         int m, s;
668         
669         /* seems to work fine on linux, openbsd and freebsd */
670         struct winsize w = {term.row, term.col, 0, 0};
671         if(openpty(&m, &s, NULL, NULL, &w) < 0)
672                 die("openpty failed: %s\n", SERRNO);
673
674         switch(pid = fork()) {
675         case -1:
676                 die("fork failed\n");
677                 break;
678         case 0:
679                 setsid(); /* create a new process group */
680                 dup2(s, STDIN_FILENO);
681                 dup2(s, STDOUT_FILENO);
682                 dup2(s, STDERR_FILENO);
683                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
684                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
685                 close(s);
686                 close(m);
687                 execsh();
688                 break;
689         default:
690                 close(s);
691                 cmdfd = m;
692                 signal(SIGCHLD, sigchld);
693         }
694 }
695
696 void
697 dump(char c) {
698         static int col;
699         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
700         if(++col % 10 == 0)
701                 fprintf(stderr, "\n");
702 }
703
704 void
705 ttyread(void) {
706         static char buf[BUFSIZ];
707         static int buflen = 0;
708         char *ptr;
709         char s[UTF_SIZ];
710         int charsize; /* size of utf8 char in bytes */
711         long utf8c;
712         int ret;
713
714         /* append read bytes to unprocessed bytes */
715         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
716                 die("Couldn't read from shell: %s\n", SERRNO);
717
718         /* process every complete utf8 char */
719         buflen += ret;
720         ptr = buf;
721         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
722                 charsize = utf8decode(ptr, &utf8c);
723                 utf8encode(&utf8c, s);
724                 tputc(s);
725                 ptr    += charsize;
726                 buflen -= charsize;
727         }
728
729         /* keep any uncomplete utf8 char for the next call */
730         memmove(buf, ptr, buflen);
731 }
732
733 void
734 ttywrite(const char *s, size_t n) {
735         if(write(cmdfd, s, n) == -1)
736                 die("write error on tty: %s\n", SERRNO);
737 }
738
739 void
740 ttyresize(int x, int y) {
741         struct winsize w;
742
743         w.ws_row = term.row;
744         w.ws_col = term.col;
745         w.ws_xpixel = w.ws_ypixel = 0;
746         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
747                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
748 }
749
750 void
751 tcursor(int mode) {
752         static TCursor c;
753
754         if(mode == CURSOR_SAVE)
755                 c = term.c;
756         else if(mode == CURSOR_LOAD)
757                 term.c = c, tmoveto(c.x, c.y);
758 }
759
760 void
761 treset(void) {
762         term.c = (TCursor){{
763                 .mode = ATTR_NULL,
764                 .fg = DefaultFG,
765                 .bg = DefaultBG
766         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
767         
768         term.top = 0, term.bot = term.row - 1;
769         term.mode = MODE_WRAP;
770         tclearregion(0, 0, term.col-1, term.row-1);
771 }
772
773 void
774 tnew(int col, int row) {
775         /* set screen size */
776         term.row = row, term.col = col;
777         term.line = malloc(term.row * sizeof(Line));
778         term.alt  = malloc(term.row * sizeof(Line));
779         for(row = 0; row < term.row; row++) {
780                 term.line[row] = malloc(term.col * sizeof(Glyph));
781                 term.alt [row] = malloc(term.col * sizeof(Glyph));
782         }
783         /* setup screen */
784         treset();
785 }
786
787 void
788 tswapscreen(void) {
789         Line* tmp = term.line;
790         term.line = term.alt;
791         term.alt = tmp;
792         term.mode ^= MODE_ALTSCREEN;
793 }
794
795 void
796 tscrolldown(int orig, int n) {
797         int i;
798         Line temp;
799         
800         LIMIT(n, 0, term.bot-orig+1);
801
802         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
803         
804         for(i = term.bot; i >= orig+n; i--) {
805                 temp = term.line[i];
806                 term.line[i] = term.line[i-n];
807                 term.line[i-n] = temp;
808         }
809 }
810
811 void
812 tscrollup(int orig, int n) {
813         int i;
814         Line temp;
815         LIMIT(n, 0, term.bot-orig+1);
816         
817         tclearregion(0, orig, term.col-1, orig+n-1);
818         
819         for(i = orig; i <= term.bot-n; i++) {
820                  temp = term.line[i];
821                  term.line[i] = term.line[i+n];
822                  term.line[i+n] = temp;
823         }
824 }
825
826 void
827 tnewline(int first_col) {
828         int y = term.c.y;
829         if(y == term.bot)
830                 tscrollup(term.top, 1);
831         else
832                 y++;
833         tmoveto(first_col ? 0 : term.c.x, y);
834 }
835
836 void
837 csiparse(void) {
838         /* int noarg = 1; */
839         char *p = escseq.buf;
840
841         escseq.narg = 0;
842         if(*p == '?')
843                 escseq.priv = 1, p++;
844         
845         while(p < escseq.buf+escseq.len) {
846                 while(isdigit(*p)) {
847                         escseq.arg[escseq.narg] *= 10;
848                         escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
849                 }
850                 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
851                         escseq.narg++, p++;
852                 else {
853                         escseq.mode = *p;
854                         escseq.narg++;
855                         return;
856                 }
857         }
858 }
859
860 void
861 tmoveto(int x, int y) {
862         LIMIT(x, 0, term.col-1);
863         LIMIT(y, 0, term.row-1);
864         term.c.state &= ~CURSOR_WRAPNEXT;
865         term.c.x = x;
866         term.c.y = y;
867 }
868
869 void
870 tsetchar(char *c) {
871         term.line[term.c.y][term.c.x] = term.c.attr;
872         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
873         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
874 }
875
876 void
877 tclearregion(int x1, int y1, int x2, int y2) {
878         int x, y, temp;
879
880         if(x1 > x2)
881                 temp = x1, x1 = x2, x2 = temp;
882         if(y1 > y2)
883                 temp = y1, y1 = y2, y2 = temp;
884
885         LIMIT(x1, 0, term.col-1);
886         LIMIT(x2, 0, term.col-1);
887         LIMIT(y1, 0, term.row-1);
888         LIMIT(y2, 0, term.row-1);
889
890         for(y = y1; y <= y2; y++)
891                 for(x = x1; x <= x2; x++)
892                         term.line[y][x].state = 0;
893 }
894
895 void
896 tdeletechar(int n) {
897         int src = term.c.x + n;
898         int dst = term.c.x;
899         int size = term.col - src;
900
901         if(src >= term.col) {
902                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
903                 return;
904         }
905         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
906         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
907 }
908
909 void
910 tinsertblank(int n) {
911         int src = term.c.x;
912         int dst = src + n;
913         int size = term.col - dst;
914
915         if(dst >= term.col) {
916                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
917                 return;
918         }
919         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
920         tclearregion(src, term.c.y, dst - 1, term.c.y);
921 }
922
923 void
924 tinsertblankline(int n) {
925         if(term.c.y < term.top || term.c.y > term.bot)
926                 return;
927
928         tscrolldown(term.c.y, n);
929 }
930
931 void
932 tdeleteline(int n) {
933         if(term.c.y < term.top || term.c.y > term.bot)
934                 return;
935
936         tscrollup(term.c.y, n);
937 }
938
939 void
940 tsetattr(int *attr, int l) {
941         int i;
942
943         for(i = 0; i < l; i++) {
944                 switch(attr[i]) {
945                 case 0:
946                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
947                         term.c.attr.fg = DefaultFG;
948                         term.c.attr.bg = DefaultBG;
949                         break;
950                 case 1:
951                         term.c.attr.mode |= ATTR_BOLD;
952                         break;
953                 case 4:
954                         term.c.attr.mode |= ATTR_UNDERLINE;
955                         break;
956                 case 7:
957                         term.c.attr.mode |= ATTR_REVERSE;
958                         break;
959                 case 22:
960                         term.c.attr.mode &= ~ATTR_BOLD;
961                         break;
962                 case 24:
963                         term.c.attr.mode &= ~ATTR_UNDERLINE;
964                         break;
965                 case 27:
966                         term.c.attr.mode &= ~ATTR_REVERSE;
967                         break;
968                 case 38:
969                         if(i + 2 < l && attr[i + 1] == 5) {
970                                 i += 2;
971                                 if(BETWEEN(attr[i], 0, 255))
972                                         term.c.attr.fg = attr[i];
973                                 else
974                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
975                         }
976                         else
977                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
978                         break;
979                 case 39:
980                         term.c.attr.fg = DefaultFG;
981                         break;
982                 case 48:
983                         if(i + 2 < l && attr[i + 1] == 5) {
984                                 i += 2;
985                                 if(BETWEEN(attr[i], 0, 255))
986                                         term.c.attr.bg = attr[i];
987                                 else
988                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
989                         }
990                         else
991                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
992                         break;
993                 case 49:
994                         term.c.attr.bg = DefaultBG;
995                         break;
996                 default:
997                         if(BETWEEN(attr[i], 30, 37))
998                                 term.c.attr.fg = attr[i] - 30;
999                         else if(BETWEEN(attr[i], 40, 47))
1000                                 term.c.attr.bg = attr[i] - 40;
1001                         else if(BETWEEN(attr[i], 90, 97))
1002                                 term.c.attr.fg = attr[i] - 90 + 8;
1003                         else if(BETWEEN(attr[i], 100, 107))
1004                                 term.c.attr.fg = attr[i] - 100 + 8;
1005                         else
1006                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
1007                         
1008                         break;
1009                 }
1010         }
1011 }
1012
1013 void
1014 tsetscroll(int t, int b) {
1015         int temp;
1016
1017         LIMIT(t, 0, term.row-1);
1018         LIMIT(b, 0, term.row-1);
1019         if(t > b) {
1020                 temp = t;
1021                 t = b;
1022                 b = temp;
1023         }
1024         term.top = t;
1025         term.bot = b;
1026 }
1027
1028 void
1029 csihandle(void) {
1030         switch(escseq.mode) {
1031         default:
1032         unknown:
1033                 fprintf(stderr, "erresc: unknown csi ");
1034                 csidump();
1035                 /* die(""); */
1036                 break;
1037         case '@': /* ICH -- Insert <n> blank char */
1038                 DEFAULT(escseq.arg[0], 1);
1039                 tinsertblank(escseq.arg[0]);
1040                 break;
1041         case 'A': /* CUU -- Cursor <n> Up */
1042         case 'e':
1043                 DEFAULT(escseq.arg[0], 1);
1044                 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
1045                 break;
1046         case 'B': /* CUD -- Cursor <n> Down */
1047                 DEFAULT(escseq.arg[0], 1);
1048                 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
1049                 break;
1050         case 'C': /* CUF -- Cursor <n> Forward */
1051         case 'a':
1052                 DEFAULT(escseq.arg[0], 1);
1053                 tmoveto(term.c.x+escseq.arg[0], term.c.y);
1054                 break;
1055         case 'D': /* CUB -- Cursor <n> Backward */
1056                 DEFAULT(escseq.arg[0], 1);
1057                 tmoveto(term.c.x-escseq.arg[0], term.c.y);
1058                 break;
1059         case 'E': /* CNL -- Cursor <n> Down and first col */
1060                 DEFAULT(escseq.arg[0], 1);
1061                 tmoveto(0, term.c.y+escseq.arg[0]);
1062                 break;
1063         case 'F': /* CPL -- Cursor <n> Up and first col */
1064                 DEFAULT(escseq.arg[0], 1);
1065                 tmoveto(0, term.c.y-escseq.arg[0]);
1066                 break;
1067         case 'G': /* CHA -- Move to <col> */
1068         case '`': /* XXX: HPA -- same? */
1069                 DEFAULT(escseq.arg[0], 1);
1070                 tmoveto(escseq.arg[0]-1, term.c.y);
1071                 break;
1072         case 'H': /* CUP -- Move to <row> <col> */
1073         case 'f': /* XXX: HVP -- same? */
1074                 DEFAULT(escseq.arg[0], 1);
1075                 DEFAULT(escseq.arg[1], 1);
1076                 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
1077                 break;
1078         /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
1079         case 'J': /* ED -- Clear screen */
1080                 switch(escseq.arg[0]) {
1081                 case 0: /* below */
1082                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1083                         if(term.c.y < term.row-1)
1084                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1085                         break;
1086                 case 1: /* above */
1087                         if(term.c.y > 1)
1088                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1089                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1090                         break;
1091                 case 2: /* all */
1092                         tclearregion(0, 0, term.col-1, term.row-1);
1093                         break;
1094                 default:
1095                         goto unknown;
1096                 }
1097                 break;
1098         case 'K': /* EL -- Clear line */
1099                 switch(escseq.arg[0]) {
1100                 case 0: /* right */
1101                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1102                         break;
1103                 case 1: /* left */
1104                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1105                         break;
1106                 case 2: /* all */
1107                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1108                         break;
1109                 }
1110                 break;
1111         case 'S': /* SU -- Scroll <n> line up */
1112                 DEFAULT(escseq.arg[0], 1);
1113                 tscrollup(term.top, escseq.arg[0]);
1114                 break;
1115         case 'T': /* SD -- Scroll <n> line down */
1116                 DEFAULT(escseq.arg[0], 1);
1117                 tscrolldown(term.top, escseq.arg[0]);
1118                 break;
1119         case 'L': /* IL -- Insert <n> blank lines */
1120                 DEFAULT(escseq.arg[0], 1);
1121                 tinsertblankline(escseq.arg[0]);
1122                 break;
1123         case 'l': /* RM -- Reset Mode */
1124                 if(escseq.priv) {
1125                         switch(escseq.arg[0]) {
1126                         case 1:
1127                                 term.mode &= ~MODE_APPKEYPAD;
1128                                 break;
1129                         case 5: /* DECSCNM -- Remove reverse video */
1130                                 if(IS_SET(MODE_REVERSE)) {
1131                                         term.mode &= ~MODE_REVERSE;
1132                                         draw();
1133                                 }
1134                                 break;
1135                         case 7:
1136                                 term.mode &= ~MODE_WRAP;
1137                                 break;
1138                         case 12: /* att610 -- Stop blinking cursor (IGNORED) */
1139                                 break;
1140                         case 20:
1141                                 term.mode &= ~MODE_CRLF;
1142                                 break;
1143                         case 25:
1144                                 term.c.state |= CURSOR_HIDE;
1145                                 break;
1146                         case 1000: /* disable X11 xterm mouse reporting */
1147                                 term.mode &= ~MODE_MOUSEBTN;
1148                                 break;
1149                         case 1002:
1150                                 term.mode &= ~MODE_MOUSEMOTION;
1151                                 break;
1152                         case 1049: /* = 1047 and 1048 */
1153                         case 47:
1154                         case 1047:
1155                                 if(IS_SET(MODE_ALTSCREEN)) {
1156                                         tclearregion(0, 0, term.col-1, term.row-1);
1157                                         tswapscreen();
1158                                 }
1159                                 if(escseq.arg[0] != 1049)
1160                                         break;
1161                         case 1048:
1162                                 tcursor(CURSOR_LOAD);
1163                                 break;
1164                         default:
1165                                 goto unknown;
1166                         }
1167                 } else {
1168                         switch(escseq.arg[0]) {
1169                         case 4:
1170                                 term.mode &= ~MODE_INSERT;
1171                                 break;
1172                         default:
1173                                 goto unknown;
1174                         }
1175                 }
1176                 break;
1177         case 'M': /* DL -- Delete <n> lines */
1178                 DEFAULT(escseq.arg[0], 1);
1179                 tdeleteline(escseq.arg[0]);
1180                 break;
1181         case 'X': /* ECH -- Erase <n> char */
1182                 DEFAULT(escseq.arg[0], 1);
1183                 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
1184                 break;
1185         case 'P': /* DCH -- Delete <n> char */
1186                 DEFAULT(escseq.arg[0], 1);
1187                 tdeletechar(escseq.arg[0]);
1188                 break;
1189         /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
1190         case 'd': /* VPA -- Move to <row> */
1191                 DEFAULT(escseq.arg[0], 1);
1192                 tmoveto(term.c.x, escseq.arg[0]-1);
1193                 break;
1194         case 'h': /* SM -- Set terminal mode */
1195                 if(escseq.priv) {
1196                         switch(escseq.arg[0]) {
1197                         case 1:
1198                                 term.mode |= MODE_APPKEYPAD;
1199                                 break;
1200                         case 5: /* DECSCNM -- Reverve video */
1201                                 if(!IS_SET(MODE_REVERSE)) {
1202                                         term.mode |= MODE_REVERSE;
1203                                         draw();
1204                                 }
1205                                 break;
1206                         case 7:
1207                                 term.mode |= MODE_WRAP;
1208                                 break;
1209                         case 20:
1210                                 term.mode |= MODE_CRLF;
1211                                 break;
1212                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1213                                  /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
1214                                 if(escseq.narg > 1 && escseq.arg[1] != 25)
1215                                         break;
1216                         case 25:
1217                                 term.c.state &= ~CURSOR_HIDE;
1218                                 break;
1219                         case 1000: /* 1000,1002: enable xterm mouse report */
1220                                 term.mode |= MODE_MOUSEBTN;
1221                                 break;
1222                         case 1002:
1223                                 term.mode |= MODE_MOUSEMOTION;
1224                                 break;
1225                         case 1049: /* = 1047 and 1048 */
1226                         case 47:
1227                         case 1047:
1228                                 if(IS_SET(MODE_ALTSCREEN))
1229                                         tclearregion(0, 0, term.col-1, term.row-1);
1230                                 else
1231                                         tswapscreen();
1232                                 if(escseq.arg[0] != 1049)
1233                                         break;
1234                         case 1048:
1235                                 tcursor(CURSOR_SAVE);
1236                                 break;
1237                         default: goto unknown;
1238                         }
1239                 } else {
1240                         switch(escseq.arg[0]) {
1241                         case 4:
1242                                 term.mode |= MODE_INSERT;
1243                                 break;
1244                         default: goto unknown;
1245                         }
1246                 };
1247                 break;
1248         case 'm': /* SGR -- Terminal attribute (color) */
1249                 tsetattr(escseq.arg, escseq.narg);
1250                 break;
1251         case 'r': /* DECSTBM -- Set Scrolling Region */
1252                 if(escseq.priv)
1253                         goto unknown;
1254                 else {
1255                         DEFAULT(escseq.arg[0], 1);
1256                         DEFAULT(escseq.arg[1], term.row);
1257                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1258                         tmoveto(0, 0);
1259                 }
1260                 break;
1261         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1262                 tcursor(CURSOR_SAVE);
1263                 break;
1264         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1265                 tcursor(CURSOR_LOAD);
1266                 break;
1267         }
1268 }
1269
1270 void
1271 csidump(void) {
1272         int i;
1273         printf("ESC [ %s", escseq.priv ? "? " : "");
1274         if(escseq.narg)
1275                 for(i = 0; i < escseq.narg; i++)
1276                         printf("%d ", escseq.arg[i]);
1277         if(escseq.mode)
1278                 putchar(escseq.mode);
1279         putchar('\n');
1280 }
1281
1282 void
1283 csireset(void) {
1284         memset(&escseq, 0, sizeof(escseq));
1285 }
1286
1287 void
1288 tputtab(void) {
1289         int space = TAB - term.c.x % TAB;
1290         tmoveto(term.c.x + space, term.c.y);
1291 }
1292
1293 void
1294 tputc(char *c) {
1295         char ascii = *c;
1296         if(term.esc & ESC_START) {
1297                 if(term.esc & ESC_CSI) {
1298                         escseq.buf[escseq.len++] = ascii;
1299                         if(BETWEEN(ascii, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1300                                 term.esc = 0;
1301                                 csiparse(), csihandle();
1302                         }
1303                         /* TODO: handle other OSC */
1304                 } else if(term.esc & ESC_OSC) {
1305                         if(ascii == ';') {
1306                                 term.titlelen = 0;
1307                                 term.esc = ESC_START | ESC_TITLE;
1308                         }
1309                 } else if(term.esc & ESC_TITLE) {
1310                         if(ascii == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1311                                 term.esc = 0;
1312                                 term.title[term.titlelen] = '\0';
1313                                 XStoreName(xw.dpy, xw.win, term.title);
1314                         } else {
1315                                 term.title[term.titlelen++] = ascii;
1316                         }
1317                 } else if(term.esc & ESC_ALTCHARSET) {
1318                         switch(ascii) {
1319                         case '0': /* Line drawing crap */
1320                                 term.c.attr.mode |= ATTR_GFX;
1321                                 break;
1322                         case 'B': /* Back to regular text */
1323                                 term.c.attr.mode &= ~ATTR_GFX;
1324                                 break;
1325                         default:
1326                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1327                         }
1328                         term.esc = 0;
1329                 } else {
1330                         switch(ascii) {
1331                         case '[':
1332                                 term.esc |= ESC_CSI;
1333                                 break;
1334                         case ']':
1335                                 term.esc |= ESC_OSC;
1336                                 break;
1337                         case '(':
1338                                 term.esc |= ESC_ALTCHARSET;
1339                                 break;
1340                         case 'D': /* IND -- Linefeed */
1341                                 if(term.c.y == term.bot)
1342                                         tscrollup(term.top, 1);
1343                                 else
1344                                         tmoveto(term.c.x, term.c.y+1);
1345                                 term.esc = 0;
1346                                 break;
1347                         case 'E': /* NEL -- Next line */
1348                                 tnewline(1); /* always go to first col */
1349                                 term.esc = 0;
1350                                 break;
1351                         case 'M': /* RI -- Reverse index */
1352                                 if(term.c.y == term.top)
1353                                         tscrolldown(term.top, 1);
1354                                 else
1355                                         tmoveto(term.c.x, term.c.y-1);
1356                                 term.esc = 0;
1357                                 break;
1358                         case 'c': /* RIS -- Reset to inital state */
1359                                 treset();
1360                                 term.esc = 0;
1361                                 break;
1362                         case '=': /* DECPAM -- Application keypad */
1363                                 term.mode |= MODE_APPKEYPAD;
1364                                 term.esc = 0;
1365                                 break;
1366                         case '>': /* DECPNM -- Normal keypad */
1367                                 term.mode &= ~MODE_APPKEYPAD;
1368                                 term.esc = 0;
1369                                 break;
1370                         case '7': /* DECSC -- Save Cursor */
1371                                 tcursor(CURSOR_SAVE);
1372                                 term.esc = 0;
1373                                 break;
1374                         case '8': /* DECRC -- Restore Cursor */
1375                                 tcursor(CURSOR_LOAD);
1376                                 term.esc = 0;
1377                                 break;
1378                         default:
1379                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1380                                     (unsigned char) ascii, isprint(ascii)?ascii:'.');
1381                                 term.esc = 0;
1382                         }
1383                 }
1384         } else {
1385                 switch(ascii) {
1386                 case '\t':
1387                         tputtab();
1388                         break;
1389                 case '\b':
1390                         tmoveto(term.c.x-1, term.c.y);
1391                         break;
1392                 case '\r':
1393                         tmoveto(0, term.c.y);
1394                         break;
1395                 case '\f':
1396                 case '\v':
1397                 case '\n':
1398                         /* go to first col if the mode is set */
1399                         tnewline(IS_SET(MODE_CRLF));
1400                         break;
1401                 case '\a':
1402                         if(!(xw.state & WIN_FOCUSED))
1403                                 xseturgency(1);
1404                         break;
1405                 case '\033':
1406                         csireset();
1407                         term.esc = ESC_START;
1408                         break;
1409                 default:
1410                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1411                                 tnewline(1); /* always go to first col */
1412                         tsetchar(c);
1413                         if(term.c.x+1 < term.col)
1414                                 tmoveto(term.c.x+1, term.c.y);
1415                         else
1416                                 term.c.state |= CURSOR_WRAPNEXT;
1417                 }
1418         }
1419 }
1420
1421 int
1422 tresize(int col, int row) {
1423         int i, x;
1424         int minrow = MIN(row, term.row);
1425         int mincol = MIN(col, term.col);
1426         int slide = term.c.y - row + 1;
1427
1428         if(col < 1 || row < 1)
1429                 return 0;
1430
1431         /* free unneeded rows */
1432         i = 0;
1433         if(slide > 0) {
1434                 /* slide screen to keep cursor where we expect it -
1435                  * tscrollup would work here, but we can optimize to
1436                  * memmove because we're freeing the earlier lines */
1437                 for(/* i = 0 */; i < slide; i++) {
1438                         free(term.line[i]);
1439                         free(term.alt[i]);
1440                 }
1441                 memmove(term.line, term.line + slide, row * sizeof(Line));
1442                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1443         }
1444         for(i += row; i < term.row; i++) {
1445                 free(term.line[i]);
1446                 free(term.alt[i]);
1447         }
1448
1449         /* resize to new height */
1450         term.line = realloc(term.line, row * sizeof(Line));
1451         term.alt  = realloc(term.alt,  row * sizeof(Line));
1452
1453         /* resize each row to new width, zero-pad if needed */
1454         for(i = 0; i < minrow; i++) {
1455                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1456                 term.alt[i]  = realloc(term.alt[i],  col * sizeof(Glyph));
1457                 for(x = mincol; x < col; x++) {
1458                         term.line[i][x].state = 0;
1459                         term.alt[i][x].state = 0;
1460                 }
1461         }
1462
1463         /* allocate any new rows */
1464         for(/* i == minrow */; i < row; i++) {
1465                 term.line[i] = calloc(col, sizeof(Glyph));
1466                 term.alt [i] = calloc(col, sizeof(Glyph));
1467         }
1468         
1469         /* update terminal size */
1470         term.col = col, term.row = row;
1471         /* make use of the LIMIT in tmoveto */
1472         tmoveto(term.c.x, term.c.y);
1473         /* reset scrolling region */
1474         tsetscroll(0, row-1);
1475         return (slide > 0);
1476 }
1477
1478 void
1479 xresize(int col, int row) {
1480         Pixmap newbuf;
1481         int oldw, oldh;
1482
1483         oldw = xw.bufw;
1484         oldh = xw.bufh;
1485         xw.bufw = MAX(1, col * xw.cw);
1486         xw.bufh = MAX(1, row * xw.ch);
1487         newbuf = XCreatePixmap(xw.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
1488         XCopyArea(xw.dpy, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
1489         XFreePixmap(xw.dpy, xw.buf);
1490         XSetForeground(xw.dpy, dc.gc, dc.col[DefaultBG]);
1491         if(xw.bufw > oldw)
1492                 XFillRectangle(xw.dpy, newbuf, dc.gc, oldw, 0,
1493                                 xw.bufw-oldw, MIN(xw.bufh, oldh));
1494         else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
1495                 XClearArea(xw.dpy, xw.win, BORDER+xw.bufw, BORDER,
1496                                 xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
1497                                 False);
1498         if(xw.bufh > oldh)
1499                 XFillRectangle(xw.dpy, newbuf, dc.gc, 0, oldh,
1500                                 xw.bufw, xw.bufh-oldh);
1501         else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
1502                 XClearArea(xw.dpy, xw.win, BORDER, BORDER+xw.bufh,
1503                                 xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
1504                                 False);
1505         xw.buf = newbuf;
1506 }
1507
1508 void
1509 xloadcols(void) {
1510         int i, r, g, b;
1511         XColor color;
1512         unsigned long white = WhitePixel(xw.dpy, xw.scr);
1513
1514         for(i = 0; i < 16; i++) {
1515                 if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
1516                         dc.col[i] = white;
1517                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1518                 } else
1519                         dc.col[i] = color.pixel;
1520         }
1521
1522         /* same colors as xterm */
1523         for(r = 0; r < 6; r++)
1524                 for(g = 0; g < 6; g++)
1525                         for(b = 0; b < 6; b++) {
1526                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1527                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1528                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1529                                 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1530                                         dc.col[i] = white;
1531                                         fprintf(stderr, "Could not allocate color %d\n", i);
1532                                 } else
1533                                         dc.col[i] = color.pixel;
1534                                 i++;
1535                         }
1536
1537         for(r = 0; r < 24; r++, i++) {
1538                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1539                 if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
1540                         dc.col[i] = white;
1541                         fprintf(stderr, "Could not allocate color %d\n", i);
1542                 } else
1543                         dc.col[i] = color.pixel;
1544         }
1545 }
1546
1547 void
1548 xclear(int x1, int y1, int x2, int y2) {
1549         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1550         XFillRectangle(xw.dpy, xw.buf, dc.gc,
1551                        x1 * xw.cw, y1 * xw.ch,
1552                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1553 }
1554
1555 void
1556 xhints(void) {
1557         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1558         XWMHints wm = {.flags = InputHint, .input = 1};
1559         XSizeHints size = {
1560                 .flags = PSize | PResizeInc | PBaseSize,
1561                 .height = xw.h,
1562                 .width = xw.w,
1563                 .height_inc = xw.ch,
1564                 .width_inc = xw.cw,
1565                 .base_height = 2*BORDER,
1566                 .base_width = 2*BORDER,
1567         };
1568         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1569 }
1570
1571 XFontSet
1572 xinitfont(char *fontstr) {
1573         XFontSet set;
1574         char *def, **missing;
1575         int n;
1576
1577         missing = NULL;
1578         set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
1579         if(missing) {
1580                 while(n--)
1581                         fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
1582                 XFreeStringList(missing);
1583         }
1584         return set;
1585 }
1586
1587 void
1588 xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
1589         XFontStruct **xfonts;
1590         char **font_names;
1591         int i, n;
1592
1593         *ascent = *descent = *lbearing = *rbearing = 0;
1594         n = XFontsOfFontSet(set, &xfonts, &font_names);
1595         for(i = 0; i < n; i++) {
1596                 *ascent = MAX(*ascent, (*xfonts)->ascent);
1597                 *descent = MAX(*descent, (*xfonts)->descent);
1598                 *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
1599                 *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
1600                 xfonts++;
1601         }
1602 }
1603
1604 void
1605 initfonts(char *fontstr, char *bfontstr) {
1606         if((dc.font.set = xinitfont(fontstr)) == NULL ||
1607            (dc.bfont.set = xinitfont(bfontstr)) == NULL)
1608                 die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
1609         xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
1610             &dc.font.lbearing, &dc.font.rbearing);
1611         xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
1612             &dc.bfont.lbearing, &dc.bfont.rbearing);
1613 }
1614
1615 void
1616 xinit(void) {
1617         XSetWindowAttributes attrs;
1618         Cursor cursor;
1619         Window parent;
1620
1621         if(!(xw.dpy = XOpenDisplay(NULL)))
1622                 die("Can't open display\n");
1623         xw.scr = XDefaultScreen(xw.dpy);
1624         
1625         /* font */
1626         initfonts(FONT, BOLDFONT);
1627
1628         /* XXX: Assuming same size for bold font */
1629         xw.cw = dc.font.rbearing - dc.font.lbearing;
1630         xw.ch = dc.font.ascent + dc.font.descent;
1631
1632         /* colors */
1633         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1634         xloadcols();
1635
1636         /* window - default size */
1637         xw.bufh = term.row * xw.ch;
1638         xw.bufw = term.col * xw.cw;
1639         xw.h = xw.bufh + 2*BORDER;
1640         xw.w = xw.bufw + 2*BORDER;
1641
1642         attrs.background_pixel = dc.col[DefaultBG];
1643         attrs.border_pixel = dc.col[DefaultBG];
1644         attrs.bit_gravity = NorthWestGravity;
1645         attrs.event_mask = FocusChangeMask | KeyPressMask
1646                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1647                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
1648                 | EnterWindowMask | LeaveWindowMask;
1649         attrs.colormap = xw.cmap;
1650
1651         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
1652         xw.win = XCreateWindow(xw.dpy, parent, 0, 0,
1653                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1654                         XDefaultVisual(xw.dpy, xw.scr),
1655                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1656                         | CWColormap,
1657                         &attrs);
1658         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dpy, xw.scr));
1659
1660
1661         /* input methods */
1662         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1663         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1664                                            | XIMStatusNothing, XNClientWindow, xw.win,
1665                                            XNFocusWindow, xw.win, NULL);
1666         /* gc */
1667         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
1668         
1669         /* white cursor, black outline */
1670         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
1671         XDefineCursor(xw.dpy, xw.win, cursor);
1672         XRecolorCursor(xw.dpy, cursor,
1673                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
1674                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
1675
1676         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1677
1678         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
1679         XMapWindow(xw.dpy, xw.win);
1680         xhints();
1681         XSync(xw.dpy, 0);
1682 }
1683
1684 void
1685 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
1686         unsigned long xfg = dc.col[base.fg], xbg = dc.col[base.bg], temp;
1687         int winx = x*xw.cw, winy = y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
1688         int i;
1689         
1690         /* only switch default fg/bg if term is in RV mode */
1691         if(IS_SET(MODE_REVERSE)) {
1692                 if(base.fg == DefaultFG)
1693                         xfg = dc.col[DefaultBG];
1694                 if(base.bg == DefaultBG)
1695                         xbg = dc.col[DefaultFG];
1696         }
1697
1698         if(base.mode & ATTR_REVERSE)
1699                 temp = xfg, xfg = xbg, xbg = temp;
1700
1701         XSetBackground(xw.dpy, dc.gc, xbg);
1702         XSetForeground(xw.dpy, dc.gc, xfg);
1703
1704         if(base.mode & ATTR_GFX) {
1705                 for(i = 0; i < bytelen; i++) {
1706                         char c = gfx[(unsigned int)s[i] % 256];
1707                         if(c)
1708                                 s[i] = c;
1709                         else if(s[i] > 0x5f)
1710                                 s[i] -= 0x5f;
1711                 }
1712         }
1713
1714         XmbDrawImageString(xw.dpy, xw.buf, base.mode & ATTR_BOLD ? dc.bfont.set : dc.font.set,
1715                 dc.gc, winx, winy, s, bytelen);
1716         
1717         if(base.mode & ATTR_UNDERLINE)
1718                 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1719 }
1720
1721 void
1722 xdrawcursor(void) {
1723         static int oldx = 0;
1724         static int oldy = 0;
1725         int sl;
1726         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
1727         
1728         LIMIT(oldx, 0, term.col-1);
1729         LIMIT(oldy, 0, term.row-1);
1730         
1731         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1732                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
1733
1734         /* remove the old cursor */
1735         if(term.line[oldy][oldx].state & GLYPH_SET) {
1736                 sl = utf8size(term.line[oldy][oldx].c);
1737                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
1738         } else
1739                 xclear(oldx, oldy, oldx, oldy);
1740         
1741         /* draw the new one */
1742         if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
1743                 sl = utf8size(g.c);
1744                 if(IS_SET(MODE_REVERSE))
1745                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
1746                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
1747                 oldx = term.c.x, oldy = term.c.y;
1748         }
1749 }
1750
1751 void
1752 draw() {
1753         drawregion(0, 0, term.col, term.row);
1754 }
1755
1756 void
1757 drawregion(int x1, int y1, int x2, int y2) {
1758         int ic, ib, x, y, ox, sl;
1759         Glyph base, new;
1760         char buf[DRAW_BUF_SIZ];
1761
1762         if(!(xw.state & WIN_VISIBLE))
1763                 return;
1764
1765         xclear(x1, y1, x2-1, y2-1);
1766         for(y = y1; y < y2; y++) {
1767                 base = term.line[y][0];
1768                 ic = ib = ox = 0;
1769                 for(x = x1; x < x2; x++) {
1770                         new = term.line[y][x];
1771                         if(sel.bx != -1 && *(new.c) && selected(x, y))
1772                                 new.mode ^= ATTR_REVERSE;
1773                         if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1774                                         ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
1775                                 xdraws(buf, base, ox, y, ic, ib);
1776                                 ic = ib = 0;
1777                         }
1778                         if(new.state & GLYPH_SET) {
1779                                 if(ib == 0) {
1780                                         ox = x;
1781                                         base = new;
1782                                 }
1783                                 sl = utf8size(new.c);
1784                                 memcpy(buf+ib, new.c, sl);
1785                                 ib += sl;
1786                                 ++ic;
1787                         }
1788                 }
1789                 if(ib > 0)
1790                         xdraws(buf, base, ox, y, ic, ib);
1791         }
1792         xdrawcursor();
1793         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1794 }
1795
1796 void
1797 expose(XEvent *ev) {
1798         XExposeEvent *e = &ev->xexpose;
1799         if(xw.state & WIN_REDRAW) {
1800                 if(!e->count) {
1801                         xw.state &= ~WIN_REDRAW;
1802                         draw();
1803                 }
1804         } else
1805                 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
1806                                 e->width, e->height, e->x, e->y);
1807 }
1808
1809 void
1810 visibility(XEvent *ev) {
1811         XVisibilityEvent *e = &ev->xvisibility;
1812         if(e->state == VisibilityFullyObscured)
1813                 xw.state &= ~WIN_VISIBLE;
1814         else if(!(xw.state & WIN_VISIBLE))
1815                 /* need a full redraw for next Expose, not just a buf copy */
1816                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
1817 }
1818
1819 void
1820 unmap(XEvent *ev) {
1821         xw.state &= ~WIN_VISIBLE;
1822 }
1823
1824 void
1825 xseturgency(int add) {
1826         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1827         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1828         XSetWMHints(xw.dpy, xw.win, h);
1829         XFree(h);
1830 }
1831
1832 void
1833 focus(XEvent *ev) {
1834         if(ev->type == FocusIn) {
1835                 xw.state |= WIN_FOCUSED;
1836                 xseturgency(0);
1837         } else
1838                 xw.state &= ~WIN_FOCUSED;
1839         draw();
1840 }
1841
1842 char*
1843 kmap(KeySym k, unsigned int state) {
1844         int i;
1845         state &= ~Mod2Mask;
1846         for(i = 0; i < LEN(key); i++) {
1847                 unsigned int mask = key[i].mask;
1848                 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
1849                         return (char*)key[i].s;
1850         }
1851         return NULL;
1852 }
1853
1854 void
1855 kpress(XEvent *ev) {
1856         XKeyEvent *e = &ev->xkey;
1857         KeySym ksym;
1858         char buf[32];
1859         char *customkey;
1860         int len;
1861         int meta;
1862         int shift;
1863         Status status;
1864
1865         meta = e->state & Mod1Mask;
1866         shift = e->state & ShiftMask;
1867         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1868         
1869         /* 1. custom keys from config.h */
1870         if((customkey = kmap(ksym, e->state)))
1871                 ttywrite(customkey, strlen(customkey));
1872         /* 2. hardcoded (overrides X lookup) */
1873         else
1874                 switch(ksym) {
1875                 case XK_Up:
1876                 case XK_Down:
1877                 case XK_Left:
1878                 case XK_Right:
1879                         /* XXX: shift up/down doesn't work */
1880                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
1881                         ttywrite(buf, 3);
1882                         break;
1883                 case XK_Insert:
1884                         if(shift)
1885                                 selpaste();
1886                         break;
1887                 case XK_Return:
1888                         if(IS_SET(MODE_CRLF))
1889                                 ttywrite("\r\n", 2);
1890                         else
1891                                 ttywrite("\r", 1);
1892                         break;
1893                         /* 3. X lookup  */
1894                 default:
1895                         if(len > 0) {
1896                                 if(meta && len == 1)
1897                                         ttywrite("\033", 1);
1898                                 ttywrite(buf, len);
1899                         }
1900                         break;
1901                 }
1902 }
1903
1904 void
1905 cmessage(XEvent *e) {
1906         /* See xembed specs
1907            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
1908         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1909                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1910                         xw.state |= WIN_FOCUSED;
1911                         xseturgency(0);
1912                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1913                         xw.state &= ~WIN_FOCUSED;
1914                 }
1915                 draw();
1916         }
1917 }
1918
1919 void
1920 resize(XEvent *e) {
1921         int col, row;
1922         
1923         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1924                 return;
1925         
1926         xw.w = e->xconfigure.width;
1927         xw.h = e->xconfigure.height;
1928         col = (xw.w - 2*BORDER) / xw.cw;
1929         row = (xw.h - 2*BORDER) / xw.ch;
1930         if(col == term.col && row == term.row)
1931                 return;
1932         if(tresize(col, row))
1933                 draw();
1934         ttyresize(col, row);
1935         xresize(col, row);
1936 }
1937
1938 void
1939 run(void) {
1940         XEvent ev;
1941         fd_set rfd;
1942         int xfd = XConnectionNumber(xw.dpy);
1943
1944         for(;;) {
1945                 FD_ZERO(&rfd);
1946                 FD_SET(cmdfd, &rfd);
1947                 FD_SET(xfd, &rfd);
1948                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1949                         if(errno == EINTR)
1950                                 continue;
1951                         die("select failed: %s\n", SERRNO);
1952                 }
1953                 if(FD_ISSET(cmdfd, &rfd)) {
1954                         ttyread();
1955                         draw();
1956                 }
1957                 while(XPending(xw.dpy)) {
1958                         XNextEvent(xw.dpy, &ev);
1959                         if(XFilterEvent(&ev, xw.win))
1960                                 continue;
1961                         if(handler[ev.type])
1962                                 (handler[ev.type])(&ev);
1963                 }
1964         }
1965 }
1966
1967 int
1968 main(int argc, char *argv[]) {
1969         int i;
1970         
1971         for(i = 1; i < argc; i++) {
1972                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1973                 case 't':
1974                         if(++i < argc) opt_title = argv[i];
1975                         break;
1976                 case 'c':
1977                         if(++i < argc) opt_class = argv[i];
1978                         break;
1979                 case 'w':
1980                         if(++i < argc) opt_embed = argv[i];
1981                         break;
1982                 case 'e': 
1983                         /* eat every remaining arguments */
1984                         if(++i < argc) opt_cmd = &argv[i];
1985                         goto run;
1986                 case 'v':
1987                 default:
1988                         die(USAGE);
1989                 }
1990         }
1991
1992  run:
1993         setlocale(LC_CTYPE, "");
1994         tnew(80, 24);
1995         ttynew();
1996         xinit();
1997         selinit();
1998         run();
1999         return 0;
2000 }