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