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