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