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