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