Enforce a terminal size to reduce race conditions in too efficient apps.
[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 size_t 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         ttyresize();
1444
1445         switch (pid = fork()) {
1446         case -1:
1447                 die("fork failed\n");
1448                 break;
1449         case 0:
1450                 close(iofd);
1451                 setsid(); /* create a new process group */
1452                 dup2(s, 0);
1453                 dup2(s, 1);
1454                 dup2(s, 2);
1455                 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1456                         die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1457                 close(s);
1458                 close(m);
1459                 execsh();
1460                 break;
1461         default:
1462                 close(s);
1463                 cmdfd = m;
1464                 signal(SIGCHLD, sigchld);
1465                 break;
1466         }
1467 }
1468
1469 size_t
1470 ttyread(void)
1471 {
1472         static char buf[BUFSIZ];
1473         static int buflen = 0;
1474         char *ptr;
1475         int charsize; /* size of utf8 char in bytes */
1476         Rune unicodep;
1477         int ret;
1478
1479         /* append read bytes to unprocessed bytes */
1480         if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1481                 die("Couldn't read from shell: %s\n", strerror(errno));
1482
1483         /* process every complete utf8 char */
1484         buflen += ret;
1485         ptr = buf;
1486         while ((charsize = utf8decode(ptr, &unicodep, buflen))) {
1487                 tputc(unicodep);
1488                 ptr += charsize;
1489                 buflen -= charsize;
1490         }
1491
1492         /* keep any uncomplete utf8 char for the next call */
1493         memmove(buf, ptr, buflen);
1494
1495         return ret;
1496 }
1497
1498 void
1499 ttywrite(const char *s, size_t n)
1500 {
1501         fd_set wfd, rfd;
1502         ssize_t r;
1503         size_t lim = 256;
1504
1505         /*
1506          * Remember that we are using a pty, which might be a modem line.
1507          * Writing too much will clog the line. That's why we are doing this
1508          * dance.
1509          * FIXME: Migrate the world to Plan 9.
1510          */
1511         while (n > 0) {
1512                 FD_ZERO(&wfd);
1513                 FD_ZERO(&rfd);
1514                 FD_SET(cmdfd, &wfd);
1515                 FD_SET(cmdfd, &rfd);
1516
1517                 /* Check if we can write. */
1518                 if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) {
1519                         if (errno == EINTR)
1520                                 continue;
1521                         die("select failed: %s\n", strerror(errno));
1522                 }
1523                 if (FD_ISSET(cmdfd, &wfd)) {
1524                         /*
1525                          * Only write the bytes written by ttywrite() or the
1526                          * default of 256. This seems to be a reasonable value
1527                          * for a serial line. Bigger values might clog the I/O.
1528                          */
1529                         if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0)
1530                                 goto write_error;
1531                         if (r < n) {
1532                                 /*
1533                                  * We weren't able to write out everything.
1534                                  * This means the buffer is getting full
1535                                  * again. Empty it.
1536                                  */
1537                                 if (n < lim)
1538                                         lim = ttyread();
1539                                 n -= r;
1540                                 s += r;
1541                         } else {
1542                                 /* All bytes have been written. */
1543                                 break;
1544                         }
1545                 }
1546                 if (FD_ISSET(cmdfd, &rfd))
1547                         lim = ttyread();
1548         }
1549         return;
1550
1551 write_error:
1552         die("write error on tty: %s\n", strerror(errno));
1553 }
1554
1555 void
1556 ttysend(char *s, size_t n)
1557 {
1558         int len;
1559         Rune u;
1560
1561         ttywrite(s, n);
1562         if (IS_SET(MODE_ECHO))
1563                 while ((len = utf8decode(s, &u, n)) > 0) {
1564                         techo(u);
1565                         n -= len;
1566                         s += len;
1567                 }
1568 }
1569
1570 void
1571 ttyresize(void)
1572 {
1573         struct winsize w;
1574
1575         w.ws_row = term.row;
1576         w.ws_col = term.col;
1577         w.ws_xpixel = xw.tw;
1578         w.ws_ypixel = xw.th;
1579         if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1580                 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1581 }
1582
1583 int
1584 tattrset(int attr)
1585 {
1586         int i, j;
1587
1588         for (i = 0; i < term.row-1; i++) {
1589                 for (j = 0; j < term.col-1; j++) {
1590                         if (term.line[i][j].mode & attr)
1591                                 return 1;
1592                 }
1593         }
1594
1595         return 0;
1596 }
1597
1598 void
1599 tsetdirt(int top, int bot)
1600 {
1601         int i;
1602
1603         LIMIT(top, 0, term.row-1);
1604         LIMIT(bot, 0, term.row-1);
1605
1606         for (i = top; i <= bot; i++)
1607                 term.dirty[i] = 1;
1608 }
1609
1610 void
1611 tsetdirtattr(int attr)
1612 {
1613         int i, j;
1614
1615         for (i = 0; i < term.row-1; i++) {
1616                 for (j = 0; j < term.col-1; j++) {
1617                         if (term.line[i][j].mode & attr) {
1618                                 tsetdirt(i, i);
1619                                 break;
1620                         }
1621                 }
1622         }
1623 }
1624
1625 void
1626 tfulldirt(void)
1627 {
1628         tsetdirt(0, term.row-1);
1629 }
1630
1631 void
1632 tcursor(int mode)
1633 {
1634         static TCursor c[2];
1635         int alt = IS_SET(MODE_ALTSCREEN);
1636
1637         if (mode == CURSOR_SAVE) {
1638                 c[alt] = term.c;
1639         } else if (mode == CURSOR_LOAD) {
1640                 term.c = c[alt];
1641                 tmoveto(c[alt].x, c[alt].y);
1642         }
1643 }
1644
1645 void
1646 treset(void)
1647 {
1648         uint i;
1649
1650         term.c = (TCursor){{
1651                 .mode = ATTR_NULL,
1652                 .fg = defaultfg,
1653                 .bg = defaultbg
1654         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1655
1656         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1657         for (i = tabspaces; i < term.col; i += tabspaces)
1658                 term.tabs[i] = 1;
1659         term.top = 0;
1660         term.bot = term.row - 1;
1661         term.mode = MODE_WRAP;
1662         memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1663         term.charset = 0;
1664
1665         for (i = 0; i < 2; i++) {
1666                 tmoveto(0, 0);
1667                 tcursor(CURSOR_SAVE);
1668                 tclearregion(0, 0, term.col-1, term.row-1);
1669                 tswapscreen();
1670         }
1671 }
1672
1673 void
1674 tnew(int col, int row)
1675 {
1676         term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1677         tresize(col, row);
1678         term.numlock = 1;
1679
1680         treset();
1681 }
1682
1683 void
1684 tswapscreen(void)
1685 {
1686         Line *tmp = term.line;
1687
1688         term.line = term.alt;
1689         term.alt = tmp;
1690         term.mode ^= MODE_ALTSCREEN;
1691         tfulldirt();
1692 }
1693
1694 void
1695 tscrolldown(int orig, int n)
1696 {
1697         int i;
1698         Line temp;
1699
1700         LIMIT(n, 0, term.bot-orig+1);
1701
1702         tsetdirt(orig, term.bot-n);
1703         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1704
1705         for (i = term.bot; i >= orig+n; i--) {
1706                 temp = term.line[i];
1707                 term.line[i] = term.line[i-n];
1708                 term.line[i-n] = temp;
1709         }
1710
1711         selscroll(orig, n);
1712 }
1713
1714 void
1715 tscrollup(int orig, int n)
1716 {
1717         int i;
1718         Line temp;
1719
1720         LIMIT(n, 0, term.bot-orig+1);
1721
1722         tclearregion(0, orig, term.col-1, orig+n-1);
1723         tsetdirt(orig+n, term.bot);
1724
1725         for (i = orig; i <= term.bot-n; i++) {
1726                 temp = term.line[i];
1727                 term.line[i] = term.line[i+n];
1728                 term.line[i+n] = temp;
1729         }
1730
1731         selscroll(orig, -n);
1732 }
1733
1734 void
1735 selscroll(int orig, int n)
1736 {
1737         if (sel.ob.x == -1)
1738                 return;
1739
1740         if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1741                 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1742                         selclear(NULL);
1743                         return;
1744                 }
1745                 if (sel.type == SEL_RECTANGULAR) {
1746                         if (sel.ob.y < term.top)
1747                                 sel.ob.y = term.top;
1748                         if (sel.oe.y > term.bot)
1749                                 sel.oe.y = term.bot;
1750                 } else {
1751                         if (sel.ob.y < term.top) {
1752                                 sel.ob.y = term.top;
1753                                 sel.ob.x = 0;
1754                         }
1755                         if (sel.oe.y > term.bot) {
1756                                 sel.oe.y = term.bot;
1757                                 sel.oe.x = term.col;
1758                         }
1759                 }
1760                 selnormalize();
1761         }
1762 }
1763
1764 void
1765 tnewline(int first_col)
1766 {
1767         int y = term.c.y;
1768
1769         if (y == term.bot) {
1770                 tscrollup(term.top, 1);
1771         } else {
1772                 y++;
1773         }
1774         tmoveto(first_col ? 0 : term.c.x, y);
1775 }
1776
1777 void
1778 csiparse(void)
1779 {
1780         char *p = csiescseq.buf, *np;
1781         long int v;
1782
1783         csiescseq.narg = 0;
1784         if (*p == '?') {
1785                 csiescseq.priv = 1;
1786                 p++;
1787         }
1788
1789         csiescseq.buf[csiescseq.len] = '\0';
1790         while (p < csiescseq.buf+csiescseq.len) {
1791                 np = NULL;
1792                 v = strtol(p, &np, 10);
1793                 if (np == p)
1794                         v = 0;
1795                 if (v == LONG_MAX || v == LONG_MIN)
1796                         v = -1;
1797                 csiescseq.arg[csiescseq.narg++] = v;
1798                 p = np;
1799                 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1800                         break;
1801                 p++;
1802         }
1803         csiescseq.mode[0] = *p++;
1804         csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1805 }
1806
1807 /* for absolute user moves, when decom is set */
1808 void
1809 tmoveato(int x, int y)
1810 {
1811         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1812 }
1813
1814 void
1815 tmoveto(int x, int y)
1816 {
1817         int miny, maxy;
1818
1819         if (term.c.state & CURSOR_ORIGIN) {
1820                 miny = term.top;
1821                 maxy = term.bot;
1822         } else {
1823                 miny = 0;
1824                 maxy = term.row - 1;
1825         }
1826         term.c.state &= ~CURSOR_WRAPNEXT;
1827         term.c.x = LIMIT(x, 0, term.col-1);
1828         term.c.y = LIMIT(y, miny, maxy);
1829 }
1830
1831 void
1832 tsetchar(Rune u, Glyph *attr, int x, int y)
1833 {
1834         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1835                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1836                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1837                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1838                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1839                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1840                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1841                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1842                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1843         };
1844
1845         /*
1846          * The table is proudly stolen from rxvt.
1847          */
1848         if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1849            BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1850                 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1851
1852         if (term.line[y][x].mode & ATTR_WIDE) {
1853                 if (x+1 < term.col) {
1854                         term.line[y][x+1].u = ' ';
1855                         term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1856                 }
1857         } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1858                 term.line[y][x-1].u = ' ';
1859                 term.line[y][x-1].mode &= ~ATTR_WIDE;
1860         }
1861
1862         term.dirty[y] = 1;
1863         term.line[y][x] = *attr;
1864         term.line[y][x].u = u;
1865 }
1866
1867 void
1868 tclearregion(int x1, int y1, int x2, int y2)
1869 {
1870         int x, y, temp;
1871         Glyph *gp;
1872
1873         if (x1 > x2)
1874                 temp = x1, x1 = x2, x2 = temp;
1875         if (y1 > y2)
1876                 temp = y1, y1 = y2, y2 = temp;
1877
1878         LIMIT(x1, 0, term.col-1);
1879         LIMIT(x2, 0, term.col-1);
1880         LIMIT(y1, 0, term.row-1);
1881         LIMIT(y2, 0, term.row-1);
1882
1883         for (y = y1; y <= y2; y++) {
1884                 term.dirty[y] = 1;
1885                 for (x = x1; x <= x2; x++) {
1886                         gp = &term.line[y][x];
1887                         if (selected(x, y))
1888                                 selclear(NULL);
1889                         gp->fg = term.c.attr.fg;
1890                         gp->bg = term.c.attr.bg;
1891                         gp->mode = 0;
1892                         gp->u = ' ';
1893                 }
1894         }
1895 }
1896
1897 void
1898 tdeletechar(int n)
1899 {
1900         int dst, src, size;
1901         Glyph *line;
1902
1903         LIMIT(n, 0, term.col - term.c.x);
1904
1905         dst = term.c.x;
1906         src = term.c.x + n;
1907         size = term.col - src;
1908         line = term.line[term.c.y];
1909
1910         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1911         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1912 }
1913
1914 void
1915 tinsertblank(int n)
1916 {
1917         int dst, src, size;
1918         Glyph *line;
1919
1920         LIMIT(n, 0, term.col - term.c.x);
1921
1922         dst = term.c.x + n;
1923         src = term.c.x;
1924         size = term.col - dst;
1925         line = term.line[term.c.y];
1926
1927         memmove(&line[dst], &line[src], size * sizeof(Glyph));
1928         tclearregion(src, term.c.y, dst - 1, term.c.y);
1929 }
1930
1931 void
1932 tinsertblankline(int n)
1933 {
1934         if (BETWEEN(term.c.y, term.top, term.bot))
1935                 tscrolldown(term.c.y, n);
1936 }
1937
1938 void
1939 tdeleteline(int n)
1940 {
1941         if (BETWEEN(term.c.y, term.top, term.bot))
1942                 tscrollup(term.c.y, n);
1943 }
1944
1945 int32_t
1946 tdefcolor(int *attr, int *npar, int l)
1947 {
1948         int32_t idx = -1;
1949         uint r, g, b;
1950
1951         switch (attr[*npar + 1]) {
1952         case 2: /* direct color in RGB space */
1953                 if (*npar + 4 >= l) {
1954                         fprintf(stderr,
1955                                 "erresc(38): Incorrect number of parameters (%d)\n",
1956                                 *npar);
1957                         break;
1958                 }
1959                 r = attr[*npar + 2];
1960                 g = attr[*npar + 3];
1961                 b = attr[*npar + 4];
1962                 *npar += 4;
1963                 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1964                         fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1965                                 r, g, b);
1966                 else
1967                         idx = TRUECOLOR(r, g, b);
1968                 break;
1969         case 5: /* indexed color */
1970                 if (*npar + 2 >= l) {
1971                         fprintf(stderr,
1972                                 "erresc(38): Incorrect number of parameters (%d)\n",
1973                                 *npar);
1974                         break;
1975                 }
1976                 *npar += 2;
1977                 if (!BETWEEN(attr[*npar], 0, 255))
1978                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1979                 else
1980                         idx = attr[*npar];
1981                 break;
1982         case 0: /* implemented defined (only foreground) */
1983         case 1: /* transparent */
1984         case 3: /* direct color in CMY space */
1985         case 4: /* direct color in CMYK space */
1986         default:
1987                 fprintf(stderr,
1988                         "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1989                 break;
1990         }
1991
1992         return idx;
1993 }
1994
1995 void
1996 tsetattr(int *attr, int l)
1997 {
1998         int i;
1999         int32_t idx;
2000
2001         for (i = 0; i < l; i++) {
2002                 switch (attr[i]) {
2003                 case 0:
2004                         term.c.attr.mode &= ~(
2005                                 ATTR_BOLD       |
2006                                 ATTR_FAINT      |
2007                                 ATTR_ITALIC     |
2008                                 ATTR_UNDERLINE  |
2009                                 ATTR_BLINK      |
2010                                 ATTR_REVERSE    |
2011                                 ATTR_INVISIBLE  |
2012                                 ATTR_STRUCK     );
2013                         term.c.attr.fg = defaultfg;
2014                         term.c.attr.bg = defaultbg;
2015                         break;
2016                 case 1:
2017                         term.c.attr.mode |= ATTR_BOLD;
2018                         break;
2019                 case 2:
2020                         term.c.attr.mode |= ATTR_FAINT;
2021                         break;
2022                 case 3:
2023                         term.c.attr.mode |= ATTR_ITALIC;
2024                         break;
2025                 case 4:
2026                         term.c.attr.mode |= ATTR_UNDERLINE;
2027                         break;
2028                 case 5: /* slow blink */
2029                         /* FALLTHROUGH */
2030                 case 6: /* rapid blink */
2031                         term.c.attr.mode |= ATTR_BLINK;
2032                         break;
2033                 case 7:
2034                         term.c.attr.mode |= ATTR_REVERSE;
2035                         break;
2036                 case 8:
2037                         term.c.attr.mode |= ATTR_INVISIBLE;
2038                         break;
2039                 case 9:
2040                         term.c.attr.mode |= ATTR_STRUCK;
2041                         break;
2042                 case 22:
2043                         term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
2044                         break;
2045                 case 23:
2046                         term.c.attr.mode &= ~ATTR_ITALIC;
2047                         break;
2048                 case 24:
2049                         term.c.attr.mode &= ~ATTR_UNDERLINE;
2050                         break;
2051                 case 25:
2052                         term.c.attr.mode &= ~ATTR_BLINK;
2053                         break;
2054                 case 27:
2055                         term.c.attr.mode &= ~ATTR_REVERSE;
2056                         break;
2057                 case 28:
2058                         term.c.attr.mode &= ~ATTR_INVISIBLE;
2059                         break;
2060                 case 29:
2061                         term.c.attr.mode &= ~ATTR_STRUCK;
2062                         break;
2063                 case 38:
2064                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
2065                                 term.c.attr.fg = idx;
2066                         break;
2067                 case 39:
2068                         term.c.attr.fg = defaultfg;
2069                         break;
2070                 case 48:
2071                         if ((idx = tdefcolor(attr, &i, l)) >= 0)
2072                                 term.c.attr.bg = idx;
2073                         break;
2074                 case 49:
2075                         term.c.attr.bg = defaultbg;
2076                         break;
2077                 default:
2078                         if (BETWEEN(attr[i], 30, 37)) {
2079                                 term.c.attr.fg = attr[i] - 30;
2080                         } else if (BETWEEN(attr[i], 40, 47)) {
2081                                 term.c.attr.bg = attr[i] - 40;
2082                         } else if (BETWEEN(attr[i], 90, 97)) {
2083                                 term.c.attr.fg = attr[i] - 90 + 8;
2084                         } else if (BETWEEN(attr[i], 100, 107)) {
2085                                 term.c.attr.bg = attr[i] - 100 + 8;
2086                         } else {
2087                                 fprintf(stderr,
2088                                         "erresc(default): gfx attr %d unknown\n",
2089                                         attr[i]), csidump();
2090                         }
2091                         break;
2092                 }
2093         }
2094 }
2095
2096 void
2097 tsetscroll(int t, int b)
2098 {
2099         int temp;
2100
2101         LIMIT(t, 0, term.row-1);
2102         LIMIT(b, 0, term.row-1);
2103         if (t > b) {
2104                 temp = t;
2105                 t = b;
2106                 b = temp;
2107         }
2108         term.top = t;
2109         term.bot = b;
2110 }
2111
2112 void
2113 tsetmode(int priv, int set, int *args, int narg)
2114 {
2115         int *lim, mode;
2116         int alt;
2117
2118         for (lim = args + narg; args < lim; ++args) {
2119                 if (priv) {
2120                         switch (*args) {
2121                         case 1: /* DECCKM -- Cursor key */
2122                                 MODBIT(term.mode, set, MODE_APPCURSOR);
2123                                 break;
2124                         case 5: /* DECSCNM -- Reverse video */
2125                                 mode = term.mode;
2126                                 MODBIT(term.mode, set, MODE_REVERSE);
2127                                 if (mode != term.mode)
2128                                         redraw();
2129                                 break;
2130                         case 6: /* DECOM -- Origin */
2131                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2132                                 tmoveato(0, 0);
2133                                 break;
2134                         case 7: /* DECAWM -- Auto wrap */
2135                                 MODBIT(term.mode, set, MODE_WRAP);
2136                                 break;
2137                         case 0:  /* Error (IGNORED) */
2138                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
2139                         case 3:  /* DECCOLM -- Column  (IGNORED) */
2140                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
2141                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
2142                         case 18: /* DECPFF -- Printer feed (IGNORED) */
2143                         case 19: /* DECPEX -- Printer extent (IGNORED) */
2144                         case 42: /* DECNRCM -- National characters (IGNORED) */
2145                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
2146                                 break;
2147                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
2148                                 MODBIT(term.mode, !set, MODE_HIDE);
2149                                 break;
2150                         case 9:    /* X10 mouse compatibility mode */
2151                                 xsetpointermotion(0);
2152                                 MODBIT(term.mode, 0, MODE_MOUSE);
2153                                 MODBIT(term.mode, set, MODE_MOUSEX10);
2154                                 break;
2155                         case 1000: /* 1000: report button press */
2156                                 xsetpointermotion(0);
2157                                 MODBIT(term.mode, 0, MODE_MOUSE);
2158                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
2159                                 break;
2160                         case 1002: /* 1002: report motion on button press */
2161                                 xsetpointermotion(0);
2162                                 MODBIT(term.mode, 0, MODE_MOUSE);
2163                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2164                                 break;
2165                         case 1003: /* 1003: enable all mouse motions */
2166                                 xsetpointermotion(set);
2167                                 MODBIT(term.mode, 0, MODE_MOUSE);
2168                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
2169                                 break;
2170                         case 1004: /* 1004: send focus events to tty */
2171                                 MODBIT(term.mode, set, MODE_FOCUS);
2172                                 break;
2173                         case 1006: /* 1006: extended reporting mode */
2174                                 MODBIT(term.mode, set, MODE_MOUSESGR);
2175                                 break;
2176                         case 1034:
2177                                 MODBIT(term.mode, set, MODE_8BIT);
2178                                 break;
2179                         case 1049: /* swap screen & set/restore cursor as xterm */
2180                                 if (!allowaltscreen)
2181                                         break;
2182                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2183                                 /* FALLTHROUGH */
2184                         case 47: /* swap screen */
2185                         case 1047:
2186                                 if (!allowaltscreen)
2187                                         break;
2188                                 alt = IS_SET(MODE_ALTSCREEN);
2189                                 if (alt) {
2190                                         tclearregion(0, 0, term.col-1,
2191                                                         term.row-1);
2192                                 }
2193                                 if (set ^ alt) /* set is always 1 or 0 */
2194                                         tswapscreen();
2195                                 if (*args != 1049)
2196                                         break;
2197                                 /* FALLTHROUGH */
2198                         case 1048:
2199                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2200                                 break;
2201                         case 2004: /* 2004: bracketed paste mode */
2202                                 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2203                                 break;
2204                         /* Not implemented mouse modes. See comments there. */
2205                         case 1001: /* mouse highlight mode; can hang the
2206                                       terminal by design when implemented. */
2207                         case 1005: /* UTF-8 mouse mode; will confuse
2208                                       applications not supporting UTF-8
2209                                       and luit. */
2210                         case 1015: /* urxvt mangled mouse mode; incompatible
2211                                       and can be mistaken for other control
2212                                       codes. */
2213                         default:
2214                                 fprintf(stderr,
2215                                         "erresc: unknown private set/reset mode %d\n",
2216                                         *args);
2217                                 break;
2218                         }
2219                 } else {
2220                         switch (*args) {
2221                         case 0:  /* Error (IGNORED) */
2222                                 break;
2223                         case 2:  /* KAM -- keyboard action */
2224                                 MODBIT(term.mode, set, MODE_KBDLOCK);
2225                                 break;
2226                         case 4:  /* IRM -- Insertion-replacement */
2227                                 MODBIT(term.mode, set, MODE_INSERT);
2228                                 break;
2229                         case 12: /* SRM -- Send/Receive */
2230                                 MODBIT(term.mode, !set, MODE_ECHO);
2231                                 break;
2232                         case 20: /* LNM -- Linefeed/new line */
2233                                 MODBIT(term.mode, set, MODE_CRLF);
2234                                 break;
2235                         default:
2236                                 fprintf(stderr,
2237                                         "erresc: unknown set/reset mode %d\n",
2238                                         *args);
2239                                 break;
2240                         }
2241                 }
2242         }
2243 }
2244
2245 void
2246 csihandle(void)
2247 {
2248         char buf[40];
2249         int len;
2250
2251         switch (csiescseq.mode[0]) {
2252         default:
2253         unknown:
2254                 fprintf(stderr, "erresc: unknown csi ");
2255                 csidump();
2256                 /* die(""); */
2257                 break;
2258         case '@': /* ICH -- Insert <n> blank char */
2259                 DEFAULT(csiescseq.arg[0], 1);
2260                 tinsertblank(csiescseq.arg[0]);
2261                 break;
2262         case 'A': /* CUU -- Cursor <n> Up */
2263                 DEFAULT(csiescseq.arg[0], 1);
2264                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2265                 break;
2266         case 'B': /* CUD -- Cursor <n> Down */
2267         case 'e': /* VPR --Cursor <n> Down */
2268                 DEFAULT(csiescseq.arg[0], 1);
2269                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2270                 break;
2271         case 'i': /* MC -- Media Copy */
2272                 switch (csiescseq.arg[0]) {
2273                 case 0:
2274                         tdump();
2275                         break;
2276                 case 1:
2277                         tdumpline(term.c.y);
2278                         break;
2279                 case 2:
2280                         tdumpsel();
2281                         break;
2282                 case 4:
2283                         term.mode &= ~MODE_PRINT;
2284                         break;
2285                 case 5:
2286                         term.mode |= MODE_PRINT;
2287                         break;
2288                 }
2289                 break;
2290         case 'c': /* DA -- Device Attributes */
2291                 if (csiescseq.arg[0] == 0)
2292                         ttywrite(vtiden, sizeof(vtiden) - 1);
2293                 break;
2294         case 'C': /* CUF -- Cursor <n> Forward */
2295         case 'a': /* HPR -- Cursor <n> Forward */
2296                 DEFAULT(csiescseq.arg[0], 1);
2297                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2298                 break;
2299         case 'D': /* CUB -- Cursor <n> Backward */
2300                 DEFAULT(csiescseq.arg[0], 1);
2301                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2302                 break;
2303         case 'E': /* CNL -- Cursor <n> Down and first col */
2304                 DEFAULT(csiescseq.arg[0], 1);
2305                 tmoveto(0, term.c.y+csiescseq.arg[0]);
2306                 break;
2307         case 'F': /* CPL -- Cursor <n> Up and first col */
2308                 DEFAULT(csiescseq.arg[0], 1);
2309                 tmoveto(0, term.c.y-csiescseq.arg[0]);
2310                 break;
2311         case 'g': /* TBC -- Tabulation clear */
2312                 switch (csiescseq.arg[0]) {
2313                 case 0: /* clear current tab stop */
2314                         term.tabs[term.c.x] = 0;
2315                         break;
2316                 case 3: /* clear all the tabs */
2317                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2318                         break;
2319                 default:
2320                         goto unknown;
2321                 }
2322                 break;
2323         case 'G': /* CHA -- Move to <col> */
2324         case '`': /* HPA */
2325                 DEFAULT(csiescseq.arg[0], 1);
2326                 tmoveto(csiescseq.arg[0]-1, term.c.y);
2327                 break;
2328         case 'H': /* CUP -- Move to <row> <col> */
2329         case 'f': /* HVP */
2330                 DEFAULT(csiescseq.arg[0], 1);
2331                 DEFAULT(csiescseq.arg[1], 1);
2332                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2333                 break;
2334         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2335                 DEFAULT(csiescseq.arg[0], 1);
2336                 tputtab(csiescseq.arg[0]);
2337                 break;
2338         case 'J': /* ED -- Clear screen */
2339                 selclear(NULL);
2340                 switch (csiescseq.arg[0]) {
2341                 case 0: /* below */
2342                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2343                         if (term.c.y < term.row-1) {
2344                                 tclearregion(0, term.c.y+1, term.col-1,
2345                                                 term.row-1);
2346                         }
2347                         break;
2348                 case 1: /* above */
2349                         if (term.c.y > 1)
2350                                 tclearregion(0, 0, term.col-1, term.c.y-1);
2351                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2352                         break;
2353                 case 2: /* all */
2354                         tclearregion(0, 0, term.col-1, term.row-1);
2355                         break;
2356                 default:
2357                         goto unknown;
2358                 }
2359                 break;
2360         case 'K': /* EL -- Clear line */
2361                 switch (csiescseq.arg[0]) {
2362                 case 0: /* right */
2363                         tclearregion(term.c.x, term.c.y, term.col-1,
2364                                         term.c.y);
2365                         break;
2366                 case 1: /* left */
2367                         tclearregion(0, term.c.y, term.c.x, term.c.y);
2368                         break;
2369                 case 2: /* all */
2370                         tclearregion(0, term.c.y, term.col-1, term.c.y);
2371                         break;
2372                 }
2373                 break;
2374         case 'S': /* SU -- Scroll <n> line up */
2375                 DEFAULT(csiescseq.arg[0], 1);
2376                 tscrollup(term.top, csiescseq.arg[0]);
2377                 break;
2378         case 'T': /* SD -- Scroll <n> line down */
2379                 DEFAULT(csiescseq.arg[0], 1);
2380                 tscrolldown(term.top, csiescseq.arg[0]);
2381                 break;
2382         case 'L': /* IL -- Insert <n> blank lines */
2383                 DEFAULT(csiescseq.arg[0], 1);
2384                 tinsertblankline(csiescseq.arg[0]);
2385                 break;
2386         case 'l': /* RM -- Reset Mode */
2387                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2388                 break;
2389         case 'M': /* DL -- Delete <n> lines */
2390                 DEFAULT(csiescseq.arg[0], 1);
2391                 tdeleteline(csiescseq.arg[0]);
2392                 break;
2393         case 'X': /* ECH -- Erase <n> char */
2394                 DEFAULT(csiescseq.arg[0], 1);
2395                 tclearregion(term.c.x, term.c.y,
2396                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2397                 break;
2398         case 'P': /* DCH -- Delete <n> char */
2399                 DEFAULT(csiescseq.arg[0], 1);
2400                 tdeletechar(csiescseq.arg[0]);
2401                 break;
2402         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2403                 DEFAULT(csiescseq.arg[0], 1);
2404                 tputtab(-csiescseq.arg[0]);
2405                 break;
2406         case 'd': /* VPA -- Move to <row> */
2407                 DEFAULT(csiescseq.arg[0], 1);
2408                 tmoveato(term.c.x, csiescseq.arg[0]-1);
2409                 break;
2410         case 'h': /* SM -- Set terminal mode */
2411                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2412                 break;
2413         case 'm': /* SGR -- Terminal attribute (color) */
2414                 tsetattr(csiescseq.arg, csiescseq.narg);
2415                 break;
2416         case 'n': /* DSR – Device Status Report (cursor position) */
2417                 if (csiescseq.arg[0] == 6) {
2418                         len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2419                                         term.c.y+1, term.c.x+1);
2420                         ttywrite(buf, len);
2421                 }
2422                 break;
2423         case 'r': /* DECSTBM -- Set Scrolling Region */
2424                 if (csiescseq.priv) {
2425                         goto unknown;
2426                 } else {
2427                         DEFAULT(csiescseq.arg[0], 1);
2428                         DEFAULT(csiescseq.arg[1], term.row);
2429                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2430                         tmoveato(0, 0);
2431                 }
2432                 break;
2433         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2434                 tcursor(CURSOR_SAVE);
2435                 break;
2436         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2437                 tcursor(CURSOR_LOAD);
2438                 break;
2439         case ' ':
2440                 switch (csiescseq.mode[1]) {
2441                 case 'q': /* DECSCUSR -- Set Cursor Style */
2442                         DEFAULT(csiescseq.arg[0], 1);
2443                         if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2444                                 goto unknown;
2445                         }
2446                         xw.cursor = csiescseq.arg[0];
2447                         break;
2448                 default:
2449                         goto unknown;
2450                 }
2451                 break;
2452         }
2453 }
2454
2455 void
2456 csidump(void)
2457 {
2458         int i;
2459         uint c;
2460
2461         printf("ESC[");
2462         for (i = 0; i < csiescseq.len; i++) {
2463                 c = csiescseq.buf[i] & 0xff;
2464                 if (isprint(c)) {
2465                         putchar(c);
2466                 } else if (c == '\n') {
2467                         printf("(\\n)");
2468                 } else if (c == '\r') {
2469                         printf("(\\r)");
2470                 } else if (c == 0x1b) {
2471                         printf("(\\e)");
2472                 } else {
2473                         printf("(%02x)", c);
2474                 }
2475         }
2476         putchar('\n');
2477 }
2478
2479 void
2480 csireset(void)
2481 {
2482         memset(&csiescseq, 0, sizeof(csiescseq));
2483 }
2484
2485 void
2486 strhandle(void)
2487 {
2488         char *p = NULL;
2489         int j, narg, par;
2490
2491         term.esc &= ~(ESC_STR_END|ESC_STR);
2492         strparse();
2493         par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2494
2495         switch (strescseq.type) {
2496         case ']': /* OSC -- Operating System Command */
2497                 switch (par) {
2498                 case 0:
2499                 case 1:
2500                 case 2:
2501                         if (narg > 1)
2502                                 xsettitle(strescseq.args[1]);
2503                         return;
2504                 case 4: /* color set */
2505                         if (narg < 3)
2506                                 break;
2507                         p = strescseq.args[2];
2508                         /* FALLTHROUGH */
2509                 case 104: /* color reset, here p = NULL */
2510                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2511                         if (xsetcolorname(j, p)) {
2512                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2513                         } else {
2514                                 /*
2515                                  * TODO if defaultbg color is changed, borders
2516                                  * are dirty
2517                                  */
2518                                 redraw();
2519                         }
2520                         return;
2521                 }
2522                 break;
2523         case 'k': /* old title set compatibility */
2524                 xsettitle(strescseq.args[0]);
2525                 return;
2526         case 'P': /* DCS -- Device Control String */
2527         case '_': /* APC -- Application Program Command */
2528         case '^': /* PM -- Privacy Message */
2529                 return;
2530         }
2531
2532         fprintf(stderr, "erresc: unknown str ");
2533         strdump();
2534 }
2535
2536 void
2537 strparse(void)
2538 {
2539         int c;
2540         char *p = strescseq.buf;
2541
2542         strescseq.narg = 0;
2543         strescseq.buf[strescseq.len] = '\0';
2544
2545         if (*p == '\0')
2546                 return;
2547
2548         while (strescseq.narg < STR_ARG_SIZ) {
2549                 strescseq.args[strescseq.narg++] = p;
2550                 while ((c = *p) != ';' && c != '\0')
2551                         ++p;
2552                 if (c == '\0')
2553                         return;
2554                 *p++ = '\0';
2555         }
2556 }
2557
2558 void
2559 strdump(void)
2560 {
2561         int i;
2562         uint c;
2563
2564         printf("ESC%c", strescseq.type);
2565         for (i = 0; i < strescseq.len; i++) {
2566                 c = strescseq.buf[i] & 0xff;
2567                 if (c == '\0') {
2568                         return;
2569                 } else if (isprint(c)) {
2570                         putchar(c);
2571                 } else if (c == '\n') {
2572                         printf("(\\n)");
2573                 } else if (c == '\r') {
2574                         printf("(\\r)");
2575                 } else if (c == 0x1b) {
2576                         printf("(\\e)");
2577                 } else {
2578                         printf("(%02x)", c);
2579                 }
2580         }
2581         printf("ESC\\\n");
2582 }
2583
2584 void
2585 strreset(void)
2586 {
2587         memset(&strescseq, 0, sizeof(strescseq));
2588 }
2589
2590 void
2591 sendbreak(const Arg *arg)
2592 {
2593         if (tcsendbreak(cmdfd, 0))
2594                 perror("Error sending break");
2595 }
2596
2597 void
2598 tprinter(char *s, size_t len)
2599 {
2600         if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2601                 fprintf(stderr, "Error writing in %s:%s\n",
2602                         opt_io, strerror(errno));
2603                 close(iofd);
2604                 iofd = -1;
2605         }
2606 }
2607
2608 void
2609 toggleprinter(const Arg *arg)
2610 {
2611         term.mode ^= MODE_PRINT;
2612 }
2613
2614 void
2615 printscreen(const Arg *arg)
2616 {
2617         tdump();
2618 }
2619
2620 void
2621 printsel(const Arg *arg)
2622 {
2623         tdumpsel();
2624 }
2625
2626 void
2627 tdumpsel(void)
2628 {
2629         char *ptr;
2630
2631         if ((ptr = getsel())) {
2632                 tprinter(ptr, strlen(ptr));
2633                 free(ptr);
2634         }
2635 }
2636
2637 void
2638 tdumpline(int n)
2639 {
2640         char buf[UTF_SIZ];
2641         Glyph *bp, *end;
2642
2643         bp = &term.line[n][0];
2644         end = &bp[MIN(tlinelen(n), term.col) - 1];
2645         if (bp != end || bp->u != ' ') {
2646                 for ( ;bp <= end; ++bp)
2647                         tprinter(buf, utf8encode(bp->u, buf));
2648         }
2649         tprinter("\n", 1);
2650 }
2651
2652 void
2653 tdump(void)
2654 {
2655         int i;
2656
2657         for (i = 0; i < term.row; ++i)
2658                 tdumpline(i);
2659 }
2660
2661 void
2662 tputtab(int n)
2663 {
2664         uint x = term.c.x;
2665
2666         if (n > 0) {
2667                 while (x < term.col && n--)
2668                         for (++x; x < term.col && !term.tabs[x]; ++x)
2669                                 /* nothing */ ;
2670         } else if (n < 0) {
2671                 while (x > 0 && n++)
2672                         for (--x; x > 0 && !term.tabs[x]; --x)
2673                                 /* nothing */ ;
2674         }
2675         term.c.x = LIMIT(x, 0, term.col-1);
2676 }
2677
2678 void
2679 techo(Rune u)
2680 {
2681         if (ISCONTROL(u)) { /* control code */
2682                 if (u & 0x80) {
2683                         u &= 0x7f;
2684                         tputc('^');
2685                         tputc('[');
2686                 } else if (u != '\n' && u != '\r' && u != '\t') {
2687                         u ^= 0x40;
2688                         tputc('^');
2689                 }
2690         }
2691         tputc(u);
2692 }
2693
2694 void
2695 tdeftran(char ascii)
2696 {
2697         static char cs[] = "0B";
2698         static int vcs[] = {CS_GRAPHIC0, CS_USA};
2699         char *p;
2700
2701         if ((p = strchr(cs, ascii)) == NULL) {
2702                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2703         } else {
2704                 term.trantbl[term.icharset] = vcs[p - cs];
2705         }
2706 }
2707
2708 void
2709 tdectest(char c)
2710 {
2711         int x, y;
2712
2713         if (c == '8') { /* DEC screen alignment test. */
2714                 for (x = 0; x < term.col; ++x) {
2715                         for (y = 0; y < term.row; ++y)
2716                                 tsetchar('E', &term.c.attr, x, y);
2717                 }
2718         }
2719 }
2720
2721 void
2722 tstrsequence(uchar c)
2723 {
2724         switch (c) {
2725         case 0x90:   /* DCS -- Device Control String */
2726                 c = 'P';
2727                 break;
2728         case 0x9f:   /* APC -- Application Program Command */
2729                 c = '_';
2730                 break;
2731         case 0x9e:   /* PM -- Privacy Message */
2732                 c = '^';
2733                 break;
2734         case 0x9d:   /* OSC -- Operating System Command */
2735                 c = ']';
2736                 break;
2737         }
2738         strreset();
2739         strescseq.type = c;
2740         term.esc |= ESC_STR;
2741 }
2742
2743 void
2744 tcontrolcode(uchar ascii)
2745 {
2746         switch (ascii) {
2747         case '\t':   /* HT */
2748                 tputtab(1);
2749                 return;
2750         case '\b':   /* BS */
2751                 tmoveto(term.c.x-1, term.c.y);
2752                 return;
2753         case '\r':   /* CR */
2754                 tmoveto(0, term.c.y);
2755                 return;
2756         case '\f':   /* LF */
2757         case '\v':   /* VT */
2758         case '\n':   /* LF */
2759                 /* go to first col if the mode is set */
2760                 tnewline(IS_SET(MODE_CRLF));
2761                 return;
2762         case '\a':   /* BEL */
2763                 if (term.esc & ESC_STR_END) {
2764                         /* backwards compatibility to xterm */
2765                         strhandle();
2766                 } else {
2767                         if (!(xw.state & WIN_FOCUSED))
2768                                 xseturgency(1);
2769                         if (bellvolume)
2770                                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2771                 }
2772                 break;
2773         case '\033': /* ESC */
2774                 csireset();
2775                 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2776                 term.esc |= ESC_START;
2777                 return;
2778         case '\016': /* SO (LS1 -- Locking shift 1) */
2779         case '\017': /* SI (LS0 -- Locking shift 0) */
2780                 term.charset = 1 - (ascii - '\016');
2781                 return;
2782         case '\032': /* SUB */
2783                 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2784         case '\030': /* CAN */
2785                 csireset();
2786                 break;
2787         case '\005': /* ENQ (IGNORED) */
2788         case '\000': /* NUL (IGNORED) */
2789         case '\021': /* XON (IGNORED) */
2790         case '\023': /* XOFF (IGNORED) */
2791         case 0177:   /* DEL (IGNORED) */
2792                 return;
2793         case 0x80:   /* TODO: PAD */
2794         case 0x81:   /* TODO: HOP */
2795         case 0x82:   /* TODO: BPH */
2796         case 0x83:   /* TODO: NBH */
2797         case 0x84:   /* TODO: IND */
2798                 break;
2799         case 0x85:   /* NEL -- Next line */
2800                 tnewline(1); /* always go to first col */
2801                 break;
2802         case 0x86:   /* TODO: SSA */
2803         case 0x87:   /* TODO: ESA */
2804                 break;
2805         case 0x88:   /* HTS -- Horizontal tab stop */
2806                 term.tabs[term.c.x] = 1;
2807                 break;
2808         case 0x89:   /* TODO: HTJ */
2809         case 0x8a:   /* TODO: VTS */
2810         case 0x8b:   /* TODO: PLD */
2811         case 0x8c:   /* TODO: PLU */
2812         case 0x8d:   /* TODO: RI */
2813         case 0x8e:   /* TODO: SS2 */
2814         case 0x8f:   /* TODO: SS3 */
2815         case 0x91:   /* TODO: PU1 */
2816         case 0x92:   /* TODO: PU2 */
2817         case 0x93:   /* TODO: STS */
2818         case 0x94:   /* TODO: CCH */
2819         case 0x95:   /* TODO: MW */
2820         case 0x96:   /* TODO: SPA */
2821         case 0x97:   /* TODO: EPA */
2822         case 0x98:   /* TODO: SOS */
2823         case 0x99:   /* TODO: SGCI */
2824                 break;
2825         case 0x9a:   /* DECID -- Identify Terminal */
2826                 ttywrite(vtiden, sizeof(vtiden) - 1);
2827                 break;
2828         case 0x9b:   /* TODO: CSI */
2829         case 0x9c:   /* TODO: ST */
2830                 break;
2831         case 0x90:   /* DCS -- Device Control String */
2832         case 0x9d:   /* OSC -- Operating System Command */
2833         case 0x9e:   /* PM -- Privacy Message */
2834         case 0x9f:   /* APC -- Application Program Command */
2835                 tstrsequence(ascii);
2836                 return;
2837         }
2838         /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2839         term.esc &= ~(ESC_STR_END|ESC_STR);
2840 }
2841
2842 /*
2843  * returns 1 when the sequence is finished and it hasn't to read
2844  * more characters for this sequence, otherwise 0
2845  */
2846 int
2847 eschandle(uchar ascii)
2848 {
2849         switch (ascii) {
2850         case '[':
2851                 term.esc |= ESC_CSI;
2852                 return 0;
2853         case '#':
2854                 term.esc |= ESC_TEST;
2855                 return 0;
2856         case 'P': /* DCS -- Device Control String */
2857         case '_': /* APC -- Application Program Command */
2858         case '^': /* PM -- Privacy Message */
2859         case ']': /* OSC -- Operating System Command */
2860         case 'k': /* old title set compatibility */
2861                 tstrsequence(ascii);
2862                 return 0;
2863         case 'n': /* LS2 -- Locking shift 2 */
2864         case 'o': /* LS3 -- Locking shift 3 */
2865                 term.charset = 2 + (ascii - 'n');
2866                 break;
2867         case '(': /* GZD4 -- set primary charset G0 */
2868         case ')': /* G1D4 -- set secondary charset G1 */
2869         case '*': /* G2D4 -- set tertiary charset G2 */
2870         case '+': /* G3D4 -- set quaternary charset G3 */
2871                 term.icharset = ascii - '(';
2872                 term.esc |= ESC_ALTCHARSET;
2873                 return 0;
2874         case 'D': /* IND -- Linefeed */
2875                 if (term.c.y == term.bot) {
2876                         tscrollup(term.top, 1);
2877                 } else {
2878                         tmoveto(term.c.x, term.c.y+1);
2879                 }
2880                 break;
2881         case 'E': /* NEL -- Next line */
2882                 tnewline(1); /* always go to first col */
2883                 break;
2884         case 'H': /* HTS -- Horizontal tab stop */
2885                 term.tabs[term.c.x] = 1;
2886                 break;
2887         case 'M': /* RI -- Reverse index */
2888                 if (term.c.y == term.top) {
2889                         tscrolldown(term.top, 1);
2890                 } else {
2891                         tmoveto(term.c.x, term.c.y-1);
2892                 }
2893                 break;
2894         case 'Z': /* DECID -- Identify Terminal */
2895                 ttywrite(vtiden, sizeof(vtiden) - 1);
2896                 break;
2897         case 'c': /* RIS -- Reset to inital state */
2898                 treset();
2899                 xresettitle();
2900                 xloadcols();
2901                 break;
2902         case '=': /* DECPAM -- Application keypad */
2903                 term.mode |= MODE_APPKEYPAD;
2904                 break;
2905         case '>': /* DECPNM -- Normal keypad */
2906                 term.mode &= ~MODE_APPKEYPAD;
2907                 break;
2908         case '7': /* DECSC -- Save Cursor */
2909                 tcursor(CURSOR_SAVE);
2910                 break;
2911         case '8': /* DECRC -- Restore Cursor */
2912                 tcursor(CURSOR_LOAD);
2913                 break;
2914         case '\\': /* ST -- String Terminator */
2915                 if (term.esc & ESC_STR_END)
2916                         strhandle();
2917                 break;
2918         default:
2919                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2920                         (uchar) ascii, isprint(ascii)? ascii:'.');
2921                 break;
2922         }
2923         return 1;
2924 }
2925
2926 void
2927 tputc(Rune u)
2928 {
2929         char c[UTF_SIZ];
2930         int control;
2931         int width, len;
2932         Glyph *gp;
2933
2934         control = ISCONTROL(u);
2935         len = utf8encode(u, c);
2936         if (!control && (width = wcwidth(u)) == -1) {
2937                 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2938                 width = 1;
2939         }
2940
2941         if (IS_SET(MODE_PRINT))
2942                 tprinter(c, len);
2943
2944         /*
2945          * STR sequence must be checked before anything else
2946          * because it uses all following characters until it
2947          * receives a ESC, a SUB, a ST or any other C1 control
2948          * character.
2949          */
2950         if (term.esc & ESC_STR) {
2951                 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
2952                    ISCONTROLC1(u)) {
2953                         term.esc &= ~(ESC_START|ESC_STR);
2954                         term.esc |= ESC_STR_END;
2955                 } else if (strescseq.len + len < sizeof(strescseq.buf) - 1) {
2956                         memmove(&strescseq.buf[strescseq.len], c, len);
2957                         strescseq.len += len;
2958                         return;
2959                 } else {
2960                 /*
2961                  * Here is a bug in terminals. If the user never sends
2962                  * some code to stop the str or esc command, then st
2963                  * will stop responding. But this is better than
2964                  * silently failing with unknown characters. At least
2965                  * then users will report back.
2966                  *
2967                  * In the case users ever get fixed, here is the code:
2968                  */
2969                 /*
2970                  * term.esc = 0;
2971                  * strhandle();
2972                  */
2973                         return;
2974                 }
2975         }
2976
2977         /*
2978          * Actions of control codes must be performed as soon they arrive
2979          * because they can be embedded inside a control sequence, and
2980          * they must not cause conflicts with sequences.
2981          */
2982         if (control) {
2983                 tcontrolcode(u);
2984                 /*
2985                  * control codes are not shown ever
2986                  */
2987                 return;
2988         } else if (term.esc & ESC_START) {
2989                 if (term.esc & ESC_CSI) {
2990                         csiescseq.buf[csiescseq.len++] = u;
2991                         if (BETWEEN(u, 0x40, 0x7E)
2992                                         || csiescseq.len >= \
2993                                         sizeof(csiescseq.buf)-1) {
2994                                 term.esc = 0;
2995                                 csiparse();
2996                                 csihandle();
2997                         }
2998                         return;
2999                 } else if (term.esc & ESC_ALTCHARSET) {
3000                         tdeftran(u);
3001                 } else if (term.esc & ESC_TEST) {
3002                         tdectest(u);
3003                 } else {
3004                         if (!eschandle(u))
3005                                 return;
3006                         /* sequence already finished */
3007                 }
3008                 term.esc = 0;
3009                 /*
3010                  * All characters which form part of a sequence are not
3011                  * printed
3012                  */
3013                 return;
3014         }
3015         if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
3016                 selclear(NULL);
3017
3018         gp = &term.line[term.c.y][term.c.x];
3019         if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
3020                 gp->mode |= ATTR_WRAP;
3021                 tnewline(1);
3022                 gp = &term.line[term.c.y][term.c.x];
3023         }
3024
3025         if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
3026                 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
3027
3028         if (term.c.x+width > term.col) {
3029                 tnewline(1);
3030                 gp = &term.line[term.c.y][term.c.x];
3031         }
3032
3033         tsetchar(u, &term.c.attr, term.c.x, term.c.y);
3034
3035         if (width == 2) {
3036                 gp->mode |= ATTR_WIDE;
3037                 if (term.c.x+1 < term.col) {
3038                         gp[1].u = '\0';
3039                         gp[1].mode = ATTR_WDUMMY;
3040                 }
3041         }
3042         if (term.c.x+width < term.col) {
3043                 tmoveto(term.c.x+width, term.c.y);
3044         } else {
3045                 term.c.state |= CURSOR_WRAPNEXT;
3046         }
3047 }
3048
3049 void
3050 tresize(int col, int row)
3051 {
3052         int i;
3053         int minrow = MIN(row, term.row);
3054         int mincol = MIN(col, term.col);
3055         int *bp;
3056         TCursor c;
3057
3058         if (col < 1 || row < 1) {
3059                 fprintf(stderr,
3060                         "tresize: error resizing to %dx%d\n", col, row);
3061                 return;
3062         }
3063
3064         /*
3065          * slide screen to keep cursor where we expect it -
3066          * tscrollup would work here, but we can optimize to
3067          * memmove because we're freeing the earlier lines
3068          */
3069         for (i = 0; i <= term.c.y - row; i++) {
3070                 free(term.line[i]);
3071                 free(term.alt[i]);
3072         }
3073         /* ensure that both src and dst are not NULL */
3074         if (i > 0) {
3075                 memmove(term.line, term.line + i, row * sizeof(Line));
3076                 memmove(term.alt, term.alt + i, row * sizeof(Line));
3077         }
3078         for (i += row; i < term.row; i++) {
3079                 free(term.line[i]);
3080                 free(term.alt[i]);
3081         }
3082
3083         /* resize to new width */
3084         term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
3085
3086         /* resize to new height */
3087         term.line = xrealloc(term.line, row * sizeof(Line));
3088         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
3089         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
3090         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
3091
3092         /* resize each row to new width, zero-pad if needed */
3093         for (i = 0; i < minrow; i++) {
3094                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
3095                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
3096         }
3097
3098         /* allocate any new rows */
3099         for (/* i == minrow */; i < row; i++) {
3100                 term.line[i] = xmalloc(col * sizeof(Glyph));
3101                 term.alt[i] = xmalloc(col * sizeof(Glyph));
3102         }
3103         if (col > term.col) {
3104                 bp = term.tabs + term.col;
3105
3106                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
3107                 while (--bp > term.tabs && !*bp)
3108                         /* nothing */ ;
3109                 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
3110                         *bp = 1;
3111         }
3112         /* update terminal size */
3113         term.col = col;
3114         term.row = row;
3115         /* reset scrolling region */
3116         tsetscroll(0, row-1);
3117         /* make use of the LIMIT in tmoveto */
3118         tmoveto(term.c.x, term.c.y);
3119         /* Clearing both screens (it makes dirty all lines) */
3120         c = term.c;
3121         for (i = 0; i < 2; i++) {
3122                 if (mincol < col && 0 < minrow) {
3123                         tclearregion(mincol, 0, col - 1, minrow - 1);
3124                 }
3125                 if (0 < col && minrow < row) {
3126                         tclearregion(0, minrow, col - 1, row - 1);
3127                 }
3128                 tswapscreen();
3129                 tcursor(CURSOR_LOAD);
3130         }
3131         term.c = c;
3132 }
3133
3134 void
3135 xresize(int col, int row)
3136 {
3137         xw.tw = MAX(1, col * xw.cw);
3138         xw.th = MAX(1, row * xw.ch);
3139
3140         XFreePixmap(xw.dpy, xw.buf);
3141         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3142                         DefaultDepth(xw.dpy, xw.scr));
3143         XftDrawChange(xw.draw, xw.buf);
3144         xclear(0, 0, xw.w, xw.h);
3145 }
3146
3147 ushort
3148 sixd_to_16bit(int x)
3149 {
3150         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
3151 }
3152
3153 int
3154 xloadcolor(int i, const char *name, Color *ncolor)
3155 {
3156         XRenderColor color = { .alpha = 0xffff };
3157
3158         if (!name) {
3159                 if (BETWEEN(i, 16, 255)) { /* 256 color */
3160                         if (i < 6*6*6+16) { /* same colors as xterm */
3161                                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
3162                                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3163                                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
3164                         } else { /* greyscale */
3165                                 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3166                                 color.green = color.blue = color.red;
3167                         }
3168                         return XftColorAllocValue(xw.dpy, xw.vis,
3169                                                   xw.cmap, &color, ncolor);
3170                 } else
3171                         name = colorname[i];
3172         }
3173
3174         return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3175 }
3176
3177 void
3178 xloadcols(void)
3179 {
3180         int i;
3181         static int loaded;
3182         Color *cp;
3183
3184         if (loaded) {
3185                 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3186                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3187         }
3188
3189         for (i = 0; i < LEN(dc.col); i++)
3190                 if (!xloadcolor(i, NULL, &dc.col[i])) {
3191                         if (colorname[i])
3192                                 die("Could not allocate color '%s'\n", colorname[i]);
3193                         else
3194                                 die("Could not allocate color %d\n", i);
3195                 }
3196         loaded = 1;
3197 }
3198
3199 int
3200 xsetcolorname(int x, const char *name)
3201 {
3202         Color ncolor;
3203
3204         if (!BETWEEN(x, 0, LEN(dc.col)))
3205                 return 1;
3206
3207
3208         if (!xloadcolor(x, name, &ncolor))
3209                 return 1;
3210
3211         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3212         dc.col[x] = ncolor;
3213
3214         return 0;
3215 }
3216
3217 void
3218 xtermclear(int col1, int row1, int col2, int row2)
3219 {
3220         XftDrawRect(xw.draw,
3221                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
3222                         borderpx + col1 * xw.cw,
3223                         borderpx + row1 * xw.ch,
3224                         (col2-col1+1) * xw.cw,
3225                         (row2-row1+1) * xw.ch);
3226 }
3227
3228 /*
3229  * Absolute coordinates.
3230  */
3231 void
3232 xclear(int x1, int y1, int x2, int y2)
3233 {
3234         XftDrawRect(xw.draw,
3235                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3236                         x1, y1, x2-x1, y2-y1);
3237 }
3238
3239 void
3240 xhints(void)
3241 {
3242         XClassHint class = {termname, opt_class ? opt_class : termname};
3243         XWMHints wm = {.flags = InputHint, .input = 1};
3244         XSizeHints *sizeh = NULL;
3245
3246         sizeh = XAllocSizeHints();
3247
3248         sizeh->flags = PSize | PResizeInc | PBaseSize;
3249         sizeh->height = xw.h;
3250         sizeh->width = xw.w;
3251         sizeh->height_inc = xw.ch;
3252         sizeh->width_inc = xw.cw;
3253         sizeh->base_height = 2 * borderpx;
3254         sizeh->base_width = 2 * borderpx;
3255         if (xw.isfixed) {
3256                 sizeh->flags |= PMaxSize | PMinSize;
3257                 sizeh->min_width = sizeh->max_width = xw.w;
3258                 sizeh->min_height = sizeh->max_height = xw.h;
3259         }
3260         if (xw.gm & (XValue|YValue)) {
3261                 sizeh->flags |= USPosition | PWinGravity;
3262                 sizeh->x = xw.l;
3263                 sizeh->y = xw.t;
3264                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3265         }
3266
3267         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3268                         &class);
3269         XFree(sizeh);
3270 }
3271
3272 int
3273 xgeommasktogravity(int mask)
3274 {
3275         switch (mask & (XNegative|YNegative)) {
3276         case 0:
3277                 return NorthWestGravity;
3278         case XNegative:
3279                 return NorthEastGravity;
3280         case YNegative:
3281                 return SouthWestGravity;
3282         }
3283
3284         return SouthEastGravity;
3285 }
3286
3287 int
3288 xloadfont(Font *f, FcPattern *pattern)
3289 {
3290         FcPattern *match;
3291         FcResult result;
3292
3293         match = FcFontMatch(NULL, pattern, &result);
3294         if (!match)
3295                 return 1;
3296
3297         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3298                 FcPatternDestroy(match);
3299                 return 1;
3300         }
3301
3302         f->set = NULL;
3303         f->pattern = FcPatternDuplicate(pattern);
3304
3305         f->ascent = f->match->ascent;
3306         f->descent = f->match->descent;
3307         f->lbearing = 0;
3308         f->rbearing = f->match->max_advance_width;
3309
3310         f->height = f->ascent + f->descent;
3311         f->width = f->lbearing + f->rbearing;
3312
3313         return 0;
3314 }
3315
3316 void
3317 xloadfonts(char *fontstr, double fontsize)
3318 {
3319         FcPattern *pattern;
3320         double fontval;
3321         float ceilf(float);
3322
3323         if (fontstr[0] == '-') {
3324                 pattern = XftXlfdParse(fontstr, False, False);
3325         } else {
3326                 pattern = FcNameParse((FcChar8 *)fontstr);
3327         }
3328
3329         if (!pattern)
3330                 die("st: can't open font %s\n", fontstr);
3331
3332         if (fontsize > 1) {
3333                 FcPatternDel(pattern, FC_PIXEL_SIZE);
3334                 FcPatternDel(pattern, FC_SIZE);
3335                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3336                 usedfontsize = fontsize;
3337         } else {
3338                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3339                                 FcResultMatch) {
3340                         usedfontsize = fontval;
3341                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3342                                 FcResultMatch) {
3343                         usedfontsize = -1;
3344                 } else {
3345                         /*
3346                          * Default font size is 12, if none given. This is to
3347                          * have a known usedfontsize value.
3348                          */
3349                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3350                         usedfontsize = 12;
3351                 }
3352                 defaultfontsize = usedfontsize;
3353         }
3354
3355         FcConfigSubstitute(0, pattern, FcMatchPattern);
3356         FcDefaultSubstitute(pattern);
3357
3358         if (xloadfont(&dc.font, pattern))
3359                 die("st: can't open font %s\n", fontstr);
3360
3361         if (usedfontsize < 0) {
3362                 FcPatternGetDouble(dc.font.match->pattern,
3363                                    FC_PIXEL_SIZE, 0, &fontval);
3364                 usedfontsize = fontval;
3365                 if (fontsize == 0)
3366                         defaultfontsize = fontval;
3367         }
3368
3369         /* Setting character width and height. */
3370         xw.cw = ceilf(dc.font.width * cwscale);
3371         xw.ch = ceilf(dc.font.height * chscale);
3372
3373         FcPatternDel(pattern, FC_SLANT);
3374         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3375         if (xloadfont(&dc.ifont, pattern))
3376                 die("st: can't open font %s\n", fontstr);
3377
3378         FcPatternDel(pattern, FC_WEIGHT);
3379         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3380         if (xloadfont(&dc.ibfont, pattern))
3381                 die("st: can't open font %s\n", fontstr);
3382
3383         FcPatternDel(pattern, FC_SLANT);
3384         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3385         if (xloadfont(&dc.bfont, pattern))
3386                 die("st: can't open font %s\n", fontstr);
3387
3388         FcPatternDestroy(pattern);
3389 }
3390
3391 void
3392 xunloadfont(Font *f)
3393 {
3394         XftFontClose(xw.dpy, f->match);
3395         FcPatternDestroy(f->pattern);
3396         if (f->set)
3397                 FcFontSetDestroy(f->set);
3398 }
3399
3400 void
3401 xunloadfonts(void)
3402 {
3403         /* Free the loaded fonts in the font cache.  */
3404         while (frclen > 0)
3405                 XftFontClose(xw.dpy, frc[--frclen].font);
3406
3407         xunloadfont(&dc.font);
3408         xunloadfont(&dc.bfont);
3409         xunloadfont(&dc.ifont);
3410         xunloadfont(&dc.ibfont);
3411 }
3412
3413 void
3414 xzoom(const Arg *arg)
3415 {
3416         Arg larg;
3417
3418         larg.f = usedfontsize + arg->f;
3419         xzoomabs(&larg);
3420 }
3421
3422 void
3423 xzoomabs(const Arg *arg)
3424 {
3425         xunloadfonts();
3426         xloadfonts(usedfont, arg->f);
3427         cresize(0, 0);
3428         redraw();
3429         xhints();
3430 }
3431
3432 void
3433 xzoomreset(const Arg *arg)
3434 {
3435         Arg larg;
3436
3437         if (defaultfontsize > 0) {
3438                 larg.f = defaultfontsize;
3439                 xzoomabs(&larg);
3440         }
3441 }
3442
3443 void
3444 xinit(void)
3445 {
3446         XGCValues gcvalues;
3447         Cursor cursor;
3448         Window parent;
3449         pid_t thispid = getpid();
3450         XColor xmousefg, xmousebg;
3451
3452         if (!(xw.dpy = XOpenDisplay(NULL)))
3453                 die("Can't open display\n");
3454         xw.scr = XDefaultScreen(xw.dpy);
3455         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3456
3457         /* font */
3458         if (!FcInit())
3459                 die("Could not init fontconfig.\n");
3460
3461         usedfont = (opt_font == NULL)? font : opt_font;
3462         xloadfonts(usedfont, 0);
3463
3464         /* colors */
3465         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3466         xloadcols();
3467
3468         /* adjust fixed window geometry */
3469         xw.w = 2 * borderpx + term.col * xw.cw;
3470         xw.h = 2 * borderpx + term.row * xw.ch;
3471         if (xw.gm & XNegative)
3472                 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3473         if (xw.gm & YNegative)
3474                 xw.t += DisplayHeight(xw.dpy, xw.scr) - xw.h - 2;
3475
3476         /* Events */
3477         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3478         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3479         xw.attrs.bit_gravity = NorthWestGravity;
3480         xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3481                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3482                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3483         xw.attrs.colormap = xw.cmap;
3484
3485         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3486                 parent = XRootWindow(xw.dpy, xw.scr);
3487         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3488                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3489                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3490                         | CWEventMask | CWColormap, &xw.attrs);
3491
3492         memset(&gcvalues, 0, sizeof(gcvalues));
3493         gcvalues.graphics_exposures = False;
3494         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3495                         &gcvalues);
3496         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3497                         DefaultDepth(xw.dpy, xw.scr));
3498         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3499         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3500
3501         /* Xft rendering context */
3502         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3503
3504         /* input methods */
3505         if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3506                 XSetLocaleModifiers("@im=local");
3507                 if ((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3508                         XSetLocaleModifiers("@im=");
3509                         if ((xw.xim = XOpenIM(xw.dpy,
3510                                         NULL, NULL, NULL)) == NULL) {
3511                                 die("XOpenIM failed. Could not open input"
3512                                         " device.\n");
3513                         }
3514                 }
3515         }
3516         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3517                                            | XIMStatusNothing, XNClientWindow, xw.win,
3518                                            XNFocusWindow, xw.win, NULL);
3519         if (xw.xic == NULL)
3520                 die("XCreateIC failed. Could not obtain input method.\n");
3521
3522         /* white cursor, black outline */
3523         cursor = XCreateFontCursor(xw.dpy, mouseshape);
3524         XDefineCursor(xw.dpy, xw.win, cursor);
3525
3526         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
3527                 xmousefg.red   = 0xffff;
3528                 xmousefg.green = 0xffff;
3529                 xmousefg.blue  = 0xffff;
3530         }
3531
3532         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
3533                 xmousebg.red   = 0x0000;
3534                 xmousebg.green = 0x0000;
3535                 xmousebg.blue  = 0x0000;
3536         }
3537
3538         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
3539
3540         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3541         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3542         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3543         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3544
3545         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3546         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3547                         PropModeReplace, (uchar *)&thispid, 1);
3548
3549         xresettitle();
3550         XMapWindow(xw.dpy, xw.win);
3551         xhints();
3552         XSync(xw.dpy, False);
3553 }
3554
3555 int
3556 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3557 {
3558         float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3559         ushort mode, prevmode = USHRT_MAX;
3560         Font *font = &dc.font;
3561         int frcflags = FRC_NORMAL;
3562         float runewidth = xw.cw;
3563         Rune rune;
3564         FT_UInt glyphidx;
3565         FcResult fcres;
3566         FcPattern *fcpattern, *fontpattern;
3567         FcFontSet *fcsets[] = { NULL };
3568         FcCharSet *fccharset;
3569         int i, f, numspecs = 0;
3570
3571         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3572                 /* Fetch rune and mode for current glyph. */
3573                 rune = glyphs[i].u;
3574                 mode = glyphs[i].mode;
3575
3576                 /* Skip dummy wide-character spacing. */
3577                 if (mode == ATTR_WDUMMY)
3578                         continue;
3579
3580                 /* Determine font for glyph if different from previous glyph. */
3581                 if (prevmode != mode) {
3582                         prevmode = mode;
3583                         font = &dc.font;
3584                         frcflags = FRC_NORMAL;
3585                         runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3586                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3587                                 font = &dc.ibfont;
3588                                 frcflags = FRC_ITALICBOLD;
3589                         } else if (mode & ATTR_ITALIC) {
3590                                 font = &dc.ifont;
3591                                 frcflags = FRC_ITALIC;
3592                         } else if (mode & ATTR_BOLD) {
3593                                 font = &dc.bfont;
3594                                 frcflags = FRC_BOLD;
3595                         }
3596                         yp = winy + font->ascent;
3597                 }
3598
3599                 /* Lookup character index with default font. */
3600                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3601                 if (glyphidx) {
3602                         specs[numspecs].font = font->match;
3603                         specs[numspecs].glyph = glyphidx;
3604                         specs[numspecs].x = (short)xp;
3605                         specs[numspecs].y = (short)yp;
3606                         xp += runewidth;
3607                         numspecs++;
3608                         continue;
3609                 }
3610
3611                 /* Fallback on font cache, search the font cache for match. */
3612                 for (f = 0; f < frclen; f++) {
3613                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3614                         /* Everything correct. */
3615                         if (glyphidx && frc[f].flags == frcflags)
3616                                 break;
3617                         /* We got a default font for a not found glyph. */
3618                         if (!glyphidx && frc[f].flags == frcflags
3619                                         && frc[f].unicodep == rune) {
3620                                 break;
3621                         }
3622                 }
3623
3624                 /* Nothing was found. Use fontconfig to find matching font. */
3625                 if (f >= frclen) {
3626                         if (!font->set)
3627                                 font->set = FcFontSort(0, font->pattern,
3628                                                        1, 0, &fcres);
3629                         fcsets[0] = font->set;
3630
3631                         /*
3632                          * Nothing was found in the cache. Now use
3633                          * some dozen of Fontconfig calls to get the
3634                          * font for one single character.
3635                          *
3636                          * Xft and fontconfig are design failures.
3637                          */
3638                         fcpattern = FcPatternDuplicate(font->pattern);
3639                         fccharset = FcCharSetCreate();
3640
3641                         FcCharSetAddChar(fccharset, rune);
3642                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3643                                         fccharset);
3644                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3645
3646                         FcConfigSubstitute(0, fcpattern,
3647                                         FcMatchPattern);
3648                         FcDefaultSubstitute(fcpattern);
3649
3650                         fontpattern = FcFontSetMatch(0, fcsets, 1,
3651                                         fcpattern, &fcres);
3652
3653                         /*
3654                          * Overwrite or create the new cache entry.
3655                          */
3656                         if (frclen >= LEN(frc)) {
3657                                 frclen = LEN(frc) - 1;
3658                                 XftFontClose(xw.dpy, frc[frclen].font);
3659                                 frc[frclen].unicodep = 0;
3660                         }
3661
3662                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
3663                                         fontpattern);
3664                         frc[frclen].flags = frcflags;
3665                         frc[frclen].unicodep = rune;
3666
3667                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3668
3669                         f = frclen;
3670                         frclen++;
3671
3672                         FcPatternDestroy(fcpattern);
3673                         FcCharSetDestroy(fccharset);
3674                 }
3675
3676                 specs[numspecs].font = frc[f].font;
3677                 specs[numspecs].glyph = glyphidx;
3678                 specs[numspecs].x = (short)xp;
3679                 specs[numspecs].y = (short)(winy + frc[f].font->ascent);
3680                 xp += runewidth;
3681                 numspecs++;
3682         }
3683
3684         return numspecs;
3685 }
3686
3687 void
3688 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3689 {
3690         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3691         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3692             width = charlen * xw.cw;
3693         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3694         XRenderColor colfg, colbg;
3695         XRectangle r;
3696
3697         /* Determine foreground and background colors based on mode. */
3698         if (base.fg == defaultfg) {
3699                 if (base.mode & ATTR_ITALIC)
3700                         base.fg = defaultitalic;
3701                 else if ((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3702                         base.fg = defaultitalic;
3703                 else if (base.mode & ATTR_UNDERLINE)
3704                         base.fg = defaultunderline;
3705         }
3706
3707         if (IS_TRUECOL(base.fg)) {
3708                 colfg.alpha = 0xffff;
3709                 colfg.red = TRUERED(base.fg);
3710                 colfg.green = TRUEGREEN(base.fg);
3711                 colfg.blue = TRUEBLUE(base.fg);
3712                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3713                 fg = &truefg;
3714         } else {
3715                 fg = &dc.col[base.fg];
3716         }
3717
3718         if (IS_TRUECOL(base.bg)) {
3719                 colbg.alpha = 0xffff;
3720                 colbg.green = TRUEGREEN(base.bg);
3721                 colbg.red = TRUERED(base.bg);
3722                 colbg.blue = TRUEBLUE(base.bg);
3723                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3724                 bg = &truebg;
3725         } else {
3726                 bg = &dc.col[base.bg];
3727         }
3728
3729         /* Change basic system colors [0-7] to bright system colors [8-15] */
3730         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3731                 fg = &dc.col[base.fg + 8];
3732
3733         if (IS_SET(MODE_REVERSE)) {
3734                 if (fg == &dc.col[defaultfg]) {
3735                         fg = &dc.col[defaultbg];
3736                 } else {
3737                         colfg.red = ~fg->color.red;
3738                         colfg.green = ~fg->color.green;
3739                         colfg.blue = ~fg->color.blue;
3740                         colfg.alpha = fg->color.alpha;
3741                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3742                                         &revfg);
3743                         fg = &revfg;
3744                 }
3745
3746                 if (bg == &dc.col[defaultbg]) {
3747                         bg = &dc.col[defaultfg];
3748                 } else {
3749                         colbg.red = ~bg->color.red;
3750                         colbg.green = ~bg->color.green;
3751                         colbg.blue = ~bg->color.blue;
3752                         colbg.alpha = bg->color.alpha;
3753                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3754                                         &revbg);
3755                         bg = &revbg;
3756                 }
3757         }
3758
3759         if (base.mode & ATTR_REVERSE) {
3760                 temp = fg;
3761                 fg = bg;
3762                 bg = temp;
3763         }
3764
3765         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3766                 colfg.red = fg->color.red / 2;
3767                 colfg.green = fg->color.green / 2;
3768                 colfg.blue = fg->color.blue / 2;
3769                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3770                 fg = &revfg;
3771         }
3772
3773         if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3774                 fg = bg;
3775
3776         if (base.mode & ATTR_INVISIBLE)
3777                 fg = bg;
3778
3779         /* Intelligent cleaning up of the borders. */
3780         if (x == 0) {
3781                 xclear(0, (y == 0)? 0 : winy, borderpx,
3782                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3783         }
3784         if (x + charlen >= term.col) {
3785                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3786                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3787         }
3788         if (y == 0)
3789                 xclear(winx, 0, winx + width, borderpx);
3790         if (y == term.row-1)
3791                 xclear(winx, winy + xw.ch, winx + width, xw.h);
3792
3793         /* Clean up the region we want to draw to. */
3794         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3795
3796         /* Set the clip region because Xft is sometimes dirty. */
3797         r.x = 0;
3798         r.y = 0;
3799         r.height = xw.ch;
3800         r.width = width;
3801         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3802
3803         /* Render the glyphs. */
3804         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3805
3806         /* Render underline and strikethrough. */
3807         if (base.mode & ATTR_UNDERLINE) {
3808                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3809                                 width, 1);
3810         }
3811
3812         if (base.mode & ATTR_STRUCK) {
3813                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3814                                 width, 1);
3815         }
3816
3817         /* Reset clip to none. */
3818         XftDrawSetClip(xw.draw, 0);
3819 }
3820
3821 void
3822 xdrawglyph(Glyph g, int x, int y)
3823 {
3824         int numspecs;
3825         XftGlyphFontSpec spec;
3826
3827         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3828         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3829 }
3830
3831 void
3832 xdrawcursor(void)
3833 {
3834         static int oldx = 0, oldy = 0;
3835         int curx;
3836         Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs}, og;
3837         int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3838         Color drawcol;
3839
3840         LIMIT(oldx, 0, term.col-1);
3841         LIMIT(oldy, 0, term.row-1);
3842
3843         curx = term.c.x;
3844
3845         /* adjust position if in dummy */
3846         if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3847                 oldx--;
3848         if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3849                 curx--;
3850
3851         /* remove the old cursor */
3852         og = term.line[oldy][oldx];
3853         if (ena_sel && selected(oldx, oldy))
3854                 og.mode ^= ATTR_REVERSE;
3855         xdrawglyph(og, oldx, oldy);
3856
3857         g.u = term.line[term.c.y][term.c.x].u;
3858
3859         /*
3860          * Select the right color for the right mode.
3861          */
3862         if (IS_SET(MODE_REVERSE)) {
3863                 g.mode |= ATTR_REVERSE;
3864                 g.bg = defaultfg;
3865                 if (ena_sel && selected(term.c.x, term.c.y)) {
3866                         drawcol = dc.col[defaultcs];
3867                         g.fg = defaultrcs;
3868                 } else {
3869                         drawcol = dc.col[defaultrcs];
3870                         g.fg = defaultcs;
3871                 }
3872         } else {
3873                 if (ena_sel && selected(term.c.x, term.c.y)) {
3874                         drawcol = dc.col[defaultrcs];
3875                         g.fg = defaultfg;
3876                         g.bg = defaultrcs;
3877                 } else {
3878                         drawcol = dc.col[defaultcs];
3879                 }
3880         }
3881
3882         if (IS_SET(MODE_HIDE))
3883                 return;
3884
3885         /* draw the new one */
3886         if (xw.state & WIN_FOCUSED) {
3887                 switch (xw.cursor) {
3888                 case 7: /* st extension: snowman */
3889                         utf8decode("☃", &g.u, UTF_SIZ);
3890                 case 0: /* Blinking Block */
3891                 case 1: /* Blinking Block (Default) */
3892                 case 2: /* Steady Block */
3893                         g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3894                         xdrawglyph(g, term.c.x, term.c.y);
3895                         break;
3896                 case 3: /* Blinking Underline */
3897                 case 4: /* Steady Underline */
3898                         XftDrawRect(xw.draw, &drawcol,
3899                                         borderpx + curx * xw.cw,
3900                                         borderpx + (term.c.y + 1) * xw.ch - \
3901                                                 cursorthickness,
3902                                         xw.cw, cursorthickness);
3903                         break;
3904                 case 5: /* Blinking bar */
3905                 case 6: /* Steady bar */
3906                         XftDrawRect(xw.draw, &drawcol,
3907                                         borderpx + curx * xw.cw,
3908                                         borderpx + term.c.y * xw.ch,
3909                                         cursorthickness, xw.ch);
3910                         break;
3911                 }
3912         } else {
3913                 XftDrawRect(xw.draw, &drawcol,
3914                                 borderpx + curx * xw.cw,
3915                                 borderpx + term.c.y * xw.ch,
3916                                 xw.cw - 1, 1);
3917                 XftDrawRect(xw.draw, &drawcol,
3918                                 borderpx + curx * xw.cw,
3919                                 borderpx + term.c.y * xw.ch,
3920                                 1, xw.ch - 1);
3921                 XftDrawRect(xw.draw, &drawcol,
3922                                 borderpx + (curx + 1) * xw.cw - 1,
3923                                 borderpx + term.c.y * xw.ch,
3924                                 1, xw.ch - 1);
3925                 XftDrawRect(xw.draw, &drawcol,
3926                                 borderpx + curx * xw.cw,
3927                                 borderpx + (term.c.y + 1) * xw.ch - 1,
3928                                 xw.cw, 1);
3929         }
3930         oldx = curx, oldy = term.c.y;
3931 }
3932
3933
3934 void
3935 xsettitle(char *p)
3936 {
3937         XTextProperty prop;
3938
3939         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3940                         &prop);
3941         XSetWMName(xw.dpy, xw.win, &prop);
3942         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3943         XFree(prop.value);
3944 }
3945
3946 void
3947 xresettitle(void)
3948 {
3949         xsettitle(opt_title ? opt_title : "st");
3950 }
3951
3952 void
3953 redraw(void)
3954 {
3955         tfulldirt();
3956         draw();
3957 }
3958
3959 void
3960 draw(void)
3961 {
3962         drawregion(0, 0, term.col, term.row);
3963         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3964                         xw.h, 0, 0);
3965         XSetForeground(xw.dpy, dc.gc,
3966                         dc.col[IS_SET(MODE_REVERSE)?
3967                                 defaultfg : defaultbg].pixel);
3968 }
3969
3970 void
3971 drawregion(int x1, int y1, int x2, int y2)
3972 {
3973         int i, x, y, ox, numspecs;
3974         Glyph base, new;
3975         XftGlyphFontSpec *specs;
3976         int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3977
3978         if (!(xw.state & WIN_VISIBLE))
3979                 return;
3980
3981         for (y = y1; y < y2; y++) {
3982                 if (!term.dirty[y])
3983                         continue;
3984
3985                 xtermclear(0, y, term.col, y);
3986                 term.dirty[y] = 0;
3987
3988                 specs = term.specbuf;
3989                 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
3990
3991                 i = ox = 0;
3992                 for (x = x1; x < x2 && i < numspecs; x++) {
3993                         new = term.line[y][x];
3994                         if (new.mode == ATTR_WDUMMY)
3995                                 continue;
3996                         if (ena_sel && selected(x, y))
3997                                 new.mode ^= ATTR_REVERSE;
3998                         if (i > 0 && ATTRCMP(base, new)) {
3999                                 xdrawglyphfontspecs(specs, base, i, ox, y);
4000                                 specs += i;
4001                                 numspecs -= i;
4002                                 i = 0;
4003                         }
4004                         if (i == 0) {
4005                                 ox = x;
4006                                 base = new;
4007                         }
4008                         i++;
4009                 }
4010                 if (i > 0)
4011                         xdrawglyphfontspecs(specs, base, i, ox, y);
4012         }
4013         xdrawcursor();
4014 }
4015
4016 void
4017 expose(XEvent *ev)
4018 {
4019         redraw();
4020 }
4021
4022 void
4023 visibility(XEvent *ev)
4024 {
4025         XVisibilityEvent *e = &ev->xvisibility;
4026
4027         MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
4028 }
4029
4030 void
4031 unmap(XEvent *ev)
4032 {
4033         xw.state &= ~WIN_VISIBLE;
4034 }
4035
4036 void
4037 xsetpointermotion(int set)
4038 {
4039         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
4040         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
4041 }
4042
4043 void
4044 xseturgency(int add)
4045 {
4046         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
4047
4048         MODBIT(h->flags, add, XUrgencyHint);
4049         XSetWMHints(xw.dpy, xw.win, h);
4050         XFree(h);
4051 }
4052
4053 void
4054 focus(XEvent *ev)
4055 {
4056         XFocusChangeEvent *e = &ev->xfocus;
4057
4058         if (e->mode == NotifyGrab)
4059                 return;
4060
4061         if (ev->type == FocusIn) {
4062                 XSetICFocus(xw.xic);
4063                 xw.state |= WIN_FOCUSED;
4064                 xseturgency(0);
4065                 if (IS_SET(MODE_FOCUS))
4066                         ttywrite("\033[I", 3);
4067         } else {
4068                 XUnsetICFocus(xw.xic);
4069                 xw.state &= ~WIN_FOCUSED;
4070                 if (IS_SET(MODE_FOCUS))
4071                         ttywrite("\033[O", 3);
4072         }
4073 }
4074
4075 int
4076 match(uint mask, uint state)
4077 {
4078         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
4079 }
4080
4081 void
4082 numlock(const Arg *dummy)
4083 {
4084         term.numlock ^= 1;
4085 }
4086
4087 char*
4088 kmap(KeySym k, uint state)
4089 {
4090         Key *kp;
4091         int i;
4092
4093         /* Check for mapped keys out of X11 function keys. */
4094         for (i = 0; i < LEN(mappedkeys); i++) {
4095                 if (mappedkeys[i] == k)
4096                         break;
4097         }
4098         if (i == LEN(mappedkeys)) {
4099                 if ((k & 0xFFFF) < 0xFD00)
4100                         return NULL;
4101         }
4102
4103         for (kp = key; kp < key + LEN(key); kp++) {
4104                 if (kp->k != k)
4105                         continue;
4106
4107                 if (!match(kp->mask, state))
4108                         continue;
4109
4110                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
4111                         continue;
4112                 if (term.numlock && kp->appkey == 2)
4113                         continue;
4114
4115                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
4116                         continue;
4117
4118                 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
4119                         continue;
4120
4121                 return kp->s;
4122         }
4123
4124         return NULL;
4125 }
4126
4127 void
4128 kpress(XEvent *ev)
4129 {
4130         XKeyEvent *e = &ev->xkey;
4131         KeySym ksym;
4132         char buf[32], *customkey;
4133         int len;
4134         Rune c;
4135         Status status;
4136         Shortcut *bp;
4137
4138         if (IS_SET(MODE_KBDLOCK))
4139                 return;
4140
4141         len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
4142         /* 1. shortcuts */
4143         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
4144                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
4145                         bp->func(&(bp->arg));
4146                         return;
4147                 }
4148         }
4149
4150         /* 2. custom keys from config.h */
4151         if ((customkey = kmap(ksym, e->state))) {
4152                 ttysend(customkey, strlen(customkey));
4153                 return;
4154         }
4155
4156         /* 3. composed string from input method */
4157         if (len == 0)
4158                 return;
4159         if (len == 1 && e->state & Mod1Mask) {
4160                 if (IS_SET(MODE_8BIT)) {
4161                         if (*buf < 0177) {
4162                                 c = *buf | 0x80;
4163                                 len = utf8encode(c, buf);
4164                         }
4165                 } else {
4166                         buf[1] = buf[0];
4167                         buf[0] = '\033';
4168                         len = 2;
4169                 }
4170         }
4171         ttysend(buf, len);
4172 }
4173
4174
4175 void
4176 cmessage(XEvent *e)
4177 {
4178         /*
4179          * See xembed specs
4180          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
4181          */
4182         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4183                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4184                         xw.state |= WIN_FOCUSED;
4185                         xseturgency(0);
4186                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4187                         xw.state &= ~WIN_FOCUSED;
4188                 }
4189         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
4190                 /* Send SIGHUP to shell */
4191                 kill(pid, SIGHUP);
4192                 exit(0);
4193         }
4194 }
4195
4196 void
4197 cresize(int width, int height)
4198 {
4199         int col, row;
4200
4201         if (width != 0)
4202                 xw.w = width;
4203         if (height != 0)
4204                 xw.h = height;
4205
4206         col = (xw.w - 2 * borderpx) / xw.cw;
4207         row = (xw.h - 2 * borderpx) / xw.ch;
4208
4209         tresize(col, row);
4210         xresize(col, row);
4211         ttyresize();
4212 }
4213
4214 void
4215 resize(XEvent *e)
4216 {
4217         if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4218                 return;
4219
4220         cresize(e->xconfigure.width, e->xconfigure.height);
4221 }
4222
4223 void
4224 run(void)
4225 {
4226         XEvent ev;
4227         int w = xw.w, h = xw.h;
4228         fd_set rfd;
4229         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4230         struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4231         long deltatime;
4232
4233         /* Waiting for window mapping */
4234         do {
4235                 XNextEvent(xw.dpy, &ev);
4236                 /*
4237                  * This XFilterEvent call is required because of XOpenIM. It
4238                  * does filter out the key event and some client message for
4239                  * the input method too.
4240                  */
4241                 if (XFilterEvent(&ev, None))
4242                         continue;
4243                 if (ev.type == ConfigureNotify) {
4244                         w = ev.xconfigure.width;
4245                         h = ev.xconfigure.height;
4246                 }
4247         } while (ev.type != MapNotify);
4248
4249         ttynew();
4250         cresize(w, h);
4251
4252         clock_gettime(CLOCK_MONOTONIC, &last);
4253         lastblink = last;
4254
4255         for (xev = actionfps;;) {
4256                 FD_ZERO(&rfd);
4257                 FD_SET(cmdfd, &rfd);
4258                 FD_SET(xfd, &rfd);
4259
4260                 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4261                         if (errno == EINTR)
4262                                 continue;
4263                         die("select failed: %s\n", strerror(errno));
4264                 }
4265                 if (FD_ISSET(cmdfd, &rfd)) {
4266                         ttyread();
4267                         if (blinktimeout) {
4268                                 blinkset = tattrset(ATTR_BLINK);
4269                                 if (!blinkset)
4270                                         MODBIT(term.mode, 0, MODE_BLINK);
4271                         }
4272                 }
4273
4274                 if (FD_ISSET(xfd, &rfd))
4275                         xev = actionfps;
4276
4277                 clock_gettime(CLOCK_MONOTONIC, &now);
4278                 drawtimeout.tv_sec = 0;
4279                 drawtimeout.tv_nsec =  (1000 * 1E6)/ xfps;
4280                 tv = &drawtimeout;
4281
4282                 dodraw = 0;
4283                 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4284                         tsetdirtattr(ATTR_BLINK);
4285                         term.mode ^= MODE_BLINK;
4286                         lastblink = now;
4287                         dodraw = 1;
4288                 }
4289                 deltatime = TIMEDIFF(now, last);
4290                 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4291                         dodraw = 1;
4292                         last = now;
4293                 }
4294
4295                 if (dodraw) {
4296                         while (XPending(xw.dpy)) {
4297                                 XNextEvent(xw.dpy, &ev);
4298                                 if (XFilterEvent(&ev, None))
4299                                         continue;
4300                                 if (handler[ev.type])
4301                                         (handler[ev.type])(&ev);
4302                         }
4303
4304                         draw();
4305                         XFlush(xw.dpy);
4306
4307                         if (xev && !FD_ISSET(xfd, &rfd))
4308                                 xev--;
4309                         if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4310                                 if (blinkset) {
4311                                         if (TIMEDIFF(now, lastblink) \
4312                                                         > blinktimeout) {
4313                                                 drawtimeout.tv_nsec = 1000;
4314                                         } else {
4315                                                 drawtimeout.tv_nsec = (1E6 * \
4316                                                         (blinktimeout - \
4317                                                         TIMEDIFF(now,
4318                                                                 lastblink)));
4319                                         }
4320                                         drawtimeout.tv_sec = \
4321                                             drawtimeout.tv_nsec / 1E9;
4322                                         drawtimeout.tv_nsec %= (long)1E9;
4323                                 } else {
4324                                         tv = NULL;
4325                                 }
4326                         }
4327                 }
4328         }
4329 }
4330
4331 void
4332 usage(void)
4333 {
4334         die("%s " VERSION " (c) 2010-2016 st engineers\n"
4335         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4336         "          [-i] [-t title] [-T title] [-w windowid] [-e command ...]"
4337         " [command ...]\n"
4338         "       st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4339         "          [-i] [-t title] [-T title] [-w windowid] -l line"
4340         " [stty_args ...]\n",
4341         argv0);
4342 }
4343
4344 int
4345 main(int argc, char *argv[])
4346 {
4347         uint cols = 80, rows = 24;
4348
4349         xw.l = xw.t = 0;
4350         xw.isfixed = False;
4351         xw.cursor = cursorshape;
4352
4353         ARGBEGIN {
4354         case 'a':
4355                 allowaltscreen = 0;
4356                 break;
4357         case 'c':
4358                 opt_class = EARGF(usage());
4359                 break;
4360         case 'e':
4361                 if (argc > 0)
4362                         --argc, ++argv;
4363                 goto run;
4364         case 'f':
4365                 opt_font = EARGF(usage());
4366                 break;
4367         case 'g':
4368                 xw.gm = XParseGeometry(EARGF(usage()),
4369                                 &xw.l, &xw.t, &cols, &rows);
4370                 break;
4371         case 'i':
4372                 xw.isfixed = 1;
4373                 break;
4374         case 'o':
4375                 opt_io = EARGF(usage());
4376                 break;
4377         case 'l':
4378                 opt_line = EARGF(usage());
4379                 break;
4380         case 't':
4381         case 'T':
4382                 opt_title = EARGF(usage());
4383                 break;
4384         case 'w':
4385                 opt_embed = EARGF(usage());
4386                 break;
4387         case 'v':
4388         default:
4389                 usage();
4390         } ARGEND;
4391
4392 run:
4393         if (argc > 0) {
4394                 /* eat all remaining arguments */
4395                 opt_cmd = argv;
4396                 if (!opt_title && !opt_line)
4397                         opt_title = basename(xstrdup(argv[0]));
4398         }
4399         setlocale(LC_CTYPE, "");
4400         XSetLocaleModifiers("");
4401         tnew(MAX(cols, 1), MAX(rows, 1));
4402         xinit();
4403         selinit();
4404         run();
4405
4406         return 0;
4407 }
4408