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