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