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