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