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