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