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