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