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