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