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