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