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