JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Selection snapping is now considering wrapping.
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.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/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
29
30 #include "arg.h"
31
32 char *argv0;
33
34 #define Glyph Glyph_
35 #define Font Font_
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
39 #define Rectangle XRectangle
40
41 #if   defined(__linux)
42  #include <pty.h>
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
44  #include <util.h>
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
46  #include <libutil.h>
47 #endif
48
49
50 /* XEMBED messages */
51 #define XEMBED_FOCUS_IN  4
52 #define XEMBED_FOCUS_OUT 5
53
54 /* Arbitrary sizes */
55 #define UTF_SIZ       4
56 #define ESC_BUF_SIZ   (128*UTF_SIZ)
57 #define ESC_ARG_SIZ   16
58 #define STR_BUF_SIZ   ESC_BUF_SIZ
59 #define STR_ARG_SIZ   ESC_ARG_SIZ
60 #define DRAW_BUF_SIZ  20*1024
61 #define XK_ANY_MOD    UINT_MAX
62 #define XK_NO_MOD     0
63 #define XK_SWITCH_MOD (1<<13)
64
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
66
67 /* macros */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
70 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
71 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
78
79 #define VT102ID "\033[?6c"
80
81 enum glyph_attribute {
82         ATTR_NULL      = 0,
83         ATTR_REVERSE   = 1,
84         ATTR_UNDERLINE = 2,
85         ATTR_BOLD      = 4,
86         ATTR_GFX       = 8,
87         ATTR_ITALIC    = 16,
88         ATTR_BLINK     = 32,
89         ATTR_WRAP      = 64,
90 };
91
92 enum cursor_movement {
93         CURSOR_SAVE,
94         CURSOR_LOAD
95 };
96
97 enum cursor_state {
98         CURSOR_DEFAULT  = 0,
99         CURSOR_WRAPNEXT = 1,
100         CURSOR_ORIGIN   = 2
101 };
102
103 enum term_mode {
104         MODE_WRAP        = 1,
105         MODE_INSERT      = 2,
106         MODE_APPKEYPAD   = 4,
107         MODE_ALTSCREEN   = 8,
108         MODE_CRLF        = 16,
109         MODE_MOUSEBTN    = 32,
110         MODE_MOUSEMOTION = 64,
111         MODE_MOUSE       = 32|64,
112         MODE_REVERSE     = 128,
113         MODE_KBDLOCK     = 256,
114         MODE_HIDE        = 512,
115         MODE_ECHO        = 1024,
116         MODE_APPCURSOR   = 2048,
117         MODE_MOUSESGR    = 4096,
118         MODE_8BIT        = 8192,
119         MODE_BLINK       = 16384,
120         MODE_FBLINK      = 32768,
121 };
122
123 enum escape_state {
124         ESC_START      = 1,
125         ESC_CSI = 2,
126         ESC_STR = 4, /* DSC, OSC, PM, APC */
127         ESC_ALTCHARSET = 8,
128         ESC_STR_END    = 16, /* a final string was encountered */
129         ESC_TEST       = 32, /* Enter in test mode */
130 };
131
132 enum window_state {
133         WIN_VISIBLE = 1,
134         WIN_REDRAW  = 2,
135         WIN_FOCUSED = 4
136 };
137
138 enum selection_type {
139         SEL_REGULAR = 1,
140         SEL_RECTANGULAR = 2
141 };
142
143 enum selection_snap {
144         SNAP_WORD = 1,
145         SNAP_LINE = 2
146 };
147
148 /* bit macro */
149 #undef B0
150 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
151
152 typedef unsigned char uchar;
153 typedef unsigned int uint;
154 typedef unsigned long ulong;
155 typedef unsigned short ushort;
156
157 typedef struct {
158         char c[UTF_SIZ];     /* character code */
159         uchar mode;  /* attribute flags */
160         ushort fg;   /* foreground  */
161         ushort bg;   /* background  */
162 } Glyph;
163
164 typedef Glyph *Line;
165
166 typedef struct {
167         Glyph attr;      /* current char attributes */
168         int x;
169         int y;
170         char state;
171 } TCursor;
172
173 /* CSI Escape sequence structs */
174 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
175 typedef struct {
176         char buf[ESC_BUF_SIZ]; /* raw string */
177         int len;               /* raw string length */
178         char priv;
179         int arg[ESC_ARG_SIZ];
180         int narg;              /* nb of args */
181         char mode;
182 } CSIEscape;
183
184 /* STR Escape sequence structs */
185 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
186 typedef struct {
187         char type;           /* ESC type ... */
188         char buf[STR_BUF_SIZ]; /* raw string */
189         int len;               /* raw string length */
190         char *args[STR_ARG_SIZ];
191         int narg;             /* nb of args */
192 } STREscape;
193
194 /* Internal representation of the screen */
195 typedef struct {
196         int row;        /* nb row */
197         int col;        /* nb col */
198         Line *line;     /* screen */
199         Line *alt;      /* alternate screen */
200         bool *dirty;    /* dirtyness of lines */
201         TCursor c;      /* cursor */
202         int top;        /* top    scroll limit */
203         int bot;        /* bottom scroll limit */
204         int mode;       /* terminal mode flags */
205         int esc;        /* escape state flags */
206         bool numlock;   /* lock numbers in keyboard */
207         bool *tabs;
208 } Term;
209
210 /* Purely graphic info */
211 typedef struct {
212         Display *dpy;
213         Colourmap cmap;
214         Window win;
215         Drawable buf;
216         Atom xembed, wmdeletewin;
217         XIM xim;
218         XIC xic;
219         Draw draw;
220         Visual *vis;
221         int scr;
222         bool isfixed; /* is fixed geometry? */
223         int fx, fy, fw, fh; /* fixed geometry */
224         int tw, th; /* tty width and height */
225         int w, h; /* window width and height */
226         int ch; /* char height */
227         int cw; /* char width  */
228         char state; /* focus, redraw, visible */
229 } XWindow;
230
231 typedef struct {
232         int b;
233         uint mask;
234         char s[ESC_BUF_SIZ];
235 } Mousekey;
236
237 typedef struct {
238         KeySym k;
239         uint mask;
240         char s[ESC_BUF_SIZ];
241         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
242         signed char appkey;             /* application keypad */
243         signed char appcursor;          /* application cursor */
244         signed char crlf;               /* crlf mode          */
245 } Key;
246
247 /* TODO: use better name for vars... */
248 typedef struct {
249         int mode;
250         int type;
251         int snap;
252         int bx, by;
253         int ex, ey;
254         struct {
255                 int x, y;
256         } b, e;
257         char *clip;
258         Atom xtarget;
259         bool alt;
260         struct timeval tclick1;
261         struct timeval tclick2;
262 } Selection;
263
264 typedef union {
265         int i;
266         unsigned int ui;
267         float f;
268         const void *v;
269 } Arg;
270
271 typedef struct {
272         unsigned int mod;
273         KeySym keysym;
274         void (*func)(const Arg *);
275         const Arg arg;
276 } Shortcut;
277
278 /* function definitions used in config.h */
279 static void clippaste(const Arg *);
280 static void numlock(const Arg *);
281 static void selpaste(const Arg *);
282 static void xzoom(const Arg *);
283
284 /* Config.h for applying patches and the configuration. */
285 #include "config.h"
286
287 /* Font structure */
288 typedef struct {
289         int height;
290         int width;
291         int ascent;
292         int descent;
293         short lbearing;
294         short rbearing;
295         XftFont *match;
296         FcFontSet *set;
297         FcPattern *pattern;
298 } Font;
299
300 /* Drawing Context */
301 typedef struct {
302         Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
303         Font font, bfont, ifont, ibfont;
304         GC gc;
305 } DC;
306
307 static void die(const char *, ...);
308 static void draw(void);
309 static void redraw(int);
310 static void drawregion(int, int, int, int);
311 static void execsh(void);
312 static void sigchld(int);
313 static void run(void);
314
315 static void csidump(void);
316 static void csihandle(void);
317 static void csiparse(void);
318 static void csireset(void);
319 static void strdump(void);
320 static void strhandle(void);
321 static void strparse(void);
322 static void strreset(void);
323
324 static int tattrset(int);
325 static void tclearregion(int, int, int, int);
326 static void tcursor(int);
327 static void tdeletechar(int);
328 static void tdeleteline(int);
329 static void tinsertblank(int);
330 static void tinsertblankline(int);
331 static void tmoveto(int, int);
332 static void tmoveato(int x, int y);
333 static void tnew(int, int);
334 static void tnewline(int);
335 static void tputtab(bool);
336 static void tputc(char *, int);
337 static void treset(void);
338 static int tresize(int, int);
339 static void tscrollup(int, int);
340 static void tscrolldown(int, int);
341 static void tsetattr(int*, int);
342 static void tsetchar(char *, Glyph *, int, int);
343 static void tsetscroll(int, int);
344 static void tswapscreen(void);
345 static void tsetdirt(int, int);
346 static void tsetdirtattr(int);
347 static void tsetmode(bool, bool, int *, int);
348 static void tfulldirt(void);
349 static void techo(char *, int);
350
351 static inline bool match(uint, uint);
352 static void ttynew(void);
353 static void ttyread(void);
354 static void ttyresize(void);
355 static void ttywrite(const char *, size_t);
356
357 static void xdraws(char *, Glyph, int, int, int, int);
358 static void xhints(void);
359 static void xclear(int, int, int, int);
360 static void xdrawcursor(void);
361 static void xinit(void);
362 static void xloadcols(void);
363 static int xsetcolorname(int, const char *);
364 static int xloadfont(Font *, FcPattern *);
365 static void xloadfonts(char *, int);
366 static void xsettitle(char *);
367 static void xresettitle(void);
368 static void xseturgency(int);
369 static void xsetsel(char*);
370 static void xtermclear(int, int, int, int);
371 static void xunloadfonts(void);
372 static void xresize(int, int);
373
374 static void expose(XEvent *);
375 static void visibility(XEvent *);
376 static void unmap(XEvent *);
377 static char *kmap(KeySym, uint);
378 static void kpress(XEvent *);
379 static void cmessage(XEvent *);
380 static void cresize(int, int);
381 static void resize(XEvent *);
382 static void focus(XEvent *);
383 static void brelease(XEvent *);
384 static void bpress(XEvent *);
385 static void bmotion(XEvent *);
386 static void selnotify(XEvent *);
387 static void selclear(XEvent *);
388 static void selrequest(XEvent *);
389
390 static void selinit(void);
391 static inline bool selected(int, int);
392 static void selcopy(void);
393 static void selscroll(int, int);
394 static void selsnap(int, int *, int *, int);
395
396 static int utf8decode(char *, long *);
397 static int utf8encode(long *, char *);
398 static int utf8size(char *);
399 static int isfullutf8(char *, int);
400
401 static ssize_t xwrite(int, char *, size_t);
402 static void *xmalloc(size_t);
403 static void *xrealloc(void *, size_t);
404 static void *xcalloc(size_t, size_t);
405
406 static void (*handler[LASTEvent])(XEvent *) = {
407         [KeyPress] = kpress,
408         [ClientMessage] = cmessage,
409         [ConfigureNotify] = resize,
410         [VisibilityNotify] = visibility,
411         [UnmapNotify] = unmap,
412         [Expose] = expose,
413         [FocusIn] = focus,
414         [FocusOut] = focus,
415         [MotionNotify] = bmotion,
416         [ButtonPress] = bpress,
417         [ButtonRelease] = brelease,
418         [SelectionClear] = selclear,
419         [SelectionNotify] = selnotify,
420         [SelectionRequest] = selrequest,
421 };
422
423 /* Globals */
424 static DC dc;
425 static XWindow xw;
426 static Term term;
427 static CSIEscape csiescseq;
428 static STREscape strescseq;
429 static int cmdfd;
430 static pid_t pid;
431 static Selection sel;
432 static int iofd = -1;
433 static char **opt_cmd = NULL;
434 static char *opt_io = NULL;
435 static char *opt_title = NULL;
436 static char *opt_embed = NULL;
437 static char *opt_class = NULL;
438 static char *opt_font = NULL;
439
440 static char *usedfont = NULL;
441 static int usedfontsize = 0;
442
443 /* Font Ring Cache */
444 enum {
445         FRC_NORMAL,
446         FRC_ITALIC,
447         FRC_BOLD,
448         FRC_ITALICBOLD
449 };
450
451 typedef struct {
452         XftFont *font;
453         long c;
454         int flags;
455 } Fontcache;
456
457 /*
458  * Fontcache is a ring buffer, with frccur as current position and frclen as
459  * the current length of used elements.
460  */
461
462 static Fontcache frc[1024];
463 static int frccur = -1, frclen = 0;
464
465 ssize_t
466 xwrite(int fd, char *s, size_t len) {
467         size_t aux = len;
468
469         while(len > 0) {
470                 ssize_t r = write(fd, s, len);
471                 if(r < 0)
472                         return r;
473                 len -= r;
474                 s += r;
475         }
476         return aux;
477 }
478
479 void *
480 xmalloc(size_t len) {
481         void *p = malloc(len);
482
483         if(!p)
484                 die("Out of memory\n");
485
486         return p;
487 }
488
489 void *
490 xrealloc(void *p, size_t len) {
491         if((p = realloc(p, len)) == NULL)
492                 die("Out of memory\n");
493
494         return p;
495 }
496
497 void *
498 xcalloc(size_t nmemb, size_t size) {
499         void *p = calloc(nmemb, size);
500
501         if(!p)
502                 die("Out of memory\n");
503
504         return p;
505 }
506
507 int
508 utf8decode(char *s, long *u) {
509         uchar c;
510         int i, n, rtn;
511
512         rtn = 1;
513         c = *s;
514         if(~c & B7) { /* 0xxxxxxx */
515                 *u = c;
516                 return rtn;
517         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
518                 *u = c&(B4|B3|B2|B1|B0);
519                 n = 1;
520         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
521                 *u = c&(B3|B2|B1|B0);
522                 n = 2;
523         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
524                 *u = c & (B2|B1|B0);
525                 n = 3;
526         } else {
527                 goto invalid;
528         }
529
530         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
531                 c = *s;
532                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
533                         goto invalid;
534                 *u <<= 6;
535                 *u |= c & (B5|B4|B3|B2|B1|B0);
536         }
537
538         if((n == 1 && *u < 0x80) ||
539            (n == 2 && *u < 0x800) ||
540            (n == 3 && *u < 0x10000) ||
541            (*u >= 0xD800 && *u <= 0xDFFF)) {
542                 goto invalid;
543         }
544
545         return rtn;
546 invalid:
547         *u = 0xFFFD;
548
549         return rtn;
550 }
551
552 int
553 utf8encode(long *u, char *s) {
554         uchar *sp;
555         ulong uc;
556         int i, n;
557
558         sp = (uchar *)s;
559         uc = *u;
560         if(uc < 0x80) {
561                 *sp = uc; /* 0xxxxxxx */
562                 return 1;
563         } else if(*u < 0x800) {
564                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
565                 n = 1;
566         } else if(uc < 0x10000) {
567                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
568                 n = 2;
569         } else if(uc <= 0x10FFFF) {
570                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
571                 n = 3;
572         } else {
573                 goto invalid;
574         }
575
576         for(i=n,++sp; i>0; --i,++sp)
577                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
578
579         return n+1;
580 invalid:
581         /* U+FFFD */
582         *s++ = '\xEF';
583         *s++ = '\xBF';
584         *s = '\xBD';
585
586         return 3;
587 }
588
589 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
590    UTF-8 otherwise return 0 */
591 int
592 isfullutf8(char *s, int b) {
593         uchar *c1, *c2, *c3;
594
595         c1 = (uchar *)s;
596         c2 = (uchar *)++s;
597         c3 = (uchar *)++s;
598         if(b < 1) {
599                 return 0;
600         } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
601                 return 0;
602         } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
603             ((b == 1) ||
604             ((b == 2) && (*c2&(B7|B6)) == B7))) {
605                 return 0;
606         } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
607             ((b == 1) ||
608             ((b == 2) && (*c2&(B7|B6)) == B7) ||
609             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
610                 return 0;
611         } else {
612                 return 1;
613         }
614 }
615
616 int
617 utf8size(char *s) {
618         uchar c = *s;
619
620         if(~c&B7) {
621                 return 1;
622         } else if((c&(B7|B6|B5)) == (B7|B6)) {
623                 return 2;
624         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
625                 return 3;
626         } else {
627                 return 4;
628         }
629 }
630
631 void
632 selinit(void) {
633         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
634         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
635         sel.mode = 0;
636         sel.bx = -1;
637         sel.clip = NULL;
638         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
639         if(sel.xtarget == None)
640                 sel.xtarget = XA_STRING;
641 }
642
643 static int
644 x2col(int x) {
645         x -= borderpx;
646         x /= xw.cw;
647
648         return LIMIT(x, 0, term.col-1);
649 }
650
651 static int
652 y2row(int y) {
653         y -= borderpx;
654         y /= xw.ch;
655
656         return LIMIT(y, 0, term.row-1);
657 }
658
659 static inline bool
660 selected(int x, int y) {
661         int bx, ex;
662
663         if(sel.ey == y && sel.by == y) {
664                 bx = MIN(sel.bx, sel.ex);
665                 ex = MAX(sel.bx, sel.ex);
666
667                 return BETWEEN(x, bx, ex);
668         }
669
670         if(sel.type == SEL_RECTANGULAR) {
671                 return ((sel.b.y <= y && y <= sel.e.y)
672                         && (sel.b.x <= x && x <= sel.e.x));
673         }
674         return ((sel.b.y < y && y < sel.e.y)
675                 || (y == sel.e.y && x <= sel.e.x))
676                 || (y == sel.b.y && x >= sel.b.x
677                         && (x <= sel.e.x || sel.b.y != sel.e.y));
678 }
679
680 void
681 selsnap(int mode, int *x, int *y, int direction) {
682         switch(mode) {
683         case SNAP_WORD:
684                 for(;;) {
685                         if(direction < 0 && *x <= 0) {
686                                 if(*y > 0 && term.line[*y - 1][term.col-1].mode
687                                                 & ATTR_WRAP) {
688                                         *y -= 1;
689                                         *x = term.col-1;
690                                 } else {
691                                         break;
692                                 }
693                         }
694                         if(direction > 0 && *x >= term.col-1) {
695                                 if(*y < term.row-1 && term.line[*y][*x].mode
696                                                 & ATTR_WRAP) {
697                                         *y += 1;
698                                         *x = 0;
699                                 } else {
700                                         break;
701                                 }
702                         }
703
704                         if(term.line[*y][*x + direction].c[0] == ' ')
705                                 break;
706
707                         *x += direction;
708                 }
709                 break;
710         case SNAP_LINE:
711                 *x = (direction < 0) ? 0 : term.col - 1;
712                 if(direction < 0 && *y > 0) {
713                         for(; *y > 0; *y += direction) {
714                                 if(!(term.line[*y-1][term.col-1].mode
715                                                 & ATTR_WRAP)) {
716                                         break;
717                                 }
718                         }
719                 } else if(direction > 0 && *y < term.row-1) {
720                         for(; *y < term.row; *y += direction) {
721                                 if(!(term.line[*y][term.col-1].mode
722                                                 & ATTR_WRAP)) {
723                                         break;
724                                 }
725                         }
726                 }
727                 break;
728         default:
729                 break;
730         }
731 }
732
733 void
734 getbuttoninfo(XEvent *e) {
735         int type;
736         uint state = e->xbutton.state &~Button1Mask;
737
738         sel.alt = IS_SET(MODE_ALTSCREEN);
739
740         sel.ex = x2col(e->xbutton.x);
741         sel.ey = y2row(e->xbutton.y);
742
743         if (sel.by < sel.ey
744                         || (sel.by == sel.ey && sel.bx < sel.ex)) {
745                 selsnap(sel.snap, &sel.bx, &sel.by, -1);
746                 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
747         } else {
748                 selsnap(sel.snap, &sel.ex, &sel.ey, -1);
749                 selsnap(sel.snap, &sel.bx, &sel.by, +1);
750         }
751
752         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
753         sel.b.y = MIN(sel.by, sel.ey);
754         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
755         sel.e.y = MAX(sel.by, sel.ey);
756
757         sel.type = SEL_REGULAR;
758         for(type = 1; type < LEN(selmasks); ++type) {
759                 if(match(selmasks[type], state)) {
760                         sel.type = type;
761                         break;
762                 }
763         }
764 }
765
766 void
767 mousereport(XEvent *e) {
768         int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
769             button = e->xbutton.button, state = e->xbutton.state,
770             len;
771         char buf[40];
772         static int ob, ox, oy;
773
774         /* from urxvt */
775         if(e->xbutton.type == MotionNotify) {
776                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
777                         return;
778                 button = ob + 32;
779                 ox = x, oy = y;
780         } else if(!IS_SET(MODE_MOUSESGR)
781                         && (e->xbutton.type == ButtonRelease
782                                 || button == AnyButton)) {
783                 button = 3;
784         } else {
785                 button -= Button1;
786                 if(button >= 3)
787                         button += 64 - 3;
788                 if(e->xbutton.type == ButtonPress) {
789                         ob = button;
790                         ox = x, oy = y;
791                 }
792         }
793
794         button += (state & ShiftMask   ? 4  : 0)
795                 + (state & Mod4Mask    ? 8  : 0)
796                 + (state & ControlMask ? 16 : 0);
797
798         len = 0;
799         if(IS_SET(MODE_MOUSESGR)) {
800                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
801                                 button, x+1, y+1,
802                                 e->xbutton.type == ButtonRelease ? 'm' : 'M');
803         } else if(x < 223 && y < 223) {
804                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
805                                 32+button, 32+x+1, 32+y+1);
806         } else {
807                 return;
808         }
809
810         ttywrite(buf, len);
811 }
812
813 void
814 bpress(XEvent *e) {
815         struct timeval now;
816         Mousekey *mk;
817
818         if(IS_SET(MODE_MOUSE)) {
819                 mousereport(e);
820                 return;
821         }
822
823         for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
824                 if(e->xbutton.button == mk->b
825                                 && match(mk->mask, e->xbutton.state)) {
826                         ttywrite(mk->s, strlen(mk->s));
827                         if(IS_SET(MODE_ECHO))
828                                 techo(mk->s, strlen(mk->s));
829                         return;
830                 }
831         }
832
833         if(e->xbutton.button == Button1) {
834                 gettimeofday(&now, NULL);
835
836                 /* Clear previous selection, logically and visually. */
837                 if(sel.bx != -1) {
838                         sel.bx = -1;
839                         tsetdirt(sel.b.y, sel.e.y);
840                         draw();
841                 }
842                 sel.mode = 1;
843                 sel.type = SEL_REGULAR;
844                 sel.ex = sel.bx = x2col(e->xbutton.x);
845                 sel.ey = sel.by = y2row(e->xbutton.y);
846
847                 /*
848                  * If the user clicks below predefined timeouts specific
849                  * snapping behaviour is exposed.
850                  */
851                 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
852                         sel.snap = SNAP_LINE;
853                 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
854                         sel.snap = SNAP_WORD;
855                 } else {
856                         sel.snap = 0;
857                 }
858                 selsnap(sel.snap, &sel.bx, &sel.by, -1);
859                 selsnap(sel.snap, &sel.ex, &sel.ey, +1);
860                 sel.b.x = sel.bx;
861                 sel.b.y = sel.by;
862                 sel.e.x = sel.ex;
863                 sel.e.y = sel.ey;
864
865                 /*
866                  * Draw selection, unless it's regular and we don't want to
867                  * make clicks visible
868                  */
869                 if(sel.snap != 0) {
870                         sel.mode++;
871                         tsetdirt(sel.b.y, sel.e.y);
872                         draw();
873                 }
874                 sel.tclick2 = sel.tclick1;
875                 sel.tclick1 = now;
876         }
877 }
878
879 void
880 selcopy(void) {
881         char *str, *ptr;
882         int x, y, bufsize, size;
883         Glyph *gp, *last;
884
885         if(sel.bx == -1) {
886                 str = NULL;
887         } else {
888                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
889                 ptr = str = xmalloc(bufsize);
890
891                 /* append every set & selected glyph to the selection */
892                 for(y = sel.b.y; y < sel.e.y + 1; y++) {
893                         gp = &term.line[y][0];
894                         last = gp + term.col;
895
896                         while(--last >= gp && !(selected(last - gp, y) && \
897                                                 strcmp(last->c, " ") != 0))
898                                 /* nothing */;
899
900                         for(x = 0; gp <= last; x++, ++gp) {
901                                 if(!selected(x, y))
902                                         continue;
903
904                                 size = utf8size(gp->c);
905                                 memcpy(ptr, gp->c, size);
906                                 ptr += size;
907                         }
908
909                         /*
910                          * Copy and pasting of line endings is inconsistent
911                          * in the inconsistent terminal and GUI world.
912                          * The best solution seems like to produce '\n' when
913                          * something is copied from st and convert '\n' to
914                          * '\r', when something to be pasted is received by
915                          * st.
916                          * FIXME: Fix the computer world.
917                          */
918                         if(y < sel.e.y && !((gp-1)->mode & ATTR_WRAP))
919                                 *ptr++ = '\n';
920                 }
921                 *ptr = 0;
922         }
923         xsetsel(str);
924 }
925
926 void
927 selnotify(XEvent *e) {
928         ulong nitems, ofs, rem;
929         int format;
930         uchar *data, *last, *repl;
931         Atom type;
932
933         ofs = 0;
934         do {
935                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
936                                         False, AnyPropertyType, &type, &format,
937                                         &nitems, &rem, &data)) {
938                         fprintf(stderr, "Clipboard allocation failed\n");
939                         return;
940                 }
941
942                 /*
943                  * As seen in selcopy:
944                  * Line endings are inconsistent in the terminal and GUI world
945                  * copy and pasting. When receiving some selection data,
946                  * replace all '\n' with '\r'.
947                  * FIXME: Fix the computer world.
948                  */
949                 repl = data;
950                 last = data + nitems * format / 8;
951                 while((repl = memchr(repl, '\n', last - repl))) {
952                         *repl++ = '\r';
953                 }
954
955                 ttywrite((const char *)data, nitems * format / 8);
956                 XFree(data);
957                 /* number of 32-bit chunks returned */
958                 ofs += nitems * format / 32;
959         } while(rem > 0);
960 }
961
962 void
963 selpaste(const Arg *dummy) {
964         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
965                         xw.win, CurrentTime);
966 }
967
968 void
969 clippaste(const Arg *dummy) {
970         Atom clipboard;
971
972         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
973         XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
974                         xw.win, CurrentTime);
975 }
976
977 void
978 selclear(XEvent *e) {
979         if(sel.bx == -1)
980                 return;
981         sel.bx = -1;
982         tsetdirt(sel.b.y, sel.e.y);
983 }
984
985 void
986 selrequest(XEvent *e) {
987         XSelectionRequestEvent *xsre;
988         XSelectionEvent xev;
989         Atom xa_targets, string;
990
991         xsre = (XSelectionRequestEvent *) e;
992         xev.type = SelectionNotify;
993         xev.requestor = xsre->requestor;
994         xev.selection = xsre->selection;
995         xev.target = xsre->target;
996         xev.time = xsre->time;
997         /* reject */
998         xev.property = None;
999
1000         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1001         if(xsre->target == xa_targets) {
1002                 /* respond with the supported type */
1003                 string = sel.xtarget;
1004                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1005                                 XA_ATOM, 32, PropModeReplace,
1006                                 (uchar *) &string, 1);
1007                 xev.property = xsre->property;
1008         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1009                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1010                                 xsre->target, 8, PropModeReplace,
1011                                 (uchar *) sel.clip, strlen(sel.clip));
1012                 xev.property = xsre->property;
1013         }
1014
1015         /* all done, send a notification to the listener */
1016         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1017                 fprintf(stderr, "Error sending SelectionNotify event\n");
1018 }
1019
1020 void
1021 xsetsel(char *str) {
1022         /* register the selection for both the clipboard and the primary */
1023         Atom clipboard;
1024
1025         free(sel.clip);
1026         sel.clip = str;
1027
1028         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1029
1030         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1031         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1032 }
1033
1034 void
1035 brelease(XEvent *e) {
1036         if(IS_SET(MODE_MOUSE)) {
1037                 mousereport(e);
1038                 return;
1039         }
1040
1041         if(e->xbutton.button == Button2) {
1042                 selpaste(NULL);
1043         } else if(e->xbutton.button == Button1) {
1044                 if(sel.mode < 2) {
1045                         sel.bx = -1;
1046                 } else {
1047                         getbuttoninfo(e);
1048                         selcopy();
1049                 }
1050                 sel.mode = 0;
1051                 term.dirty[sel.ey] = 1;
1052         }
1053 }
1054
1055 void
1056 bmotion(XEvent *e) {
1057         int oldey, oldex, oldsby, oldsey;
1058
1059         if(IS_SET(MODE_MOUSE)) {
1060                 mousereport(e);
1061                 return;
1062         }
1063
1064         if(!sel.mode)
1065                 return;
1066
1067         sel.mode++;
1068         oldey = sel.ey;
1069         oldex = sel.ex;
1070         oldsby = sel.b.y;
1071         oldsey = sel.e.y;
1072         getbuttoninfo(e);
1073
1074         if(oldey != sel.ey || oldex != sel.ex) {
1075                 tsetdirt(MIN(sel.b.y, oldsby), MAX(sel.e.y, oldsey));
1076         }
1077 }
1078
1079 void
1080 die(const char *errstr, ...) {
1081         va_list ap;
1082
1083         va_start(ap, errstr);
1084         vfprintf(stderr, errstr, ap);
1085         va_end(ap);
1086         exit(EXIT_FAILURE);
1087 }
1088
1089 void
1090 execsh(void) {
1091         char **args;
1092         char *envshell = getenv("SHELL");
1093         const struct passwd *pass = getpwuid(getuid());
1094         char buf[sizeof(long) * 8 + 1];
1095
1096         unsetenv("COLUMNS");
1097         unsetenv("LINES");
1098         unsetenv("TERMCAP");
1099
1100         if(pass) {
1101                 setenv("LOGNAME", pass->pw_name, 1);
1102                 setenv("USER", pass->pw_name, 1);
1103                 setenv("SHELL", pass->pw_shell, 0);
1104                 setenv("HOME", pass->pw_dir, 0);
1105         }
1106
1107         snprintf(buf, sizeof(buf), "%lu", xw.win);
1108         setenv("WINDOWID", buf, 1);
1109
1110         signal(SIGCHLD, SIG_DFL);
1111         signal(SIGHUP, SIG_DFL);
1112         signal(SIGINT, SIG_DFL);
1113         signal(SIGQUIT, SIG_DFL);
1114         signal(SIGTERM, SIG_DFL);
1115         signal(SIGALRM, SIG_DFL);
1116
1117         DEFAULT(envshell, shell);
1118         setenv("TERM", termname, 1);
1119         args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1120         execvp(args[0], args);
1121         exit(EXIT_FAILURE);
1122 }
1123
1124 void
1125 sigchld(int a) {
1126         int stat = 0;
1127
1128         if(waitpid(pid, &stat, 0) < 0)
1129                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1130
1131         if(WIFEXITED(stat)) {
1132                 exit(WEXITSTATUS(stat));
1133         } else {
1134                 exit(EXIT_FAILURE);
1135         }
1136 }
1137
1138 void
1139 ttynew(void) {
1140         int m, s;
1141         struct winsize w = {term.row, term.col, 0, 0};
1142
1143         /* seems to work fine on linux, openbsd and freebsd */
1144         if(openpty(&m, &s, NULL, NULL, &w) < 0)
1145                 die("openpty failed: %s\n", SERRNO);
1146
1147         switch(pid = fork()) {
1148         case -1:
1149                 die("fork failed\n");
1150                 break;
1151         case 0:
1152                 setsid(); /* create a new process group */
1153                 dup2(s, STDIN_FILENO);
1154                 dup2(s, STDOUT_FILENO);
1155                 dup2(s, STDERR_FILENO);
1156                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1157                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1158                 close(s);
1159                 close(m);
1160                 execsh();
1161                 break;
1162         default:
1163                 close(s);
1164                 cmdfd = m;
1165                 signal(SIGCHLD, sigchld);
1166                 if(opt_io) {
1167                         iofd = (!strcmp(opt_io, "-")) ?
1168                                   STDOUT_FILENO :
1169                                   open(opt_io, O_WRONLY | O_CREAT, 0666);
1170                         if(iofd < 0) {
1171                                 fprintf(stderr, "Error opening %s:%s\n",
1172                                         opt_io, strerror(errno));
1173                         }
1174                 }
1175         }
1176 }
1177
1178 void
1179 dump(char c) {
1180         static int col;
1181
1182         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1183         if(++col % 10 == 0)
1184                 fprintf(stderr, "\n");
1185 }
1186
1187 void
1188 ttyread(void) {
1189         static char buf[BUFSIZ];
1190         static int buflen = 0;
1191         char *ptr;
1192         char s[UTF_SIZ];
1193         int charsize; /* size of utf8 char in bytes */
1194         long utf8c;
1195         int ret;
1196
1197         /* append read bytes to unprocessed bytes */
1198         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1199                 die("Couldn't read from shell: %s\n", SERRNO);
1200
1201         /* process every complete utf8 char */
1202         buflen += ret;
1203         ptr = buf;
1204         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1205                 charsize = utf8decode(ptr, &utf8c);
1206                 utf8encode(&utf8c, s);
1207                 tputc(s, charsize);
1208                 ptr += charsize;
1209                 buflen -= charsize;
1210         }
1211
1212         /* keep any uncomplete utf8 char for the next call */
1213         memmove(buf, ptr, buflen);
1214 }
1215
1216 void
1217 ttywrite(const char *s, size_t n) {
1218         if(write(cmdfd, s, n) == -1)
1219                 die("write error on tty: %s\n", SERRNO);
1220 }
1221
1222 void
1223 ttyresize(void) {
1224         struct winsize w;
1225
1226         w.ws_row = term.row;
1227         w.ws_col = term.col;
1228         w.ws_xpixel = xw.tw;
1229         w.ws_ypixel = xw.th;
1230         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1231                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1232 }
1233
1234 int
1235 tattrset(int attr) {
1236         int i, j;
1237
1238         for(i = 0; i < term.row-1; i++) {
1239                 for(j = 0; j < term.col-1; j++) {
1240                         if(term.line[i][j].mode & attr)
1241                                 return 1;
1242                 }
1243         }
1244
1245         return 0;
1246 }
1247
1248 void
1249 tsetdirt(int top, int bot) {
1250         int i;
1251
1252         LIMIT(top, 0, term.row-1);
1253         LIMIT(bot, 0, term.row-1);
1254
1255         for(i = top; i <= bot; i++)
1256                 term.dirty[i] = 1;
1257 }
1258
1259 void
1260 tsetdirtattr(int attr) {
1261         int i, j;
1262
1263         for(i = 0; i < term.row-1; i++) {
1264                 for(j = 0; j < term.col-1; j++) {
1265                         if(term.line[i][j].mode & attr) {
1266                                 tsetdirt(i, i);
1267                                 break;
1268                         }
1269                 }
1270         }
1271 }
1272
1273 void
1274 tfulldirt(void) {
1275         tsetdirt(0, term.row-1);
1276 }
1277
1278 void
1279 tcursor(int mode) {
1280         static TCursor c;
1281
1282         if(mode == CURSOR_SAVE) {
1283                 c = term.c;
1284         } else if(mode == CURSOR_LOAD) {
1285                 term.c = c;
1286                 tmoveto(c.x, c.y);
1287         }
1288 }
1289
1290 void
1291 treset(void) {
1292         uint i;
1293
1294         term.c = (TCursor){{
1295                 .mode = ATTR_NULL,
1296                 .fg = defaultfg,
1297                 .bg = defaultbg
1298         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1299
1300         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1301         for(i = tabspaces; i < term.col; i += tabspaces)
1302                 term.tabs[i] = 1;
1303         term.top = 0;
1304         term.bot = term.row - 1;
1305         term.mode = MODE_WRAP;
1306
1307         tclearregion(0, 0, term.col-1, term.row-1);
1308         tmoveto(0, 0);
1309         tcursor(CURSOR_SAVE);
1310 }
1311
1312 void
1313 tnew(int col, int row) {
1314         memset(&term, 0, sizeof(Term));
1315         tresize(col, row);
1316         term.numlock = 1;
1317
1318         treset();
1319 }
1320
1321 void
1322 tswapscreen(void) {
1323         Line *tmp = term.line;
1324
1325         term.line = term.alt;
1326         term.alt = tmp;
1327         term.mode ^= MODE_ALTSCREEN;
1328         tfulldirt();
1329 }
1330
1331 void
1332 tscrolldown(int orig, int n) {
1333         int i;
1334         Line temp;
1335
1336         LIMIT(n, 0, term.bot-orig+1);
1337
1338         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1339
1340         for(i = term.bot; i >= orig+n; i--) {
1341                 temp = term.line[i];
1342                 term.line[i] = term.line[i-n];
1343                 term.line[i-n] = temp;
1344
1345                 term.dirty[i] = 1;
1346                 term.dirty[i-n] = 1;
1347         }
1348
1349         selscroll(orig, n);
1350 }
1351
1352 void
1353 tscrollup(int orig, int n) {
1354         int i;
1355         Line temp;
1356         LIMIT(n, 0, term.bot-orig+1);
1357
1358         tclearregion(0, orig, term.col-1, orig+n-1);
1359
1360         for(i = orig; i <= term.bot-n; i++) {
1361                  temp = term.line[i];
1362                  term.line[i] = term.line[i+n];
1363                  term.line[i+n] = temp;
1364
1365                  term.dirty[i] = 1;
1366                  term.dirty[i+n] = 1;
1367         }
1368
1369         selscroll(orig, -n);
1370 }
1371
1372 void
1373 selscroll(int orig, int n) {
1374         if(sel.bx == -1)
1375                 return;
1376
1377         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1378                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1379                         sel.bx = -1;
1380                         return;
1381                 }
1382                 if(sel.type == SEL_RECTANGULAR) {
1383                         if(sel.by < term.top)
1384                                 sel.by = term.top;
1385                         if(sel.ey > term.bot)
1386                                 sel.ey = term.bot;
1387                 } else {
1388                         if(sel.by < term.top) {
1389                                 sel.by = term.top;
1390                                 sel.bx = 0;
1391                         }
1392                         if(sel.ey > term.bot) {
1393                                 sel.ey = term.bot;
1394                                 sel.ex = term.col;
1395                         }
1396                 }
1397                 sel.b.y = sel.by, sel.b.x = sel.bx;
1398                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1399         }
1400 }
1401
1402 void
1403 tnewline(int first_col) {
1404         int y = term.c.y;
1405
1406         if(y == term.bot) {
1407                 tscrollup(term.top, 1);
1408         } else {
1409                 y++;
1410         }
1411         tmoveto(first_col ? 0 : term.c.x, y);
1412 }
1413
1414 void
1415 csiparse(void) {
1416         char *p = csiescseq.buf, *np;
1417         long int v;
1418
1419         csiescseq.narg = 0;
1420         if(*p == '?') {
1421                 csiescseq.priv = 1;
1422                 p++;
1423         }
1424
1425         csiescseq.buf[csiescseq.len] = '\0';
1426         while(p < csiescseq.buf+csiescseq.len) {
1427                 np = NULL;
1428                 v = strtol(p, &np, 10);
1429                 if(np == p)
1430                         v = 0;
1431                 if(v == LONG_MAX || v == LONG_MIN)
1432                         v = -1;
1433                 csiescseq.arg[csiescseq.narg++] = v;
1434                 p = np;
1435                 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1436                         break;
1437                 p++;
1438         }
1439         csiescseq.mode = *p;
1440 }
1441
1442 /* for absolute user moves, when decom is set */
1443 void
1444 tmoveato(int x, int y) {
1445         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1446 }
1447
1448 void
1449 tmoveto(int x, int y) {
1450         int miny, maxy;
1451
1452         if(term.c.state & CURSOR_ORIGIN) {
1453                 miny = term.top;
1454                 maxy = term.bot;
1455         } else {
1456                 miny = 0;
1457                 maxy = term.row - 1;
1458         }
1459         LIMIT(x, 0, term.col-1);
1460         LIMIT(y, miny, maxy);
1461         term.c.state &= ~CURSOR_WRAPNEXT;
1462         term.c.x = x;
1463         term.c.y = y;
1464 }
1465
1466 void
1467 tsetchar(char *c, Glyph *attr, int x, int y) {
1468         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1469                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1470                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1471                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1472                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1473                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1474                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1475                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1476                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1477         };
1478
1479         /*
1480          * The table is proudly stolen from rxvt.
1481          */
1482         if(attr->mode & ATTR_GFX) {
1483                 if(c[0] >= 0x41 && c[0] <= 0x7e
1484                                 && vt100_0[c[0] - 0x41]) {
1485                         c = vt100_0[c[0] - 0x41];
1486                 }
1487         }
1488
1489         term.dirty[y] = 1;
1490         term.line[y][x] = *attr;
1491         memcpy(term.line[y][x].c, c, UTF_SIZ);
1492 }
1493
1494 void
1495 tclearregion(int x1, int y1, int x2, int y2) {
1496         int x, y, temp;
1497
1498         if(x1 > x2)
1499                 temp = x1, x1 = x2, x2 = temp;
1500         if(y1 > y2)
1501                 temp = y1, y1 = y2, y2 = temp;
1502
1503         LIMIT(x1, 0, term.col-1);
1504         LIMIT(x2, 0, term.col-1);
1505         LIMIT(y1, 0, term.row-1);
1506         LIMIT(y2, 0, term.row-1);
1507
1508         for(y = y1; y <= y2; y++) {
1509                 term.dirty[y] = 1;
1510                 for(x = x1; x <= x2; x++) {
1511                         if(selected(x, y))
1512                                 selclear(NULL);
1513                         term.line[y][x] = term.c.attr;
1514                         memcpy(term.line[y][x].c, " ", 2);
1515                 }
1516         }
1517 }
1518
1519 void
1520 tdeletechar(int n) {
1521         int src = term.c.x + n;
1522         int dst = term.c.x;
1523         int size = term.col - src;
1524
1525         term.dirty[term.c.y] = 1;
1526
1527         if(src >= term.col) {
1528                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1529                 return;
1530         }
1531
1532         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1533                         size * sizeof(Glyph));
1534         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1535 }
1536
1537 void
1538 tinsertblank(int n) {
1539         int src = term.c.x;
1540         int dst = src + n;
1541         int size = term.col - dst;
1542
1543         term.dirty[term.c.y] = 1;
1544
1545         if(dst >= term.col) {
1546                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1547                 return;
1548         }
1549
1550         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1551                         size * sizeof(Glyph));
1552         tclearregion(src, term.c.y, dst - 1, term.c.y);
1553 }
1554
1555 void
1556 tinsertblankline(int n) {
1557         if(term.c.y < term.top || term.c.y > term.bot)
1558                 return;
1559
1560         tscrolldown(term.c.y, n);
1561 }
1562
1563 void
1564 tdeleteline(int n) {
1565         if(term.c.y < term.top || term.c.y > term.bot)
1566                 return;
1567
1568         tscrollup(term.c.y, n);
1569 }
1570
1571 void
1572 tsetattr(int *attr, int l) {
1573         int i;
1574
1575         for(i = 0; i < l; i++) {
1576                 switch(attr[i]) {
1577                 case 0:
1578                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1579                                         | ATTR_BOLD | ATTR_ITALIC \
1580                                         | ATTR_BLINK);
1581                         term.c.attr.fg = defaultfg;
1582                         term.c.attr.bg = defaultbg;
1583                         break;
1584                 case 1:
1585                         term.c.attr.mode |= ATTR_BOLD;
1586                         break;
1587                 case 3:
1588                         term.c.attr.mode |= ATTR_ITALIC;
1589                         break;
1590                 case 4:
1591                         term.c.attr.mode |= ATTR_UNDERLINE;
1592                         break;
1593                 case 5: /* slow blink */
1594                 case 6: /* rapid blink */
1595                         term.c.attr.mode |= ATTR_BLINK;
1596                         break;
1597                 case 7:
1598                         term.c.attr.mode |= ATTR_REVERSE;
1599                         break;
1600                 case 21:
1601                 case 22:
1602                         term.c.attr.mode &= ~ATTR_BOLD;
1603                         break;
1604                 case 23:
1605                         term.c.attr.mode &= ~ATTR_ITALIC;
1606                         break;
1607                 case 24:
1608                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1609                         break;
1610                 case 25:
1611                 case 26:
1612                         term.c.attr.mode &= ~ATTR_BLINK;
1613                         break;
1614                 case 27:
1615                         term.c.attr.mode &= ~ATTR_REVERSE;
1616                         break;
1617                 case 38:
1618                         if(i + 2 < l && attr[i + 1] == 5) {
1619                                 i += 2;
1620                                 if(BETWEEN(attr[i], 0, 255)) {
1621                                         term.c.attr.fg = attr[i];
1622                                 } else {
1623                                         fprintf(stderr,
1624                                                 "erresc: bad fgcolor %d\n",
1625                                                 attr[i]);
1626                                 }
1627                         } else {
1628                                 fprintf(stderr,
1629                                         "erresc(38): gfx attr %d unknown\n",
1630                                         attr[i]);
1631                         }
1632                         break;
1633                 case 39:
1634                         term.c.attr.fg = defaultfg;
1635                         break;
1636                 case 48:
1637                         if(i + 2 < l && attr[i + 1] == 5) {
1638                                 i += 2;
1639                                 if(BETWEEN(attr[i], 0, 255)) {
1640                                         term.c.attr.bg = attr[i];
1641                                 } else {
1642                                         fprintf(stderr,
1643                                                 "erresc: bad bgcolor %d\n",
1644                                                 attr[i]);
1645                                 }
1646                         } else {
1647                                 fprintf(stderr,
1648                                         "erresc(48): gfx attr %d unknown\n",
1649                                         attr[i]);
1650                         }
1651                         break;
1652                 case 49:
1653                         term.c.attr.bg = defaultbg;
1654                         break;
1655                 default:
1656                         if(BETWEEN(attr[i], 30, 37)) {
1657                                 term.c.attr.fg = attr[i] - 30;
1658                         } else if(BETWEEN(attr[i], 40, 47)) {
1659                                 term.c.attr.bg = attr[i] - 40;
1660                         } else if(BETWEEN(attr[i], 90, 97)) {
1661                                 term.c.attr.fg = attr[i] - 90 + 8;
1662                         } else if(BETWEEN(attr[i], 100, 107)) {
1663                                 term.c.attr.bg = attr[i] - 100 + 8;
1664                         } else {
1665                                 fprintf(stderr,
1666                                         "erresc(default): gfx attr %d unknown\n",
1667                                         attr[i]), csidump();
1668                         }
1669                         break;
1670                 }
1671         }
1672 }
1673
1674 void
1675 tsetscroll(int t, int b) {
1676         int temp;
1677
1678         LIMIT(t, 0, term.row-1);
1679         LIMIT(b, 0, term.row-1);
1680         if(t > b) {
1681                 temp = t;
1682                 t = b;
1683                 b = temp;
1684         }
1685         term.top = t;
1686         term.bot = b;
1687 }
1688
1689 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1690
1691 void
1692 tsetmode(bool priv, bool set, int *args, int narg) {
1693         int *lim, mode;
1694         bool alt;
1695
1696         for(lim = args + narg; args < lim; ++args) {
1697                 if(priv) {
1698                         switch(*args) {
1699                                 break;
1700                         case 1: /* DECCKM -- Cursor key */
1701                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1702                                 break;
1703                         case 5: /* DECSCNM -- Reverse video */
1704                                 mode = term.mode;
1705                                 MODBIT(term.mode, set, MODE_REVERSE);
1706                                 if(mode != term.mode)
1707                                         redraw(REDRAW_TIMEOUT);
1708                                 break;
1709                         case 6: /* DECOM -- Origin */
1710                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1711                                 tmoveato(0, 0);
1712                                 break;
1713                         case 7: /* DECAWM -- Auto wrap */
1714                                 MODBIT(term.mode, set, MODE_WRAP);
1715                                 break;
1716                         case 0:  /* Error (IGNORED) */
1717                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1718                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1719                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1720                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1721                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1722                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1723                         case 42: /* DECNRCM -- National characters (IGNORED) */
1724                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1725                                 break;
1726                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1727                                 MODBIT(term.mode, !set, MODE_HIDE);
1728                                 break;
1729                         case 1000: /* 1000,1002: enable xterm mouse report */
1730                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1731                                 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1732                                 break;
1733                         case 1002:
1734                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1735                                 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1736                                 break;
1737                         case 1006:
1738                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1739                                 break;
1740                         case 1034:
1741                                 MODBIT(term.mode, set, MODE_8BIT);
1742                                 break;
1743                         case 1049: /* = 1047 and 1048 */
1744                         case 47:
1745                         case 1047:
1746                                 if (!allowaltscreen)
1747                                         break;
1748
1749                                 alt = IS_SET(MODE_ALTSCREEN);
1750                                 if(alt) {
1751                                         tclearregion(0, 0, term.col-1,
1752                                                         term.row-1);
1753                                 }
1754                                 if(set ^ alt)           /* set is always 1 or 0 */
1755                                         tswapscreen();
1756                                 if(*args != 1049)
1757                                         break;
1758                                 /* FALLTRU */
1759                         case 1048:
1760                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1761                                 break;
1762                         default:
1763                                 fprintf(stderr,
1764                                         "erresc: unknown private set/reset mode %d\n",
1765                                         *args);
1766                                 break;
1767                         }
1768                 } else {
1769                         switch(*args) {
1770                         case 0:  /* Error (IGNORED) */
1771                                 break;
1772                         case 2:  /* KAM -- keyboard action */
1773                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1774                                 break;
1775                         case 4:  /* IRM -- Insertion-replacement */
1776                                 MODBIT(term.mode, set, MODE_INSERT);
1777                                 break;
1778                         case 12: /* SRM -- Send/Receive */
1779                                 MODBIT(term.mode, !set, MODE_ECHO);
1780                                 break;
1781                         case 20: /* LNM -- Linefeed/new line */
1782                                 MODBIT(term.mode, set, MODE_CRLF);
1783                                 break;
1784                         default:
1785                                 fprintf(stderr,
1786                                         "erresc: unknown set/reset mode %d\n",
1787                                         *args);
1788                                 break;
1789                         }
1790                 }
1791         }
1792 }
1793 #undef MODBIT
1794
1795
1796 void
1797 csihandle(void) {
1798         switch(csiescseq.mode) {
1799         default:
1800         unknown:
1801                 fprintf(stderr, "erresc: unknown csi ");
1802                 csidump();
1803                 /* die(""); */
1804                 break;
1805         case '@': /* ICH -- Insert <n> blank char */
1806                 DEFAULT(csiescseq.arg[0], 1);
1807                 tinsertblank(csiescseq.arg[0]);
1808                 break;
1809         case 'A': /* CUU -- Cursor <n> Up */
1810                 DEFAULT(csiescseq.arg[0], 1);
1811                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1812                 break;
1813         case 'B': /* CUD -- Cursor <n> Down */
1814         case 'e': /* VPR --Cursor <n> Down */
1815                 DEFAULT(csiescseq.arg[0], 1);
1816                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1817                 break;
1818         case 'c': /* DA -- Device Attributes */
1819                 if(csiescseq.arg[0] == 0)
1820                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1821                 break;
1822         case 'C': /* CUF -- Cursor <n> Forward */
1823         case 'a': /* HPR -- Cursor <n> Forward */
1824                 DEFAULT(csiescseq.arg[0], 1);
1825                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1826                 break;
1827         case 'D': /* CUB -- Cursor <n> Backward */
1828                 DEFAULT(csiescseq.arg[0], 1);
1829                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1830                 break;
1831         case 'E': /* CNL -- Cursor <n> Down and first col */
1832                 DEFAULT(csiescseq.arg[0], 1);
1833                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1834                 break;
1835         case 'F': /* CPL -- Cursor <n> Up and first col */
1836                 DEFAULT(csiescseq.arg[0], 1);
1837                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1838                 break;
1839         case 'g': /* TBC -- Tabulation clear */
1840                 switch(csiescseq.arg[0]) {
1841                 case 0: /* clear current tab stop */
1842                         term.tabs[term.c.x] = 0;
1843                         break;
1844                 case 3: /* clear all the tabs */
1845                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1846                         break;
1847                 default:
1848                         goto unknown;
1849                 }
1850                 break;
1851         case 'G': /* CHA -- Move to <col> */
1852         case '`': /* HPA */
1853                 DEFAULT(csiescseq.arg[0], 1);
1854                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1855                 break;
1856         case 'H': /* CUP -- Move to <row> <col> */
1857         case 'f': /* HVP */
1858                 DEFAULT(csiescseq.arg[0], 1);
1859                 DEFAULT(csiescseq.arg[1], 1);
1860                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1861                 break;
1862         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1863                 DEFAULT(csiescseq.arg[0], 1);
1864                 while(csiescseq.arg[0]--)
1865                         tputtab(1);
1866                 break;
1867         case 'J': /* ED -- Clear screen */
1868                 sel.bx = -1;
1869                 switch(csiescseq.arg[0]) {
1870                 case 0: /* below */
1871                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1872                         if(term.c.y < term.row-1) {
1873                                 tclearregion(0, term.c.y+1, term.col-1,
1874                                                 term.row-1);
1875                         }
1876                         break;
1877                 case 1: /* above */
1878                         if(term.c.y > 1)
1879                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1880                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1881                         break;
1882                 case 2: /* all */
1883                         tclearregion(0, 0, term.col-1, term.row-1);
1884                         break;
1885                 default:
1886                         goto unknown;
1887                 }
1888                 break;
1889         case 'K': /* EL -- Clear line */
1890                 switch(csiescseq.arg[0]) {
1891                 case 0: /* right */
1892                         tclearregion(term.c.x, term.c.y, term.col-1,
1893                                         term.c.y);
1894                         break;
1895                 case 1: /* left */
1896                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1897                         break;
1898                 case 2: /* all */
1899                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1900                         break;
1901                 }
1902                 break;
1903         case 'S': /* SU -- Scroll <n> line up */
1904                 DEFAULT(csiescseq.arg[0], 1);
1905                 tscrollup(term.top, csiescseq.arg[0]);
1906                 break;
1907         case 'T': /* SD -- Scroll <n> line down */
1908                 DEFAULT(csiescseq.arg[0], 1);
1909                 tscrolldown(term.top, csiescseq.arg[0]);
1910                 break;
1911         case 'L': /* IL -- Insert <n> blank lines */
1912                 DEFAULT(csiescseq.arg[0], 1);
1913                 tinsertblankline(csiescseq.arg[0]);
1914                 break;
1915         case 'l': /* RM -- Reset Mode */
1916                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1917                 break;
1918         case 'M': /* DL -- Delete <n> lines */
1919                 DEFAULT(csiescseq.arg[0], 1);
1920                 tdeleteline(csiescseq.arg[0]);
1921                 break;
1922         case 'X': /* ECH -- Erase <n> char */
1923                 DEFAULT(csiescseq.arg[0], 1);
1924                 tclearregion(term.c.x, term.c.y,
1925                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
1926                 break;
1927         case 'P': /* DCH -- Delete <n> char */
1928                 DEFAULT(csiescseq.arg[0], 1);
1929                 tdeletechar(csiescseq.arg[0]);
1930                 break;
1931         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1932                 DEFAULT(csiescseq.arg[0], 1);
1933                 while(csiescseq.arg[0]--)
1934                         tputtab(0);
1935                 break;
1936         case 'd': /* VPA -- Move to <row> */
1937                 DEFAULT(csiescseq.arg[0], 1);
1938                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1939                 break;
1940         case 'h': /* SM -- Set terminal mode */
1941                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1942                 break;
1943         case 'm': /* SGR -- Terminal attribute (color) */
1944                 tsetattr(csiescseq.arg, csiescseq.narg);
1945                 break;
1946         case 'r': /* DECSTBM -- Set Scrolling Region */
1947                 if(csiescseq.priv) {
1948                         goto unknown;
1949                 } else {
1950                         DEFAULT(csiescseq.arg[0], 1);
1951                         DEFAULT(csiescseq.arg[1], term.row);
1952                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1953                         tmoveato(0, 0);
1954                 }
1955                 break;
1956         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1957                 tcursor(CURSOR_SAVE);
1958                 break;
1959         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1960                 tcursor(CURSOR_LOAD);
1961                 break;
1962         }
1963 }
1964
1965 void
1966 csidump(void) {
1967         int i;
1968         uint c;
1969
1970         printf("ESC[");
1971         for(i = 0; i < csiescseq.len; i++) {
1972                 c = csiescseq.buf[i] & 0xff;
1973                 if(isprint(c)) {
1974                         putchar(c);
1975                 } else if(c == '\n') {
1976                         printf("(\\n)");
1977                 } else if(c == '\r') {
1978                         printf("(\\r)");
1979                 } else if(c == 0x1b) {
1980                         printf("(\\e)");
1981                 } else {
1982                         printf("(%02x)", c);
1983                 }
1984         }
1985         putchar('\n');
1986 }
1987
1988 void
1989 csireset(void) {
1990         memset(&csiescseq, 0, sizeof(csiescseq));
1991 }
1992
1993 void
1994 strhandle(void) {
1995         char *p = NULL;
1996         int i, j, narg;
1997
1998         strparse();
1999         narg = strescseq.narg;
2000
2001         switch(strescseq.type) {
2002         case ']': /* OSC -- Operating System Command */
2003                 switch(i = atoi(strescseq.args[0])) {
2004                 case 0:
2005                 case 1:
2006                 case 2:
2007                         if(narg > 1)
2008                                 xsettitle(strescseq.args[1]);
2009                         break;
2010                 case 4: /* color set */
2011                         if(narg < 3)
2012                                 break;
2013                         p = strescseq.args[2];
2014                         /* fall through */
2015                 case 104: /* color reset, here p = NULL */
2016                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2017                         if (!xsetcolorname(j, p)) {
2018                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2019                         } else {
2020                                 /*
2021                                  * TODO if defaultbg color is changed, borders
2022                                  * are dirty
2023                                  */
2024                                 redraw(0);
2025                         }
2026                         break;
2027                 default:
2028                         fprintf(stderr, "erresc: unknown str ");
2029                         strdump();
2030                         break;
2031                 }
2032                 break;
2033         case 'k': /* old title set compatibility */
2034                 xsettitle(strescseq.args[0]);
2035                 break;
2036         case 'P': /* DSC -- Device Control String */
2037         case '_': /* APC -- Application Program Command */
2038         case '^': /* PM -- Privacy Message */
2039         default:
2040                 fprintf(stderr, "erresc: unknown str ");
2041                 strdump();
2042                 /* die(""); */
2043                 break;
2044         }
2045 }
2046
2047 void
2048 strparse(void) {
2049         char *p = strescseq.buf;
2050
2051         strescseq.narg = 0;
2052         strescseq.buf[strescseq.len] = '\0';
2053         while(p && strescseq.narg < STR_ARG_SIZ)
2054                 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2055 }
2056
2057 void
2058 strdump(void) {
2059         int i;
2060         uint c;
2061
2062         printf("ESC%c", strescseq.type);
2063         for(i = 0; i < strescseq.len; i++) {
2064                 c = strescseq.buf[i] & 0xff;
2065                 if(c == '\0') {
2066                         return;
2067                 } else if(isprint(c)) {
2068                         putchar(c);
2069                 } else if(c == '\n') {
2070                         printf("(\\n)");
2071                 } else if(c == '\r') {
2072                         printf("(\\r)");
2073                 } else if(c == 0x1b) {
2074                         printf("(\\e)");
2075                 } else {
2076                         printf("(%02x)", c);
2077                 }
2078         }
2079         printf("ESC\\\n");
2080 }
2081
2082 void
2083 strreset(void) {
2084         memset(&strescseq, 0, sizeof(strescseq));
2085 }
2086
2087 void
2088 tputtab(bool forward) {
2089         uint x = term.c.x;
2090
2091         if(forward) {
2092                 if(x == term.col)
2093                         return;
2094                 for(++x; x < term.col && !term.tabs[x]; ++x)
2095                         /* nothing */ ;
2096         } else {
2097                 if(x == 0)
2098                         return;
2099                 for(--x; x > 0 && !term.tabs[x]; --x)
2100                         /* nothing */ ;
2101         }
2102         tmoveto(x, term.c.y);
2103 }
2104
2105 void
2106 techo(char *buf, int len) {
2107         for(; len > 0; buf++, len--) {
2108                 char c = *buf;
2109
2110                 if(c == '\033') {               /* escape */
2111                         tputc("^", 1);
2112                         tputc("[", 1);
2113                 } else if(c < '\x20') { /* control code */
2114                         if(c != '\n' && c != '\r' && c != '\t') {
2115                                 c |= '\x40';
2116                                 tputc("^", 1);
2117                         }
2118                         tputc(&c, 1);
2119                 } else {
2120                         break;
2121                 }
2122         }
2123         if(len)
2124                 tputc(buf, len);
2125 }
2126
2127 void
2128 tputc(char *c, int len) {
2129         uchar ascii = *c;
2130         bool control = ascii < '\x20' || ascii == 0177;
2131
2132         if(iofd != -1) {
2133                 if(xwrite(iofd, c, len) < 0) {
2134                         fprintf(stderr, "Error writing in %s:%s\n",
2135                                 opt_io, strerror(errno));
2136                         close(iofd);
2137                         iofd = -1;
2138                 }
2139         }
2140
2141         /*
2142          * STR sequences must be checked before anything else
2143          * because it can use some control codes as part of the sequence.
2144          */
2145         if(term.esc & ESC_STR) {
2146                 switch(ascii) {
2147                 case '\033':
2148                         term.esc = ESC_START | ESC_STR_END;
2149                         break;
2150                 case '\a': /* backwards compatibility to xterm */
2151                         term.esc = 0;
2152                         strhandle();
2153                         break;
2154                 default:
2155                         if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2156                                 memmove(&strescseq.buf[strescseq.len], c, len);
2157                                 strescseq.len += len;
2158                         } else {
2159                         /*
2160                          * Here is a bug in terminals. If the user never sends
2161                          * some code to stop the str or esc command, then st
2162                          * will stop responding. But this is better than
2163                          * silently failing with unknown characters. At least
2164                          * then users will report back.
2165                          *
2166                          * In the case users ever get fixed, here is the code:
2167                          */
2168                         /*
2169                          * term.esc = 0;
2170                          * strhandle();
2171                          */
2172                         }
2173                 }
2174                 return;
2175         }
2176
2177         /*
2178          * Actions of control codes must be performed as soon they arrive
2179          * because they can be embedded inside a control sequence, and
2180          * they must not cause conflicts with sequences.
2181          */
2182         if(control) {
2183                 switch(ascii) {
2184                 case '\t':      /* HT */
2185                         tputtab(1);
2186                         return;
2187                 case '\b':      /* BS */
2188                         tmoveto(term.c.x-1, term.c.y);
2189                         return;
2190                 case '\r':      /* CR */
2191                         tmoveto(0, term.c.y);
2192                         return;
2193                 case '\f':      /* LF */
2194                 case '\v':      /* VT */
2195                 case '\n':      /* LF */
2196                         /* go to first col if the mode is set */
2197                         tnewline(IS_SET(MODE_CRLF));
2198                         return;
2199                 case '\a':      /* BEL */
2200                         if(!(xw.state & WIN_FOCUSED))
2201                                 xseturgency(1);
2202                         return;
2203                 case '\033':    /* ESC */
2204                         csireset();
2205                         term.esc = ESC_START;
2206                         return;
2207                 case '\016':    /* SO */
2208                 case '\017':    /* SI */
2209                         /*
2210                          * Different charsets are hard to handle. Applications
2211                          * should use the right alt charset escapes for the
2212                          * only reason they still exist: line drawing. The
2213                          * rest is incompatible history st should not support.
2214                          */
2215                         return;
2216                 case '\032':    /* SUB */
2217                 case '\030':    /* CAN */
2218                         csireset();
2219                         return;
2220                 case '\005':    /* ENQ (IGNORED) */
2221                 case '\000':    /* NUL (IGNORED) */
2222                 case '\021':    /* XON (IGNORED) */
2223                 case '\023':    /* XOFF (IGNORED) */
2224                 case 0177:      /* DEL (IGNORED) */
2225                         return;
2226                 }
2227         } else if(term.esc & ESC_START) {
2228                 if(term.esc & ESC_CSI) {
2229                         csiescseq.buf[csiescseq.len++] = ascii;
2230                         if(BETWEEN(ascii, 0x40, 0x7E)
2231                                         || csiescseq.len >= \
2232                                         sizeof(csiescseq.buf)-1) {
2233                                 term.esc = 0;
2234                                 csiparse();
2235                                 csihandle();
2236                         }
2237                 } else if(term.esc & ESC_STR_END) {
2238                         term.esc = 0;
2239                         if(ascii == '\\')
2240                                 strhandle();
2241                 } else if(term.esc & ESC_ALTCHARSET) {
2242                         switch(ascii) {
2243                         case '0': /* Line drawing set */
2244                                 term.c.attr.mode |= ATTR_GFX;
2245                                 break;
2246                         case 'B': /* USASCII */
2247                                 term.c.attr.mode &= ~ATTR_GFX;
2248                                 break;
2249                         case 'A': /* UK (IGNORED) */
2250                         case '<': /* multinational charset (IGNORED) */
2251                         case '5': /* Finnish (IGNORED) */
2252                         case 'C': /* Finnish (IGNORED) */
2253                         case 'K': /* German (IGNORED) */
2254                                 break;
2255                         default:
2256                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2257                         }
2258                         term.esc = 0;
2259                 } else if(term.esc & ESC_TEST) {
2260                         if(ascii == '8') { /* DEC screen alignment test. */
2261                                 char E[UTF_SIZ] = "E";
2262                                 int x, y;
2263
2264                                 for(x = 0; x < term.col; ++x) {
2265                                         for(y = 0; y < term.row; ++y)
2266                                                 tsetchar(E, &term.c.attr, x, y);
2267                                 }
2268                         }
2269                         term.esc = 0;
2270                 } else {
2271                         switch(ascii) {
2272                         case '[':
2273                                 term.esc |= ESC_CSI;
2274                                 break;
2275                         case '#':
2276                                 term.esc |= ESC_TEST;
2277                                 break;
2278                         case 'P': /* DCS -- Device Control String */
2279                         case '_': /* APC -- Application Program Command */
2280                         case '^': /* PM -- Privacy Message */
2281                         case ']': /* OSC -- Operating System Command */
2282                         case 'k': /* old title set compatibility */
2283                                 strreset();
2284                                 strescseq.type = ascii;
2285                                 term.esc |= ESC_STR;
2286                                 break;
2287                         case '(': /* set primary charset G0 */
2288                                 term.esc |= ESC_ALTCHARSET;
2289                                 break;
2290                         case ')': /* set secondary charset G1 (IGNORED) */
2291                         case '*': /* set tertiary charset G2 (IGNORED) */
2292                         case '+': /* set quaternary charset G3 (IGNORED) */
2293                                 term.esc = 0;
2294                                 break;
2295                         case 'D': /* IND -- Linefeed */
2296                                 if(term.c.y == term.bot) {
2297                                         tscrollup(term.top, 1);
2298                                 } else {
2299                                         tmoveto(term.c.x, term.c.y+1);
2300                                 }
2301                                 term.esc = 0;
2302                                 break;
2303                         case 'E': /* NEL -- Next line */
2304                                 tnewline(1); /* always go to first col */
2305                                 term.esc = 0;
2306                                 break;
2307                         case 'H': /* HTS -- Horizontal tab stop */
2308                                 term.tabs[term.c.x] = 1;
2309                                 term.esc = 0;
2310                                 break;
2311                         case 'M': /* RI -- Reverse index */
2312                                 if(term.c.y == term.top) {
2313                                         tscrolldown(term.top, 1);
2314                                 } else {
2315                                         tmoveto(term.c.x, term.c.y-1);
2316                                 }
2317                                 term.esc = 0;
2318                                 break;
2319                         case 'Z': /* DECID -- Identify Terminal */
2320                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2321                                 term.esc = 0;
2322                                 break;
2323                         case 'c': /* RIS -- Reset to inital state */
2324                                 treset();
2325                                 term.esc = 0;
2326                                 xresettitle();
2327                                 break;
2328                         case '=': /* DECPAM -- Application keypad */
2329                                 term.mode |= MODE_APPKEYPAD;
2330                                 term.esc = 0;
2331                                 break;
2332                         case '>': /* DECPNM -- Normal keypad */
2333                                 term.mode &= ~MODE_APPKEYPAD;
2334                                 term.esc = 0;
2335                                 break;
2336                         case '7': /* DECSC -- Save Cursor */
2337                                 tcursor(CURSOR_SAVE);
2338                                 term.esc = 0;
2339                                 break;
2340                         case '8': /* DECRC -- Restore Cursor */
2341                                 tcursor(CURSOR_LOAD);
2342                                 term.esc = 0;
2343                                 break;
2344                         case '\\': /* ST -- Stop */
2345                                 term.esc = 0;
2346                                 break;
2347                         default:
2348                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2349                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2350                                 term.esc = 0;
2351                         }
2352                 }
2353                 /*
2354                  * All characters which form part of a sequence are not
2355                  * printed
2356                  */
2357                 return;
2358         }
2359         /*
2360          * Display control codes only if we are in graphic mode
2361          */
2362         if(control && !(term.c.attr.mode & ATTR_GFX))
2363                 return;
2364         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2365                 sel.bx = -1;
2366         if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2367                 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2368                 tnewline(1);
2369         }
2370
2371         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2372                 memmove(&term.line[term.c.y][term.c.x+1],
2373                         &term.line[term.c.y][term.c.x],
2374                         (term.col - term.c.x - 1) * sizeof(Glyph));
2375         }
2376
2377         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2378         if(term.c.x+1 < term.col) {
2379                 tmoveto(term.c.x+1, term.c.y);
2380         } else {
2381                 term.c.state |= CURSOR_WRAPNEXT;
2382         }
2383 }
2384
2385 int
2386 tresize(int col, int row) {
2387         int i;
2388         int minrow = MIN(row, term.row);
2389         int mincol = MIN(col, term.col);
2390         int slide = term.c.y - row + 1;
2391         bool *bp;
2392         Line *orig;
2393
2394         if(col < 1 || row < 1)
2395                 return 0;
2396
2397         /* free unneeded rows */
2398         i = 0;
2399         if(slide > 0) {
2400                 /*
2401                  * slide screen to keep cursor where we expect it -
2402                  * tscrollup would work here, but we can optimize to
2403                  * memmove because we're freeing the earlier lines
2404                  */
2405                 for(/* i = 0 */; i < slide; i++) {
2406                         free(term.line[i]);
2407                         free(term.alt[i]);
2408                 }
2409                 memmove(term.line, term.line + slide, row * sizeof(Line));
2410                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2411         }
2412         for(i += row; i < term.row; i++) {
2413                 free(term.line[i]);
2414                 free(term.alt[i]);
2415         }
2416
2417         /* resize to new height */
2418         term.line = xrealloc(term.line, row * sizeof(Line));
2419         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2420         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2421         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2422
2423         /* resize each row to new width, zero-pad if needed */
2424         for(i = 0; i < minrow; i++) {
2425                 term.dirty[i] = 1;
2426                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2427                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2428         }
2429
2430         /* allocate any new rows */
2431         for(/* i == minrow */; i < row; i++) {
2432                 term.dirty[i] = 1;
2433                 term.line[i] = xcalloc(col, sizeof(Glyph));
2434                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2435         }
2436         if(col > term.col) {
2437                 bp = term.tabs + term.col;
2438
2439                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2440                 while(--bp > term.tabs && !*bp)
2441                         /* nothing */ ;
2442                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2443                         *bp = 1;
2444         }
2445         /* update terminal size */
2446         term.col = col;
2447         term.row = row;
2448         /* reset scrolling region */
2449         tsetscroll(0, row-1);
2450         /* make use of the LIMIT in tmoveto */
2451         tmoveto(term.c.x, term.c.y);
2452         /* Clearing both screens */
2453         orig = term.line;
2454         do {
2455                 if(mincol < col && 0 < minrow) {
2456                         tclearregion(mincol, 0, col - 1, minrow - 1);
2457                 }
2458                 if(0 < col && minrow < row) {
2459                         tclearregion(0, minrow, col - 1, row - 1);
2460                 }
2461                 tswapscreen();
2462         } while(orig != term.line);
2463
2464         return (slide > 0);
2465 }
2466
2467 void
2468 xresize(int col, int row) {
2469         xw.tw = MAX(1, col * xw.cw);
2470         xw.th = MAX(1, row * xw.ch);
2471
2472         XFreePixmap(xw.dpy, xw.buf);
2473         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2474                         DefaultDepth(xw.dpy, xw.scr));
2475         XftDrawChange(xw.draw, xw.buf);
2476         xclear(0, 0, xw.w, xw.h);
2477 }
2478
2479 static inline ushort
2480 sixd_to_16bit(int x) {
2481         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2482 }
2483
2484 void
2485 xloadcols(void) {
2486         int i, r, g, b;
2487         XRenderColor color = { .alpha = 0xffff };
2488
2489         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2490         for(i = 0; i < LEN(colorname); i++) {
2491                 if(!colorname[i])
2492                         continue;
2493                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2494                         die("Could not allocate color '%s'\n", colorname[i]);
2495                 }
2496         }
2497
2498         /* load colors [16-255] ; same colors as xterm */
2499         for(i = 16, r = 0; r < 6; r++) {
2500                 for(g = 0; g < 6; g++) {
2501                         for(b = 0; b < 6; b++) {
2502                                 color.red = sixd_to_16bit(r);
2503                                 color.green = sixd_to_16bit(g);
2504                                 color.blue = sixd_to_16bit(b);
2505                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2506                                         die("Could not allocate color %d\n", i);
2507                                 }
2508                                 i++;
2509                         }
2510                 }
2511         }
2512
2513         for(r = 0; r < 24; r++, i++) {
2514                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2515                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2516                                         &dc.col[i])) {
2517                         die("Could not allocate color %d\n", i);
2518                 }
2519         }
2520 }
2521
2522 int
2523 xsetcolorname(int x, const char *name) {
2524         XRenderColor color = { .alpha = 0xffff };
2525         Colour colour;
2526         if (x < 0 || x > LEN(colorname))
2527                 return -1;
2528         if(!name) {
2529                 if(16 <= x && x < 16 + 216) {
2530                         int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2531                         color.red = sixd_to_16bit(r);
2532                         color.green = sixd_to_16bit(g);
2533                         color.blue = sixd_to_16bit(b);
2534                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2535                                 return 0; /* something went wrong */
2536                         dc.col[x] = colour;
2537                         return 1;
2538                 } else if (16 + 216 <= x && x < 256) {
2539                         color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2540                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2541                                 return 0; /* something went wrong */
2542                         dc.col[x] = colour;
2543                         return 1;
2544                 } else {
2545                         name = colorname[x];
2546                 }
2547         }
2548         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2549                 return 0;
2550         dc.col[x] = colour;
2551         return 1;
2552 }
2553
2554 void
2555 xtermclear(int col1, int row1, int col2, int row2) {
2556         XftDrawRect(xw.draw,
2557                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2558                         borderpx + col1 * xw.cw,
2559                         borderpx + row1 * xw.ch,
2560                         (col2-col1+1) * xw.cw,
2561                         (row2-row1+1) * xw.ch);
2562 }
2563
2564 /*
2565  * Absolute coordinates.
2566  */
2567 void
2568 xclear(int x1, int y1, int x2, int y2) {
2569         XftDrawRect(xw.draw,
2570                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2571                         x1, y1, x2-x1, y2-y1);
2572 }
2573
2574 void
2575 xhints(void) {
2576         XClassHint class = {opt_class ? opt_class : termname, termname};
2577         XWMHints wm = {.flags = InputHint, .input = 1};
2578         XSizeHints *sizeh = NULL;
2579
2580         sizeh = XAllocSizeHints();
2581         if(xw.isfixed == False) {
2582                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2583                 sizeh->height = xw.h;
2584                 sizeh->width = xw.w;
2585                 sizeh->height_inc = xw.ch;
2586                 sizeh->width_inc = xw.cw;
2587                 sizeh->base_height = 2 * borderpx;
2588                 sizeh->base_width = 2 * borderpx;
2589         } else {
2590                 sizeh->flags = PMaxSize | PMinSize;
2591                 sizeh->min_width = sizeh->max_width = xw.fw;
2592                 sizeh->min_height = sizeh->max_height = xw.fh;
2593         }
2594
2595         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2596         XFree(sizeh);
2597 }
2598
2599 int
2600 xloadfont(Font *f, FcPattern *pattern) {
2601         FcPattern *match;
2602         FcResult result;
2603
2604         match = FcFontMatch(NULL, pattern, &result);
2605         if(!match)
2606                 return 1;
2607
2608         if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2609                 FcPatternDestroy(match);
2610                 return 1;
2611         }
2612
2613         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2614                 FcPatternDestroy(match);
2615                 return 1;
2616         }
2617
2618         f->pattern = FcPatternDuplicate(pattern);
2619
2620         f->ascent = f->match->ascent;
2621         f->descent = f->match->descent;
2622         f->lbearing = 0;
2623         f->rbearing = f->match->max_advance_width;
2624
2625         f->height = f->ascent + f->descent;
2626         f->width = f->lbearing + f->rbearing;
2627
2628         return 0;
2629 }
2630
2631 void
2632 xloadfonts(char *fontstr, int fontsize) {
2633         FcPattern *pattern;
2634         FcResult result;
2635         double fontval;
2636
2637         if(fontstr[0] == '-') {
2638                 pattern = XftXlfdParse(fontstr, False, False);
2639         } else {
2640                 pattern = FcNameParse((FcChar8 *)fontstr);
2641         }
2642
2643         if(!pattern)
2644                 die("st: can't open font %s\n", fontstr);
2645
2646         if(fontsize > 0) {
2647                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2648                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2649                 usedfontsize = fontsize;
2650         } else {
2651                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2652                 if(result == FcResultMatch) {
2653                         usedfontsize = (int)fontval;
2654                 } else {
2655                         /*
2656                          * Default font size is 12, if none given. This is to
2657                          * have a known usedfontsize value.
2658                          */
2659                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2660                         usedfontsize = 12;
2661                 }
2662         }
2663
2664         FcConfigSubstitute(0, pattern, FcMatchPattern);
2665         FcDefaultSubstitute(pattern);
2666
2667         if(xloadfont(&dc.font, pattern))
2668                 die("st: can't open font %s\n", fontstr);
2669
2670         /* Setting character width and height. */
2671         xw.cw = dc.font.width;
2672         xw.ch = dc.font.height;
2673
2674         FcPatternDel(pattern, FC_SLANT);
2675         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2676         if(xloadfont(&dc.ifont, pattern))
2677                 die("st: can't open font %s\n", fontstr);
2678
2679         FcPatternDel(pattern, FC_WEIGHT);
2680         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2681         if(xloadfont(&dc.ibfont, pattern))
2682                 die("st: can't open font %s\n", fontstr);
2683
2684         FcPatternDel(pattern, FC_SLANT);
2685         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2686         if(xloadfont(&dc.bfont, pattern))
2687                 die("st: can't open font %s\n", fontstr);
2688
2689         FcPatternDestroy(pattern);
2690 }
2691
2692 void
2693 xunloadfonts(void) {
2694         int i, ip;
2695
2696         /*
2697          * Free the loaded fonts in the font cache. This is done backwards
2698          * from the frccur.
2699          */
2700         for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2701                 if(ip < 0)
2702                         ip = LEN(frc) - 1;
2703                 XftFontClose(xw.dpy, frc[ip].font);
2704         }
2705         frccur = -1;
2706         frclen = 0;
2707
2708         XftFontClose(xw.dpy, dc.font.match);
2709         FcPatternDestroy(dc.font.pattern);
2710         FcFontSetDestroy(dc.font.set);
2711         XftFontClose(xw.dpy, dc.bfont.match);
2712         FcPatternDestroy(dc.bfont.pattern);
2713         FcFontSetDestroy(dc.bfont.set);
2714         XftFontClose(xw.dpy, dc.ifont.match);
2715         FcPatternDestroy(dc.ifont.pattern);
2716         FcFontSetDestroy(dc.ifont.set);
2717         XftFontClose(xw.dpy, dc.ibfont.match);
2718         FcPatternDestroy(dc.ibfont.pattern);
2719         FcFontSetDestroy(dc.ibfont.set);
2720 }
2721
2722 void
2723 xzoom(const Arg *arg) {
2724         xunloadfonts();
2725         xloadfonts(usedfont, usedfontsize + arg->i);
2726         cresize(0, 0);
2727         redraw(0);
2728 }
2729
2730 void
2731 xinit(void) {
2732         XSetWindowAttributes attrs;
2733         XGCValues gcvalues;
2734         Cursor cursor;
2735         Window parent;
2736         int sw, sh;
2737
2738         if(!(xw.dpy = XOpenDisplay(NULL)))
2739                 die("Can't open display\n");
2740         xw.scr = XDefaultScreen(xw.dpy);
2741         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2742
2743         /* font */
2744         if(!FcInit())
2745                 die("Could not init fontconfig.\n");
2746
2747         usedfont = (opt_font == NULL)? font : opt_font;
2748         xloadfonts(usedfont, 0);
2749
2750         /* colors */
2751         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2752         xloadcols();
2753
2754         /* adjust fixed window geometry */
2755         if(xw.isfixed) {
2756                 sw = DisplayWidth(xw.dpy, xw.scr);
2757                 sh = DisplayHeight(xw.dpy, xw.scr);
2758                 if(xw.fx < 0)
2759                         xw.fx = sw + xw.fx - xw.fw - 1;
2760                 if(xw.fy < 0)
2761                         xw.fy = sh + xw.fy - xw.fh - 1;
2762
2763                 xw.h = xw.fh;
2764                 xw.w = xw.fw;
2765         } else {
2766                 /* window - default size */
2767                 xw.h = 2 * borderpx + term.row * xw.ch;
2768                 xw.w = 2 * borderpx + term.col * xw.cw;
2769                 xw.fx = 0;
2770                 xw.fy = 0;
2771         }
2772
2773         /* Events */
2774         attrs.background_pixel = dc.col[defaultbg].pixel;
2775         attrs.border_pixel = dc.col[defaultbg].pixel;
2776         attrs.bit_gravity = NorthWestGravity;
2777         attrs.event_mask = FocusChangeMask | KeyPressMask
2778                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2779                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2780         attrs.colormap = xw.cmap;
2781
2782         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2783                         XRootWindow(xw.dpy, xw.scr);
2784         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2785                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2786                         xw.vis,
2787                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2788                         | CWColormap,
2789                         &attrs);
2790
2791         memset(&gcvalues, 0, sizeof(gcvalues));
2792         gcvalues.graphics_exposures = False;
2793         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2794                         &gcvalues);
2795         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2796                         DefaultDepth(xw.dpy, xw.scr));
2797         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2798         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2799
2800         /* Xft rendering context */
2801         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2802
2803         /* input methods */
2804         if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2805                 XSetLocaleModifiers("@im=local");
2806                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2807                         XSetLocaleModifiers("@im=");
2808                         if((xw.xim = XOpenIM(xw.dpy,
2809                                         NULL, NULL, NULL)) == NULL) {
2810                                 die("XOpenIM failed. Could not open input"
2811                                         " device.\n");
2812                         }
2813                 }
2814         }
2815         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2816                                            | XIMStatusNothing, XNClientWindow, xw.win,
2817                                            XNFocusWindow, xw.win, NULL);
2818         if(xw.xic == NULL)
2819                 die("XCreateIC failed. Could not obtain input method.\n");
2820
2821         /* white cursor, black outline */
2822         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2823         XDefineCursor(xw.dpy, xw.win, cursor);
2824         XRecolorCursor(xw.dpy, cursor,
2825                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2826                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2827
2828         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2829         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2830         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2831
2832         xresettitle();
2833         XMapWindow(xw.dpy, xw.win);
2834         xhints();
2835         XSync(xw.dpy, 0);
2836 }
2837
2838 void
2839 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2840         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2841             width = charlen * xw.cw, xp, i;
2842         int frp, frcflags;
2843         int u8fl, u8fblen, u8cblen, doesexist;
2844         char *u8c, *u8fs;
2845         long u8char;
2846         Font *font = &dc.font;
2847         FcResult fcres;
2848         FcPattern *fcpattern, *fontpattern;
2849         FcFontSet *fcsets[] = { NULL };
2850         FcCharSet *fccharset;
2851         Colour *fg, *bg, *temp, revfg, revbg;
2852         XRenderColor colfg, colbg;
2853         Rectangle r;
2854
2855         frcflags = FRC_NORMAL;
2856
2857         if(base.mode & ATTR_ITALIC) {
2858                 if(base.fg == defaultfg)
2859                         base.fg = defaultitalic;
2860                 font = &dc.ifont;
2861                 frcflags = FRC_ITALIC;
2862         } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2863                 if(base.fg == defaultfg)
2864                         base.fg = defaultitalic;
2865                 font = &dc.ibfont;
2866                 frcflags = FRC_ITALICBOLD;
2867         } else if(base.mode & ATTR_UNDERLINE) {
2868                 if(base.fg == defaultfg)
2869                         base.fg = defaultunderline;
2870         }
2871         fg = &dc.col[base.fg];
2872         bg = &dc.col[base.bg];
2873
2874         if(base.mode & ATTR_BOLD) {
2875                 if(BETWEEN(base.fg, 0, 7)) {
2876                         /* basic system colors */
2877                         fg = &dc.col[base.fg + 8];
2878                 } else if(BETWEEN(base.fg, 16, 195)) {
2879                         /* 256 colors */
2880                         fg = &dc.col[base.fg + 36];
2881                 } else if(BETWEEN(base.fg, 232, 251)) {
2882                         /* greyscale */
2883                         fg = &dc.col[base.fg + 4];
2884                 }
2885                 /*
2886                  * Those ranges will not be brightened:
2887                  *      8 - 15 – bright system colors
2888                  *      196 - 231 – highest 256 color cube
2889                  *      252 - 255 – brightest colors in greyscale
2890                  */
2891                 font = &dc.bfont;
2892                 frcflags = FRC_BOLD;
2893         }
2894
2895         if(IS_SET(MODE_REVERSE)) {
2896                 if(fg == &dc.col[defaultfg]) {
2897                         fg = &dc.col[defaultbg];
2898                 } else {
2899                         colfg.red = ~fg->color.red;
2900                         colfg.green = ~fg->color.green;
2901                         colfg.blue = ~fg->color.blue;
2902                         colfg.alpha = fg->color.alpha;
2903                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2904                         fg = &revfg;
2905                 }
2906
2907                 if(bg == &dc.col[defaultbg]) {
2908                         bg = &dc.col[defaultfg];
2909                 } else {
2910                         colbg.red = ~bg->color.red;
2911                         colbg.green = ~bg->color.green;
2912                         colbg.blue = ~bg->color.blue;
2913                         colbg.alpha = bg->color.alpha;
2914                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2915                         bg = &revbg;
2916                 }
2917         }
2918
2919         if(base.mode & ATTR_REVERSE) {
2920                 temp = fg;
2921                 fg = bg;
2922                 bg = temp;
2923         }
2924
2925         if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
2926                 fg = bg;
2927
2928         /* Intelligent cleaning up of the borders. */
2929         if(x == 0) {
2930                 xclear(0, (y == 0)? 0 : winy, borderpx,
2931                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2932         }
2933         if(x + charlen >= term.col) {
2934                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2935                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2936         }
2937         if(y == 0)
2938                 xclear(winx, 0, winx + width, borderpx);
2939         if(y == term.row-1)
2940                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2941
2942         /* Clean up the region we want to draw to. */
2943         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2944
2945         /* Set the clip region because Xft is sometimes dirty. */
2946         r.x = 0;
2947         r.y = 0;
2948         r.height = xw.ch;
2949         r.width = width;
2950         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
2951
2952         fcsets[0] = font->set;
2953         for(xp = winx; bytelen > 0;) {
2954                 /*
2955                  * Search for the range in the to be printed string of glyphs
2956                  * that are in the main font. Then print that range. If
2957                  * some glyph is found that is not in the font, do the
2958                  * fallback dance.
2959                  */
2960                 u8fs = s;
2961                 u8fblen = 0;
2962                 u8fl = 0;
2963                 for(;;) {
2964                         u8c = s;
2965                         u8cblen = utf8decode(s, &u8char);
2966                         s += u8cblen;
2967                         bytelen -= u8cblen;
2968
2969                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2970                         if(!doesexist || bytelen <= 0) {
2971                                 if(bytelen <= 0) {
2972                                         if(doesexist) {
2973                                                 u8fl++;
2974                                                 u8fblen += u8cblen;
2975                                         }
2976                                 }
2977
2978                                 if(u8fl > 0) {
2979                                         XftDrawStringUtf8(xw.draw, fg,
2980                                                         font->match, xp,
2981                                                         winy + font->ascent,
2982                                                         (FcChar8 *)u8fs,
2983                                                         u8fblen);
2984                                         xp += font->width * u8fl;
2985
2986                                 }
2987                                 break;
2988                         }
2989
2990                         u8fl++;
2991                         u8fblen += u8cblen;
2992                 }
2993                 if(doesexist)
2994                         break;
2995
2996                 frp = frccur;
2997                 /* Search the font cache. */
2998                 for(i = 0; i < frclen; i++, frp--) {
2999                         if(frp <= 0)
3000                                 frp = LEN(frc) - 1;
3001
3002                         if(frc[frp].c == u8char
3003                                         && frc[frp].flags == frcflags) {
3004                                 break;
3005                         }
3006                 }
3007
3008                 /* Nothing was found. */
3009                 if(i >= frclen) {
3010                         /*
3011                          * Nothing was found in the cache. Now use
3012                          * some dozen of Fontconfig calls to get the
3013                          * font for one single character.
3014                          */
3015                         fcpattern = FcPatternDuplicate(font->pattern);
3016                         fccharset = FcCharSetCreate();
3017
3018                         FcCharSetAddChar(fccharset, u8char);
3019                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3020                                         fccharset);
3021                         FcPatternAddBool(fcpattern, FC_SCALABLE,
3022                                         FcTrue);
3023
3024                         FcConfigSubstitute(0, fcpattern,
3025                                         FcMatchPattern);
3026                         FcDefaultSubstitute(fcpattern);
3027
3028                         fontpattern = FcFontSetMatch(0, fcsets,
3029                                         FcTrue, fcpattern, &fcres);
3030
3031                         /*
3032                          * Overwrite or create the new cache entry.
3033                          */
3034                         frccur++;
3035                         frclen++;
3036                         if(frccur >= LEN(frc))
3037                                 frccur = 0;
3038                         if(frclen > LEN(frc)) {
3039                                 frclen = LEN(frc);
3040                                 XftFontClose(xw.dpy, frc[frccur].font);
3041                         }
3042
3043                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
3044                                         fontpattern);
3045                         frc[frccur].c = u8char;
3046                         frc[frccur].flags = frcflags;
3047
3048                         FcPatternDestroy(fcpattern);
3049                         FcCharSetDestroy(fccharset);
3050
3051                         frp = frccur;
3052                 }
3053
3054                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
3055                                 xp, winy + frc[frp].font->ascent,
3056                                 (FcChar8 *)u8c, u8cblen);
3057
3058                 xp += font->width;
3059         }
3060
3061         /*
3062         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3063                         winy + font->ascent, (FcChar8 *)s, bytelen);
3064         */
3065
3066         if(base.mode & ATTR_UNDERLINE) {
3067                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3068                                 width, 1);
3069         }
3070
3071         /* Reset clip to none. */
3072         XftDrawSetClip(xw.draw, 0);
3073 }
3074
3075 void
3076 xdrawcursor(void) {
3077         static int oldx = 0, oldy = 0;
3078         int sl;
3079         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3080
3081         LIMIT(oldx, 0, term.col-1);
3082         LIMIT(oldy, 0, term.row-1);
3083
3084         memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3085
3086         /* remove the old cursor */
3087         sl = utf8size(term.line[oldy][oldx].c);
3088         xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3089                         oldy, 1, sl);
3090
3091         /* draw the new one */
3092         if(!(IS_SET(MODE_HIDE))) {
3093                 if(xw.state & WIN_FOCUSED) {
3094                         if(IS_SET(MODE_REVERSE)) {
3095                                 g.mode |= ATTR_REVERSE;
3096                                 g.fg = defaultcs;
3097                                 g.bg = defaultfg;
3098                         }
3099
3100                         sl = utf8size(g.c);
3101                         xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3102                 } else {
3103                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3104                                         borderpx + term.c.x * xw.cw,
3105                                         borderpx + term.c.y * xw.ch,
3106                                         xw.cw - 1, 1);
3107                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3108                                         borderpx + term.c.x * xw.cw,
3109                                         borderpx + term.c.y * xw.ch,
3110                                         1, xw.ch - 1);
3111                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3112                                         borderpx + (term.c.x + 1) * xw.cw - 1,
3113                                         borderpx + term.c.y * xw.ch,
3114                                         1, xw.ch - 1);
3115                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3116                                         borderpx + term.c.x * xw.cw,
3117                                         borderpx + (term.c.y + 1) * xw.ch - 1,
3118                                         xw.cw, 1);
3119                 }
3120                 oldx = term.c.x, oldy = term.c.y;
3121         }
3122 }
3123
3124
3125 void
3126 xsettitle(char *p) {
3127         XTextProperty prop;
3128
3129         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3130                         &prop);
3131         XSetWMName(xw.dpy, xw.win, &prop);
3132 }
3133
3134 void
3135 xresettitle(void) {
3136         xsettitle(opt_title ? opt_title : "st");
3137 }
3138
3139 void
3140 redraw(int timeout) {
3141         struct timespec tv = {0, timeout * 1000};
3142
3143         tfulldirt();
3144         draw();
3145
3146         if(timeout > 0) {
3147                 nanosleep(&tv, NULL);
3148                 XSync(xw.dpy, False); /* necessary for a good tput flash */
3149         }
3150 }
3151
3152 void
3153 draw(void) {
3154         drawregion(0, 0, term.col, term.row);
3155         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3156                         xw.h, 0, 0);
3157         XSetForeground(xw.dpy, dc.gc,
3158                         dc.col[IS_SET(MODE_REVERSE)?
3159                                 defaultfg : defaultbg].pixel);
3160 }
3161
3162 void
3163 drawregion(int x1, int y1, int x2, int y2) {
3164         int ic, ib, x, y, ox, sl;
3165         Glyph base, new;
3166         char buf[DRAW_BUF_SIZ];
3167         bool ena_sel = sel.bx != -1;
3168
3169         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3170                 ena_sel = 0;
3171
3172         if(!(xw.state & WIN_VISIBLE))
3173                 return;
3174
3175         for(y = y1; y < y2; y++) {
3176                 if(!term.dirty[y])
3177                         continue;
3178
3179                 xtermclear(0, y, term.col, y);
3180                 term.dirty[y] = 0;
3181                 base = term.line[y][0];
3182                 ic = ib = ox = 0;
3183                 for(x = x1; x < x2; x++) {
3184                         new = term.line[y][x];
3185                         if(ena_sel && selected(x, y))
3186                                 new.mode ^= ATTR_REVERSE;
3187                         if(ib > 0 && (ATTRCMP(base, new)
3188                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3189                                 xdraws(buf, base, ox, y, ic, ib);
3190                                 ic = ib = 0;
3191                         }
3192                         if(ib == 0) {
3193                                 ox = x;
3194                                 base = new;
3195                         }
3196
3197                         sl = utf8size(new.c);
3198                         memcpy(buf+ib, new.c, sl);
3199                         ib += sl;
3200                         ++ic;
3201                 }
3202                 if(ib > 0)
3203                         xdraws(buf, base, ox, y, ic, ib);
3204         }
3205         xdrawcursor();
3206 }
3207
3208 void
3209 expose(XEvent *ev) {
3210         XExposeEvent *e = &ev->xexpose;
3211
3212         if(xw.state & WIN_REDRAW) {
3213                 if(!e->count)
3214                         xw.state &= ~WIN_REDRAW;
3215         }
3216         redraw(0);
3217 }
3218
3219 void
3220 visibility(XEvent *ev) {
3221         XVisibilityEvent *e = &ev->xvisibility;
3222
3223         if(e->state == VisibilityFullyObscured) {
3224                 xw.state &= ~WIN_VISIBLE;
3225         } else if(!(xw.state & WIN_VISIBLE)) {
3226                 /* need a full redraw for next Expose, not just a buf copy */
3227                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3228         }
3229 }
3230
3231 void
3232 unmap(XEvent *ev) {
3233         xw.state &= ~WIN_VISIBLE;
3234 }
3235
3236 void
3237 xseturgency(int add) {
3238         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3239
3240         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3241         XSetWMHints(xw.dpy, xw.win, h);
3242         XFree(h);
3243 }
3244
3245 void
3246 focus(XEvent *ev) {
3247         XFocusChangeEvent *e = &ev->xfocus;
3248
3249         if(e->mode == NotifyGrab)
3250                 return;
3251
3252         if(ev->type == FocusIn) {
3253                 XSetICFocus(xw.xic);
3254                 xw.state |= WIN_FOCUSED;
3255                 xseturgency(0);
3256         } else {
3257                 XUnsetICFocus(xw.xic);
3258                 xw.state &= ~WIN_FOCUSED;
3259         }
3260 }
3261
3262 inline bool
3263 match(uint mask, uint state) {
3264         state &= ~(ignoremod);
3265
3266         if(mask == XK_NO_MOD && state)
3267                 return false;
3268         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3269                 return false;
3270         if((state & mask) != state)
3271                 return false;
3272         return true;
3273 }
3274
3275 void
3276 numlock(const Arg *dummy) {
3277         term.numlock ^= 1;
3278 }
3279
3280 char*
3281 kmap(KeySym k, uint state) {
3282         uint mask;
3283         Key *kp;
3284         int i;
3285
3286         /* Check for mapped keys out of X11 function keys. */
3287         for(i = 0; i < LEN(mappedkeys); i++) {
3288                 if(mappedkeys[i] == k)
3289                         break;
3290         }
3291         if(i == LEN(mappedkeys)) {
3292                 if((k & 0xFFFF) < 0xFD00)
3293                         return NULL;
3294         }
3295
3296         for(kp = key; kp < key + LEN(key); kp++) {
3297                 mask = kp->mask;
3298
3299                 if(kp->k != k)
3300                         continue;
3301
3302                 if(!match(mask, state))
3303                         continue;
3304
3305                 if(kp->appkey > 0) {
3306                         if(!IS_SET(MODE_APPKEYPAD))
3307                                 continue;
3308                         if(term.numlock && kp->appkey == 2)
3309                                 continue;
3310                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3311                         continue;
3312                 }
3313
3314                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3315                                 (kp->appcursor > 0
3316                                  && !IS_SET(MODE_APPCURSOR))) {
3317                         continue;
3318                 }
3319
3320                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3321                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3322                         continue;
3323                 }
3324
3325                 return kp->s;
3326         }
3327
3328         return NULL;
3329 }
3330
3331 void
3332 kpress(XEvent *ev) {
3333         XKeyEvent *e = &ev->xkey;
3334         KeySym ksym;
3335         char xstr[31], buf[32], *customkey, *cp = buf;
3336         int len, ret;
3337         long c;
3338         Status status;
3339         Shortcut *bp;
3340
3341         if(IS_SET(MODE_KBDLOCK))
3342                 return;
3343
3344         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3345         e->state &= ~Mod2Mask;
3346         /* 1. shortcuts */
3347         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3348                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3349                         bp->func(&(bp->arg));
3350                         return;
3351                 }
3352         }
3353
3354         /* 2. custom keys from config.h */
3355         if((customkey = kmap(ksym, e->state))) {
3356                 len = strlen(customkey);
3357                 memcpy(buf, customkey, len);
3358         /* 3. hardcoded (overrides X lookup) */
3359         } else {
3360                 if(len == 0)
3361                         return;
3362
3363                 if(len == 1 && e->state & Mod1Mask) {
3364                         if(IS_SET(MODE_8BIT)) {
3365                                 if(*xstr < 0177) {
3366                                         c = *xstr | B7;
3367                                         ret = utf8encode(&c, cp);
3368                                         cp += ret;
3369                                         len = 0;
3370                                 }
3371                         } else {
3372                                 *cp++ = '\033';
3373                         }
3374                 }
3375
3376                 memcpy(cp, xstr, len);
3377                 len = cp - buf + len;
3378         }
3379
3380         ttywrite(buf, len);
3381         if(IS_SET(MODE_ECHO))
3382                 techo(buf, len);
3383 }
3384
3385
3386 void
3387 cmessage(XEvent *e) {
3388         /*
3389          * See xembed specs
3390          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3391          */
3392         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3393                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3394                         xw.state |= WIN_FOCUSED;
3395                         xseturgency(0);
3396                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3397                         xw.state &= ~WIN_FOCUSED;
3398                 }
3399         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3400                 /* Send SIGHUP to shell */
3401                 kill(pid, SIGHUP);
3402                 exit(EXIT_SUCCESS);
3403         }
3404 }
3405
3406 void
3407 cresize(int width, int height) {
3408         int col, row;
3409
3410         if(width != 0)
3411                 xw.w = width;
3412         if(height != 0)
3413                 xw.h = height;
3414
3415         col = (xw.w - 2 * borderpx) / xw.cw;
3416         row = (xw.h - 2 * borderpx) / xw.ch;
3417
3418         tresize(col, row);
3419         xresize(col, row);
3420         ttyresize();
3421 }
3422
3423 void
3424 resize(XEvent *e) {
3425         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3426                 return;
3427
3428         cresize(e->xconfigure.width, e->xconfigure.height);
3429 }
3430
3431 void
3432 run(void) {
3433         XEvent ev;
3434         fd_set rfd;
3435         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3436         struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3437
3438         gettimeofday(&lastblink, NULL);
3439         gettimeofday(&last, NULL);
3440
3441         for(xev = actionfps;;) {
3442                 FD_ZERO(&rfd);
3443                 FD_SET(cmdfd, &rfd);
3444                 FD_SET(xfd, &rfd);
3445
3446                 switch(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3447                 case -1:
3448                         if(errno == EINTR)
3449                                 continue;
3450                         die("select failed: %s\n", SERRNO);
3451                 default:
3452                         if(FD_ISSET(cmdfd, &rfd)) {
3453                                 ttyread();
3454                                 if(blinktimeout) {
3455                                         blinkset = tattrset(ATTR_BLINK);
3456                                         if(!blinkset && term.mode & ATTR_BLINK)
3457                                                 term.mode &= ~(MODE_BLINK);
3458                                 }
3459                         }
3460
3461                         if(FD_ISSET(xfd, &rfd))
3462                                 xev = actionfps;
3463                         break;
3464                 }
3465                 gettimeofday(&now, NULL);
3466                 drawtimeout.tv_sec = 0;
3467                 drawtimeout.tv_usec = (1000/xfps) * 1000;
3468                 tv = &drawtimeout;
3469
3470                 dodraw = 0;
3471                 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3472                         tsetdirtattr(ATTR_BLINK);
3473                         term.mode ^= MODE_BLINK;
3474                         gettimeofday(&lastblink, NULL);
3475                         dodraw = 1;
3476                 }
3477                 if(TIMEDIFF(now, last) \
3478                                 > (xev? (1000/xfps) : (1000/actionfps))) {
3479                         dodraw = 1;
3480                         last = now;
3481                 }
3482
3483                 if(dodraw) {
3484                         while(XPending(xw.dpy)) {
3485                                 XNextEvent(xw.dpy, &ev);
3486                                 if(XFilterEvent(&ev, None))
3487                                         continue;
3488                                 if(handler[ev.type])
3489                                         (handler[ev.type])(&ev);
3490                         }
3491
3492                         draw();
3493                         XFlush(xw.dpy);
3494
3495                         if(xev && !FD_ISSET(xfd, &rfd))
3496                                 xev--;
3497                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3498                                 if(blinkset) {
3499                                         drawtimeout.tv_usec = 1000 * \
3500                                                 blinktimeout;
3501                                 } else {
3502                                         tv = NULL;
3503                                 }
3504                         }
3505                 }
3506         }
3507 }
3508
3509 void
3510 usage(void) {
3511         die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3512         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3513         " [-t title] [-w windowid] [-e command ...]\n", argv0);
3514 }
3515
3516 int
3517 main(int argc, char *argv[]) {
3518         int bitm, xr, yr;
3519         uint wr, hr;
3520
3521         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3522         xw.isfixed = False;
3523
3524         ARGBEGIN {
3525         case 'a':
3526                 allowaltscreen = false;
3527                 break;
3528         case 'c':
3529                 opt_class = EARGF(usage());
3530                 break;
3531         case 'e':
3532                 /* eat all remaining arguments */
3533                 if(argc > 1)
3534                         opt_cmd = &argv[1];
3535                 goto run;
3536         case 'f':
3537                 opt_font = EARGF(usage());
3538                 break;
3539         case 'g':
3540                 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3541                 if(bitm & XValue)
3542                         xw.fx = xr;
3543                 if(bitm & YValue)
3544                         xw.fy = yr;
3545                 if(bitm & WidthValue)
3546                         xw.fw = (int)wr;
3547                 if(bitm & HeightValue)
3548                         xw.fh = (int)hr;
3549                 if(bitm & XNegative && xw.fx == 0)
3550                         xw.fx = -1;
3551                 if(bitm & XNegative && xw.fy == 0)
3552                         xw.fy = -1;
3553
3554                 if(xw.fh != 0 && xw.fw != 0)
3555                         xw.isfixed = True;
3556                 break;
3557         case 'o':
3558                 opt_io = EARGF(usage());
3559                 break;
3560         case 't':
3561                 opt_title = EARGF(usage());
3562                 break;
3563         case 'w':
3564                 opt_embed = EARGF(usage());
3565                 break;
3566         case 'v':
3567         default:
3568                 usage();
3569         } ARGEND;
3570
3571 run:
3572         setlocale(LC_CTYPE, "");
3573         XSetLocaleModifiers("");
3574         tnew(80, 24);
3575         xinit();
3576         ttynew();
3577         selinit();
3578         if(xw.isfixed)
3579                 cresize(xw.h, xw.w);
3580         run();
3581
3582         return 0;
3583 }
3584