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