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