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