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