JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
replaced memset by loops in tresize(); turns out it's faster.
[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 x, 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                 for(x = x1; x <= x2; x++)
694                         term.line[y][x].state = 0;
695 }
696
697 void
698 tdeletechar(int n) {
699         int src = term.c.x + n;
700         int dst = term.c.x;
701         int size = term.col - src;
702
703         if(src >= term.col) {
704                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
705                 return;
706         }
707         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
708         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
709 }
710
711 void
712 tinsertblank(int n) {
713         int src = term.c.x;
714         int dst = src + n;
715         int size = term.col - dst;
716
717         if(dst >= term.col) {
718                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
719                 return;
720         }
721         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
722         tclearregion(src, term.c.y, dst - 1, term.c.y);
723 }
724
725 void
726 tinsertblankline(int n) {
727         if(term.c.y < term.top || term.c.y > term.bot)
728                 return;
729
730         tscrolldown(term.c.y, n);
731 }
732
733 void
734 tdeleteline(int n) {
735         if(term.c.y < term.top || term.c.y > term.bot)
736                 return;
737
738         tscrollup(term.c.y, n);
739 }
740
741 void
742 tsetattr(int *attr, int l) {
743         int i;
744
745         for(i = 0; i < l; i++) {
746                 switch(attr[i]) {
747                 case 0:
748                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
749                         term.c.attr.fg = DefaultFG;
750                         term.c.attr.bg = DefaultBG;
751                         break;
752                 case 1:
753                         term.c.attr.mode |= ATTR_BOLD;   
754                         break;
755                 case 4: 
756                         term.c.attr.mode |= ATTR_UNDERLINE;
757                         break;
758                 case 7: 
759                         term.c.attr.mode |= ATTR_REVERSE;       
760                         break;
761                 case 22: 
762                         term.c.attr.mode &= ~ATTR_BOLD;  
763                         break;
764                 case 24: 
765                         term.c.attr.mode &= ~ATTR_UNDERLINE;
766                         break;
767                 case 27: 
768                         term.c.attr.mode &= ~ATTR_REVERSE;       
769                         break;
770                 case 38:
771                         if (i + 2 < l && attr[i + 1] == 5) {
772                                 i += 2;
773                                 if (BETWEEN(attr[i], 0, 255))
774                                         term.c.attr.fg = attr[i];
775                                 else
776                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
777                         }
778                         else
779                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]); 
780                         break;
781                 case 39:
782                         term.c.attr.fg = DefaultFG;
783                         break;
784                 case 48:
785                         if (i + 2 < l && attr[i + 1] == 5) {
786                                 i += 2;
787                                 if (BETWEEN(attr[i], 0, 255))
788                                         term.c.attr.bg = attr[i];
789                                 else
790                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
791                         }
792                         else
793                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]); 
794                         break;
795                 case 49:
796                         term.c.attr.bg = DefaultBG;
797                         break;
798                 default:
799                         if(BETWEEN(attr[i], 30, 37))
800                                 term.c.attr.fg = attr[i] - 30;
801                         else if(BETWEEN(attr[i], 40, 47))
802                                 term.c.attr.bg = attr[i] - 40;
803                         else if(BETWEEN(attr[i], 90, 97))
804                                 term.c.attr.fg = attr[i] - 90 + 8;
805                         else if(BETWEEN(attr[i], 100, 107))
806                                 term.c.attr.fg = attr[i] - 100 + 8;
807                         else 
808                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
809                         
810                         break;
811                 }
812         }
813 }
814
815 void
816 tsetscroll(int t, int b) {
817         int temp;
818
819         LIMIT(t, 0, term.row-1);
820         LIMIT(b, 0, term.row-1);
821         if(t > b) {
822                 temp = t;
823                 t = b;
824                 b = temp;
825         }
826         term.top = t;
827         term.bot = b;    
828 }
829
830 void
831 csihandle(void) {
832         switch(escseq.mode) {
833         default:
834         unknown:
835                 printf("erresc: unknown csi ");
836                 csidump();
837                 /* die(""); */
838                 break;
839         case '@': /* ICH -- Insert <n> blank char */
840                 DEFAULT(escseq.arg[0], 1);
841                 tinsertblank(escseq.arg[0]);
842                 break;
843         case 'A': /* CUU -- Cursor <n> Up */
844         case 'e':
845                 DEFAULT(escseq.arg[0], 1);
846                 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
847                 break;
848         case 'B': /* CUD -- Cursor <n> Down */
849                 DEFAULT(escseq.arg[0], 1);
850                 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
851                 break;
852         case 'C': /* CUF -- Cursor <n> Forward */
853         case 'a':
854                 DEFAULT(escseq.arg[0], 1);
855                 tmoveto(term.c.x+escseq.arg[0], term.c.y);
856                 break;
857         case 'D': /* CUB -- Cursor <n> Backward */
858                 DEFAULT(escseq.arg[0], 1);
859                 tmoveto(term.c.x-escseq.arg[0], term.c.y);
860                 break;
861         case 'E': /* CNL -- Cursor <n> Down and first col */
862                 DEFAULT(escseq.arg[0], 1);
863                 tmoveto(0, term.c.y+escseq.arg[0]);
864                 break;
865         case 'F': /* CPL -- Cursor <n> Up and first col */
866                 DEFAULT(escseq.arg[0], 1);
867                 tmoveto(0, term.c.y-escseq.arg[0]);
868                 break;
869         case 'G': /* CHA -- Move to <col> */
870         case '`': /* XXX: HPA -- same? */
871                 DEFAULT(escseq.arg[0], 1);
872                 tmoveto(escseq.arg[0]-1, term.c.y);
873                 break;
874         case 'H': /* CUP -- Move to <row> <col> */
875         case 'f': /* XXX: HVP -- same? */
876                 DEFAULT(escseq.arg[0], 1);
877                 DEFAULT(escseq.arg[1], 1);
878                 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
879                 break;
880         /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
881         case 'J': /* ED -- Clear screen */
882                 switch(escseq.arg[0]) {
883                 case 0: /* below */
884                         tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
885                         break;
886                 case 1: /* above */
887                         tclearregion(0, 0, term.c.x, term.c.y);
888                         break;
889                 case 2: /* all */
890                         tclearregion(0, 0, term.col-1, term.row-1);
891                         break;
892                 default:
893                         goto unknown;
894                 }
895                 break;
896         case 'K': /* EL -- Clear line */
897                 switch(escseq.arg[0]) {
898                 case 0: /* right */
899                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
900                         break;
901                 case 1: /* left */
902                         tclearregion(0, term.c.y, term.c.x, term.c.y);
903                         break;
904                 case 2: /* all */
905                         tclearregion(0, term.c.y, term.col-1, term.c.y);
906                         break;
907                 }
908                 break;
909         case 'S': /* SU -- Scroll <n> line up */
910                 DEFAULT(escseq.arg[0], 1);
911                 tscrollup(term.top, escseq.arg[0]);
912                 break;
913         case 'T': /* SD -- Scroll <n> line down */
914                 DEFAULT(escseq.arg[0], 1);
915                 tscrolldown(term.top, escseq.arg[0]);
916                 break;
917         case 'L': /* IL -- Insert <n> blank lines */
918                 DEFAULT(escseq.arg[0], 1);
919                 tinsertblankline(escseq.arg[0]);
920                 break;
921         case 'l': /* RM -- Reset Mode */
922                 if(escseq.priv) {
923                         switch(escseq.arg[0]) {
924                         case 1:
925                                 term.mode &= ~MODE_APPKEYPAD;
926                                 break;
927                         case 5: /* TODO: DECSCNM -- Remove reverse video */
928                                 break;
929                         case 7:
930                                 term.mode &= ~MODE_WRAP;
931                                 break;
932                         case 12: /* att610 -- Stop blinking cursor (IGNORED) */
933                                 break;
934                         case 25:
935                                 term.c.state |= CURSOR_HIDE;
936                                 break;
937                         case 1049: /* = 1047 and 1048 */
938                         case 1047:
939                                 if(IS_SET(MODE_ALTSCREEN)) {
940                                         tclearregion(0, 0, term.col-1, term.row-1);
941                                         tswapscreen();
942                                 }
943                                 if(escseq.arg[0] == 1047)
944                                         break;
945                         case 1048:
946                                 tcursor(CURSOR_LOAD);
947                                 break;
948                         default:
949                                 goto unknown;
950                         }
951                 } else {
952                         switch(escseq.arg[0]) {
953                         case 4:
954                                 term.mode &= ~MODE_INSERT;
955                                 break;
956                         default:
957                                 goto unknown;
958                         }
959                 }
960                 break;
961         case 'M': /* DL -- Delete <n> lines */
962                 DEFAULT(escseq.arg[0], 1);
963                 tdeleteline(escseq.arg[0]);
964                 break;
965         case 'X': /* ECH -- Erase <n> char */
966                 DEFAULT(escseq.arg[0], 1);
967                 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
968                 break;
969         case 'P': /* DCH -- Delete <n> char */
970                 DEFAULT(escseq.arg[0], 1);
971                 tdeletechar(escseq.arg[0]);
972                 break;
973         /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
974         case 'd': /* VPA -- Move to <row> */
975                 DEFAULT(escseq.arg[0], 1);
976                 tmoveto(term.c.x, escseq.arg[0]-1);
977                 break;
978         case 'h': /* SM -- Set terminal mode */
979                 if(escseq.priv) {
980                         switch(escseq.arg[0]) {
981                         case 1:
982                                 term.mode |= MODE_APPKEYPAD;
983                                 break;
984                         case 5: /* DECSCNM -- Reverve video */
985                                 /* TODO: set REVERSE on the whole screen (f) */
986                                 break;
987                         case 7:
988                                 term.mode |= MODE_WRAP;
989                                 break;
990                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
991                                  /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
992                                 if(escseq.narg > 1 && escseq.arg[1] != 25)
993                                         break;
994                         case 25:
995                                 term.c.state &= ~CURSOR_HIDE;
996                                 break;
997                         case 1049: /* = 1047 and 1048 */
998                         case 1047:
999                                 if(IS_SET(MODE_ALTSCREEN))
1000                                         tclearregion(0, 0, term.col-1, term.row-1);
1001                                 else
1002                                         tswapscreen();
1003                                 if(escseq.arg[0] == 1047)
1004                                         break;
1005                         case 1048:
1006                                 tcursor(CURSOR_SAVE);
1007                                 break;
1008                         default: goto unknown;
1009                         }
1010                 } else {
1011                         switch(escseq.arg[0]) {
1012                         case 4:
1013                                 term.mode |= MODE_INSERT;
1014                                 break;
1015                         default: goto unknown;
1016                         }
1017                 };
1018                 break;
1019         case 'm': /* SGR -- Terminal attribute (color) */
1020                 tsetattr(escseq.arg, escseq.narg);
1021                 break;
1022         case 'r': /* DECSTBM -- Set Scrolling Region */
1023                 if(escseq.priv)
1024                         goto unknown;
1025                 else {
1026                         DEFAULT(escseq.arg[0], 1);
1027                         DEFAULT(escseq.arg[1], term.row);
1028                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1029                         tmoveto(0, 0);
1030                 }
1031                 break;
1032         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1033                 tcursor(CURSOR_SAVE);
1034                 break;
1035         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1036                 tcursor(CURSOR_LOAD);
1037                 break;
1038         }
1039 }
1040
1041 void
1042 csidump(void) { 
1043         int i;
1044         printf("ESC [ %s", escseq.priv ? "? " : "");
1045         if(escseq.narg)
1046                 for(i = 0; i < escseq.narg; i++)
1047                         printf("%d ", escseq.arg[i]);
1048         if(escseq.mode)
1049                 putchar(escseq.mode);
1050         putchar('\n');
1051 }
1052
1053 void
1054 csireset(void) {
1055         memset(&escseq, 0, sizeof(escseq));
1056 }
1057
1058 void
1059 tputtab(void) {
1060         int space = TAB - term.c.x % TAB;
1061         tmoveto(term.c.x + space, term.c.y);
1062 }
1063
1064 void
1065 tputc(char c) {
1066         if(term.esc & ESC_START) {
1067                 if(term.esc & ESC_CSI) {
1068                         escseq.buf[escseq.len++] = c;
1069                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1070                                 term.esc = 0;
1071                                 csiparse(), csihandle();
1072                         }
1073                         /* TODO: handle other OSC */
1074                 } else if(term.esc & ESC_OSC) { 
1075                         if(c == ';') {
1076                                 term.titlelen = 0;
1077                                 term.esc = ESC_START | ESC_TITLE;
1078                         }
1079                 } else if(term.esc & ESC_TITLE) {
1080                         if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1081                                 term.esc = 0;
1082                                 term.title[term.titlelen] = '\0';
1083                                 XStoreName(xw.dis, xw.win, term.title);
1084                         } else {
1085                                 term.title[term.titlelen++] = c;
1086                         }
1087                 } else if(term.esc & ESC_ALTCHARSET) {
1088                         switch(c) {
1089                         case '0': /* Line drawing crap */
1090                                 term.c.attr.mode |= ATTR_GFX;
1091                                 break;
1092                         case 'B': /* Back to regular text */
1093                                 term.c.attr.mode &= ~ATTR_GFX;
1094                                 break;
1095                         default:
1096                                 printf("esc unhandled charset: ESC ( %c\n", c);
1097                         }
1098                         term.esc = 0;
1099                 } else {
1100                         switch(c) {
1101                         case '[':
1102                                 term.esc |= ESC_CSI;
1103                                 break;
1104                         case ']':
1105                                 term.esc |= ESC_OSC;
1106                                 break;
1107                         case '(':
1108                                 term.esc |= ESC_ALTCHARSET;
1109                                 break;
1110                         case 'D': /* IND -- Linefeed */
1111                                 if(term.c.y == term.bot)
1112                                         tscrollup(term.top, 1);
1113                                 else
1114                                         tmoveto(term.c.x, term.c.y+1);
1115                                 term.esc = 0;
1116                                 break;
1117                         case 'E': /* NEL -- Next line */
1118                                 tnewline();
1119                                 term.esc = 0;
1120                                 break;
1121                         case 'M': /* RI -- Reverse index */
1122                                 if(term.c.y == term.top)
1123                                         tscrolldown(term.top, 1);
1124                                 else
1125                                         tmoveto(term.c.x, term.c.y-1);
1126                                 term.esc = 0;
1127                                 break;
1128                         case 'c': /* RIS -- Reset to inital state */
1129                                 treset();
1130                                 term.esc = 0;
1131                                 break;
1132                         case '=': /* DECPAM -- Application keypad */
1133                                 term.mode |= MODE_APPKEYPAD;
1134                                 term.esc = 0;
1135                                 break;
1136                         case '>': /* DECPNM -- Normal keypad */
1137                                 term.mode &= ~MODE_APPKEYPAD;
1138                                 term.esc = 0;
1139                                 break;
1140                         case '7': /* DECSC -- Save Cursor */
1141                                 tcursor(CURSOR_SAVE);
1142                                 term.esc = 0;
1143                                 break;
1144                         case '8': /* DECRC -- Restore Cursor */
1145                                 tcursor(CURSOR_LOAD);
1146                                 term.esc = 0;
1147                                 break;
1148                         default:
1149                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1150                                 term.esc = 0;
1151                         }
1152                 }
1153         } else {
1154                 switch(c) {
1155                 case '\t':
1156                         tputtab();
1157                         break;
1158                 case '\b':
1159                         tmoveto(term.c.x-1, term.c.y);
1160                         break;
1161                 case '\r':
1162                         tmoveto(0, term.c.y);
1163                         break;
1164                 case '\n':
1165                         tnewline();
1166                         break;
1167                 case '\a':
1168                         if(!xw.focus)
1169                                 xseturgency(1);
1170                         break;
1171                 case '\033':
1172                         csireset();
1173                         term.esc = ESC_START;
1174                         break;
1175                 default:
1176                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1177                                 tnewline();
1178                         tsetchar(c);
1179                         if(term.c.x+1 < term.col)
1180                                 tmoveto(term.c.x+1, term.c.y);
1181                         else
1182                                 term.c.state |= CURSOR_WRAPNEXT;
1183                         break;
1184                 }
1185         }
1186 }
1187
1188 void
1189 tputs(char *s, int len) {
1190         for(; len > 0; len--)
1191                 tputc(*s++);
1192 }
1193
1194 void
1195 tresize(int col, int row) {
1196         int i, x;
1197         int minrow = MIN(row, term.row);
1198         int mincol = MIN(col, term.col);
1199         int slide = term.c.y - row + 1;
1200
1201         if(col < 1 || row < 1)
1202                 return;
1203
1204         /* free unneeded rows */
1205         i = 0;
1206         if(slide > 0) {
1207                 /* slide screen to keep cursor where we expect it -
1208                  * tscrollup would work here, but we can optimize to
1209                  * memmove because we're freeing the earlier lines */
1210                 for(/* i = 0 */; i < slide; i++) {
1211                         free(term.line[i]);
1212                         free(term.alt[i]);
1213                 }
1214                 memmove(term.line, term.line + slide, row * sizeof(Line));
1215                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1216         }
1217         for(i += row; i < term.row; i++) {
1218                 free(term.line[i]);
1219                 free(term.alt[i]);
1220         }
1221
1222         /* resize to new height */
1223         term.line = realloc(term.line, row * sizeof(Line));
1224         term.alt  = realloc(term.alt,  row * sizeof(Line));
1225
1226         /* resize each row to new width, zero-pad if needed */
1227         for(i = 0; i < minrow; i++) {
1228                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1229                 term.alt[i]  = realloc(term.alt[i],  col * sizeof(Glyph));
1230                 for(x = mincol; x < col; x++) {
1231                         term.line[i][x].state = 0;
1232                         term.alt[i][x].state = 0;
1233                 }
1234         }
1235
1236         /* allocate any new rows */
1237         for(/* i == minrow */; i < row; i++) {
1238                 term.line[i] = calloc(col, sizeof(Glyph));
1239                 term.alt [i] = calloc(col, sizeof(Glyph));
1240         }
1241         
1242         /* update terminal size */
1243         term.col = col, term.row = row;
1244         /* make use of the LIMIT in tmoveto */
1245         tmoveto(term.c.x, term.c.y);
1246         /* reset scrolling region */
1247         tsetscroll(0, row-1);
1248 }
1249
1250 void
1251 xloadcols(void) {
1252         int i, r, g, b;
1253         XColor color;
1254         unsigned long white = WhitePixel(xw.dis, xw.scr);
1255
1256         for(i = 0; i < 16; i++) {
1257                 if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
1258                         dc.col[i] = white;
1259                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1260                 } else
1261                         dc.col[i] = color.pixel;
1262         }
1263
1264         /* same colors as xterm */
1265         for(r = 0; r < 6; r++)
1266                 for(g = 0; g < 6; g++)
1267                         for(b = 0; b < 6; b++) {
1268                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1269                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1270                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1271                                 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1272                                         dc.col[i] = white;
1273                                         fprintf(stderr, "Could not allocate color %d\n", i);
1274                                 } else
1275                                         dc.col[i] = color.pixel;
1276                                 i++;
1277                         }
1278
1279         for(r = 0; r < 24; r++, i++) {
1280                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1281                 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1282                         dc.col[i] = white;
1283                         fprintf(stderr, "Could not allocate color %d\n", i);
1284                 } else
1285                         dc.col[i] = color.pixel;
1286         }
1287 }
1288
1289 void
1290 xclear(int x1, int y1, int x2, int y2) {
1291         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1292         XFillRectangle(xw.dis, xw.buf, dc.gc,
1293                        x1 * xw.cw, y1 * xw.ch,
1294                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1295 }
1296
1297 void
1298 xhints(void)
1299 {
1300         XClassHint class = {TNAME, TNAME};
1301         XWMHints wm = {.flags = InputHint, .input = 1};
1302         XSizeHints size = {
1303                 .flags = PSize | PResizeInc | PBaseSize,
1304                 .height = xw.h,
1305                 .width = xw.w,
1306                 .height_inc = xw.ch,
1307                 .width_inc = xw.cw,
1308                 .base_height = 2*BORDER,
1309                 .base_width = 2*BORDER,
1310         };
1311         XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1312 }
1313
1314 void
1315 xinit(void) {
1316         XSetWindowAttributes attrs;
1317
1318         if(!(xw.dis = XOpenDisplay(NULL)))
1319                 die("Can't open display\n");
1320         xw.scr = XDefaultScreen(xw.dis);
1321         
1322         /* font */
1323         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1324                 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1325
1326         /* XXX: Assuming same size for bold font */
1327         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1328         xw.ch = dc.font->ascent + dc.font->descent;
1329
1330         /* colors */
1331         xw.cmap = XDefaultColormap(xw.dis, xw.scr);
1332         xloadcols();
1333
1334         /* window - default size */
1335         xw.bufh = 24 * xw.ch;
1336         xw.bufw = 80 * xw.cw;
1337         xw.h = xw.bufh + 2*BORDER;
1338         xw.w = xw.bufw + 2*BORDER;
1339
1340         attrs.background_pixel = dc.col[DefaultBG];
1341         attrs.border_pixel = dc.col[DefaultBG];
1342         attrs.bit_gravity = NorthWestGravity;
1343         attrs.event_mask = FocusChangeMask | KeyPressMask
1344                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1345                 | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1346         attrs.colormap = xw.cmap;
1347
1348         xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1349                         xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
1350                         XDefaultVisual(xw.dis, xw.scr),
1351                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1352                         | CWColormap,
1353                         &attrs);
1354         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1355
1356
1357         /* input methods */
1358         xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
1359         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing 
1360                                            | XIMStatusNothing, XNClientWindow, xw.win, 
1361                                            XNFocusWindow, xw.win, NULL);
1362         /* gc */
1363         dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1364         
1365         XMapWindow(xw.dis, xw.win);
1366         xhints();
1367         XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
1368         XSync(xw.dis, 0);
1369 }
1370
1371 void
1372 xdraws(char *s, Glyph base, int x, int y, int len) {
1373         unsigned long xfg, xbg;
1374         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1375         int i;
1376
1377         if(base.mode & ATTR_REVERSE)
1378                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1379         else
1380                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1381
1382         XSetBackground(xw.dis, dc.gc, xbg);
1383         XSetForeground(xw.dis, dc.gc, xfg);
1384         
1385         if(base.mode & ATTR_GFX)
1386                 for(i = 0; i < len; i++) {
1387                         char c = gfx[(unsigned int)s[i] % 256];
1388                         if(c)
1389                                 s[i] = c;
1390                         else if(s[i] > 0x5f)
1391                                 s[i] -= 0x5f;
1392                 }
1393
1394         XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1395         XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1396         
1397         if(base.mode & ATTR_UNDERLINE)
1398                 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1399 }
1400
1401 void
1402 xdrawcursor(void) {
1403         static int oldx = 0;
1404         static int oldy = 0;
1405         Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1406         
1407         LIMIT(oldx, 0, term.col-1);
1408         LIMIT(oldy, 0, term.row-1);
1409         
1410         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1411                 g.c = term.line[term.c.y][term.c.x].c;
1412         
1413         /* remove the old cursor */
1414         if(term.line[oldy][oldx].state & GLYPH_SET)
1415                 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1416         else
1417                 xclear(oldx, oldy, oldx, oldy);
1418         
1419         /* draw the new one */
1420         if(!(term.c.state & CURSOR_HIDE) && xw.focus) {
1421                 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1422                 oldx = term.c.x, oldy = term.c.y;
1423         }
1424 }
1425
1426 #ifdef DEBUG
1427 /* basic drawing routines */
1428 void
1429 xdrawc(int x, int y, Glyph g) {
1430         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1431         XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1432         XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1433         XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1434         XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1435 }
1436
1437 void
1438 draw(int dummy) {
1439         int x, y;
1440
1441         xclear(0, 0, term.col-1, term.row-1);
1442         for(y = 0; y < term.row; y++)
1443                 for(x = 0; x < term.col; x++)
1444                         if(term.line[y][x].state & GLYPH_SET)
1445                                 xdrawc(x, y, term.line[y][x]);
1446
1447         xdrawcursor();
1448         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1449         XFlush(xw.dis);
1450 }
1451
1452 #else
1453 /* optimized drawing routine */
1454 void
1455 draw(int redraw_all) {
1456         int i, x, y, ox;
1457         Glyph base, new;
1458         char buf[DRAW_BUF_SIZ];
1459
1460         if(!xw.vis)
1461                 return;
1462
1463         xclear(0, 0, term.col-1, term.row-1);
1464         for(y = 0; y < term.row; y++) {
1465                 base = term.line[y][0];
1466                 i = ox = 0;
1467                 for(x = 0; x < term.col; x++) {
1468                         new = term.line[y][x];
1469                         if(sel.bx!=-1 && new.c && selected(x, y))
1470                                 new.mode ^= ATTR_REVERSE;
1471                         if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1472                                         i >= DRAW_BUF_SIZ)) {
1473                                 xdraws(buf, base, ox, y, i);
1474                                 i = 0;
1475                         }
1476                         if(new.state & GLYPH_SET) {
1477                                 if(i == 0) {
1478                                         ox = x;
1479                                         base = new;
1480                                 }
1481                                 buf[i++] = new.c;
1482                         }
1483                 }
1484                 if(i > 0)
1485                         xdraws(buf, base, ox, y, i);
1486         }
1487         xdrawcursor();
1488         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1489         XFlush(xw.dis);
1490 }
1491
1492 #endif
1493
1494 void
1495 expose(XEvent *ev) {
1496         draw(SCREEN_REDRAW);
1497 }
1498
1499 void
1500 visibility(XEvent *ev) {
1501         XVisibilityEvent *e = &ev->xvisibility;
1502         /* XXX if this goes from 0 to 1, need a full redraw for next Expose,
1503          * not just a buf copy */
1504         xw.vis = e->state != VisibilityFullyObscured;
1505 }
1506
1507 void
1508 unmap(XEvent *ev) {
1509         xw.vis = 0;
1510 }
1511
1512 void
1513 xseturgency(int add) {
1514         XWMHints *h = XGetWMHints(xw.dis, xw.win);
1515         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1516         XSetWMHints(xw.dis, xw.win, h);
1517         XFree(h);
1518 }
1519
1520 void
1521 focus(XEvent *ev) {
1522         if((xw.focus = ev->type == FocusIn))
1523                 xseturgency(0);
1524         draw(SCREEN_UPDATE);
1525 }
1526
1527 char*
1528 kmap(KeySym k) {
1529         int i;
1530         for(i = 0; i < LEN(key); i++)
1531                 if(key[i].k == k)
1532                         return (char*)key[i].s;
1533         return NULL;
1534 }
1535
1536 void
1537 kpress(XEvent *ev) {
1538         XKeyEvent *e = &ev->xkey;
1539         KeySym ksym;
1540         char buf[32];
1541         char *customkey;
1542         int len;
1543         int meta;
1544         int shift;
1545         Status status;
1546
1547         meta = e->state & Mod1Mask;
1548         shift = e->state & ShiftMask;
1549         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1550
1551         if((customkey = kmap(ksym)))
1552                 ttywrite(customkey, strlen(customkey));
1553         else if(len > 0) {
1554                 buf[sizeof(buf)-1] = '\0';
1555                 if(meta && len == 1)
1556                         ttywrite("\033", 1);
1557                 ttywrite(buf, len);
1558         } else
1559                 switch(ksym) {
1560                 case XK_Up:
1561                 case XK_Down:
1562                 case XK_Left:
1563                 case XK_Right:
1564                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1565                         ttywrite(buf, 3);
1566                         break;
1567                 case XK_Insert:
1568                         if(shift)
1569                                 selpaste();
1570                         break;
1571                 default:
1572                         fprintf(stderr, "errkey: %d\n", (int)ksym);
1573                         break;
1574                 }
1575 }
1576
1577 void
1578 resize(XEvent *e) {
1579         int col, row;
1580         
1581         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1582                 return;
1583         
1584         xw.w = e->xconfigure.width;
1585         xw.h = e->xconfigure.height;
1586         xw.bufw = xw.w - 2*BORDER;
1587         xw.bufh = xw.h - 2*BORDER;
1588         col = xw.bufw / xw.cw;
1589         row = xw.bufh / xw.ch;
1590         tresize(col, row);
1591         ttyresize(col, row);
1592         xw.bufh = MAX(1, xw.bufh);
1593         xw.bufw = MAX(1, xw.bufw);
1594         XFreePixmap(xw.dis, xw.buf);
1595         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1596 }
1597
1598 void
1599 run(void) {
1600         XEvent ev;
1601         fd_set rfd;
1602         int xfd = XConnectionNumber(xw.dis);
1603
1604         for(;;) {
1605                 FD_ZERO(&rfd);
1606                 FD_SET(cmdfd, &rfd);
1607                 FD_SET(xfd, &rfd);
1608                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1609                         if(errno == EINTR)
1610                                 continue;
1611                         die("select failed: %s\n", SERRNO);
1612                 }
1613                 if(FD_ISSET(cmdfd, &rfd)) {
1614                         ttyread();
1615                         draw(SCREEN_UPDATE); 
1616                 }
1617                 while(XPending(xw.dis)) {
1618                         XNextEvent(xw.dis, &ev);
1619                         if (XFilterEvent(&ev, xw.win))
1620                                 continue;
1621                         if(handler[ev.type])
1622                                 (handler[ev.type])(&ev);
1623                 }
1624         }
1625 }
1626
1627 int
1628 main(int argc, char *argv[]) {
1629         int i;
1630         
1631         for(i = 1; i < argc; i++) {
1632                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1633                 case 't':
1634                         if(++i < argc) opt_title = argv[i];
1635                         break;
1636                 case 'e':
1637                         if(++i < argc) opt_cmd = argv[i];
1638                         break;
1639                 case 'v':
1640                 default:
1641                         die(USAGE);
1642                 }
1643         }
1644         setlocale(LC_CTYPE, "");
1645         tnew(80, 24);
1646         ttynew();
1647         xinit();
1648         selinit();
1649         run();
1650         return 0;
1651 }