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