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