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