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