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