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