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