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