JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Add insert for the primary clipboard to MOD + Shift + Ins.
[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;
1300
1301         csiescseq.narg = 0;
1302         if(*p == '?')
1303                 csiescseq.priv = 1, p++;
1304
1305         while(p < csiescseq.buf+csiescseq.len) {
1306                 while(isdigit(*p)) {
1307                         csiescseq.arg[csiescseq.narg] *= 10;
1308                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1309                 }
1310                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1311                         csiescseq.narg++, p++;
1312                 } else {
1313                         csiescseq.mode = *p;
1314                         csiescseq.narg++;
1315
1316                         return;
1317                 }
1318         }
1319 }
1320
1321 /* for absolute user moves, when decom is set */
1322 void
1323 tmoveato(int x, int y) {
1324         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1325 }
1326
1327 void
1328 tmoveto(int x, int y) {
1329         int miny, maxy;
1330
1331         if(term.c.state & CURSOR_ORIGIN) {
1332                 miny = term.top;
1333                 maxy = term.bot;
1334         } else {
1335                 miny = 0;
1336                 maxy = term.row - 1;
1337         }
1338         LIMIT(x, 0, term.col-1);
1339         LIMIT(y, miny, maxy);
1340         term.c.state &= ~CURSOR_WRAPNEXT;
1341         term.c.x = x;
1342         term.c.y = y;
1343 }
1344
1345 void
1346 tsetchar(char *c, Glyph *attr, int x, int y) {
1347         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1348                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1349                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1350                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1351                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1352                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1353                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1354                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1355                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1356         };
1357
1358         /*
1359          * The table is proudly stolen from rxvt.
1360          */
1361         if(attr->mode & ATTR_GFX) {
1362                 if(c[0] >= 0x41 && c[0] <= 0x7e
1363                                 && vt100_0[c[0] - 0x41]) {
1364                         c = vt100_0[c[0] - 0x41];
1365                 }
1366         }
1367
1368         term.dirty[y] = 1;
1369         term.line[y][x] = *attr;
1370         memcpy(term.line[y][x].c, c, UTF_SIZ);
1371         term.line[y][x].state |= GLYPH_SET;
1372 }
1373
1374 void
1375 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1376         int x, y, temp;
1377
1378         if(x1 > x2)
1379                 temp = x1, x1 = x2, x2 = temp;
1380         if(y1 > y2)
1381                 temp = y1, y1 = y2, y2 = temp;
1382
1383         LIMIT(x1, 0, term.col-1);
1384         LIMIT(x2, 0, term.col-1);
1385         LIMIT(y1, 0, term.row-1);
1386         LIMIT(y2, 0, term.row-1);
1387
1388         for(y = y1; y <= y2; y++) {
1389                 term.dirty[y] = 1;
1390                 for(x = x1; x <= x2; x++) {
1391                         if(bce) {
1392                                 term.line[y][x] = term.c.attr;
1393                                 memcpy(term.line[y][x].c, " ", 2);
1394                                 term.line[y][x].state |= GLYPH_SET;
1395                         } else {
1396                                 term.line[y][x].state = 0;
1397                         }
1398                 }
1399         }
1400 }
1401
1402 void
1403 tdeletechar(int n) {
1404         int src = term.c.x + n;
1405         int dst = term.c.x;
1406         int size = term.col - src;
1407
1408         term.dirty[term.c.y] = 1;
1409
1410         if(src >= term.col) {
1411                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1412                 return;
1413         }
1414
1415         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1416                         size * sizeof(Glyph));
1417         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1418 }
1419
1420 void
1421 tinsertblank(int n) {
1422         int src = term.c.x;
1423         int dst = src + n;
1424         int size = term.col - dst;
1425
1426         term.dirty[term.c.y] = 1;
1427
1428         if(dst >= term.col) {
1429                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1430                 return;
1431         }
1432
1433         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1434                         size * sizeof(Glyph));
1435         tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1436 }
1437
1438 void
1439 tinsertblankline(int n) {
1440         if(term.c.y < term.top || term.c.y > term.bot)
1441                 return;
1442
1443         tscrolldown(term.c.y, n);
1444 }
1445
1446 void
1447 tdeleteline(int n) {
1448         if(term.c.y < term.top || term.c.y > term.bot)
1449                 return;
1450
1451         tscrollup(term.c.y, n);
1452 }
1453
1454 void
1455 tsetattr(int *attr, int l) {
1456         int i;
1457
1458         for(i = 0; i < l; i++) {
1459                 switch(attr[i]) {
1460                 case 0:
1461                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1462                                         | ATTR_ITALIC | ATTR_BLINK);
1463                         term.c.attr.fg = defaultfg;
1464                         term.c.attr.bg = defaultbg;
1465                         break;
1466                 case 1:
1467                         term.c.attr.mode |= ATTR_BOLD;
1468                         break;
1469                 case 3:
1470                         term.c.attr.mode |= ATTR_ITALIC;
1471                         break;
1472                 case 4:
1473                         term.c.attr.mode |= ATTR_UNDERLINE;
1474                         break;
1475                 case 5: /* slow blink */
1476                 case 6: /* rapid blink */
1477                         term.c.attr.mode |= ATTR_BLINK;
1478                         break;
1479                 case 7:
1480                         term.c.attr.mode |= ATTR_REVERSE;
1481                         break;
1482                 case 21:
1483                 case 22:
1484                         term.c.attr.mode &= ~ATTR_BOLD;
1485                         break;
1486                 case 23:
1487                         term.c.attr.mode &= ~ATTR_ITALIC;
1488                         break;
1489                 case 24:
1490                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1491                         break;
1492                 case 25:
1493                 case 26:
1494                         term.c.attr.mode &= ~ATTR_BLINK;
1495                         break;
1496                 case 27:
1497                         term.c.attr.mode &= ~ATTR_REVERSE;
1498                         break;
1499                 case 38:
1500                         if(i + 2 < l && attr[i + 1] == 5) {
1501                                 i += 2;
1502                                 if(BETWEEN(attr[i], 0, 255)) {
1503                                         term.c.attr.fg = attr[i];
1504                                 } else {
1505                                         fprintf(stderr,
1506                                                 "erresc: bad fgcolor %d\n",
1507                                                 attr[i]);
1508                                 }
1509                         } else {
1510                                 fprintf(stderr,
1511                                         "erresc(38): gfx attr %d unknown\n",
1512                                         attr[i]);
1513                         }
1514                         break;
1515                 case 39:
1516                         term.c.attr.fg = defaultfg;
1517                         break;
1518                 case 48:
1519                         if(i + 2 < l && attr[i + 1] == 5) {
1520                                 i += 2;
1521                                 if(BETWEEN(attr[i], 0, 255)) {
1522                                         term.c.attr.bg = attr[i];
1523                                 } else {
1524                                         fprintf(stderr,
1525                                                 "erresc: bad bgcolor %d\n",
1526                                                 attr[i]);
1527                                 }
1528                         } else {
1529                                 fprintf(stderr,
1530                                         "erresc(48): gfx attr %d unknown\n",
1531                                         attr[i]);
1532                         }
1533                         break;
1534                 case 49:
1535                         term.c.attr.bg = defaultbg;
1536                         break;
1537                 default:
1538                         if(BETWEEN(attr[i], 30, 37)) {
1539                                 term.c.attr.fg = attr[i] - 30;
1540                         } else if(BETWEEN(attr[i], 40, 47)) {
1541                                 term.c.attr.bg = attr[i] - 40;
1542                         } else if(BETWEEN(attr[i], 90, 97)) {
1543                                 term.c.attr.fg = attr[i] - 90 + 8;
1544                         } else if(BETWEEN(attr[i], 100, 107)) {
1545                                 term.c.attr.bg = attr[i] - 100 + 8;
1546                         } else {
1547                                 fprintf(stderr,
1548                                         "erresc(default): gfx attr %d unknown\n",
1549                                         attr[i]), csidump();
1550                         }
1551                         break;
1552                 }
1553         }
1554 }
1555
1556 void
1557 tsetscroll(int t, int b) {
1558         int temp;
1559
1560         LIMIT(t, 0, term.row-1);
1561         LIMIT(b, 0, term.row-1);
1562         if(t > b) {
1563                 temp = t;
1564                 t = b;
1565                 b = temp;
1566         }
1567         term.top = t;
1568         term.bot = b;
1569 }
1570
1571 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1572
1573 void
1574 tsetmode(bool priv, bool set, int *args, int narg) {
1575         int *lim, mode;
1576         bool alt;
1577
1578         for(lim = args + narg; args < lim; ++args) {
1579                 if(priv) {
1580                         switch(*args) {
1581                                 break;
1582                         case 1: /* DECCKM -- Cursor key */
1583                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1584                                 break;
1585                         case 5: /* DECSCNM -- Reverse video */
1586                                 mode = term.mode;
1587                                 MODBIT(term.mode, set, MODE_REVERSE);
1588                                 if(mode != term.mode)
1589                                         redraw(REDRAW_TIMEOUT);
1590                                 break;
1591                         case 6: /* DECOM -- Origin */
1592                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1593                                 tmoveato(0, 0);
1594                                 break;
1595                         case 7: /* DECAWM -- Auto wrap */
1596                                 MODBIT(term.mode, set, MODE_WRAP);
1597                                 break;
1598                         case 0:  /* Error (IGNORED) */
1599                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1600                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1601                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1602                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1603                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1604                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1605                         case 42: /* DECNRCM -- National characters (IGNORED) */
1606                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1607                                 break;
1608                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1609                                 MODBIT(term.mode, !set, MODE_HIDE);
1610                                 break;
1611                         case 1000: /* 1000,1002: enable xterm mouse report */
1612                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1613                                 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1614                                 break;
1615                         case 1002:
1616                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1617                                 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1618                                 break;
1619                         case 1006:
1620                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1621                                 break;
1622                         case 1049: /* = 1047 and 1048 */
1623                         case 47:
1624                         case 1047: {
1625                                 alt = IS_SET(MODE_ALTSCREEN);
1626                                 if(alt) {
1627                                         tclearregion(0, 0, term.col-1,
1628                                                         term.row-1, 0);
1629                                 }
1630                                 if(set ^ alt)           /* set is always 1 or 0 */
1631                                         tswapscreen();
1632                                 if(*args != 1049)
1633                                         break;
1634                         }
1635                                 /* pass through */
1636                         case 1048:
1637                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1638                                 break;
1639                         default:
1640                                 fprintf(stderr,
1641                                         "erresc: unknown private set/reset mode %d\n",
1642                                         *args);
1643                                 break;
1644                         }
1645                 } else {
1646                         switch(*args) {
1647                         case 0:  /* Error (IGNORED) */
1648                                 break;
1649                         case 2:  /* KAM -- keyboard action */
1650                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1651                                 break;
1652                         case 4:  /* IRM -- Insertion-replacement */
1653                                 MODBIT(term.mode, set, MODE_INSERT);
1654                                 break;
1655                         case 12: /* SRM -- Send/Receive */
1656                                 MODBIT(term.mode, !set, MODE_ECHO);
1657                                 break;
1658                         case 20: /* LNM -- Linefeed/new line */
1659                                 MODBIT(term.mode, set, MODE_CRLF);
1660                                 break;
1661                         default:
1662                                 fprintf(stderr,
1663                                         "erresc: unknown set/reset mode %d\n",
1664                                         *args);
1665                                 break;
1666                         }
1667                 }
1668         }
1669 }
1670 #undef MODBIT
1671
1672
1673 void
1674 csihandle(void) {
1675         switch(csiescseq.mode) {
1676         default:
1677         unknown:
1678                 fprintf(stderr, "erresc: unknown csi ");
1679                 csidump();
1680                 /* die(""); */
1681                 break;
1682         case '@': /* ICH -- Insert <n> blank char */
1683                 DEFAULT(csiescseq.arg[0], 1);
1684                 tinsertblank(csiescseq.arg[0]);
1685                 break;
1686         case 'A': /* CUU -- Cursor <n> Up */
1687                 DEFAULT(csiescseq.arg[0], 1);
1688                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1689                 break;
1690         case 'B': /* CUD -- Cursor <n> Down */
1691         case 'e': /* VPR --Cursor <n> Down */
1692                 DEFAULT(csiescseq.arg[0], 1);
1693                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1694                 break;
1695         case 'c': /* DA -- Device Attributes */
1696                 if(csiescseq.arg[0] == 0)
1697                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1698                 break;
1699         case 'C': /* CUF -- Cursor <n> Forward */
1700         case 'a': /* HPR -- Cursor <n> Forward */
1701                 DEFAULT(csiescseq.arg[0], 1);
1702                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1703                 break;
1704         case 'D': /* CUB -- Cursor <n> Backward */
1705                 DEFAULT(csiescseq.arg[0], 1);
1706                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1707                 break;
1708         case 'E': /* CNL -- Cursor <n> Down and first col */
1709                 DEFAULT(csiescseq.arg[0], 1);
1710                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1711                 break;
1712         case 'F': /* CPL -- Cursor <n> Up and first col */
1713                 DEFAULT(csiescseq.arg[0], 1);
1714                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1715                 break;
1716         case 'g': /* TBC -- Tabulation clear */
1717                 switch(csiescseq.arg[0]) {
1718                 case 0: /* clear current tab stop */
1719                         term.tabs[term.c.x] = 0;
1720                         break;
1721                 case 3: /* clear all the tabs */
1722                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1723                         break;
1724                 default:
1725                         goto unknown;
1726                 }
1727                 break;
1728         case 'G': /* CHA -- Move to <col> */
1729         case '`': /* HPA */
1730                 DEFAULT(csiescseq.arg[0], 1);
1731                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1732                 break;
1733         case 'H': /* CUP -- Move to <row> <col> */
1734         case 'f': /* HVP */
1735                 DEFAULT(csiescseq.arg[0], 1);
1736                 DEFAULT(csiescseq.arg[1], 1);
1737                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1738                 break;
1739         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1740                 DEFAULT(csiescseq.arg[0], 1);
1741                 while(csiescseq.arg[0]--)
1742                         tputtab(1);
1743                 break;
1744         case 'J': /* ED -- Clear screen */
1745                 sel.bx = -1;
1746                 switch(csiescseq.arg[0]) {
1747                 case 0: /* below */
1748                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1749                         if(term.c.y < term.row-1) {
1750                                 tclearregion(0, term.c.y+1, term.col-1,
1751                                                 term.row-1, 1);
1752                         }
1753                         break;
1754                 case 1: /* above */
1755                         if(term.c.y > 1)
1756                                 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1757                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1758                         break;
1759                 case 2: /* all */
1760                         tclearregion(0, 0, term.col-1, term.row-1, 1);
1761                         break;
1762                 default:
1763                         goto unknown;
1764                 }
1765                 break;
1766         case 'K': /* EL -- Clear line */
1767                 switch(csiescseq.arg[0]) {
1768                 case 0: /* right */
1769                         tclearregion(term.c.x, term.c.y, term.col-1,
1770                                         term.c.y, 1);
1771                         break;
1772                 case 1: /* left */
1773                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1774                         break;
1775                 case 2: /* all */
1776                         tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1777                         break;
1778                 }
1779                 break;
1780         case 'S': /* SU -- Scroll <n> line up */
1781                 DEFAULT(csiescseq.arg[0], 1);
1782                 tscrollup(term.top, csiescseq.arg[0]);
1783                 break;
1784         case 'T': /* SD -- Scroll <n> line down */
1785                 DEFAULT(csiescseq.arg[0], 1);
1786                 tscrolldown(term.top, csiescseq.arg[0]);
1787                 break;
1788         case 'L': /* IL -- Insert <n> blank lines */
1789                 DEFAULT(csiescseq.arg[0], 1);
1790                 tinsertblankline(csiescseq.arg[0]);
1791                 break;
1792         case 'l': /* RM -- Reset Mode */
1793                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1794                 break;
1795         case 'M': /* DL -- Delete <n> lines */
1796                 DEFAULT(csiescseq.arg[0], 1);
1797                 tdeleteline(csiescseq.arg[0]);
1798                 break;
1799         case 'X': /* ECH -- Erase <n> char */
1800                 DEFAULT(csiescseq.arg[0], 1);
1801                 tclearregion(term.c.x, term.c.y,
1802                                 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1803                 break;
1804         case 'P': /* DCH -- Delete <n> char */
1805                 DEFAULT(csiescseq.arg[0], 1);
1806                 tdeletechar(csiescseq.arg[0]);
1807                 break;
1808         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1809                 DEFAULT(csiescseq.arg[0], 1);
1810                 while(csiescseq.arg[0]--)
1811                         tputtab(0);
1812                 break;
1813         case 'd': /* VPA -- Move to <row> */
1814                 DEFAULT(csiescseq.arg[0], 1);
1815                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1816                 break;
1817         case 'h': /* SM -- Set terminal mode */
1818                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1819                 break;
1820         case 'm': /* SGR -- Terminal attribute (color) */
1821                 tsetattr(csiescseq.arg, csiescseq.narg);
1822                 break;
1823         case 'r': /* DECSTBM -- Set Scrolling Region */
1824                 if(csiescseq.priv) {
1825                         goto unknown;
1826                 } else {
1827                         DEFAULT(csiescseq.arg[0], 1);
1828                         DEFAULT(csiescseq.arg[1], term.row);
1829                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1830                         tmoveato(0, 0);
1831                 }
1832                 break;
1833         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1834                 tcursor(CURSOR_SAVE);
1835                 break;
1836         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1837                 tcursor(CURSOR_LOAD);
1838                 break;
1839         }
1840 }
1841
1842 void
1843 csidump(void) {
1844         int i;
1845         uint c;
1846
1847         printf("ESC[");
1848         for(i = 0; i < csiescseq.len; i++) {
1849                 c = csiescseq.buf[i] & 0xff;
1850                 if(isprint(c)) {
1851                         putchar(c);
1852                 } else if(c == '\n') {
1853                         printf("(\\n)");
1854                 } else if(c == '\r') {
1855                         printf("(\\r)");
1856                 } else if(c == 0x1b) {
1857                         printf("(\\e)");
1858                 } else {
1859                         printf("(%02x)", c);
1860                 }
1861         }
1862         putchar('\n');
1863 }
1864
1865 void
1866 csireset(void) {
1867         memset(&csiescseq, 0, sizeof(csiescseq));
1868 }
1869
1870 void
1871 strhandle(void) {
1872         char *p = NULL;
1873         int i, j, narg;
1874
1875         strparse();
1876         narg = strescseq.narg;
1877
1878         switch(strescseq.type) {
1879         case ']': /* OSC -- Operating System Command */
1880                 switch(i = atoi(strescseq.args[0])) {
1881                 case 0:
1882                 case 1:
1883                 case 2:
1884                         if(narg > 1)
1885                                 xsettitle(strescseq.args[1]);
1886                         break;
1887                 case 4: /* color set */
1888                         if(narg < 3)
1889                                 break;
1890                         p = strescseq.args[2];
1891                         /* fall through */
1892                 case 104: /* color reset, here p = NULL */
1893                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1894                         if (!xsetcolorname(j, p)) {
1895                                 fprintf(stderr, "erresc: invalid color %s\n", p);
1896                         } else {
1897                                 /*
1898                                  * TODO if defaultbg color is changed, borders
1899                                  * are dirty
1900                                  */
1901                                 redraw(0);
1902                         }
1903                         break;
1904                 default:
1905                         fprintf(stderr, "erresc: unknown str ");
1906                         strdump();
1907                         break;
1908                 }
1909                 break;
1910         case 'k': /* old title set compatibility */
1911                 xsettitle(strescseq.args[0]);
1912                 break;
1913         case 'P': /* DSC -- Device Control String */
1914         case '_': /* APC -- Application Program Command */
1915         case '^': /* PM -- Privacy Message */
1916         default:
1917                 fprintf(stderr, "erresc: unknown str ");
1918                 strdump();
1919                 /* die(""); */
1920                 break;
1921         }
1922 }
1923
1924 void
1925 strparse(void) {
1926         /*
1927          * TODO: Implement parsing like for CSI when required.
1928          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1929          */
1930         int narg = 0;
1931         char *start = strescseq.buf, *end = start + strescseq.len;
1932         strescseq.args[0] = start;
1933         while(start < end && narg < LEN(strescseq.args)) {
1934                 start = memchr(start, ';', end - start);
1935                 if(!start)
1936                         break;
1937                 *start++ = '\0';
1938                 if(start < end) {
1939                         strescseq.args[++narg] = start;
1940                 }
1941         }
1942         strescseq.narg = narg + 1;
1943 }
1944
1945 void
1946 strdump(void) {
1947         int i;
1948         uint c;
1949
1950         printf("ESC%c", strescseq.type);
1951         for(i = 0; i < strescseq.len; i++) {
1952                 c = strescseq.buf[i] & 0xff;
1953                 if(isprint(c)) {
1954                         putchar(c);
1955                 } else if(c == '\n') {
1956                         printf("(\\n)");
1957                 } else if(c == '\r') {
1958                         printf("(\\r)");
1959                 } else if(c == 0x1b) {
1960                         printf("(\\e)");
1961                 } else {
1962                         printf("(%02x)", c);
1963                 }
1964         }
1965         printf("ESC\\\n");
1966 }
1967
1968 void
1969 strreset(void) {
1970         memset(&strescseq, 0, sizeof(strescseq));
1971 }
1972
1973 void
1974 tputtab(bool forward) {
1975         uint x = term.c.x;
1976
1977         if(forward) {
1978                 if(x == term.col)
1979                         return;
1980                 for(++x; x < term.col && !term.tabs[x]; ++x)
1981                         /* nothing */ ;
1982         } else {
1983                 if(x == 0)
1984                         return;
1985                 for(--x; x > 0 && !term.tabs[x]; --x)
1986                         /* nothing */ ;
1987         }
1988         tmoveto(x, term.c.y);
1989 }
1990
1991 void
1992 techo(char *buf, int len) {
1993         for(; len > 0; buf++, len--) {
1994                 char c = *buf;
1995
1996                 if(c == '\033') {               /* escape */
1997                         tputc("^", 1);
1998                         tputc("[", 1);
1999                 } else if(c < '\x20') { /* control code */
2000                         if(c != '\n' && c != '\r' && c != '\t') {
2001                                 c |= '\x40';
2002                                 tputc("^", 1);
2003                         }
2004                         tputc(&c, 1);
2005                 } else {
2006                         break;
2007                 }
2008         }
2009         if(len)
2010                 tputc(buf, len);
2011 }
2012
2013 void
2014 tputc(char *c, int len) {
2015         uchar ascii = *c;
2016         bool control = ascii < '\x20' || ascii == 0177;
2017
2018         if(iofd != -1) {
2019                 if(xwrite(iofd, c, len) < 0) {
2020                         fprintf(stderr, "Error writing in %s:%s\n",
2021                                 opt_io, strerror(errno));
2022                         close(iofd);
2023                         iofd = -1;
2024                 }
2025         }
2026
2027         /*
2028          * STR sequences must be checked before anything else
2029          * because it can use some control codes as part of the sequence.
2030          */
2031         if(term.esc & ESC_STR) {
2032                 switch(ascii) {
2033                 case '\033':
2034                         term.esc = ESC_START | ESC_STR_END;
2035                         break;
2036                 case '\a': /* backwards compatibility to xterm */
2037                         term.esc = 0;
2038                         strhandle();
2039                         break;
2040                 default:
2041                         if(strescseq.len + len < sizeof(strescseq.buf)) {
2042                                 memmove(&strescseq.buf[strescseq.len], c, len);
2043                                 strescseq.len += len;
2044                         } else {
2045                         /*
2046                          * Here is a bug in terminals. If the user never sends
2047                          * some code to stop the str or esc command, then st
2048                          * will stop responding. But this is better than
2049                          * silently failing with unknown characters. At least
2050                          * then users will report back.
2051                          *
2052                          * In the case users ever get fixed, here is the code:
2053                          */
2054                         /*
2055                          * term.esc = 0;
2056                          * strhandle();
2057                          */
2058                         }
2059                 }
2060                 return;
2061         }
2062
2063         /*
2064          * Actions of control codes must be performed as soon they arrive
2065          * because they can be embedded inside a control sequence, and
2066          * they must not cause conflicts with sequences.
2067          */
2068         if(control) {
2069                 switch(ascii) {
2070                 case '\t':      /* HT */
2071                         tputtab(1);
2072                         return;
2073                 case '\b':      /* BS */
2074                         tmoveto(term.c.x-1, term.c.y);
2075                         return;
2076                 case '\r':      /* CR */
2077                         tmoveto(0, term.c.y);
2078                         return;
2079                 case '\f':      /* LF */
2080                 case '\v':      /* VT */
2081                 case '\n':      /* LF */
2082                         /* go to first col if the mode is set */
2083                         tnewline(IS_SET(MODE_CRLF));
2084                         return;
2085                 case '\a':      /* BEL */
2086                         if(!(xw.state & WIN_FOCUSED))
2087                                 xseturgency(1);
2088                         return;
2089                 case '\033':    /* ESC */
2090                         csireset();
2091                         term.esc = ESC_START;
2092                         return;
2093                 case '\016':    /* SO */
2094                 case '\017':    /* SI */
2095                         /*
2096                          * Different charsets are hard to handle. Applications
2097                          * should use the right alt charset escapes for the
2098                          * only reason they still exist: line drawing. The
2099                          * rest is incompatible history st should not support.
2100                          */
2101                         return;
2102                 case '\032':    /* SUB */
2103                 case '\030':    /* CAN */
2104                         csireset();
2105                         return;
2106                 case '\005':    /* ENQ (IGNORED) */
2107                 case '\000':    /* NUL (IGNORED) */
2108                 case '\021':    /* XON (IGNORED) */
2109                 case '\023':    /* XOFF (IGNORED) */
2110                 case 0177:      /* DEL (IGNORED) */
2111                         return;
2112                 }
2113         } else if(term.esc & ESC_START) {
2114                 if(term.esc & ESC_CSI) {
2115                         csiescseq.buf[csiescseq.len++] = ascii;
2116                         if(BETWEEN(ascii, 0x40, 0x7E)
2117                                         || csiescseq.len >= ESC_BUF_SIZ) {
2118                                 term.esc = 0;
2119                                 csiparse(), csihandle();
2120                         }
2121                 } else if(term.esc & ESC_STR_END) {
2122                         term.esc = 0;
2123                         if(ascii == '\\')
2124                                 strhandle();
2125                 } else if(term.esc & ESC_ALTCHARSET) {
2126                         switch(ascii) {
2127                         case '0': /* Line drawing set */
2128                                 term.c.attr.mode |= ATTR_GFX;
2129                                 break;
2130                         case 'B': /* USASCII */
2131                                 term.c.attr.mode &= ~ATTR_GFX;
2132                                 break;
2133                         case 'A': /* UK (IGNORED) */
2134                         case '<': /* multinational charset (IGNORED) */
2135                         case '5': /* Finnish (IGNORED) */
2136                         case 'C': /* Finnish (IGNORED) */
2137                         case 'K': /* German (IGNORED) */
2138                                 break;
2139                         default:
2140                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2141                         }
2142                         term.esc = 0;
2143                 } else if(term.esc & ESC_TEST) {
2144                         if(ascii == '8') { /* DEC screen alignment test. */
2145                                 char E[UTF_SIZ] = "E";
2146                                 int x, y;
2147
2148                                 for(x = 0; x < term.col; ++x) {
2149                                         for(y = 0; y < term.row; ++y)
2150                                                 tsetchar(E, &term.c.attr, x, y);
2151                                 }
2152                         }
2153                         term.esc = 0;
2154                 } else {
2155                         switch(ascii) {
2156                         case '[':
2157                                 term.esc |= ESC_CSI;
2158                                 break;
2159                         case '#':
2160                                 term.esc |= ESC_TEST;
2161                                 break;
2162                         case 'P': /* DCS -- Device Control String */
2163                         case '_': /* APC -- Application Program Command */
2164                         case '^': /* PM -- Privacy Message */
2165                         case ']': /* OSC -- Operating System Command */
2166                         case 'k': /* old title set compatibility */
2167                                 strreset();
2168                                 strescseq.type = ascii;
2169                                 term.esc |= ESC_STR;
2170                                 break;
2171                         case '(': /* set primary charset G0 */
2172                                 term.esc |= ESC_ALTCHARSET;
2173                                 break;
2174                         case ')': /* set secondary charset G1 (IGNORED) */
2175                         case '*': /* set tertiary charset G2 (IGNORED) */
2176                         case '+': /* set quaternary charset G3 (IGNORED) */
2177                                 term.esc = 0;
2178                                 break;
2179                         case 'D': /* IND -- Linefeed */
2180                                 if(term.c.y == term.bot) {
2181                                         tscrollup(term.top, 1);
2182                                 } else {
2183                                         tmoveto(term.c.x, term.c.y+1);
2184                                 }
2185                                 term.esc = 0;
2186                                 break;
2187                         case 'E': /* NEL -- Next line */
2188                                 tnewline(1); /* always go to first col */
2189                                 term.esc = 0;
2190                                 break;
2191                         case 'H': /* HTS -- Horizontal tab stop */
2192                                 term.tabs[term.c.x] = 1;
2193                                 term.esc = 0;
2194                                 break;
2195                         case 'M': /* RI -- Reverse index */
2196                                 if(term.c.y == term.top) {
2197                                         tscrolldown(term.top, 1);
2198                                 } else {
2199                                         tmoveto(term.c.x, term.c.y-1);
2200                                 }
2201                                 term.esc = 0;
2202                                 break;
2203                         case 'Z': /* DECID -- Identify Terminal */
2204                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2205                                 term.esc = 0;
2206                                 break;
2207                         case 'c': /* RIS -- Reset to inital state */
2208                                 treset();
2209                                 term.esc = 0;
2210                                 xresettitle();
2211                                 break;
2212                         case '=': /* DECPAM -- Application keypad */
2213                                 term.mode |= MODE_APPKEYPAD;
2214                                 term.esc = 0;
2215                                 break;
2216                         case '>': /* DECPNM -- Normal keypad */
2217                                 term.mode &= ~MODE_APPKEYPAD;
2218                                 term.esc = 0;
2219                                 break;
2220                         case '7': /* DECSC -- Save Cursor */
2221                                 tcursor(CURSOR_SAVE);
2222                                 term.esc = 0;
2223                                 break;
2224                         case '8': /* DECRC -- Restore Cursor */
2225                                 tcursor(CURSOR_LOAD);
2226                                 term.esc = 0;
2227                                 break;
2228                         case '\\': /* ST -- Stop */
2229                                 term.esc = 0;
2230                                 break;
2231                         default:
2232                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2233                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2234                                 term.esc = 0;
2235                         }
2236                 }
2237                 /*
2238                  * All characters which form part of a sequence are not
2239                  * printed
2240                  */
2241                 return;
2242         }
2243         /*
2244          * Display control codes only if we are in graphic mode
2245          */
2246         if(control && !(term.c.attr.mode & ATTR_GFX))
2247                 return;
2248         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2249                 sel.bx = -1;
2250         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2251                 tnewline(1); /* always go to first col */
2252
2253         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2254                 memmove(&term.line[term.c.y][term.c.x+1],
2255                         &term.line[term.c.y][term.c.x],
2256                         (term.col - term.c.x - 1) * sizeof(Glyph));
2257         }
2258
2259         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2260         if(term.c.x+1 < term.col) {
2261                 tmoveto(term.c.x+1, term.c.y);
2262         } else {
2263                 term.c.state |= CURSOR_WRAPNEXT;
2264         }
2265 }
2266
2267 int
2268 tresize(int col, int row) {
2269         int i, x;
2270         int minrow = MIN(row, term.row);
2271         int mincol = MIN(col, term.col);
2272         int slide = term.c.y - row + 1;
2273         bool *bp;
2274
2275         if(col < 1 || row < 1)
2276                 return 0;
2277
2278         /* free unneeded rows */
2279         i = 0;
2280         if(slide > 0) {
2281                 /*
2282                  * slide screen to keep cursor where we expect it -
2283                  * tscrollup would work here, but we can optimize to
2284                  * memmove because we're freeing the earlier lines
2285                  */
2286                 for(/* i = 0 */; i < slide; i++) {
2287                         free(term.line[i]);
2288                         free(term.alt[i]);
2289                 }
2290                 memmove(term.line, term.line + slide, row * sizeof(Line));
2291                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2292         }
2293         for(i += row; i < term.row; i++) {
2294                 free(term.line[i]);
2295                 free(term.alt[i]);
2296         }
2297
2298         /* resize to new height */
2299         term.line = xrealloc(term.line, row * sizeof(Line));
2300         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2301         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2302         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2303
2304         /* resize each row to new width, zero-pad if needed */
2305         for(i = 0; i < minrow; i++) {
2306                 term.dirty[i] = 1;
2307                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2308                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2309                 for(x = mincol; x < col; x++) {
2310                         term.line[i][x].state = 0;
2311                         term.alt[i][x].state = 0;
2312                 }
2313         }
2314
2315         /* allocate any new rows */
2316         for(/* i == minrow */; i < row; i++) {
2317                 term.dirty[i] = 1;
2318                 term.line[i] = xcalloc(col, sizeof(Glyph));
2319                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2320         }
2321         if(col > term.col) {
2322                 bp = term.tabs + term.col;
2323
2324                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2325                 while(--bp > term.tabs && !*bp)
2326                         /* nothing */ ;
2327                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2328                         *bp = 1;
2329         }
2330         /* update terminal size */
2331         term.col = col;
2332         term.row = row;
2333         /* reset scrolling region */
2334         tsetscroll(0, row-1);
2335         /* make use of the LIMIT in tmoveto */
2336         tmoveto(term.c.x, term.c.y);
2337
2338         return (slide > 0);
2339 }
2340
2341 void
2342 xresize(int col, int row) {
2343         xw.tw = MAX(1, col * xw.cw);
2344         xw.th = MAX(1, row * xw.ch);
2345
2346         XFreePixmap(xw.dpy, xw.buf);
2347         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2348                         DefaultDepth(xw.dpy, xw.scr));
2349         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2350         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2351
2352         XftDrawChange(xw.draw, xw.buf);
2353 }
2354
2355 static inline ushort
2356 sixd_to_16bit(int x) {
2357         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2358 }
2359
2360 void
2361 xloadcols(void) {
2362         int i, r, g, b;
2363         XRenderColor color = { .alpha = 0xffff };
2364
2365         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2366         for(i = 0; i < LEN(colorname); i++) {
2367                 if(!colorname[i])
2368                         continue;
2369                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2370                         die("Could not allocate color '%s'\n", colorname[i]);
2371                 }
2372         }
2373
2374         /* load colors [16-255] ; same colors as xterm */
2375         for(i = 16, r = 0; r < 6; r++) {
2376                 for(g = 0; g < 6; g++) {
2377                         for(b = 0; b < 6; b++) {
2378                                 color.red = sixd_to_16bit(r);
2379                                 color.green = sixd_to_16bit(g);
2380                                 color.blue = sixd_to_16bit(b);
2381                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2382                                         die("Could not allocate color %d\n", i);
2383                                 }
2384                                 i++;
2385                         }
2386                 }
2387         }
2388
2389         for(r = 0; r < 24; r++, i++) {
2390                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2391                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2392                                         &dc.col[i])) {
2393                         die("Could not allocate color %d\n", i);
2394                 }
2395         }
2396 }
2397
2398 int
2399 xsetcolorname(int x, const char *name) {
2400         XRenderColor color = { .alpha = 0xffff };
2401         Colour colour;
2402         if (x < 0 || x > LEN(colorname))
2403                 return -1;
2404         if(!name) {
2405                 if(16 <= x && x < 16 + 216) {
2406                         int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2407                         color.red = sixd_to_16bit(r);
2408                         color.green = sixd_to_16bit(g);
2409                         color.blue = sixd_to_16bit(b);
2410                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2411                                 return 0; /* something went wrong */
2412                         dc.col[x] = colour;
2413                         return 1;
2414                 } else if (16 + 216 <= x && x < 256) {
2415                         color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
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 {
2421                         name = colorname[x];
2422                 }
2423         }
2424         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2425                 return 0;
2426         dc.col[x] = colour;
2427         return 1;
2428 }
2429
2430 void
2431 xtermclear(int col1, int row1, int col2, int row2) {
2432         XftDrawRect(xw.draw,
2433                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2434                         borderpx + col1 * xw.cw,
2435                         borderpx + row1 * xw.ch,
2436                         (col2-col1+1) * xw.cw,
2437                         (row2-row1+1) * xw.ch);
2438 }
2439
2440 /*
2441  * Absolute coordinates.
2442  */
2443 void
2444 xclear(int x1, int y1, int x2, int y2) {
2445         XftDrawRect(xw.draw,
2446                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2447                         x1, y1, x2-x1, y2-y1);
2448 }
2449
2450 void
2451 xhints(void) {
2452         XClassHint class = {opt_class ? opt_class : termname, termname};
2453         XWMHints wm = {.flags = InputHint, .input = 1};
2454         XSizeHints *sizeh = NULL;
2455
2456         sizeh = XAllocSizeHints();
2457         if(xw.isfixed == False) {
2458                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2459                 sizeh->height = xw.h;
2460                 sizeh->width = xw.w;
2461                 sizeh->height_inc = xw.ch;
2462                 sizeh->width_inc = xw.cw;
2463                 sizeh->base_height = 2 * borderpx;
2464                 sizeh->base_width = 2 * borderpx;
2465         } else {
2466                 sizeh->flags = PMaxSize | PMinSize;
2467                 sizeh->min_width = sizeh->max_width = xw.fw;
2468                 sizeh->min_height = sizeh->max_height = xw.fh;
2469         }
2470
2471         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2472         XFree(sizeh);
2473 }
2474
2475 int
2476 xloadfont(Font *f, FcPattern *pattern) {
2477         FcPattern *match;
2478         FcResult result;
2479
2480         match = FcFontMatch(NULL, pattern, &result);
2481         if(!match)
2482                 return 1;
2483
2484         if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2485                 FcPatternDestroy(match);
2486                 return 1;
2487         }
2488
2489         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2490                 FcPatternDestroy(match);
2491                 return 1;
2492         }
2493
2494         f->pattern = FcPatternDuplicate(pattern);
2495
2496         f->ascent = f->match->ascent;
2497         f->descent = f->match->descent;
2498         f->lbearing = 0;
2499         f->rbearing = f->match->max_advance_width;
2500
2501         f->height = f->match->height;
2502         f->width = f->lbearing + f->rbearing;
2503
2504         return 0;
2505 }
2506
2507 void
2508 xloadfonts(char *fontstr, int fontsize) {
2509         FcPattern *pattern;
2510         FcResult result;
2511         double fontval;
2512
2513         if(fontstr[0] == '-') {
2514                 pattern = XftXlfdParse(fontstr, False, False);
2515         } else {
2516                 pattern = FcNameParse((FcChar8 *)fontstr);
2517         }
2518
2519         if(!pattern)
2520                 die("st: can't open font %s\n", fontstr);
2521
2522         if(fontsize > 0) {
2523                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2524                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2525                 usedfontsize = fontsize;
2526         } else {
2527                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2528                 if(result == FcResultMatch) {
2529                         usedfontsize = (int)fontval;
2530                 } else {
2531                         /*
2532                          * Default font size is 12, if none given. This is to
2533                          * have a known usedfontsize value.
2534                          */
2535                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2536                         usedfontsize = 12;
2537                 }
2538         }
2539
2540         FcConfigSubstitute(0, pattern, FcMatchPattern);
2541         FcDefaultSubstitute(pattern);
2542
2543         if(xloadfont(&dc.font, pattern))
2544                 die("st: can't open font %s\n", fontstr);
2545
2546         /* Setting character width and height. */
2547         xw.cw = dc.font.width;
2548         xw.ch = dc.font.height;
2549
2550         FcPatternDel(pattern, FC_SLANT);
2551         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2552         if(xloadfont(&dc.ifont, pattern))
2553                 die("st: can't open font %s\n", fontstr);
2554
2555         FcPatternDel(pattern, FC_WEIGHT);
2556         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2557         if(xloadfont(&dc.ibfont, pattern))
2558                 die("st: can't open font %s\n", fontstr);
2559
2560         FcPatternDel(pattern, FC_SLANT);
2561         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2562         if(xloadfont(&dc.bfont, pattern))
2563                 die("st: can't open font %s\n", fontstr);
2564
2565         FcPatternDestroy(pattern);
2566 }
2567
2568 void
2569 xunloadfonts(void) {
2570         int i, ip;
2571
2572         /*
2573          * Free the loaded fonts in the font cache. This is done backwards
2574          * from the frccur.
2575          */
2576         for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2577                 if(ip < 0)
2578                         ip = LEN(frc) - 1;
2579                 XftFontClose(xw.dpy, frc[ip].font);
2580         }
2581         frccur = -1;
2582         frclen = 0;
2583
2584         XftFontClose(xw.dpy, dc.font.match);
2585         FcPatternDestroy(dc.font.pattern);
2586         FcFontSetDestroy(dc.font.set);
2587         XftFontClose(xw.dpy, dc.bfont.match);
2588         FcPatternDestroy(dc.bfont.pattern);
2589         FcFontSetDestroy(dc.bfont.set);
2590         XftFontClose(xw.dpy, dc.ifont.match);
2591         FcPatternDestroy(dc.ifont.pattern);
2592         FcFontSetDestroy(dc.ifont.set);
2593         XftFontClose(xw.dpy, dc.ibfont.match);
2594         FcPatternDestroy(dc.ibfont.pattern);
2595         FcFontSetDestroy(dc.ibfont.set);
2596 }
2597
2598 void
2599 xzoom(const Arg *arg) {
2600         xunloadfonts();
2601         xloadfonts(usedfont, usedfontsize + arg->i);
2602         cresize(0, 0);
2603         redraw(0);
2604 }
2605
2606 void
2607 xinit(void) {
2608         XSetWindowAttributes attrs;
2609         XGCValues gcvalues;
2610         Cursor cursor;
2611         Window parent;
2612         int sw, sh;
2613
2614         if(!(xw.dpy = XOpenDisplay(NULL)))
2615                 die("Can't open display\n");
2616         xw.scr = XDefaultScreen(xw.dpy);
2617         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2618
2619         /* font */
2620         if(!FcInit())
2621                 die("Could not init fontconfig.\n");
2622
2623         usedfont = (opt_font == NULL)? font : opt_font;
2624         xloadfonts(usedfont, 0);
2625
2626         /* colors */
2627         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2628         xloadcols();
2629
2630         /* adjust fixed window geometry */
2631         if(xw.isfixed) {
2632                 sw = DisplayWidth(xw.dpy, xw.scr);
2633                 sh = DisplayHeight(xw.dpy, xw.scr);
2634                 if(xw.fx < 0)
2635                         xw.fx = sw + xw.fx - xw.fw - 1;
2636                 if(xw.fy < 0)
2637                         xw.fy = sh + xw.fy - xw.fh - 1;
2638
2639                 xw.h = xw.fh;
2640                 xw.w = xw.fw;
2641         } else {
2642                 /* window - default size */
2643                 xw.h = 2 * borderpx + term.row * xw.ch;
2644                 xw.w = 2 * borderpx + term.col * xw.cw;
2645                 xw.fx = 0;
2646                 xw.fy = 0;
2647         }
2648
2649         /* Events */
2650         attrs.background_pixel = dc.col[defaultbg].pixel;
2651         attrs.border_pixel = dc.col[defaultbg].pixel;
2652         attrs.bit_gravity = NorthWestGravity;
2653         attrs.event_mask = FocusChangeMask | KeyPressMask
2654                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2655                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2656         attrs.colormap = xw.cmap;
2657
2658         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2659                         XRootWindow(xw.dpy, xw.scr);
2660         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2661                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2662                         xw.vis,
2663                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2664                         | CWColormap,
2665                         &attrs);
2666
2667         memset(&gcvalues, 0, sizeof(gcvalues));
2668         gcvalues.graphics_exposures = False;
2669         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2670                         &gcvalues);
2671         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2672                         DefaultDepth(xw.dpy, xw.scr));
2673         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2674         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2675
2676         /* Xft rendering context */
2677         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2678
2679         /* input methods */
2680         if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2681                 XSetLocaleModifiers("@im=local");
2682                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2683                         XSetLocaleModifiers("@im=");
2684                         if((xw.xim = XOpenIM(xw.dpy,
2685                                         NULL, NULL, NULL)) == NULL) {
2686                                 die("XOpenIM failed. Could not open input"
2687                                         " device.\n");
2688                         }
2689                 }
2690         }
2691         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2692                                            | XIMStatusNothing, XNClientWindow, xw.win,
2693                                            XNFocusWindow, xw.win, NULL);
2694         if(xw.xic == NULL)
2695                 die("XCreateIC failed. Could not obtain input method.\n");
2696
2697         /* white cursor, black outline */
2698         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2699         XDefineCursor(xw.dpy, xw.win, cursor);
2700         XRecolorCursor(xw.dpy, cursor,
2701                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2702                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2703
2704         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2705         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2706         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2707
2708         xresettitle();
2709         XMapWindow(xw.dpy, xw.win);
2710         xhints();
2711         XSync(xw.dpy, 0);
2712 }
2713
2714 void
2715 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2716         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2717             width = charlen * xw.cw, xp, i;
2718         int frp, frcflags;
2719         int u8fl, u8fblen, u8cblen, doesexist;
2720         char *u8c, *u8fs;
2721         long u8char;
2722         Font *font = &dc.font;
2723         FcResult fcres;
2724         FcPattern *fcpattern, *fontpattern;
2725         FcFontSet *fcsets[] = { NULL };
2726         FcCharSet *fccharset;
2727         Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2728                  *temp, revfg, revbg;
2729         XRenderColor colfg, colbg;
2730
2731         frcflags = FRC_NORMAL;
2732
2733         if(base.mode & ATTR_BOLD) {
2734                 if(BETWEEN(base.fg, 0, 7)) {
2735                         /* basic system colors */
2736                         fg = &dc.col[base.fg + 8];
2737                 } else if(BETWEEN(base.fg, 16, 195)) {
2738                         /* 256 colors */
2739                         fg = &dc.col[base.fg + 36];
2740                 } else if(BETWEEN(base.fg, 232, 251)) {
2741                         /* greyscale */
2742                         fg = &dc.col[base.fg + 4];
2743                 }
2744                 /*
2745                  * Those ranges will not be brightened:
2746                  *      8 - 15 – bright system colors
2747                  *      196 - 231 – highest 256 color cube
2748                  *      252 - 255 – brightest colors in greyscale
2749                  */
2750                 font = &dc.bfont;
2751                 frcflags = FRC_BOLD;
2752         }
2753
2754         if(base.mode & ATTR_ITALIC) {
2755                 font = &dc.ifont;
2756                 frcflags = FRC_ITALIC;
2757         }
2758         if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2759                 font = &dc.ibfont;
2760                 frcflags = FRC_ITALICBOLD;
2761         }
2762
2763         if(IS_SET(MODE_REVERSE)) {
2764                 if(fg == &dc.col[defaultfg]) {
2765                         fg = &dc.col[defaultbg];
2766                 } else {
2767                         colfg.red = ~fg->color.red;
2768                         colfg.green = ~fg->color.green;
2769                         colfg.blue = ~fg->color.blue;
2770                         colfg.alpha = fg->color.alpha;
2771                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2772                         fg = &revfg;
2773                 }
2774
2775                 if(bg == &dc.col[defaultbg]) {
2776                         bg = &dc.col[defaultfg];
2777                 } else {
2778                         colbg.red = ~bg->color.red;
2779                         colbg.green = ~bg->color.green;
2780                         colbg.blue = ~bg->color.blue;
2781                         colbg.alpha = bg->color.alpha;
2782                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2783                         bg = &revbg;
2784                 }
2785         }
2786
2787         if(base.mode & ATTR_REVERSE) {
2788                 temp = fg;
2789                 fg = bg;
2790                 bg = temp;
2791         }
2792
2793         /* Intelligent cleaning up of the borders. */
2794         if(x == 0) {
2795                 xclear(0, (y == 0)? 0 : winy, borderpx,
2796                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2797         }
2798         if(x + charlen >= term.col) {
2799                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2800                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2801         }
2802         if(y == 0)
2803                 xclear(winx, 0, winx + width, borderpx);
2804         if(y == term.row-1)
2805                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2806
2807         /* Clean up the region we want to draw to. */
2808         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2809
2810         fcsets[0] = font->set;
2811         for(xp = winx; bytelen > 0;) {
2812                 /*
2813                  * Search for the range in the to be printed string of glyphs
2814                  * that are in the main font. Then print that range. If
2815                  * some glyph is found that is not in the font, do the
2816                  * fallback dance.
2817                  */
2818                 u8fs = s;
2819                 u8fblen = 0;
2820                 u8fl = 0;
2821                 for(;;) {
2822                         u8c = s;
2823                         u8cblen = utf8decode(s, &u8char);
2824                         s += u8cblen;
2825                         bytelen -= u8cblen;
2826
2827                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2828                         if(!doesexist || bytelen <= 0) {
2829                                 if(bytelen <= 0) {
2830                                         if(doesexist) {
2831                                                 u8fl++;
2832                                                 u8fblen += u8cblen;
2833                                         }
2834                                 }
2835
2836                                 if(u8fl > 0) {
2837                                         XftDrawStringUtf8(xw.draw, fg,
2838                                                         font->match, xp,
2839                                                         winy + font->ascent,
2840                                                         (FcChar8 *)u8fs,
2841                                                         u8fblen);
2842                                         xp += font->width * u8fl;
2843                                 }
2844                                 break;
2845                         }
2846
2847                         u8fl++;
2848                         u8fblen += u8cblen;
2849                 }
2850                 if(doesexist)
2851                         break;
2852
2853                 frp = frccur;
2854                 /* Search the font cache. */
2855                 for(i = 0; i < frclen; i++, frp--) {
2856                         if(frp <= 0)
2857                                 frp = LEN(frc) - 1;
2858
2859                         if(frc[frp].c == u8char
2860                                         && frc[frp].flags == frcflags) {
2861                                 break;
2862                         }
2863                 }
2864
2865                 /* Nothing was found. */
2866                 if(i >= frclen) {
2867                         /*
2868                          * Nothing was found in the cache. Now use
2869                          * some dozen of Fontconfig calls to get the
2870                          * font for one single character.
2871                          */
2872                         fcpattern = FcPatternDuplicate(font->pattern);
2873                         fccharset = FcCharSetCreate();
2874
2875                         FcCharSetAddChar(fccharset, u8char);
2876                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
2877                                         fccharset);
2878                         FcPatternAddBool(fcpattern, FC_SCALABLE,
2879                                         FcTrue);
2880
2881                         FcConfigSubstitute(0, fcpattern,
2882                                         FcMatchPattern);
2883                         FcDefaultSubstitute(fcpattern);
2884
2885                         fontpattern = FcFontSetMatch(0, fcsets,
2886                                         FcTrue, fcpattern, &fcres);
2887
2888                         /*
2889                          * Overwrite or create the new cache entry
2890                          * entry.
2891                          */
2892                         frccur++;
2893                         frclen++;
2894                         if(frccur >= LEN(frc))
2895                                 frccur = 0;
2896                         if(frclen > LEN(frc)) {
2897                                 frclen = LEN(frc);
2898                                 XftFontClose(xw.dpy, frc[frccur].font);
2899                         }
2900
2901                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
2902                                         fontpattern);
2903                         frc[frccur].c = u8char;
2904                         frc[frccur].flags = frcflags;
2905
2906                         FcPatternDestroy(fcpattern);
2907                         FcCharSetDestroy(fccharset);
2908
2909                         frp = frccur;
2910                 }
2911
2912                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2913                                 xp, winy + frc[frp].font->ascent,
2914                                 (FcChar8 *)u8c, u8cblen);
2915
2916                 xp += font->width;
2917         }
2918
2919         /*
2920         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2921                         winy + font->ascent, (FcChar8 *)s, bytelen);
2922         */
2923
2924         if(base.mode & ATTR_UNDERLINE) {
2925                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2926                                 width, 1);
2927         }
2928 }
2929
2930 void
2931 xdrawcursor(void) {
2932         static int oldx = 0, oldy = 0;
2933         int sl;
2934         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2935
2936         LIMIT(oldx, 0, term.col-1);
2937         LIMIT(oldy, 0, term.row-1);
2938
2939         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2940                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2941
2942         /* remove the old cursor */
2943         if(term.line[oldy][oldx].state & GLYPH_SET) {
2944                 sl = utf8size(term.line[oldy][oldx].c);
2945                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2946                                 oldy, 1, sl);
2947         } else {
2948                 xtermclear(oldx, oldy, oldx, oldy);
2949         }
2950
2951         /* draw the new one */
2952         if(!(IS_SET(MODE_HIDE))) {
2953                 if(!(xw.state & WIN_FOCUSED))
2954                         g.bg = defaultucs;
2955
2956                 if(IS_SET(MODE_REVERSE))
2957                         g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2958
2959                 sl = utf8size(g.c);
2960                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2961                 oldx = term.c.x, oldy = term.c.y;
2962         }
2963 }
2964
2965
2966 void
2967 xsettitle(char *p) {
2968         XTextProperty prop;
2969
2970         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2971                         &prop);
2972         XSetWMName(xw.dpy, xw.win, &prop);
2973 }
2974
2975 void
2976 xresettitle(void) {
2977         xsettitle(opt_title ? opt_title : "st");
2978 }
2979
2980 void
2981 redraw(int timeout) {
2982         struct timespec tv = {0, timeout * 1000};
2983
2984         tfulldirt();
2985         draw();
2986
2987         if(timeout > 0) {
2988                 nanosleep(&tv, NULL);
2989                 XSync(xw.dpy, False); /* necessary for a good tput flash */
2990         }
2991 }
2992
2993 void
2994 draw(void) {
2995         drawregion(0, 0, term.col, term.row);
2996         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2997                         xw.h, 0, 0);
2998         XSetForeground(xw.dpy, dc.gc,
2999                         dc.col[IS_SET(MODE_REVERSE)?
3000                                 defaultfg : defaultbg].pixel);
3001 }
3002
3003 void
3004 drawregion(int x1, int y1, int x2, int y2) {
3005         int ic, ib, x, y, ox, sl;
3006         Glyph base, new;
3007         char buf[DRAW_BUF_SIZ];
3008         bool ena_sel = sel.bx != -1;
3009
3010         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3011                 ena_sel = 0;
3012
3013         if(!(xw.state & WIN_VISIBLE))
3014                 return;
3015
3016         for(y = y1; y < y2; y++) {
3017                 if(!term.dirty[y])
3018                         continue;
3019
3020                 xtermclear(0, y, term.col, y);
3021                 term.dirty[y] = 0;
3022                 base = term.line[y][0];
3023                 ic = ib = ox = 0;
3024                 for(x = x1; x < x2; x++) {
3025                         new = term.line[y][x];
3026                         if(ena_sel && *(new.c) && selected(x, y))
3027                                 new.mode ^= ATTR_REVERSE;
3028                         if(ib > 0 && (!(new.state & GLYPH_SET)
3029                                         || ATTRCMP(base, new)
3030                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3031                                 xdraws(buf, base, ox, y, ic, ib);
3032                                 ic = ib = 0;
3033                         }
3034                         if(new.state & GLYPH_SET) {
3035                                 if(ib == 0) {
3036                                         ox = x;
3037                                         base = new;
3038                                 }
3039
3040                                 sl = utf8size(new.c);
3041                                 memcpy(buf+ib, new.c, sl);
3042                                 ib += sl;
3043                                 ++ic;
3044                         }
3045                 }
3046                 if(ib > 0)
3047                         xdraws(buf, base, ox, y, ic, ib);
3048         }
3049         xdrawcursor();
3050 }
3051
3052 void
3053 expose(XEvent *ev) {
3054         XExposeEvent *e = &ev->xexpose;
3055
3056         if(xw.state & WIN_REDRAW) {
3057                 if(!e->count)
3058                         xw.state &= ~WIN_REDRAW;
3059         }
3060         redraw(0);
3061 }
3062
3063 void
3064 visibility(XEvent *ev) {
3065         XVisibilityEvent *e = &ev->xvisibility;
3066
3067         if(e->state == VisibilityFullyObscured) {
3068                 xw.state &= ~WIN_VISIBLE;
3069         } else if(!(xw.state & WIN_VISIBLE)) {
3070                 /* need a full redraw for next Expose, not just a buf copy */
3071                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3072         }
3073 }
3074
3075 void
3076 unmap(XEvent *ev) {
3077         xw.state &= ~WIN_VISIBLE;
3078 }
3079
3080 void
3081 xseturgency(int add) {
3082         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3083
3084         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3085         XSetWMHints(xw.dpy, xw.win, h);
3086         XFree(h);
3087 }
3088
3089 void
3090 focus(XEvent *ev) {
3091         XFocusChangeEvent *e = &ev->xfocus;
3092
3093         if(e->mode == NotifyGrab)
3094                 return;
3095
3096         if(ev->type == FocusIn) {
3097                 XSetICFocus(xw.xic);
3098                 xw.state |= WIN_FOCUSED;
3099                 xseturgency(0);
3100         } else {
3101                 XUnsetICFocus(xw.xic);
3102                 xw.state &= ~WIN_FOCUSED;
3103         }
3104 }
3105
3106 inline bool
3107 match(uint mask, uint state) {
3108         state &= ~(ignoremod);
3109
3110         if(mask == XK_NO_MOD && state)
3111                 return false;
3112         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3113                 return false;
3114         if((state & mask) != state)
3115                 return false;
3116         return true;
3117 }
3118
3119 void
3120 numlock(const Arg *dummy) {
3121         term.numlock ^= 1;
3122 }
3123
3124 char*
3125 kmap(KeySym k, uint state) {
3126         uint mask;
3127         Key *kp;
3128         int i;
3129
3130         /* Check for mapped keys out of X11 function keys. */
3131         for(i = 0; i < LEN(mappedkeys); i++) {
3132                 if(mappedkeys[i] == k)
3133                         break;
3134         }
3135         if(i == LEN(mappedkeys)) {
3136                 if((k & 0xFFFF) < 0xFD00)
3137                         return NULL;
3138         }
3139
3140         for(kp = key; kp < key + LEN(key); kp++) {
3141                 mask = kp->mask;
3142
3143                 if(kp->k != k)
3144                         continue;
3145
3146                 if(!match(mask, state))
3147                         continue;
3148
3149                 if(kp->appkey > 0) {
3150                         if(!IS_SET(MODE_APPKEYPAD))
3151                                 continue;
3152                         if(term.numlock && kp->appkey == 2)
3153                                 continue;
3154                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3155                         continue;
3156                 }
3157
3158                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3159                                 (kp->appcursor > 0
3160                                  && !IS_SET(MODE_APPCURSOR))) {
3161                         continue;
3162                 }
3163
3164                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3165                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3166                         continue;
3167                 }
3168
3169                 return kp->s;
3170         }
3171
3172         return NULL;
3173 }
3174
3175 void
3176 kpress(XEvent *ev) {
3177         XKeyEvent *e = &ev->xkey;
3178         KeySym ksym;
3179         char xstr[31], buf[32], *customkey, *cp = buf;
3180         int len;
3181         Status status;
3182         Shortcut *bp;
3183
3184         if(IS_SET(MODE_KBDLOCK))
3185                 return;
3186
3187         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3188         e->state &= ~Mod2Mask;
3189         /* 1. shortcuts */
3190         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3191                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3192                         bp->func(&(bp->arg));
3193                         return;
3194                 }
3195         }
3196
3197         /* 2. custom keys from config.h */
3198         if((customkey = kmap(ksym, e->state))) {
3199                 len = strlen(customkey);
3200                 memcpy(buf, customkey, len);
3201         /* 2. hardcoded (overrides X lookup) */
3202         } else {
3203                 if(len == 0)
3204                         return;
3205
3206                 if(len == 1 && e->state & Mod1Mask)
3207                         *cp++ = '\033';
3208
3209                 memcpy(cp, xstr, len);
3210                 len = cp - buf + len;
3211         }
3212
3213         ttywrite(buf, len);
3214         if(IS_SET(MODE_ECHO))
3215                 techo(buf, len);
3216 }
3217
3218
3219 void
3220 cmessage(XEvent *e) {
3221         /*
3222          * See xembed specs
3223          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3224          */
3225         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3226                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3227                         xw.state |= WIN_FOCUSED;
3228                         xseturgency(0);
3229                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3230                         xw.state &= ~WIN_FOCUSED;
3231                 }
3232         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3233                 /* Send SIGHUP to shell */
3234                 kill(pid, SIGHUP);
3235                 exit(EXIT_SUCCESS);
3236         }
3237 }
3238
3239 void
3240 cresize(int width, int height) {
3241         int col, row;
3242
3243         if(width != 0)
3244                 xw.w = width;
3245         if(height != 0)
3246                 xw.h = height;
3247
3248         col = (xw.w - 2 * borderpx) / xw.cw;
3249         row = (xw.h - 2 * borderpx) / xw.ch;
3250
3251         tresize(col, row);
3252         xresize(col, row);
3253         ttyresize();
3254 }
3255
3256 void
3257 resize(XEvent *e) {
3258         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3259                 return;
3260
3261         cresize(e->xconfigure.width, e->xconfigure.height);
3262 }
3263
3264 void
3265 run(void) {
3266         XEvent ev;
3267         fd_set rfd;
3268         int xfd = XConnectionNumber(xw.dpy), xev;
3269         struct timeval drawtimeout, *tv = NULL, now, last;
3270
3271         gettimeofday(&last, NULL);
3272
3273         for(xev = actionfps;;) {
3274                 FD_ZERO(&rfd);
3275                 FD_SET(cmdfd, &rfd);
3276                 FD_SET(xfd, &rfd);
3277                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3278                         if(errno == EINTR)
3279                                 continue;
3280                         die("select failed: %s\n", SERRNO);
3281                 }
3282
3283                 gettimeofday(&now, NULL);
3284                 drawtimeout.tv_sec = 0;
3285                 drawtimeout.tv_usec = (1000/xfps) * 1000;
3286                 tv = &drawtimeout;
3287
3288                 if(FD_ISSET(cmdfd, &rfd))
3289                         ttyread();
3290
3291                 if(FD_ISSET(xfd, &rfd))
3292                         xev = actionfps;
3293
3294                 if(TIMEDIFF(now, last) > \
3295                                 (xev ? (1000/xfps) : (1000/actionfps))) {
3296                         while(XPending(xw.dpy)) {
3297                                 XNextEvent(xw.dpy, &ev);
3298                                 if(XFilterEvent(&ev, None))
3299                                         continue;
3300                                 if(handler[ev.type])
3301                                         (handler[ev.type])(&ev);
3302                         }
3303
3304                         draw();
3305                         XFlush(xw.dpy);
3306                         last = now;
3307
3308                         if(xev && !FD_ISSET(xfd, &rfd))
3309                                 xev--;
3310                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3311                                 tv = NULL;
3312                 }
3313         }
3314 }
3315
3316 int
3317 main(int argc, char *argv[]) {
3318         int i, bitm, xr, yr;
3319         uint wr, hr;
3320
3321         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3322         xw.isfixed = False;
3323
3324         for(i = 1; i < argc; i++) {
3325                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3326                 case 'c':
3327                         if(++i < argc)
3328                                 opt_class = argv[i];
3329                         break;
3330                 case 'e':
3331                         /* eat all remaining arguments */
3332                         if(++i < argc)
3333                                 opt_cmd = &argv[i];
3334                         goto run;
3335                 case 'f':
3336                         if(++i < argc)
3337                                 opt_font = argv[i];
3338                         break;
3339                 case 'g':
3340                         if(++i >= argc)
3341                                 break;
3342
3343                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3344                         if(bitm & XValue)
3345                                 xw.fx = xr;
3346                         if(bitm & YValue)
3347                                 xw.fy = yr;
3348                         if(bitm & WidthValue)
3349                                 xw.fw = (int)wr;
3350                         if(bitm & HeightValue)
3351                                 xw.fh = (int)hr;
3352                         if(bitm & XNegative && xw.fx == 0)
3353                                 xw.fx = -1;
3354                         if(bitm & XNegative && xw.fy == 0)
3355                                 xw.fy = -1;
3356
3357                         if(xw.fh != 0 && xw.fw != 0)
3358                                 xw.isfixed = True;
3359                         break;
3360                 case 'o':
3361                         if(++i < argc)
3362                                 opt_io = argv[i];
3363                         break;
3364                 case 't':
3365                         if(++i < argc)
3366                                 opt_title = argv[i];
3367                         break;
3368                 case 'v':
3369                 default:
3370                         die(USAGE);
3371                 case 'w':
3372                         if(++i < argc)
3373                                 opt_embed = argv[i];
3374                         break;
3375                 }
3376         }
3377
3378 run:
3379         setlocale(LC_CTYPE, "");
3380         XSetLocaleModifiers("");
3381         tnew(80, 24);
3382         xinit();
3383         ttynew();
3384         selinit();
3385         run();
3386
3387         return 0;
3388 }
3389