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