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