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