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