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