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