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