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