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