JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
33a1501403e6d83fe11d0ccaa773e9b363f01c76
[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 <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
30 #define Glyph Glyph_
31 #define Font Font_
32
33 #if   defined(__linux)
34  #include <pty.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36  #include <util.h>
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
38  #include <libutil.h>
39 #endif
40
41 #define USAGE \
42         "st " VERSION " (c) 2010-2012 st engineers\n" \
43         "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44         " [-t title] [-w windowid] [-e command ...]\n"
45
46 /* XEMBED messages */
47 #define XEMBED_FOCUS_IN  4
48 #define XEMBED_FOCUS_OUT 5
49
50 /* Arbitrary sizes */
51 #define ESC_BUF_SIZ   256
52 #define ESC_ARG_SIZ   16
53 #define STR_BUF_SIZ   256
54 #define STR_ARG_SIZ   16
55 #define DRAW_BUF_SIZ  20*1024
56 #define UTF_SIZ       4
57 #define XK_NO_MOD     UINT_MAX
58 #define XK_ANY_MOD    0
59
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61
62 #define SERRNO strerror(errno)
63 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
64 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
65 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74
75 #define VT102ID "\033[?6c"
76
77 enum glyph_attribute {
78         ATTR_NULL      = 0,
79         ATTR_REVERSE   = 1,
80         ATTR_UNDERLINE = 2,
81         ATTR_BOLD      = 4,
82         ATTR_GFX       = 8,
83         ATTR_ITALIC    = 16,
84         ATTR_BLINK     = 32,
85 };
86
87 enum cursor_movement {
88         CURSOR_UP,
89         CURSOR_DOWN,
90         CURSOR_LEFT,
91         CURSOR_RIGHT,
92         CURSOR_SAVE,
93         CURSOR_LOAD
94 };
95
96 enum cursor_state {
97         CURSOR_DEFAULT  = 0,
98         CURSOR_HIDE     = 1,
99         CURSOR_WRAPNEXT = 2
100 };
101
102 enum glyph_state {
103         GLYPH_SET   = 1,
104         GLYPH_DIRTY = 2
105 };
106
107 enum term_mode {
108         MODE_WRAP       = 1,
109         MODE_INSERT      = 2,
110         MODE_APPKEYPAD   = 4,
111         MODE_ALTSCREEN   = 8,
112         MODE_CRLF       = 16,
113         MODE_MOUSEBTN    = 32,
114         MODE_MOUSEMOTION = 64,
115         MODE_MOUSE       = 32|64,
116         MODE_REVERSE     = 128,
117         MODE_KBDLOCK     = 256
118 };
119
120 enum escape_state {
121         ESC_START      = 1,
122         ESC_CSI = 2,
123         ESC_STR = 4, /* DSC, OSC, PM, APC */
124         ESC_ALTCHARSET = 8,
125         ESC_STR_END    = 16, /* a final string was encountered */
126 };
127
128 enum window_state {
129         WIN_VISIBLE = 1,
130         WIN_REDRAW  = 2,
131         WIN_FOCUSED = 4
132 };
133
134 /* bit macro */
135 #undef B0
136 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
137
138 typedef unsigned char uchar;
139 typedef unsigned int uint;
140 typedef unsigned long ulong;
141 typedef unsigned short ushort;
142
143 typedef struct {
144         char c[UTF_SIZ];     /* character code */
145         uchar mode;  /* attribute flags */
146         ushort fg;   /* foreground  */
147         ushort bg;   /* background  */
148         uchar state; /* state flags    */
149 } Glyph;
150
151 typedef Glyph* Line;
152
153 typedef struct {
154         Glyph attr;      /* current char attributes */
155         int x;
156         int y;
157         char state;
158 } TCursor;
159
160 /* CSI Escape sequence structs */
161 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
162 typedef struct {
163         char buf[ESC_BUF_SIZ]; /* raw string */
164         int len;               /* raw string length */
165         char priv;
166         int arg[ESC_ARG_SIZ];
167         int narg;             /* nb of args */
168         char mode;
169 } CSIEscape;
170
171 /* STR Escape sequence structs */
172 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
173 typedef struct {
174         char type;           /* ESC type ... */
175         char buf[STR_BUF_SIZ]; /* raw string */
176         int len;               /* raw string length */
177         char *args[STR_ARG_SIZ];
178         int narg;             /* nb of args */
179 } STREscape;
180
181 /* Internal representation of the screen */
182 typedef struct {
183         int row;        /* nb row */
184         int col;        /* nb col */
185         Line *line;     /* screen */
186         Line *alt;      /* alternate screen */
187         bool *dirty;    /* dirtyness of lines */
188         TCursor c;      /* cursor */
189         int top;        /* top    scroll limit */
190         int bot;        /* bottom scroll limit */
191         int mode;       /* terminal mode flags */
192         int esc;        /* escape state flags */
193         bool *tabs;
194 } Term;
195
196 /* Purely graphic info */
197 typedef struct {
198         Display* dpy;
199         Colormap cmap;
200         Window win;
201         XdbeBackBuffer buf;
202         Atom xembed, wmdeletewin;
203         XIM xim;
204         XIC xic;
205         XftDraw *xft_draw;
206         Visual *vis;
207         int scr;
208         bool isfixed; /* is fixed geometry? */
209         int fx, fy, fw, fh; /* fixed geometry */
210         int tw, th; /* tty width and height */
211         int w;  /* window width */
212         int h;  /* window height */
213         int ch; /* char height */
214         int cw; /* char width  */
215         char state; /* focus, redraw, visible */
216 } XWindow;
217
218 typedef struct {
219         KeySym k;
220         uint mask;
221         char s[ESC_BUF_SIZ];
222 } Key;
223
224 /* TODO: use better name for vars... */
225 typedef struct {
226         int mode;
227         int bx, by;
228         int ex, ey;
229         struct {
230                 int x, y;
231         } b, e;
232         char *clip;
233         Atom xtarget;
234         bool alt;
235         struct timeval tclick1;
236         struct timeval tclick2;
237 } Selection;
238
239 #include "config.h"
240
241 /* Font structure */
242 typedef struct {
243         int height;
244         int width;
245         int ascent;
246         int descent;
247         short lbearing;
248         short rbearing;
249         XftFont *xft_set;
250 } Font;
251
252 /* Drawing Context */
253 typedef struct {
254         XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
255         GC gc;
256         Font font, bfont, ifont, ibfont;
257 } DC;
258
259 static void die(const char *, ...);
260 static void draw(void);
261 static void redraw(void);
262 static void drawregion(int, int, int, int);
263 static void execsh(void);
264 static void sigchld(int);
265 static void run(void);
266
267 static void csidump(void);
268 static void csihandle(void);
269 static void csiparse(void);
270 static void csireset(void);
271 static void strdump(void);
272 static void strhandle(void);
273 static void strparse(void);
274 static void strreset(void);
275
276 static void tclearregion(int, int, int, int);
277 static void tcursor(int);
278 static void tdeletechar(int);
279 static void tdeleteline(int);
280 static void tinsertblank(int);
281 static void tinsertblankline(int);
282 static void tmoveto(int, int);
283 static void tnew(int, int);
284 static void tnewline(int);
285 static void tputtab(bool);
286 static void tputc(char *, int);
287 static void treset(void);
288 static int tresize(int, int);
289 static void tscrollup(int, int);
290 static void tscrolldown(int, int);
291 static void tsetattr(int*, int);
292 static void tsetchar(char*);
293 static void tsetscroll(int, int);
294 static void tswapscreen(void);
295 static void tsetdirt(int, int);
296 static void tsetmode(bool, bool, int *, int);
297 static void tfulldirt(void);
298
299 static void ttynew(void);
300 static void ttyread(void);
301 static void ttyresize(void);
302 static void ttywrite(const char *, size_t);
303
304 static void xdraws(char *, Glyph, int, int, int, int);
305 static void xhints(void);
306 static void xclear(int, int, int, int);
307 static void xdrawcursor(void);
308 static void xinit(void);
309 static void xloadcols(void);
310 static void xresettitle(void);
311 static void xseturgency(int);
312 static void xsetsel(char*);
313 static void xtermclear(int, int, int, int);
314 static void xresize(int, int);
315
316 static void expose(XEvent *);
317 static void visibility(XEvent *);
318 static void unmap(XEvent *);
319 static char *kmap(KeySym, uint);
320 static void kpress(XEvent *);
321 static void cmessage(XEvent *);
322 static void resize(XEvent *);
323 static void focus(XEvent *);
324 static void brelease(XEvent *);
325 static void bpress(XEvent *);
326 static void bmotion(XEvent *);
327 static void selnotify(XEvent *);
328 static void selclear(XEvent *);
329 static void selrequest(XEvent *);
330
331 static void selinit(void);
332 static inline bool selected(int, int);
333 static void selcopy(void);
334 static void selpaste(void);
335 static void selscroll(int, int);
336
337 static int utf8decode(char *, long *);
338 static int utf8encode(long *, char *);
339 static int utf8size(char *);
340 static int isfullutf8(char *, int);
341
342 static void *xmalloc(size_t);
343 static void *xrealloc(void *, size_t);
344 static void *xcalloc(size_t nmemb, size_t size);
345 static char *smstrcat(char *, ...);
346
347 static void (*handler[LASTEvent])(XEvent *) = {
348         [KeyPress] = kpress,
349         [ClientMessage] = cmessage,
350         [ConfigureNotify] = resize,
351         [VisibilityNotify] = visibility,
352         [UnmapNotify] = unmap,
353         [Expose] = expose,
354         [FocusIn] = focus,
355         [FocusOut] = focus,
356         [MotionNotify] = bmotion,
357         [ButtonPress] = bpress,
358         [ButtonRelease] = brelease,
359         [SelectionClear] = selclear,
360         [SelectionNotify] = selnotify,
361         [SelectionRequest] = selrequest,
362 };
363
364 /* Globals */
365 static DC dc;
366 static XWindow xw;
367 static Term term;
368 static CSIEscape csiescseq;
369 static STREscape strescseq;
370 static int cmdfd;
371 static pid_t pid;
372 static Selection sel;
373 static int iofd = -1;
374 static char **opt_cmd = NULL;
375 static char *opt_io = NULL;
376 static char *opt_title = NULL;
377 static char *opt_embed = NULL;
378 static char *opt_class = NULL;
379 static char *opt_font = NULL;
380
381 void *
382 xmalloc(size_t len) {
383         void *p = malloc(len);
384
385         if(!p)
386                 die("Out of memory\n");
387
388         return p;
389 }
390
391 void *
392 xrealloc(void *p, size_t len) {
393         if((p = realloc(p, len)) == NULL)
394                 die("Out of memory\n");
395
396         return p;
397 }
398
399 void *
400 xcalloc(size_t nmemb, size_t size) {
401         void *p = calloc(nmemb, size);
402
403         if(!p)
404                 die("Out of memory\n");
405
406         return p;
407 }
408
409 char *
410 smstrcat(char *src, ...)
411 {
412         va_list fmtargs;
413         char *ret, *p, *v;
414         int len, slen, flen;
415
416         len = slen = strlen(src);
417
418         va_start(fmtargs, src);
419         for(;;) {
420                 v = va_arg(fmtargs, char *);
421                 if(v == NULL)
422                         break;
423                 len += strlen(v);
424         }
425         va_end(fmtargs);
426
427         p = ret = xmalloc(len+1);
428         memmove(p, src, slen);
429         p += slen;
430
431         va_start(fmtargs, src);
432         for(;;) {
433                 v = va_arg(fmtargs, char *);
434                 if(v == NULL)
435                         break;
436                 flen = strlen(v);
437                 memmove(p, v, flen);
438                 p += flen;
439         }
440         va_end(fmtargs);
441
442         ret[len] = '\0';
443
444         return ret;
445 }
446
447 int
448 utf8decode(char *s, long *u) {
449         uchar c;
450         int i, n, rtn;
451
452         rtn = 1;
453         c = *s;
454         if(~c & B7) { /* 0xxxxxxx */
455                 *u = c;
456                 return rtn;
457         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
458                 *u = c&(B4|B3|B2|B1|B0);
459                 n = 1;
460         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
461                 *u = c&(B3|B2|B1|B0);
462                 n = 2;
463         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
464                 *u = c & (B2|B1|B0);
465                 n = 3;
466         } else {
467                 goto invalid;
468         }
469
470         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
471                 c = *s;
472                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
473                         goto invalid;
474                 *u <<= 6;
475                 *u |= c & (B5|B4|B3|B2|B1|B0);
476         }
477
478         if((n == 1 && *u < 0x80) ||
479            (n == 2 && *u < 0x800) ||
480            (n == 3 && *u < 0x10000) ||
481            (*u >= 0xD800 && *u <= 0xDFFF)) {
482                 goto invalid;
483         }
484
485         return rtn;
486 invalid:
487         *u = 0xFFFD;
488
489         return rtn;
490 }
491
492 int
493 utf8encode(long *u, char *s) {
494         uchar *sp;
495         ulong uc;
496         int i, n;
497
498         sp = (uchar *)s;
499         uc = *u;
500         if(uc < 0x80) {
501                 *sp = uc; /* 0xxxxxxx */
502                 return 1;
503         } else if(*u < 0x800) {
504                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
505                 n = 1;
506         } else if(uc < 0x10000) {
507                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
508                 n = 2;
509         } else if(uc <= 0x10FFFF) {
510                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
511                 n = 3;
512         } else {
513                 goto invalid;
514         }
515
516         for(i=n,++sp; i>0; --i,++sp)
517                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
518
519         return n+1;
520 invalid:
521         /* U+FFFD */
522         *s++ = '\xEF';
523         *s++ = '\xBF';
524         *s = '\xBD';
525
526         return 3;
527 }
528
529 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
530    UTF-8 otherwise return 0 */
531 int
532 isfullutf8(char *s, int b) {
533         uchar *c1, *c2, *c3;
534
535         c1 = (uchar *)s;
536         c2 = (uchar *)++s;
537         c3 = (uchar *)++s;
538         if(b < 1) {
539                 return 0;
540         } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
541                 return 0;
542         } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
543             ((b == 1) ||
544             ((b == 2) && (*c2&(B7|B6)) == B7))) {
545                 return 0;
546         } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
547             ((b == 1) ||
548             ((b == 2) && (*c2&(B7|B6)) == B7) ||
549             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
550                 return 0;
551         } else {
552                 return 1;
553         }
554 }
555
556 int
557 utf8size(char *s) {
558         uchar c = *s;
559
560         if(~c&B7) {
561                 return 1;
562         } else if((c&(B7|B6|B5)) == (B7|B6)) {
563                 return 2;
564         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
565                 return 3;
566         } else {
567                 return 4;
568         }
569 }
570
571 void
572 selinit(void) {
573         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
574         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
575         sel.mode = 0;
576         sel.bx = -1;
577         sel.clip = NULL;
578         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
579         if(sel.xtarget == None)
580                 sel.xtarget = XA_STRING;
581 }
582
583 static inline bool
584 selected(int x, int y) {
585         int bx, ex;
586
587         if(sel.ey == y && sel.by == y) {
588                 bx = MIN(sel.bx, sel.ex);
589                 ex = MAX(sel.bx, sel.ex);
590                 return BETWEEN(x, bx, ex);
591         }
592
593         return ((sel.b.y < y && y < sel.e.y)
594                         || (y == sel.e.y && x <= sel.e.x))
595                         || (y == sel.b.y && x >= sel.b.x
596                                 && (x <= sel.e.x || sel.b.y != sel.e.y));
597 }
598
599 void
600 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
601         if(b)
602                 *b = e->xbutton.button;
603
604         *x = X2COL(e->xbutton.x);
605         *y = Y2ROW(e->xbutton.y);
606         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
607         sel.b.y = MIN(sel.by, sel.ey);
608         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
609         sel.e.y = MAX(sel.by, sel.ey);
610 }
611
612 void
613 mousereport(XEvent *e) {
614         int x = X2COL(e->xbutton.x);
615         int y = Y2ROW(e->xbutton.y);
616         int button = e->xbutton.button;
617         int state = e->xbutton.state;
618         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
619         static int ob, ox, oy;
620
621         /* from urxvt */
622         if(e->xbutton.type == MotionNotify) {
623                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
624                         return;
625                 button = ob + 32;
626                 ox = x, oy = y;
627         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
628                 button = 3;
629         } else {
630                 button -= Button1;
631                 if(button >= 3)
632                         button += 64 - 3;
633                 if(e->xbutton.type == ButtonPress) {
634                         ob = button;
635                         ox = x, oy = y;
636                 }
637         }
638
639         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
640                 + (state & Mod4Mask    ? 8  : 0)
641                 + (state & ControlMask ? 16 : 0);
642
643         ttywrite(buf, sizeof(buf));
644 }
645
646 void
647 bpress(XEvent *e) {
648         if(IS_SET(MODE_MOUSE)) {
649                 mousereport(e);
650         } else if(e->xbutton.button == Button1) {
651                 if(sel.bx != -1) {
652                         sel.bx = -1;
653                         tsetdirt(sel.b.y, sel.e.y);
654                         draw();
655                 }
656                 sel.mode = 1;
657                 sel.ex = sel.bx = X2COL(e->xbutton.x);
658                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
659         }
660 }
661
662 void
663 selcopy(void) {
664         char *str, *ptr, *p;
665         int x, y, bufsize, is_selected = 0, size;
666         Glyph *gp;
667
668         if(sel.bx == -1) {
669                 str = NULL;
670         } else {
671                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
672                 ptr = str = xmalloc(bufsize);
673
674                 /* append every set & selected glyph to the selection */
675                 for(y = 0; y < term.row; y++) {
676                         for(x = 0; x < term.col; x++) {
677                                 gp = &term.line[y][x];
678
679                                 if(!(is_selected = selected(x, y)))
680                                         continue;
681                                 p = (gp->state & GLYPH_SET) ? gp->c : " ";
682                                 size = utf8size(p);
683                                 memcpy(ptr, p, size);
684                                 ptr += size;
685                         }
686                         /* \n at the end of every selected line except for the last one */
687                         if(is_selected && y < sel.e.y)
688                                 *ptr++ = '\n';
689                 }
690                 *ptr = 0;
691         }
692         sel.alt = IS_SET(MODE_ALTSCREEN);
693         xsetsel(str);
694 }
695
696 void
697 selnotify(XEvent *e) {
698         ulong nitems, ofs, rem;
699         int format;
700         uchar *data;
701         Atom type;
702
703         ofs = 0;
704         do {
705                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
706                                         False, AnyPropertyType, &type, &format,
707                                         &nitems, &rem, &data)) {
708                         fprintf(stderr, "Clipboard allocation failed\n");
709                         return;
710                 }
711                 ttywrite((const char *) data, nitems * format / 8);
712                 XFree(data);
713                 /* number of 32-bit chunks returned */
714                 ofs += nitems * format / 32;
715         } while(rem > 0);
716 }
717
718 void
719 selpaste(void) {
720         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
721                         xw.win, CurrentTime);
722 }
723
724 void selclear(XEvent *e) {
725         if(sel.bx == -1)
726                 return;
727         sel.bx = -1;
728         tsetdirt(sel.b.y, sel.e.y);
729 }
730
731 void
732 selrequest(XEvent *e) {
733         XSelectionRequestEvent *xsre;
734         XSelectionEvent xev;
735         Atom xa_targets, string;
736
737         xsre = (XSelectionRequestEvent *) e;
738         xev.type = SelectionNotify;
739         xev.requestor = xsre->requestor;
740         xev.selection = xsre->selection;
741         xev.target = xsre->target;
742         xev.time = xsre->time;
743         /* reject */
744         xev.property = None;
745
746         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
747         if(xsre->target == xa_targets) {
748                 /* respond with the supported type */
749                 string = sel.xtarget;
750                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
751                                 XA_ATOM, 32, PropModeReplace,
752                                 (uchar *) &string, 1);
753                 xev.property = xsre->property;
754         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
755                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
756                                 xsre->target, 8, PropModeReplace,
757                                 (uchar *) sel.clip, strlen(sel.clip));
758                 xev.property = xsre->property;
759         }
760
761         /* all done, send a notification to the listener */
762         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
763                 fprintf(stderr, "Error sending SelectionNotify event\n");
764 }
765
766 void
767 xsetsel(char *str) {
768         /* register the selection for both the clipboard and the primary */
769         Atom clipboard;
770
771         free(sel.clip);
772         sel.clip = str;
773
774         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
775
776         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
777         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
778 }
779
780 void
781 brelease(XEvent *e) {
782         struct timeval now;
783
784         if(IS_SET(MODE_MOUSE)) {
785                 mousereport(e);
786                 return;
787         }
788
789         if(e->xbutton.button == Button2) {
790                 selpaste();
791         } else if(e->xbutton.button == Button1) {
792                 sel.mode = 0;
793                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
794                 term.dirty[sel.ey] = 1;
795                 if(sel.bx == sel.ex && sel.by == sel.ey) {
796                         sel.bx = -1;
797                         gettimeofday(&now, NULL);
798
799                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
800                                 /* triple click on the line */
801                                 sel.b.x = sel.bx = 0;
802                                 sel.e.x = sel.ex = term.col;
803                                 sel.b.y = sel.e.y = sel.ey;
804                                 selcopy();
805                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
806                                 /* double click to select word */
807                                 sel.bx = sel.ex;
808                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
809                                                 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
810                                         sel.bx--;
811                                 }
812                                 sel.b.x = sel.bx;
813                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
814                                                 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
815                                         sel.ex++;
816                                 }
817                                 sel.e.x = sel.ex;
818                                 sel.b.y = sel.e.y = sel.ey;
819                                 selcopy();
820                         }
821                 } else {
822                         selcopy();
823                 }
824         }
825
826         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
827         gettimeofday(&sel.tclick1, NULL);
828 }
829
830 void
831 bmotion(XEvent *e) {
832         int starty, endy, oldey, oldex;
833
834         if(IS_SET(MODE_MOUSE)) {
835                 mousereport(e);
836                 return;
837         }
838
839         if(sel.mode) {
840                 oldey = sel.ey;
841                 oldex = sel.ex;
842                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
843
844                 if(oldey != sel.ey || oldex != sel.ex) {
845                         starty = MIN(oldey, sel.ey);
846                         endy = MAX(oldey, sel.ey);
847                         tsetdirt(starty, endy);
848                 }
849         }
850 }
851
852 void
853 die(const char *errstr, ...) {
854         va_list ap;
855
856         va_start(ap, errstr);
857         vfprintf(stderr, errstr, ap);
858         va_end(ap);
859         exit(EXIT_FAILURE);
860 }
861
862 void
863 execsh(void) {
864         char **args;
865         char *envshell = getenv("SHELL");
866
867         unsetenv("COLUMNS");
868         unsetenv("LINES");
869         unsetenv("TERMCAP");
870
871         signal(SIGCHLD, SIG_DFL);
872         signal(SIGHUP, SIG_DFL);
873         signal(SIGINT, SIG_DFL);
874         signal(SIGQUIT, SIG_DFL);
875         signal(SIGTERM, SIG_DFL);
876         signal(SIGALRM, SIG_DFL);
877
878         DEFAULT(envshell, SHELL);
879         putenv("TERM="TNAME);
880         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
881         execvp(args[0], args);
882         exit(EXIT_FAILURE);
883 }
884
885 void
886 sigchld(int a) {
887         int stat = 0;
888
889         if(waitpid(pid, &stat, 0) < 0)
890                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
891
892         if(WIFEXITED(stat)) {
893                 exit(WEXITSTATUS(stat));
894         } else {
895                 exit(EXIT_FAILURE);
896         }
897 }
898
899 void
900 ttynew(void) {
901         int m, s;
902         struct winsize w = {term.row, term.col, 0, 0};
903
904         /* seems to work fine on linux, openbsd and freebsd */
905         if(openpty(&m, &s, NULL, NULL, &w) < 0)
906                 die("openpty failed: %s\n", SERRNO);
907
908         switch(pid = fork()) {
909         case -1:
910                 die("fork failed\n");
911                 break;
912         case 0:
913                 setsid(); /* create a new process group */
914                 dup2(s, STDIN_FILENO);
915                 dup2(s, STDOUT_FILENO);
916                 dup2(s, STDERR_FILENO);
917                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
918                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
919                 close(s);
920                 close(m);
921                 execsh();
922                 break;
923         default:
924                 close(s);
925                 cmdfd = m;
926                 signal(SIGCHLD, sigchld);
927                 if(opt_io) {
928                         if(!strcmp(opt_io, "-")) {
929                                 iofd = STDOUT_FILENO;
930                         } else {
931                                 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
932                                         fprintf(stderr, "Error opening %s:%s\n",
933                                                 opt_io, strerror(errno));
934                                 }
935                         }
936                 }
937         }
938 }
939
940 void
941 dump(char c) {
942         static int col;
943
944         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
945         if(++col % 10 == 0)
946                 fprintf(stderr, "\n");
947 }
948
949 void
950 ttyread(void) {
951         static char buf[BUFSIZ];
952         static int buflen = 0;
953         char *ptr;
954         char s[UTF_SIZ];
955         int charsize; /* size of utf8 char in bytes */
956         long utf8c;
957         int ret;
958
959         /* append read bytes to unprocessed bytes */
960         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
961                 die("Couldn't read from shell: %s\n", SERRNO);
962
963         /* process every complete utf8 char */
964         buflen += ret;
965         ptr = buf;
966         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
967                 charsize = utf8decode(ptr, &utf8c);
968                 utf8encode(&utf8c, s);
969                 tputc(s, charsize);
970                 ptr += charsize;
971                 buflen -= charsize;
972         }
973
974         /* keep any uncomplete utf8 char for the next call */
975         memmove(buf, ptr, buflen);
976 }
977
978 void
979 ttywrite(const char *s, size_t n) {
980         if(write(cmdfd, s, n) == -1)
981                 die("write error on tty: %s\n", SERRNO);
982 }
983
984 void
985 ttyresize(void) {
986         struct winsize w;
987
988         w.ws_row = term.row;
989         w.ws_col = term.col;
990         w.ws_xpixel = xw.tw;
991         w.ws_ypixel = xw.th;
992         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
993                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
994 }
995
996 void
997 tsetdirt(int top, int bot) {
998         int i;
999
1000         LIMIT(top, 0, term.row-1);
1001         LIMIT(bot, 0, term.row-1);
1002
1003         for(i = top; i <= bot; i++)
1004                 term.dirty[i] = 1;
1005 }
1006
1007 void
1008 tfulldirt(void) {
1009         tsetdirt(0, term.row-1);
1010 }
1011
1012 void
1013 tcursor(int mode) {
1014         static TCursor c;
1015
1016         if(mode == CURSOR_SAVE) {
1017                 c = term.c;
1018         } else if(mode == CURSOR_LOAD) {
1019                 term.c = c;
1020                 tmoveto(c.x, c.y);
1021         }
1022 }
1023
1024 void
1025 treset(void) {
1026         uint i;
1027
1028         term.c = (TCursor){{
1029                 .mode = ATTR_NULL,
1030                 .fg = DefaultFG,
1031                 .bg = DefaultBG
1032         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1033
1034         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1035         for(i = TAB; i < term.col; i += TAB)
1036                 term.tabs[i] = 1;
1037         term.top = 0;
1038         term.bot = term.row - 1;
1039         term.mode = MODE_WRAP;
1040
1041         tclearregion(0, 0, term.col-1, term.row-1);
1042 }
1043
1044 void
1045 tnew(int col, int row) {
1046         /* set screen size */
1047         term.row = row;
1048         term.col = col;
1049         term.line = xmalloc(term.row * sizeof(Line));
1050         term.alt  = xmalloc(term.row * sizeof(Line));
1051         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1052         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1053
1054         for(row = 0; row < term.row; row++) {
1055                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1056                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1057                 term.dirty[row] = 0;
1058         }
1059         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1060         /* setup screen */
1061         treset();
1062 }
1063
1064 void
1065 tswapscreen(void) {
1066         Line *tmp = term.line;
1067
1068         term.line = term.alt;
1069         term.alt = tmp;
1070         term.mode ^= MODE_ALTSCREEN;
1071         tfulldirt();
1072 }
1073
1074 void
1075 tscrolldown(int orig, int n) {
1076         int i;
1077         Line temp;
1078
1079         LIMIT(n, 0, term.bot-orig+1);
1080
1081         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1082
1083         for(i = term.bot; i >= orig+n; i--) {
1084                 temp = term.line[i];
1085                 term.line[i] = term.line[i-n];
1086                 term.line[i-n] = temp;
1087
1088                 term.dirty[i] = 1;
1089                 term.dirty[i-n] = 1;
1090         }
1091
1092         selscroll(orig, n);
1093 }
1094
1095 void
1096 tscrollup(int orig, int n) {
1097         int i;
1098         Line temp;
1099         LIMIT(n, 0, term.bot-orig+1);
1100
1101         tclearregion(0, orig, term.col-1, orig+n-1);
1102
1103         for(i = orig; i <= term.bot-n; i++) {
1104                  temp = term.line[i];
1105                  term.line[i] = term.line[i+n];
1106                  term.line[i+n] = temp;
1107
1108                  term.dirty[i] = 1;
1109                  term.dirty[i+n] = 1;
1110         }
1111
1112         selscroll(orig, -n);
1113 }
1114
1115 void
1116 selscroll(int orig, int n) {
1117         if(sel.bx == -1)
1118                 return;
1119
1120         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1121                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1122                         sel.bx = -1;
1123                         return;
1124                 }
1125                 if(sel.by < term.top) {
1126                         sel.by = term.top;
1127                         sel.bx = 0;
1128                 }
1129                 if(sel.ey > term.bot) {
1130                         sel.ey = term.bot;
1131                         sel.ex = term.col;
1132                 }
1133                 sel.b.y = sel.by, sel.b.x = sel.bx;
1134                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1135         }
1136 }
1137
1138 void
1139 tnewline(int first_col) {
1140         int y = term.c.y;
1141
1142         if(y == term.bot) {
1143                 tscrollup(term.top, 1);
1144         } else {
1145                 y++;
1146         }
1147         tmoveto(first_col ? 0 : term.c.x, y);
1148 }
1149
1150 void
1151 csiparse(void) {
1152         /* int noarg = 1; */
1153         char *p = csiescseq.buf;
1154
1155         csiescseq.narg = 0;
1156         if(*p == '?')
1157                 csiescseq.priv = 1, p++;
1158
1159         while(p < csiescseq.buf+csiescseq.len) {
1160                 while(isdigit(*p)) {
1161                         csiescseq.arg[csiescseq.narg] *= 10;
1162                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1163                 }
1164                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1165                         csiescseq.narg++, p++;
1166                 } else {
1167                         csiescseq.mode = *p;
1168                         csiescseq.narg++;
1169
1170                         return;
1171                 }
1172         }
1173 }
1174
1175 void
1176 tmoveto(int x, int y) {
1177         LIMIT(x, 0, term.col-1);
1178         LIMIT(y, 0, term.row-1);
1179         term.c.state &= ~CURSOR_WRAPNEXT;
1180         term.c.x = x;
1181         term.c.y = y;
1182 }
1183
1184 void
1185 tsetchar(char *c) {
1186         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1187                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1188                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1189                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1190                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1191                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1192                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1193                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1194                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1195         };
1196
1197         /*
1198          * The table is proudly stolen from rxvt.
1199          */
1200         if(term.c.attr.mode & ATTR_GFX) {
1201                 if(c[0] >= 0x41 && c[0] <= 0x7e
1202                                 && vt100_0[c[0] - 0x41]) {
1203                         c = vt100_0[c[0] - 0x41];
1204                 }
1205         }
1206
1207         term.dirty[term.c.y] = 1;
1208         term.line[term.c.y][term.c.x] = term.c.attr;
1209         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1210         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1211 }
1212
1213 void
1214 tclearregion(int x1, int y1, int x2, int y2) {
1215         int x, y, temp;
1216
1217         if(x1 > x2)
1218                 temp = x1, x1 = x2, x2 = temp;
1219         if(y1 > y2)
1220                 temp = y1, y1 = y2, y2 = temp;
1221
1222         LIMIT(x1, 0, term.col-1);
1223         LIMIT(x2, 0, term.col-1);
1224         LIMIT(y1, 0, term.row-1);
1225         LIMIT(y2, 0, term.row-1);
1226
1227         for(y = y1; y <= y2; y++) {
1228                 term.dirty[y] = 1;
1229                 for(x = x1; x <= x2; x++)
1230                         term.line[y][x].state = 0;
1231         }
1232 }
1233
1234 void
1235 tdeletechar(int n) {
1236         int src = term.c.x + n;
1237         int dst = term.c.x;
1238         int size = term.col - src;
1239
1240         term.dirty[term.c.y] = 1;
1241
1242         if(src >= term.col) {
1243                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1244                 return;
1245         }
1246
1247         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1248                         size * sizeof(Glyph));
1249         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1250 }
1251
1252 void
1253 tinsertblank(int n) {
1254         int src = term.c.x;
1255         int dst = src + n;
1256         int size = term.col - dst;
1257
1258         term.dirty[term.c.y] = 1;
1259
1260         if(dst >= term.col) {
1261                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1262                 return;
1263         }
1264
1265         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1266                         size * sizeof(Glyph));
1267         tclearregion(src, term.c.y, dst - 1, term.c.y);
1268 }
1269
1270 void
1271 tinsertblankline(int n) {
1272         if(term.c.y < term.top || term.c.y > term.bot)
1273                 return;
1274
1275         tscrolldown(term.c.y, n);
1276 }
1277
1278 void
1279 tdeleteline(int n) {
1280         if(term.c.y < term.top || term.c.y > term.bot)
1281                 return;
1282
1283         tscrollup(term.c.y, n);
1284 }
1285
1286 void
1287 tsetattr(int *attr, int l) {
1288         int i;
1289
1290         for(i = 0; i < l; i++) {
1291                 switch(attr[i]) {
1292                 case 0:
1293                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1294                                         | ATTR_ITALIC | ATTR_BLINK);
1295                         term.c.attr.fg = DefaultFG;
1296                         term.c.attr.bg = DefaultBG;
1297                         break;
1298                 case 1:
1299                         term.c.attr.mode |= ATTR_BOLD;
1300                         break;
1301                 case 3: /* enter standout (highlight) */
1302                         term.c.attr.mode |= ATTR_ITALIC;
1303                         break;
1304                 case 4:
1305                         term.c.attr.mode |= ATTR_UNDERLINE;
1306                         break;
1307                 case 5:
1308                         term.c.attr.mode |= ATTR_BLINK;
1309                         break;
1310                 case 7:
1311                         term.c.attr.mode |= ATTR_REVERSE;
1312                         break;
1313                 case 21:
1314                 case 22:
1315                         term.c.attr.mode &= ~ATTR_BOLD;
1316                         break;
1317                 case 23: /* leave standout (highlight) mode */
1318                         term.c.attr.mode &= ~ATTR_ITALIC;
1319                         break;
1320                 case 24:
1321                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1322                         break;
1323                 case 25:
1324                         term.c.attr.mode &= ~ATTR_BLINK;
1325                         break;
1326                 case 27:
1327                         term.c.attr.mode &= ~ATTR_REVERSE;
1328                         break;
1329                 case 38:
1330                         if(i + 2 < l && attr[i + 1] == 5) {
1331                                 i += 2;
1332                                 if(BETWEEN(attr[i], 0, 255)) {
1333                                         term.c.attr.fg = attr[i];
1334                                 } else {
1335                                         fprintf(stderr,
1336                                                 "erresc: bad fgcolor %d\n",
1337                                                 attr[i]);
1338                                 }
1339                         } else {
1340                                 fprintf(stderr,
1341                                         "erresc(38): gfx attr %d unknown\n",
1342                                         attr[i]);
1343                         }
1344                         break;
1345                 case 39:
1346                         term.c.attr.fg = DefaultFG;
1347                         break;
1348                 case 48:
1349                         if(i + 2 < l && attr[i + 1] == 5) {
1350                                 i += 2;
1351                                 if(BETWEEN(attr[i], 0, 255)) {
1352                                         term.c.attr.bg = attr[i];
1353                                 } else {
1354                                         fprintf(stderr,
1355                                                 "erresc: bad bgcolor %d\n",
1356                                                 attr[i]);
1357                                 }
1358                         } else {
1359                                 fprintf(stderr,
1360                                         "erresc(48): gfx attr %d unknown\n",
1361                                         attr[i]);
1362                         }
1363                         break;
1364                 case 49:
1365                         term.c.attr.bg = DefaultBG;
1366                         break;
1367                 default:
1368                         if(BETWEEN(attr[i], 30, 37)) {
1369                                 term.c.attr.fg = attr[i] - 30;
1370                         } else if(BETWEEN(attr[i], 40, 47)) {
1371                                 term.c.attr.bg = attr[i] - 40;
1372                         } else if(BETWEEN(attr[i], 90, 97)) {
1373                                 term.c.attr.fg = attr[i] - 90 + 8;
1374                         } else if(BETWEEN(attr[i], 100, 107)) {
1375                                 term.c.attr.bg = attr[i] - 100 + 8;
1376                         } else {
1377                                 fprintf(stderr,
1378                                         "erresc(default): gfx attr %d unknown\n",
1379                                         attr[i]), csidump();
1380                         }
1381                         break;
1382                 }
1383         }
1384 }
1385
1386 void
1387 tsetscroll(int t, int b) {
1388         int temp;
1389
1390         LIMIT(t, 0, term.row-1);
1391         LIMIT(b, 0, term.row-1);
1392         if(t > b) {
1393                 temp = t;
1394                 t = b;
1395                 b = temp;
1396         }
1397         term.top = t;
1398         term.bot = b;
1399 }
1400
1401 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1402
1403 void
1404 tsetmode(bool priv, bool set, int *args, int narg) {
1405         int *lim, mode;
1406
1407         for(lim = args + narg; args < lim; ++args) {
1408                 if(priv) {
1409                         switch(*args) {
1410                                 break;
1411                         case 1: /* DECCKM -- Cursor key */
1412                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1413                                 break;
1414                         case 5: /* DECSCNM -- Reverse video */
1415                                 mode = term.mode;
1416                                 MODBIT(term.mode, set, MODE_REVERSE);
1417                                 if(mode != term.mode)
1418                                         redraw();
1419                                 break;
1420                         case 6: /* XXX: DECOM -- Origin */
1421                                 break;
1422                         case 7: /* DECAWM -- Auto wrap */
1423                                 MODBIT(term.mode, set, MODE_WRAP);
1424                                 break;
1425                         case 8: /* XXX: DECARM -- Auto repeat */
1426                                 break;
1427                         case 0:  /* Error (IGNORED) */
1428                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1429                                 break;
1430                         case 25:
1431                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1432                                 break;
1433                         case 1000: /* 1000,1002: enable xterm mouse report */
1434                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1435                                 break;
1436                         case 1002:
1437                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1438                                 break;
1439                         case 1049: /* = 1047 and 1048 */
1440                         case 47:
1441                         case 1047:
1442                                 if(IS_SET(MODE_ALTSCREEN))
1443                                         tclearregion(0, 0, term.col-1, term.row-1);
1444                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1445                                                 (!set && IS_SET(MODE_ALTSCREEN))) {
1446                                         tswapscreen();
1447                                 }
1448                                 if(*args != 1049)
1449                                         break;
1450                                 /* pass through */
1451                         case 1048:
1452                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1453                                 break;
1454                         default:
1455                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1456                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1457                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1458                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1459                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1460                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1461                                 fprintf(stderr,
1462                                         "erresc: unknown private set/reset mode %d\n",
1463                                         *args);
1464                                 break;
1465                         }
1466                 } else {
1467                         switch(*args) {
1468                         case 0:  /* Error (IGNORED) */
1469                                 break;
1470                         case 2:  /* KAM -- keyboard action */
1471                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1472                                 break;
1473                         case 4:  /* IRM -- Insertion-replacement */
1474                                 MODBIT(term.mode, set, MODE_INSERT);
1475                                 break;
1476                         case 12: /* XXX: SRM -- Send/Receive */
1477                                 break;
1478                         case 20: /* LNM -- Linefeed/new line */
1479                                 MODBIT(term.mode, set, MODE_CRLF);
1480                                 break;
1481                         default:
1482                                 fprintf(stderr,
1483                                         "erresc: unknown set/reset mode %d\n",
1484                                         *args);
1485                                 break;
1486                         }
1487                 }
1488         }
1489 }
1490 #undef MODBIT
1491
1492
1493 void
1494 csihandle(void) {
1495         switch(csiescseq.mode) {
1496         default:
1497         unknown:
1498                 fprintf(stderr, "erresc: unknown csi ");
1499                 csidump();
1500                 /* die(""); */
1501                 break;
1502         case '@': /* ICH -- Insert <n> blank char */
1503                 DEFAULT(csiescseq.arg[0], 1);
1504                 tinsertblank(csiescseq.arg[0]);
1505                 break;
1506         case 'A': /* CUU -- Cursor <n> Up */
1507         case 'e':
1508                 DEFAULT(csiescseq.arg[0], 1);
1509                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1510                 break;
1511         case 'B': /* CUD -- Cursor <n> Down */
1512                 DEFAULT(csiescseq.arg[0], 1);
1513                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1514                 break;
1515         case 'c': /* DA -- Device Attributes */
1516                 if(csiescseq.arg[0] == 0)
1517                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1518                 break;
1519         case 'C': /* CUF -- Cursor <n> Forward */
1520         case 'a':
1521                 DEFAULT(csiescseq.arg[0], 1);
1522                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1523                 break;
1524         case 'D': /* CUB -- Cursor <n> Backward */
1525                 DEFAULT(csiescseq.arg[0], 1);
1526                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1527                 break;
1528         case 'E': /* CNL -- Cursor <n> Down and first col */
1529                 DEFAULT(csiescseq.arg[0], 1);
1530                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1531                 break;
1532         case 'F': /* CPL -- Cursor <n> Up and first col */
1533                 DEFAULT(csiescseq.arg[0], 1);
1534                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1535                 break;
1536         case 'g': /* TBC -- Tabulation clear */
1537                 switch (csiescseq.arg[0]) {
1538                 case 0: /* clear current tab stop */
1539                         term.tabs[term.c.x] = 0;
1540                         break;
1541                 case 3: /* clear all the tabs */
1542                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1543                         break;
1544                 default:
1545                         goto unknown;
1546                 }
1547                 break;
1548         case 'G': /* CHA -- Move to <col> */
1549         case '`': /* HPA */
1550                 DEFAULT(csiescseq.arg[0], 1);
1551                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1552                 break;
1553         case 'H': /* CUP -- Move to <row> <col> */
1554         case 'f': /* HVP */
1555                 DEFAULT(csiescseq.arg[0], 1);
1556                 DEFAULT(csiescseq.arg[1], 1);
1557                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1558                 break;
1559         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1560                 DEFAULT(csiescseq.arg[0], 1);
1561                 while(csiescseq.arg[0]--)
1562                         tputtab(1);
1563                 break;
1564         case 'J': /* ED -- Clear screen */
1565                 sel.bx = -1;
1566                 switch(csiescseq.arg[0]) {
1567                 case 0: /* below */
1568                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1569                         if(term.c.y < term.row-1)
1570                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1571                         break;
1572                 case 1: /* above */
1573                         if(term.c.y > 1)
1574                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1575                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1576                         break;
1577                 case 2: /* all */
1578                         tclearregion(0, 0, term.col-1, term.row-1);
1579                         break;
1580                 default:
1581                         goto unknown;
1582                 }
1583                 break;
1584         case 'K': /* EL -- Clear line */
1585                 switch(csiescseq.arg[0]) {
1586                 case 0: /* right */
1587                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1588                         break;
1589                 case 1: /* left */
1590                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1591                         break;
1592                 case 2: /* all */
1593                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1594                         break;
1595                 }
1596                 break;
1597         case 'S': /* SU -- Scroll <n> line up */
1598                 DEFAULT(csiescseq.arg[0], 1);
1599                 tscrollup(term.top, csiescseq.arg[0]);
1600                 break;
1601         case 'T': /* SD -- Scroll <n> line down */
1602                 DEFAULT(csiescseq.arg[0], 1);
1603                 tscrolldown(term.top, csiescseq.arg[0]);
1604                 break;
1605         case 'L': /* IL -- Insert <n> blank lines */
1606                 DEFAULT(csiescseq.arg[0], 1);
1607                 tinsertblankline(csiescseq.arg[0]);
1608                 break;
1609         case 'l': /* RM -- Reset Mode */
1610                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1611                 break;
1612         case 'M': /* DL -- Delete <n> lines */
1613                 DEFAULT(csiescseq.arg[0], 1);
1614                 tdeleteline(csiescseq.arg[0]);
1615                 break;
1616         case 'X': /* ECH -- Erase <n> char */
1617                 DEFAULT(csiescseq.arg[0], 1);
1618                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1619                 break;
1620         case 'P': /* DCH -- Delete <n> char */
1621                 DEFAULT(csiescseq.arg[0], 1);
1622                 tdeletechar(csiescseq.arg[0]);
1623                 break;
1624         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1625                 DEFAULT(csiescseq.arg[0], 1);
1626                 while(csiescseq.arg[0]--)
1627                         tputtab(0);
1628                 break;
1629         case 'd': /* VPA -- Move to <row> */
1630                 DEFAULT(csiescseq.arg[0], 1);
1631                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1632                 break;
1633         case 'h': /* SM -- Set terminal mode */
1634                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1635                 break;
1636         case 'm': /* SGR -- Terminal attribute (color) */
1637                 tsetattr(csiescseq.arg, csiescseq.narg);
1638                 break;
1639         case 'r': /* DECSTBM -- Set Scrolling Region */
1640                 if(csiescseq.priv) {
1641                         goto unknown;
1642                 } else {
1643                         DEFAULT(csiescseq.arg[0], 1);
1644                         DEFAULT(csiescseq.arg[1], term.row);
1645                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1646                         tmoveto(0, 0);
1647                 }
1648                 break;
1649         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1650                 tcursor(CURSOR_SAVE);
1651                 break;
1652         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1653                 tcursor(CURSOR_LOAD);
1654                 break;
1655         }
1656 }
1657
1658 void
1659 csidump(void) {
1660         int i;
1661         uint c;
1662
1663         printf("ESC[");
1664         for(i = 0; i < csiescseq.len; i++) {
1665                 c = csiescseq.buf[i] & 0xff;
1666                 if(isprint(c)) {
1667                         putchar(c);
1668                 } else if(c == '\n') {
1669                         printf("(\\n)");
1670                 } else if(c == '\r') {
1671                         printf("(\\r)");
1672                 } else if(c == 0x1b) {
1673                         printf("(\\e)");
1674                 } else {
1675                         printf("(%02x)", c);
1676                 }
1677         }
1678         putchar('\n');
1679 }
1680
1681 void
1682 csireset(void) {
1683         memset(&csiescseq, 0, sizeof(csiescseq));
1684 }
1685
1686 void
1687 strhandle(void) {
1688         char *p;
1689
1690         /*
1691          * TODO: make this being useful in case of color palette change.
1692          */
1693         strparse();
1694
1695         p = strescseq.buf;
1696
1697         switch(strescseq.type) {
1698         case ']': /* OSC -- Operating System Command */
1699                 switch(p[0]) {
1700                 case '0':
1701                 case '1':
1702                 case '2':
1703                         /*
1704                          * TODO: Handle special chars in string, like umlauts.
1705                          */
1706                         if(p[1] == ';') {
1707                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1708                         }
1709                         break;
1710                 case ';':
1711                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1712                         break;
1713                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1714                         break;
1715                 default:
1716                         fprintf(stderr, "erresc: unknown str ");
1717                         strdump();
1718                         break;
1719                 }
1720                 break;
1721         case 'k': /* old title set compatibility */
1722                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1723                 break;
1724         case 'P': /* DSC -- Device Control String */
1725         case '_': /* APC -- Application Program Command */
1726         case '^': /* PM -- Privacy Message */
1727         default:
1728                 fprintf(stderr, "erresc: unknown str ");
1729                 strdump();
1730                 /* die(""); */
1731                 break;
1732         }
1733 }
1734
1735 void
1736 strparse(void) {
1737         /*
1738          * TODO: Implement parsing like for CSI when required.
1739          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1740          */
1741         return;
1742 }
1743
1744 void
1745 strdump(void) {
1746         int i;
1747         uint c;
1748
1749         printf("ESC%c", strescseq.type);
1750         for(i = 0; i < strescseq.len; i++) {
1751                 c = strescseq.buf[i] & 0xff;
1752                 if(isprint(c)) {
1753                         putchar(c);
1754                 } else if(c == '\n') {
1755                         printf("(\\n)");
1756                 } else if(c == '\r') {
1757                         printf("(\\r)");
1758                 } else if(c == 0x1b) {
1759                         printf("(\\e)");
1760                 } else {
1761                         printf("(%02x)", c);
1762                 }
1763         }
1764         printf("ESC\\\n");
1765 }
1766
1767 void
1768 strreset(void) {
1769         memset(&strescseq, 0, sizeof(strescseq));
1770 }
1771
1772 void
1773 tputtab(bool forward) {
1774         uint x = term.c.x;
1775
1776         if(forward) {
1777                 if(x == term.col)
1778                         return;
1779                 for(++x; x < term.col && !term.tabs[x]; ++x)
1780                         /* nothing */ ;
1781         } else {
1782                 if(x == 0)
1783                         return;
1784                 for(--x; x > 0 && !term.tabs[x]; --x)
1785                         /* nothing */ ;
1786         }
1787         tmoveto(x, term.c.y);
1788 }
1789
1790 void
1791 tputc(char *c, int len) {
1792         uchar ascii = *c;
1793         bool control = ascii < '\x20' || ascii == 0177;
1794
1795         if(iofd != -1)
1796                 write(iofd, c, len);
1797         /*
1798          * STR sequences must be checked before of anything
1799          * because it can use some control codes as part of the sequence
1800          */
1801         if(term.esc & ESC_STR) {
1802                 switch(ascii) {
1803                 case '\033':
1804                         term.esc = ESC_START | ESC_STR_END;
1805                         break;
1806                 case '\a': /* backwards compatibility to xterm */
1807                         term.esc = 0;
1808                         strhandle();
1809                         break;
1810                 default:
1811                         strescseq.buf[strescseq.len++] = ascii;
1812                         if(strescseq.len+1 >= STR_BUF_SIZ) {
1813                                 term.esc = 0;
1814                                 strhandle();
1815                         }
1816                 }
1817                 return;
1818         }
1819         /*
1820          * Actions of control codes must be performed as soon they arrive
1821          * because they can be embedded inside a control sequence, and
1822          * they must not cause conflicts with sequences.
1823          */
1824         if(control) {
1825                 switch(ascii) {
1826                 case '\t':      /* HT */
1827                         tputtab(1);
1828                         return;
1829                 case '\b':      /* BS */
1830                         tmoveto(term.c.x-1, term.c.y);
1831                         return;
1832                 case '\r':      /* CR */
1833                         tmoveto(0, term.c.y);
1834                         return;
1835                 case '\f':      /* LF */
1836                 case '\v':      /* VT */
1837                 case '\n':      /* LF */
1838                         /* go to first col if the mode is set */
1839                         tnewline(IS_SET(MODE_CRLF));
1840                         return;
1841                 case '\a':      /* BEL */
1842                         if(!(xw.state & WIN_FOCUSED))
1843                                 xseturgency(1);
1844                         return;
1845                 case '\033':    /* ESC */
1846                         csireset();
1847                         term.esc = ESC_START;
1848                         return;
1849                 case '\016':    /* SO */
1850                         term.c.attr.mode |= ATTR_GFX;
1851                         return;
1852                 case '\017':    /* SI */
1853                         term.c.attr.mode &= ~ATTR_GFX;
1854                         return;
1855                 case '\032':    /* SUB */
1856                 case '\030':    /* CAN */
1857                         csireset();
1858                         return;
1859                  case '\005':   /* ENQ (IGNORED) */
1860                  case '\000':   /* NUL (IGNORED) */
1861                  case '\021':   /* XON (IGNORED) */
1862                  case '\023':   /* XOFF (IGNORED) */
1863                  case 0177:     /* DEL (IGNORED) */
1864                         return;
1865                 }
1866         } else if(term.esc & ESC_START) {
1867                 if(term.esc & ESC_CSI) {
1868                         csiescseq.buf[csiescseq.len++] = ascii;
1869                         if(BETWEEN(ascii, 0x40, 0x7E)
1870                                         || csiescseq.len >= ESC_BUF_SIZ) {
1871                                 term.esc = 0;
1872                                 csiparse(), csihandle();
1873                         }
1874                 } else if(term.esc & ESC_STR_END) {
1875                         term.esc = 0;
1876                         if(ascii == '\\')
1877                                 strhandle();
1878                 } else if(term.esc & ESC_ALTCHARSET) {
1879                         switch(ascii) {
1880                         case '0': /* Line drawing set */
1881                                 term.c.attr.mode |= ATTR_GFX;
1882                                 break;
1883                         case 'B': /* USASCII */
1884                                 term.c.attr.mode &= ~ATTR_GFX;
1885                                 break;
1886                         case 'A': /* UK (IGNORED) */
1887                         case '<': /* multinational charset (IGNORED) */
1888                         case '5': /* Finnish (IGNORED) */
1889                         case 'C': /* Finnish (IGNORED) */
1890                         case 'K': /* German (IGNORED) */
1891                                 break;
1892                         default:
1893                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1894                         }
1895                         term.esc = 0;
1896                 } else {
1897                         switch(ascii) {
1898                         case '[':
1899                                 term.esc |= ESC_CSI;
1900                                 break;
1901                         case 'P': /* DCS -- Device Control String */
1902                         case '_': /* APC -- Application Program Command */
1903                         case '^': /* PM -- Privacy Message */
1904                         case ']': /* OSC -- Operating System Command */
1905                         case 'k': /* old title set compatibility */
1906                                 strreset();
1907                                 strescseq.type = ascii;
1908                                 term.esc |= ESC_STR;
1909                                 break;
1910                         case '(': /* set primary charset G0 */
1911                                 term.esc |= ESC_ALTCHARSET;
1912                                 break;
1913                         case ')': /* set secondary charset G1 (IGNORED) */
1914                         case '*': /* set tertiary charset G2 (IGNORED) */
1915                         case '+': /* set quaternary charset G3 (IGNORED) */
1916                                 term.esc = 0;
1917                                 break;
1918                         case 'D': /* IND -- Linefeed */
1919                                 if(term.c.y == term.bot) {
1920                                         tscrollup(term.top, 1);
1921                                 } else {
1922                                         tmoveto(term.c.x, term.c.y+1);
1923                                 }
1924                                 term.esc = 0;
1925                                 break;
1926                         case 'E': /* NEL -- Next line */
1927                                 tnewline(1); /* always go to first col */
1928                                 term.esc = 0;
1929                                 break;
1930                         case 'H': /* HTS -- Horizontal tab stop */
1931                                 term.tabs[term.c.x] = 1;
1932                                 term.esc = 0;
1933                                 break;
1934                         case 'M': /* RI -- Reverse index */
1935                                 if(term.c.y == term.top) {
1936                                         tscrolldown(term.top, 1);
1937                                 } else {
1938                                         tmoveto(term.c.x, term.c.y-1);
1939                                 }
1940                                 term.esc = 0;
1941                                 break;
1942                         case 'Z': /* DECID -- Identify Terminal */
1943                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1944                                 term.esc = 0;
1945                                 break;
1946                         case 'c': /* RIS -- Reset to inital state */
1947                                 treset();
1948                                 term.esc = 0;
1949                                 xresettitle();
1950                                 break;
1951                         case '=': /* DECPAM -- Application keypad */
1952                                 term.mode |= MODE_APPKEYPAD;
1953                                 term.esc = 0;
1954                                 break;
1955                         case '>': /* DECPNM -- Normal keypad */
1956                                 term.mode &= ~MODE_APPKEYPAD;
1957                                 term.esc = 0;
1958                                 break;
1959                         case '7': /* DECSC -- Save Cursor */
1960                                 tcursor(CURSOR_SAVE);
1961                                 term.esc = 0;
1962                                 break;
1963                         case '8': /* DECRC -- Restore Cursor */
1964                                 tcursor(CURSOR_LOAD);
1965                                 term.esc = 0;
1966                                 break;
1967                         case '\\': /* ST -- Stop */
1968                                 term.esc = 0;
1969                                 break;
1970                         default:
1971                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1972                                         (uchar) ascii, isprint(ascii)? ascii:'.');
1973                                 term.esc = 0;
1974                         }
1975                 }
1976                 /*
1977                  * All characters which forms part of a sequence are not
1978                  * printed
1979                  */
1980                 return;
1981         }
1982         /*
1983          * Display control codes only if we are in graphic mode
1984          */
1985         if(control && !(term.c.attr.mode & ATTR_GFX))
1986                 return;
1987         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1988                 sel.bx = -1;
1989         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1990                 tnewline(1); /* always go to first col */
1991         tsetchar(c);
1992         if(term.c.x+1 < term.col)
1993                 tmoveto(term.c.x+1, term.c.y);
1994         else
1995                 term.c.state |= CURSOR_WRAPNEXT;
1996 }
1997
1998 int
1999 tresize(int col, int row) {
2000         int i, x;
2001         int minrow = MIN(row, term.row);
2002         int mincol = MIN(col, term.col);
2003         int slide = term.c.y - row + 1;
2004         bool *bp;
2005
2006         if(col < 1 || row < 1)
2007                 return 0;
2008
2009         /* free unneeded rows */
2010         i = 0;
2011         if(slide > 0) {
2012                 /* slide screen to keep cursor where we expect it -
2013                  * tscrollup would work here, but we can optimize to
2014                  * memmove because we're freeing the earlier lines */
2015                 for(/* i = 0 */; i < slide; i++) {
2016                         free(term.line[i]);
2017                         free(term.alt[i]);
2018                 }
2019                 memmove(term.line, term.line + slide, row * sizeof(Line));
2020                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2021         }
2022         for(i += row; i < term.row; i++) {
2023                 free(term.line[i]);
2024                 free(term.alt[i]);
2025         }
2026
2027         /* resize to new height */
2028         term.line = xrealloc(term.line, row * sizeof(Line));
2029         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2030         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2031         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2032
2033         /* resize each row to new width, zero-pad if needed */
2034         for(i = 0; i < minrow; i++) {
2035                 term.dirty[i] = 1;
2036                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2037                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2038                 for(x = mincol; x < col; x++) {
2039                         term.line[i][x].state = 0;
2040                         term.alt[i][x].state = 0;
2041                 }
2042         }
2043
2044         /* allocate any new rows */
2045         for(/* i == minrow */; i < row; i++) {
2046                 term.dirty[i] = 1;
2047                 term.line[i] = xcalloc(col, sizeof(Glyph));
2048                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2049         }
2050         if(col > term.col) {
2051                 bp = term.tabs + term.col;
2052
2053                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2054                 while(--bp > term.tabs && !*bp)
2055                         /* nothing */ ;
2056                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2057                         *bp = 1;
2058         }
2059         /* update terminal size */
2060         term.col = col, term.row = row;
2061         /* make use of the LIMIT in tmoveto */
2062         tmoveto(term.c.x, term.c.y);
2063         /* reset scrolling region */
2064         tsetscroll(0, row-1);
2065
2066         return (slide > 0);
2067 }
2068
2069 void
2070 xresize(int col, int row) {
2071         xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2072         xw.th = MAX(1, 2*BORDER + row * xw.ch);
2073
2074         XftDrawChange(xw.xft_draw, xw.buf);
2075 }
2076
2077 void
2078 xloadcols(void) {
2079         int i, r, g, b;
2080         XRenderColor xft_color = { .alpha = 0 };
2081
2082         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2083         for(i = 0; i < LEN(colorname); i++) {
2084                 if(!colorname[i])
2085                         continue;
2086                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2087                         die("Could not allocate color '%s'\n", colorname[i]);
2088                 }
2089         }
2090
2091         /* load colors [16-255] ; same colors as xterm */
2092         for(i = 16, r = 0; r < 6; r++) {
2093                 for(g = 0; g < 6; g++) {
2094                         for(b = 0; b < 6; b++) {
2095                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2096                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2097                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2098                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2099                                         die("Could not allocate color %d\n", i);
2100                                 }
2101                                 i++;
2102                         }
2103                 }
2104         }
2105
2106         for(r = 0; r < 24; r++, i++) {
2107                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2108                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2109                                         &dc.xft_col[i])) {
2110                         die("Could not allocate color %d\n", i);
2111                 }
2112         }
2113 }
2114
2115 void
2116 xtermclear(int col1, int row1, int col2, int row2) {
2117         XftDrawRect(xw.xft_draw,
2118                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2119                         BORDER + col1 * xw.cw,
2120                         BORDER + row1 * xw.ch,
2121                         (col2-col1+1) * xw.cw,
2122                         (row2-row1+1) * xw.ch);
2123 }
2124
2125 /*
2126  * Absolute coordinates.
2127  */
2128 void
2129 xclear(int x1, int y1, int x2, int y2) {
2130         XftDrawRect(xw.xft_draw,
2131                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2132                         x1, y1, x2-x1, y2-y1);
2133 }
2134
2135 void
2136 xhints(void) {
2137         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2138         XWMHints wm = {.flags = InputHint, .input = 1};
2139         XSizeHints *sizeh = NULL;
2140
2141         sizeh = XAllocSizeHints();
2142         if(xw.isfixed == False) {
2143                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2144                 sizeh->height = xw.h;
2145                 sizeh->width = xw.w;
2146                 sizeh->height_inc = xw.ch;
2147                 sizeh->width_inc = xw.cw;
2148                 sizeh->base_height = 2*BORDER;
2149                 sizeh->base_width = 2*BORDER;
2150         } else {
2151                 sizeh->flags = PMaxSize | PMinSize;
2152                 sizeh->min_width = sizeh->max_width = xw.fw;
2153                 sizeh->min_height = sizeh->max_height = xw.fh;
2154         }
2155
2156         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2157         XFree(sizeh);
2158 }
2159
2160 void
2161 xinitfont(Font *f, char *fontstr) {
2162         FcPattern *pattern, *match;
2163         FcResult result;
2164
2165         pattern = FcNameParse((FcChar8 *)fontstr);
2166         if(!pattern)
2167                 die("st: can't open font %s\n", fontstr);
2168
2169         match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2170         FcPatternDestroy(pattern);
2171         if(!match)
2172                 die("st: can't open font %s\n", fontstr);
2173         if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2174                 FcPatternDestroy(match);
2175                 die("st: can't open font %s.\n", fontstr);
2176         }
2177
2178         f->ascent = f->xft_set->ascent;
2179         f->descent = f->xft_set->descent;
2180         f->lbearing = 0;
2181         f->rbearing = f->xft_set->max_advance_width;
2182
2183         f->height = f->xft_set->height;
2184         f->width = f->lbearing + f->rbearing;
2185 }
2186
2187 void
2188 initfonts(char *fontstr) {
2189         char *fstr;
2190
2191         xinitfont(&dc.font, fontstr);
2192         xw.cw = dc.font.width;
2193         xw.ch = dc.font.height;
2194
2195         fstr = smstrcat(fontstr, ":weight=bold", NULL);
2196         xinitfont(&dc.bfont, fstr);
2197         free(fstr);
2198
2199         fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2200         xinitfont(&dc.ifont, fstr);
2201         free(fstr);
2202
2203         fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2204         xinitfont(&dc.ibfont, fstr);
2205         free(fstr);
2206 }
2207
2208 void
2209 xinit(void) {
2210         XSetWindowAttributes attrs;
2211         Cursor cursor;
2212         Window parent;
2213         int sw, sh, major, minor;
2214
2215         if(!(xw.dpy = XOpenDisplay(NULL)))
2216                 die("Can't open display\n");
2217         xw.scr = XDefaultScreen(xw.dpy);
2218         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2219
2220         /* font */
2221         initfonts((opt_font != NULL)? opt_font : FONT);
2222
2223         /* colors */
2224         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2225         xloadcols();
2226
2227         /* adjust fixed window geometry */
2228         if(xw.isfixed) {
2229                 sw = DisplayWidth(xw.dpy, xw.scr);
2230                 sh = DisplayHeight(xw.dpy, xw.scr);
2231                 if(xw.fx < 0)
2232                         xw.fx = sw + xw.fx - xw.fw - 1;
2233                 if(xw.fy < 0)
2234                         xw.fy = sh + xw.fy - xw.fh - 1;
2235
2236                 xw.h = xw.fh;
2237                 xw.w = xw.fw;
2238         } else {
2239                 /* window - default size */
2240                 xw.h = 2*BORDER + term.row * xw.ch;
2241                 xw.w = 2*BORDER + term.col * xw.cw;
2242                 xw.fx = 0;
2243                 xw.fy = 0;
2244         }
2245
2246         attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2247         attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2248         attrs.bit_gravity = NorthWestGravity;
2249         attrs.event_mask = FocusChangeMask | KeyPressMask
2250                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2251                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2252         attrs.colormap = xw.cmap;
2253
2254         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2255         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2256                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2257                         xw.vis,
2258                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2259                         | CWColormap,
2260                         &attrs);
2261
2262         /* double buffering */
2263         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2264                 die("Xdbe extension is not present\n");
2265         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2266
2267         /* Xft rendering context */
2268         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2269
2270         /* input methods */
2271         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2272         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2273                                            | XIMStatusNothing, XNClientWindow, xw.win,
2274                                            XNFocusWindow, xw.win, NULL);
2275         /* gc */
2276         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2277
2278         /* white cursor, black outline */
2279         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2280         XDefineCursor(xw.dpy, xw.win, cursor);
2281         XRecolorCursor(xw.dpy, cursor,
2282                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2283                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2284
2285         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2286         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2287         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2288
2289         xresettitle();
2290         XMapWindow(xw.dpy, xw.win);
2291         xhints();
2292         XSync(xw.dpy, 0);
2293 }
2294
2295 void
2296 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2297         int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2298             width = charlen * xw.cw;
2299         Font *font = &dc.font;
2300         XGlyphInfo extents;
2301         XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2302                  *temp, revfg, revbg;
2303         XRenderColor colfg, colbg;
2304
2305         if(base.mode & ATTR_REVERSE)
2306                 temp = fg, fg = bg, bg = temp;
2307
2308         if(base.mode & ATTR_BOLD) {
2309                 if(BETWEEN(base.fg, 0, 7)) {
2310                         /* basic system colors */
2311                         fg = &dc.xft_col[base.fg + 8];
2312                 } else if(BETWEEN(base.fg, 16, 195)) {
2313                         /* 256 colors */
2314                         fg = &dc.xft_col[base.fg + 36];
2315                 } else if(BETWEEN(base.fg, 232, 251)) {
2316                         /* greyscale */
2317                         fg = &dc.xft_col[base.fg + 4];
2318                 }
2319                 /*
2320                  * Those ranges will not be brightened:
2321                  *      8 - 15 – bright system colors
2322                  *      196 - 231 – highest 256 color cube
2323                  *      252 - 255 – brightest colors in greyscale
2324                  */
2325                 font = &dc.bfont;
2326         }
2327
2328         if(base.mode & ATTR_ITALIC)
2329                 font = &dc.ifont;
2330         if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2331                 font = &dc.ibfont;
2332
2333         if(IS_SET(MODE_REVERSE)) {
2334                 if(fg == &dc.xft_col[DefaultFG]) {
2335                         fg = &dc.xft_col[DefaultBG];
2336                 } else {
2337                         colfg.red = ~fg->color.red;
2338                         colfg.green = ~fg->color.green;
2339                         colfg.blue = ~fg->color.blue;
2340                         colfg.alpha = fg->color.alpha;
2341                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2342                         fg = &revfg;
2343                 }
2344
2345                 if(bg == &dc.xft_col[DefaultBG]) {
2346                         bg = &dc.xft_col[DefaultFG];
2347                 } else {
2348                         colbg.red = ~bg->color.red;
2349                         colbg.green = ~bg->color.green;
2350                         colbg.blue = ~bg->color.blue;
2351                         colbg.alpha = bg->color.alpha;
2352                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2353                         bg = &revbg;
2354                 }
2355         }
2356
2357         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2358                         &extents);
2359         width = extents.xOff;
2360
2361         /* Intelligent cleaning up of the borders. */
2362         if(x == 0) {
2363                 xclear(0, (y == 0)? 0 : winy, BORDER,
2364                         winy + xw.ch + (y == term.row-1)? xw.h : 0);
2365         }
2366         if(x + charlen >= term.col-1) {
2367                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2368                         (y == term.row-1)? xw.h : (winy + xw.ch));
2369         }
2370         if(y == 0)
2371                 xclear(winx, 0, winx + width, BORDER);
2372         if(y == term.row-1)
2373                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2374
2375         XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2376         XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2377                         winy + font->ascent, (FcChar8 *)s, bytelen);
2378
2379         if(base.mode & ATTR_UNDERLINE) {
2380                 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2381                                 width, 1);
2382         }
2383 }
2384
2385 void
2386 xdrawcursor(void) {
2387         static int oldx = 0, oldy = 0;
2388         int sl;
2389         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2390
2391         LIMIT(oldx, 0, term.col-1);
2392         LIMIT(oldy, 0, term.row-1);
2393
2394         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2395                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2396
2397         /* remove the old cursor */
2398         if(term.line[oldy][oldx].state & GLYPH_SET) {
2399                 sl = utf8size(term.line[oldy][oldx].c);
2400                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2401                                 oldy, 1, sl);
2402         } else {
2403                 xtermclear(oldx, oldy, oldx, oldy);
2404         }
2405
2406         /* draw the new one */
2407         if(!(term.c.state & CURSOR_HIDE)) {
2408                 if(!(xw.state & WIN_FOCUSED))
2409                         g.bg = DefaultUCS;
2410
2411                 if(IS_SET(MODE_REVERSE))
2412                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2413
2414                 sl = utf8size(g.c);
2415                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2416                 oldx = term.c.x, oldy = term.c.y;
2417         }
2418 }
2419
2420 void
2421 xresettitle(void) {
2422         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2423 }
2424
2425 void
2426 redraw(void) {
2427         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2428
2429         tfulldirt();
2430         draw();
2431         XSync(xw.dpy, False); /* necessary for a good tput flash */
2432         nanosleep(&tv, NULL);
2433 }
2434
2435 void
2436 draw(void) {
2437         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2438
2439         drawregion(0, 0, term.col, term.row);
2440         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2441 }
2442
2443 void
2444 drawregion(int x1, int y1, int x2, int y2) {
2445         int ic, ib, x, y, ox, sl;
2446         Glyph base, new;
2447         char buf[DRAW_BUF_SIZ];
2448         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2449
2450         if((sel.alt && !alt) || (!sel.alt && alt))
2451                 ena_sel = 0;
2452         if(!(xw.state & WIN_VISIBLE))
2453                 return;
2454
2455         for(y = y1; y < y2; y++) {
2456                 if(!term.dirty[y])
2457                         continue;
2458
2459                 xtermclear(0, y, term.col, y);
2460                 term.dirty[y] = 0;
2461                 base = term.line[y][0];
2462                 ic = ib = ox = 0;
2463                 for(x = x1; x < x2; x++) {
2464                         new = term.line[y][x];
2465                         if(ena_sel && *(new.c) && selected(x, y))
2466                                 new.mode ^= ATTR_REVERSE;
2467                         if(ib > 0 && (!(new.state & GLYPH_SET)
2468                                         || ATTRCMP(base, new)
2469                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2470                                 xdraws(buf, base, ox, y, ic, ib);
2471                                 ic = ib = 0;
2472                         }
2473                         if(new.state & GLYPH_SET) {
2474                                 if(ib == 0) {
2475                                         ox = x;
2476                                         base = new;
2477                                 }
2478                                 sl = utf8size(new.c);
2479                                 memcpy(buf+ib, new.c, sl);
2480                                 ib += sl;
2481                                 ++ic;
2482                         }
2483                 }
2484                 if(ib > 0)
2485                         xdraws(buf, base, ox, y, ic, ib);
2486         }
2487         xdrawcursor();
2488 }
2489
2490 void
2491 expose(XEvent *ev) {
2492         XExposeEvent *e = &ev->xexpose;
2493
2494         if(xw.state & WIN_REDRAW) {
2495                 if(!e->count)
2496                         xw.state &= ~WIN_REDRAW;
2497         }
2498 }
2499
2500 void
2501 visibility(XEvent *ev) {
2502         XVisibilityEvent *e = &ev->xvisibility;
2503
2504         if(e->state == VisibilityFullyObscured) {
2505                 xw.state &= ~WIN_VISIBLE;
2506         } else if(!(xw.state & WIN_VISIBLE)) {
2507                 /* need a full redraw for next Expose, not just a buf copy */
2508                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2509         }
2510 }
2511
2512 void
2513 unmap(XEvent *ev) {
2514         xw.state &= ~WIN_VISIBLE;
2515 }
2516
2517 void
2518 xseturgency(int add) {
2519         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2520
2521         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2522         XSetWMHints(xw.dpy, xw.win, h);
2523         XFree(h);
2524 }
2525
2526 void
2527 focus(XEvent *ev) {
2528         if(ev->type == FocusIn) {
2529                 xw.state |= WIN_FOCUSED;
2530                 xseturgency(0);
2531         } else {
2532                 xw.state &= ~WIN_FOCUSED;
2533         }
2534 }
2535
2536 char*
2537 kmap(KeySym k, uint state) {
2538         int i;
2539         uint mask;
2540
2541         state &= ~Mod2Mask;
2542         for(i = 0; i < LEN(key); i++) {
2543                 mask = key[i].mask;
2544
2545                 if(key[i].k == k && ((state & mask) == mask
2546                                 || (mask == XK_NO_MOD && !state))) {
2547                         return (char*)key[i].s;
2548                 }
2549         }
2550         return NULL;
2551 }
2552
2553 void
2554 kpress(XEvent *ev) {
2555         XKeyEvent *e = &ev->xkey;
2556         KeySym ksym;
2557         char buf[32];
2558         char *customkey;
2559         int len;
2560         int meta;
2561         int shift;
2562         Status status;
2563
2564         if (IS_SET(MODE_KBDLOCK))
2565                 return;
2566
2567         meta = e->state & Mod1Mask;
2568         shift = e->state & ShiftMask;
2569         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2570
2571         /* 1. custom keys from config.h */
2572         if((customkey = kmap(ksym, e->state))) {
2573                 ttywrite(customkey, strlen(customkey));
2574         /* 2. hardcoded (overrides X lookup) */
2575         } else {
2576                 switch(ksym) {
2577                 case XK_Up:
2578                 case XK_Down:
2579                 case XK_Left:
2580                 case XK_Right:
2581                         /* XXX: shift up/down doesn't work */
2582                         sprintf(buf, "\033%c%c",
2583                                 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2584                                 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2585                         ttywrite(buf, 3);
2586                         break;
2587                 case XK_Insert:
2588                         if(shift)
2589                                 selpaste();
2590                         break;
2591                 case XK_Return:
2592                         if(IS_SET(MODE_CRLF)) {
2593                                 ttywrite("\r\n", 2);
2594                         } else {
2595                                 ttywrite("\r", 1);
2596                         }
2597                         break;
2598                         /* 3. X lookup  */
2599                 default:
2600                         if(len > 0) {
2601                                 if(meta && len == 1)
2602                                         ttywrite("\033", 1);
2603                                 ttywrite(buf, len);
2604                         }
2605                         break;
2606                 }
2607         }
2608 }
2609
2610 void
2611 cmessage(XEvent *e) {
2612         /* See xembed specs
2613            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2614         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2615                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2616                         xw.state |= WIN_FOCUSED;
2617                         xseturgency(0);
2618                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2619                         xw.state &= ~WIN_FOCUSED;
2620                 }
2621         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2622                 /* Send SIGHUP to shell */
2623                 kill(pid, SIGHUP);
2624                 exit(EXIT_SUCCESS);
2625         }
2626 }
2627
2628 void
2629 resize(XEvent *e) {
2630         int col, row;
2631
2632         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2633                 return;
2634
2635         xw.w = e->xconfigure.width;
2636         xw.h = e->xconfigure.height;
2637         col = (xw.w - 2*BORDER) / xw.cw;
2638         row = (xw.h - 2*BORDER) / xw.ch;
2639         if(col == term.col && row == term.row)
2640                 return;
2641
2642         tresize(col, row);
2643         xresize(col, row);
2644         ttyresize();
2645 }
2646
2647 void
2648 run(void) {
2649         XEvent ev;
2650         fd_set rfd;
2651         int xfd = XConnectionNumber(xw.dpy), i;
2652         struct timeval drawtimeout, *tv = NULL;
2653
2654         for(i = 0;; i++) {
2655                 FD_ZERO(&rfd);
2656                 FD_SET(cmdfd, &rfd);
2657                 FD_SET(xfd, &rfd);
2658                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2659                         if(errno == EINTR)
2660                                 continue;
2661                         die("select failed: %s\n", SERRNO);
2662                 }
2663
2664                 /*
2665                  * Stop after a certain number of reads so the user does not
2666                  * feel like the system is stuttering.
2667                  */
2668                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2669                         ttyread();
2670
2671                         /*
2672                          * Just wait a bit so it isn't disturbing the
2673                          * user and the system is able to write something.
2674                          */
2675                         drawtimeout.tv_sec = 0;
2676                         drawtimeout.tv_usec = 5;
2677                         tv = &drawtimeout;
2678                         continue;
2679                 }
2680                 i = 0;
2681                 tv = NULL;
2682
2683                 while(XPending(xw.dpy)) {
2684                         XNextEvent(xw.dpy, &ev);
2685                         if(XFilterEvent(&ev, xw.win))
2686                                 continue;
2687                         if(handler[ev.type])
2688                                 (handler[ev.type])(&ev);
2689                 }
2690
2691                 draw();
2692                 XFlush(xw.dpy);
2693         }
2694 }
2695
2696 int
2697 main(int argc, char *argv[]) {
2698         int i, bitm, xr, yr;
2699         uint wr, hr;
2700
2701         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2702         xw.isfixed = False;
2703
2704         for(i = 1; i < argc; i++) {
2705                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2706                 case 'c':
2707                         if(++i < argc)
2708                                 opt_class = argv[i];
2709                         break;
2710                 case 'e':
2711                         /* eat every remaining arguments */
2712                         if(++i < argc)
2713                                 opt_cmd = &argv[i];
2714                         goto run;
2715                 case 'f':
2716                         if(++i < argc)
2717                                 opt_font = argv[i];
2718                         break;
2719                 case 'g':
2720                         if(++i >= argc)
2721                                 break;
2722
2723                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2724                         if(bitm & XValue)
2725                                 xw.fx = xr;
2726                         if(bitm & YValue)
2727                                 xw.fy = yr;
2728                         if(bitm & WidthValue)
2729                                 xw.fw = (int)wr;
2730                         if(bitm & HeightValue)
2731                                 xw.fh = (int)hr;
2732                         if(bitm & XNegative && xw.fx == 0)
2733                                 xw.fx = -1;
2734                         if(bitm & XNegative && xw.fy == 0)
2735                                 xw.fy = -1;
2736
2737                         if(xw.fh != 0 && xw.fw != 0)
2738                                 xw.isfixed = True;
2739                         break;
2740                 case 'o':
2741                         if(++i < argc)
2742                                 opt_io = argv[i];
2743                         break;
2744                 case 't':
2745                         if(++i < argc)
2746                                 opt_title = argv[i];
2747                         break;
2748                 case 'v':
2749                 default:
2750                         die(USAGE);
2751                 case 'w':
2752                         if(++i < argc)
2753                                 opt_embed = argv[i];
2754                         break;
2755                 }
2756         }
2757
2758 run:
2759         setlocale(LC_CTYPE, "");
2760         tnew(80, 24);
2761         ttynew();
2762         xinit();
2763         selinit();
2764         run();
2765         return 0;
2766 }
2767