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