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