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