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