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