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