]> git.armaanb.net Git - st.git/blob - st.c
Add support for iso14755
[st.git] / st.c
1 /* See LICENSE for license 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 <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <stdint.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 <termios.h>
21 #include <time.h>
22 #include <unistd.h>
23 #include <libgen.h>
24 #include <X11/Xatom.h>
25 #include <X11/Xlib.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <X11/XKBlib.h>
31 #include <fontconfig/fontconfig.h>
32 #include <wchar.h>
33
34 #include "arg.h"
35
36 char *argv0;
37
38 #define Glyph Glyph_
39 #define Font Font_
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_INVALID   0xFFFD
56 #define UTF_SIZ       4
57 #define ESC_BUF_SIZ   (128*UTF_SIZ)
58 #define ESC_ARG_SIZ   16
59 #define STR_BUF_SIZ   ESC_BUF_SIZ
60 #define STR_ARG_SIZ   ESC_ARG_SIZ
61 #define XK_ANY_MOD    UINT_MAX
62 #define XK_NO_MOD     0
63 #define XK_SWITCH_MOD (1<<13)
64
65 /* macros */
66 #define MIN(a, b)               ((a) < (b) ? (a) : (b))
67 #define MAX(a, b)               ((a) < (b) ? (b) : (a))
68 #define LEN(a)                  (sizeof(a) / sizeof(a)[0])
69 #define NUMMAXLEN(x)            ((int)(sizeof(x) * 2.56 + 0.5) + 1)
70 #define DEFAULT(a, b)           (a) = (a) ? (a) : (b)
71 #define BETWEEN(x, a, b)        ((a) <= (x) && (x) <= (b))
72 #define DIVCEIL(n, d)           (((n) + ((d) - 1)) / (d))
73 #define ISCONTROLC0(c)          (BETWEEN(c, 0, 0x1f) || (c) == '\177')
74 #define ISCONTROLC1(c)          (BETWEEN(c, 0x80, 0x9f))
75 #define ISCONTROL(c)            (ISCONTROLC0(c) || ISCONTROLC1(c))
76 #define ISDELIM(u)              (utf8strchr(worddelimiters, u) != NULL)
77 #define LIMIT(x, a, b)          (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
78 #define ATTRCMP(a, b)           ((a).mode != (b).mode || (a).fg != (b).fg || \
79                                 (a).bg != (b).bg)
80 #define IS_SET(flag)            ((term.mode & (flag)) != 0)
81 #define TIMEDIFF(t1, t2)        ((t1.tv_sec-t2.tv_sec)*1000 + \
82                                 (t1.tv_nsec-t2.tv_nsec)/1E6)
83 #define MODBIT(x, set, bit)     ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
84
85 #define TRUECOLOR(r,g,b)        (1 << 24 | (r) << 16 | (g) << 8 | (b))
86 #define IS_TRUECOL(x)           (1 << 24 & (x))
87 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
88 #define TRUEGREEN(x)            (((x) & 0xff00))
89 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
90
91 /* constants */
92 #define ISO14755CMD             "dmenu -w %lu -p codepoint: </dev/null"
93
94 enum glyph_attribute {
95         ATTR_NULL       = 0,
96         ATTR_BOLD       = 1 << 0,
97         ATTR_FAINT      = 1 << 1,
98         ATTR_ITALIC     = 1 << 2,
99         ATTR_UNDERLINE  = 1 << 3,
100         ATTR_BLINK      = 1 << 4,
101         ATTR_REVERSE    = 1 << 5,
102         ATTR_INVISIBLE  = 1 << 6,
103         ATTR_STRUCK     = 1 << 7,
104         ATTR_WRAP       = 1 << 8,
105         ATTR_WIDE       = 1 << 9,
106         ATTR_WDUMMY     = 1 << 10,
107         ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
108 };
109
110 enum cursor_movement {
111         CURSOR_SAVE,
112         CURSOR_LOAD
113 };
114
115 enum cursor_state {
116         CURSOR_DEFAULT  = 0,
117         CURSOR_WRAPNEXT = 1,
118         CURSOR_ORIGIN   = 2
119 };
120
121 enum term_mode {
122         MODE_WRAP        = 1 << 0,
123         MODE_INSERT      = 1 << 1,
124         MODE_APPKEYPAD   = 1 << 2,
125         MODE_ALTSCREEN   = 1 << 3,
126         MODE_CRLF        = 1 << 4,
127         MODE_MOUSEBTN    = 1 << 5,
128         MODE_MOUSEMOTION = 1 << 6,
129         MODE_REVERSE     = 1 << 7,
130         MODE_KBDLOCK     = 1 << 8,
131         MODE_HIDE        = 1 << 9,
132         MODE_ECHO        = 1 << 10,
133         MODE_APPCURSOR   = 1 << 11,
134         MODE_MOUSESGR    = 1 << 12,
135         MODE_8BIT        = 1 << 13,
136         MODE_BLINK       = 1 << 14,
137         MODE_FBLINK      = 1 << 15,
138         MODE_FOCUS       = 1 << 16,
139         MODE_MOUSEX10    = 1 << 17,
140         MODE_MOUSEMANY   = 1 << 18,
141         MODE_BRCKTPASTE  = 1 << 19,
142         MODE_PRINT       = 1 << 20,
143         MODE_UTF8        = 1 << 21,
144         MODE_SIXEL       = 1 << 22,
145         MODE_MOUSE       = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
146                           |MODE_MOUSEMANY,
147 };
148
149 enum charset {
150         CS_GRAPHIC0,
151         CS_GRAPHIC1,
152         CS_UK,
153         CS_USA,
154         CS_MULTI,
155         CS_GER,
156         CS_FIN
157 };
158
159 enum escape_state {
160         ESC_START      = 1,
161         ESC_CSI        = 2,
162         ESC_STR        = 4,  /* OSC, PM, APC */
163         ESC_ALTCHARSET = 8,
164         ESC_STR_END    = 16, /* a final string was encountered */
165         ESC_TEST       = 32, /* Enter in test mode */
166         ESC_UTF8       = 64,
167         ESC_DCS        =128,
168 };
169
170 enum window_state {
171         WIN_VISIBLE = 1,
172         WIN_FOCUSED = 2
173 };
174
175 enum selection_mode {
176         SEL_IDLE = 0,
177         SEL_EMPTY = 1,
178         SEL_READY = 2
179 };
180
181 enum selection_type {
182         SEL_REGULAR = 1,
183         SEL_RECTANGULAR = 2
184 };
185
186 enum selection_snap {
187         SNAP_WORD = 1,
188         SNAP_LINE = 2
189 };
190
191 typedef unsigned char uchar;
192 typedef unsigned int uint;
193 typedef unsigned long ulong;
194 typedef unsigned short ushort;
195
196 typedef uint_least32_t Rune;
197
198 typedef XftDraw *Draw;
199 typedef XftColor Color;
200
201 typedef struct {
202         Rune u;           /* character code */
203         ushort mode;      /* attribute flags */
204         uint32_t fg;      /* foreground  */
205         uint32_t bg;      /* background  */
206 } Glyph;
207
208 typedef Glyph *Line;
209
210 typedef struct {
211         Glyph attr; /* current char attributes */
212         int x;
213         int y;
214         char state;
215 } TCursor;
216
217 /* CSI Escape sequence structs */
218 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
219 typedef struct {
220         char buf[ESC_BUF_SIZ]; /* raw string */
221         int len;               /* raw string length */
222         char priv;
223         int arg[ESC_ARG_SIZ];
224         int narg;              /* nb of args */
225         char mode[2];
226 } CSIEscape;
227
228 /* STR Escape sequence structs */
229 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
230 typedef struct {
231         char type;             /* ESC type ... */
232         char buf[STR_BUF_SIZ]; /* raw string */
233         int len;               /* raw string length */
234         char *args[STR_ARG_SIZ];
235         int narg;              /* nb of args */
236 } STREscape;
237
238 /* Internal representation of the screen */
239 typedef struct {
240         int row;      /* nb row */
241         int col;      /* nb col */
242         Line *line;   /* screen */
243         Line *alt;    /* alternate screen */
244         int *dirty;  /* dirtyness of lines */
245         XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
246         TCursor c;    /* cursor */
247         int top;      /* top    scroll limit */
248         int bot;      /* bottom scroll limit */
249         int mode;     /* terminal mode flags */
250         int esc;      /* escape state flags */
251         char trantbl[4]; /* charset table translation */
252         int charset;  /* current charset */
253         int icharset; /* selected charset for sequence */
254         int numlock; /* lock numbers in keyboard */
255         int *tabs;
256 } Term;
257
258 /* Purely graphic info */
259 typedef struct {
260         Display *dpy;
261         Colormap cmap;
262         Window win;
263         Drawable buf;
264         Atom xembed, wmdeletewin, netwmname, netwmpid;
265         XIM xim;
266         XIC xic;
267         Draw draw;
268         Visual *vis;
269         XSetWindowAttributes attrs;
270         int scr;
271         int isfixed; /* is fixed geometry? */
272         int l, t; /* left and top offset */
273         int gm; /* geometry mask */
274         int tw, th; /* tty width and height */
275         int w, h; /* window width and height */
276         int ch; /* char height */
277         int cw; /* char width  */
278         char state; /* focus, redraw, visible */
279         int cursor; /* cursor style */
280 } XWindow;
281
282 typedef struct {
283         uint b;
284         uint mask;
285         char *s;
286 } MouseShortcut;
287
288 typedef struct {
289         KeySym k;
290         uint mask;
291         char *s;
292         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
293         signed char appkey;    /* application keypad */
294         signed char appcursor; /* application cursor */
295         signed char crlf;      /* crlf mode          */
296 } Key;
297
298 typedef struct {
299         int mode;
300         int type;
301         int snap;
302         /*
303          * Selection variables:
304          * nb – normalized coordinates of the beginning of the selection
305          * ne – normalized coordinates of the end of the selection
306          * ob – original coordinates of the beginning of the selection
307          * oe – original coordinates of the end of the selection
308          */
309         struct {
310                 int x, y;
311         } nb, ne, ob, oe;
312
313         char *primary, *clipboard;
314         Atom xtarget;
315         int alt;
316         struct timespec tclick1;
317         struct timespec tclick2;
318 } Selection;
319
320 typedef union {
321         int i;
322         uint ui;
323         float f;
324         const void *v;
325 } Arg;
326
327 typedef struct {
328         uint mod;
329         KeySym keysym;
330         void (*func)(const Arg *);
331         const Arg arg;
332 } Shortcut;
333
334 /* function definitions used in config.h */
335 static void clipcopy(const Arg *);
336 static void clippaste(const Arg *);
337 static void numlock(const Arg *);
338 static void selpaste(const Arg *);
339 static void xzoom(const Arg *);
340 static void xzoomabs(const Arg *);
341 static void xzoomreset(const Arg *);
342 static void printsel(const Arg *);
343 static void printscreen(const Arg *) ;
344 static void iso14755(const Arg *);
345 static void toggleprinter(const Arg *);
346 static void sendbreak(const Arg *);
347
348 /* Config.h for applying patches and the configuration. */
349 #include "config.h"
350
351 /* Font structure */
352 typedef struct {
353         int height;
354         int width;
355         int ascent;
356         int descent;
357         short lbearing;
358         short rbearing;
359         XftFont *match;
360         FcFontSet *set;
361         FcPattern *pattern;
362 } Font;
363
364 /* Drawing Context */
365 typedef struct {
366         Color col[MAX(LEN(colorname), 256)];
367         Font font, bfont, ifont, ibfont;
368         GC gc;
369 } DC;
370
371 static void die(const char *, ...);
372 static void draw(void);
373 static void redraw(void);
374 static void drawregion(int, int, int, int);
375 static void execsh(void);
376 static void stty(void);
377 static void sigchld(int);
378 static void run(void);
379
380 static void csidump(void);
381 static void csihandle(void);
382 static void csiparse(void);
383 static void csireset(void);
384 static int eschandle(uchar);
385 static void strdump(void);
386 static void strhandle(void);
387 static void strparse(void);
388 static void strreset(void);
389
390 static int tattrset(int);
391 static void tprinter(char *, size_t);
392 static void tdumpsel(void);
393 static void tdumpline(int);
394 static void tdump(void);
395 static void tclearregion(int, int, int, int);
396 static void tcursor(int);
397 static void tdeletechar(int);
398 static void tdeleteline(int);
399 static void tinsertblank(int);
400 static void tinsertblankline(int);
401 static int tlinelen(int);
402 static void tmoveto(int, int);
403 static void tmoveato(int, int);
404 static void tnew(int, int);
405 static void tnewline(int);
406 static void tputtab(int);
407 static void tputc(Rune);
408 static void treset(void);
409 static void tresize(int, int);
410 static void tscrollup(int, int);
411 static void tscrolldown(int, int);
412 static void tsetattr(int *, int);
413 static void tsetchar(Rune, Glyph *, int, int);
414 static void tsetscroll(int, int);
415 static void tswapscreen(void);
416 static void tsetdirt(int, int);
417 static void tsetdirtattr(int);
418 static void tsetmode(int, int, int *, int);
419 static void tfulldirt(void);
420 static void techo(Rune);
421 static void tcontrolcode(uchar );
422 static void tdectest(char );
423 static void tdefutf8(char);
424 static int32_t tdefcolor(int *, int *, int);
425 static void tdeftran(char);
426 static inline int match(uint, uint);
427 static void ttynew(void);
428 static size_t ttyread(void);
429 static void ttyresize(void);
430 static void ttysend(char *, size_t);
431 static void ttywrite(const char *, size_t);
432 static void tstrsequence(uchar);
433
434 static inline ushort sixd_to_16bit(int);
435 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
436 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
437 static void xdrawglyph(Glyph, int, int);
438 static void xhints(void);
439 static void xclear(int, int, int, int);
440 static void xdrawcursor(void);
441 static void xinit(void);
442 static void xloadcols(void);
443 static int xsetcolorname(int, const char *);
444 static int xgeommasktogravity(int);
445 static int xloadfont(Font *, FcPattern *);
446 static void xloadfonts(char *, double);
447 static void xsettitle(char *);
448 static void xresettitle(void);
449 static void xsetpointermotion(int);
450 static void xseturgency(int);
451 static void xsetsel(char *, Time);
452 static void xunloadfont(Font *);
453 static void xunloadfonts(void);
454 static void xresize(int, int);
455
456 static void expose(XEvent *);
457 static void visibility(XEvent *);
458 static void unmap(XEvent *);
459 static char *kmap(KeySym, uint);
460 static void kpress(XEvent *);
461 static void cmessage(XEvent *);
462 static void cresize(int, int);
463 static void resize(XEvent *);
464 static void focus(XEvent *);
465 static void brelease(XEvent *);
466 static void bpress(XEvent *);
467 static void bmotion(XEvent *);
468 static void propnotify(XEvent *);
469 static void selnotify(XEvent *);
470 static void selclear(XEvent *);
471 static void selrequest(XEvent *);
472
473 static void selinit(void);
474 static void selnormalize(void);
475 static inline int selected(int, int);
476 static char *getsel(void);
477 static void selcopy(Time);
478 static void selscroll(int, int);
479 static void selsnap(int *, int *, int);
480 static int x2col(int);
481 static int y2row(int);
482 static void getbuttoninfo(XEvent *);
483 static void mousereport(XEvent *);
484
485 static size_t utf8decode(char *, Rune *, size_t);
486 static Rune utf8decodebyte(char, size_t *);
487 static size_t utf8encode(Rune, char *);
488 static char utf8encodebyte(Rune, size_t);
489 static char *utf8strchr(char *s, Rune u);
490 static size_t utf8validate(Rune *, size_t);
491
492 static ssize_t xwrite(int, const char *, size_t);
493 static void *xmalloc(size_t);
494 static void *xrealloc(void *, size_t);
495 static char *xstrdup(char *);
496
497 static void usage(void);
498
499 static void (*handler[LASTEvent])(XEvent *) = {
500         [KeyPress] = kpress,
501         [ClientMessage] = cmessage,
502         [ConfigureNotify] = resize,
503         [VisibilityNotify] = visibility,
504         [UnmapNotify] = unmap,
505         [Expose] = expose,
506         [FocusIn] = focus,
507         [FocusOut] = focus,
508         [MotionNotify] = bmotion,
509         [ButtonPress] = bpress,
510         [ButtonRelease] = brelease,
511 /*
512  * Uncomment if you want the selection to disappear when you select something
513  * different in another window.
514  */
515 /*      [SelectionClear] = selclear, */
516         [SelectionNotify] = selnotify,
517 /*
518  * PropertyNotify is only turned on when there is some INCR transfer happening
519  * for the selection retrieval.
520  */
521         [PropertyNotify] = propnotify,
522         [SelectionRequest] = selrequest,
523 };
524
525 /* Globals */
526 static DC dc;
527 static XWindow xw;
528 static Term term;
529 static CSIEscape csiescseq;
530 static STREscape strescseq;
531 static int cmdfd;
532 static pid_t pid;
533 static Selection sel;
534 static int iofd = 1;
535 static char **opt_cmd  = NULL;
536 static char *opt_class = NULL;
537 static char *opt_embed = NULL;
538 static char *opt_font  = NULL;
539 static char *opt_io    = NULL;
540 static char *opt_line  = NULL;
541 static char *opt_name  = NULL;
542 static char *opt_title = NULL;
543 static int oldbutton   = 3; /* button event on startup: 3 = release */
544
545 static char *usedfont = NULL;
546 static double usedfontsize = 0;
547 static double defaultfontsize = 0;
548
549 static uchar utfbyte[UTF_SIZ + 1] = {0x80,    0, 0xC0, 0xE0, 0xF0};
550 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
551 static Rune utfmin[UTF_SIZ + 1] = {       0,    0,  0x80,  0x800,  0x10000};
552 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
553
554 /* Font Ring Cache */
555 enum {
556         FRC_NORMAL,
557         FRC_ITALIC,
558         FRC_BOLD,
559         FRC_ITALICBOLD
560 };
561
562 typedef struct {
563         XftFont *font;
564         int flags;
565         Rune unicodep;
566 } Fontcache;
567
568 /* Fontcache is an array now. A new font will be appended to the array. */
569 static Fontcache frc[16];
570 static int frclen = 0;
571
572 ssize_t
573 xwrite(int fd, const char *s, size_t len)
574 {
575         size_t aux = len;
576         ssize_t r;
577
578         while (len > 0) {
579                 r = write(fd, s, len);
580                 if (r < 0)
581                         return r;
582                 len -= r;
583                 s += r;
584         }
585
586         return aux;
587 }
588
589 void *
590 xmalloc(size_t len)
591 {
592         void *p = malloc(len);
593
594         if (!p)
595                 die("Out of memory\n");
596
597         return p;
598 }
599
600 void *
601 xrealloc(void *p, size_t len)
602 {
603         if ((p = realloc(p, len)) == NULL)
604                 die("Out of memory\n");
605
606         return p;
607 }
608
609 char *
610 xstrdup(char *s)
611 {
612         if ((s = strdup(s)) == NULL)
613                 die("Out of memory\n");
614
615         return s;
616 }
617
618 size_t
619 utf8decode(char *c, Rune *u, size_t clen)
620 {
621         size_t i, j, len, type;
622         Rune udecoded;
623
624         *u = UTF_INVALID;
625         if (!clen)
626                 return 0;
627         udecoded = utf8decodebyte(c[0], &len);
628         if (!BETWEEN(len, 1, UTF_SIZ))
629                 return 1;
630         for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
631                 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
632                 if (type != 0)
633                         return j;
634         }
635         if (j < len)
636                 return 0;
637         *u = udecoded;
638         utf8validate(u, len);
639
640         return len;
641 }
642
643 Rune
644 utf8decodebyte(char c, size_t *i)
645 {
646         for (*i = 0; *i < LEN(utfmask); ++(*i))
647                 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
648                         return (uchar)c & ~utfmask[*i];
649
650         return 0;
651 }
652
653 size_t
654 utf8encode(Rune u, char *c)
655 {
656         size_t len, i;
657
658         len = utf8validate(&u, 0);
659         if (len > UTF_SIZ)
660                 return 0;
661
662         for (i = len - 1; i != 0; --i) {
663                 c[i] = utf8encodebyte(u, 0);
664                 u >>= 6;
665         }
666         c[0] = utf8encodebyte(u, len);
667
668         return len;
669 }
670
671 char
672 utf8encodebyte(Rune u, size_t i)
673 {
674         return utfbyte[i] | (u & ~utfmask[i]);
675 }
676
677 char *
678 utf8strchr(char *s, Rune u)
679 {
680         Rune r;
681         size_t i, j, len;
682
683         len = strlen(s);
684         for (i = 0, j = 0; i < len; i += j) {
685                 if (!(j = utf8decode(&s[i], &r, len - i)))
686                         break;
687                 if (r == u)
688                         return &(s[i]);
689         }
690
691         return NULL;
692 }
693
694 size_t
695 utf8validate(Rune *u, size_t i)
696 {
697         if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
698                 *u = UTF_INVALID;
699         for (i = 1; *u > utfmax[i]; ++i)
700                 ;
701
702         return i;
703 }
704
705 void
706 selinit(void)
707 {
708         clock_gettime(CLOCK_MONOTONIC, &sel.tclick1);
709         clock_gettime(CLOCK_MONOTONIC, &sel.tclick2);
710         sel.mode = SEL_IDLE;
711         sel.snap = 0;
712         sel.ob.x = -1;
713         sel.primary = NULL;
714         sel.clipboard = NULL;
715         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
716         if (sel.xtarget == None)
717                 sel.xtarget = XA_STRING;
718 }
719
720 int
721 x2col(int x)
722 {
723         x -= borderpx;
724         x /= xw.cw;
725
726         return LIMIT(x, 0, term.col-1);
727 }
728
729 int
730 y2row(int y)
731 {
732         y -= borderpx;
733         y /= xw.ch;
734
735         return LIMIT(y, 0, term.row-1);
736 }
737
738 int
739 tlinelen(int y)
740 {
741         int i = term.col;
742
743         if (term.line[y][i - 1].mode & ATTR_WRAP)
744                 return i;
745
746         while (i > 0 && term.line[y][i - 1].u == ' ')
747                 --i;
748
749         return i;
750 }
751
752 void
753 selnormalize(void)
754 {
755         int i;
756
757         if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
758                 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
759                 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
760         } else {
761                 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
762                 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
763         }
764         sel.nb.y = MIN(sel.ob.y, sel.oe.y);
765         sel.ne.y = MAX(sel.ob.y, sel.oe.y);
766
767         selsnap(&sel.nb.x, &sel.nb.y, -1);
768         selsnap(&sel.ne.x, &sel.ne.y, +1);
769
770         /* expand selection over line breaks */
771         if (sel.type == SEL_RECTANGULAR)
772                 return;
773         i = tlinelen(sel.nb.y);
774         if (i < sel.nb.x)
775                 sel.nb.x = i;
776         if (tlinelen(sel.ne.y) <= sel.ne.x)
777                 sel.ne.x = term.col - 1;
778 }
779
780 int
781 selected(int x, int y)
782 {
783         if (sel.mode == SEL_EMPTY)
784                 return 0;
785
786         if (sel.type == SEL_RECTANGULAR)
787                 return BETWEEN(y, sel.nb.y, sel.ne.y)
788                     && BETWEEN(x, sel.nb.x, sel.ne.x);
789
790         return BETWEEN(y, sel.nb.y, sel.ne.y)
791             && (y != sel.nb.y || x >= sel.nb.x)
792             && (y != sel.ne.y || x <= sel.ne.x);
793 }
794
795 void
796 selsnap(int *x, int *y, int direction)
797 {
798         int newx, newy, xt, yt;
799         int delim, prevdelim;
800         Glyph *gp, *prevgp;
801
802         switch (sel.snap) {
803         case SNAP_WORD:
804                 /*
805                  * Snap around if the word wraps around at the end or
806                  * beginning of a line.
807                  */
808                 prevgp = &term.line[*y][*x];
809                 prevdelim = ISDELIM(prevgp->u);
810                 for (;;) {
811                         newx = *x + direction;
812                         newy = *y;
813                         if (!BETWEEN(newx, 0, term.col - 1)) {
814                                 newy += direction;
815                                 newx = (newx + term.col) % term.col;
816                                 if (!BETWEEN(newy, 0, term.row - 1))
817                                         break;
818
819                                 if (direction > 0)
820                                         yt = *y, xt = *x;
821                                 else
822                                         yt = newy, xt = newx;
823                                 if (!(term.line[yt][xt].mode & ATTR_WRAP))
824                                         break;
825                         }
826
827                         if (newx >= tlinelen(newy))
828                                 break;
829
830                         gp = &term.line[newy][newx];
831                         delim = ISDELIM(gp->u);
832                         if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
833                                         || (delim && gp->u != prevgp->u)))
834                                 break;
835
836                         *x = newx;
837                         *y = newy;
838                         prevgp = gp;
839                         prevdelim = delim;
840                 }
841                 break;
842         case SNAP_LINE:
843                 /*
844                  * Snap around if the the previous line or the current one
845                  * has set ATTR_WRAP at its end. Then the whole next or
846                  * previous line will be selected.
847                  */
848                 *x = (direction < 0) ? 0 : term.col - 1;
849                 if (direction < 0) {
850                         for (; *y > 0; *y += direction) {
851                                 if (!(term.line[*y-1][term.col-1].mode
852                                                 & ATTR_WRAP)) {
853                                         break;
854                                 }
855                         }
856                 } else if (direction > 0) {
857                         for (; *y < term.row-1; *y += direction) {
858                                 if (!(term.line[*y][term.col-1].mode
859                                                 & ATTR_WRAP)) {
860                                         break;
861                                 }
862                         }
863                 }
864                 break;
865         }
866 }
867
868 void
869 getbuttoninfo(XEvent *e)
870 {
871         int type;
872         uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
873
874         sel.alt = IS_SET(MODE_ALTSCREEN);
875
876         sel.oe.x = x2col(e->xbutton.x);
877         sel.oe.y = y2row(e->xbutton.y);
878         selnormalize();
879
880         sel.type = SEL_REGULAR;
881         for (type = 1; type < LEN(selmasks); ++type) {
882                 if (match(selmasks[type], state)) {
883                         sel.type = type;
884                         break;
885                 }
886         }
887 }
888
889 void
890 mousereport(XEvent *e)
891 {
892         int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
893             button = e->xbutton.button, state = e->xbutton.state,
894             len;
895         char buf[40];
896         static int ox, oy;
897
898         /* from urxvt */
899         if (e->xbutton.type == MotionNotify) {
900                 if (x == ox && y == oy)
901                         return;
902                 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
903                         return;
904                 /* MOUSE_MOTION: no reporting if no button is pressed */
905                 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
906                         return;
907
908                 button = oldbutton + 32;
909                 ox = x;
910                 oy = y;
911         } else {
912                 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
913                         button = 3;
914                 } else {
915                         button -= Button1;
916                         if (button >= 3)
917                                 button += 64 - 3;
918                 }
919                 if (e->xbutton.type == ButtonPress) {
920                         oldbutton = button;
921                         ox = x;
922                         oy = y;
923                 } else if (e->xbutton.type == ButtonRelease) {
924                         oldbutton = 3;
925                         /* MODE_MOUSEX10: no button release reporting */
926                         if (IS_SET(MODE_MOUSEX10))
927                                 return;
928                         if (button == 64 || button == 65)
929                                 return;
930                 }
931         }
932
933         if (!IS_SET(MODE_MOUSEX10)) {
934                 button += ((state & ShiftMask  ) ? 4  : 0)
935                         + ((state & Mod4Mask   ) ? 8  : 0)
936                         + ((state & ControlMask) ? 16 : 0);
937         }
938
939         if (IS_SET(MODE_MOUSESGR)) {
940                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
941                                 button, x+1, y+1,
942                                 e->xbutton.type == ButtonRelease ? 'm' : 'M');
943         } else if (x < 223 && y < 223) {
944                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
945                                 32+button, 32+x+1, 32+y+1);
946         } else {
947                 return;
948         }
949
950         ttywrite(buf, len);
951 }
952
953 void
954 bpress(XEvent *e)
955 {
956         struct timespec now;
957         MouseShortcut *ms;
958
959         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
960                 mousereport(e);
961                 return;
962         }
963
964         for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
965                 if (e->xbutton.button == ms->b
966                                 && match(ms->mask, e->xbutton.state)) {
967                         ttysend(ms->s, strlen(ms->s));
968                         return;
969                 }
970         }
971
972         if (e->xbutton.button == Button1) {
973                 clock_gettime(CLOCK_MONOTONIC, &now);
974
975                 /* Clear previous selection, logically and visually. */
976                 selclear(NULL);
977                 sel.mode = SEL_EMPTY;
978                 sel.type = SEL_REGULAR;
979                 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
980                 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
981
982                 /*
983                  * If the user clicks below predefined timeouts specific
984                  * snapping behaviour is exposed.
985                  */
986                 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
987                         sel.snap = SNAP_LINE;
988                 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
989                         sel.snap = SNAP_WORD;
990                 } else {
991                         sel.snap = 0;
992                 }
993                 selnormalize();
994
995                 if (sel.snap != 0)
996                         sel.mode = SEL_READY;
997                 tsetdirt(sel.nb.y, sel.ne.y);
998                 sel.tclick2 = sel.tclick1;
999                 sel.tclick1 = now;
1000         }
1001 }
1002
1003 char *
1004 getsel(void)
1005 {
1006         char *str, *ptr;
1007         int y, bufsize, lastx, linelen;
1008         Glyph *gp, *last;
1009
1010         if (sel.ob.x == -1)
1011                 return NULL;
1012
1013         bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
1014         ptr = str = xmalloc(bufsize);
1015
1016         /* append every set & selected glyph to the selection */
1017         for (y = sel.nb.y; y <= sel.ne.y; y++) {
1018                 if ((linelen = tlinelen(y)) == 0) {
1019                         *ptr++ = '\n';
1020                         continue;
1021                 }
1022
1023                 if (sel.type == SEL_RECTANGULAR) {
1024                         gp = &term.line[y][sel.nb.x];
1025                         lastx = sel.ne.x;
1026                 } else {
1027                         gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
1028                         lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
1029                 }
1030                 last = &term.line[y][MIN(lastx, linelen-1)];
1031                 while (last >= gp && last->u == ' ')
1032                         --last;
1033
1034                 for ( ; gp <= last; ++gp) {
1035                         if (gp->mode & ATTR_WDUMMY)
1036                                 continue;
1037
1038                         ptr += utf8encode(gp->u, ptr);
1039                 }
1040
1041                 /*
1042                  * Copy and pasting of line endings is inconsistent
1043                  * in the inconsistent terminal and GUI world.
1044                  * The best solution seems like to produce '\n' when
1045                  * something is copied from st and convert '\n' to
1046                  * '\r', when something to be pasted is received by
1047                  * st.
1048                  * FIXME: Fix the computer world.
1049                  */
1050                 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1051                         *ptr++ = '\n';
1052         }
1053         *ptr = 0;
1054         return str;
1055 }
1056
1057 void
1058 selcopy(Time t)
1059 {
1060         xsetsel(getsel(), t);
1061 }
1062
1063 void
1064 propnotify(XEvent *e)
1065 {
1066         XPropertyEvent *xpev;
1067         Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1068
1069         xpev = &e->xproperty;
1070         if (xpev->state == PropertyNewValue &&
1071                         (xpev->atom == XA_PRIMARY ||
1072                          xpev->atom == clipboard)) {
1073                 selnotify(e);
1074         }
1075 }
1076
1077 void
1078 selnotify(XEvent *e)
1079 {
1080         ulong nitems, ofs, rem;
1081         int format;
1082         uchar *data, *last, *repl;
1083         Atom type, incratom, property;
1084
1085         incratom = XInternAtom(xw.dpy, "INCR", 0);
1086
1087         ofs = 0;
1088         if (e->type == SelectionNotify) {
1089                 property = e->xselection.property;
1090         } else if(e->type == PropertyNotify) {
1091                 property = e->xproperty.atom;
1092         } else {
1093                 return;
1094         }
1095         if (property == None)
1096                 return;
1097
1098         do {
1099                 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
1100                                         BUFSIZ/4, False, AnyPropertyType,
1101                                         &type, &format, &nitems, &rem,
1102                                         &data)) {
1103                         fprintf(stderr, "Clipboard allocation failed\n");
1104                         return;
1105                 }
1106
1107                 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
1108                         /*
1109                          * If there is some PropertyNotify with no data, then
1110                          * this is the signal of the selection owner that all
1111                          * data has been transferred. We won't need to receive
1112                          * PropertyNotify events anymore.
1113                          */
1114                         MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
1115                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1116                                         &xw.attrs);
1117                 }
1118
1119                 if (type == incratom) {
1120                         /*
1121                          * Activate the PropertyNotify events so we receive
1122                          * when the selection owner does send us the next
1123                          * chunk of data.
1124                          */
1125                         MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
1126                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1127                                         &xw.attrs);
1128
1129                         /*
1130                          * Deleting the property is the transfer start signal.
1131                          */
1132                         XDeleteProperty(xw.dpy, xw.win, (int)property);
1133                         continue;
1134                 }
1135
1136                 /*
1137                  * As seen in getsel:
1138                  * Line endings are inconsistent in the terminal and GUI world
1139                  * copy and pasting. When receiving some selection data,
1140                  * replace all '\n' with '\r'.
1141                  * FIXME: Fix the computer world.
1142                  */
1143                 repl = data;
1144                 last = data + nitems * format / 8;
1145                 while ((repl = memchr(repl, '\n', last - repl))) {
1146                         *repl++ = '\r';
1147                 }
1148
1149                 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
1150                         ttywrite("\033[200~", 6);
1151                 ttysend((char *)data, nitems * format / 8);
1152                 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
1153                         ttywrite("\033[201~", 6);
1154                 XFree(data);
1155                 /* number of 32-bit chunks returned */
1156                 ofs += nitems * format / 32;
1157         } while (rem > 0);
1158
1159         /*
1160          * Deleting the property again tells the selection owner to send the
1161          * next data chunk in the property.
1162          */
1163         XDeleteProperty(xw.dpy, xw.win, (int)property);
1164 }
1165
1166 void
1167 selpaste(const Arg *dummy)
1168 {
1169         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1170                         xw.win, CurrentTime);
1171 }
1172
1173 void
1174 clipcopy(const Arg *dummy)
1175 {
1176         Atom clipboard;
1177
1178         if (sel.clipboard != NULL)
1179                 free(sel.clipboard);
1180
1181         if (sel.primary != NULL) {
1182                 sel.clipboard = xstrdup(sel.primary);
1183                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1184                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1185         }
1186 }
1187
1188 void
1189 clippaste(const Arg *dummy)
1190 {
1191         Atom clipboard;
1192
1193         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1194         XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1195                         xw.win, CurrentTime);
1196 }
1197
1198 void
1199 selclear(XEvent *e)
1200 {
1201         if (sel.ob.x == -1)
1202                 return;
1203         sel.mode = SEL_IDLE;
1204         sel.ob.x = -1;
1205         tsetdirt(sel.nb.y, sel.ne.y);
1206 }
1207
1208 void
1209 selrequest(XEvent *e)
1210 {
1211         XSelectionRequestEvent *xsre;
1212         XSelectionEvent xev;
1213         Atom xa_targets, string, clipboard;
1214         char *seltext;
1215
1216         xsre = (XSelectionRequestEvent *) e;
1217         xev.type = SelectionNotify;
1218         xev.requestor = xsre->requestor;
1219         xev.selection = xsre->selection;
1220         xev.target = xsre->target;
1221         xev.time = xsre->time;
1222         if (xsre->property == None)
1223                 xsre->property = xsre->target;
1224
1225         /* reject */
1226         xev.property = None;
1227
1228         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1229         if (xsre->target == xa_targets) {
1230                 /* respond with the supported type */
1231                 string = sel.xtarget;
1232                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1233                                 XA_ATOM, 32, PropModeReplace,
1234                                 (uchar *) &string, 1);
1235                 xev.property = xsre->property;
1236         } else if (xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1237                 /*
1238                  * xith XA_STRING non ascii characters may be incorrect in the
1239                  * requestor. It is not our problem, use utf8.
1240                  */
1241                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1242                 if (xsre->selection == XA_PRIMARY) {
1243                         seltext = sel.primary;
1244                 } else if (xsre->selection == clipboard) {
1245                         seltext = sel.clipboard;
1246                 } else {
1247                         fprintf(stderr,
1248                                 "Unhandled clipboard selection 0x%lx\n",
1249                                 xsre->selection);
1250                         return;
1251                 }
1252                 if (seltext != NULL) {
1253                         XChangeProperty(xsre->display, xsre->requestor,
1254                                         xsre->property, xsre->target,
1255                                         8, PropModeReplace,
1256                                         (uchar *)seltext, strlen(seltext));
1257                         xev.property = xsre->property;
1258                 }
1259         }
1260
1261         /* all done, send a notification to the listener */
1262         if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
1263                 fprintf(stderr, "Error sending SelectionNotify event\n");
1264 }
1265
1266 void
1267 xsetsel(char *str, Time t)
1268 {
1269         free(sel.primary);
1270         sel.primary = str;
1271
1272         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1273         if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1274                 selclear(0);
1275 }
1276
1277 void
1278 brelease(XEvent *e)
1279 {
1280         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1281                 mousereport(e);
1282                 return;
1283         }
1284
1285         if (e->xbutton.button == Button2) {
1286                 selpaste(NULL);
1287         } else if (e->xbutton.button == Button1) {
1288                 if (sel.mode == SEL_READY) {
1289                         getbuttoninfo(e);
1290                         selcopy(e->xbutton.time);
1291                 } else
1292                         selclear(NULL);
1293                 sel.mode = SEL_IDLE;
1294                 tsetdirt(sel.nb.y, sel.ne.y);
1295         }
1296 }
1297
1298 void
1299 bmotion(XEvent *e)
1300 {
1301         int oldey, oldex, oldsby, oldsey;
1302
1303         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1304                 mousereport(e);
1305                 return;
1306         }
1307
1308         if (!sel.mode)
1309                 return;
1310
1311         sel.mode = SEL_READY;
1312         oldey = sel.oe.y;
1313         oldex = sel.oe.x;
1314         oldsby = sel.nb.y;
1315         oldsey = sel.ne.y;
1316         getbuttoninfo(e);
1317
1318         if (oldey != sel.oe.y || oldex != sel.oe.x)
1319                 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1320 }
1321
1322 void
1323 die(const char *errstr, ...)
1324 {
1325         va_list ap;
1326
1327         va_start(ap, errstr);
1328         vfprintf(stderr, errstr, ap);
1329         va_end(ap);
1330         exit(1);
1331 }
1332
1333 void
1334 execsh(void)
1335 {
1336         char **args, *sh, *prog;
1337         const struct passwd *pw;
1338         char buf[sizeof(long) * 8 + 1];
1339
1340         errno = 0;
1341         if ((pw = getpwuid(getuid())) == NULL) {
1342                 if (errno)
1343                         die("getpwuid:%s\n", strerror(errno));
1344                 else
1345                         die("who are you?\n");
1346         }
1347
1348         if ((sh = getenv("SHELL")) == NULL)
1349                 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1350
1351         if (opt_cmd)
1352                 prog = opt_cmd[0];
1353         else if (utmp)
1354                 prog = utmp;
1355         else
1356                 prog = sh;
1357         args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1358
1359         snprintf(buf, sizeof(buf), "%lu", xw.win);
1360
1361         unsetenv("COLUMNS");
1362         unsetenv("LINES");
1363         unsetenv("TERMCAP");
1364         setenv("LOGNAME", pw->pw_name, 1);
1365         setenv("USER", pw->pw_name, 1);
1366         setenv("SHELL", sh, 1);
1367         setenv("HOME", pw->pw_dir, 1);
1368         setenv("TERM", termname, 1);
1369         setenv("WINDOWID", buf, 1);
1370
1371         signal(SIGCHLD, SIG_DFL);
1372         signal(SIGHUP, SIG_DFL);
1373         signal(SIGINT, SIG_DFL);
1374         signal(SIGQUIT, SIG_DFL);
1375         signal(SIGTERM, SIG_DFL);
1376         signal(SIGALRM, SIG_DFL);
1377
1378         execvp(prog, args);
1379         _exit(1);
1380 }
1381
1382 void
1383 sigchld(int a)
1384 {
1385         int stat;
1386         pid_t p;
1387
1388         if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
1389                 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1390
1391         if (pid != p)
1392                 return;
1393
1394         if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1395                 die("child finished with error '%d'\n", stat);
1396         exit(0);
1397 }
1398
1399
1400 void
1401 stty(void)
1402 {
1403         char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1404         size_t n, siz;
1405
1406         if ((n = strlen(stty_args)) > sizeof(cmd)-1)
1407                 die("incorrect stty parameters\n");
1408         memcpy(cmd, stty_args, n);
1409         q = cmd + n;
1410         siz = sizeof(cmd) - n;
1411         for (p = opt_cmd; p && (s = *p); ++p) {
1412                 if ((n = strlen(s)) > siz-1)
1413                         die("stty parameter length too long\n");
1414                 *q++ = ' ';
1415                 memcpy(q, s, n);
1416                 q += n;
1417                 siz -= n + 1;
1418         }
1419         *q = '\0';
1420         if (system(cmd) != 0)
1421             perror("Couldn't call stty");
1422 }
1423
1424 void
1425 ttynew(void)
1426 {
1427         int m, s;
1428         struct winsize w = {term.row, term.col, 0, 0};
1429
1430         if (opt_io) {
1431                 term.mode |= MODE_PRINT;
1432                 iofd = (!strcmp(opt_io, "-")) ?
1433                           1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1434                 if (iofd < 0) {
1435                         fprintf(stderr, "Error opening %s:%s\n",
1436                                 opt_io, strerror(errno));
1437                 }
1438         }
1439
1440         if (opt_line) {
1441                 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
1442                         die("open line failed: %s\n", strerror(errno));
1443                 dup2(cmdfd, 0);
1444                 stty();
1445                 return;
1446         }
1447
1448         /* seems to work fine on linux, openbsd and freebsd */
1449         if (openpty(&m, &s, NULL, NULL, &w) < 0)
1450                 die("openpty failed: %s\n", strerror(errno));
1451
1452         switch (pid = fork()) {
1453         case -1:
1454                 die("fork failed\n");
1455                 break;
1456         case 0:
1457                 close(iofd);
1458                 setsid(); /* create a new process group */
1459                 dup2(s, 0);
1460                 dup2(s, 1);
1461                 dup2(s, 2);
1462                 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1463                         die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1464                 close(s);
1465                 close(m);
1466                 execsh();
1467                 break;
1468         default:
1469                 close(s);
1470                 cmdfd = m;
1471                 signal(SIGCHLD, sigchld);
1472                 break;
1473         }
1474 }
1475
1476 size_t
1477 ttyread(void)
1478 {
1479         static char buf[BUFSIZ];
1480         static int buflen = 0;
1481         char *ptr;
1482         int charsize; /* size of utf8 char in bytes */
1483         Rune unicodep;
1484         int ret;
1485
1486         /* append read bytes to unprocessed bytes */
1487         if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1488                 die("Couldn't read from shell: %s\n", strerror(errno));
1489
1490         buflen += ret;
1491         ptr = buf;
1492
1493         for (;;) {
1494                 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
1495                         /* process a complete utf8 char */
1496                         charsize = utf8decode(ptr, &unicodep, buflen);
1497                         if (charsize == 0)
1498                                 break;
1499                         tputc(unicodep);
1500                         ptr += charsize;
1501                         buflen -= charsize;
1502
1503                 } else {
1504                         if (buflen <= 0)
1505                                 break;
1506                         tputc(*ptr++ & 0xFF);
1507                         buflen--;
1508                 }
1509         }
1510         /* keep any uncomplete utf8 char for the next call */
1511         if (buflen > 0)
1512                 memmove(buf, ptr, buflen);
1513
1514         return ret;
1515 }
1516
1517 void
1518 ttywrite(const char *s, size_t n)
1519 {
1520         fd_set wfd, rfd;
1521         ssize_t r;
1522         size_t lim = 256;
1523
1524         /*
1525          * Remember that we are using a pty, which might be a modem line.
1526          * Writing too much will clog the line. That's why we are doing this
1527          * dance.
1528          * FIXME: Migrate the world to Plan 9.
1529          */
1530         while (n > 0) {
1531                 FD_ZERO(&wfd);
1532                 FD_ZERO(&rfd);
1533                 FD_SET(cmdfd, &wfd);
1534                 FD_SET(cmdfd, &rfd);
1535
1536                 /* Check if we can write. */
1537                 if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
1538                         if (errno == EINTR)
1539                                 continue;
1540                         die("select failed: %s\n", strerror(errno));
1541                 }
1542                 if (FD_ISSET(cmdfd, &wfd)) {
1543                         /*
1544                          * Only write the bytes written by ttywrite() or the
1545                          * default of 256. This seems to be a reasonable value
1546                          * for a serial line. Bigger values might clog the I/O.
1547                          */
1548                         if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
1549                                 goto write_error;
1550                         if (r < n) {
1551                                 /*
1552                                  * We weren't able to write out everything.
1553                                  * This means the buffer is getting full
1554                                  * again. Empty it.
1555                                  */
1556                                 if (n < lim)
1557                                         lim = ttyread();
1558                                 n -= r;
1559                                 s += r;
1560                         } else {
1561                                 /* All bytes have been written. */
1562                                 break;
1563                         }
1564                 }
1565                 if (FD_ISSET(cmdfd, &rfd))
1566                         lim = ttyread();
1567         }
1568         return;
1569
1570 write_error:
1571         die("write error on tty: %s\n", strerror(errno));
1572 }
1573
1574 void
1575 ttysend(char *s, size_t n)
1576 {
1577         int len;
1578         char *t, *lim;
1579         Rune u;
1580
1581         ttywrite(s, n);
1582         if (!IS_SET(MODE_ECHO))
1583                 return;
1584
1585         lim = &s[n];
1586         for (t = s; t < lim; t += len) {
1587                 if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
1588                         len = utf8decode(t, &u, n);
1589                 } else {
1590                         u = *t & 0xFF;
1591                         len = 1;
1592                 }
1593                 if (len <= 0)
1594                         break;
1595                 techo(u);
1596                 n -= len;
1597         }
1598 }
1599
1600 void
1601 ttyresize(void)
1602 {
1603         struct winsize w;
1604
1605         w.ws_row = term.row;
1606         w.ws_col = term.col;
1607         w.ws_xpixel = xw.tw;
1608         w.ws_ypixel = xw.th;
1609         if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1610                 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1611 }
1612
1613 int
1614 tattrset(int attr)
1615 {
1616         int i, j;
1617
1618         for (i = 0; i < term.row-1; i++) {
1619                 for (j = 0; j < term.col-1; j++) {
1620                         if (term.line[i][j].mode & attr)
1621                                 return 1;
1622                 }
1623         }
1624
1625         return 0;
1626 }
1627
1628 void
1629 tsetdirt(int top, int bot)
1630 {
1631         int i;
1632
1633         LIMIT(top, 0, term.row-1);
1634         LIMIT(bot, 0, term.row-1);
1635
1636         for (i = top; i <= bot; i++)
1637                 term.dirty[i] = 1;
1638 }
1639
1640 void
1641 tsetdirtattr(int attr)
1642 {
1643         int i, j;
1644
1645         for (i = 0; i < term.row-1; i++) {
1646                 for (j = 0; j < term.col-1; j++) {
1647                         if (term.line[i][j].mode & attr) {
1648                                 tsetdirt(i, i);
1649                                 break;
1650                         }
1651                 }
1652         }
1653 }
1654
1655 void
1656 tfulldirt(void)
1657 {
1658         tsetdirt(0, term.row-1);
1659 }
1660
1661 void
1662 tcursor(int mode)
1663 {
1664         static TCursor c[2];
1665         int alt = IS_SET(MODE_ALTSCREEN);
1666
1667         if (mode == CURSOR_SAVE) {
1668                 c[alt] = term.c;
1669         } else if (mode == CURSOR_LOAD) {
1670                 term.c = c[alt];
1671                 tmoveto(c[alt].x, c[alt].y);
1672         }
1673 }
1674
1675 void
1676 treset(void)
1677 {
1678         uint i;
1679
1680         term.c = (TCursor){{
1681                 .mode = ATTR_NULL,
1682                 .fg = defaultfg,
1683                 .bg = defaultbg
1684         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1685
1686         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1687         for (i = tabspaces; i < term.col; i += tabspaces)
1688                 term.tabs[i] = 1;
1689         term.top = 0;
1690         term.bot = term.row - 1;
1691         term.mode = MODE_WRAP|MODE_UTF8;
1692         memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1693         term.charset = 0;
1694
1695         for (i = 0; i < 2; i++) {
1696                 tmoveto(0, 0);
1697                 tcursor(CURSOR_SAVE);
1698                 tclearregion(0, 0, term.col-1, term.row-1);
1699                 tswapscreen();
1700         }
1701 }
1702
1703 void
1704 tnew(int col, int row)
1705 {
1706         term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1707         tresize(col, row);
1708         term.numlock = 1;
1709
1710         treset();
1711 }
1712
1713 void
1714 tswapscreen(void)
1715 {
1716         Line *tmp = term.line;
1717
1718         term.line = term.alt;
1719         term.alt = tmp;
1720         term.mode ^= MODE_ALTSCREEN;
1721         tfulldirt();
1722 }
1723
1724 void
1725 tscrolldown(int orig, int n)
1726 {
1727         int i;
1728         Line temp;
1729
1730         LIMIT(n, 0, term.bot-orig+1);
1731
1732         tsetdirt(orig, term.bot-n);
1733         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1734
1735         for (i = term.bot; i >= orig+n; i--) {
1736                 temp = term.line[i];
1737                 term.line[i] = term.line[i-n];
1738                 term.line[i-n] = temp;
1739         }
1740
1741         selscroll(orig, n);
1742 }
1743
1744 void
1745 tscrollup(int orig, int n)
1746 {
1747         int i;
1748         Line temp;
1749
1750         LIMIT(n, 0, term.bot-orig+1);
1751
1752         tclearregion(0, orig, term.col-1, orig+n-1);
1753         tsetdirt(orig+n, term.bot);
1754
1755         for (i = orig; i <= term.bot-n; i++) {
1756                 temp = term.line[i];
1757                 term.line[i] = term.line[i+n];
1758                 term.line[i+n] = temp;
1759         }
1760
1761         selscroll(orig, -n);
1762 }
1763
1764 void
1765 selscroll(int orig, int n)
1766 {
1767         if (sel.ob.x == -1)
1768                 return;
1769
1770         if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1771                 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1772                         selclear(NULL);
1773                         return;
1774                 }
1775                 if (sel.type == SEL_RECTANGULAR) {
1776                         if (sel.ob.y < term.top)
1777                                 sel.ob.y = term.top;
1778                         if (sel.oe.y > term.bot)
1779                                 sel.oe.y = term.bot;
1780                 } else {
1781                         if (sel.ob.y < term.top) {
1782                                 sel.ob.y = term.top;
1783                                 sel.ob.x = 0;
1784                         }
1785                         if (sel.oe.y > term.bot) {
1786                                 sel.oe.y = term.bot;
1787                                 sel.oe.x = term.col;
1788                         }
1789                 }
1790                 selnormalize();
1791         }
1792 }
1793
1794 void
1795 tnewline(int first_col)
1796 {
1797         int y = term.c.y;
1798
1799         if (y == term.bot) {
1800                 tscrollup(term.top, 1);
1801         } else {
1802                 y++;
1803         }
1804         tmoveto(first_col ? 0 : term.c.x, y);
1805 }
1806
1807 void
1808 csiparse(void)
1809 {
1810         char *p = csiescseq.buf, *np;
1811         long int v;
1812
1813         csiescseq.narg = 0;
1814         if (*p == '?') {
1815                 csiescseq.priv = 1;
1816                 p++;
1817         }
1818
1819         csiescseq.buf[csiescseq.len] = '\0';
1820         while (p < csiescseq.buf+csiescseq.len) {
1821                 np = NULL;
1822                 v = strtol(p, &np, 10);
1823                 if (np == p)
1824                         v = 0;
1825                 if (v == LONG_MAX || v == LONG_MIN)
1826                         v = -1;
1827                 csiescseq.arg[csiescseq.narg++] = v;
1828                 p = np;
1829                 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1830                         break;
1831                 p++;
1832         }
1833         csiescseq.mode[0] = *p++;
1834         csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1835 }
1836
1837 /* for absolute user moves, when decom is set */
1838 void
1839 tmoveato(int x, int y)
1840 {
1841         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1842 }
1843
1844 void
1845 tmoveto(int x, int y)
1846 {
1847         int miny, maxy;
1848
1849         if (term.c.state & CURSOR_ORIGIN) {
1850                 miny = term.top;
1851                 maxy = term.bot;
1852         } else {
1853                 miny = 0;
1854                 maxy = term.row - 1;
1855         }
1856         term.c.state &= ~CURSOR_WRAPNEXT;
1857         term.c.x = LIMIT(x, 0, term.col-1);
1858         term.c.y = LIMIT(y, miny, maxy);
1859 }
1860
1861 void
1862 tsetchar(Rune u, Glyph *attr, int x, int y)
1863 {
1864         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1865                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1866                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1867                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1868                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1869                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1870                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1871                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1872                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1873         };
1874
1875         /*
1876          * The table is proudly stolen from rxvt.
1877          */
1878         if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1879            BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1880                 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1881
1882         if (term.line[y][x].mode & ATTR_WIDE) {
1883                 if (x+1 < term.col) {
1884                         term.line[y][x+1].u = ' ';
1885                         term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1886                 }
1887         } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1888                 term.line[y][x-1].u = ' ';
1889                 term.line[y][x-1].mode &= ~ATTR_WIDE;
1890         }
1891
1892         term.dirty[y] = 1;
1893         term.line[y][x] = *attr;
1894         term.line[y][x].u = u;
1895 }
1896
1897 void
1898 tclearregion(int x1, int y1, int x2, int y2)
1899 {
1900         int x, y, temp;
1901         Glyph *gp;
1902
1903         if (x1 > x2)
1904                 temp = x1, x1 = x2, x2 = temp;
1905         if (y1 > y2)
1906                 temp = y1, y1 = y2, y2 = temp;
1907
1908         LIMIT(x1, 0, term.col-1);
1909         LIMIT(x2, 0, term.col-1);
1910         LIMIT(y1, 0, term.row-1);
1911         LIMIT(y2, 0, term.row-1);
1912
1913         for (y = y1; y <= y2; y++) {
1914                 term.dirty[y] = 1;
1915                 for (x = x1; x <= x2; x++) {
1916                         gp = &term.line[y][x];
1917                         if (selected(x, y))
1918                                 selclear(NULL);
1919                         gp->fg = term.c.attr.fg;
1920                         gp->bg = term.c.attr.bg;
1921                         gp->mode = 0;
1922                         gp->u = ' ';
1923                 }
1924         }
1925 }
1926
1927 void
1928 tdeletechar(int n)
1929 {
1930         int dst, src, size;
1931         Glyph *line;
1932
1933         LIMIT(n, 0, term.col - term.c.x);
1934
1935         dst = term.c.x;
1936         src = term.c.x + n;
1937         size = term.col - src;
1938         line = term.line[term.c.y];
1939
1940         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1941         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1942 }
1943
1944 void
1945 tinsertblank(int n)
1946 {
1947         int dst, src, size;
1948         Glyph *line;
1949
1950         LIMIT(n, 0, term.col - term.c.x);
1951
1952         dst = term.c.x + n;
1953         src = term.c.x;
1954         size = term.col - dst;
1955         line = term.line[term.c.y];
1956
1957         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1958         tclearregion(src, term.c.y, dst - 1, term.c.y);
1959 }
1960
1961 void
1962 tinsertblankline(int n)
1963 {
1964         if (BETWEEN(term.c.y, term.top, term.bot))
1965                 tscrolldown(term.c.y, n);
1966 }
1967
1968 void
1969 tdeleteline(int n)
1970 {
1971         if (BETWEEN(term.c.y, term.top, term.bot))
1972                 tscrollup(term.c.y, n);
1973 }
1974
1975 int32_t
1976 tdefcolor(int *attr, int *npar, int l)
1977 {
1978         int32_t idx = -1;
1979         uint r, g, b;
1980
1981         switch (attr[*npar + 1]) {
1982         case 2: /* direct color in RGB space */
1983                 if (*npar + 4 >= l) {
1984                         fprintf(stderr,
1985                                 "erresc(38): Incorrect number of parameters (%d)\n",
1986                                 *npar);
1987                         break;
1988                 }
1989                 r = attr[*npar + 2];
1990                 g = attr[*npar + 3];
1991                 b = attr[*npar + 4];
1992                 *npar += 4;
1993                 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1994                         fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1995                                 r, g, b);
1996                 else
1997                         idx = TRUECOLOR(r, g, b);
1998                 break;
1999         case 5: /* indexed color */
2000                 if (*npar + 2 >= l) {
2001                         fprintf(stderr,
2002                                 "erresc(38): Incorrect number of parameters (%d)\n",
2003                                 *npar);
2004                         break;
2005                 }
2006                 *npar += 2;
2007                 if (!BETWEEN(attr[*npar], 0, 255))
2008                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
2009                 else
2010                         idx = attr[*npar];
2011                 break;
2012         case 0: /* implemented defined (only foreground) */
2013         case 1: /* transparent */
2014         case 3: /* direct color in CMY space */
2015         case 4: /* direct color in CMYK space */
2016         default:
2017                 fprintf(stderr,
2018                         "erresc(38): gfx attr %d unknown\n", attr[*npar]);
2019                 break;
2020         }
2021
2022         return idx;
2023 }
2024
2025 void
2026 tsetattr(int *attr, int l)
2027 {
2028         int i;
2029         int32_t idx;
2030
2031         for (i = 0; i < l; i++) {
2032                 switch (attr[i]) {
2033                 case 0:
2034                         term.c.attr.mode &= ~(
2035                                 ATTR_BOLD       |
2036                                 ATTR_FAINT      |
2037                                 ATTR_ITALIC     |
2038                                 ATTR_UNDERLINE  |
2039                                 ATTR_BLINK      |
2040                                 ATTR_REVERSE    |
2041                                 ATTR_INVISIBLE  |
2042                                 ATTR_STRUCK     );
2043                         term.c.attr.fg = defaultfg;
2044                         term.c.attr.bg = defaultbg;
2045                         break;
2046                 case 1:
2047                         term.c.attr.mode |= ATTR_BOLD;
2048                         break;
2049                 case 2:
2050                         term.c.attr.mode |= ATTR_FAINT;
2051                         break;
2052                 case 3:
2053                         term.c.attr.mode |= ATTR_ITALIC;
2054                         break;
2055                 case 4:
2056                         term.c.attr.mode |= ATTR_UNDERLINE;
2057                         break;
2058                 case 5: /* slow blink */
2059                         /* FALLTHROUGH */
2060                 case 6: /* rapid blink */
2061                         term.c.attr.mode |= ATTR_BLINK;
2062                         break;
2063                 case 7:
2064                         term.c.attr.mode |= ATTR_REVERSE;
2065                         break;
2066                 case 8:
2067                         term.c.attr.mode |= ATTR_INVISIBLE;
2068                         break;
2069                 case 9:
2070                         term.c.attr.mode |= ATTR_STRUCK;
2071                         break;
2072                 case 22:
2073                         term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
2074                         break;
2075                 case 23:
2076                         term.c.attr.mode &= ~ATTR_ITALIC;
2077                         break;
2078                 case 24:
2079                         term.c.attr.mode &= ~ATTR_UNDERLINE;
2080                         break;
2081                 case 25:
2082                         term.c.attr.mode &= ~ATTR_BLINK;
2083                         break;
2084                 case 27:
2085                         term.c.attr.mode &= ~ATTR_REVERSE;
2086                         break;
2087                 case 28:
2088                         term.c.attr.mode &= ~ATTR_INVISIBLE;
2089                         break;
2090                 case 29:
2091                         term.c.attr.mode &= ~ATTR_STRUCK;
2092                         break;
2093                 case 38:
2094                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
2095                                 term.c.attr.fg = idx;
2096                         break;
2097                 case 39:
2098                         term.c.attr.fg = defaultfg;
2099                         break;
2100                 case 48:
2101                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
2102                                 term.c.attr.bg = idx;
2103                         break;
2104                 case 49:
2105                         term.c.attr.bg = defaultbg;
2106                         break;
2107                 default:
2108                         if (BETWEEN(attr[i], 30, 37)) {
2109                                 term.c.attr.fg = attr[i] - 30;
2110                         } else if (BETWEEN(attr[i], 40, 47)) {
2111                                 term.c.attr.bg = attr[i] - 40;
2112                         } else if (BETWEEN(attr[i], 90, 97)) {
2113                                 term.c.attr.fg = attr[i] - 90 + 8;
2114                         } else if (BETWEEN(attr[i], 100, 107)) {
2115                                 term.c.attr.bg = attr[i] - 100 + 8;
2116                         } else {
2117                                 fprintf(stderr,
2118                                         "erresc(default): gfx attr %d unknown\n",
2119                                         attr[i]), csidump();
2120                         }
2121                         break;
2122                 }
2123         }
2124 }
2125
2126 void
2127 tsetscroll(int t, int b)
2128 {
2129         int temp;
2130
2131         LIMIT(t, 0, term.row-1);
2132         LIMIT(b, 0, term.row-1);
2133         if (t > b) {
2134                 temp = t;
2135                 t = b;
2136                 b = temp;
2137         }
2138         term.top = t;
2139         term.bot = b;
2140 }
2141
2142 void
2143 tsetmode(int priv, int set, int *args, int narg)
2144 {
2145         int *lim, mode;
2146         int alt;
2147
2148         for (lim = args + narg; args < lim; ++args) {
2149                 if (priv) {
2150                         switch (*args) {
2151                         case 1: /* DECCKM -- Cursor key */
2152                                 MODBIT(term.mode, set, MODE_APPCURSOR);
2153                                 break;
2154                         case 5: /* DECSCNM -- Reverse video */
2155                                 mode = term.mode;
2156                                 MODBIT(term.mode, set, MODE_REVERSE);
2157                                 if (mode != term.mode)
2158                                         redraw();
2159                                 break;
2160                         case 6: /* DECOM -- Origin */
2161                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2162                                 tmoveato(0, 0);
2163                                 break;
2164                         case 7: /* DECAWM -- Auto wrap */
2165                                 MODBIT(term.mode, set, MODE_WRAP);
2166                                 break;
2167                         case 0:  /* Error (IGNORED) */
2168                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
2169                         case 3:  /* DECCOLM -- Column  (IGNORED) */
2170                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
2171                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
2172                         case 18: /* DECPFF -- Printer feed (IGNORED) */
2173                         case 19: /* DECPEX -- Printer extent (IGNORED) */
2174                         case 42: /* DECNRCM -- National characters (IGNORED) */
2175                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
2176                                 break;
2177                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
2178                                 MODBIT(term.mode, !set, MODE_HIDE);
2179                                 break;
2180                         case 9:    /* X10 mouse compatibility mode */
2181                                 xsetpointermotion(0);
2182                                 MODBIT(term.mode, 0, MODE_MOUSE);
2183                                 MODBIT(term.mode, set, MODE_MOUSEX10);
2184                                 break;
2185                         case 1000: /* 1000: report button press */
2186                                 xsetpointermotion(0);
2187                                 MODBIT(term.mode, 0, MODE_MOUSE);
2188                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
2189                                 break;
2190                         case 1002: /* 1002: report motion on button press */
2191                                 xsetpointermotion(0);
2192                                 MODBIT(term.mode, 0, MODE_MOUSE);
2193                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2194                                 break;
2195                         case 1003: /* 1003: enable all mouse motions */
2196                                 xsetpointermotion(set);
2197                                 MODBIT(term.mode, 0, MODE_MOUSE);
2198                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
2199                                 break;
2200                         case 1004: /* 1004: send focus events to tty */
2201                                 MODBIT(term.mode, set, MODE_FOCUS);
2202                                 break;
2203                         case 1006: /* 1006: extended reporting mode */
2204                                 MODBIT(term.mode, set, MODE_MOUSESGR);
2205                                 break;
2206                         case 1034:
2207                                 MODBIT(term.mode, set, MODE_8BIT);
2208                                 break;
2209                         case 1049: /* swap screen & set/restore cursor as xterm */
2210                                 if (!allowaltscreen)
2211                                         break;
2212                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2213                                 /* FALLTHROUGH */
2214                         case 47: /* swap screen */
2215                         case 1047:
2216                                 if (!allowaltscreen)
2217                                         break;
2218                                 alt = IS_SET(MODE_ALTSCREEN);
2219                                 if (alt) {
2220                                         tclearregion(0, 0, term.col-1,
2221                                                         term.row-1);
2222                                 }
2223                                 if (set ^ alt) /* set is always 1 or 0 */
2224                                         tswapscreen();
2225                                 if (*args != 1049)
2226                                         break;
2227                                 /* FALLTHROUGH */
2228                         case 1048:
2229                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2230                                 break;
2231                         case 2004: /* 2004: bracketed paste mode */
2232                                 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2233                                 break;
2234                         /* Not implemented mouse modes. See comments there. */
2235                         case 1001: /* mouse highlight mode; can hang the
2236                                       terminal by design when implemented. */
2237                         case 1005: /* UTF-8 mouse mode; will confuse
2238                                       applications not supporting UTF-8
2239                                       and luit. */
2240                         case 1015: /* urxvt mangled mouse mode; incompatible
2241                                       and can be mistaken for other control
2242                                       codes. */
2243                         default:
2244                                 fprintf(stderr,
2245                                         "erresc: unknown private set/reset mode %d\n",
2246                                         *args);
2247                                 break;
2248                         }
2249                 } else {
2250                         switch (*args) {
2251                         case 0:  /* Error (IGNORED) */
2252                                 break;
2253                         case 2:  /* KAM -- keyboard action */
2254                                 MODBIT(term.mode, set, MODE_KBDLOCK);
2255                                 break;
2256                         case 4:  /* IRM -- Insertion-replacement */
2257                                 MODBIT(term.mode, set, MODE_INSERT);
2258                                 break;
2259                         case 12: /* SRM -- Send/Receive */
2260                                 MODBIT(term.mode, !set, MODE_ECHO);
2261                                 break;
2262                         case 20: /* LNM -- Linefeed/new line */
2263                                 MODBIT(term.mode, set, MODE_CRLF);
2264                                 break;
2265                         default:
2266                                 fprintf(stderr,
2267                                         "erresc: unknown set/reset mode %d\n",
2268                                         *args);
2269                                 break;
2270                         }
2271                 }
2272         }
2273 }
2274
2275 void
2276 csihandle(void)
2277 {
2278         char buf[40];
2279         int len;
2280
2281         switch (csiescseq.mode[0]) {
2282         default:
2283         unknown:
2284                 fprintf(stderr, "erresc: unknown csi ");
2285                 csidump();
2286                 /* die(""); */
2287                 break;
2288         case '@': /* ICH -- Insert <n> blank char */
2289                 DEFAULT(csiescseq.arg[0], 1);
2290                 tinsertblank(csiescseq.arg[0]);
2291                 break;
2292         case 'A': /* CUU -- Cursor <n> Up */
2293                 DEFAULT(csiescseq.arg[0], 1);
2294                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2295                 break;
2296         case 'B': /* CUD -- Cursor <n> Down */
2297         case 'e': /* VPR --Cursor <n> Down */
2298                 DEFAULT(csiescseq.arg[0], 1);
2299                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2300                 break;
2301         case 'i': /* MC -- Media Copy */
2302                 switch (csiescseq.arg[0]) {
2303                 case 0:
2304                         tdump();
2305                         break;
2306                 case 1:
2307                         tdumpline(term.c.y);
2308                         break;
2309                 case 2:
2310                         tdumpsel();
2311                         break;
2312                 case 4:
2313                         term.mode &= ~MODE_PRINT;
2314                         break;
2315                 case 5:
2316                         term.mode |= MODE_PRINT;
2317                         break;
2318                 }
2319                 break;
2320         case 'c': /* DA -- Device Attributes */
2321                 if (csiescseq.arg[0] == 0)
2322                         ttywrite(vtiden, sizeof(vtiden) - 1);
2323                 break;
2324         case 'C': /* CUF -- Cursor <n> Forward */
2325         case 'a': /* HPR -- Cursor <n> Forward */
2326                 DEFAULT(csiescseq.arg[0], 1);
2327                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2328                 break;
2329         case 'D': /* CUB -- Cursor <n> Backward */
2330                 DEFAULT(csiescseq.arg[0], 1);
2331                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2332                 break;
2333         case 'E': /* CNL -- Cursor <n> Down and first col */
2334                 DEFAULT(csiescseq.arg[0], 1);
2335                 tmoveto(0, term.c.y+csiescseq.arg[0]);
2336                 break;
2337         case 'F': /* CPL -- Cursor <n> Up and first col */
2338                 DEFAULT(csiescseq.arg[0], 1);
2339                 tmoveto(0, term.c.y-csiescseq.arg[0]);
2340                 break;
2341         case 'g': /* TBC -- Tabulation clear */
2342                 switch (csiescseq.arg[0]) {
2343                 case 0: /* clear current tab stop */
2344                         term.tabs[term.c.x] = 0;
2345                         break;
2346                 case 3: /* clear all the tabs */
2347                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2348                         break;
2349                 default:
2350                         goto unknown;
2351                 }
2352                 break;
2353         case 'G': /* CHA -- Move to <col> */
2354         case '`': /* HPA */
2355                 DEFAULT(csiescseq.arg[0], 1);
2356                 tmoveto(csiescseq.arg[0]-1, term.c.y);
2357                 break;
2358         case 'H': /* CUP -- Move to <row> <col> */
2359         case 'f': /* HVP */
2360                 DEFAULT(csiescseq.arg[0], 1);
2361                 DEFAULT(csiescseq.arg[1], 1);
2362                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2363                 break;
2364         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2365                 DEFAULT(csiescseq.arg[0], 1);
2366                 tputtab(csiescseq.arg[0]);
2367                 break;
2368         case 'J': /* ED -- Clear screen */
2369                 selclear(NULL);
2370                 switch (csiescseq.arg[0]) {
2371                 case 0: /* below */
2372                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2373                         if (term.c.y < term.row-1) {
2374                                 tclearregion(0, term.c.y+1, term.col-1,
2375                                                 term.row-1);
2376                         }
2377                         break;
2378                 case 1: /* above */
2379                         if (term.c.y > 1)
2380                                 tclearregion(0, 0, term.col-1, term.c.y-1);
2381                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2382                         break;
2383                 case 2: /* all */
2384                         tclearregion(0, 0, term.col-1, term.row-1);
2385                         break;
2386                 default:
2387                         goto unknown;
2388                 }
2389                 break;
2390         case 'K': /* EL -- Clear line */
2391                 switch (csiescseq.arg[0]) {
2392                 case 0: /* right */
2393                         tclearregion(term.c.x, term.c.y, term.col-1,
2394                                         term.c.y);
2395                         break;
2396                 case 1: /* left */
2397                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2398                         break;
2399                 case 2: /* all */
2400                         tclearregion(0, term.c.y, term.col-1, term.c.y);
2401                         break;
2402                 }
2403                 break;
2404         case 'S': /* SU -- Scroll <n> line up */
2405                 DEFAULT(csiescseq.arg[0], 1);
2406                 tscrollup(term.top, csiescseq.arg[0]);
2407                 break;
2408         case 'T': /* SD -- Scroll <n> line down */
2409                 DEFAULT(csiescseq.arg[0], 1);
2410                 tscrolldown(term.top, csiescseq.arg[0]);
2411                 break;
2412         case 'L': /* IL -- Insert <n> blank lines */
2413                 DEFAULT(csiescseq.arg[0], 1);
2414                 tinsertblankline(csiescseq.arg[0]);
2415                 break;
2416         case 'l': /* RM -- Reset Mode */
2417                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2418                 break;
2419         case 'M': /* DL -- Delete <n> lines */
2420                 DEFAULT(csiescseq.arg[0], 1);
2421                 tdeleteline(csiescseq.arg[0]);
2422                 break;
2423         case 'X': /* ECH -- Erase <n> char */
2424                 DEFAULT(csiescseq.arg[0], 1);
2425                 tclearregion(term.c.x, term.c.y,
2426                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2427                 break;
2428         case 'P': /* DCH -- Delete <n> char */
2429                 DEFAULT(csiescseq.arg[0], 1);
2430                 tdeletechar(csiescseq.arg[0]);
2431                 break;
2432         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2433                 DEFAULT(csiescseq.arg[0], 1);
2434                 tputtab(-csiescseq.arg[0]);
2435                 break;
2436         case 'd': /* VPA -- Move to <row> */
2437                 DEFAULT(csiescseq.arg[0], 1);
2438                 tmoveato(term.c.x, csiescseq.arg[0]-1);
2439                 break;
2440         case 'h': /* SM -- Set terminal mode */
2441                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2442                 break;
2443         case 'm': /* SGR -- Terminal attribute (color) */
2444                 tsetattr(csiescseq.arg, csiescseq.narg);
2445                 break;
2446         case 'n': /* DSR – Device Status Report (cursor position) */
2447                 if (csiescseq.arg[0] == 6) {
2448                         len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2449                                         term.c.y+1, term.c.x+1);
2450                         ttywrite(buf, len);
2451                 }
2452                 break;
2453         case 'r': /* DECSTBM -- Set Scrolling Region */
2454                 if (csiescseq.priv) {
2455                         goto unknown;
2456                 } else {
2457                         DEFAULT(csiescseq.arg[0], 1);
2458                         DEFAULT(csiescseq.arg[1], term.row);
2459                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2460                         tmoveato(0, 0);
2461                 }
2462                 break;
2463         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2464                 tcursor(CURSOR_SAVE);
2465                 break;
2466         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2467                 tcursor(CURSOR_LOAD);
2468                 break;
2469         case ' ':
2470                 switch (csiescseq.mode[1]) {
2471                 case 'q': /* DECSCUSR -- Set Cursor Style */
2472                         DEFAULT(csiescseq.arg[0], 1);
2473                         if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2474                                 goto unknown;
2475                         }
2476                         xw.cursor = csiescseq.arg[0];
2477                         break;
2478                 default:
2479                         goto unknown;
2480                 }
2481                 break;
2482         }
2483 }
2484
2485 void
2486 csidump(void)
2487 {
2488         int i;
2489         uint c;
2490
2491         printf("ESC[");
2492         for (i = 0; i < csiescseq.len; i++) {
2493                 c = csiescseq.buf[i] & 0xff;
2494                 if (isprint(c)) {
2495                         putchar(c);
2496                 } else if (c == '\n') {
2497                         printf("(\\n)");
2498                 } else if (c == '\r') {
2499                         printf("(\\r)");
2500                 } else if (c == 0x1b) {
2501                         printf("(\\e)");
2502                 } else {
2503                         printf("(%02x)", c);
2504                 }
2505         }
2506         putchar('\n');
2507 }
2508
2509 void
2510 csireset(void)
2511 {
2512         memset(&csiescseq, 0, sizeof(csiescseq));
2513 }
2514
2515 void
2516 strhandle(void)
2517 {
2518         char *p = NULL;
2519         int j, narg, par;
2520
2521         term.esc &= ~(ESC_STR_END|ESC_STR);
2522         strparse();
2523         par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2524
2525         switch (strescseq.type) {
2526         case ']': /* OSC -- Operating System Command */
2527                 switch (par) {
2528                 case 0:
2529                 case 1:
2530                 case 2:
2531                         if (narg > 1)
2532                                 xsettitle(strescseq.args[1]);
2533                         return;
2534                 case 4: /* color set */
2535                         if (narg < 3)
2536                                 break;
2537                         p = strescseq.args[2];
2538                         /* FALLTHROUGH */
2539                 case 104: /* color reset, here p = NULL */
2540                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2541                         if (xsetcolorname(j, p)) {
2542                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2543                         } else {
2544                                 /*
2545                                  * TODO if defaultbg color is changed, borders
2546                                  * are dirty
2547                                  */
2548                                 redraw();
2549                         }
2550                         return;
2551                 }
2552                 break;
2553         case 'k': /* old title set compatibility */
2554                 xsettitle(strescseq.args[0]);
2555                 return;
2556         case 'P': /* DCS -- Device Control String */
2557                 term.mode |= ESC_DCS;
2558         case '_': /* APC -- Application Program Command */
2559         case '^': /* PM -- Privacy Message */
2560                 return;
2561         }
2562
2563         fprintf(stderr, "erresc: unknown str ");
2564         strdump();
2565 }
2566
2567 void
2568 strparse(void)
2569 {
2570         int c;
2571         char *p = strescseq.buf;
2572
2573         strescseq.narg = 0;
2574         strescseq.buf[strescseq.len] = '\0';
2575
2576         if (*p == '\0')
2577                 return;
2578
2579         while (strescseq.narg < STR_ARG_SIZ) {
2580                 strescseq.args[strescseq.narg++] = p;
2581                 while ((c = *p) != ';' && c != '\0')
2582                         ++p;
2583                 if (c == '\0')
2584                         return;
2585                 *p++ = '\0';
2586         }
2587 }
2588
2589 void
2590 strdump(void)
2591 {
2592         int i;
2593         uint c;
2594
2595         printf("ESC%c", strescseq.type);
2596         for (i = 0; i < strescseq.len; i++) {
2597                 c = strescseq.buf[i] & 0xff;
2598                 if (c == '\0') {
2599                         return;
2600                 } else if (isprint(c)) {
2601                         putchar(c);
2602                 } else if (c == '\n') {
2603                         printf("(\\n)");
2604                 } else if (c == '\r') {
2605                         printf("(\\r)");
2606                 } else if (c == 0x1b) {
2607                         printf("(\\e)");
2608                 } else {
2609                         printf("(%02x)", c);
2610                 }
2611         }
2612         printf("ESC\\\n");
2613 }
2614
2615 void
2616 strreset(void)
2617 {
2618         memset(&strescseq, 0, sizeof(strescseq));
2619 }
2620
2621 void
2622 sendbreak(const Arg *arg)
2623 {
2624         if (tcsendbreak(cmdfd, 0))
2625                 perror("Error sending break");
2626 }
2627
2628 void
2629 tprinter(char *s, size_t len)
2630 {
2631         if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2632                 fprintf(stderr, "Error writing in %s:%s\n",
2633                         opt_io, strerror(errno));
2634                 close(iofd);
2635                 iofd = -1;
2636         }
2637 }
2638
2639 void
2640 iso14755(const Arg *arg)
2641 {
2642         char cmd[sizeof(ISO14755CMD) + NUMMAXLEN(xw.win)];
2643         FILE *p;
2644         char *us, *e, codepoint[9], uc[UTF_SIZ];
2645         unsigned long utf32;
2646
2647         snprintf(cmd, sizeof(cmd), ISO14755CMD, xw.win);
2648         if (!(p = popen(cmd, "r")))
2649                 return;
2650
2651         us = fgets(codepoint, sizeof(codepoint), p);
2652         pclose(p);
2653
2654         if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
2655                 return;
2656         if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
2657             (*e != '\n' && *e != '\0'))
2658                 return;
2659
2660         ttysend(uc, utf8encode(utf32, uc));
2661 }
2662
2663 void
2664 toggleprinter(const Arg *arg)
2665 {
2666         term.mode ^= MODE_PRINT;
2667 }
2668
2669 void
2670 printscreen(const Arg *arg)
2671 {
2672         tdump();
2673 }
2674
2675 void
2676 printsel(const Arg *arg)
2677 {
2678         tdumpsel();
2679 }
2680
2681 void
2682 tdumpsel(void)
2683 {
2684         char *ptr;
2685
2686         if ((ptr = getsel())) {
2687                 tprinter(ptr, strlen(ptr));
2688                 free(ptr);
2689         }
2690 }
2691
2692 void
2693 tdumpline(int n)
2694 {
2695         char buf[UTF_SIZ];
2696         Glyph *bp, *end;
2697
2698         bp = &term.line[n][0];
2699         end = &bp[MIN(tlinelen(n), term.col) - 1];
2700         if (bp != end || bp->u != ' ') {
2701                 for ( ;bp <= end; ++bp)
2702                         tprinter(buf, utf8encode(bp->u, buf));
2703         }
2704         tprinter("\n", 1);
2705 }
2706
2707 void
2708 tdump(void)
2709 {
2710         int i;
2711
2712         for (i = 0; i < term.row; ++i)
2713                 tdumpline(i);
2714 }
2715
2716 void
2717 tputtab(int n)
2718 {
2719         uint x = term.c.x;
2720
2721         if (n > 0) {
2722                 while (x < term.col && n--)
2723                         for (++x; x < term.col && !term.tabs[x]; ++x)
2724                                 /* nothing */ ;
2725         } else if (n < 0) {
2726                 while (x > 0 && n++)
2727                         for (--x; x > 0 && !term.tabs[x]; --x)
2728                                 /* nothing */ ;
2729         }
2730         term.c.x = LIMIT(x, 0, term.col-1);
2731 }
2732
2733 void
2734 techo(Rune u)
2735 {
2736         if (ISCONTROL(u)) { /* control code */
2737                 if (u & 0x80) {
2738                         u &= 0x7f;
2739                         tputc('^');
2740                         tputc('[');
2741                 } else if (u != '\n' && u != '\r' && u != '\t') {
2742                         u ^= 0x40;
2743                         tputc('^');
2744                 }
2745         }
2746         tputc(u);
2747 }
2748
2749 void
2750 tdefutf8(char ascii)
2751 {
2752         if (ascii == 'G')
2753                 term.mode |= MODE_UTF8;
2754         else if (ascii == '@')
2755                 term.mode &= ~MODE_UTF8;
2756 }
2757
2758 void
2759 tdeftran(char ascii)
2760 {
2761         static char cs[] = "0B";
2762         static int vcs[] = {CS_GRAPHIC0, CS_USA};
2763         char *p;
2764
2765         if ((p = strchr(cs, ascii)) == NULL) {
2766                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2767         } else {
2768                 term.trantbl[term.icharset] = vcs[p - cs];
2769         }
2770 }
2771
2772 void
2773 tdectest(char c)
2774 {
2775         int x, y;
2776
2777         if (c == '8') { /* DEC screen alignment test. */
2778                 for (x = 0; x < term.col; ++x) {
2779                         for (y = 0; y < term.row; ++y)
2780                                 tsetchar('E', &term.c.attr, x, y);
2781                 }
2782         }
2783 }
2784
2785 void
2786 tstrsequence(uchar c)
2787 {
2788         strreset();
2789
2790         switch (c) {
2791         case 0x90:   /* DCS -- Device Control String */
2792                 c = 'P';
2793                 term.esc |= ESC_DCS;
2794                 break;
2795         case 0x9f:   /* APC -- Application Program Command */
2796                 c = '_';
2797                 break;
2798         case 0x9e:   /* PM -- Privacy Message */
2799                 c = '^';
2800                 break;
2801         case 0x9d:   /* OSC -- Operating System Command */
2802                 c = ']';
2803                 break;
2804         }
2805         strescseq.type = c;
2806         term.esc |= ESC_STR;
2807 }
2808
2809 void
2810 tcontrolcode(uchar ascii)
2811 {
2812         switch (ascii) {
2813         case '\t':   /* HT */
2814                 tputtab(1);
2815                 return;
2816         case '\b':   /* BS */
2817                 tmoveto(term.c.x-1, term.c.y);
2818                 return;
2819         case '\r':   /* CR */
2820                 tmoveto(0, term.c.y);
2821                 return;
2822         case '\f':   /* LF */
2823         case '\v':   /* VT */
2824         case '\n':   /* LF */
2825                 /* go to first col if the mode is set */
2826                 tnewline(IS_SET(MODE_CRLF));
2827                 return;
2828         case '\a':   /* BEL */
2829                 if (term.esc & ESC_STR_END) {
2830                         /* backwards compatibility to xterm */
2831                         strhandle();
2832                 } else {
2833                         if (!(xw.state & WIN_FOCUSED))
2834                                 xseturgency(1);
2835                         if (bellvolume)
2836                                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2837                 }
2838                 break;
2839         case '\033': /* ESC */
2840                 csireset();
2841                 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2842                 term.esc |= ESC_START;
2843                 return;
2844         case '\016': /* SO (LS1 -- Locking shift 1) */
2845         case '\017': /* SI (LS0 -- Locking shift 0) */
2846                 term.charset = 1 - (ascii - '\016');
2847                 return;
2848         case '\032': /* SUB */
2849                 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2850         case '\030': /* CAN */
2851                 csireset();
2852                 break;
2853         case '\005': /* ENQ (IGNORED) */
2854         case '\000': /* NUL (IGNORED) */
2855         case '\021': /* XON (IGNORED) */
2856         case '\023': /* XOFF (IGNORED) */
2857         case 0177:   /* DEL (IGNORED) */
2858                 return;
2859         case 0x80:   /* TODO: PAD */
2860         case 0x81:   /* TODO: HOP */
2861         case 0x82:   /* TODO: BPH */
2862         case 0x83:   /* TODO: NBH */
2863         case 0x84:   /* TODO: IND */
2864                 break;
2865         case 0x85:   /* NEL -- Next line */
2866                 tnewline(1); /* always go to first col */
2867                 break;
2868         case 0x86:   /* TODO: SSA */
2869         case 0x87:   /* TODO: ESA */
2870                 break;
2871         case 0x88:   /* HTS -- Horizontal tab stop */
2872                 term.tabs[term.c.x] = 1;
2873                 break;
2874         case 0x89:   /* TODO: HTJ */
2875         case 0x8a:   /* TODO: VTS */
2876         case 0x8b:   /* TODO: PLD */
2877         case 0x8c:   /* TODO: PLU */
2878         case 0x8d:   /* TODO: RI */
2879         case 0x8e:   /* TODO: SS2 */
2880         case 0x8f:   /* TODO: SS3 */
2881         case 0x91:   /* TODO: PU1 */
2882         case 0x92:   /* TODO: PU2 */
2883         case 0x93:   /* TODO: STS */
2884         case 0x94:   /* TODO: CCH */
2885         case 0x95:   /* TODO: MW */
2886         case 0x96:   /* TODO: SPA */
2887         case 0x97:   /* TODO: EPA */
2888         case 0x98:   /* TODO: SOS */
2889         case 0x99:   /* TODO: SGCI */
2890                 break;
2891         case 0x9a:   /* DECID -- Identify Terminal */
2892                 ttywrite(vtiden, sizeof(vtiden) - 1);
2893                 break;
2894         case 0x9b:   /* TODO: CSI */
2895         case 0x9c:   /* TODO: ST */
2896                 break;
2897         case 0x90:   /* DCS -- Device Control String */
2898         case 0x9d:   /* OSC -- Operating System Command */
2899         case 0x9e:   /* PM -- Privacy Message */
2900         case 0x9f:   /* APC -- Application Program Command */
2901                 tstrsequence(ascii);
2902                 return;
2903         }
2904         /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2905         term.esc &= ~(ESC_STR_END|ESC_STR);
2906 }
2907
2908 /*
2909  * returns 1 when the sequence is finished and it hasn't to read
2910  * more characters for this sequence, otherwise 0
2911  */
2912 int
2913 eschandle(uchar ascii)
2914 {
2915         switch (ascii) {
2916         case '[':
2917                 term.esc |= ESC_CSI;
2918                 return 0;
2919         case '#':
2920                 term.esc |= ESC_TEST;
2921                 return 0;
2922         case '%':
2923                 term.esc |= ESC_UTF8;
2924                 return 0;
2925         case 'P': /* DCS -- Device Control String */
2926         case '_': /* APC -- Application Program Command */
2927         case '^': /* PM -- Privacy Message */
2928         case ']': /* OSC -- Operating System Command */
2929         case 'k': /* old title set compatibility */
2930                 tstrsequence(ascii);
2931                 return 0;
2932         case 'n': /* LS2 -- Locking shift 2 */
2933         case 'o': /* LS3 -- Locking shift 3 */
2934                 term.charset = 2 + (ascii - 'n');
2935                 break;
2936         case '(': /* GZD4 -- set primary charset G0 */
2937         case ')': /* G1D4 -- set secondary charset G1 */
2938         case '*': /* G2D4 -- set tertiary charset G2 */
2939         case '+': /* G3D4 -- set quaternary charset G3 */
2940                 term.icharset = ascii - '(';
2941                 term.esc |= ESC_ALTCHARSET;
2942                 return 0;
2943         case 'D': /* IND -- Linefeed */
2944                 if (term.c.y == term.bot) {
2945                         tscrollup(term.top, 1);
2946                 } else {
2947                         tmoveto(term.c.x, term.c.y+1);
2948                 }
2949                 break;
2950         case 'E': /* NEL -- Next line */
2951                 tnewline(1); /* always go to first col */
2952                 break;
2953         case 'H': /* HTS -- Horizontal tab stop */
2954                 term.tabs[term.c.x] = 1;
2955                 break;
2956         case 'M': /* RI -- Reverse index */
2957                 if (term.c.y == term.top) {
2958                         tscrolldown(term.top, 1);
2959                 } else {
2960                         tmoveto(term.c.x, term.c.y-1);
2961                 }
2962                 break;
2963         case 'Z': /* DECID -- Identify Terminal */
2964                 ttywrite(vtiden, sizeof(vtiden) - 1);
2965                 break;
2966         case 'c': /* RIS -- Reset to inital state */
2967                 treset();
2968                 xresettitle();
2969                 xloadcols();
2970                 break;
2971         case '=': /* DECPAM -- Application keypad */
2972                 term.mode |= MODE_APPKEYPAD;
2973                 break;
2974         case '>': /* DECPNM -- Normal keypad */
2975                 term.mode &= ~MODE_APPKEYPAD;
2976                 break;
2977         case '7': /* DECSC -- Save Cursor */
2978                 tcursor(CURSOR_SAVE);
2979                 break;
2980         case '8': /* DECRC -- Restore Cursor */
2981                 tcursor(CURSOR_LOAD);
2982                 break;
2983         case '\\': /* ST -- String Terminator */
2984                 if (term.esc & ESC_STR_END)
2985                         strhandle();
2986                 break;
2987         default:
2988                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2989                         (uchar) ascii, isprint(ascii)? ascii:'.');
2990                 break;
2991         }
2992         return 1;
2993 }
2994
2995 void
2996 tputc(Rune u)
2997 {
2998         char c[UTF_SIZ];
2999         int control;
3000         int width, len;
3001         Glyph *gp;
3002
3003         control = ISCONTROL(u);
3004         if (!IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
3005                 c[0] = u;
3006                 width = len = 1;
3007         } else {
3008                 len = utf8encode(u, c);
3009                 if (!control && (width = wcwidth(u)) == -1) {
3010                         memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
3011                         width = 1;
3012                 }
3013         }
3014
3015         if (IS_SET(MODE_PRINT))
3016                 tprinter(c, len);
3017
3018         /*
3019          * STR sequence must be checked before anything else
3020          * because it uses all following characters until it
3021          * receives a ESC, a SUB, a ST or any other C1 control
3022          * character.
3023          */
3024         if (term.esc & ESC_STR) {
3025                 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
3026                    ISCONTROLC1(u)) {
3027                         term.esc &= ~(ESC_START|ESC_STR|ESC_DCS);
3028                         if (IS_SET(MODE_SIXEL)) {
3029                                 /* TODO: render sixel */;
3030                                 term.mode &= ~MODE_SIXEL;
3031                                 return;
3032                         }
3033                         term.esc |= ESC_STR_END;
3034                         goto check_control_code;
3035                 }
3036
3037
3038                 if (IS_SET(MODE_SIXEL)) {
3039                         /* TODO: implement sixel mode */
3040                         return;
3041                 }
3042                 if (term.esc&ESC_DCS && strescseq.len == 0 && u == 'q')
3043                         term.mode |= MODE_SIXEL;
3044
3045                 if (strescseq.len+len >= sizeof(strescseq.buf)-1) {
3046                         /*
3047                          * Here is a bug in terminals. If the user never sends
3048                          * some code to stop the str or esc command, then st
3049                          * will stop responding. But this is better than
3050                          * silently failing with unknown characters. At least
3051                          * then users will report back.
3052                          *
3053                          * In the case users ever get fixed, here is the code:
3054                          */
3055                         /*
3056                          * term.esc = 0;
3057                          * strhandle();
3058                          */
3059                         return;
3060                 }
3061
3062                 memmove(&strescseq.buf[strescseq.len], c, len);
3063                 strescseq.len += len;
3064                 return;
3065         }
3066
3067 check_control_code:
3068         /*
3069          * Actions of control codes must be performed as soon they arrive
3070          * because they can be embedded inside a control sequence, and
3071          * they must not cause conflicts with sequences.
3072          */
3073         if (control) {
3074                 tcontrolcode(u);
3075                 /*
3076                  * control codes are not shown ever
3077                  */
3078                 return;
3079         } else if (term.esc & ESC_START) {
3080                 if (term.esc & ESC_CSI) {
3081                         csiescseq.buf[csiescseq.len++] = u;
3082                         if (BETWEEN(u, 0x40, 0x7E)
3083                                         || csiescseq.len >= \
3084                                         sizeof(csiescseq.buf)-1) {
3085                                 term.esc = 0;
3086                                 csiparse();
3087                                 csihandle();
3088                         }
3089                         return;
3090                 } else if (term.esc & ESC_UTF8) {
3091                         tdefutf8(u);
3092                 } else if (term.esc & ESC_ALTCHARSET) {
3093                         tdeftran(u);
3094                 } else if (term.esc & ESC_TEST) {
3095                         tdectest(u);
3096                 } else {
3097                         if (!eschandle(u))
3098                                 return;
3099                         /* sequence already finished */
3100                 }
3101                 term.esc = 0;
3102                 /*
3103                  * All characters which form part of a sequence are not
3104                  * printed
3105                  */
3106                 return;
3107         }
3108         if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
3109                 selclear(NULL);
3110
3111         gp = &term.line[term.c.y][term.c.x];
3112         if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
3113                 gp->mode |= ATTR_WRAP;
3114                 tnewline(1);
3115                 gp = &term.line[term.c.y][term.c.x];
3116         }
3117
3118         if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
3119                 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
3120
3121         if (term.c.x+width > term.col) {
3122                 tnewline(1);
3123                 gp = &term.line[term.c.y][term.c.x];
3124         }
3125
3126         tsetchar(u, &term.c.attr, term.c.x, term.c.y);
3127
3128         if (width == 2) {
3129                 gp->mode |= ATTR_WIDE;
3130                 if (term.c.x+1 < term.col) {
3131                         gp[1].u = '\0';
3132                         gp[1].mode = ATTR_WDUMMY;
3133                 }
3134         }
3135         if (term.c.x+width < term.col) {
3136                 tmoveto(term.c.x+width, term.c.y);
3137         } else {
3138                 term.c.state |= CURSOR_WRAPNEXT;
3139         }
3140 }
3141
3142 void
3143 tresize(int col, int row)
3144 {
3145         int i;
3146         int minrow = MIN(row, term.row);
3147         int mincol = MIN(col, term.col);
3148         int *bp;
3149         TCursor c;
3150
3151         if (col < 1 || row < 1) {
3152                 fprintf(stderr,
3153                         "tresize: error resizing to %dx%d\n", col, row);
3154                 return;
3155         }
3156
3157         /*
3158          * slide screen to keep cursor where we expect it -
3159          * tscrollup would work here, but we can optimize to
3160          * memmove because we're freeing the earlier lines
3161          */
3162         for (i = 0; i <= term.c.y - row; i++) {
3163                 free(term.line[i]);
3164                 free(term.alt[i]);
3165         }
3166         /* ensure that both src and dst are not NULL */
3167         if (i > 0) {
3168                 memmove(term.line, term.line + i, row * sizeof(Line));
3169                 memmove(term.alt, term.alt + i, row * sizeof(Line));
3170         }
3171         for (i += row; i < term.row; i++) {
3172                 free(term.line[i]);
3173                 free(term.alt[i]);
3174         }
3175
3176         /* resize to new width */
3177         term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
3178
3179         /* resize to new height */
3180         term.line = xrealloc(term.line, row * sizeof(Line));
3181         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
3182         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
3183         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
3184
3185         /* resize each row to new width, zero-pad if needed */
3186         for (i = 0; i < minrow; i++) {
3187                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
3188                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
3189         }
3190
3191         /* allocate any new rows */
3192         for (/* i == minrow */; i < row; i++) {
3193                 term.line[i] = xmalloc(col * sizeof(Glyph));
3194                 term.alt[i] = xmalloc(col * sizeof(Glyph));
3195         }
3196         if (col > term.col) {
3197                 bp = term.tabs + term.col;
3198
3199                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
3200                 while (--bp > term.tabs && !*bp)
3201                         /* nothing */ ;
3202                 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
3203                         *bp = 1;
3204         }
3205         /* update terminal size */
3206         term.col = col;
3207         term.row = row;
3208         /* reset scrolling region */
3209         tsetscroll(0, row-1);
3210         /* make use of the LIMIT in tmoveto */
3211         tmoveto(term.c.x, term.c.y);
3212         /* Clearing both screens (it makes dirty all lines) */
3213         c = term.c;
3214         for (i = 0; i < 2; i++) {
3215                 if (mincol < col && 0 < minrow) {
3216                         tclearregion(mincol, 0, col - 1, minrow - 1);
3217                 }
3218                 if (0 < col && minrow < row) {
3219                         tclearregion(0, minrow, col - 1, row - 1);
3220                 }
3221                 tswapscreen();
3222                 tcursor(CURSOR_LOAD);
3223         }
3224         term.c = c;
3225 }
3226
3227 void
3228 xresize(int col, int row)
3229 {
3230         xw.tw = MAX(1, col * xw.cw);
3231         xw.th = MAX(1, row * xw.ch);
3232
3233         XFreePixmap(xw.dpy, xw.buf);
3234         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3235                         DefaultDepth(xw.dpy, xw.scr));
3236         XftDrawChange(xw.draw, xw.buf);
3237         xclear(0, 0, xw.w, xw.h);
3238 }
3239
3240 ushort
3241 sixd_to_16bit(int x)
3242 {
3243         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
3244 }
3245
3246 int
3247 xloadcolor(int i, const char *name, Color *ncolor)
3248 {
3249         XRenderColor color = { .alpha = 0xffff };
3250
3251         if (!name) {
3252                 if (BETWEEN(i, 16, 255)) { /* 256 color */
3253                         if (i < 6*6*6+16) { /* same colors as xterm */
3254                                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
3255                                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3256                                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
3257                         } else { /* greyscale */
3258                                 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3259                                 color.green = color.blue = color.red;
3260                         }
3261                         return XftColorAllocValue(xw.dpy, xw.vis,
3262                                                   xw.cmap, &color, ncolor);
3263                 } else
3264                         name = colorname[i];
3265         }
3266
3267         return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3268 }
3269
3270 void
3271 xloadcols(void)
3272 {
3273         int i;
3274         static int loaded;
3275         Color *cp;
3276
3277         if (loaded) {
3278                 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3279                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3280         }
3281
3282         for (i = 0; i < LEN(dc.col); i++)
3283                 if (!xloadcolor(i, NULL, &dc.col[i])) {
3284                         if (colorname[i])
3285                                 die("Could not allocate color '%s'\n", colorname[i]);
3286                         else
3287                                 die("Could not allocate color %d\n", i);
3288                 }
3289         loaded = 1;
3290 }
3291
3292 int
3293 xsetcolorname(int x, const char *name)
3294 {
3295         Color ncolor;
3296
3297         if (!BETWEEN(x, 0, LEN(dc.col)))
3298                 return 1;
3299
3300
3301         if (!xloadcolor(x, name, &ncolor))
3302                 return 1;
3303
3304         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3305         dc.col[x] = ncolor;
3306
3307         return 0;
3308 }
3309
3310 /*
3311  * Absolute coordinates.
3312  */
3313 void
3314 xclear(int x1, int y1, int x2, int y2)
3315 {
3316         XftDrawRect(xw.draw,
3317                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3318                         x1, y1, x2-x1, y2-y1);
3319 }
3320
3321 void
3322 xhints(void)
3323 {
3324         XClassHint class = {opt_name ? opt_name : termname,
3325                             opt_class ? opt_class : termname};
3326         XWMHints wm = {.flags = InputHint, .input = 1};
3327         XSizeHints *sizeh = NULL;
3328
3329         sizeh = XAllocSizeHints();
3330
3331         sizeh->flags = PSize | PResizeInc | PBaseSize;
3332         sizeh->height = xw.h;
3333         sizeh->width = xw.w;
3334         sizeh->height_inc = xw.ch;
3335         sizeh->width_inc = xw.cw;
3336         sizeh->base_height = 2 * borderpx;
3337         sizeh->base_width = 2 * borderpx;
3338         if (xw.isfixed) {
3339                 sizeh->flags |= PMaxSize | PMinSize;
3340                 sizeh->min_width = sizeh->max_width = xw.w;
3341                 sizeh->min_height = sizeh->max_height = xw.h;
3342         }
3343         if (xw.gm & (XValue|YValue)) {
3344                 sizeh->flags |= USPosition | PWinGravity;
3345                 sizeh->x = xw.l;
3346                 sizeh->y = xw.t;
3347                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3348         }
3349
3350         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3351                         &class);
3352         XFree(sizeh);
3353 }
3354
3355 int
3356 xgeommasktogravity(int mask)
3357 {
3358         switch (mask & (XNegative|YNegative)) {
3359         case 0:
3360                 return NorthWestGravity;
3361         case XNegative:
3362                 return NorthEastGravity;
3363         case YNegative:
3364                 return SouthWestGravity;
3365         }
3366
3367         return SouthEastGravity;
3368 }
3369
3370 int
3371 xloadfont(Font *f, FcPattern *pattern)
3372 {
3373         FcPattern *match;
3374         FcResult result;
3375         XGlyphInfo extents;
3376
3377         match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
3378         if (!match)
3379                 return 1;
3380
3381         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3382                 FcPatternDestroy(match);
3383                 return 1;
3384         }
3385
3386         XftTextExtentsUtf8(xw.dpy, f->match,
3387                 (const FcChar8 *) ascii_printable,
3388                 strlen(ascii_printable), &extents);
3389
3390         f->set = NULL;
3391         f->pattern = FcPatternDuplicate(pattern);
3392
3393         f->ascent = f->match->ascent;
3394         f->descent = f->match->descent;
3395         f->lbearing = 0;
3396         f->rbearing = f->match->max_advance_width;
3397
3398         f->height = f->ascent + f->descent;
3399         f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
3400
3401         return 0;
3402 }
3403
3404 void
3405 xloadfonts(char *fontstr, double fontsize)
3406 {
3407         FcPattern *pattern;
3408         double fontval;
3409         float ceilf(float);
3410
3411         if (fontstr[0] == '-') {
3412                 pattern = XftXlfdParse(fontstr, False, False);
3413         } else {
3414                 pattern = FcNameParse((FcChar8 *)fontstr);
3415         }
3416
3417         if (!pattern)
3418                 die("st: can't open font %s\n", fontstr);
3419
3420         if (fontsize > 1) {
3421                 FcPatternDel(pattern, FC_PIXEL_SIZE);
3422                 FcPatternDel(pattern, FC_SIZE);
3423                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3424                 usedfontsize = fontsize;
3425         } else {
3426                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3427                                 FcResultMatch) {
3428                         usedfontsize = fontval;
3429                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3430                                 FcResultMatch) {
3431                         usedfontsize = -1;
3432                 } else {
3433                         /*
3434                          * Default font size is 12, if none given. This is to
3435                          * have a known usedfontsize value.
3436                          */
3437                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3438                         usedfontsize = 12;
3439                 }
3440                 defaultfontsize = usedfontsize;
3441         }
3442
3443         if (xloadfont(&dc.font, pattern))
3444                 die("st: can't open font %s\n", fontstr);
3445
3446         if (usedfontsize < 0) {
3447                 FcPatternGetDouble(dc.font.match->pattern,
3448                                    FC_PIXEL_SIZE, 0, &fontval);
3449                 usedfontsize = fontval;
3450                 if (fontsize == 0)
3451                         defaultfontsize = fontval;
3452         }
3453
3454         /* Setting character width and height. */
3455         xw.cw = ceilf(dc.font.width * cwscale);
3456         xw.ch = ceilf(dc.font.height * chscale);
3457
3458         FcPatternDel(pattern, FC_SLANT);
3459         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3460         if (xloadfont(&dc.ifont, pattern))
3461                 die("st: can't open font %s\n", fontstr);
3462
3463         FcPatternDel(pattern, FC_WEIGHT);
3464         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3465         if (xloadfont(&dc.ibfont, pattern))
3466                 die("st: can't open font %s\n", fontstr);
3467
3468         FcPatternDel(pattern, FC_SLANT);
3469         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3470         if (xloadfont(&dc.bfont, pattern))
3471                 die("st: can't open font %s\n", fontstr);
3472
3473         FcPatternDestroy(pattern);
3474 }
3475
3476 void
3477 xunloadfont(Font *f)
3478 {
3479         XftFontClose(xw.dpy, f->match);
3480         FcPatternDestroy(f->pattern);
3481         if (f->set)
3482                 FcFontSetDestroy(f->set);
3483 }
3484
3485 void
3486 xunloadfonts(void)
3487 {
3488         /* Free the loaded fonts in the font cache.  */
3489         while (frclen > 0)
3490                 XftFontClose(xw.dpy, frc[--frclen].font);
3491
3492         xunloadfont(&dc.font);
3493         xunloadfont(&dc.bfont);
3494         xunloadfont(&dc.ifont);
3495         xunloadfont(&dc.ibfont);
3496 }
3497
3498 void
3499 xzoom(const Arg *arg)
3500 {
3501         Arg larg;
3502
3503         larg.f = usedfontsize + arg->f;
3504         xzoomabs(&larg);
3505 }
3506
3507 void
3508 xzoomabs(const Arg *arg)
3509 {
3510         xunloadfonts();
3511         xloadfonts(usedfont, arg->f);
3512         cresize(0, 0);
3513         ttyresize();
3514         redraw();
3515         xhints();
3516 }
3517
3518 void
3519 xzoomreset(const Arg *arg)
3520 {
3521         Arg larg;
3522
3523         if (defaultfontsize > 0) {
3524                 larg.f = defaultfontsize;
3525                 xzoomabs(&larg);
3526         }
3527 }
3528
3529 void
3530 xinit(void)
3531 {
3532         XGCValues gcvalues;
3533         Cursor cursor;
3534         Window parent;
3535         pid_t thispid = getpid();
3536         XColor xmousefg, xmousebg;
3537
3538         if (!(xw.dpy = XOpenDisplay(NULL)))
3539                 die("Can't open display\n");
3540         xw.scr = XDefaultScreen(xw.dpy);
3541         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3542
3543         /* font */
3544         if (!FcInit())
3545                 die("Could not init fontconfig.\n");
3546
3547         usedfont = (opt_font == NULL)? font : opt_font;
3548         xloadfonts(usedfont, 0);
3549
3550         /* colors */
3551         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3552         xloadcols();
3553
3554         /* adjust fixed window geometry */
3555         xw.w = 2 * borderpx + term.col * xw.cw;
3556         xw.h = 2 * borderpx + term.row * xw.ch;
3557         if (xw.gm & XNegative)
3558                 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3559         if (xw.gm & YNegative)
3560                 xw.t += DisplayHeight(xw.dpy, xw.scr) - xw.h - 2;
3561
3562         /* Events */
3563         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3564         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3565         xw.attrs.bit_gravity = NorthWestGravity;
3566         xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3567                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3568                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3569         xw.attrs.colormap = xw.cmap;
3570
3571         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3572                 parent = XRootWindow(xw.dpy, xw.scr);
3573         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3574                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3575                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3576                         | CWEventMask | CWColormap, &xw.attrs);
3577
3578         memset(&gcvalues, 0, sizeof(gcvalues));
3579         gcvalues.graphics_exposures = False;
3580         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3581                         &gcvalues);
3582         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3583                         DefaultDepth(xw.dpy, xw.scr));
3584         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3585         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3586
3587         /* Xft rendering context */
3588         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3589
3590         /* input methods */
3591         if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3592                 XSetLocaleModifiers("@im=local");
3593                 if ((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3594                         XSetLocaleModifiers("@im=");
3595                         if ((xw.xim = XOpenIM(xw.dpy,
3596                                         NULL, NULL, NULL)) == NULL) {
3597                                 die("XOpenIM failed. Could not open input"
3598                                         " device.\n");
3599                         }
3600                 }
3601         }
3602         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3603                                            | XIMStatusNothing, XNClientWindow, xw.win,
3604                                            XNFocusWindow, xw.win, NULL);
3605         if (xw.xic == NULL)
3606                 die("XCreateIC failed. Could not obtain input method.\n");
3607
3608         /* white cursor, black outline */
3609         cursor = XCreateFontCursor(xw.dpy, mouseshape);
3610         XDefineCursor(xw.dpy, xw.win, cursor);
3611
3612         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
3613                 xmousefg.red   = 0xffff;
3614                 xmousefg.green = 0xffff;
3615                 xmousefg.blue  = 0xffff;
3616         }
3617
3618         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
3619                 xmousebg.red   = 0x0000;
3620                 xmousebg.green = 0x0000;
3621                 xmousebg.blue  = 0x0000;
3622         }
3623
3624         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
3625
3626         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3627         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3628         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3629         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3630
3631         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3632         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3633                         PropModeReplace, (uchar *)&thispid, 1);
3634
3635         xresettitle();
3636         XMapWindow(xw.dpy, xw.win);
3637         xhints();
3638         XSync(xw.dpy, False);
3639 }
3640
3641 int
3642 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3643 {
3644         float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3645         ushort mode, prevmode = USHRT_MAX;
3646         Font *font = &dc.font;
3647         int frcflags = FRC_NORMAL;
3648         float runewidth = xw.cw;
3649         Rune rune;
3650         FT_UInt glyphidx;
3651         FcResult fcres;
3652         FcPattern *fcpattern, *fontpattern;
3653         FcFontSet *fcsets[] = { NULL };
3654         FcCharSet *fccharset;
3655         int i, f, numspecs = 0;
3656
3657         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3658                 /* Fetch rune and mode for current glyph. */
3659                 rune = glyphs[i].u;
3660                 mode = glyphs[i].mode;
3661
3662                 /* Skip dummy wide-character spacing. */
3663                 if (mode == ATTR_WDUMMY)
3664                         continue;
3665
3666                 /* Determine font for glyph if different from previous glyph. */
3667                 if (prevmode != mode) {
3668                         prevmode = mode;
3669                         font = &dc.font;
3670                         frcflags = FRC_NORMAL;
3671                         runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3672                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3673                                 font = &dc.ibfont;
3674                                 frcflags = FRC_ITALICBOLD;
3675                         } else if (mode & ATTR_ITALIC) {
3676                                 font = &dc.ifont;
3677                                 frcflags = FRC_ITALIC;
3678                         } else if (mode & ATTR_BOLD) {
3679                                 font = &dc.bfont;
3680                                 frcflags = FRC_BOLD;
3681                         }
3682                         yp = winy + font->ascent;
3683                 }
3684
3685                 /* Lookup character index with default font. */
3686                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3687                 if (glyphidx) {
3688                         specs[numspecs].font = font->match;
3689                         specs[numspecs].glyph = glyphidx;
3690                         specs[numspecs].x = (short)xp;
3691                         specs[numspecs].y = (short)yp;
3692                         xp += runewidth;
3693                         numspecs++;
3694                         continue;
3695                 }
3696
3697                 /* Fallback on font cache, search the font cache for match. */
3698                 for (f = 0; f < frclen; f++) {
3699                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3700                         /* Everything correct. */
3701                         if (glyphidx && frc[f].flags == frcflags)
3702                                 break;
3703                         /* We got a default font for a not found glyph. */
3704                         if (!glyphidx && frc[f].flags == frcflags
3705                                         && frc[f].unicodep == rune) {
3706                                 break;
3707                         }
3708                 }
3709
3710                 /* Nothing was found. Use fontconfig to find matching font. */
3711                 if (f >= frclen) {
3712                         if (!font->set)
3713                                 font->set = FcFontSort(0, font->pattern,
3714                                                        1, 0, &fcres);
3715                         fcsets[0] = font->set;
3716
3717                         /*
3718                          * Nothing was found in the cache. Now use
3719                          * some dozen of Fontconfig calls to get the
3720                          * font for one single character.
3721                          *
3722                          * Xft and fontconfig are design failures.
3723                          */
3724                         fcpattern = FcPatternDuplicate(font->pattern);
3725                         fccharset = FcCharSetCreate();
3726
3727                         FcCharSetAddChar(fccharset, rune);
3728                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3729                                         fccharset);
3730                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3731
3732                         FcConfigSubstitute(0, fcpattern,
3733                                         FcMatchPattern);
3734                         FcDefaultSubstitute(fcpattern);
3735
3736                         fontpattern = FcFontSetMatch(0, fcsets, 1,
3737                                         fcpattern, &fcres);
3738
3739                         /*
3740                          * Overwrite or create the new cache entry.
3741                          */
3742                         if (frclen >= LEN(frc)) {
3743                                 frclen = LEN(frc) - 1;
3744                                 XftFontClose(xw.dpy, frc[frclen].font);
3745                                 frc[frclen].unicodep = 0;
3746                         }
3747
3748                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
3749                                         fontpattern);
3750                         frc[frclen].flags = frcflags;
3751                         frc[frclen].unicodep = rune;
3752
3753                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3754
3755                         f = frclen;
3756                         frclen++;
3757
3758                         FcPatternDestroy(fcpattern);
3759                         FcCharSetDestroy(fccharset);
3760                 }
3761
3762                 specs[numspecs].font = frc[f].font;
3763                 specs[numspecs].glyph = glyphidx;
3764                 specs[numspecs].x = (short)xp;
3765                 specs[numspecs].y = (short)yp;
3766                 xp += runewidth;
3767                 numspecs++;
3768         }
3769
3770         return numspecs;
3771 }
3772
3773 void
3774 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3775 {
3776         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3777         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3778             width = charlen * xw.cw;
3779         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3780         XRenderColor colfg, colbg;
3781         XRectangle r;
3782
3783         /* Determine foreground and background colors based on mode. */
3784         if (base.fg == defaultfg) {
3785                 if (base.mode & ATTR_ITALIC)
3786                         base.fg = defaultitalic;
3787                 else if ((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3788                         base.fg = defaultitalic;
3789                 else if (base.mode & ATTR_UNDERLINE)
3790                         base.fg = defaultunderline;
3791         }
3792
3793         if (IS_TRUECOL(base.fg)) {
3794                 colfg.alpha = 0xffff;
3795                 colfg.red = TRUERED(base.fg);
3796                 colfg.green = TRUEGREEN(base.fg);
3797                 colfg.blue = TRUEBLUE(base.fg);
3798                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3799                 fg = &truefg;
3800         } else {
3801                 fg = &dc.col[base.fg];
3802         }
3803
3804         if (IS_TRUECOL(base.bg)) {
3805                 colbg.alpha = 0xffff;
3806                 colbg.green = TRUEGREEN(base.bg);
3807                 colbg.red = TRUERED(base.bg);
3808                 colbg.blue = TRUEBLUE(base.bg);
3809                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3810                 bg = &truebg;
3811         } else {
3812                 bg = &dc.col[base.bg];
3813         }
3814
3815         /* Change basic system colors [0-7] to bright system colors [8-15] */
3816         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3817                 fg = &dc.col[base.fg + 8];
3818
3819         if (IS_SET(MODE_REVERSE)) {
3820                 if (fg == &dc.col[defaultfg]) {
3821                         fg = &dc.col[defaultbg];
3822                 } else {
3823                         colfg.red = ~fg->color.red;
3824                         colfg.green = ~fg->color.green;
3825                         colfg.blue = ~fg->color.blue;
3826                         colfg.alpha = fg->color.alpha;
3827                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3828                                         &revfg);
3829                         fg = &revfg;
3830                 }
3831
3832                 if (bg == &dc.col[defaultbg]) {
3833                         bg = &dc.col[defaultfg];
3834                 } else {
3835                         colbg.red = ~bg->color.red;
3836                         colbg.green = ~bg->color.green;
3837                         colbg.blue = ~bg->color.blue;
3838                         colbg.alpha = bg->color.alpha;
3839                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3840                                         &revbg);
3841                         bg = &revbg;
3842                 }
3843         }
3844
3845         if (base.mode & ATTR_REVERSE) {
3846                 temp = fg;
3847                 fg = bg;
3848                 bg = temp;
3849         }
3850
3851         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3852                 colfg.red = fg->color.red / 2;
3853                 colfg.green = fg->color.green / 2;
3854                 colfg.blue = fg->color.blue / 2;
3855                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3856                 fg = &revfg;
3857         }
3858
3859         if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3860                 fg = bg;
3861
3862         if (base.mode & ATTR_INVISIBLE)
3863                 fg = bg;
3864
3865         /* Intelligent cleaning up of the borders. */
3866         if (x == 0) {
3867                 xclear(0, (y == 0)? 0 : winy, borderpx,
3868                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3869         }
3870         if (x + charlen >= term.col) {
3871                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3872                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3873         }
3874         if (y == 0)
3875                 xclear(winx, 0, winx + width, borderpx);
3876         if (y == term.row-1)
3877                 xclear(winx, winy + xw.ch, winx + width, xw.h);
3878
3879         /* Clean up the region we want to draw to. */
3880         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3881
3882         /* Set the clip region because Xft is sometimes dirty. */
3883         r.x = 0;
3884         r.y = 0;
3885         r.height = xw.ch;
3886         r.width = width;
3887         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3888
3889         /* Render the glyphs. */
3890         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3891
3892         /* Render underline and strikethrough. */
3893         if (base.mode & ATTR_UNDERLINE) {
3894                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3895                                 width, 1);
3896         }
3897
3898         if (base.mode & ATTR_STRUCK) {
3899                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3900                                 width, 1);
3901         }
3902
3903         /* Reset clip to none. */
3904         XftDrawSetClip(xw.draw, 0);
3905 }
3906
3907 void
3908 xdrawglyph(Glyph g, int x, int y)
3909 {
3910         int numspecs;
3911         XftGlyphFontSpec spec;
3912
3913         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3914         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3915 }
3916
3917 void
3918 xdrawcursor(void)
3919 {
3920         static int oldx = 0, oldy = 0;
3921         int curx;
3922         Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
3923         int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3924         Color drawcol;
3925
3926         LIMIT(oldx, 0, term.col-1);
3927         LIMIT(oldy, 0, term.row-1);
3928
3929         curx = term.c.x;
3930
3931         /* adjust position if in dummy */
3932         if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3933                 oldx--;
3934         if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3935                 curx--;
3936
3937         /* remove the old cursor */
3938         og = term.line[oldy][oldx];
3939         if (ena_sel && selected(oldx, oldy))
3940                 og.mode ^= ATTR_REVERSE;
3941         xdrawglyph(og, oldx, oldy);
3942
3943         g.u = term.line[term.c.y][term.c.x].u;
3944
3945         /*
3946          * Select the right color for the right mode.
3947          */
3948         if (IS_SET(MODE_REVERSE)) {
3949                 g.mode |= ATTR_REVERSE;
3950                 g.bg = defaultfg;
3951                 if (ena_sel && selected(term.c.x, term.c.y)) {
3952                         drawcol = dc.col[defaultcs];
3953                         g.fg = defaultrcs;
3954                 } else {
3955                         drawcol = dc.col[defaultrcs];
3956                         g.fg = defaultcs;
3957                 }
3958         } else {
3959                 if (ena_sel && selected(term.c.x, term.c.y)) {
3960                         drawcol = dc.col[defaultrcs];
3961                         g.fg = defaultfg;
3962                         g.bg = defaultrcs;
3963                 } else {
3964                         drawcol = dc.col[defaultcs];
3965                 }
3966         }
3967
3968         if (IS_SET(MODE_HIDE))
3969                 return;
3970
3971         /* draw the new one */
3972         if (xw.state & WIN_FOCUSED) {
3973                 switch (xw.cursor) {
3974                 case 7: /* st extension: snowman */
3975                         utf8decode("☃", &g.u, UTF_SIZ);
3976                 case 0: /* Blinking Block */
3977                 case 1: /* Blinking Block (Default) */
3978                 case 2: /* Steady Block */
3979                         g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3980                         xdrawglyph(g, term.c.x, term.c.y);
3981                         break;
3982                 case 3: /* Blinking Underline */
3983                 case 4: /* Steady Underline */
3984                         XftDrawRect(xw.draw, &drawcol,
3985                                         borderpx + curx * xw.cw,
3986                                         borderpx + (term.c.y + 1) * xw.ch - \
3987                                                 cursorthickness,
3988                                         xw.cw, cursorthickness);
3989                         break;
3990                 case 5: /* Blinking bar */
3991                 case 6: /* Steady bar */
3992                         XftDrawRect(xw.draw, &drawcol,
3993                                         borderpx + curx * xw.cw,
3994                                         borderpx + term.c.y * xw.ch,
3995                                         cursorthickness, xw.ch);
3996                         break;
3997                 }
3998         } else {
3999                 XftDrawRect(xw.draw, &drawcol,
4000                                 borderpx + curx * xw.cw,
4001                                 borderpx + term.c.y * xw.ch,
4002                                 xw.cw - 1, 1);
4003                 XftDrawRect(xw.draw, &drawcol,
4004                                 borderpx + curx * xw.cw,
4005                                 borderpx + term.c.y * xw.ch,
4006                                 1, xw.ch - 1);
4007                 XftDrawRect(xw.draw, &drawcol,
4008                                 borderpx + (curx + 1) * xw.cw - 1,
4009                                 borderpx + term.c.y * xw.ch,
4010                                 1, xw.ch - 1);
4011                 XftDrawRect(xw.draw, &drawcol,
4012                                 borderpx + curx * xw.cw,
4013                                 borderpx + (term.c.y + 1) * xw.ch - 1,
4014                                 xw.cw, 1);
4015         }
4016         oldx = curx, oldy = term.c.y;
4017 }
4018
4019
4020 void
4021 xsettitle(char *p)
4022 {
4023         XTextProperty prop;
4024
4025         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
4026                         &prop);
4027         XSetWMName(xw.dpy, xw.win, &prop);
4028         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
4029         XFree(prop.value);
4030 }
4031
4032 void
4033 xresettitle(void)
4034 {
4035         xsettitle(opt_title ? opt_title : "st");
4036 }
4037
4038 void
4039 redraw(void)
4040 {
4041         tfulldirt();
4042         draw();
4043 }
4044
4045 void
4046 draw(void)
4047 {
4048         drawregion(0, 0, term.col, term.row);
4049         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
4050                         xw.h, 0, 0);
4051         XSetForeground(xw.dpy, dc.gc,
4052                         dc.col[IS_SET(MODE_REVERSE)?
4053                                 defaultfg : defaultbg].pixel);
4054 }
4055
4056 void
4057 drawregion(int x1, int y1, int x2, int y2)
4058 {
4059         int i, x, y, ox, numspecs;
4060         Glyph base, new;
4061         XftGlyphFontSpec *specs;
4062         int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
4063
4064         if (!(xw.state & WIN_VISIBLE))
4065                 return;
4066
4067         for (y = y1; y < y2; y++) {
4068                 if (!term.dirty[y])
4069                         continue;
4070
4071                 term.dirty[y] = 0;
4072
4073                 specs = term.specbuf;
4074                 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
4075
4076                 i = ox = 0;
4077                 for (x = x1; x < x2 && i < numspecs; x++) {
4078                         new = term.line[y][x];
4079                         if (new.mode == ATTR_WDUMMY)
4080                                 continue;
4081                         if (ena_sel && selected(x, y))
4082                                 new.mode ^= ATTR_REVERSE;
4083                         if (i > 0 && ATTRCMP(base, new)) {
4084                                 xdrawglyphfontspecs(specs, base, i, ox, y);
4085                                 specs += i;
4086                                 numspecs -= i;
4087                                 i = 0;
4088                         }
4089                         if (i == 0) {
4090                                 ox = x;
4091                                 base = new;
4092                         }
4093                         i++;
4094                 }
4095                 if (i > 0)
4096                         xdrawglyphfontspecs(specs, base, i, ox, y);
4097         }
4098         xdrawcursor();
4099 }
4100
4101 void
4102 expose(XEvent *ev)
4103 {
4104         redraw();
4105 }
4106
4107 void
4108 visibility(XEvent *ev)
4109 {
4110         XVisibilityEvent *e = &ev->xvisibility;
4111
4112         MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
4113 }
4114
4115 void
4116 unmap(XEvent *ev)
4117 {
4118         xw.state &= ~WIN_VISIBLE;
4119 }
4120
4121 void
4122 xsetpointermotion(int set)
4123 {
4124         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
4125         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
4126 }
4127
4128 void
4129 xseturgency(int add)
4130 {
4131         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
4132
4133         MODBIT(h->flags, add, XUrgencyHint);
4134         XSetWMHints(xw.dpy, xw.win, h);
4135         XFree(h);
4136 }
4137
4138 void
4139 focus(XEvent *ev)
4140 {
4141         XFocusChangeEvent *e = &ev->xfocus;
4142
4143         if (e->mode == NotifyGrab)
4144                 return;
4145
4146         if (ev->type == FocusIn) {
4147                 XSetICFocus(xw.xic);
4148                 xw.state |= WIN_FOCUSED;
4149                 xseturgency(0);
4150                 if (IS_SET(MODE_FOCUS))
4151                         ttywrite("\033[I", 3);
4152         } else {
4153                 XUnsetICFocus(xw.xic);
4154                 xw.state &= ~WIN_FOCUSED;
4155                 if (IS_SET(MODE_FOCUS))
4156                         ttywrite("\033[O", 3);
4157         }
4158 }
4159
4160 int
4161 match(uint mask, uint state)
4162 {
4163         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
4164 }
4165
4166 void
4167 numlock(const Arg *dummy)
4168 {
4169         term.numlock ^= 1;
4170 }
4171
4172 char*
4173 kmap(KeySym k, uint state)
4174 {
4175         Key *kp;
4176         int i;
4177
4178         /* Check for mapped keys out of X11 function keys. */
4179         for (i = 0; i < LEN(mappedkeys); i++) {
4180                 if (mappedkeys[i] == k)
4181                         break;
4182         }
4183         if (i == LEN(mappedkeys)) {
4184                 if ((k & 0xFFFF) < 0xFD00)
4185                         return NULL;
4186         }
4187
4188         for (kp = key; kp < key + LEN(key); kp++) {
4189                 if (kp->k != k)
4190                         continue;
4191
4192                 if (!match(kp->mask, state))
4193                         continue;
4194
4195                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
4196                         continue;
4197                 if (term.numlock && kp->appkey == 2)
4198                         continue;
4199
4200                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
4201                         continue;
4202
4203                 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
4204                         continue;
4205
4206                 return kp->s;
4207         }
4208
4209         return NULL;
4210 }
4211
4212 void
4213 kpress(XEvent *ev)
4214 {
4215         XKeyEvent *e = &ev->xkey;
4216         KeySym ksym;
4217         char buf[32], *customkey;
4218         int len;
4219         Rune c;
4220         Status status;
4221         Shortcut *bp;
4222
4223         if (IS_SET(MODE_KBDLOCK))
4224                 return;
4225
4226         len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
4227         /* 1. shortcuts */
4228         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
4229                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
4230                         bp->func(&(bp->arg));
4231                         return;
4232                 }
4233         }
4234
4235         /* 2. custom keys from config.h */
4236         if ((customkey = kmap(ksym, e->state))) {
4237                 ttysend(customkey, strlen(customkey));
4238                 return;
4239         }
4240
4241         /* 3. composed string from input method */
4242         if (len == 0)
4243                 return;
4244         if (len == 1 && e->state & Mod1Mask) {
4245                 if (IS_SET(MODE_8BIT)) {
4246                         if (*buf < 0177) {
4247                                 c = *buf | 0x80;
4248                                 len = utf8encode(c, buf);
4249                         }
4250                 } else {
4251                         buf[1] = buf[0];
4252                         buf[0] = '\033';
4253                         len = 2;
4254                 }
4255         }
4256         ttysend(buf, len);
4257 }
4258
4259
4260 void
4261 cmessage(XEvent *e)
4262 {
4263         /*
4264          * See xembed specs
4265          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
4266          */
4267         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4268                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4269                         xw.state |= WIN_FOCUSED;
4270                         xseturgency(0);
4271                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4272                         xw.state &= ~WIN_FOCUSED;
4273                 }
4274         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
4275                 /* Send SIGHUP to shell */
4276                 kill(pid, SIGHUP);
4277                 exit(0);
4278         }
4279 }
4280
4281 void
4282 cresize(int width, int height)
4283 {
4284         int col, row;
4285
4286         if (width != 0)
4287                 xw.w = width;
4288         if (height != 0)
4289                 xw.h = height;
4290
4291         col = (xw.w - 2 * borderpx) / xw.cw;
4292         row = (xw.h - 2 * borderpx) / xw.ch;
4293
4294         tresize(col, row);
4295         xresize(col, row);
4296 }
4297
4298 void
4299 resize(XEvent *e)
4300 {
4301         if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4302                 return;
4303
4304         cresize(e->xconfigure.width, e->xconfigure.height);
4305         ttyresize();
4306 }
4307
4308 void
4309 run(void)
4310 {
4311         XEvent ev;
4312         int w = xw.w, h = xw.h;
4313         fd_set rfd;
4314         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4315         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4316         long deltatime;
4317
4318         /* Waiting for window mapping */
4319         do {
4320                 XNextEvent(xw.dpy, &ev);
4321                 /*
4322                  * This XFilterEvent call is required because of XOpenIM. It
4323                  * does filter out the key event and some client message for
4324                  * the input method too.
4325                  */
4326                 if (XFilterEvent(&ev, None))
4327                         continue;
4328                 if (ev.type == ConfigureNotify) {
4329                         w = ev.xconfigure.width;
4330                         h = ev.xconfigure.height;
4331                 }
4332         } while (ev.type != MapNotify);
4333
4334         cresize(w, h);
4335         ttynew();
4336         ttyresize();
4337
4338         clock_gettime(CLOCK_MONOTONIC, &last);
4339         lastblink = last;
4340
4341         for (xev = actionfps;;) {
4342                 FD_ZERO(&rfd);
4343                 FD_SET(cmdfd, &rfd);
4344                 FD_SET(xfd, &rfd);
4345
4346                 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4347                         if (errno == EINTR)
4348                                 continue;
4349                         die("select failed: %s\n", strerror(errno));
4350                 }
4351                 if (FD_ISSET(cmdfd, &rfd)) {
4352                         ttyread();
4353                         if (blinktimeout) {
4354                                 blinkset = tattrset(ATTR_BLINK);
4355                                 if (!blinkset)
4356                                         MODBIT(term.mode, 0, MODE_BLINK);
4357                         }
4358                 }
4359
4360                 if (FD_ISSET(xfd, &rfd))
4361                         xev = actionfps;
4362
4363                 clock_gettime(CLOCK_MONOTONIC, &now);
4364                 drawtimeout.tv_sec = 0;
4365                 drawtimeout.tv_nsec =  (1000 * 1E6)/ xfps;
4366                 tv = &drawtimeout;
4367
4368                 dodraw = 0;
4369                 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4370                         tsetdirtattr(ATTR_BLINK);
4371                         term.mode ^= MODE_BLINK;
4372                         lastblink = now;
4373                         dodraw = 1;
4374                 }
4375                 deltatime = TIMEDIFF(now, last);
4376                 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4377                         dodraw = 1;
4378                         last = now;
4379                 }
4380
4381                 if (dodraw) {
4382                         while (XPending(xw.dpy)) {
4383                                 XNextEvent(xw.dpy, &ev);
4384                                 if (XFilterEvent(&ev, None))
4385                                         continue;
4386                                 if (handler[ev.type])
4387                                         (handler[ev.type])(&ev);
4388                         }
4389
4390                         draw();
4391                         XFlush(xw.dpy);
4392
4393                         if (xev && !FD_ISSET(xfd, &rfd))
4394                                 xev--;
4395                         if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4396                                 if (blinkset) {
4397                                         if (TIMEDIFF(now, lastblink) \
4398                                                         > blinktimeout) {
4399                                                 drawtimeout.tv_nsec = 1000;
4400                                         } else {
4401                                                 drawtimeout.tv_nsec = (1E6 * \
4402                                                         (blinktimeout - \
4403                                                         TIMEDIFF(now,
4404                                                                 lastblink)));
4405                                         }
4406                                         drawtimeout.tv_sec = \
4407                                             drawtimeout.tv_nsec / 1E9;
4408                                         drawtimeout.tv_nsec %= (long)1E9;
4409                                 } else {
4410                                         tv = NULL;
4411                                 }
4412                         }
4413                 }
4414         }
4415 }
4416
4417 void
4418 usage(void)
4419 {
4420         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
4421             " [-n name] [-o file]\n"
4422             "          [-T title] [-t title] [-w windowid]"
4423             " [[-e] command [args ...]]\n"
4424             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
4425             " [-n name] [-o file]\n"
4426             "          [-T title] [-t title] [-w windowid] -l line"
4427             " [stty_args ...]\n", argv0, argv0);
4428 }
4429
4430 int
4431 main(int argc, char *argv[])
4432 {
4433         uint cols = 80, rows = 24;
4434
4435         xw.l = xw.t = 0;
4436         xw.isfixed = False;
4437         xw.cursor = cursorshape;
4438
4439         ARGBEGIN {
4440         case 'a':
4441                 allowaltscreen = 0;
4442                 break;
4443         case 'c':
4444                 opt_class = EARGF(usage());
4445                 break;
4446         case 'e':
4447                 if (argc > 0)
4448                         --argc, ++argv;
4449                 goto run;
4450         case 'f':
4451                 opt_font = EARGF(usage());
4452                 break;
4453         case 'g':
4454                 xw.gm = XParseGeometry(EARGF(usage()),
4455                                 &xw.l, &xw.t, &cols, &rows);
4456                 break;
4457         case 'i':
4458                 xw.isfixed = 1;
4459                 break;
4460         case 'o':
4461                 opt_io = EARGF(usage());
4462                 break;
4463         case 'l':
4464                 opt_line = EARGF(usage());
4465                 break;
4466         case 'n':
4467                 opt_name = EARGF(usage());
4468                 break;
4469         case 't':
4470         case 'T':
4471                 opt_title = EARGF(usage());
4472                 break;
4473         case 'w':
4474                 opt_embed = EARGF(usage());
4475                 break;
4476         case 'v':
4477                 die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
4478                 break;
4479         default:
4480                 usage();
4481         } ARGEND;
4482
4483 run:
4484         if (argc > 0) {
4485                 /* eat all remaining arguments */
4486                 opt_cmd = argv;
4487                 if (!opt_title && !opt_line)
4488                         opt_title = basename(xstrdup(argv[0]));
4489         }
4490         setlocale(LC_CTYPE, "");
4491         XSetLocaleModifiers("");
4492         tnew(MAX(cols, 1), MAX(rows, 1));
4493         xinit();
4494         selinit();
4495         run();
4496
4497         return 0;
4498 }
4499