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