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