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