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