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