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