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