JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
This adds the fontcache dependency to try something out. Additionally the
[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 <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
30 #define Glyph Glyph_
31 #define Font Font_
32
33 #if   defined(__linux)
34  #include <pty.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36  #include <util.h>
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
38  #include <libutil.h>
39 #endif
40
41 #define USAGE \
42         "st " VERSION " (c) 2010-2012 st engineers\n" \
43         "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44         " [-t title] [-w windowid] [-e command ...]\n"
45
46 /* XEMBED messages */
47 #define XEMBED_FOCUS_IN  4
48 #define XEMBED_FOCUS_OUT 5
49
50 /* Arbitrary sizes */
51 #define ESC_BUF_SIZ   256
52 #define ESC_ARG_SIZ   16
53 #define STR_BUF_SIZ   256
54 #define STR_ARG_SIZ   16
55 #define DRAW_BUF_SIZ  20*1024
56 #define UTF_SIZ       4
57 #define XK_NO_MOD     UINT_MAX
58 #define XK_ANY_MOD    0
59
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61
62 #define SERRNO strerror(errno)
63 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
64 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
65 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74
75 enum glyph_attribute {
76         ATTR_NULL      = 0,
77         ATTR_REVERSE   = 1,
78         ATTR_UNDERLINE = 2,
79         ATTR_BOLD      = 4,
80         ATTR_GFX       = 8,
81         ATTR_ITALIC    = 16,
82         ATTR_BLINK     = 32,
83 };
84
85 enum cursor_movement {
86         CURSOR_UP,
87         CURSOR_DOWN,
88         CURSOR_LEFT,
89         CURSOR_RIGHT,
90         CURSOR_SAVE,
91         CURSOR_LOAD
92 };
93
94 enum cursor_state {
95         CURSOR_DEFAULT  = 0,
96         CURSOR_HIDE     = 1,
97         CURSOR_WRAPNEXT = 2
98 };
99
100 enum glyph_state {
101         GLYPH_SET   = 1,
102         GLYPH_DIRTY = 2
103 };
104
105 enum term_mode {
106         MODE_WRAP       = 1,
107         MODE_INSERT      = 2,
108         MODE_APPKEYPAD   = 4,
109         MODE_ALTSCREEN   = 8,
110         MODE_CRLF       = 16,
111         MODE_MOUSEBTN    = 32,
112         MODE_MOUSEMOTION = 64,
113         MODE_MOUSE       = 32|64,
114         MODE_REVERSE     = 128,
115         MODE_KBDLOCK     = 256
116 };
117
118 enum escape_state {
119         ESC_START      = 1,
120         ESC_CSI = 2,
121         ESC_STR = 4, /* DSC, OSC, PM, APC */
122         ESC_ALTCHARSET = 8,
123         ESC_STR_END    = 16, /* a final string was encountered */
124 };
125
126 enum window_state {
127         WIN_VISIBLE = 1,
128         WIN_REDRAW  = 2,
129         WIN_FOCUSED = 4
130 };
131
132 /* bit macro */
133 #undef B0
134 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
135
136 typedef unsigned char uchar;
137 typedef unsigned int uint;
138 typedef unsigned long ulong;
139 typedef unsigned short ushort;
140
141 typedef struct {
142         char c[UTF_SIZ];     /* character code */
143         uchar mode;  /* attribute flags */
144         ushort fg;   /* foreground  */
145         ushort bg;   /* background  */
146         uchar state; /* state flags    */
147 } Glyph;
148
149 typedef Glyph* Line;
150
151 typedef struct {
152         Glyph attr;      /* current char attributes */
153         int x;
154         int y;
155         char state;
156 } TCursor;
157
158 /* CSI Escape sequence structs */
159 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
160 typedef struct {
161         char buf[ESC_BUF_SIZ]; /* raw string */
162         int len;               /* raw string length */
163         char priv;
164         int arg[ESC_ARG_SIZ];
165         int narg;             /* nb of args */
166         char mode;
167 } CSIEscape;
168
169 /* STR Escape sequence structs */
170 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
171 typedef struct {
172         char type;           /* ESC type ... */
173         char buf[STR_BUF_SIZ]; /* raw string */
174         int len;               /* raw string length */
175         char *args[STR_ARG_SIZ];
176         int narg;             /* nb of args */
177 } STREscape;
178
179 /* Internal representation of the screen */
180 typedef struct {
181         int row;        /* nb row */
182         int col;        /* nb col */
183         Line* line;     /* screen */
184         Line* alt;      /* alternate screen */
185         bool* dirty;    /* dirtyness of lines */
186         TCursor c;      /* cursor */
187         int top;        /* top    scroll limit */
188         int bot;        /* bottom scroll limit */
189         int mode;       /* terminal mode flags */
190         int esc;        /* escape state flags */
191         bool *tabs;
192 } Term;
193
194 /* Purely graphic info */
195 typedef struct {
196         Display* dpy;
197         Colormap cmap;
198         Window win;
199         XdbeBackBuffer buf;
200         Atom xembed;
201         XIM xim;
202         XIC xic;
203         XftDraw *xft_draw;
204         Visual *vis;
205         int scr;
206         bool isfixed; /* is fixed geometry? */
207         int fx, fy, fw, fh; /* fixed geometry */
208         int tw, th; /* tty width and height */
209         int w;  /* window width */
210         int h;  /* window height */
211         int ch; /* char height */
212         int cw; /* char width  */
213         char state; /* focus, redraw, visible */
214 } XWindow;
215
216 typedef struct {
217         KeySym k;
218         uint mask;
219         char s[ESC_BUF_SIZ];
220 } Key;
221
222 /* TODO: use better name for vars... */
223 typedef struct {
224         int mode;
225         int bx, by;
226         int ex, ey;
227         struct {int x, y;} b, e;
228         char *clip;
229         Atom xtarget;
230         bool alt;
231         struct timeval tclick1;
232         struct timeval tclick2;
233 } Selection;
234
235 #include "config.h"
236
237 /* Font structure */
238 typedef struct {
239         int height;
240         int width;
241         int ascent;
242         int descent;
243         short lbearing;
244         short rbearing;
245         XftFont* xft_set;
246 } Font;
247
248 /* Drawing Context */
249 typedef struct {
250         XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
251         GC gc;
252         Font font, bfont, ifont, ibfont;
253 } DC;
254
255 static void die(const char*, ...);
256 static void draw(void);
257 static void redraw(void);
258 static void drawregion(int, int, int, int);
259 static void execsh(void);
260 static void sigchld(int);
261 static void run(void);
262
263 static void csidump(void);
264 static void csihandle(void);
265 static void csiparse(void);
266 static void csireset(void);
267 static void strdump(void);
268 static void strhandle(void);
269 static void strparse(void);
270 static void strreset(void);
271
272 static void tclearregion(int, int, int, int);
273 static void tcursor(int);
274 static void tdeletechar(int);
275 static void tdeleteline(int);
276 static void tinsertblank(int);
277 static void tinsertblankline(int);
278 static void tmoveto(int, int);
279 static void tnew(int, int);
280 static void tnewline(int);
281 static void tputtab(bool);
282 static void tputc(char*, int);
283 static void treset(void);
284 static int tresize(int, int);
285 static void tscrollup(int, int);
286 static void tscrolldown(int, int);
287 static void tsetattr(int*, int);
288 static void tsetchar(char*);
289 static void tsetscroll(int, int);
290 static void tswapscreen(void);
291 static void tsetdirt(int, int);
292 static void tsetmode(bool, bool, int *, int);
293 static void tfulldirt(void);
294
295 static void ttynew(void);
296 static void ttyread(void);
297 static void ttyresize(void);
298 static void ttywrite(const char *, size_t);
299
300 static void xdraws(char *, Glyph, int, int, int, int);
301 static void xhints(void);
302 static void xclear(int, int, int, int);
303 static void xclearborders(void);
304 static void xdrawcursor(void);
305 static void xinit(void);
306 static void xloadcols(void);
307 static void xresettitle(void);
308 static void xseturgency(int);
309 static void xsetsel(char*);
310 static void xtermclear(int, int, int, int);
311 static void xresize(int, int);
312
313 static void expose(XEvent *);
314 static void visibility(XEvent *);
315 static void unmap(XEvent *);
316 static char* kmap(KeySym, uint);
317 static void kpress(XEvent *);
318 static void cmessage(XEvent *);
319 static void resize(XEvent *);
320 static void focus(XEvent *);
321 static void brelease(XEvent *);
322 static void bpress(XEvent *);
323 static void bmotion(XEvent *);
324 static void selnotify(XEvent *);
325 static void selclear(XEvent *);
326 static void selrequest(XEvent *);
327
328 static void selinit(void);
329 static inline bool selected(int, int);
330 static void selcopy(void);
331 static void selpaste(void);
332 static void selscroll(int, int);
333
334 static int utf8decode(char *, long *);
335 static int utf8encode(long *, char *);
336 static int utf8size(char *);
337 static int isfullutf8(char *, int);
338
339 static void *xmalloc(size_t);
340 static void *xrealloc(void *, size_t);
341 static void *xcalloc(size_t nmemb, size_t size);
342 static char *smstrcat(char *, ...);
343
344 static void (*handler[LASTEvent])(XEvent *) = {
345         [KeyPress] = kpress,
346         [ClientMessage] = cmessage,
347         [ConfigureNotify] = resize,
348         [VisibilityNotify] = visibility,
349         [UnmapNotify] = unmap,
350         [Expose] = expose,
351         [FocusIn] = focus,
352         [FocusOut] = focus,
353         [MotionNotify] = bmotion,
354         [ButtonPress] = bpress,
355         [ButtonRelease] = brelease,
356         [SelectionClear] = selclear,
357         [SelectionNotify] = selnotify,
358         [SelectionRequest] = selrequest,
359 };
360
361 /* Globals */
362 static DC dc;
363 static XWindow xw;
364 static Term term;
365 static CSIEscape csiescseq;
366 static STREscape strescseq;
367 static int cmdfd;
368 static pid_t pid;
369 static Selection sel;
370 static int iofd = -1;
371 static char **opt_cmd = NULL;
372 static char *opt_io = NULL;
373 static char *opt_title = NULL;
374 static char *opt_embed = NULL;
375 static char *opt_class = NULL;
376 static char *opt_font = NULL;
377
378 void *
379 xmalloc(size_t len) {
380         void *p = malloc(len);
381         if(!p)
382                 die("Out of memory\n");
383         return p;
384 }
385
386 void *
387 xrealloc(void *p, size_t len) {
388         if((p = realloc(p, len)) == NULL)
389                 die("Out of memory\n");
390         return p;
391 }
392
393 void *
394 xcalloc(size_t nmemb, size_t size) {
395         void *p = calloc(nmemb, size);
396         if(!p)
397                 die("Out of memory\n");
398         return p;
399 }
400
401 char *
402 smstrcat(char *src, ...)
403 {
404         va_list fmtargs;
405         char *ret, *p, *v;
406         int len, slen, flen;
407
408         len = slen = strlen(src);
409
410         va_start(fmtargs, src);
411         for(;;) {
412                 v = va_arg(fmtargs, char *);
413                 if(v == NULL)
414                         break;
415                 len += strlen(v);
416         }
417         va_end(fmtargs);
418
419         p = ret = xmalloc(len+1);
420         memmove(p, src, slen);
421         p += slen;
422
423         va_start(fmtargs, src);
424         for(;;) {
425                 v = va_arg(fmtargs, char *);
426                 if(v == NULL)
427                         break;
428                 flen = strlen(v);
429                 memmove(p, v, flen);
430                 p += flen;
431         }
432         va_end(fmtargs);
433
434         ret[len] = '\0';
435
436         return ret;
437 }
438
439 int
440 utf8decode(char *s, long *u) {
441         uchar c;
442         int i, n, rtn;
443
444         rtn = 1;
445         c = *s;
446         if(~c & B7) { /* 0xxxxxxx */
447                 *u = c;
448                 return rtn;
449         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
450                 *u = c&(B4|B3|B2|B1|B0);
451                 n = 1;
452         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
453                 *u = c&(B3|B2|B1|B0);
454                 n = 2;
455         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
456                 *u = c & (B2|B1|B0);
457                 n = 3;
458         } else
459                 goto invalid;
460         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
461                 c = *s;
462                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
463                         goto invalid;
464                 *u <<= 6;
465                 *u |= c & (B5|B4|B3|B2|B1|B0);
466         }
467         if((n == 1 && *u < 0x80) ||
468            (n == 2 && *u < 0x800) ||
469            (n == 3 && *u < 0x10000) ||
470            (*u >= 0xD800 && *u <= 0xDFFF))
471                 goto invalid;
472         return rtn;
473 invalid:
474         *u = 0xFFFD;
475         return rtn;
476 }
477
478 int
479 utf8encode(long *u, char *s) {
480         uchar *sp;
481         ulong uc;
482         int i, n;
483
484         sp = (uchar*) s;
485         uc = *u;
486         if(uc < 0x80) {
487                 *sp = uc; /* 0xxxxxxx */
488                 return 1;
489         } else if(*u < 0x800) {
490                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
491                 n = 1;
492         } else if(uc < 0x10000) {
493                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
494                 n = 2;
495         } else if(uc <= 0x10FFFF) {
496                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
497                 n = 3;
498         } else {
499                 goto invalid;
500         }
501         for(i=n,++sp; i>0; --i,++sp)
502                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
503         return n+1;
504 invalid:
505         /* U+FFFD */
506         *s++ = '\xEF';
507         *s++ = '\xBF';
508         *s = '\xBD';
509         return 3;
510 }
511
512 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
513    UTF-8 otherwise return 0 */
514 int
515 isfullutf8(char *s, int b) {
516         uchar *c1, *c2, *c3;
517
518         c1 = (uchar *) s;
519         c2 = (uchar *) ++s;
520         c3 = (uchar *) ++s;
521         if(b < 1)
522                 return 0;
523         else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
524                 return 0;
525         else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
526             ((b == 1) ||
527             ((b == 2) && (*c2&(B7|B6)) == B7)))
528                 return 0;
529         else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
530             ((b == 1) ||
531             ((b == 2) && (*c2&(B7|B6)) == B7) ||
532             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
533                 return 0;
534         else
535                 return 1;
536 }
537
538 int
539 utf8size(char *s) {
540         uchar c = *s;
541
542         if(~c&B7)
543                 return 1;
544         else if((c&(B7|B6|B5)) == (B7|B6))
545                 return 2;
546         else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
547                 return 3;
548         else
549                 return 4;
550 }
551
552 void
553 selinit(void) {
554         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
555         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
556         sel.mode = 0;
557         sel.bx = -1;
558         sel.clip = NULL;
559         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
560         if(sel.xtarget == None)
561                 sel.xtarget = XA_STRING;
562 }
563
564 static inline bool
565 selected(int x, int y) {
566         if(sel.ey == y && sel.by == y) {
567                 int bx = MIN(sel.bx, sel.ex);
568                 int ex = MAX(sel.bx, sel.ex);
569                 return BETWEEN(x, bx, ex);
570         }
571         return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
572                 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
573 }
574
575 void
576 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
577         if(b)
578                 *b = e->xbutton.button;
579
580         *x = X2COL(e->xbutton.x);
581         *y = Y2ROW(e->xbutton.y);
582         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
583         sel.b.y = MIN(sel.by, sel.ey);
584         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
585         sel.e.y = MAX(sel.by, sel.ey);
586 }
587
588 void
589 mousereport(XEvent *e) {
590         int x = X2COL(e->xbutton.x);
591         int y = Y2ROW(e->xbutton.y);
592         int button = e->xbutton.button;
593         int state = e->xbutton.state;
594         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
595         static int ob, ox, oy;
596
597         /* from urxvt */
598         if(e->xbutton.type == MotionNotify) {
599                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
600                         return;
601                 button = ob + 32;
602                 ox = x, oy = y;
603         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
604                 button = 3;
605         } else {
606                 button -= Button1;
607                 if(button >= 3)
608                         button += 64 - 3;
609                 if(e->xbutton.type == ButtonPress) {
610                         ob = button;
611                         ox = x, oy = y;
612                 }
613         }
614
615         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
616                 + (state & Mod4Mask    ? 8  : 0)
617                 + (state & ControlMask ? 16 : 0);
618
619         ttywrite(buf, sizeof(buf));
620 }
621
622 void
623 bpress(XEvent *e) {
624         if(IS_SET(MODE_MOUSE))
625                 mousereport(e);
626         else if(e->xbutton.button == Button1) {
627                 if(sel.bx != -1) {
628                         sel.bx = -1;
629                         tsetdirt(sel.b.y, sel.e.y);
630                         draw();
631                 }
632                 sel.mode = 1;
633                 sel.ex = sel.bx = X2COL(e->xbutton.x);
634                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
635         }
636 }
637
638 void
639 selcopy(void) {
640         char *str, *ptr;
641         int x, y, bufsize, is_selected = 0;
642
643         if(sel.bx == -1)
644                 str = NULL;
645
646         else {
647                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
648                 ptr = str = xmalloc(bufsize);
649
650                 /* append every set & selected glyph to the selection */
651                 for(y = 0; y < term.row; y++) {
652                         for(x = 0; x < term.col; x++) {
653                                 int size;
654                                 char *p;
655                                 Glyph *gp = &term.line[y][x];
656
657                                 if(!(is_selected = selected(x, y)))
658                                         continue;
659                                 p = (gp->state & GLYPH_SET) ? gp->c : " ";
660                                 size = utf8size(p);
661                                 memcpy(ptr, p, size);
662                                 ptr += size;
663                         }
664                         /* \n at the end of every selected line except for the last one */
665                         if(is_selected && y < sel.e.y)
666                                 *ptr++ = '\n';
667                 }
668                 *ptr = 0;
669         }
670         sel.alt = IS_SET(MODE_ALTSCREEN);
671         xsetsel(str);
672 }
673
674 void
675 selnotify(XEvent *e) {
676         ulong nitems, ofs, rem;
677         int format;
678         uchar *data;
679         Atom type;
680
681         ofs = 0;
682         do {
683                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
684                                         False, AnyPropertyType, &type, &format,
685                                         &nitems, &rem, &data)) {
686                         fprintf(stderr, "Clipboard allocation failed\n");
687                         return;
688                 }
689                 ttywrite((const char *) data, nitems * format / 8);
690                 XFree(data);
691                 /* number of 32-bit chunks returned */
692                 ofs += nitems * format / 32;
693         } while(rem > 0);
694 }
695
696 void
697 selpaste() {
698         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
699 }
700
701 void selclear(XEvent *e) {
702         if(sel.bx == -1)
703                 return;
704         sel.bx = -1;
705         tsetdirt(sel.b.y, sel.e.y);
706 }
707
708 void
709 selrequest(XEvent *e) {
710         XSelectionRequestEvent *xsre;
711         XSelectionEvent xev;
712         Atom xa_targets;
713
714         xsre = (XSelectionRequestEvent *) e;
715         xev.type = SelectionNotify;
716         xev.requestor = xsre->requestor;
717         xev.selection = xsre->selection;
718         xev.target = xsre->target;
719         xev.time = xsre->time;
720         /* reject */
721         xev.property = None;
722
723         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
724         if(xsre->target == xa_targets) {
725                 /* respond with the supported type */
726                 Atom string = sel.xtarget;
727                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
728                                 XA_ATOM, 32, PropModeReplace,
729                                 (uchar *) &string, 1);
730                 xev.property = xsre->property;
731         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
732                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
733                                 xsre->target, 8, PropModeReplace,
734                                 (uchar *) sel.clip, strlen(sel.clip));
735                 xev.property = xsre->property;
736         }
737
738         /* all done, send a notification to the listener */
739         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
740                 fprintf(stderr, "Error sending SelectionNotify event\n");
741 }
742
743 void
744 xsetsel(char *str) {
745         /* register the selection for both the clipboard and the primary */
746         Atom clipboard;
747
748         free(sel.clip);
749         sel.clip = str;
750
751         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
752
753         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
754         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
755 }
756
757 void
758 brelease(XEvent *e) {
759         if(IS_SET(MODE_MOUSE)) {
760                 mousereport(e);
761                 return;
762         }
763         if(e->xbutton.button == Button2)
764                 selpaste();
765         else if(e->xbutton.button == Button1) {
766                 sel.mode = 0;
767                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
768                 term.dirty[sel.ey] = 1;
769                 if(sel.bx == sel.ex && sel.by == sel.ey) {
770                         struct timeval now;
771                         sel.bx = -1;
772                         gettimeofday(&now, NULL);
773
774                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
775                                 /* triple click on the line */
776                                 sel.b.x = sel.bx = 0;
777                                 sel.e.x = sel.ex = term.col;
778                                 sel.b.y = sel.e.y = sel.ey;
779                                 selcopy();
780                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
781                                 /* double click to select word */
782                                 sel.bx = sel.ex;
783                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
784                                           term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
785                                 sel.b.x = sel.bx;
786                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
787                                           term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
788                                 sel.e.x = sel.ex;
789                                 sel.b.y = sel.e.y = sel.ey;
790                                 selcopy();
791                         }
792                 } else
793                         selcopy();
794         }
795         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
796         gettimeofday(&sel.tclick1, NULL);
797 }
798
799 void
800 bmotion(XEvent *e) {
801         if(IS_SET(MODE_MOUSE)) {
802                 mousereport(e);
803                 return;
804         }
805         if(sel.mode) {
806                 int oldey = sel.ey, oldex = sel.ex;
807                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
808
809                 if(oldey != sel.ey || oldex != sel.ex) {
810                         int starty = MIN(oldey, sel.ey);
811                         int endy = MAX(oldey, sel.ey);
812                         tsetdirt(starty, endy);
813                 }
814         }
815 }
816
817 void
818 die(const char *errstr, ...) {
819         va_list ap;
820
821         va_start(ap, errstr);
822         vfprintf(stderr, errstr, ap);
823         va_end(ap);
824         exit(EXIT_FAILURE);
825 }
826
827 void
828 execsh(void) {
829         char **args;
830         char *envshell = getenv("SHELL");
831
832         unsetenv("COLUMNS");
833         unsetenv("LINES");
834         unsetenv("TERMCAP");
835
836         signal(SIGCHLD, SIG_DFL);
837         signal(SIGHUP, SIG_DFL);
838         signal(SIGINT, SIG_DFL);
839         signal(SIGQUIT, SIG_DFL);
840         signal(SIGTERM, SIG_DFL);
841         signal(SIGALRM, SIG_DFL);
842
843         DEFAULT(envshell, SHELL);
844         putenv("TERM="TNAME);
845         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
846         execvp(args[0], args);
847         exit(EXIT_FAILURE);
848 }
849
850 void
851 sigchld(int a) {
852         int stat = 0;
853         if(waitpid(pid, &stat, 0) < 0)
854                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
855         if(WIFEXITED(stat))
856                 exit(WEXITSTATUS(stat));
857         else
858                 exit(EXIT_FAILURE);
859 }
860
861 void
862 ttynew(void) {
863         int m, s;
864
865         /* seems to work fine on linux, openbsd and freebsd */
866         struct winsize w = {term.row, term.col, 0, 0};
867         if(openpty(&m, &s, NULL, NULL, &w) < 0)
868                 die("openpty failed: %s\n", SERRNO);
869
870         switch(pid = fork()) {
871         case -1:
872                 die("fork failed\n");
873                 break;
874         case 0:
875                 setsid(); /* create a new process group */
876                 dup2(s, STDIN_FILENO);
877                 dup2(s, STDOUT_FILENO);
878                 dup2(s, STDERR_FILENO);
879                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
880                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
881                 close(s);
882                 close(m);
883                 execsh();
884                 break;
885         default:
886                 close(s);
887                 cmdfd = m;
888                 signal(SIGCHLD, sigchld);
889                 if(opt_io) {
890                         if(!strcmp(opt_io, "-")) {
891                                 iofd = STDOUT_FILENO;
892                         } else {
893                                 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
894                                         fprintf(stderr, "Error opening %s:%s\n",
895                                                 opt_io, strerror(errno));
896                                 }
897                         }
898                 }
899         }
900 }
901
902 void
903 dump(char c) {
904         static int col;
905         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
906         if(++col % 10 == 0)
907                 fprintf(stderr, "\n");
908 }
909
910 void
911 ttyread(void) {
912         static char buf[BUFSIZ];
913         static int buflen = 0;
914         char *ptr;
915         char s[UTF_SIZ];
916         int charsize; /* size of utf8 char in bytes */
917         long utf8c;
918         int ret;
919
920         /* append read bytes to unprocessed bytes */
921         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
922                 die("Couldn't read from shell: %s\n", SERRNO);
923
924         /* process every complete utf8 char */
925         buflen += ret;
926         ptr = buf;
927         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
928                 charsize = utf8decode(ptr, &utf8c);
929                 utf8encode(&utf8c, s);
930                 tputc(s, charsize);
931                 ptr    += charsize;
932                 buflen -= charsize;
933         }
934
935         /* keep any uncomplete utf8 char for the next call */
936         memmove(buf, ptr, buflen);
937 }
938
939 void
940 ttywrite(const char *s, size_t n) {
941         if(write(cmdfd, s, n) == -1)
942                 die("write error on tty: %s\n", SERRNO);
943 }
944
945 void
946 ttyresize(void) {
947         struct winsize w;
948
949         w.ws_row = term.row;
950         w.ws_col = term.col;
951         w.ws_xpixel = xw.tw;
952         w.ws_ypixel = xw.th;
953         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
954                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
955 }
956
957 void
958 tsetdirt(int top, int bot)
959 {
960         int i;
961
962         LIMIT(top, 0, term.row-1);
963         LIMIT(bot, 0, term.row-1);
964
965         for(i = top; i <= bot; i++)
966                 term.dirty[i] = 1;
967 }
968
969 void
970 tfulldirt(void)
971 {
972         tsetdirt(0, term.row-1);
973 }
974
975 void
976 tcursor(int mode) {
977         static TCursor c;
978
979         if(mode == CURSOR_SAVE)
980                 c = term.c;
981         else if(mode == CURSOR_LOAD)
982                 term.c = c, tmoveto(c.x, c.y);
983 }
984
985 void
986 treset(void) {
987         uint i;
988         term.c = (TCursor){{
989                 .mode = ATTR_NULL,
990                 .fg = DefaultFG,
991                 .bg = DefaultBG
992         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
993
994         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
995         for(i = TAB; i < term.col; i += TAB)
996                 term.tabs[i] = 1;
997         term.top = 0, term.bot = term.row - 1;
998         term.mode = MODE_WRAP;
999
1000         tclearregion(0, 0, term.col-1, term.row-1);
1001 }
1002
1003 void
1004 tnew(int col, int row) {
1005         /* set screen size */
1006         term.row = row, term.col = col;
1007         term.line = xmalloc(term.row * sizeof(Line));
1008         term.alt  = xmalloc(term.row * sizeof(Line));
1009         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1010         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1011
1012         for(row = 0; row < term.row; row++) {
1013                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1014                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1015                 term.dirty[row] = 0;
1016         }
1017         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1018         /* setup screen */
1019         treset();
1020 }
1021
1022 void
1023 tswapscreen(void) {
1024         Line* tmp = term.line;
1025         term.line = term.alt;
1026         term.alt = tmp;
1027         term.mode ^= MODE_ALTSCREEN;
1028         tfulldirt();
1029 }
1030
1031 void
1032 tscrolldown(int orig, int n) {
1033         int i;
1034         Line temp;
1035
1036         LIMIT(n, 0, term.bot-orig+1);
1037
1038         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1039
1040         for(i = term.bot; i >= orig+n; i--) {
1041                 temp = term.line[i];
1042                 term.line[i] = term.line[i-n];
1043                 term.line[i-n] = temp;
1044
1045                 term.dirty[i] = 1;
1046                 term.dirty[i-n] = 1;
1047         }
1048
1049         selscroll(orig, n);
1050 }
1051
1052 void
1053 tscrollup(int orig, int n) {
1054         int i;
1055         Line temp;
1056         LIMIT(n, 0, term.bot-orig+1);
1057
1058         tclearregion(0, orig, term.col-1, orig+n-1);
1059
1060         for(i = orig; i <= term.bot-n; i++) {
1061                  temp = term.line[i];
1062                  term.line[i] = term.line[i+n];
1063                  term.line[i+n] = temp;
1064
1065                  term.dirty[i] = 1;
1066                  term.dirty[i+n] = 1;
1067         }
1068
1069         selscroll(orig, -n);
1070 }
1071
1072 void
1073 selscroll(int orig, int n) {
1074         if(sel.bx == -1)
1075                 return;
1076
1077         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1078                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1079                         sel.bx = -1;
1080                         return;
1081                 }
1082                 if(sel.by < term.top) {
1083                         sel.by = term.top;
1084                         sel.bx = 0;
1085                 }
1086                 if(sel.ey > term.bot) {
1087                         sel.ey = term.bot;
1088                         sel.ex = term.col;
1089                 }
1090                 sel.b.y = sel.by, sel.b.x = sel.bx;
1091                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1092         }
1093 }
1094
1095 void
1096 tnewline(int first_col) {
1097         int y = term.c.y;
1098         if(y == term.bot)
1099                 tscrollup(term.top, 1);
1100         else
1101                 y++;
1102         tmoveto(first_col ? 0 : term.c.x, y);
1103 }
1104
1105 void
1106 csiparse(void) {
1107         /* int noarg = 1; */
1108         char *p = csiescseq.buf;
1109
1110         csiescseq.narg = 0;
1111         if(*p == '?')
1112                 csiescseq.priv = 1, p++;
1113
1114         while(p < csiescseq.buf+csiescseq.len) {
1115                 while(isdigit(*p)) {
1116                         csiescseq.arg[csiescseq.narg] *= 10;
1117                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1118                 }
1119                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1120                         csiescseq.narg++, p++;
1121                 else {
1122                         csiescseq.mode = *p;
1123                         csiescseq.narg++;
1124                         return;
1125                 }
1126         }
1127 }
1128
1129 void
1130 tmoveto(int x, int y) {
1131         LIMIT(x, 0, term.col-1);
1132         LIMIT(y, 0, term.row-1);
1133         term.c.state &= ~CURSOR_WRAPNEXT;
1134         term.c.x = x;
1135         term.c.y = y;
1136 }
1137
1138 void
1139 tsetchar(char *c) {
1140         /*
1141          * The table is proudly stolen from rxvt.
1142          */
1143         if(term.c.attr.mode & ATTR_GFX) {
1144                 char *vt100_0[62] = { /* 0x41 - 0x7e */
1145                         "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1146                         0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1147                         0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1148                         0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1149                         "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1150                         "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1151                         "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1152                         "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1153                 };
1154
1155                 if(c[0] >= 0x41 && c[0] <= 0x7e
1156                                 && vt100_0[c[0] - 0x41]) {
1157                         c = vt100_0[c[0] - 0x41];
1158                 }
1159         }
1160
1161         term.dirty[term.c.y] = 1;
1162         term.line[term.c.y][term.c.x] = term.c.attr;
1163         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1164         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1165 }
1166
1167 void
1168 tclearregion(int x1, int y1, int x2, int y2) {
1169         int x, y, temp;
1170
1171         if(x1 > x2)
1172                 temp = x1, x1 = x2, x2 = temp;
1173         if(y1 > y2)
1174                 temp = y1, y1 = y2, y2 = temp;
1175
1176         LIMIT(x1, 0, term.col-1);
1177         LIMIT(x2, 0, term.col-1);
1178         LIMIT(y1, 0, term.row-1);
1179         LIMIT(y2, 0, term.row-1);
1180
1181         for(y = y1; y <= y2; y++) {
1182                 term.dirty[y] = 1;
1183                 for(x = x1; x <= x2; x++)
1184                         term.line[y][x].state = 0;
1185         }
1186 }
1187
1188 void
1189 tdeletechar(int n) {
1190         int src = term.c.x + n;
1191         int dst = term.c.x;
1192         int size = term.col - src;
1193
1194         term.dirty[term.c.y] = 1;
1195
1196         if(src >= term.col) {
1197                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1198                 return;
1199         }
1200         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1201         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1202 }
1203
1204 void
1205 tinsertblank(int n) {
1206         int src = term.c.x;
1207         int dst = src + n;
1208         int size = term.col - dst;
1209
1210         term.dirty[term.c.y] = 1;
1211
1212         if(dst >= term.col) {
1213                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1214                 return;
1215         }
1216         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1217         tclearregion(src, term.c.y, dst - 1, term.c.y);
1218 }
1219
1220 void
1221 tinsertblankline(int n) {
1222         if(term.c.y < term.top || term.c.y > term.bot)
1223                 return;
1224
1225         tscrolldown(term.c.y, n);
1226 }
1227
1228 void
1229 tdeleteline(int n) {
1230         if(term.c.y < term.top || term.c.y > term.bot)
1231                 return;
1232
1233         tscrollup(term.c.y, n);
1234 }
1235
1236 void
1237 tsetattr(int *attr, int l) {
1238         int i;
1239
1240         for(i = 0; i < l; i++) {
1241                 switch(attr[i]) {
1242                 case 0:
1243                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1244                                         | ATTR_ITALIC | ATTR_BLINK);
1245                         term.c.attr.fg = DefaultFG;
1246                         term.c.attr.bg = DefaultBG;
1247                         break;
1248                 case 1:
1249                         term.c.attr.mode |= ATTR_BOLD;
1250                         break;
1251                 case 3: /* enter standout (highlight) */
1252                         term.c.attr.mode |= ATTR_ITALIC;
1253                         break;
1254                 case 4:
1255                         term.c.attr.mode |= ATTR_UNDERLINE;
1256                         break;
1257                 case 5:
1258                         term.c.attr.mode |= ATTR_BLINK;
1259                         break;
1260                 case 7:
1261                         term.c.attr.mode |= ATTR_REVERSE;
1262                         break;
1263                 case 21:
1264                 case 22:
1265                         term.c.attr.mode &= ~ATTR_BOLD;
1266                         break;
1267                 case 23: /* leave standout (highlight) mode */
1268                         term.c.attr.mode &= ~ATTR_ITALIC;
1269                         break;
1270                 case 24:
1271                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1272                         break;
1273                 case 25:
1274                         term.c.attr.mode &= ~ATTR_BLINK;
1275                         break;
1276                 case 27:
1277                         term.c.attr.mode &= ~ATTR_REVERSE;
1278                         break;
1279                 case 38:
1280                         if(i + 2 < l && attr[i + 1] == 5) {
1281                                 i += 2;
1282                                 if(BETWEEN(attr[i], 0, 255))
1283                                         term.c.attr.fg = attr[i];
1284                                 else
1285                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1286                         }
1287                         else
1288                                 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1289                         break;
1290                 case 39:
1291                         term.c.attr.fg = DefaultFG;
1292                         break;
1293                 case 48:
1294                         if(i + 2 < l && attr[i + 1] == 5) {
1295                                 i += 2;
1296                                 if(BETWEEN(attr[i], 0, 255))
1297                                         term.c.attr.bg = attr[i];
1298                                 else
1299                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1300                         }
1301                         else
1302                                 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1303                         break;
1304                 case 49:
1305                         term.c.attr.bg = DefaultBG;
1306                         break;
1307                 default:
1308                         if(BETWEEN(attr[i], 30, 37))
1309                                 term.c.attr.fg = attr[i] - 30;
1310                         else if(BETWEEN(attr[i], 40, 47))
1311                                 term.c.attr.bg = attr[i] - 40;
1312                         else if(BETWEEN(attr[i], 90, 97))
1313                                 term.c.attr.fg = attr[i] - 90 + 8;
1314                         else if(BETWEEN(attr[i], 100, 107))
1315                                 term.c.attr.bg = attr[i] - 100 + 8;
1316                         else
1317                                 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1318                         break;
1319                 }
1320         }
1321 }
1322
1323 void
1324 tsetscroll(int t, int b) {
1325         int temp;
1326
1327         LIMIT(t, 0, term.row-1);
1328         LIMIT(b, 0, term.row-1);
1329         if(t > b) {
1330                 temp = t;
1331                 t = b;
1332                 b = temp;
1333         }
1334         term.top = t;
1335         term.bot = b;
1336 }
1337
1338 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1339
1340 void
1341 tsetmode(bool priv, bool set, int *args, int narg) {
1342         int *lim, mode;
1343
1344         for(lim = args + narg; args < lim; ++args) {
1345                 if(priv) {
1346                         switch(*args) {
1347                                 break;
1348                         case 1: /* DECCKM -- Cursor key */
1349                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1350                                 break;
1351                         case 5: /* DECSCNM -- Reverse video */
1352                                 mode = term.mode;
1353                                 MODBIT(term.mode, set, MODE_REVERSE);
1354                                 if(mode != term.mode)
1355                                         redraw();
1356                                 break;
1357                         case 6: /* XXX: DECOM -- Origin */
1358                                 break;
1359                         case 7: /* DECAWM -- Auto wrap */
1360                                 MODBIT(term.mode, set, MODE_WRAP);
1361                                 break;
1362                         case 8: /* XXX: DECARM -- Auto repeat */
1363                                 break;
1364                         case 0:  /* Error (IGNORED) */
1365                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1366                                 break;
1367                         case 25:
1368                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1369                                 break;
1370                         case 1000: /* 1000,1002: enable xterm mouse report */
1371                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1372                                 break;
1373                         case 1002:
1374                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1375                                 break;
1376                         case 1049: /* = 1047 and 1048 */
1377                         case 47:
1378                         case 1047:
1379                                 if(IS_SET(MODE_ALTSCREEN))
1380                                         tclearregion(0, 0, term.col-1, term.row-1);
1381                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1382                                     (!set && IS_SET(MODE_ALTSCREEN))) {
1383                                             tswapscreen();
1384                                 }
1385                                 if(*args != 1049)
1386                                         break;
1387                                 /* pass through */
1388                         case 1048:
1389                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1390                                 break;
1391                         default:
1392                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1393                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1394                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1395                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1396                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1397                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1398                                 fprintf(stderr,
1399                                         "erresc: unknown private set/reset mode %d\n",
1400                                         *args);
1401                                 break;
1402                         }
1403                 } else {
1404                         switch(*args) {
1405                         case 0:  /* Error (IGNORED) */
1406                                 break;
1407                         case 2:  /* KAM -- keyboard action */
1408                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1409                                 break;
1410                         case 4:  /* IRM -- Insertion-replacement */
1411                                 MODBIT(term.mode, set, MODE_INSERT);
1412                                 break;
1413                         case 12: /* XXX: SRM -- Send/Receive */
1414                                 break;
1415                         case 20: /* LNM -- Linefeed/new line */
1416                                 MODBIT(term.mode, set, MODE_CRLF);
1417                                 break;
1418                         default:
1419                                 fprintf(stderr,
1420                                         "erresc: unknown set/reset mode %d\n",
1421                                         *args);
1422                                 break;
1423                         }
1424                 }
1425         }
1426 }
1427 #undef MODBIT
1428
1429
1430 void
1431 csihandle(void) {
1432         switch(csiescseq.mode) {
1433         default:
1434         unknown:
1435                 fprintf(stderr, "erresc: unknown csi ");
1436                 csidump();
1437                 /* die(""); */
1438                 break;
1439         case '@': /* ICH -- Insert <n> blank char */
1440                 DEFAULT(csiescseq.arg[0], 1);
1441                 tinsertblank(csiescseq.arg[0]);
1442                 break;
1443         case 'A': /* CUU -- Cursor <n> Up */
1444         case 'e':
1445                 DEFAULT(csiescseq.arg[0], 1);
1446                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1447                 break;
1448         case 'B': /* CUD -- Cursor <n> Down */
1449                 DEFAULT(csiescseq.arg[0], 1);
1450                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1451                 break;
1452         case 'C': /* CUF -- Cursor <n> Forward */
1453         case 'a':
1454                 DEFAULT(csiescseq.arg[0], 1);
1455                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1456                 break;
1457         case 'D': /* CUB -- Cursor <n> Backward */
1458                 DEFAULT(csiescseq.arg[0], 1);
1459                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1460                 break;
1461         case 'E': /* CNL -- Cursor <n> Down and first col */
1462                 DEFAULT(csiescseq.arg[0], 1);
1463                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1464                 break;
1465         case 'F': /* CPL -- Cursor <n> Up and first col */
1466                 DEFAULT(csiescseq.arg[0], 1);
1467                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1468                 break;
1469         case 'g': /* TBC -- Tabulation clear */
1470                 switch (csiescseq.arg[0]) {
1471                 case 0: /* clear current tab stop */
1472                         term.tabs[term.c.x] = 0;
1473                         break;
1474                 case 3: /* clear all the tabs */
1475                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1476                         break;
1477                 default:
1478                         goto unknown;
1479                 }
1480                 break;
1481         case 'G': /* CHA -- Move to <col> */
1482         case '`': /* HPA */
1483                 DEFAULT(csiescseq.arg[0], 1);
1484                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1485                 break;
1486         case 'H': /* CUP -- Move to <row> <col> */
1487         case 'f': /* HVP */
1488                 DEFAULT(csiescseq.arg[0], 1);
1489                 DEFAULT(csiescseq.arg[1], 1);
1490                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1491                 break;
1492         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1493                 DEFAULT(csiescseq.arg[0], 1);
1494                 while(csiescseq.arg[0]--)
1495                         tputtab(1);
1496                 break;
1497         case 'J': /* ED -- Clear screen */
1498                 sel.bx = -1;
1499                 switch(csiescseq.arg[0]) {
1500                 case 0: /* below */
1501                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1502                         if(term.c.y < term.row-1)
1503                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1504                         break;
1505                 case 1: /* above */
1506                         if(term.c.y > 1)
1507                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1508                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1509                         break;
1510                 case 2: /* all */
1511                         tclearregion(0, 0, term.col-1, term.row-1);
1512                         break;
1513                 default:
1514                         goto unknown;
1515                 }
1516                 break;
1517         case 'K': /* EL -- Clear line */
1518                 switch(csiescseq.arg[0]) {
1519                 case 0: /* right */
1520                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1521                         break;
1522                 case 1: /* left */
1523                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1524                         break;
1525                 case 2: /* all */
1526                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1527                         break;
1528                 }
1529                 break;
1530         case 'S': /* SU -- Scroll <n> line up */
1531                 DEFAULT(csiescseq.arg[0], 1);
1532                 tscrollup(term.top, csiescseq.arg[0]);
1533                 break;
1534         case 'T': /* SD -- Scroll <n> line down */
1535                 DEFAULT(csiescseq.arg[0], 1);
1536                 tscrolldown(term.top, csiescseq.arg[0]);
1537                 break;
1538         case 'L': /* IL -- Insert <n> blank lines */
1539                 DEFAULT(csiescseq.arg[0], 1);
1540                 tinsertblankline(csiescseq.arg[0]);
1541                 break;
1542         case 'l': /* RM -- Reset Mode */
1543                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1544                 break;
1545         case 'M': /* DL -- Delete <n> lines */
1546                 DEFAULT(csiescseq.arg[0], 1);
1547                 tdeleteline(csiescseq.arg[0]);
1548                 break;
1549         case 'X': /* ECH -- Erase <n> char */
1550                 DEFAULT(csiescseq.arg[0], 1);
1551                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1552                 break;
1553         case 'P': /* DCH -- Delete <n> char */
1554                 DEFAULT(csiescseq.arg[0], 1);
1555                 tdeletechar(csiescseq.arg[0]);
1556                 break;
1557         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1558                 DEFAULT(csiescseq.arg[0], 1);
1559                 while(csiescseq.arg[0]--)
1560                         tputtab(0);
1561                 break;
1562         case 'd': /* VPA -- Move to <row> */
1563                 DEFAULT(csiescseq.arg[0], 1);
1564                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1565                 break;
1566         case 'h': /* SM -- Set terminal mode */
1567                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1568                 break;
1569         case 'm': /* SGR -- Terminal attribute (color) */
1570                 tsetattr(csiescseq.arg, csiescseq.narg);
1571                 break;
1572         case 'r': /* DECSTBM -- Set Scrolling Region */
1573                 if(csiescseq.priv)
1574                         goto unknown;
1575                 else {
1576                         DEFAULT(csiescseq.arg[0], 1);
1577                         DEFAULT(csiescseq.arg[1], term.row);
1578                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1579                         tmoveto(0, 0);
1580                 }
1581                 break;
1582         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1583                 tcursor(CURSOR_SAVE);
1584                 break;
1585         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1586                 tcursor(CURSOR_LOAD);
1587                 break;
1588         }
1589 }
1590
1591 void
1592 csidump(void) {
1593         int i;
1594         printf("ESC[");
1595         for(i = 0; i < csiescseq.len; i++) {
1596                 uint c = csiescseq.buf[i] & 0xff;
1597                 if(isprint(c)) putchar(c);
1598                 else if(c == '\n') printf("(\\n)");
1599                 else if(c == '\r') printf("(\\r)");
1600                 else if(c == 0x1b) printf("(\\e)");
1601                 else printf("(%02x)", c);
1602         }
1603         putchar('\n');
1604 }
1605
1606 void
1607 csireset(void) {
1608         memset(&csiescseq, 0, sizeof(csiescseq));
1609 }
1610
1611 void
1612 strhandle(void) {
1613         char *p;
1614
1615         /*
1616          * TODO: make this being useful in case of color palette change.
1617          */
1618         strparse();
1619
1620         p = strescseq.buf;
1621
1622         switch(strescseq.type) {
1623         case ']': /* OSC -- Operating System Command */
1624                 switch(p[0]) {
1625                 case '0':
1626                 case '1':
1627                 case '2':
1628                         /*
1629                          * TODO: Handle special chars in string, like umlauts.
1630                          */
1631                         if(p[1] == ';') {
1632                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1633                         }
1634                         break;
1635                 case ';':
1636                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1637                         break;
1638                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1639                         break;
1640                 default:
1641                         fprintf(stderr, "erresc: unknown str ");
1642                         strdump();
1643                         break;
1644                 }
1645                 break;
1646         case 'k': /* old title set compatibility */
1647                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1648                 break;
1649         case 'P': /* DSC -- Device Control String */
1650         case '_': /* APC -- Application Program Command */
1651         case '^': /* PM -- Privacy Message */
1652         default:
1653                 fprintf(stderr, "erresc: unknown str ");
1654                 strdump();
1655                 /* die(""); */
1656                 break;
1657         }
1658 }
1659
1660 void
1661 strparse(void) {
1662         /*
1663          * TODO: Implement parsing like for CSI when required.
1664          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1665          */
1666         return;
1667 }
1668
1669 void
1670 strdump(void) {
1671         int i;
1672         printf("ESC%c", strescseq.type);
1673         for(i = 0; i < strescseq.len; i++) {
1674                 uint c = strescseq.buf[i] & 0xff;
1675                 if(isprint(c)) putchar(c);
1676                 else if(c == '\n') printf("(\\n)");
1677                 else if(c == '\r') printf("(\\r)");
1678                 else if(c == 0x1b) printf("(\\e)");
1679                 else printf("(%02x)", c);
1680         }
1681         printf("ESC\\\n");
1682 }
1683
1684 void
1685 strreset(void) {
1686         memset(&strescseq, 0, sizeof(strescseq));
1687 }
1688
1689 void
1690 tputtab(bool forward) {
1691         uint x = term.c.x;
1692
1693         if(forward) {
1694                 if(x == term.col)
1695                         return;
1696                 for(++x; x < term.col && !term.tabs[x]; ++x)
1697                         /* nothing */ ;
1698         } else {
1699                 if(x == 0)
1700                         return;
1701                 for(--x; x > 0 && !term.tabs[x]; --x)
1702                         /* nothing */ ;
1703         }
1704         tmoveto(x, term.c.y);
1705 }
1706
1707 void
1708 tputc(char *c, int len) {
1709         uchar ascii = *c;
1710
1711         if(iofd != -1)
1712                 write(iofd, c, len);
1713
1714         switch(ascii) {
1715         case '\t':
1716                 tputtab(1);
1717                 return;
1718         case '\b':
1719                 tmoveto(term.c.x-1, term.c.y);
1720                 return;
1721         case '\r':
1722                 tmoveto(0, term.c.y);
1723                 return;
1724         case '\f':
1725         case '\v':
1726         case '\n':
1727                 /* go to first col if the mode is set */
1728                 tnewline(IS_SET(MODE_CRLF));
1729                 return;
1730         case '\a':
1731                 if(term.esc & ESC_STR)
1732                         break;
1733
1734                 if(!(xw.state & WIN_FOCUSED))
1735                         xseturgency(1);
1736                 return;
1737         case '\033':
1738                 csireset();
1739                 term.esc = ESC_START;
1740                 return;
1741         }
1742
1743         if(term.esc & ESC_START) {
1744                 if(term.esc & ESC_CSI) {
1745                         csiescseq.buf[csiescseq.len++] = ascii;
1746                         if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1747                                 term.esc = 0;
1748                                 csiparse(), csihandle();
1749                         }
1750                 } else if(term.esc & ESC_STR) {
1751                         switch(ascii) {
1752                         case '\033':
1753                                 term.esc = ESC_START | ESC_STR_END;
1754                                 break;
1755                         case '\a': /* backwards compatibility to xterm */
1756                                 term.esc = 0;
1757                                 strhandle();
1758                                 break;
1759                         default:
1760                                 strescseq.buf[strescseq.len++] = ascii;
1761                                 if(strescseq.len+1 >= STR_BUF_SIZ) {
1762                                         term.esc = 0;
1763                                         strhandle();
1764                                 }
1765                         }
1766                 } else if(term.esc & ESC_STR_END) {
1767                         term.esc = 0;
1768                         if(ascii == '\\')
1769                                 strhandle();
1770                 } else if(term.esc & ESC_ALTCHARSET) {
1771                         switch(ascii) {
1772                         case '0': /* Line drawing set */
1773                                 term.c.attr.mode |= ATTR_GFX;
1774                                 break;
1775                         case 'B': /* USASCII */
1776                                 term.c.attr.mode &= ~ATTR_GFX;
1777                                 break;
1778                         case 'A': /* UK (IGNORED) */
1779                         case '<': /* multinational charset (IGNORED) */
1780                         case '5': /* Finnish (IGNORED) */
1781                         case 'C': /* Finnish (IGNORED) */
1782                         case 'K': /* German (IGNORED) */
1783                                 break;
1784                         default:
1785                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1786                         }
1787                         term.esc = 0;
1788                 } else {
1789                         switch(ascii) {
1790                         case '[':
1791                                 term.esc |= ESC_CSI;
1792                                 break;
1793                         case 'P': /* DCS -- Device Control String */
1794                         case '_': /* APC -- Application Program Command */
1795                         case '^': /* PM -- Privacy Message */
1796                         case ']': /* OSC -- Operating System Command */
1797                         case 'k': /* old title set compatibility */
1798                                 strreset();
1799                                 strescseq.type = ascii;
1800                                 term.esc |= ESC_STR;
1801                                 break;
1802                         case '(': /* set primary charset G0 */
1803                                 term.esc |= ESC_ALTCHARSET;
1804                                 break;
1805                         case ')': /* set secondary charset G1 (IGNORED) */
1806                         case '*': /* set tertiary charset G2 (IGNORED) */
1807                         case '+': /* set quaternary charset G3 (IGNORED) */
1808                                 term.esc = 0;
1809                                 break;
1810                         case 'D': /* IND -- Linefeed */
1811                                 if(term.c.y == term.bot)
1812                                         tscrollup(term.top, 1);
1813                                 else
1814                                         tmoveto(term.c.x, term.c.y+1);
1815                                 term.esc = 0;
1816                                 break;
1817                         case 'E': /* NEL -- Next line */
1818                                 tnewline(1); /* always go to first col */
1819                                 term.esc = 0;
1820                                 break;
1821                         case 'H': /* HTS -- Horizontal tab stop */
1822                                 term.tabs[term.c.x] = 1;
1823                                 term.esc = 0;
1824                                 break;
1825                         case 'M': /* RI -- Reverse index */
1826                                 if(term.c.y == term.top)
1827                                         tscrolldown(term.top, 1);
1828                                 else
1829                                         tmoveto(term.c.x, term.c.y-1);
1830                                 term.esc = 0;
1831                                 break;
1832                         case 'c': /* RIS -- Reset to inital state */
1833                                 treset();
1834                                 term.esc = 0;
1835                                 xclearborders();
1836                                 xresettitle();
1837                                 break;
1838                         case '=': /* DECPAM -- Application keypad */
1839                                 term.mode |= MODE_APPKEYPAD;
1840                                 term.esc = 0;
1841                                 break;
1842                         case '>': /* DECPNM -- Normal keypad */
1843                                 term.mode &= ~MODE_APPKEYPAD;
1844                                 term.esc = 0;
1845                                 break;
1846                         case '7': /* DECSC -- Save Cursor */
1847                                 tcursor(CURSOR_SAVE);
1848                                 term.esc = 0;
1849                                 break;
1850                         case '8': /* DECRC -- Restore Cursor */
1851                                 tcursor(CURSOR_LOAD);
1852                                 term.esc = 0;
1853                                 break;
1854                         case '\\': /* ST -- Stop */
1855                                 term.esc = 0;
1856                                 break;
1857                         default:
1858                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1859                                     (uchar) ascii, isprint(ascii)?ascii:'.');
1860                                 term.esc = 0;
1861                         }
1862                 }
1863         } else {
1864                 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1865                         sel.bx = -1;
1866                 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1867                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1868                                 tnewline(1); /* always go to first col */
1869                         tsetchar(c);
1870                         if(term.c.x+1 < term.col)
1871                                 tmoveto(term.c.x+1, term.c.y);
1872                         else
1873                                 term.c.state |= CURSOR_WRAPNEXT;
1874                 }
1875         }
1876 }
1877
1878 int
1879 tresize(int col, int row) {
1880         int i, x;
1881         int minrow = MIN(row, term.row);
1882         int mincol = MIN(col, term.col);
1883         int slide = term.c.y - row + 1;
1884
1885         if(col < 1 || row < 1)
1886                 return 0;
1887
1888         /* free unneeded rows */
1889         i = 0;
1890         if(slide > 0) {
1891                 /* slide screen to keep cursor where we expect it -
1892                  * tscrollup would work here, but we can optimize to
1893                  * memmove because we're freeing the earlier lines */
1894                 for(/* i = 0 */; i < slide; i++) {
1895                         free(term.line[i]);
1896                         free(term.alt[i]);
1897                 }
1898                 memmove(term.line, term.line + slide, row * sizeof(Line));
1899                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1900         }
1901         for(i += row; i < term.row; i++) {
1902                 free(term.line[i]);
1903                 free(term.alt[i]);
1904         }
1905
1906         /* resize to new height */
1907         term.line = xrealloc(term.line, row * sizeof(Line));
1908         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
1909         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1910         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1911
1912         /* resize each row to new width, zero-pad if needed */
1913         for(i = 0; i < minrow; i++) {
1914                 term.dirty[i] = 1;
1915                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1916                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
1917                 for(x = mincol; x < col; x++) {
1918                         term.line[i][x].state = 0;
1919                         term.alt[i][x].state = 0;
1920                 }
1921         }
1922
1923         /* allocate any new rows */
1924         for(/* i == minrow */; i < row; i++) {
1925                 term.dirty[i] = 1;
1926                 term.line[i] = xcalloc(col, sizeof(Glyph));
1927                 term.alt [i] = xcalloc(col, sizeof(Glyph));
1928         }
1929         if(col > term.col) {
1930                 bool *bp = term.tabs + term.col;
1931
1932                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1933                 while(--bp > term.tabs && !*bp)
1934                         /* nothing */ ;
1935                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1936                         *bp = 1;
1937         }
1938         /* update terminal size */
1939         term.col = col, term.row = row;
1940         /* make use of the LIMIT in tmoveto */
1941         tmoveto(term.c.x, term.c.y);
1942         /* reset scrolling region */
1943         tsetscroll(0, row-1);
1944
1945         return (slide > 0);
1946 }
1947
1948 void
1949 xresize(int col, int row) {
1950         xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1951         xw.th = MAX(1, 2*BORDER + row * xw.ch);
1952
1953         XftDrawChange(xw.xft_draw, xw.buf);
1954 }
1955
1956 void
1957 xloadcols(void) {
1958         int i, r, g, b;
1959         XRenderColor xft_color = { .alpha = 0 };
1960
1961         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1962         for(i = 0; i < LEN(colorname); i++) {
1963                 if(!colorname[i])
1964                         continue;
1965                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1966                         die("Could not allocate color '%s'\n", colorname[i]);
1967                 }
1968         }
1969
1970         /* load colors [16-255] ; same colors as xterm */
1971         for(i = 16, r = 0; r < 6; r++) {
1972                 for(g = 0; g < 6; g++) {
1973                         for(b = 0; b < 6; b++) {
1974                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1975                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1976                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1977                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1978                                         die("Could not allocate color %d\n", i);
1979                                 }
1980                                 i++;
1981                         }
1982                 }
1983         }
1984
1985         for(r = 0; r < 24; r++, i++) {
1986                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1987                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1988                         die("Could not allocate color %d\n", i);
1989                 }
1990         }
1991 }
1992
1993 void
1994 xtermclear(int col1, int row1, int col2, int row2) {
1995         XftDrawRect(xw.xft_draw,
1996                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
1997                         BORDER + col1 * xw.cw,
1998                         BORDER + row1 * xw.ch,
1999                         (col2-col1+1) * xw.cw,
2000                         (row2-row1+1) * xw.ch);
2001 }
2002
2003 /*
2004  * Absolute coordinates.
2005  */
2006 void
2007 xclear(int x1, int y1, int x2, int y2) {
2008         XftDrawRect(xw.xft_draw,
2009                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2010                         x1, y1, x2-x1, y2-y1);
2011 }
2012
2013 void
2014 xclearborders(void) {
2015         /* top and left border */
2016         xclear(0, 0, BORDER, xw.h);
2017         xclear(0, 0, xw.w, BORDER);
2018
2019         /* lower and right border */
2020         xclear(BORDER, xw.th - 1, xw.w, xw.h);
2021         /* Will just draw what hasn't been drawn by the previous call. */
2022         xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2023 }
2024
2025 void
2026 xhints(void) {
2027         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2028         XWMHints wm = {.flags = InputHint, .input = 1};
2029         XSizeHints *sizeh = NULL;
2030
2031         sizeh = XAllocSizeHints();
2032         if(xw.isfixed == False) {
2033                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2034                 sizeh->height = xw.h;
2035                 sizeh->width = xw.w;
2036                 sizeh->height_inc = xw.ch;
2037                 sizeh->width_inc = xw.cw;
2038                 sizeh->base_height = 2*BORDER;
2039                 sizeh->base_width = 2*BORDER;
2040         } else {
2041                 sizeh->flags = PMaxSize | PMinSize;
2042                 sizeh->min_width = sizeh->max_width = xw.fw;
2043                 sizeh->min_height = sizeh->max_height = xw.fh;
2044         }
2045
2046         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2047         XFree(sizeh);
2048 }
2049
2050 void
2051 xinitfont(Font *f, char *fontstr) {
2052         FcPattern *pattern, *match;
2053         FcResult result;
2054
2055         pattern = FcNameParse((FcChar8 *)fontstr);
2056         if(!pattern)
2057                 die("st: can't open font %s\n", fontstr);
2058
2059         match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2060         FcPatternDestroy(pattern);
2061         if(!match)
2062                 die("st: can't open font %s\n", fontstr);
2063         if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2064                 FcPatternDestroy(match);
2065                 die("st: can't open font %s.\n", fontstr);
2066         }
2067
2068         f->ascent = f->xft_set->ascent;
2069         f->descent = f->xft_set->descent;
2070         f->lbearing = 0;
2071         f->rbearing = f->xft_set->max_advance_width;
2072
2073         f->height = f->xft_set->height;
2074         f->width = f->lbearing + f->rbearing;
2075 }
2076
2077 void
2078 initfonts(char *fontstr) {
2079         char *fstr;
2080
2081         xinitfont(&dc.font, fontstr);
2082         xw.cw = dc.font.width;
2083         xw.ch = dc.font.height;
2084
2085         fstr = smstrcat(fontstr, ":weight=bold", NULL);
2086         xinitfont(&dc.bfont, fstr);
2087         free(fstr);
2088
2089         fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2090         xinitfont(&dc.ifont, fstr);
2091         free(fstr);
2092
2093         fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2094         xinitfont(&dc.ibfont, fstr);
2095         free(fstr);
2096 }
2097
2098 void
2099 xinit(void) {
2100         XSetWindowAttributes attrs;
2101         Cursor cursor;
2102         Window parent;
2103         int sw, sh, major, minor;
2104
2105         if(!(xw.dpy = XOpenDisplay(NULL)))
2106                 die("Can't open display\n");
2107         xw.scr = XDefaultScreen(xw.dpy);
2108         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2109
2110         /* font */
2111         initfonts((opt_font != NULL)? opt_font : FONT);
2112
2113         /* colors */
2114         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2115         xloadcols();
2116
2117         /* adjust fixed window geometry */
2118         if(xw.isfixed) {
2119                 sw = DisplayWidth(xw.dpy, xw.scr);
2120                 sh = DisplayHeight(xw.dpy, xw.scr);
2121                 if(xw.fx < 0)
2122                         xw.fx = sw + xw.fx - xw.fw - 1;
2123                 if(xw.fy < 0)
2124                         xw.fy = sh + xw.fy - xw.fh - 1;
2125
2126                 xw.h = xw.fh;
2127                 xw.w = xw.fw;
2128         } else {
2129                 /* window - default size */
2130                 xw.h = 2*BORDER + term.row * xw.ch;
2131                 xw.w = 2*BORDER + term.col * xw.cw;
2132                 xw.fx = 0;
2133                 xw.fy = 0;
2134         }
2135
2136         attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2137         attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2138         attrs.bit_gravity = NorthWestGravity;
2139         attrs.event_mask = FocusChangeMask | KeyPressMask
2140                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2141                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2142         attrs.colormap = xw.cmap;
2143
2144         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2145         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2146                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2147                         xw.vis,
2148                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2149                         | CWColormap,
2150                         &attrs);
2151
2152         /* double buffering */
2153         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2154                 die("Xdbe extension is not present\n");
2155         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2156
2157         /* Xft rendering context */
2158         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2159
2160         /* input methods */
2161         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2162         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2163                                            | XIMStatusNothing, XNClientWindow, xw.win,
2164                                            XNFocusWindow, xw.win, NULL);
2165         /* gc */
2166         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2167
2168         /* white cursor, black outline */
2169         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2170         XDefineCursor(xw.dpy, xw.win, cursor);
2171         XRecolorCursor(xw.dpy, cursor,
2172                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2173                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2174
2175         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2176
2177         xresettitle();
2178         XMapWindow(xw.dpy, xw.win);
2179         xhints();
2180         XSync(xw.dpy, 0);
2181 }
2182
2183 void
2184 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2185         int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch,
2186             width = charlen*xw.cw;
2187         Font *font = &dc.font;
2188         XGlyphInfo extents;
2189         XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2190                  *temp, revfg, revbg;
2191         XRenderColor colfg, colbg;
2192
2193         if(base.mode & ATTR_REVERSE)
2194                 temp = fg, fg = bg, bg = temp;
2195         if(base.mode & ATTR_BOLD) {
2196                 fg = &dc.xft_col[base.fg + 8];
2197                 font = &dc.bfont;
2198         }
2199         if(base.mode & ATTR_ITALIC)
2200                 font = &dc.ifont;
2201         if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2202                 font = &dc.ibfont;
2203
2204         if(IS_SET(MODE_REVERSE)) {
2205                 if(fg == &dc.xft_col[DefaultFG]) {
2206                         fg = &dc.xft_col[DefaultBG];
2207                 } else {
2208                         colfg.red = ~fg->color.red;
2209                         colfg.green = ~fg->color.green;
2210                         colfg.blue = ~fg->color.blue;
2211                         colfg.alpha = fg->color.alpha;
2212                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2213                         fg = &revfg;
2214                 }
2215
2216                 if(bg == &dc.xft_col[DefaultBG]) {
2217                         bg = &dc.xft_col[DefaultFG];
2218                 } else {
2219                         colbg.red = ~bg->color.red;
2220                         colbg.green = ~bg->color.green;
2221                         colbg.blue = ~bg->color.blue;
2222                         colbg.alpha = bg->color.alpha;
2223                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2224                         bg = &revbg;
2225                 }
2226         }
2227
2228         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2229                         &extents);
2230         width = extents.xOff;
2231
2232         XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2233         XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2234                         winy + font->ascent, (FcChar8 *)s, bytelen);
2235
2236         if(base.mode & ATTR_UNDERLINE) {
2237                 XftDrawRect(xw.xft_draw, fg, winx, winy+1,
2238                                 width, 1);
2239         }
2240 }
2241
2242 void
2243 xdrawcursor(void) {
2244         static int oldx = 0;
2245         static int oldy = 0;
2246         int sl;
2247         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2248
2249         LIMIT(oldx, 0, term.col-1);
2250         LIMIT(oldy, 0, term.row-1);
2251
2252         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2253                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2254
2255         /* remove the old cursor */
2256         if(term.line[oldy][oldx].state & GLYPH_SET) {
2257                 sl = utf8size(term.line[oldy][oldx].c);
2258                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2259         } else
2260                 xtermclear(oldx, oldy, oldx, oldy);
2261
2262         /* draw the new one */
2263         if(!(term.c.state & CURSOR_HIDE)) {
2264                 if(!(xw.state & WIN_FOCUSED))
2265                         g.bg = DefaultUCS;
2266
2267                 if(IS_SET(MODE_REVERSE))
2268                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2269
2270                 sl = utf8size(g.c);
2271                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2272                 oldx = term.c.x, oldy = term.c.y;
2273         }
2274 }
2275
2276 void
2277 xresettitle(void) {
2278         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2279 }
2280
2281 void
2282 redraw(void) {
2283         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2284
2285         xclearborders();
2286         tfulldirt();
2287         draw();
2288         XSync(xw.dpy, False); /* necessary for a good tput flash */
2289         nanosleep(&tv, NULL);
2290 }
2291
2292 void
2293 draw(void) {
2294         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2295
2296         drawregion(0, 0, term.col, term.row);
2297         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2298 }
2299
2300 void
2301 drawregion(int x1, int y1, int x2, int y2) {
2302         int ic, ib, x, y, ox, sl;
2303         Glyph base, new;
2304         char buf[DRAW_BUF_SIZ];
2305         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2306
2307         if((sel.alt && !alt) || (!sel.alt && alt))
2308                 ena_sel = 0;
2309         if(!(xw.state & WIN_VISIBLE))
2310                 return;
2311
2312         for(y = y1; y < y2; y++) {
2313                 if(!term.dirty[y])
2314                         continue;
2315                 xtermclear(0, y, term.col, y);
2316                 term.dirty[y] = 0;
2317                 base = term.line[y][0];
2318                 ic = ib = ox = 0;
2319                 for(x = x1; x < x2; x++) {
2320                         new = term.line[y][x];
2321                         if(ena_sel && *(new.c) && selected(x, y))
2322                                 new.mode ^= ATTR_REVERSE;
2323                         if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2324                                                   ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2325                                 xdraws(buf, base, ox, y, ic, ib);
2326                                 ic = ib = 0;
2327                         }
2328                         if(new.state & GLYPH_SET) {
2329                                 if(ib == 0) {
2330                                         ox = x;
2331                                         base = new;
2332                                 }
2333                                 sl = utf8size(new.c);
2334                                 memcpy(buf+ib, new.c, sl);
2335                                 ib += sl;
2336                                 ++ic;
2337                         }
2338                 }
2339                 if(ib > 0)
2340                         xdraws(buf, base, ox, y, ic, ib);
2341         }
2342         xdrawcursor();
2343 }
2344
2345 void
2346 expose(XEvent *ev) {
2347         XExposeEvent *e = &ev->xexpose;
2348         if(xw.state & WIN_REDRAW) {
2349                 if(!e->count)
2350                         xw.state &= ~WIN_REDRAW;
2351         }
2352 }
2353
2354 void
2355 visibility(XEvent *ev) {
2356         XVisibilityEvent *e = &ev->xvisibility;
2357         if(e->state == VisibilityFullyObscured)
2358                 xw.state &= ~WIN_VISIBLE;
2359         else if(!(xw.state & WIN_VISIBLE))
2360                 /* need a full redraw for next Expose, not just a buf copy */
2361                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2362 }
2363
2364 void
2365 unmap(XEvent *ev) {
2366         xw.state &= ~WIN_VISIBLE;
2367 }
2368
2369 void
2370 xseturgency(int add) {
2371         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2372         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2373         XSetWMHints(xw.dpy, xw.win, h);
2374         XFree(h);
2375 }
2376
2377 void
2378 focus(XEvent *ev) {
2379         if(ev->type == FocusIn) {
2380                 xw.state |= WIN_FOCUSED;
2381                 xseturgency(0);
2382         } else
2383                 xw.state &= ~WIN_FOCUSED;
2384 }
2385
2386 char*
2387 kmap(KeySym k, uint state) {
2388         int i;
2389         state &= ~Mod2Mask;
2390         for(i = 0; i < LEN(key); i++) {
2391                 uint mask = key[i].mask;
2392                 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2393                         return (char*)key[i].s;
2394         }
2395         return NULL;
2396 }
2397
2398 void
2399 kpress(XEvent *ev) {
2400         XKeyEvent *e = &ev->xkey;
2401         KeySym ksym;
2402         char buf[32];
2403         char *customkey;
2404         int len;
2405         int meta;
2406         int shift;
2407         Status status;
2408
2409         if (IS_SET(MODE_KBDLOCK))
2410                 return;
2411         meta = e->state & Mod1Mask;
2412         shift = e->state & ShiftMask;
2413         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2414
2415         /* 1. custom keys from config.h */
2416         if((customkey = kmap(ksym, e->state)))
2417                 ttywrite(customkey, strlen(customkey));
2418         /* 2. hardcoded (overrides X lookup) */
2419         else
2420                 switch(ksym) {
2421                 case XK_Up:
2422                 case XK_Down:
2423                 case XK_Left:
2424                 case XK_Right:
2425                         /* XXX: shift up/down doesn't work */
2426                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2427                         ttywrite(buf, 3);
2428                         break;
2429                 case XK_Insert:
2430                         if(shift)
2431                                 selpaste();
2432                         break;
2433                 case XK_Return:
2434                         if(IS_SET(MODE_CRLF))
2435                                 ttywrite("\r\n", 2);
2436                         else
2437                                 ttywrite("\r", 1);
2438                         break;
2439                         /* 3. X lookup  */
2440                 default:
2441                         if(len > 0) {
2442                                 if(meta && len == 1)
2443                                         ttywrite("\033", 1);
2444                                 ttywrite(buf, len);
2445                         }
2446                         break;
2447                 }
2448 }
2449
2450 void
2451 cmessage(XEvent *e) {
2452         /* See xembed specs
2453            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2454         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2455                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2456                         xw.state |= WIN_FOCUSED;
2457                         xseturgency(0);
2458                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2459                         xw.state &= ~WIN_FOCUSED;
2460                 }
2461         }
2462 }
2463
2464 void
2465 resize(XEvent *e) {
2466         int col, row;
2467
2468         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2469                 return;
2470
2471         xw.w = e->xconfigure.width;
2472         xw.h = e->xconfigure.height;
2473         col = (xw.w - 2*BORDER) / xw.cw;
2474         row = (xw.h - 2*BORDER) / xw.ch;
2475         if(col == term.col && row == term.row)
2476                 return;
2477
2478         tresize(col, row);
2479         xresize(col, row);
2480         xclearborders();
2481         ttyresize();
2482 }
2483
2484 void
2485 run(void) {
2486         XEvent ev;
2487         fd_set rfd;
2488         int xfd = XConnectionNumber(xw.dpy), i;
2489         struct timeval drawtimeout, *tv = NULL;
2490
2491         for(i = 0;; i++) {
2492                 FD_ZERO(&rfd);
2493                 FD_SET(cmdfd, &rfd);
2494                 FD_SET(xfd, &rfd);
2495                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2496                         if(errno == EINTR)
2497                                 continue;
2498                         die("select failed: %s\n", SERRNO);
2499                 }
2500
2501                 /*
2502                  * Stop after a certain number of reads so the user does not
2503                  * feel like the system is stuttering.
2504                  */
2505                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2506                         ttyread();
2507
2508                         /*
2509                          * Just wait a bit so it isn't disturbing the
2510                          * user and the system is able to write something.
2511                          */
2512                         drawtimeout.tv_sec = 0;
2513                         drawtimeout.tv_usec = 5;
2514                         tv = &drawtimeout;
2515                         continue;
2516                 }
2517                 i = 0;
2518                 tv = NULL;
2519
2520                 while(XPending(xw.dpy)) {
2521                         XNextEvent(xw.dpy, &ev);
2522                         if(XFilterEvent(&ev, xw.win))
2523                                 continue;
2524                         if(handler[ev.type])
2525                                 (handler[ev.type])(&ev);
2526                 }
2527
2528                 draw();
2529                 XFlush(xw.dpy);
2530         }
2531 }
2532
2533 int
2534 main(int argc, char *argv[]) {
2535         int i, bitm, xr, yr;
2536         uint wr, hr;
2537
2538         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2539         xw.isfixed = False;
2540
2541         for(i = 1; i < argc; i++) {
2542                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2543                 case 'c':
2544                         if(++i < argc)
2545                                 opt_class = argv[i];
2546                         break;
2547                 case 'e':
2548                         /* eat every remaining arguments */
2549                         if(++i < argc)
2550                                 opt_cmd = &argv[i];
2551                         goto run;
2552                 case 'f':
2553                         if(++i < argc)
2554                                 opt_font = argv[i];
2555                         break;
2556                 case 'g':
2557                         if(++i >= argc)
2558                                 break;
2559
2560                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2561                         if(bitm & XValue)
2562                                 xw.fx = xr;
2563                         if(bitm & YValue)
2564                                 xw.fy = yr;
2565                         if(bitm & WidthValue)
2566                                 xw.fw = (int)wr;
2567                         if(bitm & HeightValue)
2568                                 xw.fh = (int)hr;
2569                         if(bitm & XNegative && xw.fx == 0)
2570                                 xw.fx = -1;
2571                         if(bitm & XNegative && xw.fy == 0)
2572                                 xw.fy = -1;
2573
2574                         if(xw.fh != 0 && xw.fw != 0)
2575                                 xw.isfixed = True;
2576                         break;
2577                 case 'o':
2578                         if(++i < argc)
2579                                 opt_io = argv[i];
2580                         break;
2581                 case 't':
2582                         if(++i < argc)
2583                                 opt_title = argv[i];
2584                         break;
2585                 case 'v':
2586                 default:
2587                         die(USAGE);
2588                 case 'w':
2589                         if(++i < argc)
2590                                 opt_embed = argv[i];
2591                         break;
2592                 }
2593         }
2594
2595  run:
2596         setlocale(LC_CTYPE, "");
2597         tnew(80, 24);
2598         ttynew();
2599         xinit();
2600         selinit();
2601         run();
2602         return 0;
2603 }
2604