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