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