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