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