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