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