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