JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
4fbe05c9ef764e2e5876a075a13632245935770b
[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 <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
29 #define Glyph Glyph_
30 #define Font Font_
31
32 #if   defined(__linux)
33  #include <pty.h>
34 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
35  #include <util.h>
36 #elif defined(__FreeBSD__) || defined(__DragonFly__)
37  #include <libutil.h>
38 #endif
39
40 #define USAGE \
41         "st " VERSION " (c) 2010-2012 st engineers\n" \
42         "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
43         " [-t title] [-w windowid] [-e command ...]\n"
44
45 /* XEMBED messages */
46 #define XEMBED_FOCUS_IN  4
47 #define XEMBED_FOCUS_OUT 5
48
49 /* Arbitrary sizes */
50 #define ESC_BUF_SIZ   256
51 #define ESC_ARG_SIZ   16
52 #define STR_BUF_SIZ   256
53 #define STR_ARG_SIZ   16
54 #define DRAW_BUF_SIZ  20*1024
55 #define UTF_SIZ       4
56 #define XK_NO_MOD     UINT_MAX
57 #define XK_ANY_MOD    0
58
59 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
60
61 #define SERRNO strerror(errno)
62 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
63 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
64 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
65 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
66 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
67 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
68 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
69 #define IS_SET(flag) (term.mode & (flag))
70 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
71 #define X2COL(x) (((x) - BORDER)/xw.cw)
72 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
73
74 enum glyph_attribute {
75         ATTR_NULL      = 0,
76         ATTR_REVERSE   = 1,
77         ATTR_UNDERLINE = 2,
78         ATTR_BOLD      = 4,
79         ATTR_GFX       = 8,
80         ATTR_ITALIC    = 16,
81         ATTR_BLINK     = 32,
82 };
83
84 enum cursor_movement {
85         CURSOR_UP,
86         CURSOR_DOWN,
87         CURSOR_LEFT,
88         CURSOR_RIGHT,
89         CURSOR_SAVE,
90         CURSOR_LOAD
91 };
92
93 enum cursor_state {
94         CURSOR_DEFAULT  = 0,
95         CURSOR_HIDE     = 1,
96         CURSOR_WRAPNEXT = 2
97 };
98
99 enum glyph_state {
100         GLYPH_SET   = 1,
101         GLYPH_DIRTY = 2
102 };
103
104 enum term_mode {
105         MODE_WRAP       = 1,
106         MODE_INSERT      = 2,
107         MODE_APPKEYPAD   = 4,
108         MODE_ALTSCREEN   = 8,
109         MODE_CRLF       = 16,
110         MODE_MOUSEBTN    = 32,
111         MODE_MOUSEMOTION = 64,
112         MODE_MOUSE       = 32|64,
113         MODE_REVERSE     = 128,
114         MODE_KBDLOCK     = 256
115 };
116
117 enum escape_state {
118         ESC_START      = 1,
119         ESC_CSI = 2,
120         ESC_STR = 4, /* DSC, OSC, PM, APC */
121         ESC_ALTCHARSET = 8,
122         ESC_STR_END    = 16, /* a final string was encountered */
123 };
124
125 enum window_state {
126         WIN_VISIBLE = 1,
127         WIN_REDRAW  = 2,
128         WIN_FOCUSED = 4
129 };
130
131 /* bit macro */
132 #undef B0
133 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
134
135 typedef unsigned char uchar;
136 typedef unsigned int uint;
137 typedef unsigned long ulong;
138 typedef unsigned short ushort;
139
140 typedef struct {
141         char c[UTF_SIZ];     /* character code */
142         uchar mode;  /* attribute flags */
143         ushort fg;   /* foreground  */
144         ushort bg;   /* background  */
145         uchar state; /* state flags    */
146 } Glyph;
147
148 typedef Glyph* Line;
149
150 typedef struct {
151         Glyph attr;      /* current char attributes */
152         int x;
153         int y;
154         char state;
155 } TCursor;
156
157 /* CSI Escape sequence structs */
158 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
159 typedef struct {
160         char buf[ESC_BUF_SIZ]; /* raw string */
161         int len;               /* raw string length */
162         char priv;
163         int arg[ESC_ARG_SIZ];
164         int narg;             /* nb of args */
165         char mode;
166 } CSIEscape;
167
168 /* STR Escape sequence structs */
169 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
170 typedef struct {
171         char type;           /* ESC type ... */
172         char buf[STR_BUF_SIZ]; /* raw string */
173         int len;               /* raw string length */
174         char *args[STR_ARG_SIZ];
175         int narg;             /* nb of args */
176 } STREscape;
177
178 /* Internal representation of the screen */
179 typedef struct {
180         int row;        /* nb row */
181         int col;        /* nb col */
182         Line* line;     /* screen */
183         Line* alt;      /* alternate screen */
184         bool* dirty;    /* dirtyness of lines */
185         TCursor c;      /* cursor */
186         int top;        /* top    scroll limit */
187         int bot;        /* bottom scroll limit */
188         int mode;       /* terminal mode flags */
189         int esc;        /* escape state flags */
190         bool *tabs;
191 } Term;
192
193 /* Purely graphic info */
194 typedef struct {
195         Display* dpy;
196         Colormap cmap;
197         Window win;
198         XdbeBackBuffer buf;
199         Atom xembed;
200         XIM xim;
201         XIC xic;
202         XftDraw *xft_draw;
203         Visual *vis;
204         int scr;
205         bool isfixed; /* is fixed geometry? */
206         int fx, fy, fw, fh; /* fixed geometry */
207         int tw, th; /* tty width and height */
208         int w;  /* window width */
209         int h;  /* window height */
210         int ch; /* char height */
211         int cw; /* char width  */
212         char state; /* focus, redraw, visible */
213 } XWindow;
214
215 typedef struct {
216         KeySym k;
217         uint mask;
218         char s[ESC_BUF_SIZ];
219 } Key;
220
221 /* TODO: use better name for vars... */
222 typedef struct {
223         int mode;
224         int bx, by;
225         int ex, ey;
226         struct {int x, y;} b, e;
227         char *clip;
228         Atom xtarget;
229         bool alt;
230         struct timeval tclick1;
231         struct timeval tclick2;
232 } Selection;
233
234 #include "config.h"
235
236 /* Font structure */
237 typedef struct {
238         int ascent;
239         int descent;
240         short lbearing;
241         short rbearing;
242         XftFont* xft_set;
243 } Font;
244
245 /* Drawing Context */
246 typedef struct {
247         XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
248         GC gc;
249         Font font, bfont, ifont, ibfont;
250 } DC;
251
252 static void die(const char*, ...);
253 static void draw(void);
254 static void redraw(void);
255 static void drawregion(int, int, int, int);
256 static void execsh(void);
257 static void sigchld(int);
258 static void run(void);
259
260 static void csidump(void);
261 static void csihandle(void);
262 static void csiparse(void);
263 static void csireset(void);
264 static void strdump(void);
265 static void strhandle(void);
266 static void strparse(void);
267 static void strreset(void);
268
269 static void tclearregion(int, int, int, int);
270 static void tcursor(int);
271 static void tdeletechar(int);
272 static void tdeleteline(int);
273 static void tinsertblank(int);
274 static void tinsertblankline(int);
275 static void tmoveto(int, int);
276 static void tnew(int, int);
277 static void tnewline(int);
278 static void tputtab(bool);
279 static void tputc(char*, int);
280 static void treset(void);
281 static int tresize(int, int);
282 static void tscrollup(int, int);
283 static void tscrolldown(int, int);
284 static void tsetattr(int*, int);
285 static void tsetchar(char*);
286 static void tsetscroll(int, int);
287 static void tswapscreen(void);
288 static void tsetdirt(int, int);
289 static void tsetmode(bool, bool, int *, int);
290 static void tfulldirt(void);
291
292 static void ttynew(void);
293 static void ttyread(void);
294 static void ttyresize(void);
295 static void ttywrite(const char *, size_t);
296
297 static void xdraws(char *, Glyph, int, int, int, int);
298 static void xhints(void);
299 static void xclear(int, int, int, int);
300 static void xclearborders(void);
301 static void xdrawcursor(void);
302 static void xinit(void);
303 static void xloadcols(void);
304 static void xresettitle(void);
305 static void xseturgency(int);
306 static void xsetsel(char*);
307 static void xtermclear(int, int, int, int);
308 static void xresize(int, int);
309
310 static void expose(XEvent *);
311 static void visibility(XEvent *);
312 static void unmap(XEvent *);
313 static char* kmap(KeySym, uint);
314 static void kpress(XEvent *);
315 static void cmessage(XEvent *);
316 static void resize(XEvent *);
317 static void focus(XEvent *);
318 static void brelease(XEvent *);
319 static void bpress(XEvent *);
320 static void bmotion(XEvent *);
321 static void selnotify(XEvent *);
322 static void selclear(XEvent *);
323 static void selrequest(XEvent *);
324
325 static void selinit(void);
326 static inline bool selected(int, int);
327 static void selcopy(void);
328 static void selpaste(void);
329 static void selscroll(int, int);
330
331 static int utf8decode(char *, long *);
332 static int utf8encode(long *, char *);
333 static int utf8size(char *);
334 static int isfullutf8(char *, int);
335
336 static void *xmalloc(size_t);
337 static void *xrealloc(void *, size_t);
338 static void *xcalloc(size_t nmemb, size_t size);
339 static char *smstrcat(char *, ...);
340
341 static void (*handler[LASTEvent])(XEvent *) = {
342         [KeyPress] = kpress,
343         [ClientMessage] = cmessage,
344         [ConfigureNotify] = resize,
345         [VisibilityNotify] = visibility,
346         [UnmapNotify] = unmap,
347         [Expose] = expose,
348         [FocusIn] = focus,
349         [FocusOut] = focus,
350         [MotionNotify] = bmotion,
351         [ButtonPress] = bpress,
352         [ButtonRelease] = brelease,
353         [SelectionClear] = selclear,
354         [SelectionNotify] = selnotify,
355         [SelectionRequest] = selrequest,
356 };
357
358 /* Globals */
359 static DC dc;
360 static XWindow xw;
361 static Term term;
362 static CSIEscape csiescseq;
363 static STREscape strescseq;
364 static int cmdfd;
365 static pid_t pid;
366 static Selection sel;
367 static int iofd = -1;
368 static char **opt_cmd = NULL;
369 static char *opt_io = NULL;
370 static char *opt_title = NULL;
371 static char *opt_embed = NULL;
372 static char *opt_class = NULL;
373 static char *opt_font = NULL;
374
375 void *
376 xmalloc(size_t len) {
377         void *p = malloc(len);
378         if(!p)
379                 die("Out of memory\n");
380         return p;
381 }
382
383 void *
384 xrealloc(void *p, size_t len) {
385         if((p = realloc(p, len)) == NULL)
386                 die("Out of memory\n");
387         return p;
388 }
389
390 void *
391 xcalloc(size_t nmemb, size_t size) {
392         void *p = calloc(nmemb, size);
393         if(!p)
394                 die("Out of memory\n");
395         return p;
396 }
397
398 char *
399 smstrcat(char *src, ...)
400 {
401         va_list fmtargs;
402         char *ret, *p, *v;
403         int len, slen, flen;
404
405         len = slen = strlen(src);
406
407         va_start(fmtargs, src);
408         for(;;) {
409                 v = va_arg(fmtargs, char *);
410                 if(v == NULL)
411                         break;
412                 len += strlen(v);
413         }
414         va_end(fmtargs);
415
416         p = ret = xmalloc(len+1);
417         memmove(p, src, slen);
418         p += slen;
419
420         va_start(fmtargs, src);
421         for(;;) {
422                 v = va_arg(fmtargs, char *);
423                 if(v == NULL)
424                         break;
425                 flen = strlen(v);
426                 memmove(p, v, flen);
427                 p += flen;
428         }
429         va_end(fmtargs);
430
431         ret[len] = '\0';
432
433         return ret;
434 }
435
436 int
437 utf8decode(char *s, long *u) {
438         uchar c;
439         int i, n, rtn;
440
441         rtn = 1;
442         c = *s;
443         if(~c & B7) { /* 0xxxxxxx */
444                 *u = c;
445                 return rtn;
446         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
447                 *u = c&(B4|B3|B2|B1|B0);
448                 n = 1;
449         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
450                 *u = c&(B3|B2|B1|B0);
451                 n = 2;
452         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
453                 *u = c & (B2|B1|B0);
454                 n = 3;
455         } else
456                 goto invalid;
457         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
458                 c = *s;
459                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
460                         goto invalid;
461                 *u <<= 6;
462                 *u |= c & (B5|B4|B3|B2|B1|B0);
463         }
464         if((n == 1 && *u < 0x80) ||
465            (n == 2 && *u < 0x800) ||
466            (n == 3 && *u < 0x10000) ||
467            (*u >= 0xD800 && *u <= 0xDFFF))
468                 goto invalid;
469         return rtn;
470 invalid:
471         *u = 0xFFFD;
472         return rtn;
473 }
474
475 int
476 utf8encode(long *u, char *s) {
477         uchar *sp;
478         ulong uc;
479         int i, n;
480
481         sp = (uchar*) s;
482         uc = *u;
483         if(uc < 0x80) {
484                 *sp = uc; /* 0xxxxxxx */
485                 return 1;
486         } else if(*u < 0x800) {
487                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
488                 n = 1;
489         } else if(uc < 0x10000) {
490                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
491                 n = 2;
492         } else if(uc <= 0x10FFFF) {
493                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
494                 n = 3;
495         } else {
496                 goto invalid;
497         }
498         for(i=n,++sp; i>0; --i,++sp)
499                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
500         return n+1;
501 invalid:
502         /* U+FFFD */
503         *s++ = '\xEF';
504         *s++ = '\xBF';
505         *s = '\xBD';
506         return 3;
507 }
508
509 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
510    UTF-8 otherwise return 0 */
511 int
512 isfullutf8(char *s, int b) {
513         uchar *c1, *c2, *c3;
514
515         c1 = (uchar *) s;
516         c2 = (uchar *) ++s;
517         c3 = (uchar *) ++s;
518         if(b < 1)
519                 return 0;
520         else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
521                 return 0;
522         else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
523             ((b == 1) ||
524             ((b == 2) && (*c2&(B7|B6)) == B7)))
525                 return 0;
526         else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
527             ((b == 1) ||
528             ((b == 2) && (*c2&(B7|B6)) == B7) ||
529             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
530                 return 0;
531         else
532                 return 1;
533 }
534
535 int
536 utf8size(char *s) {
537         uchar c = *s;
538
539         if(~c&B7)
540                 return 1;
541         else if((c&(B7|B6|B5)) == (B7|B6))
542                 return 2;
543         else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
544                 return 3;
545         else
546                 return 4;
547 }
548
549 void
550 selinit(void) {
551         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
552         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
553         sel.mode = 0;
554         sel.bx = -1;
555         sel.clip = NULL;
556         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
557         if(sel.xtarget == None)
558                 sel.xtarget = XA_STRING;
559 }
560
561 static inline bool
562 selected(int x, int y) {
563         if(sel.ey == y && sel.by == y) {
564                 int bx = MIN(sel.bx, sel.ex);
565                 int ex = MAX(sel.bx, sel.ex);
566                 return BETWEEN(x, bx, ex);
567         }
568         return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
569                 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
570 }
571
572 void
573 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
574         if(b)
575                 *b = e->xbutton.button;
576
577         *x = X2COL(e->xbutton.x);
578         *y = Y2ROW(e->xbutton.y);
579         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
580         sel.b.y = MIN(sel.by, sel.ey);
581         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
582         sel.e.y = MAX(sel.by, sel.ey);
583 }
584
585 void
586 mousereport(XEvent *e) {
587         int x = X2COL(e->xbutton.x);
588         int y = Y2ROW(e->xbutton.y);
589         int button = e->xbutton.button;
590         int state = e->xbutton.state;
591         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
592         static int ob, ox, oy;
593
594         /* from urxvt */
595         if(e->xbutton.type == MotionNotify) {
596                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
597                         return;
598                 button = ob + 32;
599                 ox = x, oy = y;
600         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
601                 button = 3;
602         } else {
603                 button -= Button1;
604                 if(button >= 3)
605                         button += 64 - 3;
606                 if(e->xbutton.type == ButtonPress) {
607                         ob = button;
608                         ox = x, oy = y;
609                 }
610         }
611
612         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
613                 + (state & Mod4Mask    ? 8  : 0)
614                 + (state & ControlMask ? 16 : 0);
615
616         ttywrite(buf, sizeof(buf));
617 }
618
619 void
620 bpress(XEvent *e) {
621         if(IS_SET(MODE_MOUSE))
622                 mousereport(e);
623         else if(e->xbutton.button == Button1) {
624                 if(sel.bx != -1) {
625                         sel.bx = -1;
626                         tsetdirt(sel.b.y, sel.e.y);
627                         draw();
628                 }
629                 sel.mode = 1;
630                 sel.ex = sel.bx = X2COL(e->xbutton.x);
631                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
632         }
633 }
634
635 void
636 selcopy(void) {
637         char *str, *ptr;
638         int x, y, bufsize, is_selected = 0;
639
640         if(sel.bx == -1)
641                 str = NULL;
642
643         else {
644                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
645                 ptr = str = xmalloc(bufsize);
646
647                 /* append every set & selected glyph to the selection */
648                 for(y = 0; y < term.row; y++) {
649                         for(x = 0; x < term.col; x++) {
650                                 int size;
651                                 char *p;
652                                 Glyph *gp = &term.line[y][x];
653
654                                 if(!(is_selected = selected(x, y)))
655                                         continue;
656                                 p = (gp->state & GLYPH_SET) ? gp->c : " ";
657                                 size = utf8size(p);
658                                 memcpy(ptr, p, size);
659                                 ptr += size;
660                         }
661                         /* \n at the end of every selected line except for the last one */
662                         if(is_selected && y < sel.e.y)
663                                 *ptr++ = '\n';
664                 }
665                 *ptr = 0;
666         }
667         sel.alt = IS_SET(MODE_ALTSCREEN);
668         xsetsel(str);
669 }
670
671 void
672 selnotify(XEvent *e) {
673         ulong nitems, ofs, rem;
674         int format;
675         uchar *data;
676         Atom type;
677
678         ofs = 0;
679         do {
680                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
681                                         False, AnyPropertyType, &type, &format,
682                                         &nitems, &rem, &data)) {
683                         fprintf(stderr, "Clipboard allocation failed\n");
684                         return;
685                 }
686                 ttywrite((const char *) data, nitems * format / 8);
687                 XFree(data);
688                 /* number of 32-bit chunks returned */
689                 ofs += nitems * format / 32;
690         } while(rem > 0);
691 }
692
693 void
694 selpaste() {
695         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
696 }
697
698 void selclear(XEvent *e) {
699         if(sel.bx == -1)
700                 return;
701         sel.bx = -1;
702         tsetdirt(sel.b.y, sel.e.y);
703 }
704
705 void
706 selrequest(XEvent *e) {
707         XSelectionRequestEvent *xsre;
708         XSelectionEvent xev;
709         Atom xa_targets;
710
711         xsre = (XSelectionRequestEvent *) e;
712         xev.type = SelectionNotify;
713         xev.requestor = xsre->requestor;
714         xev.selection = xsre->selection;
715         xev.target = xsre->target;
716         xev.time = xsre->time;
717         /* reject */
718         xev.property = None;
719
720         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
721         if(xsre->target == xa_targets) {
722                 /* respond with the supported type */
723                 Atom string = sel.xtarget;
724                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
725                                 XA_ATOM, 32, PropModeReplace,
726                                 (uchar *) &string, 1);
727                 xev.property = xsre->property;
728         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
729                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
730                                 xsre->target, 8, PropModeReplace,
731                                 (uchar *) sel.clip, strlen(sel.clip));
732                 xev.property = xsre->property;
733         }
734
735         /* all done, send a notification to the listener */
736         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
737                 fprintf(stderr, "Error sending SelectionNotify event\n");
738 }
739
740 void
741 xsetsel(char *str) {
742         /* register the selection for both the clipboard and the primary */
743         Atom clipboard;
744
745         free(sel.clip);
746         sel.clip = str;
747
748         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
749
750         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
751         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
752 }
753
754 void
755 brelease(XEvent *e) {
756         if(IS_SET(MODE_MOUSE)) {
757                 mousereport(e);
758                 return;
759         }
760         if(e->xbutton.button == Button2)
761                 selpaste();
762         else if(e->xbutton.button == Button1) {
763                 sel.mode = 0;
764                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
765                 term.dirty[sel.ey] = 1;
766                 if(sel.bx == sel.ex && sel.by == sel.ey) {
767                         struct timeval now;
768                         sel.bx = -1;
769                         gettimeofday(&now, NULL);
770
771                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
772                                 /* triple click on the line */
773                                 sel.b.x = sel.bx = 0;
774                                 sel.e.x = sel.ex = term.col;
775                                 sel.b.y = sel.e.y = sel.ey;
776                                 selcopy();
777                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
778                                 /* double click to select word */
779                                 sel.bx = sel.ex;
780                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
781                                           term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
782                                 sel.b.x = sel.bx;
783                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
784                                           term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
785                                 sel.e.x = sel.ex;
786                                 sel.b.y = sel.e.y = sel.ey;
787                                 selcopy();
788                         }
789                 } else
790                         selcopy();
791         }
792         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
793         gettimeofday(&sel.tclick1, NULL);
794 }
795
796 void
797 bmotion(XEvent *e) {
798         if(IS_SET(MODE_MOUSE)) {
799                 mousereport(e);
800                 return;
801         }
802         if(sel.mode) {
803                 int oldey = sel.ey, oldex = sel.ex;
804                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
805
806                 if(oldey != sel.ey || oldex != sel.ex) {
807                         int starty = MIN(oldey, sel.ey);
808                         int endy = MAX(oldey, sel.ey);
809                         tsetdirt(starty, endy);
810                 }
811         }
812 }
813
814 void
815 die(const char *errstr, ...) {
816         va_list ap;
817
818         va_start(ap, errstr);
819         vfprintf(stderr, errstr, ap);
820         va_end(ap);
821         exit(EXIT_FAILURE);
822 }
823
824 void
825 execsh(void) {
826         char **args;
827         char *envshell = getenv("SHELL");
828
829         unsetenv("COLUMNS");
830         unsetenv("LINES");
831         unsetenv("TERMCAP");
832
833         signal(SIGCHLD, SIG_DFL);
834         signal(SIGHUP, SIG_DFL);
835         signal(SIGINT, SIG_DFL);
836         signal(SIGQUIT, SIG_DFL);
837         signal(SIGTERM, SIG_DFL);
838         signal(SIGALRM, SIG_DFL);
839
840         DEFAULT(envshell, SHELL);
841         putenv("TERM="TNAME);
842         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
843         execvp(args[0], args);
844         exit(EXIT_FAILURE);
845 }
846
847 void
848 sigchld(int a) {
849         int stat = 0;
850         if(waitpid(pid, &stat, 0) < 0)
851                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
852         if(WIFEXITED(stat))
853                 exit(WEXITSTATUS(stat));
854         else
855                 exit(EXIT_FAILURE);
856 }
857
858 void
859 ttynew(void) {
860         int m, s;
861
862         /* seems to work fine on linux, openbsd and freebsd */
863         struct winsize w = {term.row, term.col, 0, 0};
864         if(openpty(&m, &s, NULL, NULL, &w) < 0)
865                 die("openpty failed: %s\n", SERRNO);
866
867         switch(pid = fork()) {
868         case -1:
869                 die("fork failed\n");
870                 break;
871         case 0:
872                 setsid(); /* create a new process group */
873                 dup2(s, STDIN_FILENO);
874                 dup2(s, STDOUT_FILENO);
875                 dup2(s, STDERR_FILENO);
876                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
877                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
878                 close(s);
879                 close(m);
880                 execsh();
881                 break;
882         default:
883                 close(s);
884                 cmdfd = m;
885                 signal(SIGCHLD, sigchld);
886                 if(opt_io) {
887                         if(!strcmp(opt_io, "-")) {
888                                 iofd = STDOUT_FILENO;
889                         } else {
890                                 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
891                                         fprintf(stderr, "Error opening %s:%s\n",
892                                                 opt_io, strerror(errno));
893                                 }
894                         }
895                 }
896         }
897 }
898
899 void
900 dump(char c) {
901         static int col;
902         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
903         if(++col % 10 == 0)
904                 fprintf(stderr, "\n");
905 }
906
907 void
908 ttyread(void) {
909         static char buf[BUFSIZ];
910         static int buflen = 0;
911         char *ptr;
912         char s[UTF_SIZ];
913         int charsize; /* size of utf8 char in bytes */
914         long utf8c;
915         int ret;
916
917         /* append read bytes to unprocessed bytes */
918         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
919                 die("Couldn't read from shell: %s\n", SERRNO);
920
921         /* process every complete utf8 char */
922         buflen += ret;
923         ptr = buf;
924         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
925                 charsize = utf8decode(ptr, &utf8c);
926                 utf8encode(&utf8c, s);
927                 tputc(s, charsize);
928                 ptr    += charsize;
929                 buflen -= charsize;
930         }
931
932         /* keep any uncomplete utf8 char for the next call */
933         memmove(buf, ptr, buflen);
934 }
935
936 void
937 ttywrite(const char *s, size_t n) {
938         if(write(cmdfd, s, n) == -1)
939                 die("write error on tty: %s\n", SERRNO);
940 }
941
942 void
943 ttyresize(void) {
944         struct winsize w;
945
946         w.ws_row = term.row;
947         w.ws_col = term.col;
948         w.ws_xpixel = xw.tw;
949         w.ws_ypixel = xw.th;
950         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
951                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
952 }
953
954 void
955 tsetdirt(int top, int bot)
956 {
957         int i;
958
959         LIMIT(top, 0, term.row-1);
960         LIMIT(bot, 0, term.row-1);
961
962         for(i = top; i <= bot; i++)
963                 term.dirty[i] = 1;
964 }
965
966 void
967 tfulldirt(void)
968 {
969         tsetdirt(0, term.row-1);
970 }
971
972 void
973 tcursor(int mode) {
974         static TCursor c;
975
976         if(mode == CURSOR_SAVE)
977                 c = term.c;
978         else if(mode == CURSOR_LOAD)
979                 term.c = c, tmoveto(c.x, c.y);
980 }
981
982 void
983 treset(void) {
984         uint i;
985         term.c = (TCursor){{
986                 .mode = ATTR_NULL,
987                 .fg = DefaultFG,
988                 .bg = DefaultBG
989         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
990
991         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
992         for(i = TAB; i < term.col; i += TAB)
993                 term.tabs[i] = 1;
994         term.top = 0, term.bot = term.row - 1;
995         term.mode = MODE_WRAP;
996
997         tclearregion(0, 0, term.col-1, term.row-1);
998 }
999
1000 void
1001 tnew(int col, int row) {
1002         /* set screen size */
1003         term.row = row, term.col = col;
1004         term.line = xmalloc(term.row * sizeof(Line));
1005         term.alt  = xmalloc(term.row * sizeof(Line));
1006         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1007         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1008
1009         for(row = 0; row < term.row; row++) {
1010                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1011                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1012                 term.dirty[row] = 0;
1013         }
1014         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1015         /* setup screen */
1016         treset();
1017 }
1018
1019 void
1020 tswapscreen(void) {
1021         Line* tmp = term.line;
1022         term.line = term.alt;
1023         term.alt = tmp;
1024         term.mode ^= MODE_ALTSCREEN;
1025         tfulldirt();
1026 }
1027
1028 void
1029 tscrolldown(int orig, int n) {
1030         int i;
1031         Line temp;
1032
1033         LIMIT(n, 0, term.bot-orig+1);
1034
1035         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1036
1037         for(i = term.bot; i >= orig+n; i--) {
1038                 temp = term.line[i];
1039                 term.line[i] = term.line[i-n];
1040                 term.line[i-n] = temp;
1041
1042                 term.dirty[i] = 1;
1043                 term.dirty[i-n] = 1;
1044         }
1045
1046         selscroll(orig, n);
1047 }
1048
1049 void
1050 tscrollup(int orig, int n) {
1051         int i;
1052         Line temp;
1053         LIMIT(n, 0, term.bot-orig+1);
1054
1055         tclearregion(0, orig, term.col-1, orig+n-1);
1056
1057         for(i = orig; i <= term.bot-n; i++) {
1058                  temp = term.line[i];
1059                  term.line[i] = term.line[i+n];
1060                  term.line[i+n] = temp;
1061
1062                  term.dirty[i] = 1;
1063                  term.dirty[i+n] = 1;
1064         }
1065
1066         selscroll(orig, -n);
1067 }
1068
1069 void
1070 selscroll(int orig, int n) {
1071         if(sel.bx == -1)
1072                 return;
1073
1074         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1075                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1076                         sel.bx = -1;
1077                         return;
1078                 }
1079                 if(sel.by < term.top) {
1080                         sel.by = term.top;
1081                         sel.bx = 0;
1082                 }
1083                 if(sel.ey > term.bot) {
1084                         sel.ey = term.bot;
1085                         sel.ex = term.col;
1086                 }
1087                 sel.b.y = sel.by, sel.b.x = sel.bx;
1088                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1089         }
1090 }
1091
1092 void
1093 tnewline(int first_col) {
1094         int y = term.c.y;
1095         if(y == term.bot)
1096                 tscrollup(term.top, 1);
1097         else
1098                 y++;
1099         tmoveto(first_col ? 0 : term.c.x, y);
1100 }
1101
1102 void
1103 csiparse(void) {
1104         /* int noarg = 1; */
1105         char *p = csiescseq.buf;
1106
1107         csiescseq.narg = 0;
1108         if(*p == '?')
1109                 csiescseq.priv = 1, p++;
1110
1111         while(p < csiescseq.buf+csiescseq.len) {
1112                 while(isdigit(*p)) {
1113                         csiescseq.arg[csiescseq.narg] *= 10;
1114                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1115                 }
1116                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1117                         csiescseq.narg++, p++;
1118                 else {
1119                         csiescseq.mode = *p;
1120                         csiescseq.narg++;
1121                         return;
1122                 }
1123         }
1124 }
1125
1126 void
1127 tmoveto(int x, int y) {
1128         LIMIT(x, 0, term.col-1);
1129         LIMIT(y, 0, term.row-1);
1130         term.c.state &= ~CURSOR_WRAPNEXT;
1131         term.c.x = x;
1132         term.c.y = y;
1133 }
1134
1135 void
1136 tsetchar(char *c) {
1137         /*
1138          * The table is proudly stolen from rxvt.
1139          */
1140         if(term.c.attr.mode & ATTR_GFX) {
1141                 char *vt100_0[62] = { /* 0x41 - 0x7e */
1142                         "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1143                         0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1144                         0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1145                         0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1146                         "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1147                         "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1148                         "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1149                         "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1150                 };
1151
1152                 if(c[0] >= 0x41 && c[0] <= 0x7e
1153                                 && vt100_0[c[0] - 0x41]) {
1154                         c = vt100_0[c[0] - 0x41];
1155                 }
1156         }
1157
1158         term.dirty[term.c.y] = 1;
1159         term.line[term.c.y][term.c.x] = term.c.attr;
1160         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1161         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1162 }
1163
1164 void
1165 tclearregion(int x1, int y1, int x2, int y2) {
1166         int x, y, temp;
1167
1168         if(x1 > x2)
1169                 temp = x1, x1 = x2, x2 = temp;
1170         if(y1 > y2)
1171                 temp = y1, y1 = y2, y2 = temp;
1172
1173         LIMIT(x1, 0, term.col-1);
1174         LIMIT(x2, 0, term.col-1);
1175         LIMIT(y1, 0, term.row-1);
1176         LIMIT(y2, 0, term.row-1);
1177
1178         for(y = y1; y <= y2; y++) {
1179                 term.dirty[y] = 1;
1180                 for(x = x1; x <= x2; x++)
1181                         term.line[y][x].state = 0;
1182         }
1183 }
1184
1185 void
1186 tdeletechar(int n) {
1187         int src = term.c.x + n;
1188         int dst = term.c.x;
1189         int size = term.col - src;
1190
1191         term.dirty[term.c.y] = 1;
1192
1193         if(src >= term.col) {
1194                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1195                 return;
1196         }
1197         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1198         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1199 }
1200
1201 void
1202 tinsertblank(int n) {
1203         int src = term.c.x;
1204         int dst = src + n;
1205         int size = term.col - dst;
1206
1207         term.dirty[term.c.y] = 1;
1208
1209         if(dst >= term.col) {
1210                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1211                 return;
1212         }
1213         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1214         tclearregion(src, term.c.y, dst - 1, term.c.y);
1215 }
1216
1217 void
1218 tinsertblankline(int n) {
1219         if(term.c.y < term.top || term.c.y > term.bot)
1220                 return;
1221
1222         tscrolldown(term.c.y, n);
1223 }
1224
1225 void
1226 tdeleteline(int n) {
1227         if(term.c.y < term.top || term.c.y > term.bot)
1228                 return;
1229
1230         tscrollup(term.c.y, n);
1231 }
1232
1233 void
1234 tsetattr(int *attr, int l) {
1235         int i;
1236
1237         for(i = 0; i < l; i++) {
1238                 switch(attr[i]) {
1239                 case 0:
1240                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1241                                         | ATTR_ITALIC | ATTR_BLINK);
1242                         term.c.attr.fg = DefaultFG;
1243                         term.c.attr.bg = DefaultBG;
1244                         break;
1245                 case 1:
1246                         term.c.attr.mode |= ATTR_BOLD;
1247                         break;
1248                 case 3: /* enter standout (highlight) */
1249                         term.c.attr.mode |= ATTR_ITALIC;
1250                         break;
1251                 case 4:
1252                         term.c.attr.mode |= ATTR_UNDERLINE;
1253                         break;
1254                 case 5:
1255                         term.c.attr.mode |= ATTR_BLINK;
1256                         break;
1257                 case 7:
1258                         term.c.attr.mode |= ATTR_REVERSE;
1259                         break;
1260                 case 21:
1261                 case 22:
1262                         term.c.attr.mode &= ~ATTR_BOLD;
1263                         break;
1264                 case 23: /* leave standout (highlight) mode */
1265                         term.c.attr.mode &= ~ATTR_ITALIC;
1266                         break;
1267                 case 24:
1268                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1269                         break;
1270                 case 25:
1271                         term.c.attr.mode &= ~ATTR_BLINK;
1272                         break;
1273                 case 27:
1274                         term.c.attr.mode &= ~ATTR_REVERSE;
1275                         break;
1276                 case 38:
1277                         if(i + 2 < l && attr[i + 1] == 5) {
1278                                 i += 2;
1279                                 if(BETWEEN(attr[i], 0, 255))
1280                                         term.c.attr.fg = attr[i];
1281                                 else
1282                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1283                         }
1284                         else
1285                                 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1286                         break;
1287                 case 39:
1288                         term.c.attr.fg = DefaultFG;
1289                         break;
1290                 case 48:
1291                         if(i + 2 < l && attr[i + 1] == 5) {
1292                                 i += 2;
1293                                 if(BETWEEN(attr[i], 0, 255))
1294                                         term.c.attr.bg = attr[i];
1295                                 else
1296                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1297                         }
1298                         else
1299                                 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1300                         break;
1301                 case 49:
1302                         term.c.attr.bg = DefaultBG;
1303                         break;
1304                 default:
1305                         if(BETWEEN(attr[i], 30, 37))
1306                                 term.c.attr.fg = attr[i] - 30;
1307                         else if(BETWEEN(attr[i], 40, 47))
1308                                 term.c.attr.bg = attr[i] - 40;
1309                         else if(BETWEEN(attr[i], 90, 97))
1310                                 term.c.attr.fg = attr[i] - 90 + 8;
1311                         else if(BETWEEN(attr[i], 100, 107))
1312                                 term.c.attr.bg = attr[i] - 100 + 8;
1313                         else
1314                                 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1315                         break;
1316                 }
1317         }
1318 }
1319
1320 void
1321 tsetscroll(int t, int b) {
1322         int temp;
1323
1324         LIMIT(t, 0, term.row-1);
1325         LIMIT(b, 0, term.row-1);
1326         if(t > b) {
1327                 temp = t;
1328                 t = b;
1329                 b = temp;
1330         }
1331         term.top = t;
1332         term.bot = b;
1333 }
1334
1335 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1336
1337 void
1338 tsetmode(bool priv, bool set, int *args, int narg) {
1339         int *lim, mode;
1340
1341         for(lim = args + narg; args < lim; ++args) {
1342                 if(priv) {
1343                         switch(*args) {
1344                                 break;
1345                         case 1: /* DECCKM -- Cursor key */
1346                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1347                                 break;
1348                         case 5: /* DECSCNM -- Reverve video */
1349                                 mode = term.mode;
1350                                 MODBIT(term.mode, set, MODE_REVERSE);
1351                                 if(mode != term.mode)
1352                                         redraw();
1353                                 break;
1354                         case 6: /* XXX: DECOM -- Origin */
1355                                 break;
1356                         case 7: /* DECAWM -- Auto wrap */
1357                                 MODBIT(term.mode, set, MODE_WRAP);
1358                                 break;
1359                         case 8: /* XXX: DECARM -- Auto repeat */
1360                                 break;
1361                         case 0:  /* Error (IGNORED) */
1362                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1363                                 break;
1364                         case 25:
1365                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1366                                 break;
1367                         case 1000: /* 1000,1002: enable xterm mouse report */
1368                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1369                                 break;
1370                         case 1002:
1371                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1372                                 break;
1373                         case 1049: /* = 1047 and 1048 */
1374                         case 47:
1375                         case 1047:
1376                                 if(IS_SET(MODE_ALTSCREEN))
1377                                         tclearregion(0, 0, term.col-1, term.row-1);
1378                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1379                                     (!set && IS_SET(MODE_ALTSCREEN))) {
1380                                             tswapscreen();
1381                                 }
1382                                 if(*args != 1049)
1383                                         break;
1384                                 /* pass through */
1385                         case 1048:
1386                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1387                                 break;
1388                         default:
1389                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1390                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1391                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1392                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1393                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1394                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1395                                 fprintf(stderr,
1396                                         "erresc: unknown private set/reset mode %d\n",
1397                                         *args);
1398                                 break;
1399                         }
1400                 } else {
1401                         switch(*args) {
1402                         case 0:  /* Error (IGNORED) */
1403                                 break;
1404                         case 2:  /* KAM -- keyboard action */
1405                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1406                                 break;
1407                         case 4:  /* IRM -- Insertion-replacement */
1408                                 MODBIT(term.mode, set, MODE_INSERT);
1409                                 break;
1410                         case 12: /* XXX: SRM -- Send/Receive */
1411                                 break;
1412                         case 20: /* LNM -- Linefeed/new line */
1413                                 MODBIT(term.mode, set, MODE_CRLF);
1414                                 break;
1415                         default:
1416                                 fprintf(stderr,
1417                                         "erresc: unknown set/reset mode %d\n",
1418                                         *args);
1419                                 break;
1420                         }
1421                 }
1422         }
1423 }
1424 #undef MODBIT
1425
1426
1427 void
1428 csihandle(void) {
1429         switch(csiescseq.mode) {
1430         default:
1431         unknown:
1432                 fprintf(stderr, "erresc: unknown csi ");
1433                 csidump();
1434                 /* die(""); */
1435                 break;
1436         case '@': /* ICH -- Insert <n> blank char */
1437                 DEFAULT(csiescseq.arg[0], 1);
1438                 tinsertblank(csiescseq.arg[0]);
1439                 break;
1440         case 'A': /* CUU -- Cursor <n> Up */
1441         case 'e':
1442                 DEFAULT(csiescseq.arg[0], 1);
1443                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1444                 break;
1445         case 'B': /* CUD -- Cursor <n> Down */
1446                 DEFAULT(csiescseq.arg[0], 1);
1447                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1448                 break;
1449         case 'C': /* CUF -- Cursor <n> Forward */
1450         case 'a':
1451                 DEFAULT(csiescseq.arg[0], 1);
1452                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1453                 break;
1454         case 'D': /* CUB -- Cursor <n> Backward */
1455                 DEFAULT(csiescseq.arg[0], 1);
1456                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1457                 break;
1458         case 'E': /* CNL -- Cursor <n> Down and first col */
1459                 DEFAULT(csiescseq.arg[0], 1);
1460                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1461                 break;
1462         case 'F': /* CPL -- Cursor <n> Up and first col */
1463                 DEFAULT(csiescseq.arg[0], 1);
1464                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1465                 break;
1466         case 'g': /* TBC -- Tabulation clear */
1467                 switch (csiescseq.arg[0]) {
1468                 case 0: /* clear current tab stop */
1469                         term.tabs[term.c.x] = 0;
1470                         break;
1471                 case 3: /* clear all the tabs */
1472                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1473                         break;
1474                 default:
1475                         goto unknown;
1476                 }
1477                 break;
1478         case 'G': /* CHA -- Move to <col> */
1479         case '`': /* HPA */
1480                 DEFAULT(csiescseq.arg[0], 1);
1481                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1482                 break;
1483         case 'H': /* CUP -- Move to <row> <col> */
1484         case 'f': /* HVP */
1485                 DEFAULT(csiescseq.arg[0], 1);
1486                 DEFAULT(csiescseq.arg[1], 1);
1487                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1488                 break;
1489         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1490                 DEFAULT(csiescseq.arg[0], 1);
1491                 while(csiescseq.arg[0]--)
1492                         tputtab(1);
1493                 break;
1494         case 'J': /* ED -- Clear screen */
1495                 sel.bx = -1;
1496                 switch(csiescseq.arg[0]) {
1497                 case 0: /* below */
1498                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1499                         if(term.c.y < term.row-1)
1500                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1501                         break;
1502                 case 1: /* above */
1503                         if(term.c.y > 1)
1504                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1505                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1506                         break;
1507                 case 2: /* all */
1508                         tclearregion(0, 0, term.col-1, term.row-1);
1509                         break;
1510                 default:
1511                         goto unknown;
1512                 }
1513                 break;
1514         case 'K': /* EL -- Clear line */
1515                 switch(csiescseq.arg[0]) {
1516                 case 0: /* right */
1517                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1518                         break;
1519                 case 1: /* left */
1520                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1521                         break;
1522                 case 2: /* all */
1523                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1524                         break;
1525                 }
1526                 break;
1527         case 'S': /* SU -- Scroll <n> line up */
1528                 DEFAULT(csiescseq.arg[0], 1);
1529                 tscrollup(term.top, csiescseq.arg[0]);
1530                 break;
1531         case 'T': /* SD -- Scroll <n> line down */
1532                 DEFAULT(csiescseq.arg[0], 1);
1533                 tscrolldown(term.top, csiescseq.arg[0]);
1534                 break;
1535         case 'L': /* IL -- Insert <n> blank lines */
1536                 DEFAULT(csiescseq.arg[0], 1);
1537                 tinsertblankline(csiescseq.arg[0]);
1538                 break;
1539         case 'l': /* RM -- Reset Mode */
1540                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1541                 break;
1542         case 'M': /* DL -- Delete <n> lines */
1543                 DEFAULT(csiescseq.arg[0], 1);
1544                 tdeleteline(csiescseq.arg[0]);
1545                 break;
1546         case 'X': /* ECH -- Erase <n> char */
1547                 DEFAULT(csiescseq.arg[0], 1);
1548                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1549                 break;
1550         case 'P': /* DCH -- Delete <n> char */
1551                 DEFAULT(csiescseq.arg[0], 1);
1552                 tdeletechar(csiescseq.arg[0]);
1553                 break;
1554         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1555                 DEFAULT(csiescseq.arg[0], 1);
1556                 while(csiescseq.arg[0]--)
1557                         tputtab(0);
1558                 break;
1559         case 'd': /* VPA -- Move to <row> */
1560                 DEFAULT(csiescseq.arg[0], 1);
1561                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1562                 break;
1563         case 'h': /* SM -- Set terminal mode */
1564                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1565                 break;
1566         case 'm': /* SGR -- Terminal attribute (color) */
1567                 tsetattr(csiescseq.arg, csiescseq.narg);
1568                 break;
1569         case 'r': /* DECSTBM -- Set Scrolling Region */
1570                 if(csiescseq.priv)
1571                         goto unknown;
1572                 else {
1573                         DEFAULT(csiescseq.arg[0], 1);
1574                         DEFAULT(csiescseq.arg[1], term.row);
1575                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1576                         tmoveto(0, 0);
1577                 }
1578                 break;
1579         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1580                 tcursor(CURSOR_SAVE);
1581                 break;
1582         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1583                 tcursor(CURSOR_LOAD);
1584                 break;
1585         }
1586 }
1587
1588 void
1589 csidump(void) {
1590         int i;
1591         printf("ESC[");
1592         for(i = 0; i < csiescseq.len; i++) {
1593                 uint c = csiescseq.buf[i] & 0xff;
1594                 if(isprint(c)) putchar(c);
1595                 else if(c == '\n') printf("(\\n)");
1596                 else if(c == '\r') printf("(\\r)");
1597                 else if(c == 0x1b) printf("(\\e)");
1598                 else printf("(%02x)", c);
1599         }
1600         putchar('\n');
1601 }
1602
1603 void
1604 csireset(void) {
1605         memset(&csiescseq, 0, sizeof(csiescseq));
1606 }
1607
1608 void
1609 strhandle(void) {
1610         char *p;
1611
1612         /*
1613          * TODO: make this being useful in case of color palette change.
1614          */
1615         strparse();
1616
1617         p = strescseq.buf;
1618
1619         switch(strescseq.type) {
1620         case ']': /* OSC -- Operating System Command */
1621                 switch(p[0]) {
1622                 case '0':
1623                 case '1':
1624                 case '2':
1625                         /*
1626                          * TODO: Handle special chars in string, like umlauts.
1627                          */
1628                         if(p[1] == ';') {
1629                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1630                         }
1631                         break;
1632                 case ';':
1633                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1634                         break;
1635                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1636                         break;
1637                 default:
1638                         fprintf(stderr, "erresc: unknown str ");
1639                         strdump();
1640                         break;
1641                 }
1642                 break;
1643         case 'k': /* old title set compatibility */
1644                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1645                 break;
1646         case 'P': /* DSC -- Device Control String */
1647         case '_': /* APC -- Application Program Command */
1648         case '^': /* PM -- Privacy Message */
1649         default:
1650                 fprintf(stderr, "erresc: unknown str ");
1651                 strdump();
1652                 /* die(""); */
1653                 break;
1654         }
1655 }
1656
1657 void
1658 strparse(void) {
1659         /*
1660          * TODO: Implement parsing like for CSI when required.
1661          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1662          */
1663         return;
1664 }
1665
1666 void
1667 strdump(void) {
1668         int i;
1669         printf("ESC%c", strescseq.type);
1670         for(i = 0; i < strescseq.len; i++) {
1671                 uint c = strescseq.buf[i] & 0xff;
1672                 if(isprint(c)) putchar(c);
1673                 else if(c == '\n') printf("(\\n)");
1674                 else if(c == '\r') printf("(\\r)");
1675                 else if(c == 0x1b) printf("(\\e)");
1676                 else printf("(%02x)", c);
1677         }
1678         printf("ESC\\\n");
1679 }
1680
1681 void
1682 strreset(void) {
1683         memset(&strescseq, 0, sizeof(strescseq));
1684 }
1685
1686 void
1687 tputtab(bool forward) {
1688         uint x = term.c.x;
1689
1690         if(forward) {
1691                 if(x == term.col)
1692                         return;
1693                 for(++x; x < term.col && !term.tabs[x]; ++x)
1694                         /* nothing */ ;
1695         } else {
1696                 if(x == 0)
1697                         return;
1698                 for(--x; x > 0 && !term.tabs[x]; --x)
1699                         /* nothing */ ;
1700         }
1701         tmoveto(x, term.c.y);
1702 }
1703
1704 void
1705 tputc(char *c, int len) {
1706         uchar ascii = *c;
1707
1708         if(iofd != -1)
1709                 write(iofd, c, len);
1710
1711         switch(ascii) {
1712         case '\t':
1713                 tputtab(1);
1714                 return;
1715         case '\b':
1716                 tmoveto(term.c.x-1, term.c.y);
1717                 return;
1718         case '\r':
1719                 tmoveto(0, term.c.y);
1720                 return;
1721         case '\f':
1722         case '\v':
1723         case '\n':
1724                 /* go to first col if the mode is set */
1725                 tnewline(IS_SET(MODE_CRLF));
1726                 return;
1727         case '\a':
1728                 if(term.esc & ESC_STR)
1729                         break;
1730
1731                 if(!(xw.state & WIN_FOCUSED))
1732                         xseturgency(1);
1733                 return;
1734         case '\033':
1735                 csireset();
1736                 term.esc = ESC_START;
1737                 return;
1738         }
1739
1740         if(term.esc & ESC_START) {
1741                 if(term.esc & ESC_CSI) {
1742                         csiescseq.buf[csiescseq.len++] = ascii;
1743                         if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1744                                 term.esc = 0;
1745                                 csiparse(), csihandle();
1746                         }
1747                 } else if(term.esc & ESC_STR) {
1748                         switch(ascii) {
1749                         case '\033':
1750                                 term.esc = ESC_START | ESC_STR_END;
1751                                 break;
1752                         case '\a': /* backwards compatibility to xterm */
1753                                 term.esc = 0;
1754                                 strhandle();
1755                                 break;
1756                         default:
1757                                 strescseq.buf[strescseq.len++] = ascii;
1758                                 if(strescseq.len+1 >= STR_BUF_SIZ) {
1759                                         term.esc = 0;
1760                                         strhandle();
1761                                 }
1762                         }
1763                 } else if(term.esc & ESC_STR_END) {
1764                         term.esc = 0;
1765                         if(ascii == '\\')
1766                                 strhandle();
1767                 } else if(term.esc & ESC_ALTCHARSET) {
1768                         switch(ascii) {
1769                         case '0': /* Line drawing set */
1770                                 term.c.attr.mode |= ATTR_GFX;
1771                                 break;
1772                         case 'B': /* USASCII */
1773                                 term.c.attr.mode &= ~ATTR_GFX;
1774                                 break;
1775                         case 'A': /* UK (IGNORED) */
1776                         case '<': /* multinational charset (IGNORED) */
1777                         case '5': /* Finnish (IGNORED) */
1778                         case 'C': /* Finnish (IGNORED) */
1779                         case 'K': /* German (IGNORED) */
1780                                 break;
1781                         default:
1782                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1783                         }
1784                         term.esc = 0;
1785                 } else {
1786                         switch(ascii) {
1787                         case '[':
1788                                 term.esc |= ESC_CSI;
1789                                 break;
1790                         case 'P': /* DCS -- Device Control String */
1791                         case '_': /* APC -- Application Program Command */
1792                         case '^': /* PM -- Privacy Message */
1793                         case ']': /* OSC -- Operating System Command */
1794                         case 'k': /* old title set compatibility */
1795                                 strreset();
1796                                 strescseq.type = ascii;
1797                                 term.esc |= ESC_STR;
1798                                 break;
1799                         case '(': /* set primary charset G0 */
1800                                 term.esc |= ESC_ALTCHARSET;
1801                                 break;
1802                         case ')': /* set secondary charset G1 (IGNORED) */
1803                         case '*': /* set tertiary charset G2 (IGNORED) */
1804                         case '+': /* set quaternary charset G3 (IGNORED) */
1805                                 term.esc = 0;
1806                                 break;
1807                         case 'D': /* IND -- Linefeed */
1808                                 if(term.c.y == term.bot)
1809                                         tscrollup(term.top, 1);
1810                                 else
1811                                         tmoveto(term.c.x, term.c.y+1);
1812                                 term.esc = 0;
1813                                 break;
1814                         case 'E': /* NEL -- Next line */
1815                                 tnewline(1); /* always go to first col */
1816                                 term.esc = 0;
1817                                 break;
1818                         case 'H': /* HTS -- Horizontal tab stop */
1819                                 term.tabs[term.c.x] = 1;
1820                                 term.esc = 0;
1821                                 break;
1822                         case 'M': /* RI -- Reverse index */
1823                                 if(term.c.y == term.top)
1824                                         tscrolldown(term.top, 1);
1825                                 else
1826                                         tmoveto(term.c.x, term.c.y-1);
1827                                 term.esc = 0;
1828                                 break;
1829                         case 'c': /* RIS -- Reset to inital state */
1830                                 treset();
1831                                 term.esc = 0;
1832                                 xclearborders();
1833                                 xresettitle();
1834                                 break;
1835                         case '=': /* DECPAM -- Application keypad */
1836                                 term.mode |= MODE_APPKEYPAD;
1837                                 term.esc = 0;
1838                                 break;
1839                         case '>': /* DECPNM -- Normal keypad */
1840                                 term.mode &= ~MODE_APPKEYPAD;
1841                                 term.esc = 0;
1842                                 break;
1843                         case '7': /* DECSC -- Save Cursor */
1844                                 tcursor(CURSOR_SAVE);
1845                                 term.esc = 0;
1846                                 break;
1847                         case '8': /* DECRC -- Restore Cursor */
1848                                 tcursor(CURSOR_LOAD);
1849                                 term.esc = 0;
1850                                 break;
1851                         case '\\': /* ST -- Stop */
1852                                 term.esc = 0;
1853                                 break;
1854                         default:
1855                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1856                                     (uchar) ascii, isprint(ascii)?ascii:'.');
1857                                 term.esc = 0;
1858                         }
1859                 }
1860         } else {
1861                 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1862                         sel.bx = -1;
1863                 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1864                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1865                                 tnewline(1); /* always go to first col */
1866                         tsetchar(c);
1867                         if(term.c.x+1 < term.col)
1868                                 tmoveto(term.c.x+1, term.c.y);
1869                         else
1870                                 term.c.state |= CURSOR_WRAPNEXT;
1871                 }
1872         }
1873 }
1874
1875 int
1876 tresize(int col, int row) {
1877         int i, x;
1878         int minrow = MIN(row, term.row);
1879         int mincol = MIN(col, term.col);
1880         int slide = term.c.y - row + 1;
1881
1882         if(col < 1 || row < 1)
1883                 return 0;
1884
1885         /* free unneeded rows */
1886         i = 0;
1887         if(slide > 0) {
1888                 /* slide screen to keep cursor where we expect it -
1889                  * tscrollup would work here, but we can optimize to
1890                  * memmove because we're freeing the earlier lines */
1891                 for(/* i = 0 */; i < slide; i++) {
1892                         free(term.line[i]);
1893                         free(term.alt[i]);
1894                 }
1895                 memmove(term.line, term.line + slide, row * sizeof(Line));
1896                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1897         }
1898         for(i += row; i < term.row; i++) {
1899                 free(term.line[i]);
1900                 free(term.alt[i]);
1901         }
1902
1903         /* resize to new height */
1904         term.line = xrealloc(term.line, row * sizeof(Line));
1905         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
1906         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1907         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1908
1909         /* resize each row to new width, zero-pad if needed */
1910         for(i = 0; i < minrow; i++) {
1911                 term.dirty[i] = 1;
1912                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1913                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
1914                 for(x = mincol; x < col; x++) {
1915                         term.line[i][x].state = 0;
1916                         term.alt[i][x].state = 0;
1917                 }
1918         }
1919
1920         /* allocate any new rows */
1921         for(/* i == minrow */; i < row; i++) {
1922                 term.dirty[i] = 1;
1923                 term.line[i] = xcalloc(col, sizeof(Glyph));
1924                 term.alt [i] = xcalloc(col, sizeof(Glyph));
1925         }
1926         if(col > term.col) {
1927                 bool *bp = term.tabs + term.col;
1928
1929                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1930                 while(--bp > term.tabs && !*bp)
1931                         /* nothing */ ;
1932                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1933                         *bp = 1;
1934         }
1935         /* update terminal size */
1936         term.col = col, term.row = row;
1937         /* make use of the LIMIT in tmoveto */
1938         tmoveto(term.c.x, term.c.y);
1939         /* reset scrolling region */
1940         tsetscroll(0, row-1);
1941
1942         return (slide > 0);
1943 }
1944
1945 void
1946 xresize(int col, int row) {
1947         xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1948         xw.th = MAX(1, 2*BORDER + row * xw.ch);
1949
1950         XftDrawChange(xw.xft_draw, xw.buf);
1951 }
1952
1953 void
1954 xloadcols(void) {
1955         int i, r, g, b;
1956         XRenderColor xft_color = { .alpha = 0 };
1957
1958         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1959         for(i = 0; i < LEN(colorname); i++) {
1960                 if(!colorname[i])
1961                         continue;
1962                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1963                         die("Could not allocate color '%s'\n", colorname[i]);
1964                 }
1965         }
1966
1967         /* load colors [16-255] ; same colors as xterm */
1968         for(i = 16, r = 0; r < 6; r++)
1969                 for(g = 0; g < 6; g++)
1970                         for(b = 0; b < 6; b++) {
1971                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1972                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1973                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1974                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1975                                         die("Could not allocate color %d\n", i);
1976                                 }
1977                                 i++;
1978                         }
1979
1980         for(r = 0; r < 24; r++, i++) {
1981                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1982                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1983                         dc.xft_col[i] = dc.xft_col[256];
1984                         fprintf(stderr, "Could not allocate color %d\n", i);
1985                 }
1986         }
1987 }
1988
1989 void
1990 xtermclear(int col1, int row1, int col2, int row2) {
1991         XftDrawRect(xw.xft_draw,
1992                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
1993                         BORDER + col1 * xw.cw,
1994                         BORDER + row1 * xw.ch,
1995                         (col2-col1+1) * xw.cw,
1996                         (row2-row1+1) * xw.ch);
1997 }
1998
1999 /*
2000  * Absolute coordinates.
2001  */
2002 void
2003 xclear(int x1, int y1, int x2, int y2) {
2004         XftDrawRect(xw.xft_draw,
2005                         &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2006                         x1, y1, x2-x1, y2-y1);
2007 }
2008
2009 void
2010 xclearborders(void) {
2011         /* top and left border */
2012         xclear(0, 0, BORDER, xw.h);
2013         xclear(0, 0, xw.w, BORDER);
2014
2015         /* lower and right border */
2016         xclear(BORDER, xw.th - 1, xw.w, xw.h);
2017         /* Will just draw what hasn't been drawn by the previous call. */
2018         xclear(xw.tw - 1, BORDER, xw.w, xw.h - xw.th - 2);
2019 }
2020
2021 void
2022 xhints(void) {
2023         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2024         XWMHints wm = {.flags = InputHint, .input = 1};
2025         XSizeHints *sizeh = NULL;
2026
2027         sizeh = XAllocSizeHints();
2028         if(xw.isfixed == False) {
2029                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2030                 sizeh->height = xw.h;
2031                 sizeh->width = xw.w;
2032                 sizeh->height_inc = xw.ch;
2033                 sizeh->width_inc = xw.cw;
2034                 sizeh->base_height = 2*BORDER;
2035                 sizeh->base_width = 2*BORDER;
2036         } else {
2037                 sizeh->flags = PMaxSize | PMinSize;
2038                 sizeh->min_width = sizeh->max_width = xw.fw;
2039                 sizeh->min_height = sizeh->max_height = xw.fh;
2040         }
2041
2042         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2043         XFree(sizeh);
2044 }
2045
2046 void
2047 xinitfont(Font *f, char *fontstr) {
2048         f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
2049
2050         if(!f->xft_set)
2051                 die("st: can't open font %s.\n", fontstr);
2052
2053         f->ascent = f->xft_set->ascent;
2054         f->descent = f->xft_set->descent;
2055         f->lbearing = 0;
2056         f->rbearing = f->xft_set->max_advance_width;
2057 }
2058
2059 void
2060 initfonts(char *fontstr) {
2061         char *fstr;
2062
2063         xinitfont(&dc.font, fontstr);
2064
2065         fstr = smstrcat(fontstr, ":weight=bold", NULL);
2066         xinitfont(&dc.bfont, fstr);
2067         free(fstr);
2068
2069         fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2070         xinitfont(&dc.ifont, fstr);
2071         free(fstr);
2072
2073         fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2074         xinitfont(&dc.ibfont, fstr);
2075         free(fstr);
2076 }
2077
2078 void
2079 xinit(void) {
2080         XSetWindowAttributes attrs;
2081         Cursor cursor;
2082         Window parent;
2083         int sw, sh, major, minor;
2084
2085         if(!(xw.dpy = XOpenDisplay(NULL)))
2086                 die("Can't open display\n");
2087         xw.scr = XDefaultScreen(xw.dpy);
2088         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2089
2090         /* font */
2091         initfonts((opt_font != NULL)? opt_font : FONT);
2092
2093         /* XXX: Assuming same size for bold font */
2094         xw.cw = dc.font.rbearing - dc.font.lbearing;
2095         xw.ch = dc.font.ascent + dc.font.descent;
2096
2097         /* colors */
2098         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2099         xloadcols();
2100
2101         /* adjust fixed window geometry */
2102         if(xw.isfixed) {
2103                 sw = DisplayWidth(xw.dpy, xw.scr);
2104                 sh = DisplayHeight(xw.dpy, xw.scr);
2105                 if(xw.fx < 0)
2106                         xw.fx = sw + xw.fx - xw.fw - 1;
2107                 if(xw.fy < 0)
2108                         xw.fy = sh + xw.fy - xw.fh - 1;
2109
2110                 xw.h = xw.fh;
2111                 xw.w = xw.fw;
2112         } else {
2113                 /* window - default size */
2114                 xw.h = 2*BORDER + term.row * xw.ch;
2115                 xw.w = 2*BORDER + term.col * xw.cw;
2116                 xw.fx = 0;
2117                 xw.fy = 0;
2118         }
2119
2120         attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2121         attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2122         attrs.bit_gravity = NorthWestGravity;
2123         attrs.event_mask = FocusChangeMask | KeyPressMask
2124                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2125                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2126         attrs.colormap = xw.cmap;
2127
2128         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2129         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2130                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2131                         xw.vis,
2132                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2133                         | CWColormap,
2134                         &attrs);
2135
2136         /* double buffering */
2137         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2138                 die("Xdbe extension is not present\n");
2139         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2140
2141         /* Xft rendering context */
2142         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2143
2144         /* input methods */
2145         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2146         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2147                                            | XIMStatusNothing, XNClientWindow, xw.win,
2148                                            XNFocusWindow, xw.win, NULL);
2149         /* gc */
2150         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2151
2152         /* white cursor, black outline */
2153         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2154         XDefineCursor(xw.dpy, xw.win, cursor);
2155         XRecolorCursor(xw.dpy, cursor,
2156                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2157                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2158
2159         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2160
2161         xresettitle();
2162         XMapWindow(xw.dpy, xw.win);
2163         xhints();
2164         XSync(xw.dpy, 0);
2165 }
2166
2167 void
2168 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2169         int fg = base.fg, bg = base.bg, temp;
2170         int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2171         Font *font = &dc.font;
2172         XGlyphInfo extents;
2173
2174         /* only switch default fg/bg if term is in RV mode */
2175         if(IS_SET(MODE_REVERSE)) {
2176                 if(fg == DefaultFG)
2177                         fg = DefaultBG;
2178                 if(bg == DefaultBG)
2179                         bg = DefaultFG;
2180         }
2181
2182         if(base.mode & ATTR_REVERSE)
2183                 temp = fg, fg = bg, bg = temp;
2184
2185         if(base.mode & ATTR_BOLD)
2186                 font = &dc.bfont;
2187
2188         if(base.mode & ATTR_ITALIC)
2189                 font = &dc.ifont;
2190         if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2191                 font = &dc.ibfont;
2192
2193         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
2194         width = extents.xOff;
2195         XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
2196         XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
2197
2198         if(base.mode & ATTR_UNDERLINE) {
2199                 XftDrawRect(xw.xft_draw, &dc.xft_col[fg], winx, winy+1,
2200                                 width, 1);
2201         }
2202 }
2203
2204 void
2205 xdrawcursor(void) {
2206         static int oldx = 0;
2207         static int oldy = 0;
2208         int sl;
2209         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2210
2211         LIMIT(oldx, 0, term.col-1);
2212         LIMIT(oldy, 0, term.row-1);
2213
2214         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2215                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2216
2217         /* remove the old cursor */
2218         if(term.line[oldy][oldx].state & GLYPH_SET) {
2219                 sl = utf8size(term.line[oldy][oldx].c);
2220                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2221         } else
2222                 xtermclear(oldx, oldy, oldx, oldy);
2223
2224         /* draw the new one */
2225         if(!(term.c.state & CURSOR_HIDE)) {
2226                 if(!(xw.state & WIN_FOCUSED))
2227                         g.bg = DefaultUCS;
2228
2229                 if(IS_SET(MODE_REVERSE))
2230                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2231
2232                 sl = utf8size(g.c);
2233                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2234                 oldx = term.c.x, oldy = term.c.y;
2235         }
2236 }
2237
2238 void
2239 xresettitle(void) {
2240         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2241 }
2242
2243 void
2244 redraw(void) {
2245         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2246
2247         xclearborders();
2248         tfulldirt();
2249         draw();
2250         XSync(xw.dpy, False); /* necessary for a good tput flash */
2251         nanosleep(&tv, NULL);
2252 }
2253
2254 void
2255 draw(void) {
2256         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2257
2258         drawregion(0, 0, term.col, term.row);
2259         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2260 }
2261
2262 void
2263 drawregion(int x1, int y1, int x2, int y2) {
2264         int ic, ib, x, y, ox, sl;
2265         Glyph base, new;
2266         char buf[DRAW_BUF_SIZ];
2267         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2268
2269         if((sel.alt && !alt) || (!sel.alt && alt))
2270                 ena_sel = 0;
2271         if(!(xw.state & WIN_VISIBLE))
2272                 return;
2273
2274         for(y = y1; y < y2; y++) {
2275                 if(!term.dirty[y])
2276                         continue;
2277                 xtermclear(0, y, term.col, y);
2278                 term.dirty[y] = 0;
2279                 base = term.line[y][0];
2280                 ic = ib = ox = 0;
2281                 for(x = x1; x < x2; x++) {
2282                         new = term.line[y][x];
2283                         if(ena_sel && *(new.c) && selected(x, y))
2284                                 new.mode ^= ATTR_REVERSE;
2285                         if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2286                                                   ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2287                                 xdraws(buf, base, ox, y, ic, ib);
2288                                 ic = ib = 0;
2289                         }
2290                         if(new.state & GLYPH_SET) {
2291                                 if(ib == 0) {
2292                                         ox = x;
2293                                         base = new;
2294                                 }
2295                                 sl = utf8size(new.c);
2296                                 memcpy(buf+ib, new.c, sl);
2297                                 ib += sl;
2298                                 ++ic;
2299                         }
2300                 }
2301                 if(ib > 0)
2302                         xdraws(buf, base, ox, y, ic, ib);
2303         }
2304         xdrawcursor();
2305 }
2306
2307 void
2308 expose(XEvent *ev) {
2309         XExposeEvent *e = &ev->xexpose;
2310         if(xw.state & WIN_REDRAW) {
2311                 if(!e->count)
2312                         xw.state &= ~WIN_REDRAW;
2313         }
2314 }
2315
2316 void
2317 visibility(XEvent *ev) {
2318         XVisibilityEvent *e = &ev->xvisibility;
2319         if(e->state == VisibilityFullyObscured)
2320                 xw.state &= ~WIN_VISIBLE;
2321         else if(!(xw.state & WIN_VISIBLE))
2322                 /* need a full redraw for next Expose, not just a buf copy */
2323                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2324 }
2325
2326 void
2327 unmap(XEvent *ev) {
2328         xw.state &= ~WIN_VISIBLE;
2329 }
2330
2331 void
2332 xseturgency(int add) {
2333         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2334         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2335         XSetWMHints(xw.dpy, xw.win, h);
2336         XFree(h);
2337 }
2338
2339 void
2340 focus(XEvent *ev) {
2341         if(ev->type == FocusIn) {
2342                 xw.state |= WIN_FOCUSED;
2343                 xseturgency(0);
2344         } else
2345                 xw.state &= ~WIN_FOCUSED;
2346 }
2347
2348 char*
2349 kmap(KeySym k, uint state) {
2350         int i;
2351         state &= ~Mod2Mask;
2352         for(i = 0; i < LEN(key); i++) {
2353                 uint mask = key[i].mask;
2354                 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2355                         return (char*)key[i].s;
2356         }
2357         return NULL;
2358 }
2359
2360 void
2361 kpress(XEvent *ev) {
2362         XKeyEvent *e = &ev->xkey;
2363         KeySym ksym;
2364         char buf[32];
2365         char *customkey;
2366         int len;
2367         int meta;
2368         int shift;
2369         Status status;
2370
2371         if (IS_SET(MODE_KBDLOCK))
2372                 return;
2373         meta = e->state & Mod1Mask;
2374         shift = e->state & ShiftMask;
2375         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2376
2377         /* 1. custom keys from config.h */
2378         if((customkey = kmap(ksym, e->state)))
2379                 ttywrite(customkey, strlen(customkey));
2380         /* 2. hardcoded (overrides X lookup) */
2381         else
2382                 switch(ksym) {
2383                 case XK_Up:
2384                 case XK_Down:
2385                 case XK_Left:
2386                 case XK_Right:
2387                         /* XXX: shift up/down doesn't work */
2388                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2389                         ttywrite(buf, 3);
2390                         break;
2391                 case XK_Insert:
2392                         if(shift)
2393                                 selpaste();
2394                         break;
2395                 case XK_Return:
2396                         if(IS_SET(MODE_CRLF))
2397                                 ttywrite("\r\n", 2);
2398                         else
2399                                 ttywrite("\r", 1);
2400                         break;
2401                         /* 3. X lookup  */
2402                 default:
2403                         if(len > 0) {
2404                                 if(meta && len == 1)
2405                                         ttywrite("\033", 1);
2406                                 ttywrite(buf, len);
2407                         }
2408                         break;
2409                 }
2410 }
2411
2412 void
2413 cmessage(XEvent *e) {
2414         /* See xembed specs
2415            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2416         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2417                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2418                         xw.state |= WIN_FOCUSED;
2419                         xseturgency(0);
2420                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2421                         xw.state &= ~WIN_FOCUSED;
2422                 }
2423         }
2424 }
2425
2426 void
2427 resize(XEvent *e) {
2428         int col, row;
2429
2430         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2431                 return;
2432
2433         xw.w = e->xconfigure.width;
2434         xw.h = e->xconfigure.height;
2435         col = (xw.w - 2*BORDER) / xw.cw;
2436         row = (xw.h - 2*BORDER) / xw.ch;
2437         if(col == term.col && row == term.row)
2438                 return;
2439
2440         tresize(col, row);
2441         xresize(col, row);
2442         xclearborders();
2443         ttyresize();
2444 }
2445
2446 void
2447 run(void) {
2448         XEvent ev;
2449         fd_set rfd;
2450         int xfd = XConnectionNumber(xw.dpy), i;
2451         struct timeval drawtimeout, *tv = NULL;
2452
2453         for(i = 0;; i++) {
2454                 FD_ZERO(&rfd);
2455                 FD_SET(cmdfd, &rfd);
2456                 FD_SET(xfd, &rfd);
2457                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2458                         if(errno == EINTR)
2459                                 continue;
2460                         die("select failed: %s\n", SERRNO);
2461                 }
2462
2463                 /*
2464                  * Stop after a certain number of reads so the user does not
2465                  * feel like the system is stuttering.
2466                  */
2467                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2468                         ttyread();
2469
2470                         /*
2471                          * Just wait a bit so it isn't disturbing the
2472                          * user and the system is able to write something.
2473                          */
2474                         drawtimeout.tv_sec = 0;
2475                         drawtimeout.tv_usec = 5;
2476                         tv = &drawtimeout;
2477                         continue;
2478                 }
2479                 i = 0;
2480                 tv = NULL;
2481
2482                 while(XPending(xw.dpy)) {
2483                         XNextEvent(xw.dpy, &ev);
2484                         if(XFilterEvent(&ev, xw.win))
2485                                 continue;
2486                         if(handler[ev.type])
2487                                 (handler[ev.type])(&ev);
2488                 }
2489
2490                 draw();
2491                 XFlush(xw.dpy);
2492         }
2493 }
2494
2495 int
2496 main(int argc, char *argv[]) {
2497         int i, bitm, xr, yr;
2498         uint wr, hr;
2499
2500         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2501         xw.isfixed = False;
2502
2503         for(i = 1; i < argc; i++) {
2504                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2505                 case 'c':
2506                         if(++i < argc)
2507                                 opt_class = argv[i];
2508                         break;
2509                 case 'e':
2510                         /* eat every remaining arguments */
2511                         if(++i < argc)
2512                                 opt_cmd = &argv[i];
2513                         goto run;
2514                 case 'f':
2515                         if(++i < argc)
2516                                 opt_font = argv[i];
2517                         break;
2518                 case 'g':
2519                         if(++i >= argc)
2520                                 break;
2521
2522                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2523                         if(bitm & XValue)
2524                                 xw.fx = xr;
2525                         if(bitm & YValue)
2526                                 xw.fy = yr;
2527                         if(bitm & WidthValue)
2528                                 xw.fw = (int)wr;
2529                         if(bitm & HeightValue)
2530                                 xw.fh = (int)hr;
2531                         if(bitm & XNegative && xw.fx == 0)
2532                                 xw.fx = -1;
2533                         if(bitm & XNegative && xw.fy == 0)
2534                                 xw.fy = -1;
2535
2536                         if(xw.fh != 0 && xw.fw != 0)
2537                                 xw.isfixed = True;
2538                         break;
2539                 case 'o':
2540                         if(++i < argc)
2541                                 opt_io = argv[i];
2542                         break;
2543                 case 't':
2544                         if(++i < argc)
2545                                 opt_title = argv[i];
2546                         break;
2547                 case 'v':
2548                 default:
2549                         die(USAGE);
2550                 case 'w':
2551                         if(++i < argc)
2552                                 opt_embed = argv[i];
2553                         break;
2554                 }
2555         }
2556
2557  run:
2558         setlocale(LC_CTYPE, "");
2559         tnew(80, 24);
2560         ttynew();
2561         xinit();
2562         selinit();
2563         run();
2564         return 0;
2565 }
2566