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