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