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