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