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