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