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