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