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