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