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