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