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