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