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