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