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