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