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