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