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