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