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