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