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