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