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