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