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