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