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