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