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