JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Removing the debug messages again.
[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-2013 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         fprintf(stderr, "selrequest\n");
797         XSelectionRequestEvent *xsre;
798         XSelectionEvent xev;
799         Atom xa_targets, string;
800
801         xsre = (XSelectionRequestEvent *) e;
802         xev.type = SelectionNotify;
803         xev.requestor = xsre->requestor;
804         xev.selection = xsre->selection;
805         xev.target = xsre->target;
806         xev.time = xsre->time;
807         /* reject */
808         xev.property = None;
809
810         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
811         if(xsre->target == xa_targets) {
812                 /* respond with the supported type */
813                 string = sel.xtarget;
814                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
815                                 XA_ATOM, 32, PropModeReplace,
816                                 (uchar *) &string, 1);
817                 xev.property = xsre->property;
818         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
819                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
820                                 xsre->target, 8, PropModeReplace,
821                                 (uchar *) sel.clip, strlen(sel.clip));
822                 xev.property = xsre->property;
823         }
824
825         /* all done, send a notification to the listener */
826         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
827                 fprintf(stderr, "Error sending SelectionNotify event\n");
828 }
829
830 void
831 xsetsel(char *str) {
832         fprintf(stderr, "xsetsel: %s\n", str);
833         /* register the selection for both the clipboard and the primary */
834         Atom clipboard;
835
836         free(sel.clip);
837         sel.clip = str;
838
839         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
840
841         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
842         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
843 }
844
845 void
846 brelease(XEvent *e) {
847         struct timeval now;
848
849         if(IS_SET(MODE_MOUSE)) {
850                 mousereport(e);
851                 return;
852         }
853
854         if(e->xbutton.button == Button2) {
855                 selpaste(NULL);
856         } else if(e->xbutton.button == Button1) {
857                 sel.mode = 0;
858                 getbuttoninfo(e);
859                 term.dirty[sel.ey] = 1;
860                 if(sel.bx == sel.ex && sel.by == sel.ey) {
861                         sel.bx = -1;
862                         gettimeofday(&now, NULL);
863
864                         if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
865                                 /* triple click on the line */
866                                 sel.b.x = sel.bx = 0;
867                                 sel.e.x = sel.ex = term.col;
868                                 sel.b.y = sel.e.y = sel.ey;
869                                 selcopy();
870                         } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
871                                 /* double click to select word */
872                                 sel.bx = sel.ex;
873                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
874                                                 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
875                                         sel.bx--;
876                                 }
877                                 sel.b.x = sel.bx;
878                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
879                                                 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
880                                         sel.ex++;
881                                 }
882                                 sel.e.x = sel.ex;
883                                 sel.b.y = sel.e.y = sel.ey;
884                                 selcopy();
885                         }
886                 } else {
887                         selcopy();
888                 }
889         }
890
891         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
892         gettimeofday(&sel.tclick1, NULL);
893 }
894
895 void
896 bmotion(XEvent *e) {
897         int starty, endy, oldey, oldex;
898
899         if(IS_SET(MODE_MOUSE)) {
900                 mousereport(e);
901                 return;
902         }
903
904         if(!sel.mode)
905                 return;
906
907         oldey = sel.ey;
908         oldex = sel.ex;
909         getbuttoninfo(e);
910
911         if(oldey != sel.ey || oldex != sel.ex) {
912                 starty = MIN(oldey, sel.ey);
913                 endy = MAX(oldey, sel.ey);
914                 tsetdirt(starty, endy);
915         }
916 }
917
918 void
919 die(const char *errstr, ...) {
920         va_list ap;
921
922         va_start(ap, errstr);
923         vfprintf(stderr, errstr, ap);
924         va_end(ap);
925         exit(EXIT_FAILURE);
926 }
927
928 void
929 execsh(void) {
930         char **args;
931         char *envshell = getenv("SHELL");
932         const struct passwd *pass = getpwuid(getuid());
933         char buf[sizeof(long) * 8 + 1];
934
935         unsetenv("COLUMNS");
936         unsetenv("LINES");
937         unsetenv("TERMCAP");
938
939         if(pass) {
940                 setenv("LOGNAME", pass->pw_name, 1);
941                 setenv("USER", pass->pw_name, 1);
942                 setenv("SHELL", pass->pw_shell, 0);
943                 setenv("HOME", pass->pw_dir, 0);
944         }
945
946         snprintf(buf, sizeof(buf), "%lu", xw.win);
947         setenv("WINDOWID", buf, 1);
948
949         signal(SIGCHLD, SIG_DFL);
950         signal(SIGHUP, SIG_DFL);
951         signal(SIGINT, SIG_DFL);
952         signal(SIGQUIT, SIG_DFL);
953         signal(SIGTERM, SIG_DFL);
954         signal(SIGALRM, SIG_DFL);
955
956         DEFAULT(envshell, shell);
957         setenv("TERM", termname, 1);
958         args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
959         execvp(args[0], args);
960         exit(EXIT_FAILURE);
961 }
962
963 void
964 sigchld(int a) {
965         int stat = 0;
966
967         if(waitpid(pid, &stat, 0) < 0)
968                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
969
970         if(WIFEXITED(stat)) {
971                 exit(WEXITSTATUS(stat));
972         } else {
973                 exit(EXIT_FAILURE);
974         }
975 }
976
977 void
978 ttynew(void) {
979         int m, s;
980         struct winsize w = {term.row, term.col, 0, 0};
981
982         /* seems to work fine on linux, openbsd and freebsd */
983         if(openpty(&m, &s, NULL, NULL, &w) < 0)
984                 die("openpty failed: %s\n", SERRNO);
985
986         switch(pid = fork()) {
987         case -1:
988                 die("fork failed\n");
989                 break;
990         case 0:
991                 setsid(); /* create a new process group */
992                 dup2(s, STDIN_FILENO);
993                 dup2(s, STDOUT_FILENO);
994                 dup2(s, STDERR_FILENO);
995                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
996                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
997                 close(s);
998                 close(m);
999                 execsh();
1000                 break;
1001         default:
1002                 close(s);
1003                 cmdfd = m;
1004                 signal(SIGCHLD, sigchld);
1005                 if(opt_io) {
1006                         iofd = (!strcmp(opt_io, "-")) ?
1007                                   STDOUT_FILENO :
1008                                   open(opt_io, O_WRONLY | O_CREAT, 0666);
1009                         if(iofd < 0) {
1010                                 fprintf(stderr, "Error opening %s:%s\n",
1011                                         opt_io, strerror(errno));
1012                         }
1013                 }
1014         }
1015 }
1016
1017 void
1018 dump(char c) {
1019         static int col;
1020
1021         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1022         if(++col % 10 == 0)
1023                 fprintf(stderr, "\n");
1024 }
1025
1026 void
1027 ttyread(void) {
1028         static char buf[BUFSIZ];
1029         static int buflen = 0;
1030         char *ptr;
1031         char s[UTF_SIZ];
1032         int charsize; /* size of utf8 char in bytes */
1033         long utf8c;
1034         int ret;
1035
1036         /* append read bytes to unprocessed bytes */
1037         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1038                 die("Couldn't read from shell: %s\n", SERRNO);
1039
1040         /* process every complete utf8 char */
1041         buflen += ret;
1042         ptr = buf;
1043         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1044                 charsize = utf8decode(ptr, &utf8c);
1045                 utf8encode(&utf8c, s);
1046                 tputc(s, charsize);
1047                 ptr += charsize;
1048                 buflen -= charsize;
1049         }
1050
1051         /* keep any uncomplete utf8 char for the next call */
1052         memmove(buf, ptr, buflen);
1053 }
1054
1055 void
1056 ttywrite(const char *s, size_t n) {
1057         if(write(cmdfd, s, n) == -1)
1058                 die("write error on tty: %s\n", SERRNO);
1059 }
1060
1061 void
1062 ttyresize(void) {
1063         struct winsize w;
1064
1065         w.ws_row = term.row;
1066         w.ws_col = term.col;
1067         w.ws_xpixel = xw.tw;
1068         w.ws_ypixel = xw.th;
1069         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1070                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1071 }
1072
1073 void
1074 tsetdirt(int top, int bot) {
1075         int i;
1076
1077         LIMIT(top, 0, term.row-1);
1078         LIMIT(bot, 0, term.row-1);
1079
1080         for(i = top; i <= bot; i++)
1081                 term.dirty[i] = 1;
1082 }
1083
1084 void
1085 tfulldirt(void) {
1086         tsetdirt(0, term.row-1);
1087 }
1088
1089 void
1090 tcursor(int mode) {
1091         static TCursor c;
1092
1093         if(mode == CURSOR_SAVE) {
1094                 c = term.c;
1095         } else if(mode == CURSOR_LOAD) {
1096                 term.c = c;
1097                 tmoveto(c.x, c.y);
1098         }
1099 }
1100
1101 void
1102 treset(void) {
1103         uint i;
1104
1105         term.c = (TCursor){{
1106                 .mode = ATTR_NULL,
1107                 .fg = defaultfg,
1108                 .bg = defaultbg
1109         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1110
1111         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1112         for(i = tabspaces; i < term.col; i += tabspaces)
1113                 term.tabs[i] = 1;
1114         term.top = 0;
1115         term.bot = term.row - 1;
1116         term.mode = MODE_WRAP;
1117
1118         tclearregion(0, 0, term.col-1, term.row-1, 0);
1119         tmoveto(0, 0);
1120         tcursor(CURSOR_SAVE);
1121 }
1122
1123 void
1124 tnew(int col, int row) {
1125         /* set screen size */
1126         term.row = row;
1127         term.col = col;
1128         term.line = xmalloc(term.row * sizeof(Line));
1129         term.alt  = xmalloc(term.row * sizeof(Line));
1130         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1131         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1132
1133         for(row = 0; row < term.row; row++) {
1134                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1135                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1136                 term.dirty[row] = 0;
1137         }
1138
1139         term.numlock = 1;
1140         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1141         /* setup screen */
1142         treset();
1143 }
1144
1145 void
1146 tswapscreen(void) {
1147         Line *tmp = term.line;
1148
1149         term.line = term.alt;
1150         term.alt = tmp;
1151         term.mode ^= MODE_ALTSCREEN;
1152         tfulldirt();
1153 }
1154
1155 void
1156 tscrolldown(int orig, int n) {
1157         int i;
1158         Line temp;
1159
1160         LIMIT(n, 0, term.bot-orig+1);
1161
1162         tclearregion(0, term.bot-n+1, term.col-1, term.bot, 0);
1163
1164         for(i = term.bot; i >= orig+n; i--) {
1165                 temp = term.line[i];
1166                 term.line[i] = term.line[i-n];
1167                 term.line[i-n] = temp;
1168
1169                 term.dirty[i] = 1;
1170                 term.dirty[i-n] = 1;
1171         }
1172
1173         selscroll(orig, n);
1174 }
1175
1176 void
1177 tscrollup(int orig, int n) {
1178         int i;
1179         Line temp;
1180         LIMIT(n, 0, term.bot-orig+1);
1181
1182         tclearregion(0, orig, term.col-1, orig+n-1, 0);
1183
1184         for(i = orig; i <= term.bot-n; i++) {
1185                  temp = term.line[i];
1186                  term.line[i] = term.line[i+n];
1187                  term.line[i+n] = temp;
1188
1189                  term.dirty[i] = 1;
1190                  term.dirty[i+n] = 1;
1191         }
1192
1193         selscroll(orig, -n);
1194 }
1195
1196 void
1197 selscroll(int orig, int n) {
1198         if(sel.bx == -1)
1199                 return;
1200
1201         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1202                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1203                         sel.bx = -1;
1204                         return;
1205                 }
1206                 if(sel.by < term.top) {
1207                         sel.by = term.top;
1208                         sel.bx = 0;
1209                 }
1210                 if(sel.ey > term.bot) {
1211                         sel.ey = term.bot;
1212                         sel.ex = term.col;
1213                 }
1214                 sel.b.y = sel.by, sel.b.x = sel.bx;
1215                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1216         }
1217 }
1218
1219 void
1220 tnewline(int first_col) {
1221         int y = term.c.y;
1222
1223         if(y == term.bot) {
1224                 tscrollup(term.top, 1);
1225         } else {
1226                 y++;
1227         }
1228         tmoveto(first_col ? 0 : term.c.x, y);
1229 }
1230
1231 void
1232 csiparse(void) {
1233         /* int noarg = 1; */
1234         char *p = csiescseq.buf;
1235
1236         csiescseq.narg = 0;
1237         if(*p == '?')
1238                 csiescseq.priv = 1, p++;
1239
1240         while(p < csiescseq.buf+csiescseq.len) {
1241                 while(isdigit(*p)) {
1242                         csiescseq.arg[csiescseq.narg] *= 10;
1243                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1244                 }
1245                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1246                         csiescseq.narg++, p++;
1247                 } else {
1248                         csiescseq.mode = *p;
1249                         csiescseq.narg++;
1250
1251                         return;
1252                 }
1253         }
1254 }
1255
1256 /* for absolute user moves, when decom is set */
1257 void
1258 tmoveato(int x, int y) {
1259         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1260 }
1261
1262 void
1263 tmoveto(int x, int y) {
1264         int miny, maxy;
1265
1266         if(term.c.state & CURSOR_ORIGIN) {
1267                 miny = term.top;
1268                 maxy = term.bot;
1269         } else {
1270                 miny = 0;
1271                 maxy = term.row - 1;
1272         }
1273         LIMIT(x, 0, term.col-1);
1274         LIMIT(y, miny, maxy);
1275         term.c.state &= ~CURSOR_WRAPNEXT;
1276         term.c.x = x;
1277         term.c.y = y;
1278 }
1279
1280 void
1281 tsetchar(char *c, Glyph *attr, int x, int y) {
1282         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1283                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1284                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1285                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1286                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1287                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1288                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1289                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1290                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1291         };
1292
1293         /*
1294          * The table is proudly stolen from rxvt.
1295          */
1296         if(attr->mode & ATTR_GFX) {
1297                 if(c[0] >= 0x41 && c[0] <= 0x7e
1298                                 && vt100_0[c[0] - 0x41]) {
1299                         c = vt100_0[c[0] - 0x41];
1300                 }
1301         }
1302
1303         term.dirty[y] = 1;
1304         term.line[y][x] = *attr;
1305         memcpy(term.line[y][x].c, c, UTF_SIZ);
1306         term.line[y][x].state |= GLYPH_SET;
1307 }
1308
1309 void
1310 tclearregion(int x1, int y1, int x2, int y2, int bce) {
1311         int x, y, temp;
1312
1313         if(x1 > x2)
1314                 temp = x1, x1 = x2, x2 = temp;
1315         if(y1 > y2)
1316                 temp = y1, y1 = y2, y2 = temp;
1317
1318         LIMIT(x1, 0, term.col-1);
1319         LIMIT(x2, 0, term.col-1);
1320         LIMIT(y1, 0, term.row-1);
1321         LIMIT(y2, 0, term.row-1);
1322
1323         for(y = y1; y <= y2; y++) {
1324                 term.dirty[y] = 1;
1325                 for(x = x1; x <= x2; x++) {
1326                         if(bce) {
1327                                 term.line[y][x] = term.c.attr;
1328                                 memcpy(term.line[y][x].c, " ", 2);
1329                                 term.line[y][x].state |= GLYPH_SET;
1330                         } else {
1331                                 term.line[y][x].state = 0;
1332                         }
1333                 }
1334         }
1335 }
1336
1337 void
1338 tdeletechar(int n) {
1339         int src = term.c.x + n;
1340         int dst = term.c.x;
1341         int size = term.col - src;
1342
1343         term.dirty[term.c.y] = 1;
1344
1345         if(src >= term.col) {
1346                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1347                 return;
1348         }
1349
1350         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1351                         size * sizeof(Glyph));
1352         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y, 0);
1353 }
1354
1355 void
1356 tinsertblank(int n) {
1357         int src = term.c.x;
1358         int dst = src + n;
1359         int size = term.col - dst;
1360
1361         term.dirty[term.c.y] = 1;
1362
1363         if(dst >= term.col) {
1364                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 0);
1365                 return;
1366         }
1367
1368         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1369                         size * sizeof(Glyph));
1370         tclearregion(src, term.c.y, dst - 1, term.c.y, 0);
1371 }
1372
1373 void
1374 tinsertblankline(int n) {
1375         if(term.c.y < term.top || term.c.y > term.bot)
1376                 return;
1377
1378         tscrolldown(term.c.y, n);
1379 }
1380
1381 void
1382 tdeleteline(int n) {
1383         if(term.c.y < term.top || term.c.y > term.bot)
1384                 return;
1385
1386         tscrollup(term.c.y, n);
1387 }
1388
1389 void
1390 tsetattr(int *attr, int l) {
1391         int i;
1392
1393         for(i = 0; i < l; i++) {
1394                 switch(attr[i]) {
1395                 case 0:
1396                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1397                                         | ATTR_ITALIC | ATTR_BLINK);
1398                         term.c.attr.fg = defaultfg;
1399                         term.c.attr.bg = defaultbg;
1400                         break;
1401                 case 1:
1402                         term.c.attr.mode |= ATTR_BOLD;
1403                         break;
1404                 case 3:
1405                         term.c.attr.mode |= ATTR_ITALIC;
1406                         break;
1407                 case 4:
1408                         term.c.attr.mode |= ATTR_UNDERLINE;
1409                         break;
1410                 case 5:
1411                         term.c.attr.mode |= ATTR_BLINK;
1412                         break;
1413                 case 7:
1414                         term.c.attr.mode |= ATTR_REVERSE;
1415                         break;
1416                 case 21:
1417                 case 22:
1418                         term.c.attr.mode &= ~ATTR_BOLD;
1419                         break;
1420                 case 23:
1421                         term.c.attr.mode &= ~ATTR_ITALIC;
1422                         break;
1423                 case 24:
1424                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1425                         break;
1426                 case 25:
1427                         term.c.attr.mode &= ~ATTR_BLINK;
1428                         break;
1429                 case 27:
1430                         term.c.attr.mode &= ~ATTR_REVERSE;
1431                         break;
1432                 case 38:
1433                         if(i + 2 < l && attr[i + 1] == 5) {
1434                                 i += 2;
1435                                 if(BETWEEN(attr[i], 0, 255)) {
1436                                         term.c.attr.fg = attr[i];
1437                                 } else {
1438                                         fprintf(stderr,
1439                                                 "erresc: bad fgcolor %d\n",
1440                                                 attr[i]);
1441                                 }
1442                         } else {
1443                                 fprintf(stderr,
1444                                         "erresc(38): gfx attr %d unknown\n",
1445                                         attr[i]);
1446                         }
1447                         break;
1448                 case 39:
1449                         term.c.attr.fg = defaultfg;
1450                         break;
1451                 case 48:
1452                         if(i + 2 < l && attr[i + 1] == 5) {
1453                                 i += 2;
1454                                 if(BETWEEN(attr[i], 0, 255)) {
1455                                         term.c.attr.bg = attr[i];
1456                                 } else {
1457                                         fprintf(stderr,
1458                                                 "erresc: bad bgcolor %d\n",
1459                                                 attr[i]);
1460                                 }
1461                         } else {
1462                                 fprintf(stderr,
1463                                         "erresc(48): gfx attr %d unknown\n",
1464                                         attr[i]);
1465                         }
1466                         break;
1467                 case 49:
1468                         term.c.attr.bg = defaultbg;
1469                         break;
1470                 default:
1471                         if(BETWEEN(attr[i], 30, 37)) {
1472                                 term.c.attr.fg = attr[i] - 30;
1473                         } else if(BETWEEN(attr[i], 40, 47)) {
1474                                 term.c.attr.bg = attr[i] - 40;
1475                         } else if(BETWEEN(attr[i], 90, 97)) {
1476                                 term.c.attr.fg = attr[i] - 90 + 8;
1477                         } else if(BETWEEN(attr[i], 100, 107)) {
1478                                 term.c.attr.bg = attr[i] - 100 + 8;
1479                         } else {
1480                                 fprintf(stderr,
1481                                         "erresc(default): gfx attr %d unknown\n",
1482                                         attr[i]), csidump();
1483                         }
1484                         break;
1485                 }
1486         }
1487 }
1488
1489 void
1490 tsetscroll(int t, int b) {
1491         int temp;
1492
1493         LIMIT(t, 0, term.row-1);
1494         LIMIT(b, 0, term.row-1);
1495         if(t > b) {
1496                 temp = t;
1497                 t = b;
1498                 b = temp;
1499         }
1500         term.top = t;
1501         term.bot = b;
1502 }
1503
1504 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1505
1506 void
1507 tsetmode(bool priv, bool set, int *args, int narg) {
1508         int *lim, mode;
1509         bool alt;
1510
1511         for(lim = args + narg; args < lim; ++args) {
1512                 if(priv) {
1513                         switch(*args) {
1514                                 break;
1515                         case 1: /* DECCKM -- Cursor key */
1516                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1517                                 break;
1518                         case 5: /* DECSCNM -- Reverse video */
1519                                 mode = term.mode;
1520                                 MODBIT(term.mode, set, MODE_REVERSE);
1521                                 if(mode != term.mode)
1522                                         redraw(REDRAW_TIMEOUT);
1523                                 break;
1524                         case 6: /* DECOM -- Origin */
1525                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1526                                 tmoveato(0, 0);
1527                                 break;
1528                         case 7: /* DECAWM -- Auto wrap */
1529                                 MODBIT(term.mode, set, MODE_WRAP);
1530                                 break;
1531                         case 0:  /* Error (IGNORED) */
1532                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1533                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1534                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1535                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1536                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1537                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1538                         case 42: /* DECNRCM -- National characters (IGNORED) */
1539                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1540                                 break;
1541                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1542                                 MODBIT(term.mode, !set, MODE_HIDE);
1543                                 break;
1544                         case 1000: /* 1000,1002: enable xterm mouse report */
1545                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1546                                 break;
1547                         case 1002:
1548                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1549                                 break;
1550                         case 1049: /* = 1047 and 1048 */
1551                         case 47:
1552                         case 1047: {
1553                                 alt = IS_SET(MODE_ALTSCREEN);
1554                                 if(alt) {
1555                                         tclearregion(0, 0, term.col-1,
1556                                                         term.row-1, 0);
1557                                 }
1558                                 if(set ^ alt)           /* set is always 1 or 0 */
1559                                         tswapscreen();
1560                                 if(*args != 1049)
1561                                         break;
1562                         }
1563                                 /* pass through */
1564                         case 1048:
1565                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1566                                 break;
1567                         default:
1568                                 fprintf(stderr,
1569                                         "erresc: unknown private set/reset mode %d\n",
1570                                         *args);
1571                                 break;
1572                         }
1573                 } else {
1574                         switch(*args) {
1575                         case 0:  /* Error (IGNORED) */
1576                                 break;
1577                         case 2:  /* KAM -- keyboard action */
1578                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1579                                 break;
1580                         case 4:  /* IRM -- Insertion-replacement */
1581                                 MODBIT(term.mode, set, MODE_INSERT);
1582                                 break;
1583                         case 12: /* SRM -- Send/Receive */
1584                                 MODBIT(term.mode, !set, MODE_ECHO);
1585                                 break;
1586                         case 20: /* LNM -- Linefeed/new line */
1587                                 MODBIT(term.mode, set, MODE_CRLF);
1588                                 break;
1589                         default:
1590                                 fprintf(stderr,
1591                                         "erresc: unknown set/reset mode %d\n",
1592                                         *args);
1593                                 break;
1594                         }
1595                 }
1596         }
1597 }
1598 #undef MODBIT
1599
1600
1601 void
1602 csihandle(void) {
1603         switch(csiescseq.mode) {
1604         default:
1605         unknown:
1606                 fprintf(stderr, "erresc: unknown csi ");
1607                 csidump();
1608                 /* die(""); */
1609                 break;
1610         case '@': /* ICH -- Insert <n> blank char */
1611                 DEFAULT(csiescseq.arg[0], 1);
1612                 tinsertblank(csiescseq.arg[0]);
1613                 break;
1614         case 'A': /* CUU -- Cursor <n> Up */
1615                 DEFAULT(csiescseq.arg[0], 1);
1616                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1617                 break;
1618         case 'B': /* CUD -- Cursor <n> Down */
1619         case 'e': /* VPR --Cursor <n> Down */
1620                 DEFAULT(csiescseq.arg[0], 1);
1621                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1622                 break;
1623         case 'c': /* DA -- Device Attributes */
1624                 if(csiescseq.arg[0] == 0)
1625                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1626                 break;
1627         case 'C': /* CUF -- Cursor <n> Forward */
1628         case 'a': /* HPR -- Cursor <n> Forward */
1629                 DEFAULT(csiescseq.arg[0], 1);
1630                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1631                 break;
1632         case 'D': /* CUB -- Cursor <n> Backward */
1633                 DEFAULT(csiescseq.arg[0], 1);
1634                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1635                 break;
1636         case 'E': /* CNL -- Cursor <n> Down and first col */
1637                 DEFAULT(csiescseq.arg[0], 1);
1638                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1639                 break;
1640         case 'F': /* CPL -- Cursor <n> Up and first col */
1641                 DEFAULT(csiescseq.arg[0], 1);
1642                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1643                 break;
1644         case 'g': /* TBC -- Tabulation clear */
1645                 switch (csiescseq.arg[0]) {
1646                 case 0: /* clear current tab stop */
1647                         term.tabs[term.c.x] = 0;
1648                         break;
1649                 case 3: /* clear all the tabs */
1650                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1651                         break;
1652                 default:
1653                         goto unknown;
1654                 }
1655                 break;
1656         case 'G': /* CHA -- Move to <col> */
1657         case '`': /* HPA */
1658                 DEFAULT(csiescseq.arg[0], 1);
1659                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1660                 break;
1661         case 'H': /* CUP -- Move to <row> <col> */
1662         case 'f': /* HVP */
1663                 DEFAULT(csiescseq.arg[0], 1);
1664                 DEFAULT(csiescseq.arg[1], 1);
1665                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1666                 break;
1667         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1668                 DEFAULT(csiescseq.arg[0], 1);
1669                 while(csiescseq.arg[0]--)
1670                         tputtab(1);
1671                 break;
1672         case 'J': /* ED -- Clear screen */
1673                 sel.bx = -1;
1674                 switch(csiescseq.arg[0]) {
1675                 case 0: /* below */
1676                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y, 1);
1677                         if(term.c.y < term.row-1) {
1678                                 tclearregion(0, term.c.y+1, term.col-1,
1679                                                 term.row-1, 1);
1680                         }
1681                         break;
1682                 case 1: /* above */
1683                         if(term.c.y > 1)
1684                                 tclearregion(0, 0, term.col-1, term.c.y-1, 1);
1685                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1686                         break;
1687                 case 2: /* all */
1688                         tclearregion(0, 0, term.col-1, term.row-1, 1);
1689                         break;
1690                 default:
1691                         goto unknown;
1692                 }
1693                 break;
1694         case 'K': /* EL -- Clear line */
1695                 switch(csiescseq.arg[0]) {
1696                 case 0: /* right */
1697                         tclearregion(term.c.x, term.c.y, term.col-1,
1698                                         term.c.y, 1);
1699                         break;
1700                 case 1: /* left */
1701                         tclearregion(0, term.c.y, term.c.x, term.c.y, 1);
1702                         break;
1703                 case 2: /* all */
1704                         tclearregion(0, term.c.y, term.col-1, term.c.y, 1);
1705                         break;
1706                 }
1707                 break;
1708         case 'S': /* SU -- Scroll <n> line up */
1709                 DEFAULT(csiescseq.arg[0], 1);
1710                 tscrollup(term.top, csiescseq.arg[0]);
1711                 break;
1712         case 'T': /* SD -- Scroll <n> line down */
1713                 DEFAULT(csiescseq.arg[0], 1);
1714                 tscrolldown(term.top, csiescseq.arg[0]);
1715                 break;
1716         case 'L': /* IL -- Insert <n> blank lines */
1717                 DEFAULT(csiescseq.arg[0], 1);
1718                 tinsertblankline(csiescseq.arg[0]);
1719                 break;
1720         case 'l': /* RM -- Reset Mode */
1721                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1722                 break;
1723         case 'M': /* DL -- Delete <n> lines */
1724                 DEFAULT(csiescseq.arg[0], 1);
1725                 tdeleteline(csiescseq.arg[0]);
1726                 break;
1727         case 'X': /* ECH -- Erase <n> char */
1728                 DEFAULT(csiescseq.arg[0], 1);
1729                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0],
1730                                 term.c.y, 0);
1731                 break;
1732         case 'P': /* DCH -- Delete <n> char */
1733                 DEFAULT(csiescseq.arg[0], 1);
1734                 tdeletechar(csiescseq.arg[0]);
1735                 break;
1736         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1737                 DEFAULT(csiescseq.arg[0], 1);
1738                 while(csiescseq.arg[0]--)
1739                         tputtab(0);
1740                 break;
1741         case 'd': /* VPA -- Move to <row> */
1742                 DEFAULT(csiescseq.arg[0], 1);
1743                 tmoveato(term.c.x, csiescseq.arg[0]-1);
1744                 break;
1745         case 'h': /* SM -- Set terminal mode */
1746                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1747                 break;
1748         case 'm': /* SGR -- Terminal attribute (color) */
1749                 tsetattr(csiescseq.arg, csiescseq.narg);
1750                 break;
1751         case 'r': /* DECSTBM -- Set Scrolling Region */
1752                 if(csiescseq.priv) {
1753                         goto unknown;
1754                 } else {
1755                         DEFAULT(csiescseq.arg[0], 1);
1756                         DEFAULT(csiescseq.arg[1], term.row);
1757                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1758                         tmoveato(0, 0);
1759                 }
1760                 break;
1761         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1762                 tcursor(CURSOR_SAVE);
1763                 break;
1764         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1765                 tcursor(CURSOR_LOAD);
1766                 break;
1767         }
1768 }
1769
1770 void
1771 csidump(void) {
1772         int i;
1773         uint c;
1774
1775         printf("ESC[");
1776         for(i = 0; i < csiescseq.len; i++) {
1777                 c = csiescseq.buf[i] & 0xff;
1778                 if(isprint(c)) {
1779                         putchar(c);
1780                 } else if(c == '\n') {
1781                         printf("(\\n)");
1782                 } else if(c == '\r') {
1783                         printf("(\\r)");
1784                 } else if(c == 0x1b) {
1785                         printf("(\\e)");
1786                 } else {
1787                         printf("(%02x)", c);
1788                 }
1789         }
1790         putchar('\n');
1791 }
1792
1793 void
1794 csireset(void) {
1795         memset(&csiescseq, 0, sizeof(csiescseq));
1796 }
1797
1798 void
1799 strhandle(void) {
1800         char *p;
1801
1802         /*
1803          * TODO: make this being useful in case of color palette change.
1804          */
1805         strparse();
1806
1807         p = strescseq.buf;
1808
1809         switch(strescseq.type) {
1810         case ']': /* OSC -- Operating System Command */
1811                 switch(p[0]) {
1812                 case '0':
1813                 case '1':
1814                 case '2':
1815                         /*
1816                          * TODO: Handle special chars in string, like umlauts.
1817                          */
1818                         if(p[1] == ';') {
1819                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1820                         }
1821                         break;
1822                 case ';':
1823                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1824                         break;
1825                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1826                         break;
1827                 default:
1828                         fprintf(stderr, "erresc: unknown str ");
1829                         strdump();
1830                         break;
1831                 }
1832                 break;
1833         case 'k': /* old title set compatibility */
1834                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1835                 break;
1836         case 'P': /* DSC -- Device Control String */
1837         case '_': /* APC -- Application Program Command */
1838         case '^': /* PM -- Privacy Message */
1839         default:
1840                 fprintf(stderr, "erresc: unknown str ");
1841                 strdump();
1842                 /* die(""); */
1843                 break;
1844         }
1845 }
1846
1847 void
1848 strparse(void) {
1849         /*
1850          * TODO: Implement parsing like for CSI when required.
1851          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1852          */
1853         return;
1854 }
1855
1856 void
1857 strdump(void) {
1858         int i;
1859         uint c;
1860
1861         printf("ESC%c", strescseq.type);
1862         for(i = 0; i < strescseq.len; i++) {
1863                 c = strescseq.buf[i] & 0xff;
1864                 if(isprint(c)) {
1865                         putchar(c);
1866                 } else if(c == '\n') {
1867                         printf("(\\n)");
1868                 } else if(c == '\r') {
1869                         printf("(\\r)");
1870                 } else if(c == 0x1b) {
1871                         printf("(\\e)");
1872                 } else {
1873                         printf("(%02x)", c);
1874                 }
1875         }
1876         printf("ESC\\\n");
1877 }
1878
1879 void
1880 strreset(void) {
1881         memset(&strescseq, 0, sizeof(strescseq));
1882 }
1883
1884 void
1885 tputtab(bool forward) {
1886         uint x = term.c.x;
1887
1888         if(forward) {
1889                 if(x == term.col)
1890                         return;
1891                 for(++x; x < term.col && !term.tabs[x]; ++x)
1892                         /* nothing */ ;
1893         } else {
1894                 if(x == 0)
1895                         return;
1896                 for(--x; x > 0 && !term.tabs[x]; --x)
1897                         /* nothing */ ;
1898         }
1899         tmoveto(x, term.c.y);
1900 }
1901
1902 void
1903 techo(char *buf, int len) {
1904         for(; len > 0; buf++, len--) {
1905                 char c = *buf;
1906
1907                 if(c == '\033') {               /* escape */
1908                         tputc("^", 1);
1909                         tputc("[", 1);
1910                 } else if (c < '\x20') {        /* control code */
1911                         if(c != '\n' && c != '\r' && c != '\t') {
1912                                 c |= '\x40';
1913                                 tputc("^", 1);
1914                         }
1915                         tputc(&c, 1);
1916                 } else {
1917                         break;
1918                 }
1919         }
1920         if (len)
1921                 tputc(buf, len);
1922 }
1923
1924 void
1925 tputc(char *c, int len) {
1926         uchar ascii = *c;
1927         bool control = ascii < '\x20' || ascii == 0177;
1928
1929         if(iofd != -1) {
1930                 if (xwrite(iofd, c, len) < 0) {
1931                         fprintf(stderr, "Error writing in %s:%s\n",
1932                                 opt_io, strerror(errno));
1933                         close(iofd);
1934                         iofd = -1;
1935                 }
1936         }
1937
1938         /*
1939          * STR sequences must be checked before anything else
1940          * because it can use some control codes as part of the sequence.
1941          */
1942         if(term.esc & ESC_STR) {
1943                 switch(ascii) {
1944                 case '\033':
1945                         term.esc = ESC_START | ESC_STR_END;
1946                         break;
1947                 case '\a': /* backwards compatibility to xterm */
1948                         term.esc = 0;
1949                         strhandle();
1950                         break;
1951                 default:
1952                         if(strescseq.len + len < sizeof(strescseq.buf)) {
1953                                 memmove(&strescseq.buf[strescseq.len], c, len);
1954                                 strescseq.len += len;
1955                         } else {
1956                         /*
1957                          * Here is a bug in terminals. If the user never sends
1958                          * some code to stop the str or esc command, then st
1959                          * will stop responding. But this is better than
1960                          * silently failing with unknown characters. At least
1961                          * then users will report back.
1962                          *
1963                          * In the case users ever get fixed, here is the code:
1964                          */
1965                         /*
1966                          * term.esc = 0;
1967                          * strhandle();
1968                          */
1969                         }
1970                 }
1971                 return;
1972         }
1973
1974         /*
1975          * Actions of control codes must be performed as soon they arrive
1976          * because they can be embedded inside a control sequence, and
1977          * they must not cause conflicts with sequences.
1978          */
1979         if(control) {
1980                 switch(ascii) {
1981                 case '\t':      /* HT */
1982                         tputtab(1);
1983                         return;
1984                 case '\b':      /* BS */
1985                         tmoveto(term.c.x-1, term.c.y);
1986                         return;
1987                 case '\r':      /* CR */
1988                         tmoveto(0, term.c.y);
1989                         return;
1990                 case '\f':      /* LF */
1991                 case '\v':      /* VT */
1992                 case '\n':      /* LF */
1993                         /* go to first col if the mode is set */
1994                         tnewline(IS_SET(MODE_CRLF));
1995                         return;
1996                 case '\a':      /* BEL */
1997                         if(!(xw.state & WIN_FOCUSED))
1998                                 xseturgency(1);
1999                         return;
2000                 case '\033':    /* ESC */
2001                         csireset();
2002                         term.esc = ESC_START;
2003                         return;
2004                 case '\016':    /* SO */
2005                 case '\017':    /* SI */
2006                         /*
2007                          * Different charsets are hard to handle. Applications
2008                          * should use the right alt charset escapes for the
2009                          * only reason they still exist: line drawing. The
2010                          * rest is incompatible history st should not support.
2011                          */
2012                         return;
2013                 case '\032':    /* SUB */
2014                 case '\030':    /* CAN */
2015                         csireset();
2016                         return;
2017                 case '\005':    /* ENQ (IGNORED) */
2018                 case '\000':    /* NUL (IGNORED) */
2019                 case '\021':    /* XON (IGNORED) */
2020                 case '\023':    /* XOFF (IGNORED) */
2021                 case 0177:      /* DEL (IGNORED) */
2022                         return;
2023                 }
2024         } else if(term.esc & ESC_START) {
2025                 if(term.esc & ESC_CSI) {
2026                         csiescseq.buf[csiescseq.len++] = ascii;
2027                         if(BETWEEN(ascii, 0x40, 0x7E)
2028                                         || csiescseq.len >= ESC_BUF_SIZ) {
2029                                 term.esc = 0;
2030                                 csiparse(), csihandle();
2031                         }
2032                 } else if(term.esc & ESC_STR_END) {
2033                         term.esc = 0;
2034                         if(ascii == '\\')
2035                                 strhandle();
2036                 } else if(term.esc & ESC_ALTCHARSET) {
2037                         switch(ascii) {
2038                         case '0': /* Line drawing set */
2039                                 term.c.attr.mode |= ATTR_GFX;
2040                                 break;
2041                         case 'B': /* USASCII */
2042                                 term.c.attr.mode &= ~ATTR_GFX;
2043                                 break;
2044                         case 'A': /* UK (IGNORED) */
2045                         case '<': /* multinational charset (IGNORED) */
2046                         case '5': /* Finnish (IGNORED) */
2047                         case 'C': /* Finnish (IGNORED) */
2048                         case 'K': /* German (IGNORED) */
2049                                 break;
2050                         default:
2051                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2052                         }
2053                         term.esc = 0;
2054                 } else if(term.esc & ESC_TEST) {
2055                         if(ascii == '8') { /* DEC screen alignment test. */
2056                                 char E[UTF_SIZ] = "E";
2057                                 int x, y;
2058
2059                                 for(x = 0; x < term.col; ++x) {
2060                                         for(y = 0; y < term.row; ++y)
2061                                                 tsetchar(E, &term.c.attr, x, y);
2062                                 }
2063                         }
2064                         term.esc = 0;
2065                 } else {
2066                         switch(ascii) {
2067                         case '[':
2068                                 term.esc |= ESC_CSI;
2069                                 break;
2070                         case '#':
2071                                 term.esc |= ESC_TEST;
2072                                 break;
2073                         case 'P': /* DCS -- Device Control String */
2074                         case '_': /* APC -- Application Program Command */
2075                         case '^': /* PM -- Privacy Message */
2076                         case ']': /* OSC -- Operating System Command */
2077                         case 'k': /* old title set compatibility */
2078                                 strreset();
2079                                 strescseq.type = ascii;
2080                                 term.esc |= ESC_STR;
2081                                 break;
2082                         case '(': /* set primary charset G0 */
2083                                 term.esc |= ESC_ALTCHARSET;
2084                                 break;
2085                         case ')': /* set secondary charset G1 (IGNORED) */
2086                         case '*': /* set tertiary charset G2 (IGNORED) */
2087                         case '+': /* set quaternary charset G3 (IGNORED) */
2088                                 term.esc = 0;
2089                                 break;
2090                         case 'D': /* IND -- Linefeed */
2091                                 if(term.c.y == term.bot) {
2092                                         tscrollup(term.top, 1);
2093                                 } else {
2094                                         tmoveto(term.c.x, term.c.y+1);
2095                                 }
2096                                 term.esc = 0;
2097                                 break;
2098                         case 'E': /* NEL -- Next line */
2099                                 tnewline(1); /* always go to first col */
2100                                 term.esc = 0;
2101                                 break;
2102                         case 'H': /* HTS -- Horizontal tab stop */
2103                                 term.tabs[term.c.x] = 1;
2104                                 term.esc = 0;
2105                                 break;
2106                         case 'M': /* RI -- Reverse index */
2107                                 if(term.c.y == term.top) {
2108                                         tscrolldown(term.top, 1);
2109                                 } else {
2110                                         tmoveto(term.c.x, term.c.y-1);
2111                                 }
2112                                 term.esc = 0;
2113                                 break;
2114                         case 'Z': /* DECID -- Identify Terminal */
2115                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2116                                 term.esc = 0;
2117                                 break;
2118                         case 'c': /* RIS -- Reset to inital state */
2119                                 treset();
2120                                 term.esc = 0;
2121                                 xresettitle();
2122                                 break;
2123                         case '=': /* DECPAM -- Application keypad */
2124                                 term.mode |= MODE_APPKEYPAD;
2125                                 term.esc = 0;
2126                                 break;
2127                         case '>': /* DECPNM -- Normal keypad */
2128                                 term.mode &= ~MODE_APPKEYPAD;
2129                                 term.esc = 0;
2130                                 break;
2131                         case '7': /* DECSC -- Save Cursor */
2132                                 tcursor(CURSOR_SAVE);
2133                                 term.esc = 0;
2134                                 break;
2135                         case '8': /* DECRC -- Restore Cursor */
2136                                 tcursor(CURSOR_LOAD);
2137                                 term.esc = 0;
2138                                 break;
2139                         case '\\': /* ST -- Stop */
2140                                 term.esc = 0;
2141                                 break;
2142                         default:
2143                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2144                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2145                                 term.esc = 0;
2146                         }
2147                 }
2148                 /*
2149                  * All characters which form part of a sequence are not
2150                  * printed
2151                  */
2152                 return;
2153         }
2154         /*
2155          * Display control codes only if we are in graphic mode
2156          */
2157         if(control && !(term.c.attr.mode & ATTR_GFX))
2158                 return;
2159         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2160                 sel.bx = -1;
2161         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2162                 tnewline(1); /* always go to first col */
2163
2164         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2165                 memmove(&term.line[term.c.y][term.c.x+1],
2166                         &term.line[term.c.y][term.c.x],
2167                         (term.col - term.c.x - 1) * sizeof(Glyph));
2168         }
2169
2170         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2171         if(term.c.x+1 < term.col) {
2172                 tmoveto(term.c.x+1, term.c.y);
2173         } else {
2174                 term.c.state |= CURSOR_WRAPNEXT;
2175         }
2176 }
2177
2178 int
2179 tresize(int col, int row) {
2180         int i, x;
2181         int minrow = MIN(row, term.row);
2182         int mincol = MIN(col, term.col);
2183         int slide = term.c.y - row + 1;
2184         bool *bp;
2185
2186         if(col < 1 || row < 1)
2187                 return 0;
2188
2189         /* free unneeded rows */
2190         i = 0;
2191         if(slide > 0) {
2192                 /* slide screen to keep cursor where we expect it -
2193                  * tscrollup would work here, but we can optimize to
2194                  * memmove because we're freeing the earlier lines */
2195                 for(/* i = 0 */; i < slide; i++) {
2196                         free(term.line[i]);
2197                         free(term.alt[i]);
2198                 }
2199                 memmove(term.line, term.line + slide, row * sizeof(Line));
2200                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2201         }
2202         for(i += row; i < term.row; i++) {
2203                 free(term.line[i]);
2204                 free(term.alt[i]);
2205         }
2206
2207         /* resize to new height */
2208         term.line = xrealloc(term.line, row * sizeof(Line));
2209         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2210         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2211         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2212
2213         /* resize each row to new width, zero-pad if needed */
2214         for(i = 0; i < minrow; i++) {
2215                 term.dirty[i] = 1;
2216                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2217                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2218                 for(x = mincol; x < col; x++) {
2219                         term.line[i][x].state = 0;
2220                         term.alt[i][x].state = 0;
2221                 }
2222         }
2223
2224         /* allocate any new rows */
2225         for(/* i == minrow */; i < row; i++) {
2226                 term.dirty[i] = 1;
2227                 term.line[i] = xcalloc(col, sizeof(Glyph));
2228                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2229         }
2230         if(col > term.col) {
2231                 bp = term.tabs + term.col;
2232
2233                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2234                 while(--bp > term.tabs && !*bp)
2235                         /* nothing */ ;
2236                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2237                         *bp = 1;
2238         }
2239         /* update terminal size */
2240         term.col = col;
2241         term.row = row;
2242         /* reset scrolling region */
2243         tsetscroll(0, row-1);
2244         /* make use of the LIMIT in tmoveto */
2245         tmoveto(term.c.x, term.c.y);
2246
2247         return (slide > 0);
2248 }
2249
2250 void
2251 xresize(int col, int row) {
2252         xw.tw = MAX(1, col * xw.cw);
2253         xw.th = MAX(1, row * xw.ch);
2254
2255         if(!usedbe) {
2256                 XFreePixmap(xw.dpy, xw.buf);
2257                 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2258                                 DefaultDepth(xw.dpy, xw.scr));
2259                 XSetForeground(xw.dpy, dc.gc, 0);
2260                 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2261         }
2262
2263         XftDrawChange(xw.draw, xw.buf);
2264 }
2265
2266 void
2267 xloadcols(void) {
2268         int i, r, g, b;
2269         XRenderColor color = { .alpha = 0 };
2270
2271         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2272         for(i = 0; i < LEN(colorname); i++) {
2273                 if(!colorname[i])
2274                         continue;
2275                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2276                         die("Could not allocate color '%s'\n", colorname[i]);
2277                 }
2278         }
2279
2280         /* load colors [16-255] ; same colors as xterm */
2281         for(i = 16, r = 0; r < 6; r++) {
2282                 for(g = 0; g < 6; g++) {
2283                         for(b = 0; b < 6; b++) {
2284                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2285                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2286                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2287                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2288                                         die("Could not allocate color %d\n", i);
2289                                 }
2290                                 i++;
2291                         }
2292                 }
2293         }
2294
2295         for(r = 0; r < 24; r++, i++) {
2296                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2297                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2298                                         &dc.col[i])) {
2299                         die("Could not allocate color %d\n", i);
2300                 }
2301         }
2302 }
2303
2304 void
2305 xtermclear(int col1, int row1, int col2, int row2) {
2306         XftDrawRect(xw.draw,
2307                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2308                         borderpx + col1 * xw.cw,
2309                         borderpx + row1 * xw.ch,
2310                         (col2-col1+1) * xw.cw,
2311                         (row2-row1+1) * xw.ch);
2312 }
2313
2314 /*
2315  * Absolute coordinates.
2316  */
2317 void
2318 xclear(int x1, int y1, int x2, int y2) {
2319         XftDrawRect(xw.draw,
2320                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2321                         x1, y1, x2-x1, y2-y1);
2322 }
2323
2324 void
2325 xhints(void) {
2326         XClassHint class = {opt_class ? opt_class : termname, termname};
2327         XWMHints wm = {.flags = InputHint, .input = 1};
2328         XSizeHints *sizeh = NULL;
2329
2330         sizeh = XAllocSizeHints();
2331         if(xw.isfixed == False) {
2332                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2333                 sizeh->height = xw.h;
2334                 sizeh->width = xw.w;
2335                 sizeh->height_inc = xw.ch;
2336                 sizeh->width_inc = xw.cw;
2337                 sizeh->base_height = 2 * borderpx;
2338                 sizeh->base_width = 2 * borderpx;
2339         } else {
2340                 sizeh->flags = PMaxSize | PMinSize;
2341                 sizeh->min_width = sizeh->max_width = xw.fw;
2342                 sizeh->min_height = sizeh->max_height = xw.fh;
2343         }
2344
2345         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2346         XFree(sizeh);
2347 }
2348
2349 int
2350 xloadfont(Font *f, FcPattern *pattern) {
2351         FcPattern *match;
2352         FcResult result;
2353
2354         match = FcFontMatch(NULL, pattern, &result);
2355         if(!match)
2356                 return 1;
2357
2358         if(!(f->set = FcFontSort(0, match, FcTrue, 0, &result))) {
2359                 FcPatternDestroy(match);
2360                 return 1;
2361         }
2362
2363         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2364                 FcPatternDestroy(match);
2365                 return 1;
2366         }
2367
2368         f->pattern = FcPatternDuplicate(pattern);
2369
2370         f->ascent = f->match->ascent;
2371         f->descent = f->match->descent;
2372         f->lbearing = 0;
2373         f->rbearing = f->match->max_advance_width;
2374
2375         f->height = f->match->height;
2376         f->width = f->lbearing + f->rbearing;
2377
2378         return 0;
2379 }
2380
2381 void
2382 xloadfonts(char *fontstr, int fontsize) {
2383         FcPattern *pattern;
2384         FcResult result;
2385         double fontval;
2386
2387         if(fontstr[0] == '-') {
2388                 pattern = XftXlfdParse(fontstr, False, False);
2389         } else {
2390                 pattern = FcNameParse((FcChar8 *)fontstr);
2391         }
2392
2393         if(!pattern)
2394                 die("st: can't open font %s\n", fontstr);
2395
2396         if(fontsize > 0) {
2397                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2398                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2399                 usedfontsize = fontsize;
2400         } else {
2401                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2402                 if(result == FcResultMatch) {
2403                         usedfontsize = (int)fontval;
2404                 } else {
2405                         /*
2406                          * Default font size is 12, if none given. This is to
2407                          * have a known usedfontsize value.
2408                          */
2409                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2410                         usedfontsize = 12;
2411                 }
2412         }
2413
2414         FcConfigSubstitute(0, pattern, FcMatchPattern);
2415         FcDefaultSubstitute(pattern);
2416
2417         if(xloadfont(&dc.font, pattern))
2418                 die("st: can't open font %s\n", fontstr);
2419
2420         /* Setting character width and height. */
2421         xw.cw = dc.font.width;
2422         xw.ch = dc.font.height;
2423
2424         FcPatternDel(pattern, FC_WEIGHT);
2425         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2426         if(xloadfont(&dc.bfont, pattern))
2427                 die("st: can't open font %s\n", fontstr);
2428
2429         FcPatternDel(pattern, FC_SLANT);
2430         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2431         if(xloadfont(&dc.ibfont, pattern))
2432                 die("st: can't open font %s\n", fontstr);
2433
2434         FcPatternDel(pattern, FC_WEIGHT);
2435         if(xloadfont(&dc.ifont, pattern))
2436                 die("st: can't open font %s\n", fontstr);
2437
2438         FcPatternDestroy(pattern);
2439 }
2440
2441 void
2442 xunloadfonts(void)
2443 {
2444         int i, ip;
2445
2446         /*
2447          * Free the loaded fonts in the font cache. This is done backwards
2448          * from the frccur.
2449          */
2450         for (i = 0, ip = frccur; i < frclen; i++, ip--) {
2451                 if (ip < 0)
2452                         ip = LEN(frc) - 1;
2453                 XftFontClose(xw.dpy, frc[ip].font);
2454         }
2455         frccur = -1;
2456         frclen = 0;
2457
2458         XftFontClose(xw.dpy, dc.font.match);
2459         FcPatternDestroy(dc.font.pattern);
2460         FcFontSetDestroy(dc.font.set);
2461         XftFontClose(xw.dpy, dc.bfont.match);
2462         FcPatternDestroy(dc.bfont.pattern);
2463         FcFontSetDestroy(dc.bfont.set);
2464         XftFontClose(xw.dpy, dc.ifont.match);
2465         FcPatternDestroy(dc.ifont.pattern);
2466         FcFontSetDestroy(dc.ifont.set);
2467         XftFontClose(xw.dpy, dc.ibfont.match);
2468         FcPatternDestroy(dc.ibfont.pattern);
2469         FcFontSetDestroy(dc.ibfont.set);
2470 }
2471
2472 void
2473 xzoom(const Arg *arg)
2474 {
2475         xunloadfonts();
2476         xloadfonts(usedfont, usedfontsize + arg->i);
2477         cresize(0, 0);
2478         redraw(0);
2479 }
2480
2481 void
2482 xinit(void) {
2483         XSetWindowAttributes attrs;
2484         XGCValues gcvalues;
2485         Cursor cursor;
2486         Window parent;
2487         int sw, sh, major, minor;
2488
2489         if(!(xw.dpy = XOpenDisplay(NULL)))
2490                 die("Can't open display\n");
2491         xw.scr = XDefaultScreen(xw.dpy);
2492         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2493
2494         /* font */
2495         if (!FcInit())
2496                 die("Could not init fontconfig.\n");
2497
2498         usedfont = (opt_font == NULL)? font : opt_font;
2499         xloadfonts(usedfont, 0);
2500
2501         /* colors */
2502         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2503         xloadcols();
2504
2505         /* adjust fixed window geometry */
2506         if(xw.isfixed) {
2507                 sw = DisplayWidth(xw.dpy, xw.scr);
2508                 sh = DisplayHeight(xw.dpy, xw.scr);
2509                 if(xw.fx < 0)
2510                         xw.fx = sw + xw.fx - xw.fw - 1;
2511                 if(xw.fy < 0)
2512                         xw.fy = sh + xw.fy - xw.fh - 1;
2513
2514                 xw.h = xw.fh;
2515                 xw.w = xw.fw;
2516         } else {
2517                 /* window - default size */
2518                 xw.h = 2 * borderpx + term.row * xw.ch;
2519                 xw.w = 2 * borderpx + term.col * xw.cw;
2520                 xw.fx = 0;
2521                 xw.fy = 0;
2522         }
2523
2524         /* Events */
2525         attrs.background_pixel = dc.col[defaultbg].pixel;
2526         attrs.border_pixel = dc.col[defaultbg].pixel;
2527         attrs.bit_gravity = NorthWestGravity;
2528         attrs.event_mask = FocusChangeMask | KeyPressMask
2529                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2530                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2531         attrs.colormap = xw.cmap;
2532
2533         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2534                         XRootWindow(xw.dpy, xw.scr);
2535         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2536                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2537                         xw.vis,
2538                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2539                         | CWColormap,
2540                         &attrs);
2541
2542         /* double buffering */
2543         /*
2544         if(XdbeQueryExtension(xw.dpy, &major, &minor)) {
2545                 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win,
2546                                 XdbeBackground);
2547                 usedbe = True;
2548         } else {
2549         */
2550                 memset(&gcvalues, 0, sizeof(gcvalues));
2551                 gcvalues.graphics_exposures = False;
2552                 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2553                                 &gcvalues);
2554                 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2555                                 DefaultDepth(xw.dpy, xw.scr));
2556                 XSetForeground(xw.dpy, dc.gc, 0);
2557                 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2558                 //xw.buf = xw.win;
2559         /*
2560         }
2561         */
2562
2563         /* Xft rendering context */
2564         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2565
2566         /* input methods */
2567         if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2568                 XSetLocaleModifiers("@im=local");
2569                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2570                         XSetLocaleModifiers("@im=");
2571                         if((xw.xim = XOpenIM(xw.dpy,
2572                                         NULL, NULL, NULL)) == NULL) {
2573                                 die("XOpenIM failed. Could not open input"
2574                                         " device.\n");
2575                         }
2576                 }
2577         }
2578         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2579                                            | XIMStatusNothing, XNClientWindow, xw.win,
2580                                            XNFocusWindow, xw.win, NULL);
2581         if(xw.xic == NULL)
2582                 die("XCreateIC failed. Could not obtain input method.\n");
2583
2584         /* white cursor, black outline */
2585         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2586         XDefineCursor(xw.dpy, xw.win, cursor);
2587         XRecolorCursor(xw.dpy, cursor,
2588                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2589                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2590
2591         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2592         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2593         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2594
2595         xresettitle();
2596         XMapWindow(xw.dpy, xw.win);
2597         xhints();
2598         XSync(xw.dpy, 0);
2599 }
2600
2601 void
2602 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2603         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2604             width = charlen * xw.cw, xp, i;
2605         int frp, frcflags;
2606         int u8fl, u8fblen, u8cblen, doesexist;
2607         char *u8c, *u8fs;
2608         long u8char;
2609         Font *font = &dc.font;
2610         FcResult fcres;
2611         FcPattern *fcpattern, *fontpattern;
2612         FcFontSet *fcsets[] = { NULL };
2613         FcCharSet *fccharset;
2614         Colour *fg = &dc.col[base.fg], *bg = &dc.col[base.bg],
2615                  *temp, revfg, revbg;
2616         XRenderColor colfg, colbg;
2617
2618         frcflags = FRC_NORMAL;
2619
2620         if(base.mode & ATTR_BOLD) {
2621                 if(BETWEEN(base.fg, 0, 7)) {
2622                         /* basic system colors */
2623                         fg = &dc.col[base.fg + 8];
2624                 } else if(BETWEEN(base.fg, 16, 195)) {
2625                         /* 256 colors */
2626                         fg = &dc.col[base.fg + 36];
2627                 } else if(BETWEEN(base.fg, 232, 251)) {
2628                         /* greyscale */
2629                         fg = &dc.col[base.fg + 4];
2630                 }
2631                 /*
2632                  * Those ranges will not be brightened:
2633                  *      8 - 15 – bright system colors
2634                  *      196 - 231 – highest 256 color cube
2635                  *      252 - 255 – brightest colors in greyscale
2636                  */
2637                 font = &dc.bfont;
2638                 frcflags = FRC_BOLD;
2639         }
2640
2641         if(base.mode & ATTR_ITALIC) {
2642                 font = &dc.ifont;
2643                 frcflags = FRC_ITALIC;
2644         }
2645         if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2646                 font = &dc.ibfont;
2647                 frcflags = FRC_ITALICBOLD;
2648         }
2649
2650         if(IS_SET(MODE_REVERSE)) {
2651                 if(fg == &dc.col[defaultfg]) {
2652                         fg = &dc.col[defaultbg];
2653                 } else {
2654                         colfg.red = ~fg->color.red;
2655                         colfg.green = ~fg->color.green;
2656                         colfg.blue = ~fg->color.blue;
2657                         colfg.alpha = fg->color.alpha;
2658                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2659                         fg = &revfg;
2660                 }
2661
2662                 if(bg == &dc.col[defaultbg]) {
2663                         bg = &dc.col[defaultfg];
2664                 } else {
2665                         colbg.red = ~bg->color.red;
2666                         colbg.green = ~bg->color.green;
2667                         colbg.blue = ~bg->color.blue;
2668                         colbg.alpha = bg->color.alpha;
2669                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2670                         bg = &revbg;
2671                 }
2672         }
2673
2674         if(base.mode & ATTR_REVERSE) {
2675                 temp = fg;
2676                 fg = bg;
2677                 bg = temp;
2678         }
2679
2680         /* Intelligent cleaning up of the borders. */
2681         if(x == 0) {
2682                 xclear(0, (y == 0)? 0 : winy, borderpx,
2683                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
2684         }
2685         if(x + charlen >= term.col) {
2686                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2687                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
2688         }
2689         if(y == 0)
2690                 xclear(winx, 0, winx + width, borderpx);
2691         if(y == term.row-1)
2692                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2693
2694         /* Clean up the region we want to draw to. */
2695         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
2696
2697         fcsets[0] = font->set;
2698         for (xp = winx; bytelen > 0;) {
2699                 /*
2700                  * Search for the range in the to be printed string of glyphs
2701                  * that are in the main font. Then print that range. If
2702                  * some glyph is found that is not in the font, do the
2703                  * fallback dance.
2704                  */
2705                 u8fs = s;
2706                 u8fblen = 0;
2707                 u8fl = 0;
2708                 for (;;) {
2709                         u8c = s;
2710                         u8cblen = utf8decode(s, &u8char);
2711                         s += u8cblen;
2712                         bytelen -= u8cblen;
2713
2714                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
2715                         if (!doesexist || bytelen <= 0) {
2716                                 if (bytelen <= 0) {
2717                                         if (doesexist) {
2718                                                 u8fl++;
2719                                                 u8fblen += u8cblen;
2720                                         }
2721                                 }
2722
2723                                 if (u8fl > 0) {
2724                                         XftDrawStringUtf8(xw.draw, fg,
2725                                                         font->match, xp,
2726                                                         winy + font->ascent,
2727                                                         (FcChar8 *)u8fs,
2728                                                         u8fblen);
2729                                         xp += font->width * u8fl;
2730                                 }
2731                                 break;
2732                         }
2733
2734                         u8fl++;
2735                         u8fblen += u8cblen;
2736                 }
2737                 if (doesexist)
2738                         break;
2739
2740                 frp = frccur;
2741                 /* Search the font cache. */
2742                 for (i = 0; i < frclen; i++, frp--) {
2743                         if (frp <= 0)
2744                                 frp = LEN(frc) - 1;
2745
2746                         if (frc[frp].c == u8char
2747                                         && frc[frp].flags == frcflags) {
2748                                 break;
2749                         }
2750                 }
2751
2752                 /* Nothing was found. */
2753                 if (i >= frclen) {
2754                         /*
2755                          * Nothing was found in the cache. Now use
2756                          * some dozen of Fontconfig calls to get the
2757                          * font for one single character.
2758                          */
2759                         fcpattern = FcPatternDuplicate(font->pattern);
2760                         fccharset = FcCharSetCreate();
2761
2762                         FcCharSetAddChar(fccharset, u8char);
2763                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
2764                                         fccharset);
2765                         FcPatternAddBool(fcpattern, FC_SCALABLE,
2766                                         FcTrue);
2767
2768                         FcConfigSubstitute(0, fcpattern,
2769                                         FcMatchPattern);
2770                         FcDefaultSubstitute(fcpattern);
2771
2772                         fontpattern = FcFontSetMatch(0, fcsets,
2773                                         FcTrue, fcpattern, &fcres);
2774
2775                         /*
2776                          * Overwrite or create the new cache entry
2777                          * entry.
2778                          */
2779                         frccur++;
2780                         frclen++;
2781                         if (frccur >= LEN(frc))
2782                                 frccur = 0;
2783                         if (frclen > LEN(frc)) {
2784                                 frclen = LEN(frc);
2785                                 XftFontClose(xw.dpy, frc[frccur].font);
2786                         }
2787
2788                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
2789                                         fontpattern);
2790                         frc[frccur].c = u8char;
2791                         frc[frccur].flags = frcflags;
2792
2793                         FcPatternDestroy(fcpattern);
2794                         FcCharSetDestroy(fccharset);
2795
2796                         frp = frccur;
2797                 }
2798
2799                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
2800                                 xp, winy + frc[frp].font->ascent,
2801                                 (FcChar8 *)u8c, u8cblen);
2802
2803                 xp += font->width;
2804         }
2805
2806         /*
2807         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
2808                         winy + font->ascent, (FcChar8 *)s, bytelen);
2809         */
2810
2811         if(base.mode & ATTR_UNDERLINE) {
2812                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
2813                                 width, 1);
2814         }
2815 }
2816
2817 void
2818 xdrawcursor(void) {
2819         static int oldx = 0, oldy = 0;
2820         int sl;
2821         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2822
2823         LIMIT(oldx, 0, term.col-1);
2824         LIMIT(oldy, 0, term.row-1);
2825
2826         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2827                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2828
2829         /* remove the old cursor */
2830         if(term.line[oldy][oldx].state & GLYPH_SET) {
2831                 sl = utf8size(term.line[oldy][oldx].c);
2832                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2833                                 oldy, 1, sl);
2834         } else {
2835                 xtermclear(oldx, oldy, oldx, oldy);
2836         }
2837
2838         /* draw the new one */
2839         if(!(IS_SET(MODE_HIDE))) {
2840                 if(!(xw.state & WIN_FOCUSED))
2841                         g.bg = defaultucs;
2842
2843                 if(IS_SET(MODE_REVERSE))
2844                         g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2845
2846                 sl = utf8size(g.c);
2847                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2848                 oldx = term.c.x, oldy = term.c.y;
2849         }
2850 }
2851
2852 void
2853 xresettitle(void) {
2854         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2855 }
2856
2857 void
2858 redraw(int timeout) {
2859         struct timespec tv = {0, timeout * 1000};
2860
2861         tfulldirt();
2862         draw();
2863
2864         if(timeout > 0) {
2865                 nanosleep(&tv, NULL);
2866                 XSync(xw.dpy, False); /* necessary for a good tput flash */
2867         }
2868 }
2869
2870 void
2871 draw(void) {
2872         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2873
2874         drawregion(0, 0, term.col, term.row);
2875         if(usedbe) {
2876                 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2877         } else {
2878                 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
2879                                 xw.h, 0, 0);
2880                 XSetForeground(xw.dpy, dc.gc, 0);
2881         }
2882 }
2883
2884 void
2885 drawregion(int x1, int y1, int x2, int y2) {
2886         int ic, ib, x, y, ox, sl;
2887         Glyph base, new;
2888         char buf[DRAW_BUF_SIZ];
2889         bool ena_sel = sel.bx != -1;
2890
2891         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
2892                 ena_sel = 0;
2893
2894         if(!(xw.state & WIN_VISIBLE))
2895                 return;
2896
2897         for(y = y1; y < y2; y++) {
2898                 if(!term.dirty[y])
2899                         continue;
2900
2901                 xtermclear(0, y, term.col, y);
2902                 term.dirty[y] = 0;
2903                 base = term.line[y][0];
2904                 ic = ib = ox = 0;
2905                 for(x = x1; x < x2; x++) {
2906                         new = term.line[y][x];
2907                         if(ena_sel && *(new.c) && selected(x, y))
2908                                 new.mode ^= ATTR_REVERSE;
2909                         if(ib > 0 && (!(new.state & GLYPH_SET)
2910                                         || ATTRCMP(base, new)
2911                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2912                                 xdraws(buf, base, ox, y, ic, ib);
2913                                 ic = ib = 0;
2914                         }
2915                         if(new.state & GLYPH_SET) {
2916                                 if(ib == 0) {
2917                                         ox = x;
2918                                         base = new;
2919                                 }
2920
2921                                 sl = utf8size(new.c);
2922                                 memcpy(buf+ib, new.c, sl);
2923                                 ib += sl;
2924                                 ++ic;
2925                         }
2926                 }
2927                 if(ib > 0)
2928                         xdraws(buf, base, ox, y, ic, ib);
2929         }
2930         xdrawcursor();
2931 }
2932
2933 void
2934 expose(XEvent *ev) {
2935         XExposeEvent *e = &ev->xexpose;
2936
2937         if(xw.state & WIN_REDRAW) {
2938                 if(!e->count)
2939                         xw.state &= ~WIN_REDRAW;
2940         }
2941         redraw(0);
2942 }
2943
2944 void
2945 visibility(XEvent *ev) {
2946         XVisibilityEvent *e = &ev->xvisibility;
2947
2948         if(e->state == VisibilityFullyObscured) {
2949                 xw.state &= ~WIN_VISIBLE;
2950         } else if(!(xw.state & WIN_VISIBLE)) {
2951                 /* need a full redraw for next Expose, not just a buf copy */
2952                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2953         }
2954 }
2955
2956 void
2957 unmap(XEvent *ev) {
2958         xw.state &= ~WIN_VISIBLE;
2959 }
2960
2961 void
2962 xseturgency(int add) {
2963         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2964
2965         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2966         XSetWMHints(xw.dpy, xw.win, h);
2967         XFree(h);
2968 }
2969
2970 void
2971 focus(XEvent *ev) {
2972         if(ev->type == FocusIn) {
2973                 XSetICFocus(xw.xic);
2974                 xw.state |= WIN_FOCUSED;
2975                 xseturgency(0);
2976         } else {
2977                 XUnsetICFocus(xw.xic);
2978                 xw.state &= ~WIN_FOCUSED;
2979         }
2980 }
2981
2982 inline bool
2983 match(uint mask, uint state) {
2984         if(mask == XK_NO_MOD && state)
2985                 return false;
2986         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
2987                 return false;
2988         if((state & mask) != state)
2989                 return false;
2990         return true;
2991 }
2992
2993 void
2994 numlock(const Arg *dummy) {
2995         term.numlock ^= 1;
2996 }
2997
2998 char*
2999 kmap(KeySym k, uint state) {
3000         uint mask;
3001         Key *kp;
3002         int i;
3003
3004         /* Check for mapped keys out of X11 function keys. */
3005         for(i = 0; i < LEN(mappedkeys); i++) {
3006                 if(mappedkeys[i] == k)
3007                         break;
3008         }
3009         if(i == LEN(mappedkeys)) {
3010                 if((k & 0xFFFF) < 0xFD00)
3011                         return NULL;
3012         }
3013
3014         for(kp = key; kp < key + LEN(key); kp++) {
3015                 mask = kp->mask;
3016
3017                 if(kp->k != k)
3018                         continue;
3019
3020                 if(!match(mask, state))
3021                         continue;
3022
3023                 if(kp->appkey > 0) {
3024                         if(!IS_SET(MODE_APPKEYPAD))
3025                                 continue;
3026                         if(term.numlock && kp->appkey == 2)
3027                                 continue;
3028                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3029                         continue;
3030                 }
3031
3032                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3033                                 (kp->appcursor > 0
3034                                  && !IS_SET(MODE_APPCURSOR))) {
3035                         continue;
3036                 }
3037
3038                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3039                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3040                         continue;
3041                 }
3042
3043                 return kp->s;
3044         }
3045
3046         return NULL;
3047 }
3048
3049 void
3050 kpress(XEvent *ev) {
3051         XKeyEvent *e = &ev->xkey;
3052         KeySym ksym;
3053         char xstr[31], buf[32], *customkey, *cp = buf;
3054         int len;
3055         Status status;
3056         Shortcut *bp;
3057
3058         if (IS_SET(MODE_KBDLOCK))
3059                 return;
3060
3061         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3062         e->state &= ~Mod2Mask;
3063         /* 1. shortcuts */
3064         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3065                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3066                         bp->func(&(bp->arg));
3067                         return;
3068                 }
3069         }
3070
3071         /* 2. custom keys from config.h */
3072         if((customkey = kmap(ksym, e->state))) {
3073                 len = strlen(customkey);
3074                 memcpy(buf, customkey, len);
3075         /* 2. hardcoded (overrides X lookup) */
3076         } else {
3077                 if(len == 0)
3078                         return;
3079
3080                 if (len == 1 && e->state & Mod1Mask)
3081                         *cp++ = '\033';
3082
3083                 memcpy(cp, xstr, len);
3084                 len = cp - buf + len;
3085         }
3086
3087         ttywrite(buf, len);
3088         if(IS_SET(MODE_ECHO))
3089                 techo(buf, len);
3090 }
3091
3092
3093 void
3094 cmessage(XEvent *e) {
3095         /* See xembed specs
3096            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
3097         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3098                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3099                         xw.state |= WIN_FOCUSED;
3100                         xseturgency(0);
3101                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3102                         xw.state &= ~WIN_FOCUSED;
3103                 }
3104         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3105                 /* Send SIGHUP to shell */
3106                 kill(pid, SIGHUP);
3107                 exit(EXIT_SUCCESS);
3108         }
3109 }
3110
3111 void
3112 cresize(int width, int height)
3113 {
3114         int col, row;
3115
3116         if(width != 0)
3117                 xw.w = width;
3118         if(height != 0)
3119                 xw.h = height;
3120
3121         col = (xw.w - 2 * borderpx) / xw.cw;
3122         row = (xw.h - 2 * borderpx) / xw.ch;
3123
3124         tresize(col, row);
3125         xresize(col, row);
3126         ttyresize();
3127 }
3128
3129 void
3130 resize(XEvent *e) {
3131         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3132                 return;
3133
3134         cresize(e->xconfigure.width, e->xconfigure.height);
3135 }
3136
3137 void
3138 run(void) {
3139         XEvent ev;
3140         fd_set rfd;
3141         int xfd = XConnectionNumber(xw.dpy), i;
3142         struct timeval drawtimeout, *tv = NULL;
3143
3144         for(i = 0;; i++) {
3145                 FD_ZERO(&rfd);
3146                 FD_SET(cmdfd, &rfd);
3147                 FD_SET(xfd, &rfd);
3148                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3149                         if(errno == EINTR)
3150                                 continue;
3151                         die("select failed: %s\n", SERRNO);
3152                 }
3153
3154                 /*
3155                  * Stop after a certain number of reads so the user does not
3156                  * feel like the system is stuttering.
3157                  */
3158                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
3159                         ttyread();
3160
3161                         /*
3162                          * Just wait a bit so it isn't disturbing the
3163                          * user and the system is able to write something.
3164                          */
3165                         drawtimeout.tv_sec = 0;
3166                         drawtimeout.tv_usec = 5;
3167                         tv = &drawtimeout;
3168                         continue;
3169                 }
3170                 i = 0;
3171                 tv = NULL;
3172
3173                 while(XPending(xw.dpy)) {
3174                         XNextEvent(xw.dpy, &ev);
3175                         if(XFilterEvent(&ev, None))
3176                                 continue;
3177                         if(handler[ev.type])
3178                                 (handler[ev.type])(&ev);
3179                 }
3180
3181                 draw();
3182                 XFlush(xw.dpy);
3183         }
3184 }
3185
3186 int
3187 main(int argc, char *argv[]) {
3188         int i, bitm, xr, yr;
3189         uint wr, hr;
3190
3191         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3192         xw.isfixed = False;
3193
3194         for(i = 1; i < argc; i++) {
3195                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
3196                 case 'c':
3197                         if(++i < argc)
3198                                 opt_class = argv[i];
3199                         break;
3200                 case 'e':
3201                         /* eat all remaining arguments */
3202                         if(++i < argc)
3203                                 opt_cmd = &argv[i];
3204                         goto run;
3205                 case 'f':
3206                         if(++i < argc)
3207                                 opt_font = argv[i];
3208                         break;
3209                 case 'g':
3210                         if(++i >= argc)
3211                                 break;
3212
3213                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
3214                         if(bitm & XValue)
3215                                 xw.fx = xr;
3216                         if(bitm & YValue)
3217                                 xw.fy = yr;
3218                         if(bitm & WidthValue)
3219                                 xw.fw = (int)wr;
3220                         if(bitm & HeightValue)
3221                                 xw.fh = (int)hr;
3222                         if(bitm & XNegative && xw.fx == 0)
3223                                 xw.fx = -1;
3224                         if(bitm & XNegative && xw.fy == 0)
3225                                 xw.fy = -1;
3226
3227                         if(xw.fh != 0 && xw.fw != 0)
3228                                 xw.isfixed = True;
3229                         break;
3230                 case 'o':
3231                         if(++i < argc)
3232                                 opt_io = argv[i];
3233                         break;
3234                 case 't':
3235                         if(++i < argc)
3236                                 opt_title = argv[i];
3237                         break;
3238                 case 'v':
3239                 default:
3240                         die(USAGE);
3241                 case 'w':
3242                         if(++i < argc)
3243                                 opt_embed = argv[i];
3244                         break;
3245                 }
3246         }
3247
3248 run:
3249         setlocale(LC_CTYPE, "");
3250         XSetLocaleModifiers("");
3251         tnew(80, 24);
3252         xinit();
3253         ttynew();
3254         selinit();
3255         run();
3256
3257         return 0;
3258 }
3259