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