JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Adopting arg.h with more flexible cmd handling.
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
29
30 #include "arg.h"
31
32 char *argv0;
33
34 #define Glyph Glyph_
35 #define Font Font_
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
39
40 #if   defined(__linux)
41  #include <pty.h>
42 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
43  #include <util.h>
44 #elif defined(__FreeBSD__) || defined(__DragonFly__)
45  #include <libutil.h>
46 #endif
47
48
49 /* XEMBED messages */
50 #define XEMBED_FOCUS_IN  4
51 #define XEMBED_FOCUS_OUT 5
52
53 /* Arbitrary sizes */
54 #define UTF_SIZ       4
55 #define ESC_BUF_SIZ   (128*UTF_SIZ)
56 #define ESC_ARG_SIZ   16
57 #define STR_BUF_SIZ   ESC_BUF_SIZ
58 #define STR_ARG_SIZ   ESC_ARG_SIZ
59 #define DRAW_BUF_SIZ  20*1024
60 #define XK_ANY_MOD    UINT_MAX
61 #define XK_NO_MOD     0
62 #define XK_SWITCH_MOD (1<<13)
63
64 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
65
66 /* macros */
67 #define SERRNO strerror(errno)
68 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
69 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
70 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
71 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
72 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
73 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
74 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
75 #define IS_SET(flag) ((term.mode & (flag)) != 0)
76 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
77
78 #define VT102ID "\033[?6c"
79
80 enum glyph_attribute {
81         ATTR_NULL      = 0,
82         ATTR_REVERSE   = 1,
83         ATTR_UNDERLINE = 2,
84         ATTR_BOLD      = 4,
85         ATTR_GFX       = 8,
86         ATTR_ITALIC    = 16,
87         ATTR_BLINK     = 32,
88 };
89
90 enum cursor_movement {
91         CURSOR_SAVE,
92         CURSOR_LOAD
93 };
94
95 enum cursor_state {
96         CURSOR_DEFAULT  = 0,
97         CURSOR_WRAPNEXT = 1,
98         CURSOR_ORIGIN   = 2
99 };
100
101 enum glyph_state {
102         GLYPH_SET   = 1,
103         GLYPH_DIRTY = 2
104 };
105
106 enum term_mode {
107         MODE_WRAP        = 1,
108         MODE_INSERT      = 2,
109         MODE_APPKEYPAD   = 4,
110         MODE_ALTSCREEN   = 8,
111         MODE_CRLF        = 16,
112         MODE_MOUSEBTN    = 32,
113         MODE_MOUSEMOTION = 64,
114         MODE_MOUSE       = 32|64,
115         MODE_REVERSE     = 128,
116         MODE_KBDLOCK     = 256,
117         MODE_HIDE        = 512,
118         MODE_ECHO        = 1024,
119         MODE_APPCURSOR   = 2048,
120         MODE_MOUSESGR    = 4096,
121 };
122
123 enum escape_state {
124         ESC_START      = 1,
125         ESC_CSI = 2,
126         ESC_STR = 4, /* DSC, OSC, PM, APC */
127         ESC_ALTCHARSET = 8,
128         ESC_STR_END    = 16, /* a final string was encountered */
129         ESC_TEST       = 32, /* Enter in test mode */
130 };
131
132 enum window_state {
133         WIN_VISIBLE = 1,
134         WIN_REDRAW  = 2,
135         WIN_FOCUSED = 4
136 };
137
138 enum selection_type {
139         SEL_REGULAR = 1,
140         SEL_RECTANGULAR = 2
141 };
142
143 /* bit macro */
144 #undef B0
145 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
146
147 typedef unsigned char uchar;
148 typedef unsigned int uint;
149 typedef unsigned long ulong;
150 typedef unsigned short ushort;
151
152 typedef struct {
153         char c[UTF_SIZ];     /* character code */
154         uchar mode;  /* attribute flags */
155         ushort fg;   /* foreground  */
156         ushort bg;   /* background  */
157         uchar state; /* state flags    */
158 } Glyph;
159
160 typedef Glyph *Line;
161
162 typedef struct {
163         Glyph attr;      /* current char attributes */
164         int x;
165         int y;
166         char state;
167 } TCursor;
168
169 /* CSI Escape sequence structs */
170 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
171 typedef struct {
172         char buf[ESC_BUF_SIZ]; /* raw string */
173         int len;               /* raw string length */
174         char priv;
175         int arg[ESC_ARG_SIZ];
176         int narg;              /* nb of args */
177         char mode;
178 } CSIEscape;
179
180 /* STR Escape sequence structs */
181 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
182 typedef struct {
183         char type;           /* ESC type ... */
184         char buf[STR_BUF_SIZ]; /* raw string */
185         int len;               /* raw string length */
186         char *args[STR_ARG_SIZ];
187         int narg;             /* nb of args */
188 } STREscape;
189
190 /* Internal representation of the screen */
191 typedef struct {
192         int row;        /* nb row */
193         int col;        /* nb col */
194         Line *line;     /* screen */
195         Line *alt;      /* alternate screen */
196         bool *dirty;    /* dirtyness of lines */
197         TCursor c;      /* cursor */
198         int top;        /* top    scroll limit */
199         int bot;        /* bottom scroll limit */
200         int mode;       /* terminal mode flags */
201         int esc;        /* escape state flags */
202         bool numlock;   /* lock numbers in keyboard */
203         bool *tabs;
204 } Term;
205
206 /* Purely graphic info */
207 typedef struct {
208         Display *dpy;
209         Colourmap cmap;
210         Window win;
211         Drawable buf;
212         Atom xembed, wmdeletewin;
213         XIM xim;
214         XIC xic;
215         Draw draw;
216         Visual *vis;
217         int scr;
218         bool isfixed; /* is fixed geometry? */
219         int fx, fy, fw, fh; /* fixed geometry */
220         int tw, th; /* tty width and height */
221         int w, h; /* window width and height */
222         int ch; /* char height */
223         int cw; /* char width  */
224         char state; /* focus, redraw, visible */
225 } XWindow;
226
227 typedef struct {
228         KeySym k;
229         uint mask;
230         char s[ESC_BUF_SIZ];
231         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
232         signed char appkey;             /* application keypad */
233         signed char appcursor;          /* application cursor */
234         signed char crlf;               /* crlf mode          */
235 } Key;
236
237 /* TODO: use better name for vars... */
238 typedef struct {
239         int mode;
240         int type;
241         int bx, by;
242         int ex, ey;
243         struct {
244                 int x, y;
245         } b, e;
246         char *clip;
247         Atom xtarget;
248         bool alt;
249         struct timeval tclick1;
250         struct timeval tclick2;
251 } Selection;
252
253 typedef union {
254         int i;
255         unsigned int ui;
256         float f;
257         const void *v;
258 } Arg;
259
260 typedef struct {
261         unsigned int mod;
262         KeySym keysym;
263         void (*func)(const Arg *);
264         const Arg arg;
265 } Shortcut;
266
267 /* function definitions used in config.h */
268 static void clippaste(const Arg *);
269 static void numlock(const Arg *);
270 static void selpaste(const Arg *);
271 static void xzoom(const Arg *);
272
273 /* Config.h for applying patches and the configuration. */
274 #include "config.h"
275
276 /* Font structure */
277 typedef struct {
278         int height;
279         int width;
280         int ascent;
281         int descent;
282         short lbearing;
283         short rbearing;
284         XftFont *match;
285         FcFontSet *set;
286         FcPattern *pattern;
287 } Font;
288
289 /* Drawing Context */
290 typedef struct {
291         Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
292         Font font, bfont, ifont, ibfont;
293         GC gc;
294 } DC;
295
296 static void die(const char *, ...);
297 static void draw(void);
298 static void redraw(int);
299 static void drawregion(int, int, int, int);
300 static void execsh(void);
301 static void sigchld(int);
302 static void run(void);
303
304 static void csidump(void);
305 static void csihandle(void);
306 static void csiparse(void);
307 static void csireset(void);
308 static void strdump(void);
309 static void strhandle(void);
310 static void strparse(void);
311 static void strreset(void);
312
313 static void tclearregion(int, int, int, int, 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                                 if (!allowaltscreen)
1620                                         break;
1621
1622                                 alt = IS_SET(MODE_ALTSCREEN);
1623                                 if(alt) {
1624                                         tclearregion(0, 0, term.col-1,
1625                                                         term.row-1, 0);
1626                                 }
1627                                 if(set ^ alt)           /* set is always 1 or 0 */
1628                                         tswapscreen();
1629                                 if(*args != 1049)
1630                                         break;
1631                                 /* FALLTRU */
1632                         case 1048:
1633                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1634                                 break;
1635                         default:
1636                                 fprintf(stderr,
1637                                         "erresc: unknown private set/reset mode %d\n",
1638                                         *args);
1639                                 break;
1640                         }
1641                 } else {
1642                         switch(*args) {
1643                         case 0:  /* Error (IGNORED) */
1644                                 break;
1645                         case 2:  /* KAM -- keyboard action */
1646                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1647                                 break;
1648                         case 4:  /* IRM -- Insertion-replacement */
1649                                 MODBIT(term.mode, set, MODE_INSERT);
1650                                 break;
1651                         case 12: /* SRM -- Send/Receive */
1652                                 MODBIT(term.mode, !set, MODE_ECHO);
1653                                 break;
1654                         case 20: /* LNM -- Linefeed/new line */
1655                                 MODBIT(term.mode, set, MODE_CRLF);
1656                                 break;
1657                         default:
1658                                 fprintf(stderr,
1659                                         "erresc: unknown set/reset mode %d\n",
1660                                         *args);
1661                                 break;
1662                         }
1663                 }
1664         }
1665 }
1666 #undef MODBIT
1667
1668
1669 void
1670 csihandle(void) {
1671         switch(csiescseq.mode) {
1672         default:
1673         unknown:
1674                 fprintf(stderr, "erresc: unknown csi ");
1675                 csidump();
1676                 /* die(""); */
1677                 break;
1678         case '@': /* ICH -- Insert <n> blank char */
1679                 DEFAULT(csiescseq.arg[0], 1);
1680                 tinsertblank(csiescseq.arg[0]);
1681                 break;
1682         case 'A': /* CUU -- Cursor <n> Up */
1683                 DEFAULT(csiescseq.arg[0], 1);
1684                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1685                 break;
1686         case 'B': /* CUD -- Cursor <n> Down */
1687         case 'e': /* VPR --Cursor <n> Down */
1688                 DEFAULT(csiescseq.arg[0], 1);
1689                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1690                 break;
1691         case 'c': /* DA -- Device Attributes */
1692                 if(csiescseq.arg[0] == 0)
1693                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1694                 break;
1695         case 'C': /* CUF -- Cursor <n> Forward */
1696         case 'a': /* HPR -- Cursor <n> Forward */
1697                 DEFAULT(csiescseq.arg[0], 1);
1698                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1699                 break;
1700         case 'D': /* CUB -- Cursor <n> Backward */
1701                 DEFAULT(csiescseq.arg[0], 1);
1702                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1703                 break;
1704         case 'E': /* CNL -- Cursor <n> Down and first col */
1705                 DEFAULT(csiescseq.arg[0], 1);
1706                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1707                 break;
1708         case 'F': /* CPL -- Cursor <n> Up and first col */
1709                 DEFAULT(csiescseq.arg[0], 1);
1710                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1711                 break;
1712         case 'g': /* TBC -- Tabulation clear */
1713                 switch(csiescseq.arg[0]) {
1714                 case 0: /* clear current tab stop */
1715                         term.tabs[term.c.x] = 0;
1716                         break;
1717                 case 3: /* clear all the tabs */
1718                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1719                         break;
1720                 default:
1721                         goto unknown;
1722                 }
1723                 break;
1724         case 'G': /* CHA -- Move to <col> */
1725         case '`': /* HPA */
1726                 DEFAULT(csiescseq.arg[0], 1);
1727                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1728                 break;
1729         case 'H': /* CUP -- Move to <row> <col> */
1730         case 'f': /* HVP */
1731                 DEFAULT(csiescseq.arg[0], 1);
1732                 DEFAULT(csiescseq.arg[1], 1);
1733                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1734                 break;
1735         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1736                 DEFAULT(csiescseq.arg[0], 1);
1737                 while(csiescseq.arg[0]--)
1738                         tputtab(1);
1739                 break;
1740         case 'J': /* ED -- Clear screen */
1741                 sel.bx = -1;
1742                 switch(csiescseq.arg[0]) {
1743                 case 0: /* below */
1744                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1745                         if(term.c.y < term.row-1) {
1746                                 tclearregion(0, term.c.y+1, term.col-1,
1747                                                 term.row-1, 1);
1748                         }
1749                         break;
1750                 case 1: /* above */
1751                         if(term.c.y > 1)
1752                                 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1753                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1754                         break;
1755                 case 2: /* all */
1756                         tclearregion(0, 0, term.col-1, term.row-1, 1);
1757                         break;
1758                 default:
1759                         goto unknown;
1760                 }
1761                 break;
1762         case 'K': /* EL -- Clear line */
1763                 switch(csiescseq.arg[0]) {
1764                 case 0: /* right */
1765                         tclearregion(term.c.x, term.c.y, term.col-1,
1766                                         term.c.y, 1);
1767                         break;
1768                 case 1: /* left */
1769                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1770                         break;
1771                 case 2: /* all */
1772                         tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1773                         break;
1774                 }
1775                 break;
1776         case 'S': /* SU -- Scroll <n> line up */
1777                 DEFAULT(csiescseq.arg[0], 1);
1778                 tscrollup(term.top, csiescseq.arg[0]);
1779                 break;
1780         case 'T': /* SD -- Scroll <n> line down */
1781                 DEFAULT(csiescseq.arg[0], 1);
1782                 tscrolldown(term.top, csiescseq.arg[0]);
1783                 break;
1784         case 'L': /* IL -- Insert <n> blank lines */
1785                 DEFAULT(csiescseq.arg[0], 1);
1786                 tinsertblankline(csiescseq.arg[0]);
1787                 break;
1788         case 'l': /* RM -- Reset Mode */
1789                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1790                 break;
1791         case 'M': /* DL -- Delete <n> lines */
1792                 DEFAULT(csiescseq.arg[0], 1);
1793                 tdeleteline(csiescseq.arg[0]);
1794                 break;
1795         case 'X': /* ECH -- Erase <n> char */
1796                 DEFAULT(csiescseq.arg[0], 1);
1797                 tclearregion(term.c.x, term.c.y,
1798                                 term.c.x + csiescseq.arg[0] - 1, term.c.y, 1);
1799                 break;
1800         case 'P': /* DCH -- Delete <n> char */
1801                 DEFAULT(csiescseq.arg[0], 1);
1802                 tdeletechar(csiescseq.arg[0]);
1803                 break;
1804         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1805                 DEFAULT(csiescseq.arg[0], 1);
1806                 while(csiescseq.arg[0]--)
1807                         tputtab(0);
1808                 break;
1809         case 'd': /* VPA -- Move to <row> */
1810                 DEFAULT(csiescseq.arg[0], 1);
1811                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1812                 break;
1813         case 'h': /* SM -- Set terminal mode */
1814                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1815                 break;
1816         case 'm': /* SGR -- Terminal attribute (color) */
1817                 tsetattr(csiescseq.arg, csiescseq.narg);
1818                 break;
1819         case 'r': /* DECSTBM -- Set Scrolling Region */
1820                 if(csiescseq.priv) {
1821                         goto unknown;
1822                 } else {
1823                         DEFAULT(csiescseq.arg[0], 1);
1824                         DEFAULT(csiescseq.arg[1], term.row);
1825                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1826                         tmoveato(0, 0);
1827                 }
1828                 break;
1829         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1830                 tcursor(CURSOR_SAVE);
1831                 break;
1832         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1833                 tcursor(CURSOR_LOAD);
1834                 break;
1835         }
1836 }
1837
1838 void
1839 csidump(void) {
1840         int i;
1841         uint c;
1842
1843         printf("ESC[");
1844         for(i = 0; i < csiescseq.len; i++) {
1845                 c = csiescseq.buf[i] & 0xff;
1846                 if(isprint(c)) {
1847                         putchar(c);
1848                 } else if(c == '\n') {
1849                         printf("(\\n)");
1850                 } else if(c == '\r') {
1851                         printf("(\\r)");
1852                 } else if(c == 0x1b) {
1853                         printf("(\\e)");
1854                 } else {
1855                         printf("(%02x)", c);
1856                 }
1857         }
1858         putchar('\n');
1859 }
1860
1861 void
1862 csireset(void) {
1863         memset(&csiescseq, 0, sizeof(csiescseq));
1864 }
1865
1866 void
1867 strhandle(void) {
1868         char *p = NULL;
1869         int i, j, narg;
1870
1871         strparse();
1872         narg = strescseq.narg;
1873
1874         switch(strescseq.type) {
1875         case ']': /* OSC -- Operating System Command */
1876                 switch(i = atoi(strescseq.args[0])) {
1877                 case 0:
1878                 case 1:
1879                 case 2:
1880                         if(narg > 1)
1881                                 xsettitle(strescseq.args[1]);
1882                         break;
1883                 case 4: /* color set */
1884                         if(narg < 3)
1885                                 break;
1886                         p = strescseq.args[2];
1887                         /* fall through */
1888                 case 104: /* color reset, here p = NULL */
1889                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
1890                         if (!xsetcolorname(j, p)) {
1891                                 fprintf(stderr, "erresc: invalid color %s\n", p);
1892                         } else {
1893                                 /*
1894                                  * TODO if defaultbg color is changed, borders
1895                                  * are dirty
1896                                  */
1897                                 redraw(0);
1898                         }
1899                         break;
1900                 default:
1901                         fprintf(stderr, "erresc: unknown str ");
1902                         strdump();
1903                         break;
1904                 }
1905                 break;
1906         case 'k': /* old title set compatibility */
1907                 xsettitle(strescseq.args[0]);
1908                 break;
1909         case 'P': /* DSC -- Device Control String */
1910         case '_': /* APC -- Application Program Command */
1911         case '^': /* PM -- Privacy Message */
1912         default:
1913                 fprintf(stderr, "erresc: unknown str ");
1914                 strdump();
1915                 /* die(""); */
1916                 break;
1917         }
1918 }
1919
1920 void
1921 strparse(void) {
1922         char *p = strescseq.buf;
1923
1924         strescseq.narg = 0;
1925         strescseq.buf[strescseq.len] = '\0';
1926         while(p && strescseq.narg < STR_ARG_SIZ)
1927                 strescseq.args[strescseq.narg++] = strsep(&p, ";");
1928 }
1929
1930 void
1931 strdump(void) {
1932         int i;
1933         uint c;
1934
1935         printf("ESC%c", strescseq.type);
1936         for(i = 0; i < strescseq.len; i++) {
1937                 c = strescseq.buf[i] & 0xff;
1938                 if(c == '\0') {
1939                         return;
1940                 } else if(isprint(c)) {
1941                         putchar(c);
1942                 } else if(c == '\n') {
1943                         printf("(\\n)");
1944                 } else if(c == '\r') {
1945                         printf("(\\r)");
1946                 } else if(c == 0x1b) {
1947                         printf("(\\e)");
1948                 } else {
1949                         printf("(%02x)", c);
1950                 }
1951         }
1952         printf("ESC\\\n");
1953 }
1954
1955 void
1956 strreset(void) {
1957         memset(&strescseq, 0, sizeof(strescseq));
1958 }
1959
1960 void
1961 tputtab(bool forward) {
1962         uint x = term.c.x;
1963
1964         if(forward) {
1965                 if(x == term.col)
1966                         return;
1967                 for(++x; x < term.col && !term.tabs[x]; ++x)
1968                         /* nothing */ ;
1969         } else {
1970                 if(x == 0)
1971                         return;
1972                 for(--x; x > 0 && !term.tabs[x]; --x)
1973                         /* nothing */ ;
1974         }
1975         tmoveto(x, term.c.y);
1976 }
1977
1978 void
1979 techo(char *buf, int len) {
1980         for(; len > 0; buf++, len--) {
1981                 char c = *buf;
1982
1983                 if(c == '\033') {               /* escape */
1984                         tputc("^", 1);
1985                         tputc("[", 1);
1986                 } else if(c < '\x20') { /* control code */
1987                         if(c != '\n' && c != '\r' && c != '\t') {
1988                                 c |= '\x40';
1989                                 tputc("^", 1);
1990                         }
1991                         tputc(&c, 1);
1992                 } else {
1993                         break;
1994                 }
1995         }
1996         if(len)
1997                 tputc(buf, len);
1998 }
1999
2000 void
2001 tputc(char *c, int len) {
2002         uchar ascii = *c;
2003         bool control = ascii < '\x20' || ascii == 0177;
2004
2005         if(iofd != -1) {
2006                 if(xwrite(iofd, c, len) < 0) {
2007                         fprintf(stderr, "Error writing in %s:%s\n",
2008                                 opt_io, strerror(errno));
2009                         close(iofd);
2010                         iofd = -1;
2011                 }
2012         }
2013
2014         /*
2015          * STR sequences must be checked before anything else
2016          * because it can use some control codes as part of the sequence.
2017          */
2018         if(term.esc & ESC_STR) {
2019                 switch(ascii) {
2020                 case '\033':
2021                         term.esc = ESC_START | ESC_STR_END;
2022                         break;
2023                 case '\a': /* backwards compatibility to xterm */
2024                         term.esc = 0;
2025                         strhandle();
2026                         break;
2027                 default:
2028                         if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2029                                 memmove(&strescseq.buf[strescseq.len], c, len);
2030                                 strescseq.len += len;
2031                         } else {
2032                         /*
2033                          * Here is a bug in terminals. If the user never sends
2034                          * some code to stop the str or esc command, then st
2035                          * will stop responding. But this is better than
2036                          * silently failing with unknown characters. At least
2037                          * then users will report back.
2038                          *
2039                          * In the case users ever get fixed, here is the code:
2040                          */
2041                         /*
2042                          * term.esc = 0;
2043                          * strhandle();
2044                          */
2045                         }
2046                 }
2047                 return;
2048         }
2049
2050         /*
2051          * Actions of control codes must be performed as soon they arrive
2052          * because they can be embedded inside a control sequence, and
2053          * they must not cause conflicts with sequences.
2054          */
2055         if(control) {
2056                 switch(ascii) {
2057                 case '\t':      /* HT */
2058                         tputtab(1);
2059                         return;
2060                 case '\b':      /* BS */
2061                         tmoveto(term.c.x-1, term.c.y);
2062                         return;
2063                 case '\r':      /* CR */
2064                         tmoveto(0, term.c.y);
2065                         return;
2066                 case '\f':      /* LF */
2067                 case '\v':      /* VT */
2068                 case '\n':      /* LF */
2069                         /* go to first col if the mode is set */
2070                         tnewline(IS_SET(MODE_CRLF));
2071                         return;
2072                 case '\a':      /* BEL */
2073                         if(!(xw.state & WIN_FOCUSED))
2074                                 xseturgency(1);
2075                         return;
2076                 case '\033':    /* ESC */
2077                         csireset();
2078                         term.esc = ESC_START;
2079                         return;
2080                 case '\016':    /* SO */
2081                 case '\017':    /* SI */
2082                         /*
2083                          * Different charsets are hard to handle. Applications
2084                          * should use the right alt charset escapes for the
2085                          * only reason they still exist: line drawing. The
2086                          * rest is incompatible history st should not support.
2087                          */
2088                         return;
2089                 case '\032':    /* SUB */
2090                 case '\030':    /* CAN */
2091                         csireset();
2092                         return;
2093                 case '\005':    /* ENQ (IGNORED) */
2094                 case '\000':    /* NUL (IGNORED) */
2095                 case '\021':    /* XON (IGNORED) */
2096                 case '\023':    /* XOFF (IGNORED) */
2097                 case 0177:      /* DEL (IGNORED) */
2098                         return;
2099                 }
2100         } else if(term.esc & ESC_START) {
2101                 if(term.esc & ESC_CSI) {
2102                         csiescseq.buf[csiescseq.len++] = ascii;
2103                         if(BETWEEN(ascii, 0x40, 0x7E)
2104                                         || csiescseq.len >= \
2105                                         sizeof(csiescseq.buf)-1) {
2106                                 term.esc = 0;
2107                                 csiparse();
2108                                 csihandle();
2109                         }
2110                 } else if(term.esc & ESC_STR_END) {
2111                         term.esc = 0;
2112                         if(ascii == '\\')
2113                                 strhandle();
2114                 } else if(term.esc & ESC_ALTCHARSET) {
2115                         switch(ascii) {
2116                         case '0': /* Line drawing set */
2117                                 term.c.attr.mode |= ATTR_GFX;
2118                                 break;
2119                         case 'B': /* USASCII */
2120                                 term.c.attr.mode &= ~ATTR_GFX;
2121                                 break;
2122                         case 'A': /* UK (IGNORED) */
2123                         case '<': /* multinational charset (IGNORED) */
2124                         case '5': /* Finnish (IGNORED) */
2125                         case 'C': /* Finnish (IGNORED) */
2126                         case 'K': /* German (IGNORED) */
2127                                 break;
2128                         default:
2129                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2130                         }
2131                         term.esc = 0;
2132                 } else if(term.esc & ESC_TEST) {
2133                         if(ascii == '8') { /* DEC screen alignment test. */
2134                                 char E[UTF_SIZ] = "E";
2135                                 int x, y;
2136
2137                                 for(x = 0; x < term.col; ++x) {
2138                                         for(y = 0; y < term.row; ++y)
2139                                                 tsetchar(E, &term.c.attr, x, y);
2140                                 }
2141                         }
2142                         term.esc = 0;
2143                 } else {
2144                         switch(ascii) {
2145                         case '[':
2146                                 term.esc |= ESC_CSI;
2147                                 break;
2148                         case '#':
2149                                 term.esc |= ESC_TEST;
2150                                 break;
2151                         case 'P': /* DCS -- Device Control String */
2152                         case '_': /* APC -- Application Program Command */
2153                         case '^': /* PM -- Privacy Message */
2154                         case ']': /* OSC -- Operating System Command */
2155                         case 'k': /* old title set compatibility */
2156                                 strreset();
2157                                 strescseq.type = ascii;
2158                                 term.esc |= ESC_STR;
2159                                 break;
2160                         case '(': /* set primary charset G0 */
2161                                 term.esc |= ESC_ALTCHARSET;
2162                                 break;
2163                         case ')': /* set secondary charset G1 (IGNORED) */
2164                         case '*': /* set tertiary charset G2 (IGNORED) */
2165                         case '+': /* set quaternary charset G3 (IGNORED) */
2166                                 term.esc = 0;
2167                                 break;
2168                         case 'D': /* IND -- Linefeed */
2169                                 if(term.c.y == term.bot) {
2170                                         tscrollup(term.top, 1);
2171                                 } else {
2172                                         tmoveto(term.c.x, term.c.y+1);
2173                                 }
2174                                 term.esc = 0;
2175                                 break;
2176                         case 'E': /* NEL -- Next line */
2177                                 tnewline(1); /* always go to first col */
2178                                 term.esc = 0;
2179                                 break;
2180                         case 'H': /* HTS -- Horizontal tab stop */
2181                                 term.tabs[term.c.x] = 1;
2182                                 term.esc = 0;
2183                                 break;
2184                         case 'M': /* RI -- Reverse index */
2185                                 if(term.c.y == term.top) {
2186                                         tscrolldown(term.top, 1);
2187                                 } else {
2188                                         tmoveto(term.c.x, term.c.y-1);
2189                                 }
2190                                 term.esc = 0;
2191                                 break;
2192                         case 'Z': /* DECID -- Identify Terminal */
2193                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2194                                 term.esc = 0;
2195                                 break;
2196                         case 'c': /* RIS -- Reset to inital state */
2197                                 treset();
2198                                 term.esc = 0;
2199                                 xresettitle();
2200                                 break;
2201                         case '=': /* DECPAM -- Application keypad */
2202                                 term.mode |= MODE_APPKEYPAD;
2203                                 term.esc = 0;
2204                                 break;
2205                         case '>': /* DECPNM -- Normal keypad */
2206                                 term.mode &= ~MODE_APPKEYPAD;
2207                                 term.esc = 0;
2208                                 break;
2209                         case '7': /* DECSC -- Save Cursor */
2210                                 tcursor(CURSOR_SAVE);
2211                                 term.esc = 0;
2212                                 break;
2213                         case '8': /* DECRC -- Restore Cursor */
2214                                 tcursor(CURSOR_LOAD);
2215                                 term.esc = 0;
2216                                 break;
2217                         case '\\': /* ST -- Stop */
2218                                 term.esc = 0;
2219                                 break;
2220                         default:
2221                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2222                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2223                                 term.esc = 0;
2224                         }
2225                 }
2226                 /*
2227                  * All characters which form part of a sequence are not
2228                  * printed
2229                  */
2230                 return;
2231         }
2232         /*
2233          * Display control codes only if we are in graphic mode
2234          */
2235         if(control && !(term.c.attr.mode & ATTR_GFX))
2236                 return;
2237         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2238                 sel.bx = -1;
2239         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2240                 tnewline(1); /* always go to first col */
2241
2242         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2243                 memmove(&term.line[term.c.y][term.c.x+1],
2244                         &term.line[term.c.y][term.c.x],
2245                         (term.col - term.c.x - 1) * sizeof(Glyph));
2246         }
2247
2248         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2249         if(term.c.x+1 < term.col) {
2250                 tmoveto(term.c.x+1, term.c.y);
2251         } else {
2252                 term.c.state |= CURSOR_WRAPNEXT;
2253         }
2254 }
2255
2256 int
2257 tresize(int col, int row) {
2258         int i, x;
2259         int minrow = MIN(row, term.row);
2260         int mincol = MIN(col, term.col);
2261         int slide = term.c.y - row + 1;
2262         bool *bp;
2263
2264         if(col < 1 || row < 1)
2265                 return 0;
2266
2267         /* free unneeded rows */
2268         i = 0;
2269         if(slide > 0) {
2270                 /*
2271                  * slide screen to keep cursor where we expect it -
2272                  * tscrollup would work here, but we can optimize to
2273                  * memmove because we're freeing the earlier lines
2274                  */
2275                 for(/* i = 0 */; i < slide; i++) {
2276                         free(term.line[i]);
2277                         free(term.alt[i]);
2278                 }
2279                 memmove(term.line, term.line + slide, row * sizeof(Line));
2280                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2281         }
2282         for(i += row; i < term.row; i++) {
2283                 free(term.line[i]);
2284                 free(term.alt[i]);
2285         }
2286
2287         /* resize to new height */
2288         term.line = xrealloc(term.line, row * sizeof(Line));
2289         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2290         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2291         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2292
2293         /* resize each row to new width, zero-pad if needed */
2294         for(i = 0; i < minrow; i++) {
2295                 term.dirty[i] = 1;
2296                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2297                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2298                 for(x = mincol; x < col; x++) {
2299                         term.line[i][x].state = 0;
2300                         term.alt[i][x].state = 0;
2301                 }
2302         }
2303
2304         /* allocate any new rows */
2305         for(/* i == minrow */; i < row; i++) {
2306                 term.dirty[i] = 1;
2307                 term.line[i] = xcalloc(col, sizeof(Glyph));
2308                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2309         }
2310         if(col > term.col) {
2311                 bp = term.tabs + term.col;
2312
2313                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2314                 while(--bp > term.tabs && !*bp)
2315                         /* nothing */ ;
2316                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2317                         *bp = 1;
2318         }
2319         /* update terminal size */
2320         term.col = col;
2321         term.row = row;
2322         /* reset scrolling region */
2323         tsetscroll(0, row-1);
2324         /* make use of the LIMIT in tmoveto */
2325         tmoveto(term.c.x, term.c.y);
2326
2327         return (slide > 0);
2328 }
2329
2330 void
2331 xresize(int col, int row) {
2332         xw.tw = MAX(1, col * xw.cw);
2333         xw.th = MAX(1, row * xw.ch);
2334
2335         XFreePixmap(xw.dpy, xw.buf);
2336         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2337                         DefaultDepth(xw.dpy, xw.scr));
2338         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg].pixel);
2339         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2340
2341         XftDrawChange(xw.draw, xw.buf);
2342 }
2343
2344 static inline ushort
2345 sixd_to_16bit(int x) {
2346         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2347 }
2348
2349 void
2350 xloadcols(void) {
2351         int i, r, g, b;
2352         XRenderColor color = { .alpha = 0xffff };
2353
2354         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2355         for(i = 0; i < LEN(colorname); i++) {
2356                 if(!colorname[i])
2357                         continue;
2358                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2359                         die("Could not allocate color '%s'\n", colorname[i]);
2360                 }
2361         }
2362
2363         /* load colors [16-255] ; same colors as xterm */
2364         for(i = 16, r = 0; r < 6; r++) {
2365                 for(g = 0; g < 6; g++) {
2366                         for(b = 0; b < 6; b++) {
2367                                 color.red = sixd_to_16bit(r);
2368                                 color.green = sixd_to_16bit(g);
2369                                 color.blue = sixd_to_16bit(b);
2370                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2371                                         die("Could not allocate color %d\n", i);
2372                                 }
2373                                 i++;
2374                         }
2375                 }
2376         }
2377
2378         for(r = 0; r < 24; r++, i++) {
2379                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2380                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2381                                         &dc.col[i])) {
2382                         die("Could not allocate color %d\n", i);
2383                 }
2384         }
2385 }
2386
2387 int
2388 xsetcolorname(int x, const char *name) {
2389         XRenderColor color = { .alpha = 0xffff };
2390         Colour colour;
2391         if (x < 0 || x > LEN(colorname))
2392                 return -1;
2393         if(!name) {
2394                 if(16 <= x && x < 16 + 216) {
2395                         int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2396                         color.red = sixd_to_16bit(r);
2397                         color.green = sixd_to_16bit(g);
2398                         color.blue = sixd_to_16bit(b);
2399                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2400                                 return 0; /* something went wrong */
2401                         dc.col[x] = colour;
2402                         return 1;
2403                 } else if (16 + 216 <= x && x < 256) {
2404                         color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2405                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2406                                 return 0; /* something went wrong */
2407                         dc.col[x] = colour;
2408                         return 1;
2409                 } else {
2410                         name = colorname[x];
2411                 }
2412         }
2413         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2414                 return 0;
2415         dc.col[x] = colour;
2416         return 1;
2417 }
2418
2419 void
2420 xtermclear(int col1, int row1, int col2, int row2) {
2421         XftDrawRect(xw.draw,
2422                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2423                         borderpx + col1 * xw.cw,
2424                         borderpx + row1 * xw.ch,
2425                         (col2-col1+1) * xw.cw,
2426                         (row2-row1+1) * xw.ch);
2427 }
2428
2429 /*
2430  * Absolute coordinates.
2431  */
2432 void
2433 xclear(int x1, int y1, int x2, int y2) {
2434         XftDrawRect(xw.draw,
2435                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2436                         x1, y1, x2-x1, y2-y1);
2437 }
2438
2439 void
2440 xhints(void) {
2441         XClassHint class = {opt_class ? opt_class : termname, termname};
2442         XWMHints wm = {.flags = InputHint, .input = 1};
2443         XSizeHints *sizeh = NULL;
2444
2445         sizeh = XAllocSizeHints();
2446         if(xw.isfixed == False) {
2447                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2448                 sizeh->height = xw.h;
2449                 sizeh->width = xw.w;
2450                 sizeh->height_inc = xw.ch;
2451                 sizeh->width_inc = xw.cw;
2452                 sizeh->base_height = 2 * borderpx;
2453                 sizeh->base_width = 2 * borderpx;
2454         } else {
2455                 sizeh->flags = PMaxSize | PMinSize;
2456                 sizeh->min_width = sizeh->max_width = xw.fw;
2457                 sizeh->min_height = sizeh->max_height = xw.fh;
2458         }
2459
2460         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2461         XFree(sizeh);
2462 }
2463
2464 int
2465 xloadfont(Font *f, FcPattern *pattern) {
2466         FcPattern *match;
2467         FcResult result;
2468
2469         match = FcFontMatch(NULL, pattern, &result);
2470         if(!match)
2471                 return 1;
2472
2473         if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2474                 FcPatternDestroy(match);
2475                 return 1;
2476         }
2477
2478         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2479                 FcPatternDestroy(match);
2480                 return 1;
2481         }
2482
2483         f->pattern = FcPatternDuplicate(pattern);
2484
2485         f->ascent = f->match->ascent;
2486         f->descent = f->match->descent;
2487         f->lbearing = 0;
2488         f->rbearing = f->match->max_advance_width;
2489
2490         f->height = f->ascent + f->descent;
2491         f->width = f->lbearing + f->rbearing;
2492
2493         return 0;
2494 }
2495
2496 void
2497 xloadfonts(char *fontstr, int fontsize) {
2498         FcPattern *pattern;
2499         FcResult result;
2500         double fontval;
2501
2502         if(fontstr[0] == '-') {
2503                 pattern = XftXlfdParse(fontstr, False, False);
2504         } else {
2505                 pattern = FcNameParse((FcChar8 *)fontstr);
2506         }
2507
2508         if(!pattern)
2509                 die("st: can't open font %s\n", fontstr);
2510
2511         if(fontsize > 0) {
2512                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2513                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2514                 usedfontsize = fontsize;
2515         } else {
2516                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2517                 if(result == FcResultMatch) {
2518                         usedfontsize = (int)fontval;
2519                 } else {
2520                         /*
2521                          * Default font size is 12, if none given. This is to
2522                          * have a known usedfontsize value.
2523                          */
2524                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2525                         usedfontsize = 12;
2526                 }
2527         }
2528
2529         FcConfigSubstitute(0, pattern, FcMatchPattern);
2530         FcDefaultSubstitute(pattern);
2531
2532         if(xloadfont(&dc.font, pattern))
2533                 die("st: can't open font %s\n", fontstr);
2534
2535         /* Setting character width and height. */
2536         xw.cw = dc.font.width;
2537         xw.ch = dc.font.height;
2538
2539         FcPatternDel(pattern, FC_SLANT);
2540         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2541         if(xloadfont(&dc.ifont, pattern))
2542                 die("st: can't open font %s\n", fontstr);
2543
2544         FcPatternDel(pattern, FC_WEIGHT);
2545         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2546         if(xloadfont(&dc.ibfont, pattern))
2547                 die("st: can't open font %s\n", fontstr);
2548
2549         FcPatternDel(pattern, FC_SLANT);
2550         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2551         if(xloadfont(&dc.bfont, pattern))
2552                 die("st: can't open font %s\n", fontstr);
2553
2554         FcPatternDestroy(pattern);
2555 }
2556
2557 void
2558 xunloadfonts(void) {
2559         int i, ip;
2560
2561         /*
2562          * Free the loaded fonts in the font cache. This is done backwards
2563          * from the frccur.
2564          */
2565         for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2566                 if(ip < 0)
2567                         ip = LEN(frc) - 1;
2568                 XftFontClose(xw.dpy, frc[ip].font);
2569         }
2570         frccur = -1;
2571         frclen = 0;
2572
2573         XftFontClose(xw.dpy, dc.font.match);
2574         FcPatternDestroy(dc.font.pattern);
2575         FcFontSetDestroy(dc.font.set);
2576         XftFontClose(xw.dpy, dc.bfont.match);
2577         FcPatternDestroy(dc.bfont.pattern);
2578         FcFontSetDestroy(dc.bfont.set);
2579         XftFontClose(xw.dpy, dc.ifont.match);
2580         FcPatternDestroy(dc.ifont.pattern);
2581         FcFontSetDestroy(dc.ifont.set);
2582         XftFontClose(xw.dpy, dc.ibfont.match);
2583         FcPatternDestroy(dc.ibfont.pattern);
2584         FcFontSetDestroy(dc.ibfont.set);
2585 }
2586
2587 void
2588 xzoom(const Arg *arg) {
2589         xunloadfonts();
2590         xloadfonts(usedfont, usedfontsize + arg->i);
2591         cresize(0, 0);
2592         redraw(0);
2593 }
2594
2595 void
2596 xinit(void) {
2597         XSetWindowAttributes attrs;
2598         XGCValues gcvalues;
2599         Cursor cursor;
2600         Window parent;
2601         int sw, sh;
2602
2603         if(!(xw.dpy = XOpenDisplay(NULL)))
2604                 die("Can't open display\n");
2605         xw.scr = XDefaultScreen(xw.dpy);
2606         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2607
2608         /* font */
2609         if(!FcInit())
2610                 die("Could not init fontconfig.\n");
2611
2612         usedfont = (opt_font == NULL)? font : opt_font;
2613         xloadfonts(usedfont, 0);
2614
2615         /* colors */
2616         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2617         xloadcols();
2618
2619         /* adjust fixed window geometry */
2620         if(xw.isfixed) {
2621                 sw = DisplayWidth(xw.dpy, xw.scr);
2622                 sh = DisplayHeight(xw.dpy, xw.scr);
2623                 if(xw.fx < 0)
2624                         xw.fx = sw + xw.fx - xw.fw - 1;
2625                 if(xw.fy < 0)
2626                         xw.fy = sh + xw.fy - xw.fh - 1;
2627
2628                 xw.h = xw.fh;
2629                 xw.w = xw.fw;
2630         } else {
2631                 /* window - default size */
2632                 xw.h = 2 * borderpx + term.row * xw.ch;
2633                 xw.w = 2 * borderpx + term.col * xw.cw;
2634                 xw.fx = 0;
2635                 xw.fy = 0;
2636         }
2637
2638         /* Events */
2639         attrs.background_pixel = dc.col[defaultbg].pixel;
2640         attrs.border_pixel = dc.col[defaultbg].pixel;
2641         attrs.bit_gravity = NorthWestGravity;
2642         attrs.event_mask = FocusChangeMask | KeyPressMask
2643                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2644                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2645         attrs.colormap = xw.cmap;
2646
2647         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2648                         XRootWindow(xw.dpy, xw.scr);
2649         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2650                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2651                         xw.vis,
2652                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2653                         | CWColormap,
2654                         &attrs);
2655
2656         memset(&gcvalues, 0, sizeof(gcvalues));
2657         gcvalues.graphics_exposures = False;
2658         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2659                         &gcvalues);
2660         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2661                         DefaultDepth(xw.dpy, xw.scr));
2662         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2663         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2664
2665         /* Xft rendering context */
2666         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2667
2668         /* input methods */
2669         if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2670                 XSetLocaleModifiers("@im=local");
2671                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2672                         XSetLocaleModifiers("@im=");
2673                         if((xw.xim = XOpenIM(xw.dpy,
2674                                         NULL, NULL, NULL)) == NULL) {
2675                                 die("XOpenIM failed. Could not open input"
2676                                         " device.\n");
2677                         }
2678                 }
2679         }
2680         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2681                                            | XIMStatusNothing, XNClientWindow, xw.win,
2682                                            XNFocusWindow, xw.win, NULL);
2683         if(xw.xic == NULL)
2684                 die("XCreateIC failed. Could not obtain input method.\n");
2685
2686         /* white cursor, black outline */
2687         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2688         XDefineCursor(xw.dpy, xw.win, cursor);
2689         XRecolorCursor(xw.dpy, cursor,
2690                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2691                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2692
2693         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2694         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2695         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2696
2697         xresettitle();
2698         XMapWindow(xw.dpy, xw.win);
2699         xhints();
2700         XSync(xw.dpy, 0);
2701 }
2702
2703 void
2704 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2705         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2706             width = charlen * xw.cw, xp, i;
2707         int frp, frcflags;
2708         int u8fl, u8fblen, u8cblen, doesexist;
2709         char *u8c, *u8fs;
2710         long u8char;
2711         Font *font = &dc.font;
2712         FcResult fcres;
2713         FcPattern *fcpattern, *fontpattern;
2714         FcFontSet *fcsets[] = { NULL };
2715         FcCharSet *fccharset;
2716         Colour *fg, *bg, *temp, revfg, revbg;
2717         XRenderColor colfg, colbg;
2718
2719         frcflags = FRC_NORMAL;
2720
2721         if(base.mode & ATTR_ITALIC) {
2722                 if(base.fg == defaultfg)
2723                         base.fg = defaultitalic;
2724                 font = &dc.ifont;
2725                 frcflags = FRC_ITALIC;
2726         } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2727                 if(base.fg == defaultfg)
2728                         base.fg = defaultitalic;
2729                 font = &dc.ibfont;
2730                 frcflags = FRC_ITALICBOLD;
2731         } else if(base.mode & ATTR_UNDERLINE) {
2732                 if(base.fg == defaultfg)
2733                         base.fg = defaultunderline;
2734         }
2735         fg = &dc.col[base.fg];
2736         bg = &dc.col[base.bg];
2737
2738         if(base.mode & ATTR_BOLD) {
2739                 if(BETWEEN(base.fg, 0, 7)) {
2740                         /* basic system colors */
2741                         fg = &dc.col[base.fg + 8];
2742                 } else if(BETWEEN(base.fg, 16, 195)) {
2743                         /* 256 colors */
2744                         fg = &dc.col[base.fg + 36];
2745                 } else if(BETWEEN(base.fg, 232, 251)) {
2746                         /* greyscale */
2747                         fg = &dc.col[base.fg + 4];
2748                 }
2749                 /*
2750                  * Those ranges will not be brightened:
2751                  *      8 - 15 – bright system colors
2752                  *      196 - 231 – highest 256 color cube
2753                  *      252 - 255 – brightest colors in greyscale
2754                  */
2755                 font = &dc.bfont;
2756                 frcflags = FRC_BOLD;
2757         }
2758
2759         if(IS_SET(MODE_REVERSE)) {
2760                 if(fg == &dc.col[defaultfg]) {
2761                         fg = &dc.col[defaultbg];
2762                 } else {
2763                         colfg.red = ~fg->color.red;
2764                         colfg.green = ~fg->color.green;
2765                         colfg.blue = ~fg->color.blue;
2766                         colfg.alpha = fg->color.alpha;
2767                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2768                         fg = &revfg;
2769                 }
2770
2771                 if(bg == &dc.col[defaultbg]) {
2772                         bg = &dc.col[defaultfg];
2773                 } else {
2774                         colbg.red = ~bg->color.red;
2775                         colbg.green = ~bg->color.green;
2776                         colbg.blue = ~bg->color.blue;
2777                         colbg.alpha = bg->color.alpha;
2778                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2779                         bg = &revbg;
2780                 }
2781         }
2782
2783         if(base.mode & ATTR_REVERSE) {
2784                 temp = fg;
2785                 fg = bg;
2786                 bg = temp;
2787         }
2788
2789         /* Intelligent cleaning up of the borders. */
2790         if(x == 0) {
2791                 xclear(0, (y == 0)? 0 : winy, borderpx,
2792                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2793         }
2794         if(x + charlen >= term.col) {
2795                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2796                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2797         }
2798         if(y == 0)
2799                 xclear(winx, 0, winx + width, borderpx);
2800         if(y == term.row-1)
2801                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2802
2803         /* Clean up the region we want to draw to. */
2804         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2805
2806         fcsets[0] = font->set;
2807         for(xp = winx; bytelen > 0;) {
2808                 /*
2809                  * Search for the range in the to be printed string of glyphs
2810                  * that are in the main font. Then print that range. If
2811                  * some glyph is found that is not in the font, do the
2812                  * fallback dance.
2813                  */
2814                 u8fs = s;
2815                 u8fblen = 0;
2816                 u8fl = 0;
2817                 for(;;) {
2818                         u8c = s;
2819                         u8cblen = utf8decode(s, &u8char);
2820                         s += u8cblen;
2821                         bytelen -= u8cblen;
2822
2823                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2824                         if(!doesexist || bytelen <= 0) {
2825                                 if(bytelen <= 0) {
2826                                         if(doesexist) {
2827                                                 u8fl++;
2828                                                 u8fblen += u8cblen;
2829                                         }
2830                                 }
2831
2832                                 if(u8fl > 0) {
2833                                         XftDrawStringUtf8(xw.draw, fg,
2834                                                         font->match, xp,
2835                                                         winy + font->ascent,
2836                                                         (FcChar8 *)u8fs,
2837                                                         u8fblen);
2838                                         xp += font->width * u8fl;
2839                                 }
2840                                 break;
2841                         }
2842
2843                         u8fl++;
2844                         u8fblen += u8cblen;
2845                 }
2846                 if(doesexist)
2847                         break;
2848
2849                 frp = frccur;
2850                 /* Search the font cache. */
2851                 for(i = 0; i < frclen; i++, frp--) {
2852                         if(frp <= 0)
2853                                 frp = LEN(frc) - 1;
2854
2855                         if(frc[frp].c == u8char
2856                                         && frc[frp].flags == frcflags) {
2857                                 break;
2858                         }
2859                 }
2860
2861                 /* Nothing was found. */
2862                 if(i >= frclen) {
2863                         /*
2864                          * Nothing was found in the cache. Now use
2865                          * some dozen of Fontconfig calls to get the
2866                          * font for one single character.
2867                          */
2868                         fcpattern = FcPatternDuplicate(font->pattern);
2869                         fccharset = FcCharSetCreate();
2870
2871                         FcCharSetAddChar(fccharset, u8char);
2872                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
2873                                         fccharset);
2874                         FcPatternAddBool(fcpattern, FC_SCALABLE,
2875                                         FcTrue);
2876
2877                         FcConfigSubstitute(0, fcpattern,
2878                                         FcMatchPattern);
2879                         FcDefaultSubstitute(fcpattern);
2880
2881                         fontpattern = FcFontSetMatch(0, fcsets,
2882                                         FcTrue, fcpattern, &fcres);
2883
2884                         /*
2885                          * Overwrite or create the new cache entry.
2886                          */
2887                         frccur++;
2888                         frclen++;
2889                         if(frccur >= LEN(frc))
2890                                 frccur = 0;
2891                         if(frclen > LEN(frc)) {
2892                                 frclen = LEN(frc);
2893                                 XftFontClose(xw.dpy, frc[frccur].font);
2894                         }
2895
2896                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
2897                                         fontpattern);
2898                         frc[frccur].c = u8char;
2899                         frc[frccur].flags = frcflags;
2900
2901                         FcPatternDestroy(fcpattern);
2902                         FcCharSetDestroy(fccharset);
2903
2904                         frp = frccur;
2905                 }
2906
2907                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2908                                 xp, winy + frc[frp].font->ascent,
2909                                 (FcChar8 *)u8c, u8cblen);
2910
2911                 xp += font->width;
2912         }
2913
2914         /*
2915         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2916                         winy + font->ascent, (FcChar8 *)s, bytelen);
2917         */
2918
2919         if(base.mode & ATTR_UNDERLINE) {
2920                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2921                                 width, 1);
2922         }
2923 }
2924
2925 void
2926 xdrawcursor(void) {
2927         static int oldx = 0, oldy = 0;
2928         int sl;
2929         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2930
2931         LIMIT(oldx, 0, term.col-1);
2932         LIMIT(oldy, 0, term.row-1);
2933
2934         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2935                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2936
2937         /* remove the old cursor */
2938         if(term.line[oldy][oldx].state & GLYPH_SET) {
2939                 sl = utf8size(term.line[oldy][oldx].c);
2940                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2941                                 oldy, 1, sl);
2942         } else {
2943                 xtermclear(oldx, oldy, oldx, oldy);
2944         }
2945
2946         /* draw the new one */
2947         if(!(IS_SET(MODE_HIDE))) {
2948                 if(!(xw.state & WIN_FOCUSED))
2949                         g.bg = defaultucs;
2950
2951                 if(IS_SET(MODE_REVERSE))
2952                         g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2953
2954                 sl = utf8size(g.c);
2955                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2956                 oldx = term.c.x, oldy = term.c.y;
2957         }
2958 }
2959
2960
2961 void
2962 xsettitle(char *p) {
2963         XTextProperty prop;
2964
2965         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
2966                         &prop);
2967         XSetWMName(xw.dpy, xw.win, &prop);
2968 }
2969
2970 void
2971 xresettitle(void) {
2972         xsettitle(opt_title ? opt_title : "st");
2973 }
2974
2975 void
2976 redraw(int timeout) {
2977         struct timespec tv = {0, timeout * 1000};
2978
2979         tfulldirt();
2980         draw();
2981
2982         if(timeout > 0) {
2983                 nanosleep(&tv, NULL);
2984                 XSync(xw.dpy, False); /* necessary for a good tput flash */
2985         }
2986 }
2987
2988 void
2989 draw(void) {
2990         drawregion(0, 0, term.col, term.row);
2991         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2992                         xw.h, 0, 0);
2993         XSetForeground(xw.dpy, dc.gc,
2994                         dc.col[IS_SET(MODE_REVERSE)?
2995                                 defaultfg : defaultbg].pixel);
2996 }
2997
2998 void
2999 drawregion(int x1, int y1, int x2, int y2) {
3000         int ic, ib, x, y, ox, sl;
3001         Glyph base, new;
3002         char buf[DRAW_BUF_SIZ];
3003         bool ena_sel = sel.bx != -1;
3004
3005         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3006                 ena_sel = 0;
3007
3008         if(!(xw.state & WIN_VISIBLE))
3009                 return;
3010
3011         for(y = y1; y < y2; y++) {
3012                 if(!term.dirty[y])
3013                         continue;
3014
3015                 xtermclear(0, y, term.col, y);
3016                 term.dirty[y] = 0;
3017                 base = term.line[y][0];
3018                 ic = ib = ox = 0;
3019                 for(x = x1; x < x2; x++) {
3020                         new = term.line[y][x];
3021                         if(ena_sel && *(new.c) && selected(x, y))
3022                                 new.mode ^= ATTR_REVERSE;
3023                         if(ib > 0 && (!(new.state & GLYPH_SET)
3024                                         || ATTRCMP(base, new)
3025                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3026                                 xdraws(buf, base, ox, y, ic, ib);
3027                                 ic = ib = 0;
3028                         }
3029                         if(new.state & GLYPH_SET) {
3030                                 if(ib == 0) {
3031                                         ox = x;
3032                                         base = new;
3033                                 }
3034
3035                                 sl = utf8size(new.c);
3036                                 memcpy(buf+ib, new.c, sl);
3037                                 ib += sl;
3038                                 ++ic;
3039                         }
3040                 }
3041                 if(ib > 0)
3042                         xdraws(buf, base, ox, y, ic, ib);
3043         }
3044         xdrawcursor();
3045 }
3046
3047 void
3048 expose(XEvent *ev) {
3049         XExposeEvent *e = &ev->xexpose;
3050
3051         if(xw.state & WIN_REDRAW) {
3052                 if(!e->count)
3053                         xw.state &= ~WIN_REDRAW;
3054         }
3055         redraw(0);
3056 }
3057
3058 void
3059 visibility(XEvent *ev) {
3060         XVisibilityEvent *e = &ev->xvisibility;
3061
3062         if(e->state == VisibilityFullyObscured) {
3063                 xw.state &= ~WIN_VISIBLE;
3064         } else if(!(xw.state & WIN_VISIBLE)) {
3065                 /* need a full redraw for next Expose, not just a buf copy */
3066                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3067         }
3068 }
3069
3070 void
3071 unmap(XEvent *ev) {
3072         xw.state &= ~WIN_VISIBLE;
3073 }
3074
3075 void
3076 xseturgency(int add) {
3077         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3078
3079         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3080         XSetWMHints(xw.dpy, xw.win, h);
3081         XFree(h);
3082 }
3083
3084 void
3085 focus(XEvent *ev) {
3086         XFocusChangeEvent *e = &ev->xfocus;
3087
3088         if(e->mode == NotifyGrab)
3089                 return;
3090
3091         if(ev->type == FocusIn) {
3092                 XSetICFocus(xw.xic);
3093                 xw.state |= WIN_FOCUSED;
3094                 xseturgency(0);
3095         } else {
3096                 XUnsetICFocus(xw.xic);
3097                 xw.state &= ~WIN_FOCUSED;
3098         }
3099 }
3100
3101 inline bool
3102 match(uint mask, uint state) {
3103         state &= ~(ignoremod);
3104
3105         if(mask == XK_NO_MOD && state)
3106                 return false;
3107         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3108                 return false;
3109         if((state & mask) != state)
3110                 return false;
3111         return true;
3112 }
3113
3114 void
3115 numlock(const Arg *dummy) {
3116         term.numlock ^= 1;
3117 }
3118
3119 char*
3120 kmap(KeySym k, uint state) {
3121         uint mask;
3122         Key *kp;
3123         int i;
3124
3125         /* Check for mapped keys out of X11 function keys. */
3126         for(i = 0; i < LEN(mappedkeys); i++) {
3127                 if(mappedkeys[i] == k)
3128                         break;
3129         }
3130         if(i == LEN(mappedkeys)) {
3131                 if((k & 0xFFFF) < 0xFD00)
3132                         return NULL;
3133         }
3134
3135         for(kp = key; kp < key + LEN(key); kp++) {
3136                 mask = kp->mask;
3137
3138                 if(kp->k != k)
3139                         continue;
3140
3141                 if(!match(mask, state))
3142                         continue;
3143
3144                 if(kp->appkey > 0) {
3145                         if(!IS_SET(MODE_APPKEYPAD))
3146                                 continue;
3147                         if(term.numlock && kp->appkey == 2)
3148                                 continue;
3149                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3150                         continue;
3151                 }
3152
3153                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3154                                 (kp->appcursor > 0
3155                                  && !IS_SET(MODE_APPCURSOR))) {
3156                         continue;
3157                 }
3158
3159                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3160                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3161                         continue;
3162                 }
3163
3164                 return kp->s;
3165         }
3166
3167         return NULL;
3168 }
3169
3170 void
3171 kpress(XEvent *ev) {
3172         XKeyEvent *e = &ev->xkey;
3173         KeySym ksym;
3174         char xstr[31], buf[32], *customkey, *cp = buf;
3175         int len;
3176         Status status;
3177         Shortcut *bp;
3178
3179         if(IS_SET(MODE_KBDLOCK))
3180                 return;
3181
3182         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3183         e->state &= ~Mod2Mask;
3184         /* 1. shortcuts */
3185         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3186                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3187                         bp->func(&(bp->arg));
3188                         return;
3189                 }
3190         }
3191
3192         /* 2. custom keys from config.h */
3193         if((customkey = kmap(ksym, e->state))) {
3194                 len = strlen(customkey);
3195                 memcpy(buf, customkey, len);
3196         /* 2. hardcoded (overrides X lookup) */
3197         } else {
3198                 if(len == 0)
3199                         return;
3200
3201                 if(len == 1 && e->state & Mod1Mask)
3202                         *cp++ = '\033';
3203
3204                 memcpy(cp, xstr, len);
3205                 len = cp - buf + len;
3206         }
3207
3208         ttywrite(buf, len);
3209         if(IS_SET(MODE_ECHO))
3210                 techo(buf, len);
3211 }
3212
3213
3214 void
3215 cmessage(XEvent *e) {
3216         /*
3217          * See xembed specs
3218          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3219          */
3220         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3221                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3222                         xw.state |= WIN_FOCUSED;
3223                         xseturgency(0);
3224                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3225                         xw.state &= ~WIN_FOCUSED;
3226                 }
3227         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3228                 /* Send SIGHUP to shell */
3229                 kill(pid, SIGHUP);
3230                 exit(EXIT_SUCCESS);
3231         }
3232 }
3233
3234 void
3235 cresize(int width, int height) {
3236         int col, row;
3237
3238         if(width != 0)
3239                 xw.w = width;
3240         if(height != 0)
3241                 xw.h = height;
3242
3243         col = (xw.w - 2 * borderpx) / xw.cw;
3244         row = (xw.h - 2 * borderpx) / xw.ch;
3245
3246         tresize(col, row);
3247         xresize(col, row);
3248         ttyresize();
3249 }
3250
3251 void
3252 resize(XEvent *e) {
3253         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3254                 return;
3255
3256         cresize(e->xconfigure.width, e->xconfigure.height);
3257 }
3258
3259 void
3260 run(void) {
3261         XEvent ev;
3262         fd_set rfd;
3263         int xfd = XConnectionNumber(xw.dpy), xev;
3264         struct timeval drawtimeout, *tv = NULL, now, last;
3265
3266         gettimeofday(&last, NULL);
3267
3268         for(xev = actionfps;;) {
3269                 FD_ZERO(&rfd);
3270                 FD_SET(cmdfd, &rfd);
3271                 FD_SET(xfd, &rfd);
3272                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3273                         if(errno == EINTR)
3274                                 continue;
3275                         die("select failed: %s\n", SERRNO);
3276                 }
3277
3278                 gettimeofday(&now, NULL);
3279                 drawtimeout.tv_sec = 0;
3280                 drawtimeout.tv_usec = (1000/xfps) * 1000;
3281                 tv = &drawtimeout;
3282
3283                 if(FD_ISSET(cmdfd, &rfd))
3284                         ttyread();
3285
3286                 if(FD_ISSET(xfd, &rfd))
3287                         xev = actionfps;
3288
3289                 if(TIMEDIFF(now, last) > \
3290                                 (xev ? (1000/xfps) : (1000/actionfps))) {
3291                         while(XPending(xw.dpy)) {
3292                                 XNextEvent(xw.dpy, &ev);
3293                                 if(XFilterEvent(&ev, None))
3294                                         continue;
3295                                 if(handler[ev.type])
3296                                         (handler[ev.type])(&ev);
3297                         }
3298
3299                         draw();
3300                         XFlush(xw.dpy);
3301                         last = now;
3302
3303                         if(xev && !FD_ISSET(xfd, &rfd))
3304                                 xev--;
3305                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd))
3306                                 tv = NULL;
3307                 }
3308         }
3309 }
3310
3311 void
3312 usage(void) {
3313         die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3314         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3315         " [-t title] [-w windowid] [-e command ...]\n", argv0);
3316 }
3317
3318 int
3319 main(int argc, char *argv[]) {
3320         int bitm, xr, yr;
3321         uint wr, hr;
3322
3323         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3324         xw.isfixed = False;
3325
3326         ARGBEGIN {
3327         case 'a':
3328                 allowaltscreen = false;
3329                 break;
3330         case 'c':
3331                 opt_class = EARGF(usage());
3332                 break;
3333         case 'e':
3334                 /* eat all remaining arguments */
3335                 opt_cmd = &argv[1];
3336                 goto run;
3337         case 'f':
3338                 opt_font = EARGF(usage());
3339                 break;
3340         case 'g':
3341                 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3342                 if(bitm & XValue)
3343                         xw.fx = xr;
3344                 if(bitm & YValue)
3345                         xw.fy = yr;
3346                 if(bitm & WidthValue)
3347                         xw.fw = (int)wr;
3348                 if(bitm & HeightValue)
3349                         xw.fh = (int)hr;
3350                 if(bitm & XNegative && xw.fx == 0)
3351                         xw.fx = -1;
3352                 if(bitm & XNegative && xw.fy == 0)
3353                         xw.fy = -1;
3354
3355                 if(xw.fh != 0 && xw.fw != 0)
3356                         xw.isfixed = True;
3357                 break;
3358         case 'o':
3359                 opt_io = EARGF(usage());
3360                 break;
3361         case 't':
3362                 opt_title = EARGF(usage());
3363                 break;
3364         case 'w':
3365                 opt_embed = EARGF(usage());
3366                 break;
3367         case 'v':
3368         default:
3369                 usage();
3370         } ARGEND;
3371
3372 run:
3373         setlocale(LC_CTYPE, "");
3374         XSetLocaleModifiers("");
3375         tnew(80, 24);
3376         xinit();
3377         ttynew();
3378         selinit();
3379         run();
3380
3381         return 0;
3382 }
3383