JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Using strtok_r for the string parsing.
[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++ = '\n';
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         /* int noarg = 1; */
1299         char *p = csiescseq.buf, *np;
1300         long int v;
1301
1302         csiescseq.narg = 0;
1303         if(*p == '?') {
1304                 csiescseq.priv = 1;
1305                 p++;
1306         }
1307
1308         while(p < csiescseq.buf+csiescseq.len) {
1309                 np = NULL;
1310                 v = strtol(p, &np, 10);
1311                 if(v == LONG_MAX || v == LONG_MIN)
1312                         v = -1;
1313                 csiescseq.arg[csiescseq.narg] = v;
1314                 if(np != NULL)
1315                         p = np;
1316
1317                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1318                         csiescseq.narg++, p++;
1319                 } else {
1320                         csiescseq.mode = *p;
1321                         csiescseq.narg++;
1322
1323                         return;
1324                 }
1325         }
1326 }
1327
1328 /* for absolute user moves, when decom is set */
1329 void
1330 tmoveato(int x, int y) {
1331         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1332 }
1333
1334 void
1335 tmoveto(int x, int y) {
1336         int miny, maxy;
1337
1338         if(term.c.state & CURSOR_ORIGIN) {
1339                 miny = term.top;
1340                 maxy = term.bot;
1341         } else {
1342                 miny = 0;
1343                 maxy = term.row - 1;
1344         }
1345         LIMIT(x, 0, term.col-1);
1346         LIMIT(y, miny, maxy);
1347         term.c.state &= ~CURSOR_WRAPNEXT;
1348         term.c.x = x;
1349         term.c.y = y;
1350 }
1351
1352 void
1353 tsetchar(char *c, Glyph *attr, int x, int y) {
1354         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1355                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1356                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1357                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1358                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1359                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1360                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1361                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1362                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1363         };
1364
1365         /*
1366          * The table is proudly stolen from rxvt.
1367          */
1368         if(attr->mode & ATTR_GFX) {
1369                 if(c[0] >= 0x41 && c[0] <= 0x7e
1370                                 && vt100_0[c[0] - 0x41]) {
1371                         c = vt100_0[c[0] - 0x41];
1372                 }
1373         }
1374
1375         term.dirty[y] = 1;
1376         term.line[y][x] = *attr;
1377         memcpy(term.line[y][x].c, c, UTF_SIZ);
1378         term.line[y][x].state |= GLYPH_SET;
1379 }
1380
1381 void
1382 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1383         int x, y, temp;
1384
1385         if(x1 > x2)
1386                 temp = x1, x1 = x2, x2 = temp;
1387         if(y1 > y2)
1388                 temp = y1, y1 = y2, y2 = temp;
1389
1390         LIMIT(x1, 0, term.col-1);
1391         LIMIT(x2, 0, term.col-1);
1392         LIMIT(y1, 0, term.row-1);
1393         LIMIT(y2, 0, term.row-1);
1394
1395         for(y = y1; y <= y2; y++) {
1396                 term.dirty[y] = 1;
1397                 for(x = x1; x <= x2; x++) {
1398                         if(bce) {
1399                                 term.line[y][x] = term.c.attr;
1400                                 memcpy(term.line[y][x].c, " ", 2);
1401                                 term.line[y][x].state |= GLYPH_SET;
1402                         } else {
1403                                 term.line[y][x].state = 0;
1404                         }
1405                 }
1406         }
1407 }
1408
1409 void
1410 tdeletechar(int n) {
1411         int src = term.c.x + n;
1412         int dst = term.c.x;
1413         int size = term.col - src;
1414
1415         term.dirty[term.c.y] = 1;
1416
1417         if(src >= term.col) {
1418                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1419                 return;
1420         }
1421
1422         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1423                         size * sizeof(Glyph));
1424         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1425 }
1426
1427 void
1428 tinsertblank(int n) {
1429         int src = term.c.x;
1430         int dst = src + n;
1431         int size = term.col - dst;
1432
1433         term.dirty[term.c.y] = 1;
1434
1435         if(dst >= term.col) {
1436                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1437                 return;
1438         }
1439
1440         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1441                         size * sizeof(Glyph));
1442         tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1443 }
1444
1445 void
1446 tinsertblankline(int n) {
1447         if(term.c.y < term.top || term.c.y > term.bot)
1448                 return;
1449
1450         tscrolldown(term.c.y, n);
1451 }
1452
1453 void
1454 tdeleteline(int n) {
1455         if(term.c.y < term.top || term.c.y > term.bot)
1456                 return;
1457
1458         tscrollup(term.c.y, n);
1459 }
1460
1461 void
1462 tsetattr(int *attr, int l) {
1463         int i;
1464
1465         for(i = 0; i < l; i++) {
1466                 switch(attr[i]) {
1467                 case 0:
1468                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1469                                         | ATTR_ITALIC | ATTR_BLINK);
1470                         term.c.attr.fg = defaultfg;
1471                         term.c.attr.bg = defaultbg;
1472                         break;
1473                 case 1:
1474                         term.c.attr.mode |= ATTR_BOLD;
1475                         break;
1476                 case 3:
1477                         term.c.attr.mode |= ATTR_ITALIC;
1478                         break;
1479                 case 4:
1480                         term.c.attr.mode |= ATTR_UNDERLINE;
1481                         break;
1482                 case 5: /* slow blink */
1483                 case 6: /* rapid blink */
1484                         term.c.attr.mode |= ATTR_BLINK;
1485                         break;
1486                 case 7:
1487                         term.c.attr.mode |= ATTR_REVERSE;
1488                         break;
1489                 case 21:
1490                 case 22:
1491                         term.c.attr.mode &= ~ATTR_BOLD;
1492                         break;
1493                 case 23:
1494                         term.c.attr.mode &= ~ATTR_ITALIC;
1495                         break;
1496                 case 24:
1497                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1498                         break;
1499                 case 25:
1500                 case 26:
1501                         term.c.attr.mode &= ~ATTR_BLINK;
1502                         break;
1503                 case 27:
1504                         term.c.attr.mode &= ~ATTR_REVERSE;
1505                         break;
1506                 case 38:
1507                         if(i + 2 < l && attr[i + 1] == 5) {
1508                                 i += 2;
1509                                 if(BETWEEN(attr[i], 0, 255)) {
1510                                         term.c.attr.fg = attr[i];
1511                                 } else {
1512                                         fprintf(stderr,
1513                                                 "erresc: bad fgcolor %d\n",
1514                                                 attr[i]);
1515                                 }
1516                         } else {
1517                                 fprintf(stderr,
1518                                         "erresc(38): gfx attr %d unknown\n",
1519                                         attr[i]);
1520                         }
1521                         break;
1522                 case 39:
1523                         term.c.attr.fg = defaultfg;
1524                         break;
1525                 case 48:
1526                         if(i + 2 < l && attr[i + 1] == 5) {
1527                                 i += 2;
1528                                 if(BETWEEN(attr[i], 0, 255)) {
1529                                         term.c.attr.bg = attr[i];
1530                                 } else {
1531                                         fprintf(stderr,
1532                                                 "erresc: bad bgcolor %d\n",
1533                                                 attr[i]);
1534                                 }
1535                         } else {
1536                                 fprintf(stderr,
1537                                         "erresc(48): gfx attr %d unknown\n",
1538                                         attr[i]);
1539                         }
1540                         break;
1541                 case 49:
1542                         term.c.attr.bg = defaultbg;
1543                         break;
1544                 default:
1545                         if(BETWEEN(attr[i], 30, 37)) {
1546                                 term.c.attr.fg = attr[i] - 30;
1547                         } else if(BETWEEN(attr[i], 40, 47)) {
1548                                 term.c.attr.bg = attr[i] - 40;
1549                         } else if(BETWEEN(attr[i], 90, 97)) {
1550                                 term.c.attr.fg = attr[i] - 90 + 8;
1551                         } else if(BETWEEN(attr[i], 100, 107)) {
1552                                 term.c.attr.bg = attr[i] - 100 + 8;
1553                         } else {
1554                                 fprintf(stderr,
1555                                         "erresc(default): gfx attr %d unknown\n",
1556                                         attr[i]), csidump();
1557                         }
1558                         break;
1559                 }
1560         }
1561 }
1562
1563 void
1564 tsetscroll(int t, int b) {
1565         int temp;
1566
1567         LIMIT(t, 0, term.row-1);
1568         LIMIT(b, 0, term.row-1);
1569         if(t > b) {
1570                 temp = t;
1571                 t = b;
1572                 b = temp;
1573         }
1574         term.top = t;
1575         term.bot = b;
1576 }
1577
1578 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1579
1580 void
1581 tsetmode(bool priv, bool set, int *args, int narg) {
1582         int *lim, mode;
1583         bool alt;
1584
1585         for(lim = args + narg; args < lim; ++args) {
1586                 if(priv) {
1587                         switch(*args) {
1588                                 break;
1589                         case 1: /* DECCKM -- Cursor key */
1590                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1591                                 break;
1592                         case 5: /* DECSCNM -- Reverse video */
1593                                 mode = term.mode;
1594                                 MODBIT(term.mode, set, MODE_REVERSE);
1595                                 if(mode != term.mode)
1596                                         redraw(REDRAW_TIMEOUT);
1597                                 break;
1598                         case 6: /* DECOM -- Origin */
1599                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1600                                 tmoveato(0, 0);
1601                                 break;
1602                         case 7: /* DECAWM -- Auto wrap */
1603                                 MODBIT(term.mode, set, MODE_WRAP);
1604                                 break;
1605                         case 0:  /* Error (IGNORED) */
1606                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1607                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1608                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1609                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1610                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1611                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1612                         case 42: /* DECNRCM -- National characters (IGNORED) */
1613                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1614                                 break;
1615                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1616                                 MODBIT(term.mode, !set, MODE_HIDE);
1617                                 break;
1618                         case 1000: /* 1000,1002: enable xterm mouse report */
1619                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1620                                 MODBIT(term.mode, 0, MODE_MOUSEMOTION);
1621                                 break;
1622                         case 1002:
1623                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1624                                 MODBIT(term.mode, 0, MODE_MOUSEBTN);
1625                                 break;
1626                         case 1006:
1627                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1628                                 break;
1629                         case 1049: /* = 1047 and 1048 */
1630                         case 47:
1631                         case 1047: {
1632                                 alt = IS_SET(MODE_ALTSCREEN);
1633                                 if(alt) {
1634                                         tclearregion(0, 0, term.col-1,
1635                                                         term.row-1, 0);
1636                                 }
1637                                 if(set ^ alt)           /* set is always 1 or 0 */
1638                                         tswapscreen();
1639                                 if(*args != 1049)
1640                                         break;
1641                         }
1642                                 /* pass through */
1643                         case 1048:
1644                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1645                                 break;
1646                         default:
1647                                 fprintf(stderr,
1648                                         "erresc: unknown private set/reset mode %d\n",
1649                                         *args);
1650                                 break;
1651                         }
1652                 } else {
1653                         switch(*args) {
1654                         case 0:  /* Error (IGNORED) */
1655                                 break;
1656                         case 2:  /* KAM -- keyboard action */
1657                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1658                                 break;
1659                         case 4:  /* IRM -- Insertion-replacement */
1660                                 MODBIT(term.mode, set, MODE_INSERT);
1661                                 break;
1662                         case 12: /* SRM -- Send/Receive */
1663                                 MODBIT(term.mode, !set, MODE_ECHO);
1664                                 break;
1665                         case 20: /* LNM -- Linefeed/new line */
1666                                 MODBIT(term.mode, set, MODE_CRLF);
1667                                 break;
1668                         default:
1669                                 fprintf(stderr,
1670                                         "erresc: unknown set/reset mode %d\n",
1671                                         *args);
1672                                 break;
1673                         }
1674                 }
1675         }
1676 }
1677 #undef MODBIT
1678
1679
1680 void
1681 csihandle(void) {
1682         switch(csiescseq.mode) {
1683         default:
1684         unknown:
1685                 fprintf(stderr, "erresc: unknown csi ");
1686                 csidump();
1687                 /* die(""); */
1688                 break;
1689         case '@': /* ICH -- Insert <n> blank char */
1690                 DEFAULT(csiescseq.arg[0], 1);
1691                 tinsertblank(csiescseq.arg[0]);
1692                 break;
1693         case 'A': /* CUU -- Cursor <n> Up */
1694                 DEFAULT(csiescseq.arg[0], 1);
1695                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1696                 break;
1697         case 'B': /* CUD -- Cursor <n> Down */
1698         case 'e': /* VPR --Cursor <n> Down */
1699                 DEFAULT(csiescseq.arg[0], 1);
1700                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1701                 break;
1702         case 'c': /* DA -- Device Attributes */
1703                 if(csiescseq.arg[0] == 0)
1704                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1705                 break;
1706         case 'C': /* CUF -- Cursor <n> Forward */
1707         case 'a': /* HPR -- Cursor <n> Forward */
1708                 DEFAULT(csiescseq.arg[0], 1);
1709                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1710                 break;
1711         case 'D': /* CUB -- Cursor <n> Backward */
1712                 DEFAULT(csiescseq.arg[0], 1);
1713                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1714                 break;
1715         case 'E': /* CNL -- Cursor <n> Down and first col */
1716                 DEFAULT(csiescseq.arg[0], 1);
1717                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1718                 break;
1719         case 'F': /* CPL -- Cursor <n> Up and first col */
1720                 DEFAULT(csiescseq.arg[0], 1);
1721                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1722                 break;
1723         case 'g': /* TBC -- Tabulation clear */
1724                 switch(csiescseq.arg[0]) {
1725                 case 0: /* clear current tab stop */
1726                         term.tabs[term.c.x] = 0;
1727                         break;
1728                 case 3: /* clear all the tabs */
1729                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1730                         break;
1731                 default:
1732                         goto unknown;
1733                 }
1734                 break;
1735         case 'G': /* CHA -- Move to <col> */
1736         case '`': /* HPA */
1737                 DEFAULT(csiescseq.arg[0], 1);
1738                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1739                 break;
1740         case 'H': /* CUP -- Move to <row> <col> */
1741         case 'f': /* HVP */
1742                 DEFAULT(csiescseq.arg[0], 1);
1743                 DEFAULT(csiescseq.arg[1], 1);
1744                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1745                 break;
1746         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1747                 DEFAULT(csiescseq.arg[0], 1);
1748                 while(csiescseq.arg[0]--)
1749                         tputtab(1);
1750                 break;
1751         case 'J': /* ED -- Clear screen */
1752                 sel.bx = -1;
1753                 switch(csiescseq.arg[0]) {
1754                 case 0: /* below */
1755                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1756                         if(term.c.y < term.row-1) {
1757                                 tclearregion(0, term.c.y+1, term.col-1,
1758                                                 term.row-1, 1);
1759                         }
1760                         break;
1761                 case 1: /* above */
1762                         if(term.c.y > 1)
1763                                 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1764                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1765                         break;
1766                 case 2: /* all */
1767                         tclearregion(0, 0, term.col-1, term.row-1, 1);
1768                         break;
1769                 default:
1770                         goto unknown;
1771                 }
1772                 break;
1773         case 'K': /* EL -- Clear line */
1774                 switch(csiescseq.arg[0]) {
1775                 case 0: /* right */
1776                         tclearregion(term.c.x, term.c.y, term.col-1,
1777                                         term.c.y, 1);
1778                         break;
1779                 case 1: /* left */
1780                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1781                         break;
1782                 case 2: /* all */
1783                         tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1784                         break;
1785                 }
1786                 break;
1787         case 'S': /* SU -- Scroll <n> line up */
1788                 DEFAULT(csiescseq.arg[0], 1);
1789                 tscrollup(term.top, csiescseq.arg[0]);
1790                 break;
1791         case 'T': /* SD -- Scroll <n> line down */
1792                 DEFAULT(csiescseq.arg[0], 1);
1793                 tscrolldown(term.top, csiescseq.arg[0]);
1794                 break;
1795         case 'L': /* IL -- Insert <n> blank lines */
1796                 DEFAULT(csiescseq.arg[0], 1);
1797                 tinsertblankline(csiescseq.arg[0]);
1798                 break;
1799         case 'l': /* RM -- Reset Mode */
1800                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1801                 break;
1802         case 'M': /* DL -- Delete <n> lines */
1803                 DEFAULT(csiescseq.arg[0], 1);
1804                 tdeleteline(csiescseq.arg[0]);
1805                 break;
1806         case 'X': /* ECH -- Erase <n> char */
1807                 DEFAULT(csiescseq.arg[0], 1);
1808                 tclearregion(term.c.x, term.c.y,
1809                                 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1810                 break;
1811         case 'P': /* DCH -- Delete <n> char */
1812                 DEFAULT(csiescseq.arg[0], 1);
1813                 tdeletechar(csiescseq.arg[0]);
1814                 break;
1815         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1816                 DEFAULT(csiescseq.arg[0], 1);
1817                 while(csiescseq.arg[0]--)
1818                         tputtab(0);
1819                 break;
1820         case 'd': /* VPA -- Move to <row> */
1821                 DEFAULT(csiescseq.arg[0], 1);
1822                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1823                 break;
1824         case 'h': /* SM -- Set terminal mode */
1825                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1826                 break;
1827         case 'm': /* SGR -- Terminal attribute (color) */
1828                 tsetattr(csiescseq.arg, csiescseq.narg);
1829                 break;
1830         case 'r': /* DECSTBM -- Set Scrolling Region */
1831                 if(csiescseq.priv) {
1832                         goto unknown;
1833                 } else {
1834                         DEFAULT(csiescseq.arg[0], 1);
1835                         DEFAULT(csiescseq.arg[1], term.row);
1836                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1837                         tmoveato(0, 0);
1838                 }
1839                 break;
1840         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1841                 tcursor(CURSOR_SAVE);
1842                 break;
1843         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1844                 tcursor(CURSOR_LOAD);
1845                 break;
1846         }
1847 }
1848
1849 void
1850 csidump(void) {
1851         int i;
1852         uint c;
1853
1854         printf("ESC[");
1855         for(i = 0; i < csiescseq.len; i++) {
1856                 c = csiescseq.buf[i] & 0xff;
1857                 if(isprint(c)) {
1858                         putchar(c);
1859                 } else if(c == '\n') {
1860                         printf("(\\n)");
1861                 } else if(c == '\r') {
1862                         printf("(\\r)");
1863                 } else if(c == 0x1b) {
1864                         printf("(\\e)");
1865                 } else {
1866                         printf("(%02x)", c);
1867                 }
1868         }
1869         putchar('\n');
1870 }
1871
1872 void
1873 csireset(void) {
1874         memset(&csiescseq, 0, sizeof(csiescseq));
1875 }
1876
1877 void
1878 strhandle(void) {
1879         char *p = NULL;
1880         int i, j, narg;
1881
1882         strparse();
1883         narg = strescseq.narg;
1884
1885         switch(strescseq.type) {
1886         case ']': /* OSC -- Operating System Command */
1887                 switch(i = atoi(strescseq.args[0])) {
1888                 case 0:
1889                 case 1:
1890                 case 2:
1891                         if(narg > 1)
1892                                 xsettitle(strescseq.args[1]);
1893                         break;
1894                 case 4: /* color set */
1895                         if(narg < 3)
1896                                 break;
1897                         p = strescseq.args[2];
1898                         /* fall through */
1899                 case 104: /* color reset, here p = NULL */
1900                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1901                         if (!xsetcolorname(j, p)) {
1902                                 fprintf(stderr, "erresc: invalid color %s\n", p);
1903                         } else {
1904                                 /*
1905                                  * TODO if defaultbg color is changed, borders
1906                                  * are dirty
1907                                  */
1908                                 redraw(0);
1909                         }
1910                         break;
1911                 default:
1912                         fprintf(stderr, "erresc: unknown str ");
1913                         strdump();
1914                         break;
1915                 }
1916                 break;
1917         case 'k': /* old title set compatibility */
1918                 xsettitle(strescseq.args[0]);
1919                 break;
1920         case 'P': /* DSC -- Device Control String */
1921         case '_': /* APC -- Application Program Command */
1922         case '^': /* PM -- Privacy Message */
1923         default:
1924                 fprintf(stderr, "erresc: unknown str ");
1925                 strdump();
1926                 /* die(""); */
1927                 break;
1928         }
1929 }
1930
1931 void
1932 strparse(void) {
1933         char *p = strescseq.buf, *np, *sp;
1934
1935         strescseq.narg = 0;
1936         np = strtok_r(strescseq.buf, ";", &sp);
1937         while(p < strescseq.buf+strescseq.len && np != NULL) {
1938                 strescseq.args[strescseq.narg++] = p;
1939
1940                 np = strtok_r(NULL, ";", &sp);
1941                 if(np != NULL)
1942                         p = np;
1943         }
1944 }
1945
1946 void
1947 strdump(void) {
1948         int i;
1949         uint c;
1950
1951         printf("ESC%c", strescseq.type);
1952         for(i = 0; i < strescseq.len; i++) {
1953                 c = strescseq.buf[i] & 0xff;
1954                 if(isprint(c)) {
1955                         putchar(c);
1956                 } else if(c == '\n') {
1957                         printf("(\\n)");
1958                 } else if(c == '\r') {
1959                         printf("(\\r)");
1960                 } else if(c == 0x1b) {
1961                         printf("(\\e)");
1962                 } else {
1963                         printf("(%02x)", c);
1964                 }
1965         }
1966         printf("ESC\\\n");
1967 }
1968
1969 void
1970 strreset(void) {
1971         memset(&strescseq, 0, sizeof(strescseq));
1972 }
1973
1974 void
1975 tputtab(bool forward) {
1976         uint x = term.c.x;
1977
1978         if(forward) {
1979                 if(x == term.col)
1980                         return;
1981                 for(++x; x < term.col && !term.tabs[x]; ++x)
1982                         /* nothing */ ;
1983         } else {
1984                 if(x == 0)
1985                         return;
1986                 for(--x; x > 0 && !term.tabs[x]; --x)
1987                         /* nothing */ ;
1988         }
1989         tmoveto(x, term.c.y);
1990 }
1991
1992 void
1993 techo(char *buf, int len) {
1994         for(; len > 0; buf++, len--) {
1995                 char c = *buf;
1996
1997                 if(c == '\033') {               /* escape */
1998                         tputc("^", 1);
1999                         tputc("[", 1);
2000                 } else if(c < '\x20') { /* control code */
2001                         if(c != '\n' && c != '\r' && c != '\t') {
2002                                 c |= '\x40';
2003                                 tputc("^", 1);
2004                         }
2005                         tputc(&c, 1);
2006                 } else {
2007                         break;
2008                 }
2009         }
2010         if(len)
2011                 tputc(buf, len);
2012 }
2013
2014 void
2015 tputc(char *c, int len) {
2016         uchar ascii = *c;
2017         bool control = ascii < '\x20' || ascii == 0177;
2018
2019         if(iofd != -1) {
2020                 if(xwrite(iofd, c, len) < 0) {
2021                         fprintf(stderr, "Error writing in %s:%s\n",
2022                                 opt_io, strerror(errno));
2023                         close(iofd);
2024                         iofd = -1;
2025                 }
2026         }
2027
2028         /*
2029          * STR sequences must be checked before anything else
2030          * because it can use some control codes as part of the sequence.
2031          */
2032         if(term.esc & ESC_STR) {
2033                 switch(ascii) {
2034                 case '\033':
2035                         term.esc = ESC_START | ESC_STR_END;
2036                         break;
2037                 case '\a': /* backwards compatibility to xterm */
2038                         term.esc = 0;
2039                         strhandle();
2040                         break;
2041                 default:
2042                         if(strescseq.len + len < sizeof(strescseq.buf)) {
2043                                 memmove(&strescseq.buf[strescseq.len], c, len);
2044                                 strescseq.len += len;
2045                         } else {
2046                         /*
2047                          * Here is a bug in terminals. If the user never sends
2048                          * some code to stop the str or esc command, then st
2049                          * will stop responding. But this is better than
2050                          * silently failing with unknown characters. At least
2051                          * then users will report back.
2052                          *
2053                          * In the case users ever get fixed, here is the code:
2054                          */
2055                         /*
2056                          * term.esc = 0;
2057                          * strhandle();
2058                          */
2059                         }
2060                 }
2061                 return;
2062         }
2063
2064         /*
2065          * Actions of control codes must be performed as soon they arrive
2066          * because they can be embedded inside a control sequence, and
2067          * they must not cause conflicts with sequences.
2068          */
2069         if(control) {
2070                 switch(ascii) {
2071                 case '\t':      /* HT */
2072                         tputtab(1);
2073                         return;
2074                 case '\b':      /* BS */
2075                         tmoveto(term.c.x-1, term.c.y);
2076                         return;
2077                 case '\r':      /* CR */
2078                         tmoveto(0, term.c.y);
2079                         return;
2080                 case '\f':      /* LF */
2081                 case '\v':      /* VT */
2082                 case '\n':      /* LF */
2083                         /* go to first col if the mode is set */
2084                         tnewline(IS_SET(MODE_CRLF));
2085                         return;
2086                 case '\a':      /* BEL */
2087                         if(!(xw.state & WIN_FOCUSED))
2088                                 xseturgency(1);
2089                         return;
2090                 case '\033':    /* ESC */
2091                         csireset();
2092                         term.esc = ESC_START;
2093                         return;
2094                 case '\016':    /* SO */
2095                 case '\017':    /* SI */
2096                         /*
2097                          * Different charsets are hard to handle. Applications
2098                          * should use the right alt charset escapes for the
2099                          * only reason they still exist: line drawing. The
2100                          * rest is incompatible history st should not support.
2101                          */
2102                         return;
2103                 case '\032':    /* SUB */
2104                 case '\030':    /* CAN */
2105                         csireset();
2106                         return;
2107                 case '\005':    /* ENQ (IGNORED) */
2108                 case '\000':    /* NUL (IGNORED) */
2109                 case '\021':    /* XON (IGNORED) */
2110                 case '\023':    /* XOFF (IGNORED) */
2111                 case 0177:      /* DEL (IGNORED) */
2112                         return;
2113                 }
2114         } else if(term.esc & ESC_START) {
2115                 if(term.esc & ESC_CSI) {
2116                         csiescseq.buf[csiescseq.len++] = ascii;
2117                         if(BETWEEN(ascii, 0x40, 0x7E)
2118                                         || csiescseq.len >= ESC_BUF_SIZ) {
2119                                 term.esc = 0;
2120                                 csiparse();
2121                                 csihandle();
2122                         }
2123                 } else if(term.esc & ESC_STR_END) {
2124                         term.esc = 0;
2125                         if(ascii == '\\')
2126                                 strhandle();
2127                 } else if(term.esc & ESC_ALTCHARSET) {
2128                         switch(ascii) {
2129                         case '0': /* Line drawing set */
2130                                 term.c.attr.mode |= ATTR_GFX;
2131                                 break;
2132                         case 'B': /* USASCII */
2133                                 term.c.attr.mode &= ~ATTR_GFX;
2134                                 break;
2135                         case 'A': /* UK (IGNORED) */
2136                         case '<': /* multinational charset (IGNORED) */
2137                         case '5': /* Finnish (IGNORED) */
2138                         case 'C': /* Finnish (IGNORED) */
2139                         case 'K': /* German (IGNORED) */
2140                                 break;
2141                         default:
2142                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2143                         }
2144                         term.esc = 0;
2145                 } else if(term.esc & ESC_TEST) {
2146                         if(ascii == '8') { /* DEC screen alignment test. */
2147                                 char E[UTF_SIZ] = "E";
2148                                 int x, y;
2149
2150                                 for(x = 0; x < term.col; ++x) {
2151                                         for(y = 0; y < term.row; ++y)
2152                                                 tsetchar(E, &term.c.attr, x, y);
2153                                 }
2154                         }
2155                         term.esc = 0;
2156                 } else {
2157                         switch(ascii) {
2158                         case '[':
2159                                 term.esc |= ESC_CSI;
2160                                 break;
2161                         case '#':
2162                                 term.esc |= ESC_TEST;
2163                                 break;
2164                         case 'P': /* DCS -- Device Control String */
2165                         case '_': /* APC -- Application Program Command */
2166                         case '^': /* PM -- Privacy Message */
2167                         case ']': /* OSC -- Operating System Command */
2168                         case 'k': /* old title set compatibility */
2169                                 strreset();
2170                                 strescseq.type = ascii;
2171                                 term.esc |= ESC_STR;
2172                                 break;
2173                         case '(': /* set primary charset G0 */
2174                                 term.esc |= ESC_ALTCHARSET;
2175                                 break;
2176                         case ')': /* set secondary charset G1 (IGNORED) */
2177                         case '*': /* set tertiary charset G2 (IGNORED) */
2178                         case '+': /* set quaternary charset G3 (IGNORED) */
2179                                 term.esc = 0;
2180                                 break;
2181                         case 'D': /* IND -- Linefeed */
2182                                 if(term.c.y == term.bot) {
2183                                         tscrollup(term.top, 1);
2184                                 } else {
2185                                         tmoveto(term.c.x, term.c.y+1);
2186                                 }
2187                                 term.esc = 0;
2188                                 break;
2189                         case 'E': /* NEL -- Next line */
2190                                 tnewline(1); /* always go to first col */
2191                                 term.esc = 0;
2192                                 break;
2193                         case 'H': /* HTS -- Horizontal tab stop */
2194                                 term.tabs[term.c.x] = 1;
2195                                 term.esc = 0;
2196                                 break;
2197                         case 'M': /* RI -- Reverse index */
2198                                 if(term.c.y == term.top) {
2199                                         tscrolldown(term.top, 1);
2200                                 } else {
2201                                         tmoveto(term.c.x, term.c.y-1);
2202                                 }
2203                                 term.esc = 0;
2204                                 break;
2205                         case 'Z': /* DECID -- Identify Terminal */
2206                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2207                                 term.esc = 0;
2208                                 break;
2209                         case 'c': /* RIS -- Reset to inital state */
2210                                 treset();
2211                                 term.esc = 0;
2212                                 xresettitle();
2213                                 break;
2214                         case '=': /* DECPAM -- Application keypad */
2215                                 term.mode |= MODE_APPKEYPAD;
2216                                 term.esc = 0;
2217                                 break;
2218                         case '>': /* DECPNM -- Normal keypad */
2219                                 term.mode &= ~MODE_APPKEYPAD;
2220                                 term.esc = 0;
2221                                 break;
2222                         case '7': /* DECSC -- Save Cursor */
2223                                 tcursor(CURSOR_SAVE);
2224                                 term.esc = 0;
2225                                 break;
2226                         case '8': /* DECRC -- Restore Cursor */
2227                                 tcursor(CURSOR_LOAD);
2228                                 term.esc = 0;
2229                                 break;
2230                         case '\\': /* ST -- Stop */
2231                                 term.esc = 0;
2232                                 break;
2233                         default:
2234                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2235                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2236                                 term.esc = 0;
2237                         }
2238                 }
2239                 /*
2240                  * All characters which form part of a sequence are not
2241                  * printed
2242                  */
2243                 return;
2244         }
2245         /*
2246          * Display control codes only if we are in graphic mode
2247          */
2248         if(control && !(term.c.attr.mode & ATTR_GFX))
2249                 return;
2250         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2251                 sel.bx = -1;
2252         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2253                 tnewline(1); /* always go to first col */
2254
2255         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2256                 memmove(&term.line[term.c.y][term.c.x+1],
2257                         &term.line[term.c.y][term.c.x],
2258                         (term.col - term.c.x - 1) * sizeof(Glyph));
2259         }
2260
2261         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2262         if(term.c.x+1 < term.col) {
2263                 tmoveto(term.c.x+1, term.c.y);
2264         } else {
2265                 term.c.state |= CURSOR_WRAPNEXT;
2266         }
2267 }
2268
2269 int
2270 tresize(int col, int row) {
2271         int i, x;
2272         int minrow = MIN(row, term.row);
2273         int mincol = MIN(col, term.col);
2274         int slide = term.c.y - row + 1;
2275         bool *bp;
2276
2277         if(col < 1 || row < 1)
2278                 return 0;
2279
2280         /* free unneeded rows */
2281         i = 0;
2282         if(slide > 0) {
2283                 /*
2284                  * slide screen to keep cursor where we expect it -
2285                  * tscrollup would work here, but we can optimize to
2286                  * memmove because we're freeing the earlier lines
2287                  */
2288                 for(/* i = 0 */; i < slide; i++) {
2289                         free(term.line[i]);
2290                         free(term.alt[i]);
2291                 }
2292                 memmove(term.line, term.line + slide, row * sizeof(Line));
2293                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2294         }
2295         for(i += row; i < term.row; i++) {
2296                 free(term.line[i]);
2297                 free(term.alt[i]);
2298         }
2299
2300         /* resize to new height */
2301         term.line = xrealloc(term.line, row * sizeof(Line));
2302         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2303         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2304         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2305
2306         /* resize each row to new width, zero-pad if needed */
2307         for(i = 0; i < minrow; i++) {
2308                 term.dirty[i] = 1;
2309                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2310                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2311                 for(x = mincol; x < col; x++) {
2312                         term.line[i][x].state = 0;
2313                         term.alt[i][x].state = 0;
2314                 }
2315         }
2316
2317         /* allocate any new rows */
2318         for(/* i == minrow */; i < row; i++) {
2319                 term.dirty[i] = 1;
2320                 term.line[i] = xcalloc(col, sizeof(Glyph));
2321                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2322         }
2323         if(col > term.col) {
2324                 bp = term.tabs + term.col;
2325
2326                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2327                 while(--bp > term.tabs && !*bp)
2328                         /* nothing */ ;
2329                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2330                         *bp = 1;
2331         }
2332         /* update terminal size */
2333         term.col = col;
2334         term.row = row;
2335         /* reset scrolling region */
2336         tsetscroll(0, row-1);
2337         /* make use of the LIMIT in tmoveto */
2338         tmoveto(term.c.x, term.c.y);
2339
2340         return (slide > 0);
2341 }
2342
2343 void
2344 xresize(int col, int row) {
2345         xw.tw = MAX(1, col * xw.cw);
2346         xw.th = MAX(1, row * xw.ch);
2347
2348         XFreePixmap(xw.dpy, xw.buf);
2349         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2350                         DefaultDepth(xw.dpy, xw.scr));
2351         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2352         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2353
2354         XftDrawChange(xw.draw, xw.buf);
2355 }
2356
2357 static inline ushort
2358 sixd_to_16bit(int x) {
2359         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2360 }
2361
2362 void
2363 xloadcols(void) {
2364         int i, r, g, b;
2365         XRenderColor color = { .alpha = 0xffff };
2366
2367         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2368         for(i = 0; i < LEN(colorname); i++) {
2369                 if(!colorname[i])
2370                         continue;
2371                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2372                         die("Could not allocate color '%s'\n", colorname[i]);
2373                 }
2374         }
2375
2376         /* load colors [16-255] ; same colors as xterm */
2377         for(i = 16, r = 0; r < 6; r++) {
2378                 for(g = 0; g < 6; g++) {
2379                         for(b = 0; b < 6; b++) {
2380                                 color.red = sixd_to_16bit(r);
2381                                 color.green = sixd_to_16bit(g);
2382                                 color.blue = sixd_to_16bit(b);
2383                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2384                                         die("Could not allocate color %d\n", i);
2385                                 }
2386                                 i++;
2387                         }
2388                 }
2389         }
2390
2391         for(r = 0; r < 24; r++, i++) {
2392                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2393                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2394                                         &dc.col[i])) {
2395                         die("Could not allocate color %d\n", i);
2396                 }
2397         }
2398 }
2399
2400 int
2401 xsetcolorname(int x, const char *name) {
2402         XRenderColor color = { .alpha = 0xffff };
2403         Colour colour;
2404         if (x < 0 || x > LEN(colorname))
2405                 return -1;
2406         if(!name) {
2407                 if(16 <= x && x < 16 + 216) {
2408                         int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2409                         color.red = sixd_to_16bit(r);
2410                         color.green = sixd_to_16bit(g);
2411                         color.blue = sixd_to_16bit(b);
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 if (16 + 216 <= x && x < 256) {
2417                         color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2418                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2419                                 return 0; /* something went wrong */
2420                         dc.col[x] = colour;
2421                         return 1;
2422                 } else {
2423                         name = colorname[x];
2424                 }
2425         }
2426         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2427                 return 0;
2428         dc.col[x] = colour;
2429         return 1;
2430 }
2431
2432 void
2433 xtermclear(int col1, int row1, int col2, int row2) {
2434         XftDrawRect(xw.draw,
2435                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2436                         borderpx + col1 * xw.cw,
2437                         borderpx + row1 * xw.ch,
2438                         (col2-col1+1) * xw.cw,
2439                         (row2-row1+1) * xw.ch);
2440 }
2441
2442 /*
2443  * Absolute coordinates.
2444  */
2445 void
2446 xclear(int x1, int y1, int x2, int y2) {
2447         XftDrawRect(xw.draw,
2448                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2449                         x1, y1, x2-x1, y2-y1);
2450 }
2451
2452 void
2453 xhints(void) {
2454         XClassHint class = {opt_class ? opt_class : termname, termname};
2455         XWMHints wm = {.flags = InputHint, .input = 1};
2456         XSizeHints *sizeh = NULL;
2457
2458         sizeh = XAllocSizeHints();
2459         if(xw.isfixed == False) {
2460                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2461                 sizeh->height = xw.h;
2462                 sizeh->width = xw.w;
2463                 sizeh->height_inc = xw.ch;
2464                 sizeh->width_inc = xw.cw;
2465                 sizeh->base_height = 2 * borderpx;
2466                 sizeh->base_width = 2 * borderpx;
2467         } else {
2468                 sizeh->flags = PMaxSize | PMinSize;
2469                 sizeh->min_width = sizeh->max_width = xw.fw;
2470                 sizeh->min_height = sizeh->max_height = xw.fh;
2471         }
2472
2473         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2474         XFree(sizeh);
2475 }
2476
2477 int
2478 xloadfont(Font *f, FcPattern *pattern) {
2479         FcPattern *match;
2480         FcResult result;
2481
2482         match = FcFontMatch(NULL, pattern, &result);
2483         if(!match)
2484                 return 1;
2485
2486         if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2487                 FcPatternDestroy(match);
2488                 return 1;
2489         }
2490
2491         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2492                 FcPatternDestroy(match);
2493                 return 1;
2494         }
2495
2496         f->pattern = FcPatternDuplicate(pattern);
2497
2498         f->ascent = f->match->ascent;
2499         f->descent = f->match->descent;
2500         f->lbearing = 0;
2501         f->rbearing = f->match->max_advance_width;
2502
2503         f->height = f->match->height;
2504         f->width = f->lbearing + f->rbearing;
2505
2506         return 0;
2507 }
2508
2509 void
2510 xloadfonts(char *fontstr, int fontsize) {
2511         FcPattern *pattern;
2512         FcResult result;
2513         double fontval;
2514
2515         if(fontstr[0] == '-') {
2516                 pattern = XftXlfdParse(fontstr, False, False);
2517         } else {
2518                 pattern = FcNameParse((FcChar8 *)fontstr);
2519         }
2520
2521         if(!pattern)
2522                 die("st: can't open font %s\n", fontstr);
2523
2524         if(fontsize > 0) {
2525                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2526                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2527                 usedfontsize = fontsize;
2528         } else {
2529                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2530                 if(result == FcResultMatch) {
2531                         usedfontsize = (int)fontval;
2532                 } else {
2533                         /*
2534                          * Default font size is 12, if none given. This is to
2535                          * have a known usedfontsize value.
2536                          */
2537                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2538                         usedfontsize = 12;
2539                 }
2540         }
2541
2542         FcConfigSubstitute(0, pattern, FcMatchPattern);
2543         FcDefaultSubstitute(pattern);
2544
2545         if(xloadfont(&dc.font, pattern))
2546                 die("st: can't open font %s\n", fontstr);
2547
2548         /* Setting character width and height. */
2549         xw.cw = dc.font.width;
2550         xw.ch = dc.font.height;
2551
2552         FcPatternDel(pattern, FC_SLANT);
2553         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2554         if(xloadfont(&dc.ifont, pattern))
2555                 die("st: can't open font %s\n", fontstr);
2556
2557         FcPatternDel(pattern, FC_WEIGHT);
2558         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2559         if(xloadfont(&dc.ibfont, pattern))
2560                 die("st: can't open font %s\n", fontstr);
2561
2562         FcPatternDel(pattern, FC_SLANT);
2563         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2564         if(xloadfont(&dc.bfont, pattern))
2565                 die("st: can't open font %s\n", fontstr);
2566
2567         FcPatternDestroy(pattern);
2568 }
2569
2570 void
2571 xunloadfonts(void) {
2572         int i, ip;
2573
2574         /*
2575          * Free the loaded fonts in the font cache. This is done backwards
2576          * from the frccur.
2577          */
2578         for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2579                 if(ip < 0)
2580                         ip = LEN(frc) - 1;
2581                 XftFontClose(xw.dpy, frc[ip].font);
2582         }
2583         frccur = -1;
2584         frclen = 0;
2585
2586         XftFontClose(xw.dpy, dc.font.match);
2587         FcPatternDestroy(dc.font.pattern);
2588         FcFontSetDestroy(dc.font.set);
2589         XftFontClose(xw.dpy, dc.bfont.match);
2590         FcPatternDestroy(dc.bfont.pattern);
2591         FcFontSetDestroy(dc.bfont.set);
2592         XftFontClose(xw.dpy, dc.ifont.match);
2593         FcPatternDestroy(dc.ifont.pattern);
2594         FcFontSetDestroy(dc.ifont.set);
2595         XftFontClose(xw.dpy, dc.ibfont.match);
2596         FcPatternDestroy(dc.ibfont.pattern);
2597         FcFontSetDestroy(dc.ibfont.set);
2598 }
2599
2600 void
2601 xzoom(const Arg *arg) {
2602         xunloadfonts();
2603         xloadfonts(usedfont, usedfontsize + arg->i);
2604         cresize(0, 0);
2605         redraw(0);
2606 }
2607
2608 void
2609 xinit(void) {
2610         XSetWindowAttributes attrs;
2611         XGCValues gcvalues;
2612         Cursor cursor;
2613         Window parent;
2614         int sw, sh;
2615
2616         if(!(xw.dpy = XOpenDisplay(NULL)))
2617                 die("Can't open display\n");
2618         xw.scr = XDefaultScreen(xw.dpy);
2619         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2620
2621         /* font */
2622         if(!FcInit())
2623                 die("Could not init fontconfig.\n");
2624
2625         usedfont = (opt_font == NULL)? font : opt_font;
2626         xloadfonts(usedfont, 0);
2627
2628         /* colors */
2629         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2630         xloadcols();
2631
2632         /* adjust fixed window geometry */
2633         if(xw.isfixed) {
2634                 sw = DisplayWidth(xw.dpy, xw.scr);
2635                 sh = DisplayHeight(xw.dpy, xw.scr);
2636                 if(xw.fx < 0)
2637                         xw.fx = sw + xw.fx - xw.fw - 1;
2638                 if(xw.fy < 0)
2639                         xw.fy = sh + xw.fy - xw.fh - 1;
2640
2641                 xw.h = xw.fh;
2642                 xw.w = xw.fw;
2643         } else {
2644                 /* window - default size */
2645                 xw.h = 2 * borderpx + term.row * xw.ch;
2646                 xw.w = 2 * borderpx + term.col * xw.cw;
2647                 xw.fx = 0;
2648                 xw.fy = 0;
2649         }
2650
2651         /* Events */
2652         attrs.background_pixel = dc.col[defaultbg].pixel;
2653         attrs.border_pixel = dc.col[defaultbg].pixel;
2654         attrs.bit_gravity = NorthWestGravity;
2655         attrs.event_mask = FocusChangeMask | KeyPressMask
2656                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2657                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2658         attrs.colormap = xw.cmap;
2659
2660         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2661                         XRootWindow(xw.dpy, xw.scr);
2662         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2663                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2664                         xw.vis,
2665                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2666                         | CWColormap,
2667                         &attrs);
2668
2669         memset(&gcvalues, 0, sizeof(gcvalues));
2670         gcvalues.graphics_exposures = False;
2671         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2672                         &gcvalues);
2673         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2674                         DefaultDepth(xw.dpy, xw.scr));
2675         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2676         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2677
2678         /* Xft rendering context */
2679         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2680
2681         /* input methods */
2682         if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2683                 XSetLocaleModifiers("@im=local");
2684                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2685                         XSetLocaleModifiers("@im=");
2686                         if((xw.xim = XOpenIM(xw.dpy,
2687                                         NULL, NULL, NULL)) == NULL) {
2688                                 die("XOpenIM failed. Could not open input"
2689                                         " device.\n");
2690                         }
2691                 }
2692         }
2693         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2694                                            | XIMStatusNothing, XNClientWindow, xw.win,
2695                                            XNFocusWindow, xw.win, NULL);
2696         if(xw.xic == NULL)
2697                 die("XCreateIC failed. Could not obtain input method.\n");
2698
2699         /* white cursor, black outline */
2700         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2701         XDefineCursor(xw.dpy, xw.win, cursor);
2702         XRecolorCursor(xw.dpy, cursor,
2703                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2704                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2705
2706         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2707         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2708         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2709
2710         xresettitle();
2711         XMapWindow(xw.dpy, xw.win);
2712         xhints();
2713         XSync(xw.dpy, 0);
2714 }
2715
2716 void
2717 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2718         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2719             width = charlen * xw.cw, xp, i;
2720         int frp, frcflags;
2721         int u8fl, u8fblen, u8cblen, doesexist;
2722         char *u8c, *u8fs;
2723         long u8char;
2724         Font *font = &dc.font;
2725         FcResult fcres;
2726         FcPattern *fcpattern, *fontpattern;
2727         FcFontSet *fcsets[] = { NULL };
2728         FcCharSet *fccharset;
2729         Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2730                  *temp, revfg, revbg;
2731         XRenderColor colfg, colbg;
2732
2733         frcflags = FRC_NORMAL;
2734
2735         if(base.mode & ATTR_BOLD) {
2736                 if(BETWEEN(base.fg, 0, 7)) {
2737                         /* basic system colors */
2738                         fg = &dc.col[base.fg + 8];
2739                 } else if(BETWEEN(base.fg, 16, 195)) {
2740                         /* 256 colors */
2741                         fg = &dc.col[base.fg + 36];
2742                 } else if(BETWEEN(base.fg, 232, 251)) {
2743                         /* greyscale */
2744                         fg = &dc.col[base.fg + 4];
2745                 }
2746                 /*
2747                  * Those ranges will not be brightened:
2748                  *      8 - 15 – bright system colors
2749                  *      196 - 231 – highest 256 color cube
2750                  *      252 - 255 – brightest colors in greyscale
2751                  */
2752                 font = &dc.bfont;
2753                 frcflags = FRC_BOLD;
2754         }
2755
2756         if(base.mode & ATTR_ITALIC) {
2757                 font = &dc.ifont;
2758                 frcflags = FRC_ITALIC;
2759         }
2760         if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2761                 font = &dc.ibfont;
2762                 frcflags = FRC_ITALICBOLD;
2763         }
2764
2765         if(IS_SET(MODE_REVERSE)) {
2766                 if(fg == &dc.col[defaultfg]) {
2767                         fg = &dc.col[defaultbg];
2768                 } else {
2769                         colfg.red = ~fg->color.red;
2770                         colfg.green = ~fg->color.green;
2771                         colfg.blue = ~fg->color.blue;
2772                         colfg.alpha = fg->color.alpha;
2773                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2774                         fg = &revfg;
2775                 }
2776
2777                 if(bg == &dc.col[defaultbg]) {
2778                         bg = &dc.col[defaultfg];
2779                 } else {
2780                         colbg.red = ~bg->color.red;
2781                         colbg.green = ~bg->color.green;
2782                         colbg.blue = ~bg->color.blue;
2783                         colbg.alpha = bg->color.alpha;
2784                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2785                         bg = &revbg;
2786                 }
2787         }
2788
2789         if(base.mode & ATTR_REVERSE) {
2790                 temp = fg;
2791                 fg = bg;
2792                 bg = temp;
2793         }
2794
2795         /* Intelligent cleaning up of the borders. */
2796         if(x == 0) {
2797                 xclear(0, (y == 0)? 0 : winy, borderpx,
2798                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2799         }
2800         if(x + charlen >= term.col) {
2801                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2802                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2803         }
2804         if(y == 0)
2805                 xclear(winx, 0, winx + width, borderpx);
2806         if(y == term.row-1)
2807                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2808
2809         /* Clean up the region we want to draw to. */
2810         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2811
2812         fcsets[0] = font->set;
2813         for(xp = winx; bytelen > 0;) {
2814                 /*
2815                  * Search for the range in the to be printed string of glyphs
2816                  * that are in the main font. Then print that range. If
2817                  * some glyph is found that is not in the font, do the
2818                  * fallback dance.
2819                  */
2820                 u8fs = s;
2821                 u8fblen = 0;
2822                 u8fl = 0;
2823                 for(;;) {
2824                         u8c = s;
2825                         u8cblen = utf8decode(s, &u8char);
2826                         s += u8cblen;
2827                         bytelen -= u8cblen;
2828
2829                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2830                         if(!doesexist || bytelen <= 0) {
2831                                 if(bytelen <= 0) {
2832                                         if(doesexist) {
2833                                                 u8fl++;
2834                                                 u8fblen += u8cblen;
2835                                         }
2836                                 }
2837
2838                                 if(u8fl > 0) {
2839                                         XftDrawStringUtf8(xw.draw, fg,
2840                                                         font->match, xp,
2841                                                         winy + font->ascent,
2842                                                         (FcChar8 *)u8fs,
2843                                                         u8fblen);
2844                                         xp += font->width * u8fl;
2845                                 }
2846                                 break;
2847                         }
2848
2849                         u8fl++;
2850                         u8fblen += u8cblen;
2851                 }
2852                 if(doesexist)
2853                         break;
2854
2855                 frp = frccur;
2856                 /* Search the font cache. */
2857                 for(i = 0; i < frclen; i++, frp--) {
2858                         if(frp <= 0)
2859                                 frp = LEN(frc) - 1;
2860
2861                         if(frc[frp].c == u8char
2862                                         && frc[frp].flags == frcflags) {
2863                                 break;
2864                         }
2865                 }
2866
2867                 /* Nothing was found. */
2868                 if(i >= frclen) {
2869                         /*
2870                          * Nothing was found in the cache. Now use
2871                          * some dozen of Fontconfig calls to get the
2872                          * font for one single character.
2873                          */
2874                         fcpattern = FcPatternDuplicate(font->pattern);
2875                         fccharset = FcCharSetCreate();
2876
2877                         FcCharSetAddChar(fccharset, u8char);
2878                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
2879                                         fccharset);
2880                         FcPatternAddBool(fcpattern, FC_SCALABLE,
2881                                         FcTrue);
2882
2883                         FcConfigSubstitute(0, fcpattern,
2884                                         FcMatchPattern);
2885                         FcDefaultSubstitute(fcpattern);
2886
2887                         fontpattern = FcFontSetMatch(0, fcsets,
2888                                         FcTrue, fcpattern, &fcres);
2889
2890                         /*
2891                          * Overwrite or create the new cache entry
2892                          * entry.
2893                          */
2894                         frccur++;
2895                         frclen++;
2896                         if(frccur >= LEN(frc))
2897                                 frccur = 0;
2898                         if(frclen > LEN(frc)) {
2899                                 frclen = LEN(frc);
2900                                 XftFontClose(xw.dpy, frc[frccur].font);
2901                         }
2902
2903                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
2904                                         fontpattern);
2905                         frc[frccur].c = u8char;
2906                         frc[frccur].flags = frcflags;
2907
2908                         FcPatternDestroy(fcpattern);
2909                         FcCharSetDestroy(fccharset);
2910
2911                         frp = frccur;
2912                 }
2913
2914                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2915                                 xp, winy + frc[frp].font->ascent,
2916                                 (FcChar8 *)u8c, u8cblen);
2917
2918                 xp += font->width;
2919         }
2920
2921         /*
2922         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2923                         winy + font->ascent, (FcChar8 *)s, bytelen);
2924         */
2925
2926         if(base.mode & ATTR_UNDERLINE) {
2927                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2928                                 width, 1);
2929         }
2930 }
2931
2932 void
2933 xdrawcursor(void) {
2934         static int oldx = 0, oldy = 0;
2935         int sl;
2936         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2937
2938         LIMIT(oldx, 0, term.col-1);
2939         LIMIT(oldy, 0, term.row-1);
2940
2941         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2942                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2943
2944         /* remove the old cursor */
2945         if(term.line[oldy][oldx].state & GLYPH_SET) {
2946                 sl = utf8size(term.line[oldy][oldx].c);
2947                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2948                                 oldy, 1, sl);
2949         } else {
2950                 xtermclear(oldx, oldy, oldx, oldy);
2951         }
2952
2953         /* draw the new one */
2954         if(!(IS_SET(MODE_HIDE))) {
2955                 if(!(xw.state & WIN_FOCUSED))
2956                         g.bg = defaultucs;
2957
2958                 if(IS_SET(MODE_REVERSE))
2959                         g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2960
2961                 sl = utf8size(g.c);
2962                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2963                 oldx = term.c.x, oldy = term.c.y;
2964         }
2965 }
2966
2967
2968 void
2969 xsettitle(char *p) {
2970         XTextProperty prop;
2971
2972         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2973                         &prop);
2974         XSetWMName(xw.dpy, xw.win, &prop);
2975 }
2976
2977 void
2978 xresettitle(void) {
2979         xsettitle(opt_title ? opt_title : "st");
2980 }
2981
2982 void
2983 redraw(int timeout) {
2984         struct timespec tv = {0, timeout * 1000};
2985
2986         tfulldirt();
2987         draw();
2988
2989         if(timeout > 0) {
2990                 nanosleep(&tv, NULL);
2991                 XSync(xw.dpy, False); /* necessary for a good tput flash */
2992         }
2993 }
2994
2995 void
2996 draw(void) {
2997         drawregion(0, 0, term.col, term.row);
2998         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2999                         xw.h, 0, 0);
3000         XSetForeground(xw.dpy, dc.gc,
3001                         dc.col[IS_SET(MODE_REVERSE)?
3002                                 defaultfg : defaultbg].pixel);
3003 }
3004
3005 void
3006 drawregion(int x1, int y1, int x2, int y2) {
3007         int ic, ib, x, y, ox, sl;
3008         Glyph base, new;
3009         char buf[DRAW_BUF_SIZ];
3010         bool ena_sel = sel.bx != -1;
3011
3012         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3013                 ena_sel = 0;
3014
3015         if(!(xw.state & WIN_VISIBLE))
3016                 return;
3017
3018         for(y = y1; y < y2; y++) {
3019                 if(!term.dirty[y])
3020                         continue;
3021
3022                 xtermclear(0, y, term.col, y);
3023                 term.dirty[y] = 0;
3024                 base = term.line[y][0];
3025                 ic = ib = ox = 0;
3026                 for(x = x1; x < x2; x++) {
3027                         new = term.line[y][x];
3028                         if(ena_sel && *(new.c) && selected(x, y))
3029                                 new.mode ^= ATTR_REVERSE;
3030                         if(ib > 0 && (!(new.state & GLYPH_SET)
3031                                         || ATTRCMP(base, new)
3032                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3033                                 xdraws(buf, base, ox, y, ic, ib);
3034                                 ic = ib = 0;
3035                         }
3036                         if(new.state & GLYPH_SET) {
3037                                 if(ib == 0) {
3038                                         ox = x;
3039                                         base = new;
3040                                 }
3041
3042                                 sl = utf8size(new.c);
3043                                 memcpy(buf+ib, new.c, sl);
3044                                 ib += sl;
3045                                 ++ic;
3046                         }
3047                 }
3048                 if(ib > 0)
3049                         xdraws(buf, base, ox, y, ic, ib);
3050         }
3051         xdrawcursor();
3052 }
3053
3054 void
3055 expose(XEvent *ev) {
3056         XExposeEvent *e = &ev->xexpose;
3057
3058         if(xw.state & WIN_REDRAW) {
3059                 if(!e->count)
3060                         xw.state &= ~WIN_REDRAW;
3061         }
3062         redraw(0);
3063 }
3064
3065 void
3066 visibility(XEvent *ev) {
3067         XVisibilityEvent *e = &ev->xvisibility;
3068
3069         if(e->state == VisibilityFullyObscured) {
3070                 xw.state &= ~WIN_VISIBLE;
3071         } else if(!(xw.state & WIN_VISIBLE)) {
3072                 /* need a full redraw for next Expose, not just a buf copy */
3073                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3074         }
3075 }
3076
3077 void
3078 unmap(XEvent *ev) {
3079         xw.state &= ~WIN_VISIBLE;
3080 }
3081
3082 void
3083 xseturgency(int add) {
3084         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3085
3086         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3087         XSetWMHints(xw.dpy, xw.win, h);
3088         XFree(h);
3089 }
3090
3091 void
3092 focus(XEvent *ev) {
3093         XFocusChangeEvent *e = &ev->xfocus;
3094
3095         if(e->mode == NotifyGrab)
3096                 return;
3097
3098         if(ev->type == FocusIn) {
3099                 XSetICFocus(xw.xic);
3100                 xw.state |= WIN_FOCUSED;
3101                 xseturgency(0);
3102         } else {
3103                 XUnsetICFocus(xw.xic);
3104                 xw.state &= ~WIN_FOCUSED;
3105         }
3106 }
3107
3108 inline bool
3109 match(uint mask, uint state) {
3110         state &= ~(ignoremod);
3111
3112         if(mask == XK_NO_MOD && state)
3113                 return false;
3114         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3115                 return false;
3116         if((state & mask) != state)
3117                 return false;
3118         return true;
3119 }
3120
3121 void
3122 numlock(const Arg *dummy) {
3123         term.numlock ^= 1;
3124 }
3125
3126 char*
3127 kmap(KeySym k, uint state) {
3128         uint mask;
3129         Key *kp;
3130         int i;
3131
3132         /* Check for mapped keys out of X11 function keys. */
3133         for(i = 0; i < LEN(mappedkeys); i++) {
3134                 if(mappedkeys[i] == k)
3135                         break;
3136         }
3137         if(i == LEN(mappedkeys)) {
3138                 if((k & 0xFFFF) < 0xFD00)
3139                         return NULL;
3140         }
3141
3142         for(kp = key; kp < key + LEN(key); kp++) {
3143                 mask = kp->mask;
3144
3145                 if(kp->k != k)
3146                         continue;
3147
3148                 if(!match(mask, state))
3149                         continue;
3150
3151                 if(kp->appkey > 0) {
3152                         if(!IS_SET(MODE_APPKEYPAD))
3153                                 continue;
3154                         if(term.numlock && kp->appkey == 2)
3155                                 continue;
3156                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3157                         continue;
3158                 }
3159
3160                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3161                                 (kp->appcursor > 0
3162                                  && !IS_SET(MODE_APPCURSOR))) {
3163                         continue;
3164                 }
3165
3166                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3167                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3168                         continue;
3169                 }
3170
3171                 return kp->s;
3172         }
3173
3174         return NULL;
3175 }
3176
3177 void
3178 kpress(XEvent *ev) {
3179         XKeyEvent *e = &ev->xkey;
3180         KeySym ksym;
3181         char xstr[31], buf[32], *customkey, *cp = buf;
3182         int len;
3183         Status status;
3184         Shortcut *bp;
3185
3186         if(IS_SET(MODE_KBDLOCK))
3187                 return;
3188
3189         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3190         e->state &= ~Mod2Mask;
3191         /* 1. shortcuts */
3192         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3193                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3194                         bp->func(&(bp->arg));
3195                         return;
3196                 }
3197         }
3198
3199         /* 2. custom keys from config.h */
3200         if((customkey = kmap(ksym, e->state))) {
3201                 len = strlen(customkey);
3202                 memcpy(buf, customkey, len);
3203         /* 2. hardcoded (overrides X lookup) */
3204         } else {
3205                 if(len == 0)
3206                         return;
3207
3208                 if(len == 1 && e->state & Mod1Mask)
3209                         *cp++ = '\033';
3210
3211                 memcpy(cp, xstr, len);
3212                 len = cp - buf + len;
3213         }
3214
3215         ttywrite(buf, len);
3216         if(IS_SET(MODE_ECHO))
3217                 techo(buf, len);
3218 }
3219
3220
3221 void
3222 cmessage(XEvent *e) {
3223         /*
3224          * See xembed specs
3225          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3226          */
3227         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3228                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3229                         xw.state |= WIN_FOCUSED;
3230                         xseturgency(0);
3231                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3232                         xw.state &= ~WIN_FOCUSED;
3233                 }
3234         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3235                 /* Send SIGHUP to shell */
3236                 kill(pid, SIGHUP);
3237                 exit(EXIT_SUCCESS);
3238         }
3239 }
3240
3241 void
3242 cresize(int width, int height) {
3243         int col, row;
3244
3245         if(width != 0)
3246                 xw.w = width;
3247         if(height != 0)
3248                 xw.h = height;
3249
3250         col = (xw.w - 2 * borderpx) / xw.cw;
3251         row = (xw.h - 2 * borderpx) / xw.ch;
3252
3253         tresize(col, row);
3254         xresize(col, row);
3255         ttyresize();
3256 }
3257
3258 void
3259 resize(XEvent *e) {
3260         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3261                 return;
3262
3263         cresize(e->xconfigure.width, e->xconfigure.height);
3264 }
3265
3266 void
3267 run(void) {
3268         XEvent ev;
3269         fd_set rfd;
3270         int xfd = XConnectionNumber(xw.dpy), xev;
3271         struct timeval drawtimeout, *tv = NULL, now, last;
3272
3273         gettimeofday(&last, NULL);
3274
3275         for(xev = actionfps;;) {
3276                 FD_ZERO(&rfd);
3277                 FD_SET(cmdfd, &rfd);
3278                 FD_SET(xfd, &rfd);
3279                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3280                         if(errno == EINTR)
3281                                 continue;
3282                         die("select failed: %s\n", SERRNO);
3283                 }
3284
3285                 gettimeofday(&now, NULL);
3286                 drawtimeout.tv_sec = 0;
3287                 drawtimeout.tv_usec = (1000/xfps) * 1000;
3288                 tv = &drawtimeout;
3289
3290                 if(FD_ISSET(cmdfd, &rfd))
3291                         ttyread();
3292
3293                 if(FD_ISSET(xfd, &rfd))
3294                         xev = actionfps;
3295
3296                 if(TIMEDIFF(now, last) > \
3297                                 (xev ? (1000/xfps) : (1000/actionfps))) {
3298                         while(XPending(xw.dpy)) {
3299                                 XNextEvent(xw.dpy, &ev);
3300                                 if(XFilterEvent(&ev, None))
3301                                         continue;
3302                                 if(handler[ev.type])
3303                                         (handler[ev.type])(&ev);
3304                         }
3305
3306                         draw();
3307                         XFlush(xw.dpy);
3308                         last = now;
3309
3310                         if(xev && !FD_ISSET(xfd, &rfd))
3311                                 xev--;
3312                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3313                                 tv = NULL;
3314                 }
3315         }
3316 }
3317
3318 int
3319 main(int argc, char *argv[]) {
3320         int i, bitm, xr, yr;
3321         uint wr, hr;
3322
3323         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3324         xw.isfixed = False;
3325
3326         for(i = 1; i < argc; i++) {
3327                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3328                 case 'c':
3329                         if(++i < argc)
3330                                 opt_class = argv[i];
3331                         break;
3332                 case 'e':
3333                         /* eat all remaining arguments */
3334                         if(++i < argc)
3335                                 opt_cmd = &argv[i];
3336                         goto run;
3337                 case 'f':
3338                         if(++i < argc)
3339                                 opt_font = argv[i];
3340                         break;
3341                 case 'g':
3342                         if(++i >= argc)
3343                                 break;
3344
3345                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3346                         if(bitm & XValue)
3347                                 xw.fx = xr;
3348                         if(bitm & YValue)
3349                                 xw.fy = yr;
3350                         if(bitm & WidthValue)
3351                                 xw.fw = (int)wr;
3352                         if(bitm & HeightValue)
3353                                 xw.fh = (int)hr;
3354                         if(bitm & XNegative && xw.fx == 0)
3355                                 xw.fx = -1;
3356                         if(bitm & XNegative && xw.fy == 0)
3357                                 xw.fy = -1;
3358
3359                         if(xw.fh != 0 && xw.fw != 0)
3360                                 xw.isfixed = True;
3361                         break;
3362                 case 'o':
3363                         if(++i < argc)
3364                                 opt_io = argv[i];
3365                         break;
3366                 case 't':
3367                         if(++i < argc)
3368                                 opt_title = argv[i];
3369                         break;
3370                 case 'v':
3371                 default:
3372                         die(USAGE);
3373                 case 'w':
3374                         if(++i < argc)
3375                                 opt_embed = argv[i];
3376                         break;
3377                 }
3378         }
3379
3380 run:
3381         setlocale(LC_CTYPE, "");
3382         XSetLocaleModifiers("");
3383         tnew(80, 24);
3384         xinit();
3385         ttynew();
3386         selinit();
3387         run();
3388
3389         return 0;
3390 }
3391