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