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