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