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