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