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