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