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