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