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