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