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