JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
If there is really someone without SHELL set, help him/her.
[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 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
30 #define Glyph Glyph_
31 #define Font Font_
32
33 #if   defined(__linux)
34  #include <pty.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36  #include <util.h>
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
38  #include <libutil.h>
39 #endif
40
41 #define USAGE \
42         "st " VERSION " (c) 2010-2012 st engineers\n" \
43         "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44         " [-t title] [-w windowid] [-e command ...]\n"
45
46 /* XEMBED messages */
47 #define XEMBED_FOCUS_IN  4
48 #define XEMBED_FOCUS_OUT 5
49
50 /* Arbitrary sizes */
51 #define ESC_BUF_SIZ   256
52 #define ESC_ARG_SIZ   16
53 #define STR_BUF_SIZ   256
54 #define STR_ARG_SIZ   16
55 #define DRAW_BUF_SIZ  20*1024
56 #define UTF_SIZ       4
57 #define XK_NO_MOD     UINT_MAX
58 #define XK_ANY_MOD    0
59
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61
62 #define SERRNO strerror(errno)
63 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
64 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
65 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74
75 #define VT102ID "\033[?6c"
76
77 enum glyph_attribute {
78         ATTR_NULL      = 0,
79         ATTR_REVERSE   = 1,
80         ATTR_UNDERLINE = 2,
81         ATTR_BOLD      = 4,
82         ATTR_GFX       = 8,
83         ATTR_ITALIC    = 16,
84         ATTR_BLINK     = 32,
85 };
86
87 enum cursor_movement {
88         CURSOR_UP,
89         CURSOR_DOWN,
90         CURSOR_LEFT,
91         CURSOR_RIGHT,
92         CURSOR_SAVE,
93         CURSOR_LOAD
94 };
95
96 enum cursor_state {
97         CURSOR_DEFAULT  = 0,
98         CURSOR_HIDE     = 1,
99         CURSOR_WRAPNEXT = 2
100 };
101
102 enum glyph_state {
103         GLYPH_SET   = 1,
104         GLYPH_DIRTY = 2
105 };
106
107 enum term_mode {
108         MODE_WRAP       = 1,
109         MODE_INSERT      = 2,
110         MODE_APPKEYPAD   = 4,
111         MODE_ALTSCREEN   = 8,
112         MODE_CRLF       = 16,
113         MODE_MOUSEBTN    = 32,
114         MODE_MOUSEMOTION = 64,
115         MODE_MOUSE       = 32|64,
116         MODE_REVERSE     = 128,
117         MODE_KBDLOCK     = 256
118 };
119
120 enum escape_state {
121         ESC_START      = 1,
122         ESC_CSI = 2,
123         ESC_STR = 4, /* DSC, OSC, PM, APC */
124         ESC_ALTCHARSET = 8,
125         ESC_STR_END    = 16, /* a final string was encountered */
126         ESC_TEST       = 32, /* Enter in test mode */
127 };
128
129 enum window_state {
130         WIN_VISIBLE = 1,
131         WIN_REDRAW  = 2,
132         WIN_FOCUSED = 4
133 };
134
135 /* bit macro */
136 #undef B0
137 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
138
139 typedef unsigned char uchar;
140 typedef unsigned int uint;
141 typedef unsigned long ulong;
142 typedef unsigned short ushort;
143
144 typedef struct {
145         char c[UTF_SIZ];     /* character code */
146         uchar mode;  /* attribute flags */
147         ushort fg;   /* foreground  */
148         ushort bg;   /* background  */
149         uchar state; /* state flags    */
150 } Glyph;
151
152 typedef Glyph* Line;
153
154 typedef struct {
155         Glyph attr;      /* current char attributes */
156         int x;
157         int y;
158         char state;
159 } TCursor;
160
161 /* CSI Escape sequence structs */
162 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
163 typedef struct {
164         char buf[ESC_BUF_SIZ]; /* raw string */
165         int len;               /* raw string length */
166         char priv;
167         int arg[ESC_ARG_SIZ];
168         int narg;             /* nb of args */
169         char mode;
170 } CSIEscape;
171
172 /* STR Escape sequence structs */
173 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
174 typedef struct {
175         char type;           /* ESC type ... */
176         char buf[STR_BUF_SIZ]; /* raw string */
177         int len;               /* raw string length */
178         char *args[STR_ARG_SIZ];
179         int narg;             /* nb of args */
180 } STREscape;
181
182 /* Internal representation of the screen */
183 typedef struct {
184         int row;        /* nb row */
185         int col;        /* nb col */
186         Line *line;     /* screen */
187         Line *alt;      /* alternate screen */
188         bool *dirty;    /* dirtyness of lines */
189         TCursor c;      /* cursor */
190         int top;        /* top    scroll limit */
191         int bot;        /* bottom scroll limit */
192         int mode;       /* terminal mode flags */
193         int esc;        /* escape state flags */
194         bool *tabs;
195 } Term;
196
197 /* Purely graphic info */
198 typedef struct {
199         Display* dpy;
200         Colormap cmap;
201         Window win;
202         XdbeBackBuffer buf;
203         Atom xembed, wmdeletewin;
204         XIM xim;
205         XIC xic;
206         XftDraw *xft_draw;
207         Visual *vis;
208         int scr;
209         bool isfixed; /* is fixed geometry? */
210         int fx, fy, fw, fh; /* fixed geometry */
211         int tw, th; /* tty width and height */
212         int w;  /* window width */
213         int h;  /* window height */
214         int ch; /* char height */
215         int cw; /* char width  */
216         char state; /* focus, redraw, visible */
217 } XWindow;
218
219 typedef struct {
220         KeySym k;
221         uint mask;
222         char s[ESC_BUF_SIZ];
223 } Key;
224
225 /* TODO: use better name for vars... */
226 typedef struct {
227         int mode;
228         int bx, by;
229         int ex, ey;
230         struct {
231                 int x, y;
232         } b, e;
233         char *clip;
234         Atom xtarget;
235         bool alt;
236         struct timeval tclick1;
237         struct timeval tclick2;
238 } Selection;
239
240 #include "config.h"
241
242 /* Font structure */
243 typedef struct {
244         int height;
245         int width;
246         int ascent;
247         int descent;
248         short lbearing;
249         short rbearing;
250         XftFont *xft_set;
251 } Font;
252
253 /* Drawing Context */
254 typedef struct {
255         XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
256         GC gc;
257         Font font, bfont, ifont, ibfont;
258 } DC;
259
260 static void die(const char *, ...);
261 static void draw(void);
262 static void redraw(void);
263 static void drawregion(int, int, int, int);
264 static void execsh(void);
265 static void sigchld(int);
266 static void run(void);
267
268 static void csidump(void);
269 static void csihandle(void);
270 static void csiparse(void);
271 static void csireset(void);
272 static void strdump(void);
273 static void strhandle(void);
274 static void strparse(void);
275 static void strreset(void);
276
277 static void tclearregion(int, int, int, int);
278 static void tcursor(int);
279 static void tdeletechar(int);
280 static void tdeleteline(int);
281 static void tinsertblank(int);
282 static void tinsertblankline(int);
283 static void tmoveto(int, int);
284 static void tnew(int, int);
285 static void tnewline(int);
286 static void tputtab(bool);
287 static void tputc(char *, int);
288 static void treset(void);
289 static int tresize(int, int);
290 static void tscrollup(int, int);
291 static void tscrolldown(int, int);
292 static void tsetattr(int*, int);
293 static void tsetchar(char *, Glyph *, int, int);
294 static void tsetscroll(int, int);
295 static void tswapscreen(void);
296 static void tsetdirt(int, int);
297 static void tsetmode(bool, bool, int *, int);
298 static void tfulldirt(void);
299
300 static void ttynew(void);
301 static void ttyread(void);
302 static void ttyresize(void);
303 static void ttywrite(const char *, size_t);
304
305 static void xdraws(char *, Glyph, int, int, int, int);
306 static void xhints(void);
307 static void xclear(int, int, int, int);
308 static void xdrawcursor(void);
309 static void xinit(void);
310 static void xloadcols(void);
311 static void xresettitle(void);
312 static void xseturgency(int);
313 static void xsetsel(char*);
314 static void xtermclear(int, int, int, int);
315 static void xresize(int, int);
316
317 static void expose(XEvent *);
318 static void visibility(XEvent *);
319 static void unmap(XEvent *);
320 static char *kmap(KeySym, uint);
321 static void kpress(XEvent *);
322 static void cmessage(XEvent *);
323 static void resize(XEvent *);
324 static void focus(XEvent *);
325 static void brelease(XEvent *);
326 static void bpress(XEvent *);
327 static void bmotion(XEvent *);
328 static void selnotify(XEvent *);
329 static void selclear(XEvent *);
330 static void selrequest(XEvent *);
331
332 static void selinit(void);
333 static inline bool selected(int, int);
334 static void selcopy(void);
335 static void selpaste(void);
336 static void selscroll(int, int);
337
338 static int utf8decode(char *, long *);
339 static int utf8encode(long *, char *);
340 static int utf8size(char *);
341 static int isfullutf8(char *, int);
342
343 static void *xmalloc(size_t);
344 static void *xrealloc(void *, size_t);
345 static void *xcalloc(size_t nmemb, size_t size);
346 static char *smstrcat(char *, ...);
347
348 static void (*handler[LASTEvent])(XEvent *) = {
349         [KeyPress] = kpress,
350         [ClientMessage] = cmessage,
351         [ConfigureNotify] = resize,
352         [VisibilityNotify] = visibility,
353         [UnmapNotify] = unmap,
354         [Expose] = expose,
355         [FocusIn] = focus,
356         [FocusOut] = focus,
357         [MotionNotify] = bmotion,
358         [ButtonPress] = bpress,
359         [ButtonRelease] = brelease,
360         [SelectionClear] = selclear,
361         [SelectionNotify] = selnotify,
362         [SelectionRequest] = selrequest,
363 };
364
365 /* Globals */
366 static DC dc;
367 static XWindow xw;
368 static Term term;
369 static CSIEscape csiescseq;
370 static STREscape strescseq;
371 static int cmdfd;
372 static pid_t pid;
373 static Selection sel;
374 static int iofd = -1;
375 static char **opt_cmd = NULL;
376 static char *opt_io = NULL;
377 static char *opt_title = NULL;
378 static char *opt_embed = NULL;
379 static char *opt_class = NULL;
380 static char *opt_font = NULL;
381
382 void *
383 xmalloc(size_t len) {
384         void *p = malloc(len);
385
386         if(!p)
387                 die("Out of memory\n");
388
389         return p;
390 }
391
392 void *
393 xrealloc(void *p, size_t len) {
394         if((p = realloc(p, len)) == NULL)
395                 die("Out of memory\n");
396
397         return p;
398 }
399
400 void *
401 xcalloc(size_t nmemb, size_t size) {
402         void *p = calloc(nmemb, size);
403
404         if(!p)
405                 die("Out of memory\n");
406
407         return p;
408 }
409
410 char *
411 smstrcat(char *src, ...)
412 {
413         va_list fmtargs;
414         char *ret, *p, *v;
415         int len, slen, flen;
416
417         len = slen = strlen(src);
418
419         va_start(fmtargs, src);
420         for(;;) {
421                 v = va_arg(fmtargs, char *);
422                 if(v == NULL)
423                         break;
424                 len += strlen(v);
425         }
426         va_end(fmtargs);
427
428         p = ret = xmalloc(len+1);
429         memmove(p, src, slen);
430         p += slen;
431
432         va_start(fmtargs, src);
433         for(;;) {
434                 v = va_arg(fmtargs, char *);
435                 if(v == NULL)
436                         break;
437                 flen = strlen(v);
438                 memmove(p, v, flen);
439                 p += flen;
440         }
441         va_end(fmtargs);
442
443         ret[len] = '\0';
444
445         return ret;
446 }
447
448 int
449 utf8decode(char *s, long *u) {
450         uchar c;
451         int i, n, rtn;
452
453         rtn = 1;
454         c = *s;
455         if(~c & B7) { /* 0xxxxxxx */
456                 *u = c;
457                 return rtn;
458         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
459                 *u = c&(B4|B3|B2|B1|B0);
460                 n = 1;
461         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
462                 *u = c&(B3|B2|B1|B0);
463                 n = 2;
464         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
465                 *u = c & (B2|B1|B0);
466                 n = 3;
467         } else {
468                 goto invalid;
469         }
470
471         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
472                 c = *s;
473                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
474                         goto invalid;
475                 *u <<= 6;
476                 *u |= c & (B5|B4|B3|B2|B1|B0);
477         }
478
479         if((n == 1 && *u < 0x80) ||
480            (n == 2 && *u < 0x800) ||
481            (n == 3 && *u < 0x10000) ||
482            (*u >= 0xD800 && *u <= 0xDFFF)) {
483                 goto invalid;
484         }
485
486         return rtn;
487 invalid:
488         *u = 0xFFFD;
489
490         return rtn;
491 }
492
493 int
494 utf8encode(long *u, char *s) {
495         uchar *sp;
496         ulong uc;
497         int i, n;
498
499         sp = (uchar *)s;
500         uc = *u;
501         if(uc < 0x80) {
502                 *sp = uc; /* 0xxxxxxx */
503                 return 1;
504         } else if(*u < 0x800) {
505                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
506                 n = 1;
507         } else if(uc < 0x10000) {
508                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
509                 n = 2;
510         } else if(uc <= 0x10FFFF) {
511                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
512                 n = 3;
513         } else {
514                 goto invalid;
515         }
516
517         for(i=n,++sp; i>0; --i,++sp)
518                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
519
520         return n+1;
521 invalid:
522         /* U+FFFD */
523         *s++ = '\xEF';
524         *s++ = '\xBF';
525         *s = '\xBD';
526
527         return 3;
528 }
529
530 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
531    UTF-8 otherwise return 0 */
532 int
533 isfullutf8(char *s, int b) {
534         uchar *c1, *c2, *c3;
535
536         c1 = (uchar *)s;
537         c2 = (uchar *)++s;
538         c3 = (uchar *)++s;
539         if(b < 1) {
540                 return 0;
541         } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
542                 return 0;
543         } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
544             ((b == 1) ||
545             ((b == 2) && (*c2&(B7|B6)) == B7))) {
546                 return 0;
547         } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
548             ((b == 1) ||
549             ((b == 2) && (*c2&(B7|B6)) == B7) ||
550             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
551                 return 0;
552         } else {
553                 return 1;
554         }
555 }
556
557 int
558 utf8size(char *s) {
559         uchar c = *s;
560
561         if(~c&B7) {
562                 return 1;
563         } else if((c&(B7|B6|B5)) == (B7|B6)) {
564                 return 2;
565         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
566                 return 3;
567         } else {
568                 return 4;
569         }
570 }
571
572 void
573 selinit(void) {
574         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
575         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
576         sel.mode = 0;
577         sel.bx = -1;
578         sel.clip = NULL;
579         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
580         if(sel.xtarget == None)
581                 sel.xtarget = XA_STRING;
582 }
583
584 static inline bool
585 selected(int x, int y) {
586         int bx, ex;
587
588         if(sel.ey == y && sel.by == y) {
589                 bx = MIN(sel.bx, sel.ex);
590                 ex = MAX(sel.bx, sel.ex);
591                 return BETWEEN(x, bx, ex);
592         }
593
594         return ((sel.b.y < y && y < sel.e.y)
595                         || (y == sel.e.y && x <= sel.e.x))
596                         || (y == sel.b.y && x >= sel.b.x
597                                 && (x <= sel.e.x || sel.b.y != sel.e.y));
598 }
599
600 void
601 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
602         if(b)
603                 *b = e->xbutton.button;
604
605         *x = X2COL(e->xbutton.x);
606         *y = Y2ROW(e->xbutton.y);
607         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
608         sel.b.y = MIN(sel.by, sel.ey);
609         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
610         sel.e.y = MAX(sel.by, sel.ey);
611 }
612
613 void
614 mousereport(XEvent *e) {
615         int x = X2COL(e->xbutton.x);
616         int y = Y2ROW(e->xbutton.y);
617         int button = e->xbutton.button;
618         int state = e->xbutton.state;
619         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
620         static int ob, ox, oy;
621
622         /* from urxvt */
623         if(e->xbutton.type == MotionNotify) {
624                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
625                         return;
626                 button = ob + 32;
627                 ox = x, oy = y;
628         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
629                 button = 3;
630         } else {
631                 button -= Button1;
632                 if(button >= 3)
633                         button += 64 - 3;
634                 if(e->xbutton.type == ButtonPress) {
635                         ob = button;
636                         ox = x, oy = y;
637                 }
638         }
639
640         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
641                 + (state & Mod4Mask    ? 8  : 0)
642                 + (state & ControlMask ? 16 : 0);
643
644         ttywrite(buf, sizeof(buf));
645 }
646
647 void
648 bpress(XEvent *e) {
649         if(IS_SET(MODE_MOUSE)) {
650                 mousereport(e);
651         } else if(e->xbutton.button == Button1) {
652                 if(sel.bx != -1) {
653                         sel.bx = -1;
654                         tsetdirt(sel.b.y, sel.e.y);
655                         draw();
656                 }
657                 sel.mode = 1;
658                 sel.ex = sel.bx = X2COL(e->xbutton.x);
659                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
660         }
661 }
662
663 void
664 selcopy(void) {
665         char *str, *ptr, *p;
666         int x, y, bufsize, is_selected = 0, size;
667         Glyph *gp;
668
669         if(sel.bx == -1) {
670                 str = NULL;
671         } else {
672                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
673                 ptr = str = xmalloc(bufsize);
674
675                 /* append every set & selected glyph to the selection */
676                 for(y = 0; y < term.row; y++) {
677                         for(x = 0; x < term.col; x++) {
678                                 gp = &term.line[y][x];
679
680                                 if(!(is_selected = selected(x, y)))
681                                         continue;
682                                 p = (gp->state & GLYPH_SET) ? gp->c : " ";
683                                 size = utf8size(p);
684                                 memcpy(ptr, p, size);
685                                 ptr += size;
686                         }
687                         /* \n at the end of every selected line except for the last one */
688                         if(is_selected && y < sel.e.y)
689                                 *ptr++ = '\n';
690                 }
691                 *ptr = 0;
692         }
693         sel.alt = IS_SET(MODE_ALTSCREEN);
694         xsetsel(str);
695 }
696
697 void
698 selnotify(XEvent *e) {
699         ulong nitems, ofs, rem;
700         int format;
701         uchar *data;
702         Atom type;
703
704         ofs = 0;
705         do {
706                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
707                                         False, AnyPropertyType, &type, &format,
708                                         &nitems, &rem, &data)) {
709                         fprintf(stderr, "Clipboard allocation failed\n");
710                         return;
711                 }
712                 ttywrite((const char *) data, nitems * format / 8);
713                 XFree(data);
714                 /* number of 32-bit chunks returned */
715                 ofs += nitems * format / 32;
716         } while(rem > 0);
717 }
718
719 void
720 selpaste(void) {
721         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
722                         xw.win, CurrentTime);
723 }
724
725 void selclear(XEvent *e) {
726         if(sel.bx == -1)
727                 return;
728         sel.bx = -1;
729         tsetdirt(sel.b.y, sel.e.y);
730 }
731
732 void
733 selrequest(XEvent *e) {
734         XSelectionRequestEvent *xsre;
735         XSelectionEvent xev;
736         Atom xa_targets, string;
737
738         xsre = (XSelectionRequestEvent *) e;
739         xev.type = SelectionNotify;
740         xev.requestor = xsre->requestor;
741         xev.selection = xsre->selection;
742         xev.target = xsre->target;
743         xev.time = xsre->time;
744         /* reject */
745         xev.property = None;
746
747         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
748         if(xsre->target == xa_targets) {
749                 /* respond with the supported type */
750                 string = sel.xtarget;
751                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
752                                 XA_ATOM, 32, PropModeReplace,
753                                 (uchar *) &string, 1);
754                 xev.property = xsre->property;
755         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
756                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
757                                 xsre->target, 8, PropModeReplace,
758                                 (uchar *) sel.clip, strlen(sel.clip));
759                 xev.property = xsre->property;
760         }
761
762         /* all done, send a notification to the listener */
763         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
764                 fprintf(stderr, "Error sending SelectionNotify event\n");
765 }
766
767 void
768 xsetsel(char *str) {
769         /* register the selection for both the clipboard and the primary */
770         Atom clipboard;
771
772         free(sel.clip);
773         sel.clip = str;
774
775         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
776
777         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
778         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
779 }
780
781 void
782 brelease(XEvent *e) {
783         struct timeval now;
784
785         if(IS_SET(MODE_MOUSE)) {
786                 mousereport(e);
787                 return;
788         }
789
790         if(e->xbutton.button == Button2) {
791                 selpaste();
792         } else if(e->xbutton.button == Button1) {
793                 sel.mode = 0;
794                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
795                 term.dirty[sel.ey] = 1;
796                 if(sel.bx == sel.ex && sel.by == sel.ey) {
797                         sel.bx = -1;
798                         gettimeofday(&now, NULL);
799
800                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
801                                 /* triple click on the line */
802                                 sel.b.x = sel.bx = 0;
803                                 sel.e.x = sel.ex = term.col;
804                                 sel.b.y = sel.e.y = sel.ey;
805                                 selcopy();
806                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
807                                 /* double click to select word */
808                                 sel.bx = sel.ex;
809                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
810                                                 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
811                                         sel.bx--;
812                                 }
813                                 sel.b.x = sel.bx;
814                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
815                                                 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
816                                         sel.ex++;
817                                 }
818                                 sel.e.x = sel.ex;
819                                 sel.b.y = sel.e.y = sel.ey;
820                                 selcopy();
821                         }
822                 } else {
823                         selcopy();
824                 }
825         }
826
827         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
828         gettimeofday(&sel.tclick1, NULL);
829 }
830
831 void
832 bmotion(XEvent *e) {
833         int starty, endy, oldey, oldex;
834
835         if(IS_SET(MODE_MOUSE)) {
836                 mousereport(e);
837                 return;
838         }
839
840         if(sel.mode) {
841                 oldey = sel.ey;
842                 oldex = sel.ex;
843                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
844
845                 if(oldey != sel.ey || oldex != sel.ex) {
846                         starty = MIN(oldey, sel.ey);
847                         endy = MAX(oldey, sel.ey);
848                         tsetdirt(starty, endy);
849                 }
850         }
851 }
852
853 void
854 die(const char *errstr, ...) {
855         va_list ap;
856
857         va_start(ap, errstr);
858         vfprintf(stderr, errstr, ap);
859         va_end(ap);
860         exit(EXIT_FAILURE);
861 }
862
863 void
864 execsh(void) {
865         char **args;
866         char *envshell = getenv("SHELL");
867
868         if (envshell == NULL)
869                 envshell ="/bin/sh";
870
871         unsetenv("COLUMNS");
872         unsetenv("LINES");
873         unsetenv("TERMCAP");
874
875         signal(SIGCHLD, SIG_DFL);
876         signal(SIGHUP, SIG_DFL);
877         signal(SIGINT, SIG_DFL);
878         signal(SIGQUIT, SIG_DFL);
879         signal(SIGTERM, SIG_DFL);
880         signal(SIGALRM, SIG_DFL);
881
882         DEFAULT(envshell, SHELL);
883         putenv("TERM="TNAME);
884         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
885         execvp(args[0], args);
886         exit(EXIT_FAILURE);
887 }
888
889 void
890 sigchld(int a) {
891         int stat = 0;
892
893         if(waitpid(pid, &stat, 0) < 0)
894                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
895
896         if(WIFEXITED(stat)) {
897                 exit(WEXITSTATUS(stat));
898         } else {
899                 exit(EXIT_FAILURE);
900         }
901 }
902
903 void
904 ttynew(void) {
905         int m, s;
906         struct winsize w = {term.row, term.col, 0, 0};
907
908         /* seems to work fine on linux, openbsd and freebsd */
909         if(openpty(&m, &s, NULL, NULL, &w) < 0)
910                 die("openpty failed: %s\n", SERRNO);
911
912         switch(pid = fork()) {
913         case -1:
914                 die("fork failed\n");
915                 break;
916         case 0:
917                 setsid(); /* create a new process group */
918                 dup2(s, STDIN_FILENO);
919                 dup2(s, STDOUT_FILENO);
920                 dup2(s, STDERR_FILENO);
921                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
922                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
923                 close(s);
924                 close(m);
925                 execsh();
926                 break;
927         default:
928                 close(s);
929                 cmdfd = m;
930                 signal(SIGCHLD, sigchld);
931                 if(opt_io) {
932                         if(!strcmp(opt_io, "-")) {
933                                 iofd = STDOUT_FILENO;
934                         } else {
935                                 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
936                                         fprintf(stderr, "Error opening %s:%s\n",
937                                                 opt_io, strerror(errno));
938                                 }
939                         }
940                 }
941         }
942 }
943
944 void
945 dump(char c) {
946         static int col;
947
948         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
949         if(++col % 10 == 0)
950                 fprintf(stderr, "\n");
951 }
952
953 void
954 ttyread(void) {
955         static char buf[BUFSIZ];
956         static int buflen = 0;
957         char *ptr;
958         char s[UTF_SIZ];
959         int charsize; /* size of utf8 char in bytes */
960         long utf8c;
961         int ret;
962
963         /* append read bytes to unprocessed bytes */
964         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
965                 die("Couldn't read from shell: %s\n", SERRNO);
966
967         /* process every complete utf8 char */
968         buflen += ret;
969         ptr = buf;
970         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
971                 charsize = utf8decode(ptr, &utf8c);
972                 utf8encode(&utf8c, s);
973                 tputc(s, charsize);
974                 ptr += charsize;
975                 buflen -= charsize;
976         }
977
978         /* keep any uncomplete utf8 char for the next call */
979         memmove(buf, ptr, buflen);
980 }
981
982 void
983 ttywrite(const char *s, size_t n) {
984         if(write(cmdfd, s, n) == -1)
985                 die("write error on tty: %s\n", SERRNO);
986 }
987
988 void
989 ttyresize(void) {
990         struct winsize w;
991
992         w.ws_row = term.row;
993         w.ws_col = term.col;
994         w.ws_xpixel = xw.tw;
995         w.ws_ypixel = xw.th;
996         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
997                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
998 }
999
1000 void
1001 tsetdirt(int top, int bot) {
1002         int i;
1003
1004         LIMIT(top, 0, term.row-1);
1005         LIMIT(bot, 0, term.row-1);
1006
1007         for(i = top; i <= bot; i++)
1008                 term.dirty[i] = 1;
1009 }
1010
1011 void
1012 tfulldirt(void) {
1013         tsetdirt(0, term.row-1);
1014 }
1015
1016 void
1017 tcursor(int mode) {
1018         static TCursor c;
1019
1020         if(mode == CURSOR_SAVE) {
1021                 c = term.c;
1022         } else if(mode == CURSOR_LOAD) {
1023                 term.c = c;
1024                 tmoveto(c.x, c.y);
1025         }
1026 }
1027
1028 void
1029 treset(void) {
1030         uint i;
1031
1032         term.c = (TCursor){{
1033                 .mode = ATTR_NULL,
1034                 .fg = DefaultFG,
1035                 .bg = DefaultBG
1036         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1037
1038         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1039         for(i = TAB; i < term.col; i += TAB)
1040                 term.tabs[i] = 1;
1041         term.top = 0;
1042         term.bot = term.row - 1;
1043         term.mode = MODE_WRAP;
1044
1045         tclearregion(0, 0, term.col-1, term.row-1);
1046 }
1047
1048 void
1049 tnew(int col, int row) {
1050         /* set screen size */
1051         term.row = row;
1052         term.col = col;
1053         term.line = xmalloc(term.row * sizeof(Line));
1054         term.alt  = xmalloc(term.row * sizeof(Line));
1055         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1056         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1057
1058         for(row = 0; row < term.row; row++) {
1059                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1060                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1061                 term.dirty[row] = 0;
1062         }
1063         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1064         /* setup screen */
1065         treset();
1066 }
1067
1068 void
1069 tswapscreen(void) {
1070         Line *tmp = term.line;
1071
1072         term.line = term.alt;
1073         term.alt = tmp;
1074         term.mode ^= MODE_ALTSCREEN;
1075         tfulldirt();
1076 }
1077
1078 void
1079 tscrolldown(int orig, int n) {
1080         int i;
1081         Line temp;
1082
1083         LIMIT(n, 0, term.bot-orig+1);
1084
1085         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1086
1087         for(i = term.bot; i >= orig+n; i--) {
1088                 temp = term.line[i];
1089                 term.line[i] = term.line[i-n];
1090                 term.line[i-n] = temp;
1091
1092                 term.dirty[i] = 1;
1093                 term.dirty[i-n] = 1;
1094         }
1095
1096         selscroll(orig, n);
1097 }
1098
1099 void
1100 tscrollup(int orig, int n) {
1101         int i;
1102         Line temp;
1103         LIMIT(n, 0, term.bot-orig+1);
1104
1105         tclearregion(0, orig, term.col-1, orig+n-1);
1106
1107         for(i = orig; i <= term.bot-n; i++) {
1108                  temp = term.line[i];
1109                  term.line[i] = term.line[i+n];
1110                  term.line[i+n] = temp;
1111
1112                  term.dirty[i] = 1;
1113                  term.dirty[i+n] = 1;
1114         }
1115
1116         selscroll(orig, -n);
1117 }
1118
1119 void
1120 selscroll(int orig, int n) {
1121         if(sel.bx == -1)
1122                 return;
1123
1124         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1125                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1126                         sel.bx = -1;
1127                         return;
1128                 }
1129                 if(sel.by < term.top) {
1130                         sel.by = term.top;
1131                         sel.bx = 0;
1132                 }
1133                 if(sel.ey > term.bot) {
1134                         sel.ey = term.bot;
1135                         sel.ex = term.col;
1136                 }
1137                 sel.b.y = sel.by, sel.b.x = sel.bx;
1138                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1139         }
1140 }
1141
1142 void
1143 tnewline(int first_col) {
1144         int y = term.c.y;
1145
1146         if(y == term.bot) {
1147                 tscrollup(term.top, 1);
1148         } else {
1149                 y++;
1150         }
1151         tmoveto(first_col ? 0 : term.c.x, y);
1152 }
1153
1154 void
1155 csiparse(void) {
1156         /* int noarg = 1; */
1157         char *p = csiescseq.buf;
1158
1159         csiescseq.narg = 0;
1160         if(*p == '?')
1161                 csiescseq.priv = 1, p++;
1162
1163         while(p < csiescseq.buf+csiescseq.len) {
1164                 while(isdigit(*p)) {
1165                         csiescseq.arg[csiescseq.narg] *= 10;
1166                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1167                 }
1168                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1169                         csiescseq.narg++, p++;
1170                 } else {
1171                         csiescseq.mode = *p;
1172                         csiescseq.narg++;
1173
1174                         return;
1175                 }
1176         }
1177 }
1178
1179 void
1180 tmoveto(int x, int y) {
1181         LIMIT(x, 0, term.col-1);
1182         LIMIT(y, 0, term.row-1);
1183         term.c.state &= ~CURSOR_WRAPNEXT;
1184         term.c.x = x;
1185         term.c.y = y;
1186 }
1187
1188 void
1189 tsetchar(char *c, Glyph *attr, int x, int y) {
1190         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1191                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1192                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1193                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1194                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1195                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1196                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1197                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1198                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1199         };
1200
1201         /*
1202          * The table is proudly stolen from rxvt.
1203          */
1204         if(attr->mode & ATTR_GFX) {
1205                 if(c[0] >= 0x41 && c[0] <= 0x7e
1206                                 && vt100_0[c[0] - 0x41]) {
1207                         c = vt100_0[c[0] - 0x41];
1208                 }
1209         }
1210
1211         term.dirty[y] = 1;
1212         term.line[y][x] = *attr;
1213         memcpy(term.line[y][x].c, c, UTF_SIZ);
1214         term.line[y][x].state |= GLYPH_SET;
1215 }
1216
1217 void
1218 tclearregion(int x1, int y1, int x2, int y2) {
1219         int x, y, temp;
1220
1221         if(x1 > x2)
1222                 temp = x1, x1 = x2, x2 = temp;
1223         if(y1 > y2)
1224                 temp = y1, y1 = y2, y2 = temp;
1225
1226         LIMIT(x1, 0, term.col-1);
1227         LIMIT(x2, 0, term.col-1);
1228         LIMIT(y1, 0, term.row-1);
1229         LIMIT(y2, 0, term.row-1);
1230
1231         for(y = y1; y <= y2; y++) {
1232                 term.dirty[y] = 1;
1233                 for(x = x1; x <= x2; x++)
1234                         term.line[y][x].state = 0;
1235         }
1236 }
1237
1238 void
1239 tdeletechar(int n) {
1240         int src = term.c.x + n;
1241         int dst = term.c.x;
1242         int size = term.col - src;
1243
1244         term.dirty[term.c.y] = 1;
1245
1246         if(src >= term.col) {
1247                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1248                 return;
1249         }
1250
1251         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1252                         size * sizeof(Glyph));
1253         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1254 }
1255
1256 void
1257 tinsertblank(int n) {
1258         int src = term.c.x;
1259         int dst = src + n;
1260         int size = term.col - dst;
1261
1262         term.dirty[term.c.y] = 1;
1263
1264         if(dst >= term.col) {
1265                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1266                 return;
1267         }
1268
1269         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1270                         size * sizeof(Glyph));
1271         tclearregion(src, term.c.y, dst - 1, term.c.y);
1272 }
1273
1274 void
1275 tinsertblankline(int n) {
1276         if(term.c.y < term.top || term.c.y > term.bot)
1277                 return;
1278
1279         tscrolldown(term.c.y, n);
1280 }
1281
1282 void
1283 tdeleteline(int n) {
1284         if(term.c.y < term.top || term.c.y > term.bot)
1285                 return;
1286
1287         tscrollup(term.c.y, n);
1288 }
1289
1290 void
1291 tsetattr(int *attr, int l) {
1292         int i;
1293
1294         for(i = 0; i < l; i++) {
1295                 switch(attr[i]) {
1296                 case 0:
1297                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1298                                         | ATTR_ITALIC | ATTR_BLINK);
1299                         term.c.attr.fg = DefaultFG;
1300                         term.c.attr.bg = DefaultBG;
1301                         break;
1302                 case 1:
1303                         term.c.attr.mode |= ATTR_BOLD;
1304                         break;
1305                 case 3: /* enter standout (highlight) */
1306                         term.c.attr.mode |= ATTR_ITALIC;
1307                         break;
1308                 case 4:
1309                         term.c.attr.mode |= ATTR_UNDERLINE;
1310                         break;
1311                 case 5:
1312                         term.c.attr.mode |= ATTR_BLINK;
1313                         break;
1314                 case 7:
1315                         term.c.attr.mode |= ATTR_REVERSE;
1316                         break;
1317                 case 21:
1318                 case 22:
1319                         term.c.attr.mode &= ~ATTR_BOLD;
1320                         break;
1321                 case 23: /* leave standout (highlight) mode */
1322                         term.c.attr.mode &= ~ATTR_ITALIC;
1323                         break;
1324                 case 24:
1325                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1326                         break;
1327                 case 25:
1328                         term.c.attr.mode &= ~ATTR_BLINK;
1329                         break;
1330                 case 27:
1331                         term.c.attr.mode &= ~ATTR_REVERSE;
1332                         break;
1333                 case 38:
1334                         if(i + 2 < l && attr[i + 1] == 5) {
1335                                 i += 2;
1336                                 if(BETWEEN(attr[i], 0, 255)) {
1337                                         term.c.attr.fg = attr[i];
1338                                 } else {
1339                                         fprintf(stderr,
1340                                                 "erresc: bad fgcolor %d\n",
1341                                                 attr[i]);
1342                                 }
1343                         } else {
1344                                 fprintf(stderr,
1345                                         "erresc(38): gfx attr %d unknown\n",
1346                                         attr[i]);
1347                         }
1348                         break;
1349                 case 39:
1350                         term.c.attr.fg = DefaultFG;
1351                         break;
1352                 case 48:
1353                         if(i + 2 < l && attr[i + 1] == 5) {
1354                                 i += 2;
1355                                 if(BETWEEN(attr[i], 0, 255)) {
1356                                         term.c.attr.bg = attr[i];
1357                                 } else {
1358                                         fprintf(stderr,
1359                                                 "erresc: bad bgcolor %d\n",
1360                                                 attr[i]);
1361                                 }
1362                         } else {
1363                                 fprintf(stderr,
1364                                         "erresc(48): gfx attr %d unknown\n",
1365                                         attr[i]);
1366                         }
1367                         break;
1368                 case 49:
1369                         term.c.attr.bg = DefaultBG;
1370                         break;
1371                 default:
1372                         if(BETWEEN(attr[i], 30, 37)) {
1373                                 term.c.attr.fg = attr[i] - 30;
1374                         } else if(BETWEEN(attr[i], 40, 47)) {
1375                                 term.c.attr.bg = attr[i] - 40;
1376                         } else if(BETWEEN(attr[i], 90, 97)) {
1377                                 term.c.attr.fg = attr[i] - 90 + 8;
1378                         } else if(BETWEEN(attr[i], 100, 107)) {
1379                                 term.c.attr.bg = attr[i] - 100 + 8;
1380                         } else {
1381                                 fprintf(stderr,
1382                                         "erresc(default): gfx attr %d unknown\n",
1383                                         attr[i]), csidump();
1384                         }
1385                         break;
1386                 }
1387         }
1388 }
1389
1390 void
1391 tsetscroll(int t, int b) {
1392         int temp;
1393
1394         LIMIT(t, 0, term.row-1);
1395         LIMIT(b, 0, term.row-1);
1396         if(t > b) {
1397                 temp = t;
1398                 t = b;
1399                 b = temp;
1400         }
1401         term.top = t;
1402         term.bot = b;
1403 }
1404
1405 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1406
1407 void
1408 tsetmode(bool priv, bool set, int *args, int narg) {
1409         int *lim, mode;
1410
1411         for(lim = args + narg; args < lim; ++args) {
1412                 if(priv) {
1413                         switch(*args) {
1414                                 break;
1415                         case 1: /* DECCKM -- Cursor key */
1416                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1417                                 break;
1418                         case 5: /* DECSCNM -- Reverse video */
1419                                 mode = term.mode;
1420                                 MODBIT(term.mode, set, MODE_REVERSE);
1421                                 if(mode != term.mode)
1422                                         redraw();
1423                                 break;
1424                         case 6: /* XXX: DECOM -- Origin */
1425                                 break;
1426                         case 7: /* DECAWM -- Auto wrap */
1427                                 MODBIT(term.mode, set, MODE_WRAP);
1428                                 break;
1429                         case 8: /* XXX: DECARM -- Auto repeat */
1430                                 break;
1431                         case 0:  /* Error (IGNORED) */
1432                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1433                                 break;
1434                         case 25:
1435                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1436                                 break;
1437                         case 1000: /* 1000,1002: enable xterm mouse report */
1438                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1439                                 break;
1440                         case 1002:
1441                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1442                                 break;
1443                         case 1049: /* = 1047 and 1048 */
1444                         case 47:
1445                         case 1047:
1446                                 if(IS_SET(MODE_ALTSCREEN))
1447                                         tclearregion(0, 0, term.col-1, term.row-1);
1448                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1449                                                 (!set && IS_SET(MODE_ALTSCREEN))) {
1450                                         tswapscreen();
1451                                 }
1452                                 if(*args != 1049)
1453                                         break;
1454                                 /* pass through */
1455                         case 1048:
1456                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1457                                 break;
1458                         default:
1459                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1460                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1461                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1462                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1463                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1464                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1465                                 fprintf(stderr,
1466                                         "erresc: unknown private set/reset mode %d\n",
1467                                         *args);
1468                                 break;
1469                         }
1470                 } else {
1471                         switch(*args) {
1472                         case 0:  /* Error (IGNORED) */
1473                                 break;
1474                         case 2:  /* KAM -- keyboard action */
1475                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1476                                 break;
1477                         case 4:  /* IRM -- Insertion-replacement */
1478                                 MODBIT(term.mode, set, MODE_INSERT);
1479                                 break;
1480                         case 12: /* XXX: SRM -- Send/Receive */
1481                                 break;
1482                         case 20: /* LNM -- Linefeed/new line */
1483                                 MODBIT(term.mode, set, MODE_CRLF);
1484                                 break;
1485                         default:
1486                                 fprintf(stderr,
1487                                         "erresc: unknown set/reset mode %d\n",
1488                                         *args);
1489                                 break;
1490                         }
1491                 }
1492         }
1493 }
1494 #undef MODBIT
1495
1496
1497 void
1498 csihandle(void) {
1499         switch(csiescseq.mode) {
1500         default:
1501         unknown:
1502                 fprintf(stderr, "erresc: unknown csi ");
1503                 csidump();
1504                 /* die(""); */
1505                 break;
1506         case '@': /* ICH -- Insert <n> blank char */
1507                 DEFAULT(csiescseq.arg[0], 1);
1508                 tinsertblank(csiescseq.arg[0]);
1509                 break;
1510         case 'A': /* CUU -- Cursor <n> Up */
1511         case 'e':
1512                 DEFAULT(csiescseq.arg[0], 1);
1513                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1514                 break;
1515         case 'B': /* CUD -- Cursor <n> Down */
1516                 DEFAULT(csiescseq.arg[0], 1);
1517                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1518                 break;
1519         case 'c': /* DA -- Device Attributes */
1520                 if(csiescseq.arg[0] == 0)
1521                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1522                 break;
1523         case 'C': /* CUF -- Cursor <n> Forward */
1524         case 'a':
1525                 DEFAULT(csiescseq.arg[0], 1);
1526                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1527                 break;
1528         case 'D': /* CUB -- Cursor <n> Backward */
1529                 DEFAULT(csiescseq.arg[0], 1);
1530                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1531                 break;
1532         case 'E': /* CNL -- Cursor <n> Down and first col */
1533                 DEFAULT(csiescseq.arg[0], 1);
1534                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1535                 break;
1536         case 'F': /* CPL -- Cursor <n> Up and first col */
1537                 DEFAULT(csiescseq.arg[0], 1);
1538                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1539                 break;
1540         case 'g': /* TBC -- Tabulation clear */
1541                 switch (csiescseq.arg[0]) {
1542                 case 0: /* clear current tab stop */
1543                         term.tabs[term.c.x] = 0;
1544                         break;
1545                 case 3: /* clear all the tabs */
1546                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1547                         break;
1548                 default:
1549                         goto unknown;
1550                 }
1551                 break;
1552         case 'G': /* CHA -- Move to <col> */
1553         case '`': /* HPA */
1554                 DEFAULT(csiescseq.arg[0], 1);
1555                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1556                 break;
1557         case 'H': /* CUP -- Move to <row> <col> */
1558         case 'f': /* HVP */
1559                 DEFAULT(csiescseq.arg[0], 1);
1560                 DEFAULT(csiescseq.arg[1], 1);
1561                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1562                 break;
1563         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1564                 DEFAULT(csiescseq.arg[0], 1);
1565                 while(csiescseq.arg[0]--)
1566                         tputtab(1);
1567                 break;
1568         case 'J': /* ED -- Clear screen */
1569                 sel.bx = -1;
1570                 switch(csiescseq.arg[0]) {
1571                 case 0: /* below */
1572                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1573                         if(term.c.y < term.row-1)
1574                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1575                         break;
1576                 case 1: /* above */
1577                         if(term.c.y > 1)
1578                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1579                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1580                         break;
1581                 case 2: /* all */
1582                         tclearregion(0, 0, term.col-1, term.row-1);
1583                         break;
1584                 default:
1585                         goto unknown;
1586                 }
1587                 break;
1588         case 'K': /* EL -- Clear line */
1589                 switch(csiescseq.arg[0]) {
1590                 case 0: /* right */
1591                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1592                         break;
1593                 case 1: /* left */
1594                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1595                         break;
1596                 case 2: /* all */
1597                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1598                         break;
1599                 }
1600                 break;
1601         case 'S': /* SU -- Scroll <n> line up */
1602                 DEFAULT(csiescseq.arg[0], 1);
1603                 tscrollup(term.top, csiescseq.arg[0]);
1604                 break;
1605         case 'T': /* SD -- Scroll <n> line down */
1606                 DEFAULT(csiescseq.arg[0], 1);
1607                 tscrolldown(term.top, csiescseq.arg[0]);
1608                 break;
1609         case 'L': /* IL -- Insert <n> blank lines */
1610                 DEFAULT(csiescseq.arg[0], 1);
1611                 tinsertblankline(csiescseq.arg[0]);
1612                 break;
1613         case 'l': /* RM -- Reset Mode */
1614                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1615                 break;
1616         case 'M': /* DL -- Delete <n> lines */
1617                 DEFAULT(csiescseq.arg[0], 1);
1618                 tdeleteline(csiescseq.arg[0]);
1619                 break;
1620         case 'X': /* ECH -- Erase <n> char */
1621                 DEFAULT(csiescseq.arg[0], 1);
1622                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1623                 break;
1624         case 'P': /* DCH -- Delete <n> char */
1625                 DEFAULT(csiescseq.arg[0], 1);
1626                 tdeletechar(csiescseq.arg[0]);
1627                 break;
1628         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1629                 DEFAULT(csiescseq.arg[0], 1);
1630                 while(csiescseq.arg[0]--)
1631                         tputtab(0);
1632                 break;
1633         case 'd': /* VPA -- Move to <row> */
1634                 DEFAULT(csiescseq.arg[0], 1);
1635                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1636                 break;
1637         case 'h': /* SM -- Set terminal mode */
1638                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1639                 break;
1640         case 'm': /* SGR -- Terminal attribute (color) */
1641                 tsetattr(csiescseq.arg, csiescseq.narg);
1642                 break;
1643         case 'r': /* DECSTBM -- Set Scrolling Region */
1644                 if(csiescseq.priv) {
1645                         goto unknown;
1646                 } else {
1647                         DEFAULT(csiescseq.arg[0], 1);
1648                         DEFAULT(csiescseq.arg[1], term.row);
1649                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1650                         tmoveto(0, 0);
1651                 }
1652                 break;
1653         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1654                 tcursor(CURSOR_SAVE);
1655                 break;
1656         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1657                 tcursor(CURSOR_LOAD);
1658                 break;
1659         }
1660 }
1661
1662 void
1663 csidump(void) {
1664         int i;
1665         uint c;
1666
1667         printf("ESC[");
1668         for(i = 0; i < csiescseq.len; i++) {
1669                 c = csiescseq.buf[i] & 0xff;
1670                 if(isprint(c)) {
1671                         putchar(c);
1672                 } else if(c == '\n') {
1673                         printf("(\\n)");
1674                 } else if(c == '\r') {
1675                         printf("(\\r)");
1676                 } else if(c == 0x1b) {
1677                         printf("(\\e)");
1678                 } else {
1679                         printf("(%02x)", c);
1680                 }
1681         }
1682         putchar('\n');
1683 }
1684
1685 void
1686 csireset(void) {
1687         memset(&csiescseq, 0, sizeof(csiescseq));
1688 }
1689
1690 void
1691 strhandle(void) {
1692         char *p;
1693
1694         /*
1695          * TODO: make this being useful in case of color palette change.
1696          */
1697         strparse();
1698
1699         p = strescseq.buf;
1700
1701         switch(strescseq.type) {
1702         case ']': /* OSC -- Operating System Command */
1703                 switch(p[0]) {
1704                 case '0':
1705                 case '1':
1706                 case '2':
1707                         /*
1708                          * TODO: Handle special chars in string, like umlauts.
1709                          */
1710                         if(p[1] == ';') {
1711                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1712                         }
1713                         break;
1714                 case ';':
1715                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1716                         break;
1717                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1718                         break;
1719                 default:
1720                         fprintf(stderr, "erresc: unknown str ");
1721                         strdump();
1722                         break;
1723                 }
1724                 break;
1725         case 'k': /* old title set compatibility */
1726                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1727                 break;
1728         case 'P': /* DSC -- Device Control String */
1729         case '_': /* APC -- Application Program Command */
1730         case '^': /* PM -- Privacy Message */
1731         default:
1732                 fprintf(stderr, "erresc: unknown str ");
1733                 strdump();
1734                 /* die(""); */
1735                 break;
1736         }
1737 }
1738
1739 void
1740 strparse(void) {
1741         /*
1742          * TODO: Implement parsing like for CSI when required.
1743          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1744          */
1745         return;
1746 }
1747
1748 void
1749 strdump(void) {
1750         int i;
1751         uint c;
1752
1753         printf("ESC%c", strescseq.type);
1754         for(i = 0; i < strescseq.len; i++) {
1755                 c = strescseq.buf[i] & 0xff;
1756                 if(isprint(c)) {
1757                         putchar(c);
1758                 } else if(c == '\n') {
1759                         printf("(\\n)");
1760                 } else if(c == '\r') {
1761                         printf("(\\r)");
1762                 } else if(c == 0x1b) {
1763                         printf("(\\e)");
1764                 } else {
1765                         printf("(%02x)", c);
1766                 }
1767         }
1768         printf("ESC\\\n");
1769 }
1770
1771 void
1772 strreset(void) {
1773         memset(&strescseq, 0, sizeof(strescseq));
1774 }
1775
1776 void
1777 tputtab(bool forward) {
1778         uint x = term.c.x;
1779
1780         if(forward) {
1781                 if(x == term.col)
1782                         return;
1783                 for(++x; x < term.col && !term.tabs[x]; ++x)
1784                         /* nothing */ ;
1785         } else {
1786                 if(x == 0)
1787                         return;
1788                 for(--x; x > 0 && !term.tabs[x]; --x)
1789                         /* nothing */ ;
1790         }
1791         tmoveto(x, term.c.y);
1792 }
1793
1794 void
1795 tputc(char *c, int len) {
1796         uchar ascii = *c;
1797         bool control = ascii < '\x20' || ascii == 0177;
1798
1799         if(iofd != -1)
1800                 write(iofd, c, len);
1801         /*
1802          * STR sequences must be checked before of anything
1803          * because it can use some control codes as part of the sequence
1804          */
1805         if(term.esc & ESC_STR) {
1806                 switch(ascii) {
1807                 case '\033':
1808                         term.esc = ESC_START | ESC_STR_END;
1809                         break;
1810                 case '\a': /* backwards compatibility to xterm */
1811                         term.esc = 0;
1812                         strhandle();
1813                         break;
1814                 default:
1815                         strescseq.buf[strescseq.len++] = ascii;
1816                         if(strescseq.len+1 >= STR_BUF_SIZ) {
1817                                 term.esc = 0;
1818                                 strhandle();
1819                         }
1820                 }
1821                 return;
1822         }
1823         /*
1824          * Actions of control codes must be performed as soon they arrive
1825          * because they can be embedded inside a control sequence, and
1826          * they must not cause conflicts with sequences.
1827          */
1828         if(control) {
1829                 switch(ascii) {
1830                 case '\t':      /* HT */
1831                         tputtab(1);
1832                         return;
1833                 case '\b':      /* BS */
1834                         tmoveto(term.c.x-1, term.c.y);
1835                         return;
1836                 case '\r':      /* CR */
1837                         tmoveto(0, term.c.y);
1838                         return;
1839                 case '\f':      /* LF */
1840                 case '\v':      /* VT */
1841                 case '\n':      /* LF */
1842                         /* go to first col if the mode is set */
1843                         tnewline(IS_SET(MODE_CRLF));
1844                         return;
1845                 case '\a':      /* BEL */
1846                         if(!(xw.state & WIN_FOCUSED))
1847                                 xseturgency(1);
1848                         return;
1849                 case '\033':    /* ESC */
1850                         csireset();
1851                         term.esc = ESC_START;
1852                         return;
1853                 case '\016':    /* SO */
1854                         term.c.attr.mode |= ATTR_GFX;
1855                         return;
1856                 case '\017':    /* SI */
1857                         term.c.attr.mode &= ~ATTR_GFX;
1858                         return;
1859                 case '\032':    /* SUB */
1860                 case '\030':    /* CAN */
1861                         csireset();
1862                         return;
1863                  case '\005':   /* ENQ (IGNORED) */
1864                  case '\000':   /* NUL (IGNORED) */
1865                  case '\021':   /* XON (IGNORED) */
1866                  case '\023':   /* XOFF (IGNORED) */
1867                  case 0177:     /* DEL (IGNORED) */
1868                         return;
1869                 }
1870         } else if(term.esc & ESC_START) {
1871                 if(term.esc & ESC_CSI) {
1872                         csiescseq.buf[csiescseq.len++] = ascii;
1873                         if(BETWEEN(ascii, 0x40, 0x7E)
1874                                         || csiescseq.len >= ESC_BUF_SIZ) {
1875                                 term.esc = 0;
1876                                 csiparse(), csihandle();
1877                         }
1878                 } else if(term.esc & ESC_STR_END) {
1879                         term.esc = 0;
1880                         if(ascii == '\\')
1881                                 strhandle();
1882                 } else if(term.esc & ESC_ALTCHARSET) {
1883                         switch(ascii) {
1884                         case '0': /* Line drawing set */
1885                                 term.c.attr.mode |= ATTR_GFX;
1886                                 break;
1887                         case 'B': /* USASCII */
1888                                 term.c.attr.mode &= ~ATTR_GFX;
1889                                 break;
1890                         case 'A': /* UK (IGNORED) */
1891                         case '<': /* multinational charset (IGNORED) */
1892                         case '5': /* Finnish (IGNORED) */
1893                         case 'C': /* Finnish (IGNORED) */
1894                         case 'K': /* German (IGNORED) */
1895                                 break;
1896                         default:
1897                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1898                         }
1899                         term.esc = 0;
1900                 } else if(term.esc & ESC_TEST) {
1901                         if(ascii == '8') { /* DEC screen alignment test. */
1902                                 char E[UTF_SIZ] = "E";
1903                                 int x, y;
1904
1905                                 for(x = 0; x < term.col; ++x) {
1906                                         for(y = 0; y < term.row; ++y)
1907                                                 tsetchar(E, &term.c.attr, x, y);
1908                                 }
1909                         }
1910                         term.esc = 0;
1911                 } else {
1912                         switch(ascii) {
1913                         case '[':
1914                                 term.esc |= ESC_CSI;
1915                                 break;
1916                         case '#':
1917                                 term.esc |= ESC_TEST;
1918                                 break;
1919                         case 'P': /* DCS -- Device Control String */
1920                         case '_': /* APC -- Application Program Command */
1921                         case '^': /* PM -- Privacy Message */
1922                         case ']': /* OSC -- Operating System Command */
1923                         case 'k': /* old title set compatibility */
1924                                 strreset();
1925                                 strescseq.type = ascii;
1926                                 term.esc |= ESC_STR;
1927                                 break;
1928                         case '(': /* set primary charset G0 */
1929                                 term.esc |= ESC_ALTCHARSET;
1930                                 break;
1931                         case ')': /* set secondary charset G1 (IGNORED) */
1932                         case '*': /* set tertiary charset G2 (IGNORED) */
1933                         case '+': /* set quaternary charset G3 (IGNORED) */
1934                                 term.esc = 0;
1935                                 break;
1936                         case 'D': /* IND -- Linefeed */
1937                                 if(term.c.y == term.bot) {
1938                                         tscrollup(term.top, 1);
1939                                 } else {
1940                                         tmoveto(term.c.x, term.c.y+1);
1941                                 }
1942                                 term.esc = 0;
1943                                 break;
1944                         case 'E': /* NEL -- Next line */
1945                                 tnewline(1); /* always go to first col */
1946                                 term.esc = 0;
1947                                 break;
1948                         case 'H': /* HTS -- Horizontal tab stop */
1949                                 term.tabs[term.c.x] = 1;
1950                                 term.esc = 0;
1951                                 break;
1952                         case 'M': /* RI -- Reverse index */
1953                                 if(term.c.y == term.top) {
1954                                         tscrolldown(term.top, 1);
1955                                 } else {
1956                                         tmoveto(term.c.x, term.c.y-1);
1957                                 }
1958                                 term.esc = 0;
1959                                 break;
1960                         case 'Z': /* DECID -- Identify Terminal */
1961                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1962                                 term.esc = 0;
1963                                 break;
1964                         case 'c': /* RIS -- Reset to inital state */
1965                                 treset();
1966                                 term.esc = 0;
1967                                 xresettitle();
1968                                 break;
1969                         case '=': /* DECPAM -- Application keypad */
1970                                 term.mode |= MODE_APPKEYPAD;
1971                                 term.esc = 0;
1972                                 break;
1973                         case '>': /* DECPNM -- Normal keypad */
1974                                 term.mode &= ~MODE_APPKEYPAD;
1975                                 term.esc = 0;
1976                                 break;
1977                         case '7': /* DECSC -- Save Cursor */
1978                                 tcursor(CURSOR_SAVE);
1979                                 term.esc = 0;
1980                                 break;
1981                         case '8': /* DECRC -- Restore Cursor */
1982                                 tcursor(CURSOR_LOAD);
1983                                 term.esc = 0;
1984                                 break;
1985                         case '\\': /* ST -- Stop */
1986                                 term.esc = 0;
1987                                 break;
1988                         default:
1989                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1990                                         (uchar) ascii, isprint(ascii)? ascii:'.');
1991                                 term.esc = 0;
1992                         }
1993                 }
1994                 /*
1995                  * All characters which forms part of a sequence are not
1996                  * printed
1997                  */
1998                 return;
1999         }
2000         /*
2001          * Display control codes only if we are in graphic mode
2002          */
2003         if(control && !(term.c.attr.mode & ATTR_GFX))
2004                 return;
2005         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2006                 sel.bx = -1;
2007         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2008                 tnewline(1); /* always go to first col */
2009         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2010         if(term.c.x+1 < term.col)
2011                 tmoveto(term.c.x+1, term.c.y);
2012         else
2013                 term.c.state |= CURSOR_WRAPNEXT;
2014 }
2015
2016 int
2017 tresize(int col, int row) {
2018         int i, x;
2019         int minrow = MIN(row, term.row);
2020         int mincol = MIN(col, term.col);
2021         int slide = term.c.y - row + 1;
2022         bool *bp;
2023
2024         if(col < 1 || row < 1)
2025                 return 0;
2026
2027         /* free unneeded rows */
2028         i = 0;
2029         if(slide > 0) {
2030                 /* slide screen to keep cursor where we expect it -
2031                  * tscrollup would work here, but we can optimize to
2032                  * memmove because we're freeing the earlier lines */
2033                 for(/* i = 0 */; i < slide; i++) {
2034                         free(term.line[i]);
2035                         free(term.alt[i]);
2036                 }
2037                 memmove(term.line, term.line + slide, row * sizeof(Line));
2038                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2039         }
2040         for(i += row; i < term.row; i++) {
2041                 free(term.line[i]);
2042                 free(term.alt[i]);
2043         }
2044
2045         /* resize to new height */
2046         term.line = xrealloc(term.line, row * sizeof(Line));
2047         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2048         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2049         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2050
2051         /* resize each row to new width, zero-pad if needed */
2052         for(i = 0; i < minrow; i++) {
2053                 term.dirty[i] = 1;
2054                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2055                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2056                 for(x = mincol; x < col; x++) {
2057                         term.line[i][x].state = 0;
2058                         term.alt[i][x].state = 0;
2059                 }
2060         }
2061
2062         /* allocate any new rows */
2063         for(/* i == minrow */; i < row; i++) {
2064                 term.dirty[i] = 1;
2065                 term.line[i] = xcalloc(col, sizeof(Glyph));
2066                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2067         }
2068         if(col > term.col) {
2069                 bp = term.tabs + term.col;
2070
2071                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2072                 while(--bp > term.tabs && !*bp)
2073                         /* nothing */ ;
2074                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2075                         *bp = 1;
2076         }
2077         /* update terminal size */
2078         term.col = col, term.row = row;
2079         /* make use of the LIMIT in tmoveto */
2080         tmoveto(term.c.x, term.c.y);
2081         /* reset scrolling region */
2082         tsetscroll(0, row-1);
2083
2084         return (slide > 0);
2085 }
2086
2087 void
2088 xresize(int col, int row) {
2089         xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2090         xw.th = MAX(1, 2*BORDER + row * xw.ch);
2091
2092         XftDrawChange(xw.xft_draw, xw.buf);
2093 }
2094
2095 void
2096 xloadcols(void) {
2097         int i, r, g, b;
2098         XRenderColor xft_color = { .alpha = 0 };
2099
2100         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2101         for(i = 0; i < LEN(colorname); i++) {
2102                 if(!colorname[i])
2103                         continue;
2104                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2105                         die("Could not allocate color '%s'\n", colorname[i]);
2106                 }
2107         }
2108
2109         /* load colors [16-255] ; same colors as xterm */
2110         for(i = 16, r = 0; r < 6; r++) {
2111                 for(g = 0; g < 6; g++) {
2112                         for(b = 0; b < 6; b++) {
2113                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2114                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2115                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2116                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2117                                         die("Could not allocate color %d\n", i);
2118                                 }
2119                                 i++;
2120                         }
2121                 }
2122         }
2123
2124         for(r = 0; r < 24; r++, i++) {
2125                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2126                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2127                                         &dc.xft_col[i])) {
2128                         die("Could not allocate color %d\n", i);
2129                 }
2130         }
2131 }
2132
2133 void
2134 xtermclear(int col1, int row1, int col2, int row2) {
2135         XftDrawRect(xw.xft_draw,
2136                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2137                         BORDER + col1 * xw.cw,
2138                         BORDER + row1 * xw.ch,
2139                         (col2-col1+1) * xw.cw,
2140                         (row2-row1+1) * xw.ch);
2141 }
2142
2143 /*
2144  * Absolute coordinates.
2145  */
2146 void
2147 xclear(int x1, int y1, int x2, int y2) {
2148         XftDrawRect(xw.xft_draw,
2149                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2150                         x1, y1, x2-x1, y2-y1);
2151 }
2152
2153 void
2154 xhints(void) {
2155         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2156         XWMHints wm = {.flags = InputHint, .input = 1};
2157         XSizeHints *sizeh = NULL;
2158
2159         sizeh = XAllocSizeHints();
2160         if(xw.isfixed == False) {
2161                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2162                 sizeh->height = xw.h;
2163                 sizeh->width = xw.w;
2164                 sizeh->height_inc = xw.ch;
2165                 sizeh->width_inc = xw.cw;
2166                 sizeh->base_height = 2*BORDER;
2167                 sizeh->base_width = 2*BORDER;
2168         } else {
2169                 sizeh->flags = PMaxSize | PMinSize;
2170                 sizeh->min_width = sizeh->max_width = xw.fw;
2171                 sizeh->min_height = sizeh->max_height = xw.fh;
2172         }
2173
2174         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2175         XFree(sizeh);
2176 }
2177
2178 void
2179 xinitfont(Font *f, char *fontstr) {
2180         FcPattern *pattern, *match;
2181         FcResult result;
2182
2183         pattern = FcNameParse((FcChar8 *)fontstr);
2184         if(!pattern)
2185                 die("st: can't open font %s\n", fontstr);
2186
2187         match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2188         FcPatternDestroy(pattern);
2189         if(!match)
2190                 die("st: can't open font %s\n", fontstr);
2191         if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2192                 FcPatternDestroy(match);
2193                 die("st: can't open font %s.\n", fontstr);
2194         }
2195
2196         f->ascent = f->xft_set->ascent;
2197         f->descent = f->xft_set->descent;
2198         f->lbearing = 0;
2199         f->rbearing = f->xft_set->max_advance_width;
2200
2201         f->height = f->xft_set->height;
2202         f->width = f->lbearing + f->rbearing;
2203 }
2204
2205 void
2206 initfonts(char *fontstr) {
2207         char *fstr;
2208
2209         xinitfont(&dc.font, fontstr);
2210         xw.cw = dc.font.width;
2211         xw.ch = dc.font.height;
2212
2213         fstr = smstrcat(fontstr, ":weight=bold", NULL);
2214         xinitfont(&dc.bfont, fstr);
2215         free(fstr);
2216
2217         fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2218         xinitfont(&dc.ifont, fstr);
2219         free(fstr);
2220
2221         fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2222         xinitfont(&dc.ibfont, fstr);
2223         free(fstr);
2224 }
2225
2226 void
2227 xinit(void) {
2228         XSetWindowAttributes attrs;
2229         Cursor cursor;
2230         Window parent;
2231         int sw, sh, major, minor;
2232
2233         if(!(xw.dpy = XOpenDisplay(NULL)))
2234                 die("Can't open display\n");
2235         xw.scr = XDefaultScreen(xw.dpy);
2236         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2237
2238         /* font */
2239         initfonts((opt_font != NULL)? opt_font : FONT);
2240
2241         /* colors */
2242         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2243         xloadcols();
2244
2245         /* adjust fixed window geometry */
2246         if(xw.isfixed) {
2247                 sw = DisplayWidth(xw.dpy, xw.scr);
2248                 sh = DisplayHeight(xw.dpy, xw.scr);
2249                 if(xw.fx < 0)
2250                         xw.fx = sw + xw.fx - xw.fw - 1;
2251                 if(xw.fy < 0)
2252                         xw.fy = sh + xw.fy - xw.fh - 1;
2253
2254                 xw.h = xw.fh;
2255                 xw.w = xw.fw;
2256         } else {
2257                 /* window - default size */
2258                 xw.h = 2*BORDER + term.row * xw.ch;
2259                 xw.w = 2*BORDER + term.col * xw.cw;
2260                 xw.fx = 0;
2261                 xw.fy = 0;
2262         }
2263
2264         attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2265         attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2266         attrs.bit_gravity = NorthWestGravity;
2267         attrs.event_mask = FocusChangeMask | KeyPressMask
2268                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2269                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2270         attrs.colormap = xw.cmap;
2271
2272         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2273         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2274                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2275                         xw.vis,
2276                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2277                         | CWColormap,
2278                         &attrs);
2279
2280         /* double buffering */
2281         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2282                 die("Xdbe extension is not present\n");
2283         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2284
2285         /* Xft rendering context */
2286         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2287
2288         /* input methods */
2289         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2290         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2291                                            | XIMStatusNothing, XNClientWindow, xw.win,
2292                                            XNFocusWindow, xw.win, NULL);
2293         /* gc */
2294         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2295
2296         /* white cursor, black outline */
2297         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2298         XDefineCursor(xw.dpy, xw.win, cursor);
2299         XRecolorCursor(xw.dpy, cursor,
2300                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2301                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2302
2303         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2304         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2305         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2306
2307         xresettitle();
2308         XMapWindow(xw.dpy, xw.win);
2309         xhints();
2310         XSync(xw.dpy, 0);
2311 }
2312
2313 void
2314 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2315         int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2316             width = charlen * xw.cw;
2317         Font *font = &dc.font;
2318         XGlyphInfo extents;
2319         XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2320                  *temp, revfg, revbg;
2321         XRenderColor colfg, colbg;
2322
2323         if(base.mode & ATTR_REVERSE)
2324                 temp = fg, fg = bg, bg = temp;
2325
2326         if(base.mode & ATTR_BOLD) {
2327                 if(BETWEEN(base.fg, 0, 7)) {
2328                         /* basic system colors */
2329                         fg = &dc.xft_col[base.fg + 8];
2330                 } else if(BETWEEN(base.fg, 16, 195)) {
2331                         /* 256 colors */
2332                         fg = &dc.xft_col[base.fg + 36];
2333                 } else if(BETWEEN(base.fg, 232, 251)) {
2334                         /* greyscale */
2335                         fg = &dc.xft_col[base.fg + 4];
2336                 }
2337                 /*
2338                  * Those ranges will not be brightened:
2339                  *      8 - 15 – bright system colors
2340                  *      196 - 231 – highest 256 color cube
2341                  *      252 - 255 – brightest colors in greyscale
2342                  */
2343                 font = &dc.bfont;
2344         }
2345
2346         if(base.mode & ATTR_ITALIC)
2347                 font = &dc.ifont;
2348         if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2349                 font = &dc.ibfont;
2350
2351         if(IS_SET(MODE_REVERSE)) {
2352                 if(fg == &dc.xft_col[DefaultFG]) {
2353                         fg = &dc.xft_col[DefaultBG];
2354                 } else {
2355                         colfg.red = ~fg->color.red;
2356                         colfg.green = ~fg->color.green;
2357                         colfg.blue = ~fg->color.blue;
2358                         colfg.alpha = fg->color.alpha;
2359                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2360                         fg = &revfg;
2361                 }
2362
2363                 if(bg == &dc.xft_col[DefaultBG]) {
2364                         bg = &dc.xft_col[DefaultFG];
2365                 } else {
2366                         colbg.red = ~bg->color.red;
2367                         colbg.green = ~bg->color.green;
2368                         colbg.blue = ~bg->color.blue;
2369                         colbg.alpha = bg->color.alpha;
2370                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2371                         bg = &revbg;
2372                 }
2373         }
2374
2375         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2376                         &extents);
2377         width = extents.xOff;
2378
2379         /* Intelligent cleaning up of the borders. */
2380         if(x == 0) {
2381                 xclear(0, (y == 0)? 0 : winy, BORDER,
2382                         winy + xw.ch + (y == term.row-1)? xw.h : 0);
2383         }
2384         if(x + charlen >= term.col-1) {
2385                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2386                         (y == term.row-1)? xw.h : (winy + xw.ch));
2387         }
2388         if(y == 0)
2389                 xclear(winx, 0, winx + width, BORDER);
2390         if(y == term.row-1)
2391                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2392
2393         XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2394         XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2395                         winy + font->ascent, (FcChar8 *)s, bytelen);
2396
2397         if(base.mode & ATTR_UNDERLINE) {
2398                 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2399                                 width, 1);
2400         }
2401 }
2402
2403 void
2404 xdrawcursor(void) {
2405         static int oldx = 0, oldy = 0;
2406         int sl;
2407         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2408
2409         LIMIT(oldx, 0, term.col-1);
2410         LIMIT(oldy, 0, term.row-1);
2411
2412         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2413                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2414
2415         /* remove the old cursor */
2416         if(term.line[oldy][oldx].state & GLYPH_SET) {
2417                 sl = utf8size(term.line[oldy][oldx].c);
2418                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2419                                 oldy, 1, sl);
2420         } else {
2421                 xtermclear(oldx, oldy, oldx, oldy);
2422         }
2423
2424         /* draw the new one */
2425         if(!(term.c.state & CURSOR_HIDE)) {
2426                 if(!(xw.state & WIN_FOCUSED))
2427                         g.bg = DefaultUCS;
2428
2429                 if(IS_SET(MODE_REVERSE))
2430                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2431
2432                 sl = utf8size(g.c);
2433                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2434                 oldx = term.c.x, oldy = term.c.y;
2435         }
2436 }
2437
2438 void
2439 xresettitle(void) {
2440         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2441 }
2442
2443 void
2444 redraw(void) {
2445         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2446
2447         tfulldirt();
2448         draw();
2449         XSync(xw.dpy, False); /* necessary for a good tput flash */
2450         nanosleep(&tv, NULL);
2451 }
2452
2453 void
2454 draw(void) {
2455         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2456
2457         drawregion(0, 0, term.col, term.row);
2458         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2459 }
2460
2461 void
2462 drawregion(int x1, int y1, int x2, int y2) {
2463         int ic, ib, x, y, ox, sl;
2464         Glyph base, new;
2465         char buf[DRAW_BUF_SIZ];
2466         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2467
2468         if((sel.alt && !alt) || (!sel.alt && alt))
2469                 ena_sel = 0;
2470         if(!(xw.state & WIN_VISIBLE))
2471                 return;
2472
2473         for(y = y1; y < y2; y++) {
2474                 if(!term.dirty[y])
2475                         continue;
2476
2477                 xtermclear(0, y, term.col, y);
2478                 term.dirty[y] = 0;
2479                 base = term.line[y][0];
2480                 ic = ib = ox = 0;
2481                 for(x = x1; x < x2; x++) {
2482                         new = term.line[y][x];
2483                         if(ena_sel && *(new.c) && selected(x, y))
2484                                 new.mode ^= ATTR_REVERSE;
2485                         if(ib > 0 && (!(new.state & GLYPH_SET)
2486                                         || ATTRCMP(base, new)
2487                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2488                                 xdraws(buf, base, ox, y, ic, ib);
2489                                 ic = ib = 0;
2490                         }
2491                         if(new.state & GLYPH_SET) {
2492                                 if(ib == 0) {
2493                                         ox = x;
2494                                         base = new;
2495                                 }
2496                                 sl = utf8size(new.c);
2497                                 memcpy(buf+ib, new.c, sl);
2498                                 ib += sl;
2499                                 ++ic;
2500                         }
2501                 }
2502                 if(ib > 0)
2503                         xdraws(buf, base, ox, y, ic, ib);
2504         }
2505         xdrawcursor();
2506 }
2507
2508 void
2509 expose(XEvent *ev) {
2510         XExposeEvent *e = &ev->xexpose;
2511
2512         if(xw.state & WIN_REDRAW) {
2513                 if(!e->count)
2514                         xw.state &= ~WIN_REDRAW;
2515         }
2516 }
2517
2518 void
2519 visibility(XEvent *ev) {
2520         XVisibilityEvent *e = &ev->xvisibility;
2521
2522         if(e->state == VisibilityFullyObscured) {
2523                 xw.state &= ~WIN_VISIBLE;
2524         } else if(!(xw.state & WIN_VISIBLE)) {
2525                 /* need a full redraw for next Expose, not just a buf copy */
2526                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2527         }
2528 }
2529
2530 void
2531 unmap(XEvent *ev) {
2532         xw.state &= ~WIN_VISIBLE;
2533 }
2534
2535 void
2536 xseturgency(int add) {
2537         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2538
2539         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2540         XSetWMHints(xw.dpy, xw.win, h);
2541         XFree(h);
2542 }
2543
2544 void
2545 focus(XEvent *ev) {
2546         if(ev->type == FocusIn) {
2547                 xw.state |= WIN_FOCUSED;
2548                 xseturgency(0);
2549         } else {
2550                 xw.state &= ~WIN_FOCUSED;
2551         }
2552 }
2553
2554 char*
2555 kmap(KeySym k, uint state) {
2556         int i;
2557         uint mask;
2558
2559         state &= ~Mod2Mask;
2560         for(i = 0; i < LEN(key); i++) {
2561                 mask = key[i].mask;
2562
2563                 if(key[i].k == k && ((state & mask) == mask
2564                                 || (mask == XK_NO_MOD && !state))) {
2565                         return (char*)key[i].s;
2566                 }
2567         }
2568         return NULL;
2569 }
2570
2571 void
2572 kpress(XEvent *ev) {
2573         XKeyEvent *e = &ev->xkey;
2574         KeySym ksym;
2575         char buf[32];
2576         char *customkey;
2577         int len;
2578         int meta;
2579         int shift;
2580         Status status;
2581
2582         if (IS_SET(MODE_KBDLOCK))
2583                 return;
2584
2585         meta = e->state & Mod1Mask;
2586         shift = e->state & ShiftMask;
2587         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2588
2589         /* 1. custom keys from config.h */
2590         if((customkey = kmap(ksym, e->state))) {
2591                 ttywrite(customkey, strlen(customkey));
2592         /* 2. hardcoded (overrides X lookup) */
2593         } else {
2594                 switch(ksym) {
2595                 case XK_Up:
2596                 case XK_Down:
2597                 case XK_Left:
2598                 case XK_Right:
2599                         /* XXX: shift up/down doesn't work */
2600                         sprintf(buf, "\033%c%c",
2601                                 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2602                                 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2603                         ttywrite(buf, 3);
2604                         break;
2605                 case XK_Insert:
2606                         if(shift)
2607                                 selpaste();
2608                         break;
2609                 case XK_Return:
2610                         if(IS_SET(MODE_CRLF)) {
2611                                 ttywrite("\r\n", 2);
2612                         } else {
2613                                 ttywrite("\r", 1);
2614                         }
2615                         break;
2616                         /* 3. X lookup  */
2617                 default:
2618                         if(len > 0) {
2619                                 if(meta && len == 1)
2620                                         ttywrite("\033", 1);
2621                                 ttywrite(buf, len);
2622                         }
2623                         break;
2624                 }
2625         }
2626 }
2627
2628 void
2629 cmessage(XEvent *e) {
2630         /* See xembed specs
2631            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2632         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2633                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2634                         xw.state |= WIN_FOCUSED;
2635                         xseturgency(0);
2636                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2637                         xw.state &= ~WIN_FOCUSED;
2638                 }
2639         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2640                 /* Send SIGHUP to shell */
2641                 kill(pid, SIGHUP);
2642                 exit(EXIT_SUCCESS);
2643         }
2644 }
2645
2646 void
2647 resize(XEvent *e) {
2648         int col, row;
2649
2650         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2651                 return;
2652
2653         xw.w = e->xconfigure.width;
2654         xw.h = e->xconfigure.height;
2655         col = (xw.w - 2*BORDER) / xw.cw;
2656         row = (xw.h - 2*BORDER) / xw.ch;
2657         if(col == term.col && row == term.row)
2658                 return;
2659
2660         tresize(col, row);
2661         xresize(col, row);
2662         ttyresize();
2663 }
2664
2665 void
2666 run(void) {
2667         XEvent ev;
2668         fd_set rfd;
2669         int xfd = XConnectionNumber(xw.dpy), i;
2670         struct timeval drawtimeout, *tv = NULL;
2671
2672         for(i = 0;; i++) {
2673                 FD_ZERO(&rfd);
2674                 FD_SET(cmdfd, &rfd);
2675                 FD_SET(xfd, &rfd);
2676                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2677                         if(errno == EINTR)
2678                                 continue;
2679                         die("select failed: %s\n", SERRNO);
2680                 }
2681
2682                 /*
2683                  * Stop after a certain number of reads so the user does not
2684                  * feel like the system is stuttering.
2685                  */
2686                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2687                         ttyread();
2688
2689                         /*
2690                          * Just wait a bit so it isn't disturbing the
2691                          * user and the system is able to write something.
2692                          */
2693                         drawtimeout.tv_sec = 0;
2694                         drawtimeout.tv_usec = 5;
2695                         tv = &drawtimeout;
2696                         continue;
2697                 }
2698                 i = 0;
2699                 tv = NULL;
2700
2701                 while(XPending(xw.dpy)) {
2702                         XNextEvent(xw.dpy, &ev);
2703                         if(XFilterEvent(&ev, xw.win))
2704                                 continue;
2705                         if(handler[ev.type])
2706                                 (handler[ev.type])(&ev);
2707                 }
2708
2709                 draw();
2710                 XFlush(xw.dpy);
2711         }
2712 }
2713
2714 int
2715 main(int argc, char *argv[]) {
2716         int i, bitm, xr, yr;
2717         uint wr, hr;
2718
2719         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2720         xw.isfixed = False;
2721
2722         for(i = 1; i < argc; i++) {
2723                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2724                 case 'c':
2725                         if(++i < argc)
2726                                 opt_class = argv[i];
2727                         break;
2728                 case 'e':
2729                         /* eat every remaining arguments */
2730                         if(++i < argc)
2731                                 opt_cmd = &argv[i];
2732                         goto run;
2733                 case 'f':
2734                         if(++i < argc)
2735                                 opt_font = argv[i];
2736                         break;
2737                 case 'g':
2738                         if(++i >= argc)
2739                                 break;
2740
2741                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2742                         if(bitm & XValue)
2743                                 xw.fx = xr;
2744                         if(bitm & YValue)
2745                                 xw.fy = yr;
2746                         if(bitm & WidthValue)
2747                                 xw.fw = (int)wr;
2748                         if(bitm & HeightValue)
2749                                 xw.fh = (int)hr;
2750                         if(bitm & XNegative && xw.fx == 0)
2751                                 xw.fx = -1;
2752                         if(bitm & XNegative && xw.fy == 0)
2753                                 xw.fy = -1;
2754
2755                         if(xw.fh != 0 && xw.fw != 0)
2756                                 xw.isfixed = True;
2757                         break;
2758                 case 'o':
2759                         if(++i < argc)
2760                                 opt_io = argv[i];
2761                         break;
2762                 case 't':
2763                         if(++i < argc)
2764                                 opt_title = argv[i];
2765                         break;
2766                 case 'v':
2767                 default:
2768                         die(USAGE);
2769                 case 'w':
2770                         if(++i < argc)
2771                                 opt_embed = argv[i];
2772                         break;
2773                 }
2774         }
2775
2776 run:
2777         setlocale(LC_CTYPE, "");
2778         tnew(80, 24);
2779         ttynew();
2780         xinit();
2781         selinit();
2782         run();
2783         return 0;
2784 }
2785