JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
get rid of artifacts in border on resize down
[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 void 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.row-1);
887                         break;
888                 case 1: /* above */
889                         tclearregion(0, 0, term.c.x, term.c.y);
890                         break;
891                 case 2: /* all */
892                         tclearregion(0, 0, term.col-1, term.row-1);
893                         break;
894                 default:
895                         goto unknown;
896                 }
897                 break;
898         case 'K': /* EL -- Clear line */
899                 switch(escseq.arg[0]) {
900                 case 0: /* right */
901                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
902                         break;
903                 case 1: /* left */
904                         tclearregion(0, term.c.y, term.c.x, term.c.y);
905                         break;
906                 case 2: /* all */
907                         tclearregion(0, term.c.y, term.col-1, term.c.y);
908                         break;
909                 }
910                 break;
911         case 'S': /* SU -- Scroll <n> line up */
912                 DEFAULT(escseq.arg[0], 1);
913                 tscrollup(term.top, escseq.arg[0]);
914                 break;
915         case 'T': /* SD -- Scroll <n> line down */
916                 DEFAULT(escseq.arg[0], 1);
917                 tscrolldown(term.top, escseq.arg[0]);
918                 break;
919         case 'L': /* IL -- Insert <n> blank lines */
920                 DEFAULT(escseq.arg[0], 1);
921                 tinsertblankline(escseq.arg[0]);
922                 break;
923         case 'l': /* RM -- Reset Mode */
924                 if(escseq.priv) {
925                         switch(escseq.arg[0]) {
926                         case 1:
927                                 term.mode &= ~MODE_APPKEYPAD;
928                                 break;
929                         case 5: /* TODO: DECSCNM -- Remove reverse video */
930                                 break;
931                         case 7:
932                                 term.mode &= ~MODE_WRAP;
933                                 break;
934                         case 12: /* att610 -- Stop blinking cursor (IGNORED) */
935                                 break;
936                         case 20:
937                                 term.mode &= ~MODE_CRLF;
938                                 break;
939                         case 25:
940                                 term.c.state |= CURSOR_HIDE;
941                                 break;
942                         case 1049: /* = 1047 and 1048 */
943                         case 1047:
944                                 if(IS_SET(MODE_ALTSCREEN)) {
945                                         tclearregion(0, 0, term.col-1, term.row-1);
946                                         tswapscreen();
947                                 }
948                                 if(escseq.arg[0] == 1047)
949                                         break;
950                         case 1048:
951                                 tcursor(CURSOR_LOAD);
952                                 break;
953                         default:
954                                 goto unknown;
955                         }
956                 } else {
957                         switch(escseq.arg[0]) {
958                         case 4:
959                                 term.mode &= ~MODE_INSERT;
960                                 break;
961                         default:
962                                 goto unknown;
963                         }
964                 }
965                 break;
966         case 'M': /* DL -- Delete <n> lines */
967                 DEFAULT(escseq.arg[0], 1);
968                 tdeleteline(escseq.arg[0]);
969                 break;
970         case 'X': /* ECH -- Erase <n> char */
971                 DEFAULT(escseq.arg[0], 1);
972                 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
973                 break;
974         case 'P': /* DCH -- Delete <n> char */
975                 DEFAULT(escseq.arg[0], 1);
976                 tdeletechar(escseq.arg[0]);
977                 break;
978         /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
979         case 'd': /* VPA -- Move to <row> */
980                 DEFAULT(escseq.arg[0], 1);
981                 tmoveto(term.c.x, escseq.arg[0]-1);
982                 break;
983         case 'h': /* SM -- Set terminal mode */
984                 if(escseq.priv) {
985                         switch(escseq.arg[0]) {
986                         case 1:
987                                 term.mode |= MODE_APPKEYPAD;
988                                 break;
989                         case 5: /* DECSCNM -- Reverve video */
990                                 /* TODO: set REVERSE on the whole screen (f) */
991                                 break;
992                         case 7:
993                                 term.mode |= MODE_WRAP;
994                                 break;
995                         case 20:
996                                 term.mode |= MODE_CRLF;
997                                 break;
998                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
999                                  /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
1000                                 if(escseq.narg > 1 && escseq.arg[1] != 25)
1001                                         break;
1002                         case 25:
1003                                 term.c.state &= ~CURSOR_HIDE;
1004                                 break;
1005                         case 1049: /* = 1047 and 1048 */
1006                         case 1047:
1007                                 if(IS_SET(MODE_ALTSCREEN))
1008                                         tclearregion(0, 0, term.col-1, term.row-1);
1009                                 else
1010                                         tswapscreen();
1011                                 if(escseq.arg[0] == 1047)
1012                                         break;
1013                         case 1048:
1014                                 tcursor(CURSOR_SAVE);
1015                                 break;
1016                         default: goto unknown;
1017                         }
1018                 } else {
1019                         switch(escseq.arg[0]) {
1020                         case 4:
1021                                 term.mode |= MODE_INSERT;
1022                                 break;
1023                         default: goto unknown;
1024                         }
1025                 };
1026                 break;
1027         case 'm': /* SGR -- Terminal attribute (color) */
1028                 tsetattr(escseq.arg, escseq.narg);
1029                 break;
1030         case 'r': /* DECSTBM -- Set Scrolling Region */
1031                 if(escseq.priv)
1032                         goto unknown;
1033                 else {
1034                         DEFAULT(escseq.arg[0], 1);
1035                         DEFAULT(escseq.arg[1], term.row);
1036                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1037                         tmoveto(0, 0);
1038                 }
1039                 break;
1040         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1041                 tcursor(CURSOR_SAVE);
1042                 break;
1043         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1044                 tcursor(CURSOR_LOAD);
1045                 break;
1046         }
1047 }
1048
1049 void
1050 csidump(void) { 
1051         int i;
1052         printf("ESC [ %s", escseq.priv ? "? " : "");
1053         if(escseq.narg)
1054                 for(i = 0; i < escseq.narg; i++)
1055                         printf("%d ", escseq.arg[i]);
1056         if(escseq.mode)
1057                 putchar(escseq.mode);
1058         putchar('\n');
1059 }
1060
1061 void
1062 csireset(void) {
1063         memset(&escseq, 0, sizeof(escseq));
1064 }
1065
1066 void
1067 tputtab(void) {
1068         int space = TAB - term.c.x % TAB;
1069         tmoveto(term.c.x + space, term.c.y);
1070 }
1071
1072 void
1073 tputc(char c) {
1074         if(term.esc & ESC_START) {
1075                 if(term.esc & ESC_CSI) {
1076                         escseq.buf[escseq.len++] = c;
1077                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1078                                 term.esc = 0;
1079                                 csiparse(), csihandle();
1080                         }
1081                         /* TODO: handle other OSC */
1082                 } else if(term.esc & ESC_OSC) { 
1083                         if(c == ';') {
1084                                 term.titlelen = 0;
1085                                 term.esc = ESC_START | ESC_TITLE;
1086                         }
1087                 } else if(term.esc & ESC_TITLE) {
1088                         if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1089                                 term.esc = 0;
1090                                 term.title[term.titlelen] = '\0';
1091                                 XStoreName(xw.dis, xw.win, term.title);
1092                         } else {
1093                                 term.title[term.titlelen++] = c;
1094                         }
1095                 } else if(term.esc & ESC_ALTCHARSET) {
1096                         switch(c) {
1097                         case '0': /* Line drawing crap */
1098                                 term.c.attr.mode |= ATTR_GFX;
1099                                 break;
1100                         case 'B': /* Back to regular text */
1101                                 term.c.attr.mode &= ~ATTR_GFX;
1102                                 break;
1103                         default:
1104                                 printf("esc unhandled charset: ESC ( %c\n", c);
1105                         }
1106                         term.esc = 0;
1107                 } else {
1108                         switch(c) {
1109                         case '[':
1110                                 term.esc |= ESC_CSI;
1111                                 break;
1112                         case ']':
1113                                 term.esc |= ESC_OSC;
1114                                 break;
1115                         case '(':
1116                                 term.esc |= ESC_ALTCHARSET;
1117                                 break;
1118                         case 'D': /* IND -- Linefeed */
1119                                 if(term.c.y == term.bot)
1120                                         tscrollup(term.top, 1);
1121                                 else
1122                                         tmoveto(term.c.x, term.c.y+1);
1123                                 term.esc = 0;
1124                                 break;
1125                         case 'E': /* NEL -- Next line */
1126                                 tnewline(1); /* always go to first col */
1127                                 term.esc = 0;
1128                                 break;
1129                         case 'M': /* RI -- Reverse index */
1130                                 if(term.c.y == term.top)
1131                                         tscrolldown(term.top, 1);
1132                                 else
1133                                         tmoveto(term.c.x, term.c.y-1);
1134                                 term.esc = 0;
1135                                 break;
1136                         case 'c': /* RIS -- Reset to inital state */
1137                                 treset();
1138                                 term.esc = 0;
1139                                 break;
1140                         case '=': /* DECPAM -- Application keypad */
1141                                 term.mode |= MODE_APPKEYPAD;
1142                                 term.esc = 0;
1143                                 break;
1144                         case '>': /* DECPNM -- Normal keypad */
1145                                 term.mode &= ~MODE_APPKEYPAD;
1146                                 term.esc = 0;
1147                                 break;
1148                         case '7': /* DECSC -- Save Cursor */
1149                                 tcursor(CURSOR_SAVE);
1150                                 term.esc = 0;
1151                                 break;
1152                         case '8': /* DECRC -- Restore Cursor */
1153                                 tcursor(CURSOR_LOAD);
1154                                 term.esc = 0;
1155                                 break;
1156                         default:
1157                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1158                                 term.esc = 0;
1159                         }
1160                 }
1161         } else {
1162                 switch(c) {
1163                 case '\t':
1164                         tputtab();
1165                         break;
1166                 case '\b':
1167                         tmoveto(term.c.x-1, term.c.y);
1168                         break;
1169                 case '\r':
1170                         tmoveto(0, term.c.y);
1171                         break;
1172                 case '\f':
1173                 case '\v':
1174                 case '\n':
1175                         /* go to first col if the mode is set */
1176                         tnewline(IS_SET(MODE_CRLF));
1177                         break;
1178                 case '\a':
1179                         if(!(xw.state & WIN_FOCUSED))
1180                                 xseturgency(1);
1181                         break;
1182                 case '\033':
1183                         csireset();
1184                         term.esc = ESC_START;
1185                         break;
1186                 default:
1187                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1188                                 tnewline(1); /* always go to first col */
1189                         tsetchar(c);
1190                         if(term.c.x+1 < term.col)
1191                                 tmoveto(term.c.x+1, term.c.y);
1192                         else
1193                                 term.c.state |= CURSOR_WRAPNEXT;
1194                         break;
1195                 }
1196         }
1197 }
1198
1199 void
1200 tputs(char *s, int len) {
1201         for(; len > 0; len--)
1202                 tputc(*s++);
1203 }
1204
1205 void
1206 tresize(int col, int row) {
1207         int i, x;
1208         int minrow = MIN(row, term.row);
1209         int mincol = MIN(col, term.col);
1210         int slide = term.c.y - row + 1;
1211
1212         if(col < 1 || row < 1)
1213                 return;
1214
1215         /* free unneeded rows */
1216         i = 0;
1217         if(slide > 0) {
1218                 /* slide screen to keep cursor where we expect it -
1219                  * tscrollup would work here, but we can optimize to
1220                  * memmove because we're freeing the earlier lines */
1221                 for(/* i = 0 */; i < slide; i++) {
1222                         free(term.line[i]);
1223                         free(term.alt[i]);
1224                 }
1225                 memmove(term.line, term.line + slide, row * sizeof(Line));
1226                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1227         }
1228         for(i += row; i < term.row; i++) {
1229                 free(term.line[i]);
1230                 free(term.alt[i]);
1231         }
1232
1233         /* resize to new height */
1234         term.line = realloc(term.line, row * sizeof(Line));
1235         term.alt  = realloc(term.alt,  row * sizeof(Line));
1236
1237         /* resize each row to new width, zero-pad if needed */
1238         for(i = 0; i < minrow; i++) {
1239                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1240                 term.alt[i]  = realloc(term.alt[i],  col * sizeof(Glyph));
1241                 for(x = mincol; x < col; x++) {
1242                         term.line[i][x].state = 0;
1243                         term.alt[i][x].state = 0;
1244                 }
1245         }
1246
1247         /* allocate any new rows */
1248         for(/* i == minrow */; i < row; i++) {
1249                 term.line[i] = calloc(col, sizeof(Glyph));
1250                 term.alt [i] = calloc(col, sizeof(Glyph));
1251         }
1252         
1253         /* update terminal size */
1254         term.col = col, term.row = row;
1255         /* make use of the LIMIT in tmoveto */
1256         tmoveto(term.c.x, term.c.y);
1257         /* reset scrolling region */
1258         tsetscroll(0, row-1);
1259 }
1260
1261 void
1262 xresize(int col, int row) {
1263         Pixmap newbuf;
1264         int oldw, oldh;
1265
1266         oldw = xw.bufw;
1267         oldh = xw.bufh;
1268         xw.bufw = MAX(1, col * xw.cw);
1269         xw.bufh = MAX(1, row * xw.ch);
1270         newbuf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1271         XCopyArea(xw.dis, xw.buf, newbuf, dc.gc, 0, 0, xw.bufw, xw.bufh, 0, 0);
1272         XFreePixmap(xw.dis, xw.buf);
1273         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1274         if(xw.bufw > oldw)
1275                 XFillRectangle(xw.dis, newbuf, dc.gc, oldw, 0,
1276                                 xw.bufw-oldw, MIN(xw.bufh, oldh));
1277         else if(xw.bufw < oldw && (BORDER > 0 || xw.w > xw.bufw))
1278                 XClearArea(xw.dis, xw.win, BORDER+xw.bufw, BORDER,
1279                                 xw.w-xw.bufh-BORDER, BORDER+MIN(xw.bufh, oldh),
1280                                 False);
1281         if(xw.bufh > oldh)
1282                 XFillRectangle(xw.dis, newbuf, dc.gc, 0, oldh,
1283                                 xw.bufw, xw.bufh-oldh);
1284         else if(xw.bufh < oldh && (BORDER > 0 || xw.h > xw.bufh))
1285                 XClearArea(xw.dis, xw.win, BORDER, BORDER+xw.bufh,
1286                                 xw.w-2*BORDER, xw.h-xw.bufh-BORDER,
1287                                 False);
1288         xw.buf = newbuf;
1289 }
1290
1291 void
1292 xloadcols(void) {
1293         int i, r, g, b;
1294         XColor color;
1295         unsigned long white = WhitePixel(xw.dis, xw.scr);
1296
1297         for(i = 0; i < 16; i++) {
1298                 if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
1299                         dc.col[i] = white;
1300                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1301                 } else
1302                         dc.col[i] = color.pixel;
1303         }
1304
1305         /* same colors as xterm */
1306         for(r = 0; r < 6; r++)
1307                 for(g = 0; g < 6; g++)
1308                         for(b = 0; b < 6; b++) {
1309                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1310                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1311                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1312                                 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1313                                         dc.col[i] = white;
1314                                         fprintf(stderr, "Could not allocate color %d\n", i);
1315                                 } else
1316                                         dc.col[i] = color.pixel;
1317                                 i++;
1318                         }
1319
1320         for(r = 0; r < 24; r++, i++) {
1321                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1322                 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1323                         dc.col[i] = white;
1324                         fprintf(stderr, "Could not allocate color %d\n", i);
1325                 } else
1326                         dc.col[i] = color.pixel;
1327         }
1328 }
1329
1330 void
1331 xclear(int x1, int y1, int x2, int y2) {
1332         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1333         XFillRectangle(xw.dis, xw.buf, dc.gc,
1334                        x1 * xw.cw, y1 * xw.ch,
1335                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1336 }
1337
1338 void
1339 xhints(void)
1340 {
1341         XClassHint class = {TNAME, TNAME};
1342         XWMHints wm = {.flags = InputHint, .input = 1};
1343         XSizeHints size = {
1344                 .flags = PSize | PResizeInc | PBaseSize,
1345                 .height = xw.h,
1346                 .width = xw.w,
1347                 .height_inc = xw.ch,
1348                 .width_inc = xw.cw,
1349                 .base_height = 2*BORDER,
1350                 .base_width = 2*BORDER,
1351         };
1352         XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1353 }
1354
1355 void
1356 xinit(void) {
1357         XSetWindowAttributes attrs;
1358
1359         if(!(xw.dis = XOpenDisplay(NULL)))
1360                 die("Can't open display\n");
1361         xw.scr = XDefaultScreen(xw.dis);
1362         
1363         /* font */
1364         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1365                 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1366
1367         /* XXX: Assuming same size for bold font */
1368         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1369         xw.ch = dc.font->ascent + dc.font->descent;
1370
1371         /* colors */
1372         xw.cmap = XDefaultColormap(xw.dis, xw.scr);
1373         xloadcols();
1374
1375         /* window - default size */
1376         xw.bufh = 24 * xw.ch;
1377         xw.bufw = 80 * xw.cw;
1378         xw.h = xw.bufh + 2*BORDER;
1379         xw.w = xw.bufw + 2*BORDER;
1380
1381         attrs.background_pixel = dc.col[DefaultBG];
1382         attrs.border_pixel = dc.col[DefaultBG];
1383         attrs.bit_gravity = NorthWestGravity;
1384         attrs.event_mask = FocusChangeMask | KeyPressMask
1385                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1386                 | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1387         attrs.colormap = xw.cmap;
1388
1389         xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1390                         xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
1391                         XDefaultVisual(xw.dis, xw.scr),
1392                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1393                         | CWColormap,
1394                         &attrs);
1395         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1396
1397
1398         /* input methods */
1399         xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
1400         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing 
1401                                            | XIMStatusNothing, XNClientWindow, xw.win, 
1402                                            XNFocusWindow, xw.win, NULL);
1403         /* gc */
1404         dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1405         
1406         XMapWindow(xw.dis, xw.win);
1407         xhints();
1408         XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
1409         XSync(xw.dis, 0);
1410 }
1411
1412 void
1413 xdraws(char *s, Glyph base, int x, int y, int len) {
1414         unsigned long xfg, xbg;
1415         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1416         int i;
1417
1418         if(base.mode & ATTR_REVERSE)
1419                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1420         else
1421                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1422
1423         XSetBackground(xw.dis, dc.gc, xbg);
1424         XSetForeground(xw.dis, dc.gc, xfg);
1425         
1426         if(base.mode & ATTR_GFX)
1427                 for(i = 0; i < len; i++) {
1428                         char c = gfx[(unsigned int)s[i] % 256];
1429                         if(c)
1430                                 s[i] = c;
1431                         else if(s[i] > 0x5f)
1432                                 s[i] -= 0x5f;
1433                 }
1434
1435         XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1436         XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1437         
1438         if(base.mode & ATTR_UNDERLINE)
1439                 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1440 }
1441
1442 void
1443 xdrawcursor(void) {
1444         static int oldx = 0;
1445         static int oldy = 0;
1446         Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1447         
1448         LIMIT(oldx, 0, term.col-1);
1449         LIMIT(oldy, 0, term.row-1);
1450         
1451         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1452                 g.c = term.line[term.c.y][term.c.x].c;
1453         
1454         /* remove the old cursor */
1455         if(term.line[oldy][oldx].state & GLYPH_SET)
1456                 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1457         else
1458                 xclear(oldx, oldy, oldx, oldy);
1459         
1460         /* draw the new one */
1461         if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
1462                 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1463                 oldx = term.c.x, oldy = term.c.y;
1464         }
1465 }
1466
1467 #ifdef DEBUG
1468 /* basic drawing routines */
1469 void
1470 xdrawc(int x, int y, Glyph g) {
1471         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1472         XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1473         XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1474         XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1475         XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1476 }
1477
1478 void
1479 draw(int dummy) {
1480         int x, y;
1481
1482         xclear(0, 0, term.col-1, term.row-1);
1483         for(y = 0; y < term.row; y++)
1484                 for(x = 0; x < term.col; x++)
1485                         if(term.line[y][x].state & GLYPH_SET)
1486                                 xdrawc(x, y, term.line[y][x]);
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 #else
1494 /* optimized drawing routine */
1495 void
1496 draw(int redraw_all) {
1497         int i, x, y, ox;
1498         Glyph base, new;
1499         char buf[DRAW_BUF_SIZ];
1500
1501         if(!(xw.state & WIN_VISIBLE))
1502                 return;
1503
1504         xclear(0, 0, term.col-1, term.row-1);
1505         for(y = 0; y < term.row; y++) {
1506                 base = term.line[y][0];
1507                 i = ox = 0;
1508                 for(x = 0; x < term.col; x++) {
1509                         new = term.line[y][x];
1510                         if(sel.bx!=-1 && new.c && selected(x, y))
1511                                 new.mode ^= ATTR_REVERSE;
1512                         if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1513                                         i >= DRAW_BUF_SIZ)) {
1514                                 xdraws(buf, base, ox, y, i);
1515                                 i = 0;
1516                         }
1517                         if(new.state & GLYPH_SET) {
1518                                 if(i == 0) {
1519                                         ox = x;
1520                                         base = new;
1521                                 }
1522                                 buf[i++] = new.c;
1523                         }
1524                 }
1525                 if(i > 0)
1526                         xdraws(buf, base, ox, y, i);
1527         }
1528         xdrawcursor();
1529         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1530 }
1531
1532 #endif
1533
1534 void
1535 expose(XEvent *ev) {
1536         XExposeEvent *e = &ev->xexpose;
1537         if(xw.state & WIN_REDRAW) {
1538                 if(!e->count) {
1539                         xw.state &= ~WIN_REDRAW;
1540                         draw(SCREEN_REDRAW);
1541                 }
1542         } else
1543                 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
1544                                 e->width, e->height, e->x, e->y);
1545 }
1546
1547 void
1548 visibility(XEvent *ev) {
1549         XVisibilityEvent *e = &ev->xvisibility;
1550         if(e->state == VisibilityFullyObscured)
1551                 xw.state &= ~WIN_VISIBLE;
1552         else if(!(xw.state & WIN_VISIBLE))
1553                 /* need a full redraw for next Expose, not just a buf copy */
1554                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
1555 }
1556
1557 void
1558 unmap(XEvent *ev) {
1559         xw.state &= ~WIN_VISIBLE;
1560 }
1561
1562 void
1563 xseturgency(int add) {
1564         XWMHints *h = XGetWMHints(xw.dis, xw.win);
1565         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1566         XSetWMHints(xw.dis, xw.win, h);
1567         XFree(h);
1568 }
1569
1570 void
1571 focus(XEvent *ev) {
1572         if(ev->type == FocusIn) {
1573                 xw.state |= WIN_FOCUSED;
1574                 xseturgency(0);
1575         } else
1576                 xw.state &= ~WIN_FOCUSED;
1577         draw(SCREEN_UPDATE);
1578 }
1579
1580 char*
1581 kmap(KeySym k) {
1582         int i;
1583         for(i = 0; i < LEN(key); i++)
1584                 if(key[i].k == k)
1585                         return (char*)key[i].s;
1586         return NULL;
1587 }
1588
1589 void
1590 kpress(XEvent *ev) {
1591         XKeyEvent *e = &ev->xkey;
1592         KeySym ksym;
1593         char buf[32];
1594         char *customkey;
1595         int len;
1596         int meta;
1597         int shift;
1598         Status status;
1599
1600         meta = e->state & Mod1Mask;
1601         shift = e->state & ShiftMask;
1602         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1603         
1604         /* 1. custom keys from config.h */
1605         if((customkey = kmap(ksym)))
1606                 ttywrite(customkey, strlen(customkey));
1607         /* 2. hardcoded (overrides X lookup) */
1608         else
1609                 switch(ksym) {
1610                 case XK_Up:
1611                 case XK_Down:
1612                 case XK_Left:
1613                 case XK_Right:
1614                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1615                         ttywrite(buf, 3);
1616                         break;
1617                 case XK_Insert:
1618                         if(shift)
1619                                 selpaste();
1620                         break;
1621                 case XK_Return:
1622                         if(IS_SET(MODE_CRLF))
1623                                 ttywrite("\r\n", 2);
1624                         else
1625                                 ttywrite("\r", 1);
1626                         break;
1627                         /* 3. X lookup  */
1628                 default:
1629                         if(len > 0) {
1630                                 buf[sizeof(buf)-1] = '\0';
1631                                 if(meta && len == 1)
1632                                         ttywrite("\033", 1);
1633                                 ttywrite(buf, len);
1634                         } else /* 4. nothing to send */
1635                                 fprintf(stderr, "errkey: %d\n", (int)ksym);
1636                         break;
1637                 }
1638 }
1639
1640 void
1641 resize(XEvent *e) {
1642         int col, row;
1643         
1644         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1645                 return;
1646         
1647         xw.w = e->xconfigure.width;
1648         xw.h = e->xconfigure.height;
1649         col = (xw.w - 2*BORDER) / xw.cw;
1650         row = (xw.h - 2*BORDER) / xw.ch;
1651         if(col == term.col && row == term.row)
1652                 return;
1653         tresize(col, row);
1654         ttyresize(col, row);
1655         xresize(col, row);
1656 }
1657
1658 void
1659 run(void) {
1660         XEvent ev;
1661         fd_set rfd;
1662         int xfd = XConnectionNumber(xw.dis);
1663
1664         for(;;) {
1665                 FD_ZERO(&rfd);
1666                 FD_SET(cmdfd, &rfd);
1667                 FD_SET(xfd, &rfd);
1668                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1669                         if(errno == EINTR)
1670                                 continue;
1671                         die("select failed: %s\n", SERRNO);
1672                 }
1673                 if(FD_ISSET(cmdfd, &rfd)) {
1674                         ttyread();
1675                         draw(SCREEN_UPDATE); 
1676                 }
1677                 while(XPending(xw.dis)) {
1678                         XNextEvent(xw.dis, &ev);
1679                         if (XFilterEvent(&ev, xw.win))
1680                                 continue;
1681                         if(handler[ev.type])
1682                                 (handler[ev.type])(&ev);
1683                 }
1684         }
1685 }
1686
1687 int
1688 main(int argc, char *argv[]) {
1689         int i;
1690         
1691         for(i = 1; i < argc; i++) {
1692                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1693                 case 't':
1694                         if(++i < argc) opt_title = argv[i];
1695                         break;
1696                 case 'e':
1697                         if(++i < argc) opt_cmd = argv[i];
1698                         break;
1699                 case 'v':
1700                 default:
1701                         die(USAGE);
1702                 }
1703         }
1704         setlocale(LC_CTYPE, "");
1705         tnew(80, 24);
1706         ttynew();
1707         xinit();
1708         selinit();
1709         run();
1710         return 0;
1711 }