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