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