JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Remove all strcmp and strlen calls on Glyph.c[]
[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_FASTBLINK = 32,
99         ATTR_REVERSE   = 64,
100         ATTR_INVISIBLE = 128,
101         ATTR_STRUCK    = 256,
102         ATTR_WRAP      = 512,
103         ATTR_WIDE      = 1024,
104         ATTR_WDUMMY    = 2048,
105 };
106
107 enum cursor_movement {
108         CURSOR_SAVE,
109         CURSOR_LOAD
110 };
111
112 enum cursor_state {
113         CURSOR_DEFAULT  = 0,
114         CURSOR_WRAPNEXT = 1,
115         CURSOR_ORIGIN   = 2
116 };
117
118 enum term_mode {
119         MODE_WRAP        = 1,
120         MODE_INSERT      = 2,
121         MODE_APPKEYPAD   = 4,
122         MODE_ALTSCREEN   = 8,
123         MODE_CRLF        = 16,
124         MODE_MOUSEBTN    = 32,
125         MODE_MOUSEMOTION = 64,
126         MODE_REVERSE     = 128,
127         MODE_KBDLOCK     = 256,
128         MODE_HIDE        = 512,
129         MODE_ECHO        = 1024,
130         MODE_APPCURSOR   = 2048,
131         MODE_MOUSESGR    = 4096,
132         MODE_8BIT        = 8192,
133         MODE_BLINK       = 16384,
134         MODE_FBLINK      = 32768,
135         MODE_FOCUS       = 65536,
136         MODE_MOUSEX10    = 131072,
137         MODE_MOUSEMANY   = 262144,
138         MODE_BRCKTPASTE  = 524288,
139         MODE_PRINT       = 1048576,
140         MODE_MOUSE       = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
141                           |MODE_MOUSEMANY,
142 };
143
144 enum charset {
145         CS_GRAPHIC0,
146         CS_GRAPHIC1,
147         CS_UK,
148         CS_USA,
149         CS_MULTI,
150         CS_GER,
151         CS_FIN
152 };
153
154 enum escape_state {
155         ESC_START      = 1,
156         ESC_CSI        = 2,
157         ESC_STR        = 4,  /* DCS, OSC, PM, APC */
158         ESC_ALTCHARSET = 8,
159         ESC_STR_END    = 16, /* a final string was encountered */
160         ESC_TEST       = 32, /* Enter in test mode */
161 };
162
163 enum window_state {
164         WIN_VISIBLE = 1,
165         WIN_REDRAW  = 2,
166         WIN_FOCUSED = 4
167 };
168
169 enum selection_type {
170         SEL_REGULAR = 1,
171         SEL_RECTANGULAR = 2
172 };
173
174 enum selection_snap {
175         SNAP_WORD = 1,
176         SNAP_LINE = 2
177 };
178
179 typedef unsigned char uchar;
180 typedef unsigned int uint;
181 typedef unsigned long ulong;
182 typedef unsigned short ushort;
183
184 typedef XftDraw *Draw;
185 typedef XftColor Color;
186
187 typedef struct {
188         char c[UTF_SIZ]; /* character code */
189         ushort mode;      /* attribute flags */
190         uint32_t fg;      /* foreground  */
191         uint32_t bg;      /* background  */
192 } Glyph;
193
194 typedef Glyph *Line;
195
196 typedef struct {
197         Glyph attr; /* current char attributes */
198         int x;
199         int y;
200         char state;
201 } TCursor;
202
203 /* CSI Escape sequence structs */
204 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
205 typedef struct {
206         char buf[ESC_BUF_SIZ]; /* raw string */
207         int len;               /* raw string length */
208         char priv;
209         int arg[ESC_ARG_SIZ];
210         int narg;              /* nb of args */
211         char mode;
212 } CSIEscape;
213
214 /* STR Escape sequence structs */
215 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
216 typedef struct {
217         char type;             /* ESC type ... */
218         char buf[STR_BUF_SIZ]; /* raw string */
219         int len;               /* raw string length */
220         char *args[STR_ARG_SIZ];
221         int narg;              /* nb of args */
222 } STREscape;
223
224 /* Internal representation of the screen */
225 typedef struct {
226         int row;      /* nb row */
227         int col;      /* nb col */
228         Line *line;   /* screen */
229         Line *alt;    /* alternate screen */
230         bool *dirty;  /* dirtyness of lines */
231         TCursor c;    /* cursor */
232         int top;      /* top    scroll limit */
233         int bot;      /* bottom scroll limit */
234         int mode;     /* terminal mode flags */
235         int esc;      /* escape state flags */
236         char trantbl[4]; /* charset table translation */
237         int charset;  /* current charset */
238         int icharset; /* selected charset for sequence */
239         bool numlock; /* lock numbers in keyboard */
240         bool *tabs;
241 } Term;
242
243 /* Purely graphic info */
244 typedef struct {
245         Display *dpy;
246         Colormap cmap;
247         Window win;
248         Drawable buf;
249         Atom xembed, wmdeletewin, netwmname, netwmpid;
250         XIM xim;
251         XIC xic;
252         Draw draw;
253         Visual *vis;
254         XSetWindowAttributes attrs;
255         int scr;
256         bool isfixed; /* is fixed geometry? */
257         int l, t; /* left and top offset */
258         int gm; /* geometry mask */
259         int tw, th; /* tty width and height */
260         int w, h; /* window width and height */
261         int ch; /* char height */
262         int cw; /* char width  */
263         char state; /* focus, redraw, visible */
264 } XWindow;
265
266 typedef struct {
267         uint b;
268         uint mask;
269         char *s;
270 } Mousekey;
271
272 typedef struct {
273         KeySym k;
274         uint mask;
275         char *s;
276         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
277         signed char appkey;    /* application keypad */
278         signed char appcursor; /* application cursor */
279         signed char crlf;      /* crlf mode          */
280 } Key;
281
282 typedef struct {
283         int mode;
284         int type;
285         int snap;
286         /*
287          * Selection variables:
288          * nb – normalized coordinates of the beginning of the selection
289          * ne – normalized coordinates of the end of the selection
290          * ob – original coordinates of the beginning of the selection
291          * oe – original coordinates of the end of the selection
292          */
293         struct {
294                 int x, y;
295         } nb, ne, ob, oe;
296
297         char *clip;
298         Atom xtarget;
299         bool alt;
300         struct timespec tclick1;
301         struct timespec tclick2;
302 } Selection;
303
304 typedef union {
305         int i;
306         uint ui;
307         float f;
308         const void *v;
309 } Arg;
310
311 typedef struct {
312         uint mod;
313         KeySym keysym;
314         void (*func)(const Arg *);
315         const Arg arg;
316 } Shortcut;
317
318 /* function definitions used in config.h */
319 static void clippaste(const Arg *);
320 static void numlock(const Arg *);
321 static void selpaste(const Arg *);
322 static void xzoom(const Arg *);
323 static void printsel(const Arg *);
324 static void printscreen(const Arg *) ;
325 static void toggleprinter(const Arg *);
326
327 /* Config.h for applying patches and the configuration. */
328 #include "config.h"
329
330 /* Font structure */
331 typedef struct {
332         int height;
333         int width;
334         int ascent;
335         int descent;
336         short lbearing;
337         short rbearing;
338         XftFont *match;
339         FcFontSet *set;
340         FcPattern *pattern;
341 } Font;
342
343 /* Drawing Context */
344 typedef struct {
345         Color col[MAX(LEN(colorname), 256)];
346         Font font, bfont, ifont, ibfont;
347         GC gc;
348 } DC;
349
350 static void die(const char *, ...);
351 static void draw(void);
352 static void redraw(int);
353 static void drawregion(int, int, int, int);
354 static void execsh(void);
355 static void sigchld(int);
356 static void run(void);
357
358 static void csidump(void);
359 static void csihandle(void);
360 static void csiparse(void);
361 static void csireset(void);
362 static void strdump(void);
363 static void strhandle(void);
364 static void strparse(void);
365 static void strreset(void);
366
367 static int tattrset(int);
368 static void tprinter(char *, size_t);
369 static void tdumpsel(void);
370 static void tdumpline(int);
371 static void tdump(void);
372 static void tclearregion(int, int, int, int);
373 static void tcursor(int);
374 static void tdeletechar(int);
375 static void tdeleteline(int);
376 static void tinsertblank(int);
377 static void tinsertblankline(int);
378 static int tlinelen(int);
379 static void tmoveto(int, int);
380 static void tmoveato(int, int);
381 static void tnew(int, int);
382 static void tnewline(int);
383 static void tputtab(int);
384 static void tputc(char *, int);
385 static void treset(void);
386 static int tresize(int, int);
387 static void tscrollup(int, int);
388 static void tscrolldown(int, int);
389 static void tsetattr(int *, int);
390 static void tsetchar(char *, Glyph *, int, int);
391 static void tsetscroll(int, int);
392 static void tswapscreen(void);
393 static void tsetdirt(int, int);
394 static void tsetdirtattr(int);
395 static void tsetmode(bool, bool, int *, int);
396 static void tfulldirt(void);
397 static void techo(char *, int);
398 static void tcontrolcode(uchar );
399 static void tdectest(char );
400 static int32_t tdefcolor(int *, int *, int);
401 static void tdeftran(char);
402 static inline bool match(uint, uint);
403 static void ttynew(void);
404 static void ttyread(void);
405 static void ttyresize(void);
406 static void ttysend(char *, size_t);
407 static void ttywrite(const char *, size_t);
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_FASTBLINK  |
1687                                 ATTR_REVERSE    |
1688                                 ATTR_INVISIBLE  |
1689                                 ATTR_STRUCK     );
1690                         term.c.attr.fg = defaultfg;
1691                         term.c.attr.bg = defaultbg;
1692                         break;
1693                 case 1:
1694                         term.c.attr.mode |= ATTR_BOLD;
1695                         break;
1696                 case 2:
1697                         term.c.attr.mode |= ATTR_FAINT;
1698                         break;
1699                 case 3:
1700                         term.c.attr.mode |= ATTR_ITALIC;
1701                         break;
1702                 case 4:
1703                         term.c.attr.mode |= ATTR_UNDERLINE;
1704                         break;
1705                 case 5: /* slow blink */
1706                         term.c.attr.mode |= ATTR_BLINK;
1707                         break;
1708                 case 6: /* rapid blink */
1709                         term.c.attr.mode |= ATTR_FASTBLINK;
1710                         break;
1711                 case 7:
1712                         term.c.attr.mode |= ATTR_REVERSE;
1713                         break;
1714                 case 8:
1715                         term.c.attr.mode |= ATTR_INVISIBLE;
1716                         break;
1717                 case 9:
1718                         term.c.attr.mode |= ATTR_STRUCK;
1719                         break;
1720                 case 21:
1721                         term.c.attr.mode &= ~ATTR_BOLD;
1722                         break;
1723                 case 22:
1724                         term.c.attr.mode &= ~ATTR_FAINT;
1725                         break;
1726                 case 23:
1727                         term.c.attr.mode &= ~ATTR_ITALIC;
1728                         break;
1729                 case 24:
1730                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1731                         break;
1732                 case 25:
1733                         term.c.attr.mode &= ~ATTR_BLINK;
1734                         break;
1735                 case 26:
1736                         term.c.attr.mode &= ~ATTR_FASTBLINK;
1737                         break;
1738                 case 27:
1739                         term.c.attr.mode &= ~ATTR_REVERSE;
1740                         break;
1741                 case 28:
1742                         term.c.attr.mode &= ~ATTR_INVISIBLE;
1743                         break;
1744                 case 29:
1745                         term.c.attr.mode &= ~ATTR_STRUCK;
1746                         break;
1747                 case 38:
1748                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1749                                 term.c.attr.fg = idx;
1750                         break;
1751                 case 39:
1752                         term.c.attr.fg = defaultfg;
1753                         break;
1754                 case 48:
1755                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
1756                                 term.c.attr.bg = idx;
1757                         break;
1758                 case 49:
1759                         term.c.attr.bg = defaultbg;
1760                         break;
1761                 default:
1762                         if(BETWEEN(attr[i], 30, 37)) {
1763                                 term.c.attr.fg = attr[i] - 30;
1764                         } else if(BETWEEN(attr[i], 40, 47)) {
1765                                 term.c.attr.bg = attr[i] - 40;
1766                         } else if(BETWEEN(attr[i], 90, 97)) {
1767                                 term.c.attr.fg = attr[i] - 90 + 8;
1768                         } else if(BETWEEN(attr[i], 100, 107)) {
1769                                 term.c.attr.bg = attr[i] - 100 + 8;
1770                         } else {
1771                                 fprintf(stderr,
1772                                         "erresc(default): gfx attr %d unknown\n",
1773                                         attr[i]), csidump();
1774                         }
1775                         break;
1776                 }
1777         }
1778 }
1779
1780 void
1781 tsetscroll(int t, int b) {
1782         int temp;
1783
1784         LIMIT(t, 0, term.row-1);
1785         LIMIT(b, 0, term.row-1);
1786         if(t > b) {
1787                 temp = t;
1788                 t = b;
1789                 b = temp;
1790         }
1791         term.top = t;
1792         term.bot = b;
1793 }
1794
1795 void
1796 tsetmode(bool priv, bool set, int *args, int narg) {
1797         int *lim, mode;
1798         bool alt;
1799
1800         for(lim = args + narg; args < lim; ++args) {
1801                 if(priv) {
1802                         switch(*args) {
1803                         case 1: /* DECCKM -- Cursor key */
1804                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1805                                 break;
1806                         case 5: /* DECSCNM -- Reverse video */
1807                                 mode = term.mode;
1808                                 MODBIT(term.mode, set, MODE_REVERSE);
1809                                 if(mode != term.mode)
1810                                         redraw(REDRAW_TIMEOUT);
1811                                 break;
1812                         case 6: /* DECOM -- Origin */
1813                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1814                                 tmoveato(0, 0);
1815                                 break;
1816                         case 7: /* DECAWM -- Auto wrap */
1817                                 MODBIT(term.mode, set, MODE_WRAP);
1818                                 break;
1819                         case 0:  /* Error (IGNORED) */
1820                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1821                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1822                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1823                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1824                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1825                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1826                         case 42: /* DECNRCM -- National characters (IGNORED) */
1827                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1828                                 break;
1829                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1830                                 MODBIT(term.mode, !set, MODE_HIDE);
1831                                 break;
1832                         case 9:    /* X10 mouse compatibility mode */
1833                                 xsetpointermotion(0);
1834                                 MODBIT(term.mode, 0, MODE_MOUSE);
1835                                 MODBIT(term.mode, set, MODE_MOUSEX10);
1836                                 break;
1837                         case 1000: /* 1000: report button press */
1838                                 xsetpointermotion(0);
1839                                 MODBIT(term.mode, 0, MODE_MOUSE);
1840                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1841                                 break;
1842                         case 1002: /* 1002: report motion on button press */
1843                                 xsetpointermotion(0);
1844                                 MODBIT(term.mode, 0, MODE_MOUSE);
1845                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1846                                 break;
1847                         case 1003: /* 1003: enable all mouse motions */
1848                                 xsetpointermotion(set);
1849                                 MODBIT(term.mode, 0, MODE_MOUSE);
1850                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
1851                                 break;
1852                         case 1004: /* 1004: send focus events to tty */
1853                                 MODBIT(term.mode, set, MODE_FOCUS);
1854                                 break;
1855                         case 1006: /* 1006: extended reporting mode */
1856                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1857                                 break;
1858                         case 1034:
1859                                 MODBIT(term.mode, set, MODE_8BIT);
1860                                 break;
1861                         case 1049: /* swap screen & set/restore cursor as xterm */
1862                                 if (!allowaltscreen)
1863                                         break;
1864                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1865                                 /* FALLTHROUGH */
1866                         case 47: /* swap screen */
1867                         case 1047:
1868                                 if (!allowaltscreen)
1869                                         break;
1870                                 alt = IS_SET(MODE_ALTSCREEN);
1871                                 if(alt) {
1872                                         tclearregion(0, 0, term.col-1,
1873                                                         term.row-1);
1874                                 }
1875                                 if(set ^ alt) /* set is always 1 or 0 */
1876                                         tswapscreen();
1877                                 if(*args != 1049)
1878                                         break;
1879                                 /* FALLTHROUGH */
1880                         case 1048:
1881                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1882                                 break;
1883                         case 2004: /* 2004: bracketed paste mode */
1884                                 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1885                                 break;
1886                         /* Not implemented mouse modes. See comments there. */
1887                         case 1001: /* mouse highlight mode; can hang the
1888                                       terminal by design when implemented. */
1889                         case 1005: /* UTF-8 mouse mode; will confuse
1890                                       applications not supporting UTF-8
1891                                       and luit. */
1892                         case 1015: /* urxvt mangled mouse mode; incompatible
1893                                       and can be mistaken for other control
1894                                       codes. */
1895                         default:
1896                                 fprintf(stderr,
1897                                         "erresc: unknown private set/reset mode %d\n",
1898                                         *args);
1899                                 break;
1900                         }
1901                 } else {
1902                         switch(*args) {
1903                         case 0:  /* Error (IGNORED) */
1904                                 break;
1905                         case 2:  /* KAM -- keyboard action */
1906                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1907                                 break;
1908                         case 4:  /* IRM -- Insertion-replacement */
1909                                 MODBIT(term.mode, set, MODE_INSERT);
1910                                 break;
1911                         case 12: /* SRM -- Send/Receive */
1912                                 MODBIT(term.mode, !set, MODE_ECHO);
1913                                 break;
1914                         case 20: /* LNM -- Linefeed/new line */
1915                                 MODBIT(term.mode, set, MODE_CRLF);
1916                                 break;
1917                         default:
1918                                 fprintf(stderr,
1919                                         "erresc: unknown set/reset mode %d\n",
1920                                         *args);
1921                                 break;
1922                         }
1923                 }
1924         }
1925 }
1926
1927 void
1928 csihandle(void) {
1929         char buf[40];
1930         int len;
1931
1932         switch(csiescseq.mode) {
1933         default:
1934         unknown:
1935                 fprintf(stderr, "erresc: unknown csi ");
1936                 csidump();
1937                 /* die(""); */
1938                 break;
1939         case '@': /* ICH -- Insert <n> blank char */
1940                 DEFAULT(csiescseq.arg[0], 1);
1941                 tinsertblank(csiescseq.arg[0]);
1942                 break;
1943         case 'A': /* CUU -- Cursor <n> Up */
1944                 DEFAULT(csiescseq.arg[0], 1);
1945                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1946                 break;
1947         case 'B': /* CUD -- Cursor <n> Down */
1948         case 'e': /* VPR --Cursor <n> Down */
1949                 DEFAULT(csiescseq.arg[0], 1);
1950                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1951                 break;
1952         case 'i': /* MC -- Media Copy */
1953                 switch(csiescseq.arg[0]) {
1954                 case 0:
1955                         tdump();
1956                         break;
1957                 case 1:
1958                         tdumpline(term.c.y);
1959                         break;
1960                 case 2:
1961                         tdumpsel();
1962                         break;
1963                 case 4:
1964                         term.mode &= ~MODE_PRINT;
1965                         break;
1966                 case 5:
1967                         term.mode |= MODE_PRINT;
1968                         break;
1969                 }
1970                 break;
1971         case 'c': /* DA -- Device Attributes */
1972                 if(csiescseq.arg[0] == 0)
1973                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1974                 break;
1975         case 'C': /* CUF -- Cursor <n> Forward */
1976         case 'a': /* HPR -- Cursor <n> Forward */
1977                 DEFAULT(csiescseq.arg[0], 1);
1978                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1979                 break;
1980         case 'D': /* CUB -- Cursor <n> Backward */
1981                 DEFAULT(csiescseq.arg[0], 1);
1982                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1983                 break;
1984         case 'E': /* CNL -- Cursor <n> Down and first col */
1985                 DEFAULT(csiescseq.arg[0], 1);
1986                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1987                 break;
1988         case 'F': /* CPL -- Cursor <n> Up and first col */
1989                 DEFAULT(csiescseq.arg[0], 1);
1990                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1991                 break;
1992         case 'g': /* TBC -- Tabulation clear */
1993                 switch(csiescseq.arg[0]) {
1994                 case 0: /* clear current tab stop */
1995                         term.tabs[term.c.x] = 0;
1996                         break;
1997                 case 3: /* clear all the tabs */
1998                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1999                         break;
2000                 default:
2001                         goto unknown;
2002                 }
2003                 break;
2004         case 'G': /* CHA -- Move to <col> */
2005         case '`': /* HPA */
2006                 DEFAULT(csiescseq.arg[0], 1);
2007                 tmoveto(csiescseq.arg[0]-1, term.c.y);
2008                 break;
2009         case 'H': /* CUP -- Move to <row> <col> */
2010         case 'f': /* HVP */
2011                 DEFAULT(csiescseq.arg[0], 1);
2012                 DEFAULT(csiescseq.arg[1], 1);
2013                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2014                 break;
2015         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2016                 DEFAULT(csiescseq.arg[0], 1);
2017                 tputtab(csiescseq.arg[0]);
2018                 break;
2019         case 'J': /* ED -- Clear screen */
2020                 selclear(NULL);
2021                 switch(csiescseq.arg[0]) {
2022                 case 0: /* below */
2023                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2024                         if(term.c.y < term.row-1) {
2025                                 tclearregion(0, term.c.y+1, term.col-1,
2026                                                 term.row-1);
2027                         }
2028                         break;
2029                 case 1: /* above */
2030                         if(term.c.y > 1)
2031                                 tclearregion(0, 0, term.col-1, term.c.y-1);
2032                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2033                         break;
2034                 case 2: /* all */
2035                         tclearregion(0, 0, term.col-1, term.row-1);
2036                         break;
2037                 default:
2038                         goto unknown;
2039                 }
2040                 break;
2041         case 'K': /* EL -- Clear line */
2042                 switch(csiescseq.arg[0]) {
2043                 case 0: /* right */
2044                         tclearregion(term.c.x, term.c.y, term.col-1,
2045                                         term.c.y);
2046                         break;
2047                 case 1: /* left */
2048                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2049                         break;
2050                 case 2: /* all */
2051                         tclearregion(0, term.c.y, term.col-1, term.c.y);
2052                         break;
2053                 }
2054                 break;
2055         case 'S': /* SU -- Scroll <n> line up */
2056                 DEFAULT(csiescseq.arg[0], 1);
2057                 tscrollup(term.top, csiescseq.arg[0]);
2058                 break;
2059         case 'T': /* SD -- Scroll <n> line down */
2060                 DEFAULT(csiescseq.arg[0], 1);
2061                 tscrolldown(term.top, csiescseq.arg[0]);
2062                 break;
2063         case 'L': /* IL -- Insert <n> blank lines */
2064                 DEFAULT(csiescseq.arg[0], 1);
2065                 tinsertblankline(csiescseq.arg[0]);
2066                 break;
2067         case 'l': /* RM -- Reset Mode */
2068                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2069                 break;
2070         case 'M': /* DL -- Delete <n> lines */
2071                 DEFAULT(csiescseq.arg[0], 1);
2072                 tdeleteline(csiescseq.arg[0]);
2073                 break;
2074         case 'X': /* ECH -- Erase <n> char */
2075                 DEFAULT(csiescseq.arg[0], 1);
2076                 tclearregion(term.c.x, term.c.y,
2077                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2078                 break;
2079         case 'P': /* DCH -- Delete <n> char */
2080                 DEFAULT(csiescseq.arg[0], 1);
2081                 tdeletechar(csiescseq.arg[0]);
2082                 break;
2083         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2084                 DEFAULT(csiescseq.arg[0], 1);
2085                 tputtab(-csiescseq.arg[0]);
2086                 break;
2087         case 'd': /* VPA -- Move to <row> */
2088                 DEFAULT(csiescseq.arg[0], 1);
2089                 tmoveato(term.c.x, csiescseq.arg[0]-1);
2090                 break;
2091         case 'h': /* SM -- Set terminal mode */
2092                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2093                 break;
2094         case 'm': /* SGR -- Terminal attribute (color) */
2095                 tsetattr(csiescseq.arg, csiescseq.narg);
2096                 break;
2097         case 'n': /* DSR – Device Status Report (cursor position) */
2098                 if (csiescseq.arg[0] == 6) {
2099                         len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2100                                         term.c.y+1, term.c.x+1);
2101                         ttywrite(buf, len);
2102                 }
2103                 break;
2104         case 'r': /* DECSTBM -- Set Scrolling Region */
2105                 if(csiescseq.priv) {
2106                         goto unknown;
2107                 } else {
2108                         DEFAULT(csiescseq.arg[0], 1);
2109                         DEFAULT(csiescseq.arg[1], term.row);
2110                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2111                         tmoveato(0, 0);
2112                 }
2113                 break;
2114         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2115                 tcursor(CURSOR_SAVE);
2116                 break;
2117         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2118                 tcursor(CURSOR_LOAD);
2119                 break;
2120         }
2121 }
2122
2123 void
2124 csidump(void) {
2125         int i;
2126         uint c;
2127
2128         printf("ESC[");
2129         for(i = 0; i < csiescseq.len; i++) {
2130                 c = csiescseq.buf[i] & 0xff;
2131                 if(isprint(c)) {
2132                         putchar(c);
2133                 } else if(c == '\n') {
2134                         printf("(\\n)");
2135                 } else if(c == '\r') {
2136                         printf("(\\r)");
2137                 } else if(c == 0x1b) {
2138                         printf("(\\e)");
2139                 } else {
2140                         printf("(%02x)", c);
2141                 }
2142         }
2143         putchar('\n');
2144 }
2145
2146 void
2147 csireset(void) {
2148         memset(&csiescseq, 0, sizeof(csiescseq));
2149 }
2150
2151 void
2152 strhandle(void) {
2153         char *p = NULL;
2154         int j, narg, par;
2155
2156         term.esc &= ~(ESC_STR_END|ESC_STR);
2157         strparse();
2158         narg = strescseq.narg;
2159         par = atoi(strescseq.args[0]);
2160
2161         switch(strescseq.type) {
2162         case ']': /* OSC -- Operating System Command */
2163                 switch(par) {
2164                 case 0:
2165                 case 1:
2166                 case 2:
2167                         if(narg > 1)
2168                                 xsettitle(strescseq.args[1]);
2169                         return;
2170                 case 4: /* color set */
2171                         if(narg < 3)
2172                                 break;
2173                         p = strescseq.args[2];
2174                         /* FALLTHROUGH */
2175                 case 104: /* color reset, here p = NULL */
2176                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2177                         if(xsetcolorname(j, p)) {
2178                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2179                         } else {
2180                                 /*
2181                                  * TODO if defaultbg color is changed, borders
2182                                  * are dirty
2183                                  */
2184                                 redraw(0);
2185                         }
2186                         return;
2187                 }
2188                 break;
2189         case 'k': /* old title set compatibility */
2190                 xsettitle(strescseq.args[0]);
2191                 return;
2192         case 'P': /* DCS -- Device Control String */
2193         case '_': /* APC -- Application Program Command */
2194         case '^': /* PM -- Privacy Message */
2195                 return;
2196         }
2197
2198         fprintf(stderr, "erresc: unknown str ");
2199         strdump();
2200 }
2201
2202 void
2203 strparse(void) {
2204         char *p = strescseq.buf;
2205
2206         strescseq.narg = 0;
2207         strescseq.buf[strescseq.len] = '\0';
2208         while(p && strescseq.narg < STR_ARG_SIZ)
2209                 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2210 }
2211
2212 void
2213 strdump(void) {
2214         int i;
2215         uint c;
2216
2217         printf("ESC%c", strescseq.type);
2218         for(i = 0; i < strescseq.len; i++) {
2219                 c = strescseq.buf[i] & 0xff;
2220                 if(c == '\0') {
2221                         return;
2222                 } else if(isprint(c)) {
2223                         putchar(c);
2224                 } else if(c == '\n') {
2225                         printf("(\\n)");
2226                 } else if(c == '\r') {
2227                         printf("(\\r)");
2228                 } else if(c == 0x1b) {
2229                         printf("(\\e)");
2230                 } else {
2231                         printf("(%02x)", c);
2232                 }
2233         }
2234         printf("ESC\\\n");
2235 }
2236
2237 void
2238 strreset(void) {
2239         memset(&strescseq, 0, sizeof(strescseq));
2240 }
2241
2242 void
2243 tprinter(char *s, size_t len) {
2244         if(iofd != -1 && xwrite(iofd, s, len) < 0) {
2245                 fprintf(stderr, "Error writing in %s:%s\n",
2246                         opt_io, strerror(errno));
2247                 close(iofd);
2248                 iofd = -1;
2249         }
2250 }
2251
2252 void
2253 toggleprinter(const Arg *arg) {
2254         term.mode ^= MODE_PRINT;
2255 }
2256
2257 void
2258 printscreen(const Arg *arg) {
2259         tdump();
2260 }
2261
2262 void
2263 printsel(const Arg *arg) {
2264         tdumpsel();
2265 }
2266
2267 void
2268 tdumpsel(void) {
2269         char *ptr;
2270
2271         if((ptr = getsel())) {
2272                 tprinter(ptr, strlen(ptr));
2273                 free(ptr);
2274         }
2275 }
2276
2277 void
2278 tdumpline(int n) {
2279         Glyph *bp, *end;
2280
2281         bp = &term.line[n][0];
2282         end = &bp[MIN(tlinelen(n), term.col) - 1];
2283         if(bp != end || bp->c[0] != ' ') {
2284                 for( ;bp <= end; ++bp)
2285                         tprinter(bp->c, utf8len(bp->c));
2286         }
2287         tprinter("\n", 1);
2288 }
2289
2290 void
2291 tdump(void) {
2292         int i;
2293
2294         for(i = 0; i < term.row; ++i)
2295                 tdumpline(i);
2296 }
2297
2298 void
2299 tputtab(int n) {
2300         uint x = term.c.x;
2301
2302         if(n > 0) {
2303                 while(x < term.col && n--)
2304                         for(++x; x < term.col && !term.tabs[x]; ++x)
2305                                 /* nothing */ ;
2306         } else if(n < 0) {
2307                 while(x > 0 && n++)
2308                         for(--x; x > 0 && !term.tabs[x]; --x)
2309                                 /* nothing */ ;
2310         }
2311         tmoveto(x, term.c.y);
2312 }
2313
2314 void
2315 techo(char *buf, int len) {
2316         for(; len > 0; buf++, len--) {
2317                 char c = *buf;
2318
2319                 if(ISCONTROL(c)) { /* control code */
2320                         if(c & 0x80) {
2321                                 c &= 0x7f;
2322                                 tputc("^", 1);
2323                                 tputc("[", 1);
2324                         } else if(c != '\n' && c != '\r' && c != '\t') {
2325                                 c ^= '\x40';
2326                                 tputc("^", 1);
2327                         }
2328                         tputc(&c, 1);
2329                 } else {
2330                         break;
2331                 }
2332         }
2333         if(len)
2334                 tputc(buf, len);
2335 }
2336
2337 void
2338 tdeftran(char ascii) {
2339         static char cs[] = "0B";
2340         static int vcs[] = {CS_GRAPHIC0, CS_USA};
2341         char *p;
2342
2343         if((p = strchr(cs, ascii)) == NULL) {
2344                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2345         } else {
2346                 term.trantbl[term.icharset] = vcs[p - cs];
2347         }
2348 }
2349
2350 void
2351 tcontrolcode(uchar ascii) {
2352         static char question[UTF_SIZ] = "?";
2353
2354         switch(ascii) {
2355         case '\t':   /* HT */
2356                 tputtab(1);
2357                 return;
2358         case '\b':   /* BS */
2359                 tmoveto(term.c.x-1, term.c.y);
2360                 return;
2361         case '\r':   /* CR */
2362                 tmoveto(0, term.c.y);
2363                 return;
2364         case '\f':   /* LF */
2365         case '\v':   /* VT */
2366         case '\n':   /* LF */
2367                 /* go to first col if the mode is set */
2368                 tnewline(IS_SET(MODE_CRLF));
2369                 return;
2370         case '\a':   /* BEL */
2371                 if(term.esc & ESC_STR_END) {
2372                         /* backwards compatibility to xterm */
2373                         strhandle();
2374                 } else {
2375                         if(!(xw.state & WIN_FOCUSED))
2376                                 xseturgency(1);
2377                         if (bellvolume)
2378                                 XBell(xw.dpy, bellvolume);
2379                 }
2380                 break;
2381         case '\033': /* ESC */
2382                 csireset();
2383                 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2384                 term.esc |= ESC_START;
2385                 return;
2386         case '\016': /* SO */
2387                 term.charset = 0;
2388                 return;
2389         case '\017': /* SI */
2390                 term.charset = 1;
2391                 return;
2392         case '\032': /* SUB */
2393                 tsetchar(question, &term.c.attr, term.c.x, term.c.y);
2394         case '\030': /* CAN */
2395                 csireset();
2396                 break;
2397         case '\005': /* ENQ (IGNORED) */
2398         case '\000': /* NUL (IGNORED) */
2399         case '\021': /* XON (IGNORED) */
2400         case '\023': /* XOFF (IGNORED) */
2401         case 0177:   /* DEL (IGNORED) */
2402                 return;
2403         case 0x84:   /* TODO: IND */
2404         case 0x85:   /* TODO: NEL */
2405         case 0x88:   /* TODO: HTS */
2406         case 0x8d:   /* TODO: RI */
2407         case 0x8e:   /* TODO: SS2 */
2408         case 0x8f:   /* TODO: SS3 */
2409         case 0x90:   /* TODO: DCS */
2410         case 0x98:   /* TODO: SOS */
2411         case 0x9a:   /* TODO: DECID */
2412         case 0x9b:   /* TODO: CSI */
2413         case 0x9c:   /* TODO: ST */
2414         case 0x9d:   /* TODO: OSC */
2415         case 0x9e:   /* TODO: PM */
2416         case 0x9f:   /* TODO: APC */
2417                 break;
2418         }
2419         /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2420         term.esc &= ~(ESC_STR_END|ESC_STR);
2421         return;
2422 }
2423
2424 void
2425 tdectest(char c) {
2426         static char E[UTF_SIZ] = "E";
2427         int x, y;
2428
2429         if(c == '8') { /* DEC screen alignment test. */
2430                 for(x = 0; x < term.col; ++x) {
2431                         for(y = 0; y < term.row; ++y)
2432                                 tsetchar(E, &term.c.attr, x, y);
2433                 }
2434         }
2435 }
2436
2437 void
2438 tputc(char *c, int len) {
2439         uchar ascii;
2440         bool control;
2441         long unicodep;
2442         int width;
2443         Glyph *gp;
2444
2445         if(len == 1) {
2446                 width = 1;
2447                 unicodep = ascii = *c;
2448         } else {
2449                 utf8decode(c, &unicodep, UTF_SIZ);
2450                 width = wcwidth(unicodep);
2451                 control = ISCONTROLC1(unicodep);
2452                 ascii = unicodep;
2453         }
2454
2455         if(IS_SET(MODE_PRINT))
2456                 tprinter(c, len);
2457         control = ISCONTROL(unicodep);
2458
2459         /*
2460          * STR sequence must be checked before anything else
2461          * because it uses all following characters until it
2462          * receives a ESC, a SUB, a ST or any other C1 control
2463          * character.
2464          */
2465         if(term.esc & ESC_STR) {
2466                 if(width == 1 &&
2467                    (ascii == '\a' || ascii == 030 ||
2468                     ascii == 032  || ascii == 033 ||
2469                     ISCONTROLC1(unicodep))) {
2470                         term.esc &= ~(ESC_START|ESC_STR);
2471                         term.esc |= ESC_STR_END;
2472                 } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2473                         memmove(&strescseq.buf[strescseq.len], c, len);
2474                         strescseq.len += len;
2475                         return;
2476                 } else {
2477                 /*
2478                  * Here is a bug in terminals. If the user never sends
2479                  * some code to stop the str or esc command, then st
2480                  * will stop responding. But this is better than
2481                  * silently failing with unknown characters. At least
2482                  * then users will report back.
2483                  *
2484                  * In the case users ever get fixed, here is the code:
2485                  */
2486                 /*
2487                  * term.esc = 0;
2488                  * strhandle();
2489                  */
2490                         return;
2491                 }
2492         }
2493
2494         /*
2495          * Actions of control codes must be performed as soon they arrive
2496          * because they can be embedded inside a control sequence, and
2497          * they must not cause conflicts with sequences.
2498          */
2499         if(control) {
2500                 tcontrolcode(ascii);
2501                 /*
2502                  * control codes are not shown ever
2503                  */
2504                 return;
2505         } else if(term.esc & ESC_START) {
2506                 if(term.esc & ESC_CSI) {
2507                         csiescseq.buf[csiescseq.len++] = ascii;
2508                         if(BETWEEN(ascii, 0x40, 0x7E)
2509                                         || csiescseq.len >= \
2510                                         sizeof(csiescseq.buf)-1) {
2511                                 term.esc = 0;
2512                                 csiparse();
2513                                 csihandle();
2514                         }
2515                         return;
2516                 } else if(term.esc & ESC_ALTCHARSET) {
2517                         tdeftran(ascii);
2518                 } else if(term.esc & ESC_TEST) {
2519                         tdectest(ascii);
2520                 } else {
2521                         switch(ascii) {
2522                         case '[':
2523                                 term.esc |= ESC_CSI;
2524                                 return;
2525                         case '#':
2526                                 term.esc |= ESC_TEST;
2527                                 return;
2528                         case 'P': /* DCS -- Device Control String */
2529                         case '_': /* APC -- Application Program Command */
2530                         case '^': /* PM -- Privacy Message */
2531                         case ']': /* OSC -- Operating System Command */
2532                         case 'k': /* old title set compatibility */
2533                                 strreset();
2534                                 strescseq.type = ascii;
2535                                 term.esc |= ESC_STR;
2536                                 return;
2537                         case '(': /* set primary charset G0 */
2538                         case ')': /* set secondary charset G1 */
2539                         case '*': /* set tertiary charset G2 */
2540                         case '+': /* set quaternary charset G3 */
2541                                 term.icharset = ascii - '(';
2542                                 term.esc |= ESC_ALTCHARSET;
2543                                 return;
2544                         case 'D': /* IND -- Linefeed */
2545                                 if(term.c.y == term.bot) {
2546                                         tscrollup(term.top, 1);
2547                                 } else {
2548                                         tmoveto(term.c.x, term.c.y+1);
2549                                 }
2550                                 break;
2551                         case 'E': /* NEL -- Next line */
2552                                 tnewline(1); /* always go to first col */
2553                                 break;
2554                         case 'H': /* HTS -- Horizontal tab stop */
2555                                 term.tabs[term.c.x] = 1;
2556                                 break;
2557                         case 'M': /* RI -- Reverse index */
2558                                 if(term.c.y == term.top) {
2559                                         tscrolldown(term.top, 1);
2560                                 } else {
2561                                         tmoveto(term.c.x, term.c.y-1);
2562                                 }
2563                                 break;
2564                         case 'Z': /* DECID -- Identify Terminal */
2565                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2566                                 break;
2567                         case 'c': /* RIS -- Reset to inital state */
2568                                 treset();
2569                                 xresettitle();
2570                                 xloadcols();
2571                                 break;
2572                         case '=': /* DECPAM -- Application keypad */
2573                                 term.mode |= MODE_APPKEYPAD;
2574                                 break;
2575                         case '>': /* DECPNM -- Normal keypad */
2576                                 term.mode &= ~MODE_APPKEYPAD;
2577                                 break;
2578                         case '7': /* DECSC -- Save Cursor */
2579                                 tcursor(CURSOR_SAVE);
2580                                 break;
2581                         case '8': /* DECRC -- Restore Cursor */
2582                                 tcursor(CURSOR_LOAD);
2583                                 break;
2584                         case '\\': /* ST -- String Terminator */
2585                                 if(term.esc & ESC_STR_END)
2586                                         strhandle();
2587                                 break;
2588                         default:
2589                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2590                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2591                                 break;
2592                         }
2593                 }
2594                 term.esc = 0;
2595                 /*
2596                  * All characters which form part of a sequence are not
2597                  * printed
2598                  */
2599                 return;
2600         }
2601         if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2602                 selclear(NULL);
2603
2604         gp = &term.line[term.c.y][term.c.x];
2605         if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2606                 gp->mode |= ATTR_WRAP;
2607                 tnewline(1);
2608         }
2609
2610         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col)
2611                 memmove(gp+1, gp, (term.col - term.c.x - 1) * sizeof(Glyph));
2612
2613         if(term.c.x+width > term.col)
2614                 tnewline(1);
2615
2616         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2617
2618         if(width == 2) {
2619                 gp->mode |= ATTR_WIDE;
2620                 if(term.c.x+1 < term.col) {
2621                         gp[1].c[0] = '\0';
2622                         gp[1].mode = ATTR_WDUMMY;
2623                 }
2624         }
2625         if(term.c.x+width < term.col) {
2626                 tmoveto(term.c.x+width, term.c.y);
2627         } else {
2628                 term.c.state |= CURSOR_WRAPNEXT;
2629         }
2630 }
2631
2632 int
2633 tresize(int col, int row) {
2634         int i;
2635         int minrow = MIN(row, term.row);
2636         int mincol = MIN(col, term.col);
2637         int slide = term.c.y - row + 1;
2638         bool *bp;
2639         Line *orig;
2640         TCursor c;
2641
2642         if(col < 1 || row < 1)
2643                 return 0;
2644
2645         /* free unneeded rows */
2646         i = 0;
2647         if(slide > 0) {
2648                 /*
2649                  * slide screen to keep cursor where we expect it -
2650                  * tscrollup would work here, but we can optimize to
2651                  * memmove because we're freeing the earlier lines
2652                  */
2653                 for(/* i = 0 */; i < slide; i++) {
2654                         free(term.line[i]);
2655                         free(term.alt[i]);
2656                 }
2657                 memmove(term.line, term.line + slide, row * sizeof(Line));
2658                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2659         }
2660         for(i += row; i < term.row; i++) {
2661                 free(term.line[i]);
2662                 free(term.alt[i]);
2663         }
2664
2665         /* resize to new height */
2666         term.line = xrealloc(term.line, row * sizeof(Line));
2667         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2668         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2669         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2670
2671         /* resize each row to new width, zero-pad if needed */
2672         for(i = 0; i < minrow; i++) {
2673                 term.dirty[i] = 1;
2674                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2675                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2676         }
2677
2678         /* allocate any new rows */
2679         for(/* i == minrow */; i < row; i++) {
2680                 term.dirty[i] = 1;
2681                 term.line[i] = xmalloc(col * sizeof(Glyph));
2682                 term.alt[i] = xmalloc(col * sizeof(Glyph));
2683         }
2684         if(col > term.col) {
2685                 bp = term.tabs + term.col;
2686
2687                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2688                 while(--bp > term.tabs && !*bp)
2689                         /* nothing */ ;
2690                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2691                         *bp = 1;
2692         }
2693         /* update terminal size */
2694         term.col = col;
2695         term.row = row;
2696         /* reset scrolling region */
2697         tsetscroll(0, row-1);
2698         /* make use of the LIMIT in tmoveto */
2699         tmoveto(term.c.x, term.c.y);
2700         /* Clearing both screens */
2701         orig = term.line;
2702         c = term.c;
2703         do {
2704                 if(mincol < col && 0 < minrow) {
2705                         tclearregion(mincol, 0, col - 1, minrow - 1);
2706                 }
2707                 if(0 < col && minrow < row) {
2708                         tclearregion(0, minrow, col - 1, row - 1);
2709                 }
2710                 tswapscreen();
2711                 tcursor(CURSOR_LOAD);
2712         } while(orig != term.line);
2713         term.c = c;
2714
2715         return (slide > 0);
2716 }
2717
2718 void
2719 xresize(int col, int row) {
2720         xw.tw = MAX(1, col * xw.cw);
2721         xw.th = MAX(1, row * xw.ch);
2722
2723         XFreePixmap(xw.dpy, xw.buf);
2724         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2725                         DefaultDepth(xw.dpy, xw.scr));
2726         XftDrawChange(xw.draw, xw.buf);
2727         xclear(0, 0, xw.w, xw.h);
2728 }
2729
2730 static inline ushort
2731 sixd_to_16bit(int x) {
2732         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2733 }
2734
2735 void
2736 xloadcols(void) {
2737         int i;
2738         XRenderColor color = { .alpha = 0xffff };
2739         static bool loaded;
2740         Color *cp;
2741
2742         if(loaded) {
2743                 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2744                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2745         }
2746
2747         /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
2748         for(i = 0; i < LEN(colorname); i++) {
2749                 if(!colorname[i])
2750                         continue;
2751                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2752                         die("Could not allocate color '%s'\n", colorname[i]);
2753                 }
2754         }
2755
2756         /* load colors [16-231] ; same colors as xterm */
2757         for(i = 16; i < 6*6*6+16; i++) {
2758                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
2759                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
2760                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
2761                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2762                         die("Could not allocate color %d\n", i);
2763         }
2764
2765         /* load colors [232-255] ; grayscale */
2766         for(; i < 256; i++) {
2767                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
2768                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
2769                         die("Could not allocate color %d\n", i);
2770         }
2771         loaded = true;
2772 }
2773
2774 int
2775 xsetcolorname(int x, const char *name) {
2776         XRenderColor color = { .alpha = 0xffff };
2777         Color ncolor;
2778
2779         if(!BETWEEN(x, 0, LEN(colorname)))
2780                 return 1;
2781
2782         if(!name) {
2783                 if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
2784                         color.red   = sixd_to_16bit( ((x-16)/36)%6 );
2785                         color.green = sixd_to_16bit( ((x-16)/6) %6 );
2786                         color.blue  = sixd_to_16bit( ((x-16)/1) %6 );
2787                         if(!XftColorAllocValue(xw.dpy, xw.vis,
2788                                                 xw.cmap, &color, &ncolor)) {
2789                                 return 1;
2790                         }
2791
2792                         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2793                         dc.col[x] = ncolor;
2794                         return 0;
2795                 } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
2796                         color.red = color.green = color.blue = \
2797                                     0x0808 + 0x0a0a * (x - (16 + 216));
2798                         if(!XftColorAllocValue(xw.dpy, xw.vis,
2799                                                 xw.cmap, &color, &ncolor)) {
2800                                 return 1;
2801                         }
2802
2803                         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2804                         dc.col[x] = ncolor;
2805                         return 0;
2806                 } else { /* system colors */
2807                         name = colorname[x];
2808                 }
2809         }
2810         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
2811                 return 1;
2812
2813         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
2814         dc.col[x] = ncolor;
2815         return 0;
2816 }
2817
2818 void
2819 xtermclear(int col1, int row1, int col2, int row2) {
2820         XftDrawRect(xw.draw,
2821                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2822                         borderpx + col1 * xw.cw,
2823                         borderpx + row1 * xw.ch,
2824                         (col2-col1+1) * xw.cw,
2825                         (row2-row1+1) * xw.ch);
2826 }
2827
2828 /*
2829  * Absolute coordinates.
2830  */
2831 void
2832 xclear(int x1, int y1, int x2, int y2) {
2833         XftDrawRect(xw.draw,
2834                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2835                         x1, y1, x2-x1, y2-y1);
2836 }
2837
2838 void
2839 xhints(void) {
2840         XClassHint class = {opt_class ? opt_class : termname, termname};
2841         XWMHints wm = {.flags = InputHint, .input = 1};
2842         XSizeHints *sizeh = NULL;
2843
2844         sizeh = XAllocSizeHints();
2845
2846         sizeh->flags = PSize | PResizeInc | PBaseSize;
2847         sizeh->height = xw.h;
2848         sizeh->width = xw.w;
2849         sizeh->height_inc = xw.ch;
2850         sizeh->width_inc = xw.cw;
2851         sizeh->base_height = 2 * borderpx;
2852         sizeh->base_width = 2 * borderpx;
2853         if(xw.isfixed == True) {
2854                 sizeh->flags |= PMaxSize | PMinSize;
2855                 sizeh->min_width = sizeh->max_width = xw.w;
2856                 sizeh->min_height = sizeh->max_height = xw.h;
2857         }
2858         if(xw.gm & (XValue|YValue)) {
2859                 sizeh->flags |= USPosition | PWinGravity;
2860                 sizeh->x = xw.l;
2861                 sizeh->y = xw.t;
2862                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
2863         }
2864
2865         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
2866                         &class);
2867         XFree(sizeh);
2868 }
2869
2870 int
2871 xgeommasktogravity(int mask) {
2872         switch(mask & (XNegative|YNegative)) {
2873         case 0:
2874                 return NorthWestGravity;
2875         case XNegative:
2876                 return NorthEastGravity;
2877         case YNegative:
2878                 return SouthWestGravity;
2879         }
2880         return SouthEastGravity;
2881 }
2882
2883 int
2884 xloadfont(Font *f, FcPattern *pattern) {
2885         FcPattern *match;
2886         FcResult result;
2887
2888         match = FcFontMatch(NULL, pattern, &result);
2889         if(!match)
2890                 return 1;
2891
2892         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2893                 FcPatternDestroy(match);
2894                 return 1;
2895         }
2896
2897         f->set = NULL;
2898         f->pattern = FcPatternDuplicate(pattern);
2899
2900         f->ascent = f->match->ascent;
2901         f->descent = f->match->descent;
2902         f->lbearing = 0;
2903         f->rbearing = f->match->max_advance_width;
2904
2905         f->height = f->ascent + f->descent;
2906         f->width = f->lbearing + f->rbearing;
2907
2908         return 0;
2909 }
2910
2911 void
2912 xloadfonts(char *fontstr, double fontsize) {
2913         FcPattern *pattern;
2914         FcResult r_sz, r_psz;
2915         double fontval;
2916         float ceilf(float);
2917
2918         if(fontstr[0] == '-') {
2919                 pattern = XftXlfdParse(fontstr, False, False);
2920         } else {
2921                 pattern = FcNameParse((FcChar8 *)fontstr);
2922         }
2923
2924         if(!pattern)
2925                 die("st: can't open font %s\n", fontstr);
2926
2927         if(fontsize > 0) {
2928                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2929                 FcPatternDel(pattern, FC_SIZE);
2930                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2931                 usedfontsize = fontsize;
2932         } else {
2933                 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2934                 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2935                 if(r_psz == FcResultMatch) {
2936                         usedfontsize = fontval;
2937                 } else if(r_sz == FcResultMatch) {
2938                         usedfontsize = -1;
2939                 } else {
2940                         /*
2941                          * Default font size is 12, if none given. This is to
2942                          * have a known usedfontsize value.
2943                          */
2944                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2945                         usedfontsize = 12;
2946                 }
2947         }
2948
2949         FcConfigSubstitute(0, pattern, FcMatchPattern);
2950         FcDefaultSubstitute(pattern);
2951
2952         if(xloadfont(&dc.font, pattern))
2953                 die("st: can't open font %s\n", fontstr);
2954
2955         if(usedfontsize < 0) {
2956                 FcPatternGetDouble(dc.font.match->pattern,
2957                                    FC_PIXEL_SIZE, 0, &fontval);
2958                 usedfontsize = fontval;
2959         }
2960
2961         /* Setting character width and height. */
2962         xw.cw = ceilf(dc.font.width * cwscale);
2963         xw.ch = ceilf(dc.font.height * chscale);
2964
2965         FcPatternDel(pattern, FC_SLANT);
2966         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2967         if(xloadfont(&dc.ifont, pattern))
2968                 die("st: can't open font %s\n", fontstr);
2969
2970         FcPatternDel(pattern, FC_WEIGHT);
2971         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2972         if(xloadfont(&dc.ibfont, pattern))
2973                 die("st: can't open font %s\n", fontstr);
2974
2975         FcPatternDel(pattern, FC_SLANT);
2976         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2977         if(xloadfont(&dc.bfont, pattern))
2978                 die("st: can't open font %s\n", fontstr);
2979
2980         FcPatternDestroy(pattern);
2981 }
2982
2983 int
2984 xloadfontset(Font *f) {
2985         FcResult result;
2986
2987         if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2988                 return 1;
2989         return 0;
2990 }
2991
2992 void
2993 xunloadfont(Font *f) {
2994         XftFontClose(xw.dpy, f->match);
2995         FcPatternDestroy(f->pattern);
2996         if(f->set)
2997                 FcFontSetDestroy(f->set);
2998 }
2999
3000 void
3001 xunloadfonts(void) {
3002         /* Free the loaded fonts in the font cache.  */
3003         while(frclen > 0)
3004                 XftFontClose(xw.dpy, frc[--frclen].font);
3005
3006         xunloadfont(&dc.font);
3007         xunloadfont(&dc.bfont);
3008         xunloadfont(&dc.ifont);
3009         xunloadfont(&dc.ibfont);
3010 }
3011
3012 void
3013 xzoom(const Arg *arg) {
3014         xunloadfonts();
3015         xloadfonts(usedfont, usedfontsize + arg->i);
3016         cresize(0, 0);
3017         redraw(0);
3018         xhints();
3019 }
3020
3021 void
3022 xinit(void) {
3023         XGCValues gcvalues;
3024         Cursor cursor;
3025         Window parent;
3026         pid_t thispid = getpid();
3027
3028         if(!(xw.dpy = XOpenDisplay(NULL)))
3029                 die("Can't open display\n");
3030         xw.scr = XDefaultScreen(xw.dpy);
3031         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3032
3033         /* font */
3034         if(!FcInit())
3035                 die("Could not init fontconfig.\n");
3036
3037         usedfont = (opt_font == NULL)? font : opt_font;
3038         xloadfonts(usedfont, 0);
3039
3040         /* colors */
3041         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3042         xloadcols();
3043
3044         /* adjust fixed window geometry */
3045         xw.w = 2 * borderpx + term.col * xw.cw;
3046         xw.h = 2 * borderpx + term.row * xw.ch;
3047         if(xw.gm & XNegative)
3048                 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3049         if(xw.gm & YNegative)
3050                 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3051
3052         /* Events */
3053         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3054         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3055         xw.attrs.bit_gravity = NorthWestGravity;
3056         xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3057                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3058                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3059         xw.attrs.colormap = xw.cmap;
3060
3061         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
3062                         XRootWindow(xw.dpy, xw.scr);
3063         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3064                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3065                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3066                         | CWEventMask | CWColormap, &xw.attrs);
3067
3068         memset(&gcvalues, 0, sizeof(gcvalues));
3069         gcvalues.graphics_exposures = False;
3070         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3071                         &gcvalues);
3072         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3073                         DefaultDepth(xw.dpy, xw.scr));
3074         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3075         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3076
3077         /* Xft rendering context */
3078         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3079
3080         /* input methods */
3081         if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3082                 XSetLocaleModifiers("@im=local");
3083                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3084                         XSetLocaleModifiers("@im=");
3085                         if((xw.xim = XOpenIM(xw.dpy,
3086                                         NULL, NULL, NULL)) == NULL) {
3087                                 die("XOpenIM failed. Could not open input"
3088                                         " device.\n");
3089                         }
3090                 }
3091         }
3092         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3093                                            | XIMStatusNothing, XNClientWindow, xw.win,
3094                                            XNFocusWindow, xw.win, NULL);
3095         if(xw.xic == NULL)
3096                 die("XCreateIC failed. Could not obtain input method.\n");
3097
3098         /* white cursor, black outline */
3099         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3100         XDefineCursor(xw.dpy, xw.win, cursor);
3101         XRecolorCursor(xw.dpy, cursor,
3102                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3103                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3104
3105         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3106         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3107         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3108         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3109
3110         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3111         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3112                         PropModeReplace, (uchar *)&thispid, 1);
3113
3114         xresettitle();
3115         XMapWindow(xw.dpy, xw.win);
3116         xhints();
3117         XSync(xw.dpy, False);
3118 }
3119
3120 void
3121 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3122         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3123             width = charlen * xw.cw, xp, i;
3124         int frcflags;
3125         int u8fl, u8fblen, u8cblen, doesexist;
3126         char *u8c, *u8fs;
3127         long unicodep;
3128         Font *font = &dc.font;
3129         FcResult fcres;
3130         FcPattern *fcpattern, *fontpattern;
3131         FcFontSet *fcsets[] = { NULL };
3132         FcCharSet *fccharset;
3133         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3134         XRenderColor colfg, colbg;
3135         XRectangle r;
3136         int oneatatime;
3137
3138         frcflags = FRC_NORMAL;
3139
3140         if(base.mode & ATTR_ITALIC) {
3141                 if(base.fg == defaultfg)
3142                         base.fg = defaultitalic;
3143                 font = &dc.ifont;
3144                 frcflags = FRC_ITALIC;
3145         } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3146                 if(base.fg == defaultfg)
3147                         base.fg = defaultitalic;
3148                 font = &dc.ibfont;
3149                 frcflags = FRC_ITALICBOLD;
3150         } else if(base.mode & ATTR_UNDERLINE) {
3151                 if(base.fg == defaultfg)
3152                         base.fg = defaultunderline;
3153         }
3154
3155         if(IS_TRUECOL(base.fg)) {
3156                 colfg.alpha = 0xffff;
3157                 colfg.red = TRUERED(base.fg);
3158                 colfg.green = TRUEGREEN(base.fg);
3159                 colfg.blue = TRUEBLUE(base.fg);
3160                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3161                 fg = &truefg;
3162         } else {
3163                 fg = &dc.col[base.fg];
3164         }
3165
3166         if(IS_TRUECOL(base.bg)) {
3167                 colbg.alpha = 0xffff;
3168                 colbg.green = TRUEGREEN(base.bg);
3169                 colbg.red = TRUERED(base.bg);
3170                 colbg.blue = TRUEBLUE(base.bg);
3171                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3172                 bg = &truebg;
3173         } else {
3174                 bg = &dc.col[base.bg];
3175         }
3176
3177         if(base.mode & ATTR_BOLD) {
3178                 /*
3179                  * change basic system colors [0-7]
3180                  * to bright system colors [8-15]
3181                  */
3182                 if(BETWEEN(base.fg, 0, 7))
3183                         fg = &dc.col[base.fg + 8];
3184
3185                 if(base.mode & ATTR_ITALIC) {
3186                         font = &dc.ibfont;
3187                         frcflags = FRC_ITALICBOLD;
3188                 } else {
3189                         font = &dc.bfont;
3190                         frcflags = FRC_BOLD;
3191                 }
3192         }
3193
3194         if(IS_SET(MODE_REVERSE)) {
3195                 if(fg == &dc.col[defaultfg]) {
3196                         fg = &dc.col[defaultbg];
3197                 } else {
3198                         colfg.red = ~fg->color.red;
3199                         colfg.green = ~fg->color.green;
3200                         colfg.blue = ~fg->color.blue;
3201                         colfg.alpha = fg->color.alpha;
3202                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3203                                         &revfg);
3204                         fg = &revfg;
3205                 }
3206
3207                 if(bg == &dc.col[defaultbg]) {
3208                         bg = &dc.col[defaultfg];
3209                 } else {
3210                         colbg.red = ~bg->color.red;
3211                         colbg.green = ~bg->color.green;
3212                         colbg.blue = ~bg->color.blue;
3213                         colbg.alpha = bg->color.alpha;
3214                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3215                                         &revbg);
3216                         bg = &revbg;
3217                 }
3218         }
3219
3220         if(base.mode & ATTR_REVERSE) {
3221                 temp = fg;
3222                 fg = bg;
3223                 bg = temp;
3224         }
3225
3226         if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3227                 fg = bg;
3228
3229         if(base.mode & ATTR_INVISIBLE)
3230                 fg = bg;
3231
3232         /* Intelligent cleaning up of the borders. */
3233         if(x == 0) {
3234                 xclear(0, (y == 0)? 0 : winy, borderpx,
3235                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3236         }
3237         if(x + charlen >= term.col) {
3238                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3239                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3240         }
3241         if(y == 0)
3242                 xclear(winx, 0, winx + width, borderpx);
3243         if(y == term.row-1)
3244                 xclear(winx, winy + xw.ch, winx + width, xw.h);
3245
3246         /* Clean up the region we want to draw to. */
3247         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3248
3249         /* Set the clip region because Xft is sometimes dirty. */
3250         r.x = 0;
3251         r.y = 0;
3252         r.height = xw.ch;
3253         r.width = width;
3254         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3255
3256         for(xp = winx; bytelen > 0;) {
3257                 /*
3258                  * Search for the range in the to be printed string of glyphs
3259                  * that are in the main font. Then print that range. If
3260                  * some glyph is found that is not in the font, do the
3261                  * fallback dance.
3262                  */
3263                 u8fs = s;
3264                 u8fblen = 0;
3265                 u8fl = 0;
3266                 oneatatime = font->width != xw.cw;
3267                 for(;;) {
3268                         u8c = s;
3269                         u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
3270                         s += u8cblen;
3271                         bytelen -= u8cblen;
3272
3273                         doesexist = XftCharExists(xw.dpy, font->match, unicodep);
3274                         if(doesexist) {
3275                                         u8fl++;
3276                                         u8fblen += u8cblen;
3277                                         if(!oneatatime && bytelen > 0)
3278                                                         continue;
3279                         }
3280
3281                         if(u8fl > 0) {
3282                                 XftDrawStringUtf8(xw.draw, fg,
3283                                                 font->match, xp,
3284                                                 winy + font->ascent,
3285                                                 (FcChar8 *)u8fs,
3286                                                 u8fblen);
3287                                 xp += xw.cw * u8fl;
3288                         }
3289                         break;
3290                 }
3291                 if(doesexist) {
3292                         if(oneatatime)
3293                                 continue;
3294                         break;
3295                 }
3296
3297                 /* Search the font cache. */
3298                 for(i = 0; i < frclen; i++) {
3299                         if(XftCharExists(xw.dpy, frc[i].font, unicodep)
3300                                         && frc[i].flags == frcflags) {
3301                                 break;
3302                         }
3303                 }
3304
3305                 /* Nothing was found. */
3306                 if(i >= frclen) {
3307                         if(!font->set)
3308                                 xloadfontset(font);
3309                         fcsets[0] = font->set;
3310
3311                         /*
3312                          * Nothing was found in the cache. Now use
3313                          * some dozen of Fontconfig calls to get the
3314                          * font for one single character.
3315                          *
3316                          * Xft and fontconfig are design failures.
3317                          */
3318                         fcpattern = FcPatternDuplicate(font->pattern);
3319                         fccharset = FcCharSetCreate();
3320
3321                         FcCharSetAddChar(fccharset, unicodep);
3322                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3323                                         fccharset);
3324                         FcPatternAddBool(fcpattern, FC_SCALABLE,
3325                                         FcTrue);
3326
3327                         FcConfigSubstitute(0, fcpattern,
3328                                         FcMatchPattern);
3329                         FcDefaultSubstitute(fcpattern);
3330
3331                         fontpattern = FcFontSetMatch(0, fcsets,
3332                                         FcTrue, fcpattern, &fcres);
3333
3334                         /*
3335                          * Overwrite or create the new cache entry.
3336                          */
3337                         if(frclen >= LEN(frc)) {
3338                                 frclen = LEN(frc) - 1;
3339                                 XftFontClose(xw.dpy, frc[frclen].font);
3340                         }
3341
3342                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
3343                                         fontpattern);
3344                         frc[frclen].flags = frcflags;
3345
3346                         i = frclen;
3347                         frclen++;
3348
3349                         FcPatternDestroy(fcpattern);
3350                         FcCharSetDestroy(fccharset);
3351                 }
3352
3353                 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3354                                 xp, winy + frc[i].font->ascent,
3355                                 (FcChar8 *)u8c, u8cblen);
3356
3357                 xp += xw.cw * wcwidth(unicodep);
3358         }
3359
3360         /*
3361          * This is how the loop above actually should be. Why does the
3362          * application have to care about font details?
3363          *
3364          * I have to repeat: Xft and Fontconfig are design failures.
3365          */
3366         /*
3367         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3368                         winy + font->ascent, (FcChar8 *)s, bytelen);
3369         */
3370
3371         if(base.mode & ATTR_UNDERLINE) {
3372                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3373                                 width, 1);
3374         }
3375
3376         if(base.mode & ATTR_STRUCK) {
3377                 XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
3378                                 width, 1);
3379         }
3380
3381         /* Reset clip to none. */
3382         XftDrawSetClip(xw.draw, 0);
3383 }
3384
3385 void
3386 xdrawcursor(void) {
3387         static int oldx = 0, oldy = 0;
3388         int sl, width, curx;
3389         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3390
3391         LIMIT(oldx, 0, term.col-1);
3392         LIMIT(oldy, 0, term.row-1);
3393
3394         curx = term.c.x;
3395
3396         /* adjust position if in dummy */
3397         if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3398                 oldx--;
3399         if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3400                 curx--;
3401
3402         memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3403
3404         /* remove the old cursor */
3405         sl = utf8len(term.line[oldy][oldx].c);
3406         width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3407         xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3408                         oldy, width, sl);
3409
3410         /* draw the new one */
3411         if(!(IS_SET(MODE_HIDE))) {
3412                 if(xw.state & WIN_FOCUSED) {
3413                         if(IS_SET(MODE_REVERSE)) {
3414                                 g.mode |= ATTR_REVERSE;
3415                                 g.fg = defaultcs;
3416                                 g.bg = defaultfg;
3417                         }
3418
3419                         sl = utf8len(g.c);
3420                         width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3421                                 ? 2 : 1;
3422                         xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3423                 } else {
3424                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3425                                         borderpx + curx * xw.cw,
3426                                         borderpx + term.c.y * xw.ch,
3427                                         xw.cw - 1, 1);
3428                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3429                                         borderpx + curx * xw.cw,
3430                                         borderpx + term.c.y * xw.ch,
3431                                         1, xw.ch - 1);
3432                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3433                                         borderpx + (curx + 1) * xw.cw - 1,
3434                                         borderpx + term.c.y * xw.ch,
3435                                         1, xw.ch - 1);
3436                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3437                                         borderpx + curx * xw.cw,
3438                                         borderpx + (term.c.y + 1) * xw.ch - 1,
3439                                         xw.cw, 1);
3440                 }
3441                 oldx = curx, oldy = term.c.y;
3442         }
3443 }
3444
3445
3446 void
3447 xsettitle(char *p) {
3448         XTextProperty prop;
3449
3450         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3451                         &prop);
3452         XSetWMName(xw.dpy, xw.win, &prop);
3453         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3454         XFree(prop.value);
3455 }
3456
3457 void
3458 xresettitle(void) {
3459         xsettitle(opt_title ? opt_title : "st");
3460 }
3461
3462 void
3463 redraw(int timeout) {
3464         struct timespec tv = {0, timeout * 1000};
3465
3466         tfulldirt();
3467         draw();
3468
3469         if(timeout > 0) {
3470                 nanosleep(&tv, NULL);
3471                 XSync(xw.dpy, False); /* necessary for a good tput flash */
3472         }
3473 }
3474
3475 void
3476 draw(void) {
3477         drawregion(0, 0, term.col, term.row);
3478         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3479                         xw.h, 0, 0);
3480         XSetForeground(xw.dpy, dc.gc,
3481                         dc.col[IS_SET(MODE_REVERSE)?
3482                                 defaultfg : defaultbg].pixel);
3483 }
3484
3485 void
3486 drawregion(int x1, int y1, int x2, int y2) {
3487         int ic, ib, x, y, ox, sl;
3488         Glyph base, new;
3489         char buf[DRAW_BUF_SIZ];
3490         bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3491         long unicodep;
3492
3493         if(!(xw.state & WIN_VISIBLE))
3494                 return;
3495
3496         for(y = y1; y < y2; y++) {
3497                 if(!term.dirty[y])
3498                         continue;
3499
3500                 xtermclear(0, y, term.col, y);
3501                 term.dirty[y] = 0;
3502                 base = term.line[y][0];
3503                 ic = ib = ox = 0;
3504                 for(x = x1; x < x2; x++) {
3505                         new = term.line[y][x];
3506                         if(new.mode == ATTR_WDUMMY)
3507                                 continue;
3508                         if(ena_sel && selected(x, y))
3509                                 new.mode ^= ATTR_REVERSE;
3510                         if(ib > 0 && (ATTRCMP(base, new)
3511                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3512                                 xdraws(buf, base, ox, y, ic, ib);
3513                                 ic = ib = 0;
3514                         }
3515                         if(ib == 0) {
3516                                 ox = x;
3517                                 base = new;
3518                         }
3519
3520                         sl = utf8decode(new.c, &unicodep, UTF_SIZ);
3521                         memcpy(buf+ib, new.c, sl);
3522                         ib += sl;
3523                         ic += (new.mode & ATTR_WIDE)? 2 : 1;
3524                 }
3525                 if(ib > 0)
3526                         xdraws(buf, base, ox, y, ic, ib);
3527         }
3528         xdrawcursor();
3529 }
3530
3531 void
3532 expose(XEvent *ev) {
3533         XExposeEvent *e = &ev->xexpose;
3534
3535         if(xw.state & WIN_REDRAW) {
3536                 if(!e->count)
3537                         xw.state &= ~WIN_REDRAW;
3538         }
3539         redraw(0);
3540 }
3541
3542 void
3543 visibility(XEvent *ev) {
3544         XVisibilityEvent *e = &ev->xvisibility;
3545
3546         if(e->state == VisibilityFullyObscured) {
3547                 xw.state &= ~WIN_VISIBLE;
3548         } else if(!(xw.state & WIN_VISIBLE)) {
3549                 /* need a full redraw for next Expose, not just a buf copy */
3550                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3551         }
3552 }
3553
3554 void
3555 unmap(XEvent *ev) {
3556         xw.state &= ~WIN_VISIBLE;
3557 }
3558
3559 void
3560 xsetpointermotion(int set) {
3561         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3562         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3563 }
3564
3565 void
3566 xseturgency(int add) {
3567         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3568
3569         MODBIT(h->flags, add, XUrgencyHint);
3570         XSetWMHints(xw.dpy, xw.win, h);
3571         XFree(h);
3572 }
3573
3574 void
3575 focus(XEvent *ev) {
3576         XFocusChangeEvent *e = &ev->xfocus;
3577
3578         if(e->mode == NotifyGrab)
3579                 return;
3580
3581         if(ev->type == FocusIn) {
3582                 XSetICFocus(xw.xic);
3583                 xw.state |= WIN_FOCUSED;
3584                 xseturgency(0);
3585                 if(IS_SET(MODE_FOCUS))
3586                         ttywrite("\033[I", 3);
3587         } else {
3588                 XUnsetICFocus(xw.xic);
3589                 xw.state &= ~WIN_FOCUSED;
3590                 if(IS_SET(MODE_FOCUS))
3591                         ttywrite("\033[O", 3);
3592         }
3593 }
3594
3595 static inline bool
3596 match(uint mask, uint state) {
3597         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3598 }
3599
3600 void
3601 numlock(const Arg *dummy) {
3602         term.numlock ^= 1;
3603 }
3604
3605 char*
3606 kmap(KeySym k, uint state) {
3607         Key *kp;
3608         int i;
3609
3610         /* Check for mapped keys out of X11 function keys. */
3611         for(i = 0; i < LEN(mappedkeys); i++) {
3612                 if(mappedkeys[i] == k)
3613                         break;
3614         }
3615         if(i == LEN(mappedkeys)) {
3616                 if((k & 0xFFFF) < 0xFD00)
3617                         return NULL;
3618         }
3619
3620         for(kp = key; kp < key + LEN(key); kp++) {
3621                 if(kp->k != k)
3622                         continue;
3623
3624                 if(!match(kp->mask, state))
3625                         continue;
3626
3627                 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3628                         continue;
3629                 if(term.numlock && kp->appkey == 2)
3630                         continue;
3631
3632                 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3633                         continue;
3634
3635                 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3636                         continue;
3637
3638                 return kp->s;
3639         }
3640
3641         return NULL;
3642 }
3643
3644 void
3645 kpress(XEvent *ev) {
3646         XKeyEvent *e = &ev->xkey;
3647         KeySym ksym;
3648         char buf[32], *customkey;
3649         int len;
3650         long c;
3651         Status status;
3652         Shortcut *bp;
3653
3654         if(IS_SET(MODE_KBDLOCK))
3655                 return;
3656
3657         len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3658         /* 1. shortcuts */
3659         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3660                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3661                         bp->func(&(bp->arg));
3662                         return;
3663                 }
3664         }
3665
3666         /* 2. custom keys from config.h */
3667         if((customkey = kmap(ksym, e->state))) {
3668                 ttysend(customkey, strlen(customkey));
3669                 return;
3670         }
3671
3672         /* 3. composed string from input method */
3673         if(len == 0)
3674                 return;
3675         if(len == 1 && e->state & Mod1Mask) {
3676                 if(IS_SET(MODE_8BIT)) {
3677                         if(*buf < 0177) {
3678                                 c = *buf | 0x80;
3679                                 len = utf8encode(c, buf, UTF_SIZ);
3680                         }
3681                 } else {
3682                         buf[1] = buf[0];
3683                         buf[0] = '\033';
3684                         len = 2;
3685                 }
3686         }
3687         ttysend(buf, len);
3688 }
3689
3690
3691 void
3692 cmessage(XEvent *e) {
3693         /*
3694          * See xembed specs
3695          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3696          */
3697         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3698                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3699                         xw.state |= WIN_FOCUSED;
3700                         xseturgency(0);
3701                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3702                         xw.state &= ~WIN_FOCUSED;
3703                 }
3704         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3705                 /* Send SIGHUP to shell */
3706                 kill(pid, SIGHUP);
3707                 exit(EXIT_SUCCESS);
3708         }
3709 }
3710
3711 void
3712 cresize(int width, int height) {
3713         int col, row;
3714
3715         if(width != 0)
3716                 xw.w = width;
3717         if(height != 0)
3718                 xw.h = height;
3719
3720         col = (xw.w - 2 * borderpx) / xw.cw;
3721         row = (xw.h - 2 * borderpx) / xw.ch;
3722
3723         tresize(col, row);
3724         xresize(col, row);
3725         ttyresize();
3726 }
3727
3728 void
3729 resize(XEvent *e) {
3730         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3731                 return;
3732
3733         cresize(e->xconfigure.width, e->xconfigure.height);
3734 }
3735
3736 void
3737 run(void) {
3738         XEvent ev;
3739         int w = xw.w, h = xw.h;
3740         fd_set rfd;
3741         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3742         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
3743         long deltatime;
3744
3745         /* Waiting for window mapping */
3746         while(1) {
3747                 XNextEvent(xw.dpy, &ev);
3748                 if(ev.type == ConfigureNotify) {
3749                         w = ev.xconfigure.width;
3750                         h = ev.xconfigure.height;
3751                 } else if(ev.type == MapNotify) {
3752                         break;
3753                 }
3754         }
3755
3756         ttynew();
3757         cresize(w, h);
3758
3759         clock_gettime(CLOCK_MONOTONIC, &last);
3760         lastblink = last;
3761
3762         for(xev = actionfps;;) {
3763                 FD_ZERO(&rfd);
3764                 FD_SET(cmdfd, &rfd);
3765                 FD_SET(xfd, &rfd);
3766
3767                 if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
3768                         if(errno == EINTR)
3769                                 continue;
3770                         die("select failed: %s\n", strerror(errno));
3771                 }
3772                 if(FD_ISSET(cmdfd, &rfd)) {
3773                         ttyread();
3774                         if(blinktimeout) {
3775                                 blinkset = tattrset(ATTR_BLINK);
3776                                 if(!blinkset)
3777                                         MODBIT(term.mode, 0, MODE_BLINK);
3778                         }
3779                 }
3780
3781                 if(FD_ISSET(xfd, &rfd))
3782                         xev = actionfps;
3783
3784                 clock_gettime(CLOCK_MONOTONIC, &now);
3785                 drawtimeout.tv_sec = 0;
3786                 drawtimeout.tv_nsec = (1000/xfps) * 1E6;
3787                 tv = &drawtimeout;
3788
3789                 dodraw = 0;
3790                 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3791                         tsetdirtattr(ATTR_BLINK);
3792                         term.mode ^= MODE_BLINK;
3793                         lastblink = now;
3794                         dodraw = 1;
3795                 }
3796                 deltatime = TIMEDIFF(now, last);
3797                 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3798                                 || deltatime < 0) {
3799                         dodraw = 1;
3800                         last = now;
3801                 }
3802
3803                 if(dodraw) {
3804                         while(XPending(xw.dpy)) {
3805                                 XNextEvent(xw.dpy, &ev);
3806                                 if(XFilterEvent(&ev, None))
3807                                         continue;
3808                                 if(handler[ev.type])
3809                                         (handler[ev.type])(&ev);
3810                         }
3811
3812                         draw();
3813                         XFlush(xw.dpy);
3814
3815                         if(xev && !FD_ISSET(xfd, &rfd))
3816                                 xev--;
3817                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3818                                 if(blinkset) {
3819                                         if(TIMEDIFF(now, lastblink) \
3820                                                         > blinktimeout) {
3821                                                 drawtimeout.tv_nsec = 1000;
3822                                         } else {
3823                                                 drawtimeout.tv_nsec = (1E6 * \
3824                                                         (blinktimeout - \
3825                                                         TIMEDIFF(now,
3826                                                                 lastblink)));
3827                                         }
3828                                 } else {
3829                                         tv = NULL;
3830                                 }
3831                         }
3832                 }
3833         }
3834 }
3835
3836 void
3837 usage(void) {
3838         die("%s " VERSION " (c) 2010-2014 st engineers\n" \
3839         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3840         " [-t title] [-w windowid] [-e command ...]\n", argv0);
3841 }
3842
3843 int
3844 main(int argc, char *argv[]) {
3845         char *titles;
3846         uint cols = 80, rows = 24;
3847
3848         xw.l = xw.t = 0;
3849         xw.isfixed = False;
3850
3851         ARGBEGIN {
3852         case 'a':
3853                 allowaltscreen = false;
3854                 break;
3855         case 'c':
3856                 opt_class = EARGF(usage());
3857                 break;
3858         case 'e':
3859                 /* eat all remaining arguments */
3860                 if(argc > 1) {
3861                         opt_cmd = &argv[1];
3862                         if(argv[1] != NULL && opt_title == NULL) {
3863                                 titles = xstrdup(argv[1]);
3864                                 opt_title = basename(titles);
3865                         }
3866                 }
3867                 goto run;
3868         case 'f':
3869                 opt_font = EARGF(usage());
3870                 break;
3871         case 'g':
3872                 xw.gm = XParseGeometry(EARGF(usage()),
3873                                 &xw.l, &xw.t, &cols, &rows);
3874                 break;
3875         case 'i':
3876                 xw.isfixed = True;
3877                 break;
3878         case 'o':
3879                 opt_io = EARGF(usage());
3880                 break;
3881         case 't':
3882                 opt_title = EARGF(usage());
3883                 break;
3884         case 'w':
3885                 opt_embed = EARGF(usage());
3886                 break;
3887         case 'v':
3888         default:
3889                 usage();
3890         } ARGEND;
3891
3892 run:
3893         setlocale(LC_CTYPE, "");
3894         XSetLocaleModifiers("");
3895         tnew(cols? cols : 1, rows? rows : 1);
3896         xinit();
3897         selinit();
3898         run();
3899
3900         return 0;
3901 }
3902