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