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