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