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