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