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