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