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