JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Implementing line drawing right.
[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*, int);
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, charsize);
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
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         /*
1098          * The table is proudly stolen from rxvt.
1099          */
1100         if(term.c.attr.mode & ATTR_GFX) {
1101                 char *vt100_0[62] = { /* 0x41 - 0x7e */
1102                         "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1103                         0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1104                         0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1105                         0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1106                         "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1107                         "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1108                         "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1109                         "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1110                 };
1111
1112                 if(c[0] >= 0x41 && c[0] <= 0x7e
1113                                 && vt100_0[c[0] - 0x41]) {
1114                         c = vt100_0[c[0] - 0x41];
1115                 }
1116         }
1117
1118         term.dirty[term.c.y] = 1;
1119         term.line[term.c.y][term.c.x] = term.c.attr;
1120         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1121         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1122 }
1123
1124 void
1125 tclearregion(int x1, int y1, int x2, int y2) {
1126         int x, y, temp;
1127
1128         if(x1 > x2)
1129                 temp = x1, x1 = x2, x2 = temp;
1130         if(y1 > y2)
1131                 temp = y1, y1 = y2, y2 = temp;
1132
1133         LIMIT(x1, 0, term.col-1);
1134         LIMIT(x2, 0, term.col-1);
1135         LIMIT(y1, 0, term.row-1);
1136         LIMIT(y2, 0, term.row-1);
1137
1138         for(y = y1; y <= y2; y++) {
1139                 term.dirty[y] = 1;
1140                 for(x = x1; x <= x2; x++)
1141                         term.line[y][x].state = 0;
1142         }
1143 }
1144
1145 void
1146 tdeletechar(int n) {
1147         int src = term.c.x + n;
1148         int dst = term.c.x;
1149         int size = term.col - src;
1150
1151         term.dirty[term.c.y] = 1;
1152
1153         if(src >= term.col) {
1154                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1155                 return;
1156         }
1157         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1158         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1159 }
1160
1161 void
1162 tinsertblank(int n) {
1163         int src = term.c.x;
1164         int dst = src + n;
1165         int size = term.col - dst;
1166
1167         term.dirty[term.c.y] = 1;
1168
1169         if(dst >= term.col) {
1170                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1171                 return;
1172         }
1173         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1174         tclearregion(src, term.c.y, dst - 1, term.c.y);
1175 }
1176
1177 void
1178 tinsertblankline(int n) {
1179         if(term.c.y < term.top || term.c.y > term.bot)
1180                 return;
1181
1182         tscrolldown(term.c.y, n);
1183 }
1184
1185 void
1186 tdeleteline(int n) {
1187         if(term.c.y < term.top || term.c.y > term.bot)
1188                 return;
1189
1190         tscrollup(term.c.y, n);
1191 }
1192
1193 void
1194 tsetattr(int *attr, int l) {
1195         int i;
1196
1197         for(i = 0; i < l; i++) {
1198                 switch(attr[i]) {
1199                 case 0:
1200                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1201                                         | ATTR_ITALIC | ATTR_BLINK);
1202                         term.c.attr.fg = DefaultFG;
1203                         term.c.attr.bg = DefaultBG;
1204                         break;
1205                 case 1:
1206                         term.c.attr.mode |= ATTR_BOLD;
1207                         break;
1208                 case 3: /* enter standout (highlight) */
1209                         term.c.attr.mode |= ATTR_ITALIC;
1210                         break;
1211                 case 4:
1212                         term.c.attr.mode |= ATTR_UNDERLINE;
1213                         break;
1214                 case 5:
1215                         term.c.attr.mode |= ATTR_BLINK;
1216                         break;
1217                 case 7:
1218                         term.c.attr.mode |= ATTR_REVERSE;
1219                         break;
1220                 case 21:
1221                 case 22:
1222                         term.c.attr.mode &= ~ATTR_BOLD;
1223                         break;
1224                 case 23: /* leave standout (highlight) mode */
1225                         term.c.attr.mode &= ~ATTR_ITALIC;
1226                         break;
1227                 case 24:
1228                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1229                         break;
1230                 case 25:
1231                         term.c.attr.mode &= ~ATTR_BLINK;
1232                         break;
1233                 case 27:
1234                         term.c.attr.mode &= ~ATTR_REVERSE;
1235                         break;
1236                 case 38:
1237                         if(i + 2 < l && attr[i + 1] == 5) {
1238                                 i += 2;
1239                                 if(BETWEEN(attr[i], 0, 255))
1240                                         term.c.attr.fg = attr[i];
1241                                 else
1242                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1243                         }
1244                         else
1245                                 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1246                         break;
1247                 case 39:
1248                         term.c.attr.fg = DefaultFG;
1249                         break;
1250                 case 48:
1251                         if(i + 2 < l && attr[i + 1] == 5) {
1252                                 i += 2;
1253                                 if(BETWEEN(attr[i], 0, 255))
1254                                         term.c.attr.bg = attr[i];
1255                                 else
1256                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1257                         }
1258                         else
1259                                 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1260                         break;
1261                 case 49:
1262                         term.c.attr.bg = DefaultBG;
1263                         break;
1264                 default:
1265                         if(BETWEEN(attr[i], 30, 37))
1266                                 term.c.attr.fg = attr[i] - 30;
1267                         else if(BETWEEN(attr[i], 40, 47))
1268                                 term.c.attr.bg = attr[i] - 40;
1269                         else if(BETWEEN(attr[i], 90, 97))
1270                                 term.c.attr.fg = attr[i] - 90 + 8;
1271                         else if(BETWEEN(attr[i], 100, 107))
1272                                 term.c.attr.bg = attr[i] - 100 + 8;
1273                         else
1274                                 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1275                         break;
1276                 }
1277         }
1278 }
1279
1280 void
1281 tsetscroll(int t, int b) {
1282         int temp;
1283
1284         LIMIT(t, 0, term.row-1);
1285         LIMIT(b, 0, term.row-1);
1286         if(t > b) {
1287                 temp = t;
1288                 t = b;
1289                 b = temp;
1290         }
1291         term.top = t;
1292         term.bot = b;
1293 }
1294
1295 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1296
1297 void
1298 tsetmode(bool priv, bool set, int *args, int narg) {
1299         int *lim, mode;
1300
1301         for(lim = args + narg; args < lim; ++args) {
1302                 if(priv) {
1303                         switch(*args) {
1304                                 break;
1305                         case 1: /* DECCKM -- Cursor key */
1306                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1307                                 break;
1308                         case 5: /* DECSCNM -- Reverve video */
1309                                 mode = term.mode;
1310                                 MODBIT(term.mode,set, MODE_REVERSE);
1311                                 if(mode != term.mode)
1312                                         redraw();
1313                                 break;
1314                         case 6: /* XXX: DECOM -- Origin */
1315                                 break;
1316                         case 7: /* DECAWM -- Auto wrap */
1317                                 MODBIT(term.mode, set, MODE_WRAP);
1318                                 break;
1319                         case 8: /* XXX: DECARM -- Auto repeat */
1320                                 break;
1321                         case 0:  /* Error (IGNORED) */
1322                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1323                                 break;
1324                         case 25:
1325                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1326                                 break;
1327                         case 1000: /* 1000,1002: enable xterm mouse report */
1328                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1329                                 break;
1330                         case 1002:
1331                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1332                                 break;
1333                         case 1049: /* = 1047 and 1048 */
1334                         case 47:
1335                         case 1047:
1336                                 if(IS_SET(MODE_ALTSCREEN))
1337                                         tclearregion(0, 0, term.col-1, term.row-1);
1338                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1339                                     (!set && IS_SET(MODE_ALTSCREEN))) {
1340                                             tswapscreen();
1341                                 }
1342                                 if(*args != 1049)
1343                                         break;
1344                                 /* pass through */
1345                         case 1048:
1346                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1347                                 break;
1348                         default:
1349                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1350                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1351                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1352                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1353                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1354                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1355                                 fprintf(stderr,
1356                                         "erresc: unknown private set/reset mode %d\n",
1357                                         *args);
1358                                 break;
1359                         }
1360                 } else {
1361                         switch(*args) {
1362                         case 0:  /* Error (IGNORED) */
1363                                 break;
1364                         case 2:  /* KAM -- keyboard action */
1365                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1366                                 break;
1367                         case 4:  /* IRM -- Insertion-replacement */
1368                                 MODBIT(term.mode, set, MODE_INSERT);
1369                                 break;
1370                         case 12: /* XXX: SRM -- Send/Receive */
1371                                 break;
1372                         case 20: /* LNM -- Linefeed/new line */
1373                                 MODBIT(term.mode, set, MODE_CRLF);
1374                                 break;
1375                         default:
1376                                 fprintf(stderr,
1377                                         "erresc: unknown set/reset mode %d\n",
1378                                         *args);
1379                                 break;
1380                         }
1381                 }
1382         }
1383 }
1384 #undef MODBIT
1385
1386
1387 void
1388 csihandle(void) {
1389         switch(csiescseq.mode) {
1390         default:
1391         unknown:
1392                 fprintf(stderr, "erresc: unknown csi ");
1393                 csidump();
1394                 /* die(""); */
1395                 break;
1396         case '@': /* ICH -- Insert <n> blank char */
1397                 DEFAULT(csiescseq.arg[0], 1);
1398                 tinsertblank(csiescseq.arg[0]);
1399                 break;
1400         case 'A': /* CUU -- Cursor <n> Up */
1401         case 'e':
1402                 DEFAULT(csiescseq.arg[0], 1);
1403                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1404                 break;
1405         case 'B': /* CUD -- Cursor <n> Down */
1406                 DEFAULT(csiescseq.arg[0], 1);
1407                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1408                 break;
1409         case 'C': /* CUF -- Cursor <n> Forward */
1410         case 'a':
1411                 DEFAULT(csiescseq.arg[0], 1);
1412                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1413                 break;
1414         case 'D': /* CUB -- Cursor <n> Backward */
1415                 DEFAULT(csiescseq.arg[0], 1);
1416                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1417                 break;
1418         case 'E': /* CNL -- Cursor <n> Down and first col */
1419                 DEFAULT(csiescseq.arg[0], 1);
1420                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1421                 break;
1422         case 'F': /* CPL -- Cursor <n> Up and first col */
1423                 DEFAULT(csiescseq.arg[0], 1);
1424                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1425                 break;
1426         case 'g': /* TBC -- Tabulation clear */
1427                 switch (csiescseq.arg[0]) {
1428                 case 0: /* clear current tab stop */
1429                         term.tabs[term.c.x] = 0;
1430                         break;
1431                 case 3: /* clear all the tabs */
1432                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1433                         break;
1434                 default:
1435                         goto unknown;
1436                 }
1437                 break;
1438         case 'G': /* CHA -- Move to <col> */
1439         case '`': /* HPA */
1440                 DEFAULT(csiescseq.arg[0], 1);
1441                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1442                 break;
1443         case 'H': /* CUP -- Move to <row> <col> */
1444         case 'f': /* HVP */
1445                 DEFAULT(csiescseq.arg[0], 1);
1446                 DEFAULT(csiescseq.arg[1], 1);
1447                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1448                 break;
1449         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1450                 DEFAULT(csiescseq.arg[0], 1);
1451                 while(csiescseq.arg[0]--)
1452                         tputtab(1);
1453                 break;
1454         case 'J': /* ED -- Clear screen */
1455                 sel.bx = -1;
1456                 switch(csiescseq.arg[0]) {
1457                 case 0: /* below */
1458                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1459                         if(term.c.y < term.row-1)
1460                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1461                         break;
1462                 case 1: /* above */
1463                         if(term.c.y > 1)
1464                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1465                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1466                         break;
1467                 case 2: /* all */
1468                         tclearregion(0, 0, term.col-1, term.row-1);
1469                         break;
1470                 default:
1471                         goto unknown;
1472                 }
1473                 break;
1474         case 'K': /* EL -- Clear line */
1475                 switch(csiescseq.arg[0]) {
1476                 case 0: /* right */
1477                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1478                         break;
1479                 case 1: /* left */
1480                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1481                         break;
1482                 case 2: /* all */
1483                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1484                         break;
1485                 }
1486                 break;
1487         case 'S': /* SU -- Scroll <n> line up */
1488                 DEFAULT(csiescseq.arg[0], 1);
1489                 tscrollup(term.top, csiescseq.arg[0]);
1490                 break;
1491         case 'T': /* SD -- Scroll <n> line down */
1492                 DEFAULT(csiescseq.arg[0], 1);
1493                 tscrolldown(term.top, csiescseq.arg[0]);
1494                 break;
1495         case 'L': /* IL -- Insert <n> blank lines */
1496                 DEFAULT(csiescseq.arg[0], 1);
1497                 tinsertblankline(csiescseq.arg[0]);
1498                 break;
1499         case 'l': /* RM -- Reset Mode */
1500                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1501                 break;
1502         case 'M': /* DL -- Delete <n> lines */
1503                 DEFAULT(csiescseq.arg[0], 1);
1504                 tdeleteline(csiescseq.arg[0]);
1505                 break;
1506         case 'X': /* ECH -- Erase <n> char */
1507                 DEFAULT(csiescseq.arg[0], 1);
1508                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1509                 break;
1510         case 'P': /* DCH -- Delete <n> char */
1511                 DEFAULT(csiescseq.arg[0], 1);
1512                 tdeletechar(csiescseq.arg[0]);
1513                 break;
1514         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1515                 DEFAULT(csiescseq.arg[0], 1);
1516                 while(csiescseq.arg[0]--)
1517                         tputtab(0);
1518                 break;
1519         case 'd': /* VPA -- Move to <row> */
1520                 DEFAULT(csiescseq.arg[0], 1);
1521                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1522                 break;
1523         case 'h': /* SM -- Set terminal mode */
1524                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1525                 break;
1526         case 'm': /* SGR -- Terminal attribute (color) */
1527                 tsetattr(csiescseq.arg, csiescseq.narg);
1528                 break;
1529         case 'r': /* DECSTBM -- Set Scrolling Region */
1530                 if(csiescseq.priv)
1531                         goto unknown;
1532                 else {
1533                         DEFAULT(csiescseq.arg[0], 1);
1534                         DEFAULT(csiescseq.arg[1], term.row);
1535                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1536                         tmoveto(0, 0);
1537                 }
1538                 break;
1539         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1540                 tcursor(CURSOR_SAVE);
1541                 break;
1542         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1543                 tcursor(CURSOR_LOAD);
1544                 break;
1545         }
1546 }
1547
1548 void
1549 csidump(void) {
1550         int i;
1551         printf("ESC[");
1552         for(i = 0; i < csiescseq.len; i++) {
1553                 uint c = csiescseq.buf[i] & 0xff;
1554                 if(isprint(c)) putchar(c);
1555                 else if(c == '\n') printf("(\\n)");
1556                 else if(c == '\r') printf("(\\r)");
1557                 else if(c == 0x1b) printf("(\\e)");
1558                 else printf("(%02x)", c);
1559         }
1560         putchar('\n');
1561 }
1562
1563 void
1564 csireset(void) {
1565         memset(&csiescseq, 0, sizeof(csiescseq));
1566 }
1567
1568 void
1569 strhandle(void) {
1570         char *p;
1571
1572         /*
1573          * TODO: make this being useful in case of color palette change.
1574          */
1575         strparse();
1576
1577         p = strescseq.buf;
1578
1579         switch(strescseq.type) {
1580         case ']': /* OSC -- Operating System Command */
1581                 switch(p[0]) {
1582                 case '0':
1583                 case '1':
1584                 case '2':
1585                         /*
1586                          * TODO: Handle special chars in string, like umlauts.
1587                          */
1588                         if(p[1] == ';') {
1589                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1590                         }
1591                         break;
1592                 case ';':
1593                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1594                         break;
1595                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1596                         break;
1597                 default:
1598                         fprintf(stderr, "erresc: unknown str ");
1599                         strdump();
1600                         break;
1601                 }
1602                 break;
1603         case 'k': /* old title set compatibility */
1604                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1605                 break;
1606         case 'P': /* DSC -- Device Control String */
1607         case '_': /* APC -- Application Program Command */
1608         case '^': /* PM -- Privacy Message */
1609         default:
1610                 fprintf(stderr, "erresc: unknown str ");
1611                 strdump();
1612                 /* die(""); */
1613                 break;
1614         }
1615 }
1616
1617 void
1618 strparse(void) {
1619         /*
1620          * TODO: Implement parsing like for CSI when required.
1621          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1622          */
1623         return;
1624 }
1625
1626 void
1627 strdump(void) {
1628         int i;
1629         printf("ESC%c", strescseq.type);
1630         for(i = 0; i < strescseq.len; i++) {
1631                 uint c = strescseq.buf[i] & 0xff;
1632                 if(isprint(c)) putchar(c);
1633                 else if(c == '\n') printf("(\\n)");
1634                 else if(c == '\r') printf("(\\r)");
1635                 else if(c == 0x1b) printf("(\\e)");
1636                 else printf("(%02x)", c);
1637         }
1638         printf("ESC\\\n");
1639 }
1640
1641 void
1642 strreset(void) {
1643         memset(&strescseq, 0, sizeof(strescseq));
1644 }
1645
1646 void
1647 tputtab(bool forward) {
1648         uint x = term.c.x;
1649
1650         if(forward) {
1651                 if(x == term.col)
1652                         return;
1653                 for(++x; x < term.col && !term.tabs[x]; ++x)
1654                         /* nothing */ ;
1655         } else {
1656                 if(x == 0)
1657                         return;
1658                 for(--x; x > 0 && !term.tabs[x]; --x)
1659                         /* nothing */ ;
1660         }
1661         tmoveto(x, term.c.y);
1662 }
1663
1664 void
1665 tputc(char *c, int len) {
1666         char ascii = *c;
1667
1668         if(iofd != -1)
1669                 write(iofd, c, len);
1670
1671         if(term.esc & ESC_START) {
1672                 if(term.esc & ESC_CSI) {
1673                         csiescseq.buf[csiescseq.len++] = ascii;
1674                         if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1675                                 term.esc = 0;
1676                                 csiparse(), csihandle();
1677                         }
1678                 } else if(term.esc & ESC_STR) {
1679                         switch(ascii) {
1680                         case '\033':
1681                                 term.esc = ESC_START | ESC_STR_END;
1682                                 break;
1683                         case '\a': /* backwards compatibility to xterm */
1684                                 term.esc = 0;
1685                                 strhandle();
1686                                 break;
1687                         default:
1688                                 strescseq.buf[strescseq.len++] = ascii;
1689                                 if(strescseq.len+1 >= STR_BUF_SIZ) {
1690                                         term.esc = 0;
1691                                         strhandle();
1692                                 }
1693                         }
1694                 } else if(term.esc & ESC_STR_END) {
1695                         term.esc = 0;
1696                         if(ascii == '\\')
1697                                 strhandle();
1698                 } else if(term.esc & ESC_ALTCHARSET) {
1699                         switch(ascii) {
1700                         case '0': /* Line drawing set */
1701                                 term.c.attr.mode |= ATTR_GFX;
1702                                 break;
1703                         case 'B': /* USASCII */
1704                                 term.c.attr.mode &= ~ATTR_GFX;
1705                                 break;
1706                         case 'A': /* UK (IGNORED) */
1707                         case '<': /* multinational charset (IGNORED) */
1708                         case '5': /* Finnish (IGNORED) */
1709                         case 'C': /* Finnish (IGNORED) */
1710                         case 'K': /* German (IGNORED) */
1711                                 break;
1712                         default:
1713                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1714                         }
1715                         term.esc = 0;
1716                 } else {
1717                         switch(ascii) {
1718                         case '[':
1719                                 term.esc |= ESC_CSI;
1720                                 break;
1721                         case 'P': /* DCS -- Device Control String */
1722                         case '_': /* APC -- Application Program Command */
1723                         case '^': /* PM -- Privacy Message */
1724                         case ']': /* OSC -- Operating System Command */
1725                         case 'k': /* old title set compatibility */
1726                                 strreset();
1727                                 strescseq.type = ascii;
1728                                 term.esc |= ESC_STR;
1729                                 break;
1730                         case '(': /* set primary charset G0 */
1731                                 term.esc |= ESC_ALTCHARSET;
1732                                 break;
1733                         case ')': /* set secondary charset G1 (IGNORED) */
1734                         case '*': /* set tertiary charset G2 (IGNORED) */
1735                         case '+': /* set quaternary charset G3 (IGNORED) */
1736                                 term.esc = 0;
1737                                 break;
1738                         case 'D': /* IND -- Linefeed */
1739                                 if(term.c.y == term.bot)
1740                                         tscrollup(term.top, 1);
1741                                 else
1742                                         tmoveto(term.c.x, term.c.y+1);
1743                                 term.esc = 0;
1744                                 break;
1745                         case 'E': /* NEL -- Next line */
1746                                 tnewline(1); /* always go to first col */
1747                                 term.esc = 0;
1748                                 break;
1749                         case 'H': /* HTS -- Horizontal tab stop */
1750                                 term.tabs[term.c.x] = 1;
1751                                 term.esc = 0;
1752                                 break;
1753                         case 'M': /* RI -- Reverse index */
1754                                 if(term.c.y == term.top)
1755                                         tscrolldown(term.top, 1);
1756                                 else
1757                                         tmoveto(term.c.x, term.c.y-1);
1758                                 term.esc = 0;
1759                                 break;
1760                         case 'c': /* RIS -- Reset to inital state */
1761                                 treset();
1762                                 term.esc = 0;
1763                                 xclear(0, 0, xw.w, xw.h);
1764                                 xresettitle();
1765                                 break;
1766                         case '=': /* DECPAM -- Application keypad */
1767                                 term.mode |= MODE_APPKEYPAD;
1768                                 term.esc = 0;
1769                                 break;
1770                         case '>': /* DECPNM -- Normal keypad */
1771                                 term.mode &= ~MODE_APPKEYPAD;
1772                                 term.esc = 0;
1773                                 break;
1774                         case '7': /* DECSC -- Save Cursor */
1775                                 tcursor(CURSOR_SAVE);
1776                                 term.esc = 0;
1777                                 break;
1778                         case '8': /* DECRC -- Restore Cursor */
1779                                 tcursor(CURSOR_LOAD);
1780                                 term.esc = 0;
1781                                 break;
1782                         case '\\': /* ST -- Stop */
1783                                 term.esc = 0;
1784                                 break;
1785                         default:
1786                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1787                                     (uchar) ascii, isprint(ascii)?ascii:'.');
1788                                 term.esc = 0;
1789                         }
1790                 }
1791         } else {
1792                 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1793                         sel.bx = -1;
1794                 switch(ascii) {
1795                 case '\0': /* padding character, do nothing */
1796                         break;
1797                 case '\t':
1798                         tputtab(1);
1799                         break;
1800                 case '\b':
1801                         tmoveto(term.c.x-1, term.c.y);
1802                         break;
1803                 case '\r':
1804                         tmoveto(0, term.c.y);
1805                         break;
1806                 case '\f':
1807                 case '\v':
1808                 case '\n':
1809                         /* go to first col if the mode is set */
1810                         tnewline(IS_SET(MODE_CRLF));
1811                         break;
1812                 case '\a':
1813                         if(!(xw.state & WIN_FOCUSED))
1814                                 xseturgency(1);
1815                         break;
1816                 case '\033':
1817                         csireset();
1818                         term.esc = ESC_START;
1819                         break;
1820                 default:
1821                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1822                                 tnewline(1); /* always go to first col */
1823                         tsetchar(c);
1824                         if(term.c.x+1 < term.col)
1825                                 tmoveto(term.c.x+1, term.c.y);
1826                         else
1827                                 term.c.state |= CURSOR_WRAPNEXT;
1828                 }
1829         }
1830 }
1831
1832 int
1833 tresize(int col, int row) {
1834         int i, x;
1835         int minrow = MIN(row, term.row);
1836         int mincol = MIN(col, term.col);
1837         int slide = term.c.y - row + 1;
1838
1839         if(col < 1 || row < 1)
1840                 return 0;
1841
1842         /* free unneeded rows */
1843         i = 0;
1844         if(slide > 0) {
1845                 /* slide screen to keep cursor where we expect it -
1846                  * tscrollup would work here, but we can optimize to
1847                  * memmove because we're freeing the earlier lines */
1848                 for(/* i = 0 */; i < slide; i++) {
1849                         free(term.line[i]);
1850                         free(term.alt[i]);
1851                 }
1852                 memmove(term.line, term.line + slide, row * sizeof(Line));
1853                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1854         }
1855         for(i += row; i < term.row; i++) {
1856                 free(term.line[i]);
1857                 free(term.alt[i]);
1858         }
1859
1860         /* resize to new height */
1861         term.line = xrealloc(term.line, row * sizeof(Line));
1862         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
1863         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1864         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1865
1866         /* resize each row to new width, zero-pad if needed */
1867         for(i = 0; i < minrow; i++) {
1868                 term.dirty[i] = 1;
1869                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1870                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
1871                 for(x = mincol; x < col; x++) {
1872                         term.line[i][x].state = 0;
1873                         term.alt[i][x].state = 0;
1874                 }
1875         }
1876
1877         /* allocate any new rows */
1878         for(/* i == minrow */; i < row; i++) {
1879                 term.dirty[i] = 1;
1880                 term.line[i] = xcalloc(col, sizeof(Glyph));
1881                 term.alt [i] = xcalloc(col, sizeof(Glyph));
1882         }
1883         if(col > term.col) {
1884                 bool *bp = term.tabs + term.col;
1885
1886                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1887                 while(--bp > term.tabs && !*bp)
1888                         /* nothing */ ;
1889                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1890                         *bp = 1;
1891         }
1892         /* update terminal size */
1893         term.col = col, term.row = row;
1894         /* make use of the LIMIT in tmoveto */
1895         tmoveto(term.c.x, term.c.y);
1896         /* reset scrolling region */
1897         tsetscroll(0, row-1);
1898
1899         return (slide > 0);
1900 }
1901
1902 void
1903 xresize(int col, int row) {
1904         xw.tw = MAX(1, 2*BORDER + col * xw.cw);
1905         xw.th = MAX(1, 2*BORDER + row * xw.ch);
1906
1907         XftDrawChange(xw.xft_draw, xw.buf);
1908 }
1909
1910 void
1911 xloadcols(void) {
1912         int i, r, g, b;
1913         XRenderColor xft_color = { .alpha = 0 };
1914         ulong white = WhitePixel(xw.dpy, xw.scr);
1915
1916         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1917         for(i = 0; i < LEN(colorname); i++) {
1918                 if(!colorname[i])
1919                         continue;
1920                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
1921                         dc.col[i] = white;
1922                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1923                 } else
1924                         dc.col[i] = dc.xft_col[i].pixel;
1925         }
1926
1927         /* load colors [16-255] ; same colors as xterm */
1928         for(i = 16, r = 0; r < 6; r++)
1929                 for(g = 0; g < 6; g++)
1930                         for(b = 0; b < 6; b++) {
1931                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1932                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1933                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1934                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1935                                         dc.col[i] = white;
1936                                         fprintf(stderr, "Could not allocate color %d\n", i);
1937                                 } else
1938                                         dc.col[i] = dc.xft_col[i].pixel;
1939                                 i++;
1940                         }
1941
1942         for(r = 0; r < 24; r++, i++) {
1943                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
1944                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
1945                         dc.col[i] = white;
1946                         fprintf(stderr, "Could not allocate color %d\n", i);
1947                 } else
1948                         dc.col[i] = dc.xft_col[i].pixel;
1949         }
1950 }
1951
1952 void
1953 xclear(int x1, int y1, int x2, int y2) {
1954         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1955         XFillRectangle(xw.dpy, xw.buf, dc.gc,
1956                        BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
1957                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1958 }
1959
1960 void
1961 xhints(void) {
1962         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1963         XWMHints wm = {.flags = InputHint, .input = 1};
1964         XSizeHints *sizeh = NULL;
1965
1966         sizeh = XAllocSizeHints();
1967         if(xw.isfixed == False) {
1968                 sizeh->flags = PSize | PResizeInc | PBaseSize;
1969                 sizeh->height = xw.h;
1970                 sizeh->width = xw.w;
1971                 sizeh->height_inc = xw.ch;
1972                 sizeh->width_inc = xw.cw;
1973                 sizeh->base_height = 2*BORDER;
1974                 sizeh->base_width = 2*BORDER;
1975         } else {
1976                 sizeh->flags = PMaxSize | PMinSize;
1977                 sizeh->min_width = sizeh->max_width = xw.fw;
1978                 sizeh->min_height = sizeh->max_height = xw.fh;
1979         }
1980
1981         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
1982         XFree(sizeh);
1983 }
1984
1985 void
1986 xinitfont(Font *f, char *fontstr) {
1987         f->xft_set = XftFontOpenName(xw.dpy, xw.scr, fontstr);
1988
1989         if(!f->xft_set)
1990                 die("st: can't open font %s.\n", fontstr);
1991
1992         f->ascent = f->xft_set->ascent;
1993         f->descent = f->xft_set->descent;
1994         f->lbearing = 0;
1995         f->rbearing = f->xft_set->max_advance_width;
1996 }
1997
1998 void
1999 initfonts(char *fontstr, char *bfontstr, char *ifontstr, char *ibfontstr) {
2000         xinitfont(&dc.font, fontstr);
2001         xinitfont(&dc.bfont, bfontstr);
2002         xinitfont(&dc.ifont, ifontstr);
2003         xinitfont(&dc.ibfont, ibfontstr);
2004 }
2005
2006 void
2007 xinit(void) {
2008         XSetWindowAttributes attrs;
2009         Cursor cursor;
2010         Window parent;
2011         int sw, sh, major, minor;
2012
2013         if(!(xw.dpy = XOpenDisplay(NULL)))
2014                 die("Can't open display\n");
2015         xw.scr = XDefaultScreen(xw.dpy);
2016         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2017
2018         /* font */
2019         initfonts(FONT, BOLDFONT, ITALICFONT, ITALICBOLDFONT);
2020
2021         /* XXX: Assuming same size for bold font */
2022         xw.cw = dc.font.rbearing - dc.font.lbearing;
2023         xw.ch = dc.font.ascent + dc.font.descent;
2024
2025         /* colors */
2026         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2027         xloadcols();
2028
2029         /* adjust fixed window geometry */
2030         if(xw.isfixed) {
2031                 sw = DisplayWidth(xw.dpy, xw.scr);
2032                 sh = DisplayHeight(xw.dpy, xw.scr);
2033                 if(xw.fx < 0)
2034                         xw.fx = sw + xw.fx - xw.fw - 1;
2035                 if(xw.fy < 0)
2036                         xw.fy = sh + xw.fy - xw.fh - 1;
2037
2038                 xw.h = xw.fh;
2039                 xw.w = xw.fw;
2040         } else {
2041                 /* window - default size */
2042                 xw.h = 2*BORDER + term.row * xw.ch;
2043                 xw.w = 2*BORDER + term.col * xw.cw;
2044                 xw.fx = 0;
2045                 xw.fy = 0;
2046         }
2047
2048         attrs.background_pixel = dc.col[DefaultBG];
2049         attrs.border_pixel = dc.col[DefaultBG];
2050         attrs.bit_gravity = NorthWestGravity;
2051         attrs.event_mask = FocusChangeMask | KeyPressMask
2052                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2053                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2054         attrs.colormap = xw.cmap;
2055
2056         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2057         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2058                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2059                         xw.vis,
2060                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2061                         | CWColormap,
2062                         &attrs);
2063
2064         /* double buffering */
2065         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2066                 die("Xdbe extension is not present\n");
2067         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2068
2069         /* Xft rendering context */
2070         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2071
2072         /* input methods */
2073         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2074         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2075                                            | XIMStatusNothing, XNClientWindow, xw.win,
2076                                            XNFocusWindow, xw.win, NULL);
2077         /* gc */
2078         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2079
2080         /* white cursor, black outline */
2081         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2082         XDefineCursor(xw.dpy, xw.win, cursor);
2083         XRecolorCursor(xw.dpy, cursor,
2084                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2085                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2086
2087         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2088
2089         xresettitle();
2090         XMapWindow(xw.dpy, xw.win);
2091         xhints();
2092         XSync(xw.dpy, 0);
2093 }
2094
2095 void
2096 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2097         int fg = base.fg, bg = base.bg, temp;
2098         int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2099         Font *font = &dc.font;
2100         XGlyphInfo extents;
2101
2102         /* only switch default fg/bg if term is in RV mode */
2103         if(IS_SET(MODE_REVERSE)) {
2104                 if(fg == DefaultFG)
2105                         fg = DefaultBG;
2106                 if(bg == DefaultBG)
2107                         bg = DefaultFG;
2108         }
2109
2110         if(base.mode & ATTR_REVERSE)
2111                 temp = fg, fg = bg, bg = temp;
2112
2113         if(base.mode & ATTR_BOLD) {
2114                 fg += 8;
2115                 font = &dc.bfont;
2116         }
2117
2118         if(base.mode & ATTR_ITALIC)
2119                 font = &dc.ifont;
2120         if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2121                 font = &dc.ibfont;
2122
2123         XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
2124         XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
2125
2126         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen, &extents);
2127         width = extents.xOff;
2128         XftDrawRect(xw.xft_draw, &dc.xft_col[bg], winx, winy - font->ascent, width, xw.ch);
2129         XftDrawStringUtf8(xw.xft_draw, &dc.xft_col[fg], font->xft_set, winx, winy, (FcChar8 *)s, bytelen);
2130
2131         if(base.mode & ATTR_UNDERLINE)
2132                 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
2133 }
2134
2135 void
2136 xdrawcursor(void) {
2137         static int oldx = 0;
2138         static int oldy = 0;
2139         int sl;
2140         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2141
2142         LIMIT(oldx, 0, term.col-1);
2143         LIMIT(oldy, 0, term.row-1);
2144
2145         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2146                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2147
2148         /* remove the old cursor */
2149         if(term.line[oldy][oldx].state & GLYPH_SET) {
2150                 sl = utf8size(term.line[oldy][oldx].c);
2151                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2152         } else
2153                 xclear(oldx, oldy, oldx, oldy);
2154
2155         /* draw the new one */
2156         if(!(term.c.state & CURSOR_HIDE)) {
2157                 if(!(xw.state & WIN_FOCUSED))
2158                         g.bg = DefaultUCS;
2159
2160                 if(IS_SET(MODE_REVERSE))
2161                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2162
2163                 sl = utf8size(g.c);
2164                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2165                 oldx = term.c.x, oldy = term.c.y;
2166         }
2167 }
2168
2169 void
2170 xresettitle(void) {
2171         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2172 }
2173
2174 void
2175 redraw(void) {
2176         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2177
2178         xclear(0, 0, xw.w, xw.h);
2179         tfulldirt();
2180         draw();
2181         XSync(xw.dpy, False); /* necessary for a good tput flash */
2182         nanosleep(&tv, NULL);
2183 }
2184
2185 void
2186 draw() {
2187         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2188
2189         drawregion(0, 0, term.col, term.row);
2190         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2191 }
2192
2193 void
2194 drawregion(int x1, int y1, int x2, int y2) {
2195         int ic, ib, x, y, ox, sl;
2196         Glyph base, new;
2197         char buf[DRAW_BUF_SIZ];
2198         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2199
2200         if((sel.alt && !alt) || (!sel.alt && alt))
2201                 ena_sel = 0;
2202         if(!(xw.state & WIN_VISIBLE))
2203                 return;
2204
2205         for(y = y1; y < y2; y++) {
2206                 if(!term.dirty[y])
2207                         continue;
2208                 xclear(0, y, term.col, y);
2209                 term.dirty[y] = 0;
2210                 base = term.line[y][0];
2211                 ic = ib = ox = 0;
2212                 for(x = x1; x < x2; x++) {
2213                         new = term.line[y][x];
2214                         if(ena_sel && *(new.c) && selected(x, y))
2215                                 new.mode ^= ATTR_REVERSE;
2216                         if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2217                                                   ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2218                                 xdraws(buf, base, ox, y, ic, ib);
2219                                 ic = ib = 0;
2220                         }
2221                         if(new.state & GLYPH_SET) {
2222                                 if(ib == 0) {
2223                                         ox = x;
2224                                         base = new;
2225                                 }
2226                                 sl = utf8size(new.c);
2227                                 memcpy(buf+ib, new.c, sl);
2228                                 ib += sl;
2229                                 ++ic;
2230                         }
2231                 }
2232                 if(ib > 0)
2233                         xdraws(buf, base, ox, y, ic, ib);
2234         }
2235         xdrawcursor();
2236 }
2237
2238 void
2239 expose(XEvent *ev) {
2240         XExposeEvent *e = &ev->xexpose;
2241         if(xw.state & WIN_REDRAW) {
2242                 if(!e->count)
2243                         xw.state &= ~WIN_REDRAW;
2244         }
2245 }
2246
2247 void
2248 visibility(XEvent *ev) {
2249         XVisibilityEvent *e = &ev->xvisibility;
2250         if(e->state == VisibilityFullyObscured)
2251                 xw.state &= ~WIN_VISIBLE;
2252         else if(!(xw.state & WIN_VISIBLE))
2253                 /* need a full redraw for next Expose, not just a buf copy */
2254                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2255 }
2256
2257 void
2258 unmap(XEvent *ev) {
2259         xw.state &= ~WIN_VISIBLE;
2260 }
2261
2262 void
2263 xseturgency(int add) {
2264         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2265         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2266         XSetWMHints(xw.dpy, xw.win, h);
2267         XFree(h);
2268 }
2269
2270 void
2271 focus(XEvent *ev) {
2272         if(ev->type == FocusIn) {
2273                 xw.state |= WIN_FOCUSED;
2274                 xseturgency(0);
2275         } else
2276                 xw.state &= ~WIN_FOCUSED;
2277 }
2278
2279 char*
2280 kmap(KeySym k, uint state) {
2281         int i;
2282         state &= ~Mod2Mask;
2283         for(i = 0; i < LEN(key); i++) {
2284                 uint mask = key[i].mask;
2285                 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2286                         return (char*)key[i].s;
2287         }
2288         return NULL;
2289 }
2290
2291 void
2292 kpress(XEvent *ev) {
2293         XKeyEvent *e = &ev->xkey;
2294         KeySym ksym;
2295         char buf[32];
2296         char *customkey;
2297         int len;
2298         int meta;
2299         int shift;
2300         Status status;
2301
2302         if (IS_SET(MODE_KBDLOCK))
2303                 return;
2304         meta = e->state & Mod1Mask;
2305         shift = e->state & ShiftMask;
2306         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2307
2308         /* 1. custom keys from config.h */
2309         if((customkey = kmap(ksym, e->state)))
2310                 ttywrite(customkey, strlen(customkey));
2311         /* 2. hardcoded (overrides X lookup) */
2312         else
2313                 switch(ksym) {
2314                 case XK_Up:
2315                 case XK_Down:
2316                 case XK_Left:
2317                 case XK_Right:
2318                         /* XXX: shift up/down doesn't work */
2319                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2320                         ttywrite(buf, 3);
2321                         break;
2322                 case XK_Insert:
2323                         if(shift)
2324                                 selpaste();
2325                         break;
2326                 case XK_Return:
2327                         if(IS_SET(MODE_CRLF))
2328                                 ttywrite("\r\n", 2);
2329                         else
2330                                 ttywrite("\r", 1);
2331                         break;
2332                         /* 3. X lookup  */
2333                 default:
2334                         if(len > 0) {
2335                                 if(meta && len == 1)
2336                                         ttywrite("\033", 1);
2337                                 ttywrite(buf, len);
2338                         }
2339                         break;
2340                 }
2341 }
2342
2343 void
2344 cmessage(XEvent *e) {
2345         /* See xembed specs
2346            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2347         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2348                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2349                         xw.state |= WIN_FOCUSED;
2350                         xseturgency(0);
2351                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2352                         xw.state &= ~WIN_FOCUSED;
2353                 }
2354         }
2355 }
2356
2357 void
2358 resize(XEvent *e) {
2359         int col, row;
2360
2361         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2362                 return;
2363
2364         xw.w = e->xconfigure.width;
2365         xw.h = e->xconfigure.height;
2366         col = (xw.w - 2*BORDER) / xw.cw;
2367         row = (xw.h - 2*BORDER) / xw.ch;
2368         if(col == term.col && row == term.row)
2369                 return;
2370
2371         xclear(0, 0, xw.w, xw.h);
2372         tresize(col, row);
2373         xresize(col, row);
2374         ttyresize();
2375 }
2376
2377 void
2378 run(void) {
2379         XEvent ev;
2380         fd_set rfd;
2381         int xfd = XConnectionNumber(xw.dpy), i;
2382         struct timeval drawtimeout, *tv = NULL;
2383
2384         for(i = 0;; i++) {
2385                 FD_ZERO(&rfd);
2386                 FD_SET(cmdfd, &rfd);
2387                 FD_SET(xfd, &rfd);
2388                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2389                         if(errno == EINTR)
2390                                 continue;
2391                         die("select failed: %s\n", SERRNO);
2392                 }
2393
2394                 /*
2395                  * Stop after a certain number of reads so the user does not
2396                  * feel like the system is stuttering.
2397                  */
2398                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2399                         ttyread();
2400
2401                         /*
2402                          * Just wait a bit so it isn't disturbing the
2403                          * user and the system is able to write something.
2404                          */
2405                         drawtimeout.tv_sec = 0;
2406                         drawtimeout.tv_usec = 5;
2407                         tv = &drawtimeout;
2408                         continue;
2409                 }
2410                 i = 0;
2411                 tv = NULL;
2412
2413                 while(XPending(xw.dpy)) {
2414                         XNextEvent(xw.dpy, &ev);
2415                         if(XFilterEvent(&ev, xw.win))
2416                                 continue;
2417                         if(handler[ev.type])
2418                                 (handler[ev.type])(&ev);
2419                 }
2420
2421                 draw();
2422                 XFlush(xw.dpy);
2423         }
2424 }
2425
2426 int
2427 main(int argc, char *argv[]) {
2428         int i, bitm, xr, yr;
2429         uint wr, hr;
2430
2431         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2432         xw.isfixed = False;
2433
2434         for(i = 1; i < argc; i++) {
2435                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2436                 case 't':
2437                         if(++i < argc) opt_title = argv[i];
2438                         break;
2439                 case 'c':
2440                         if(++i < argc) opt_class = argv[i];
2441                         break;
2442                 case 'w':
2443                         if(++i < argc) opt_embed = argv[i];
2444                         break;
2445                 case 'f':
2446                         if(++i < argc) opt_io = argv[i];
2447                         break;
2448                 case 'e':
2449                         /* eat every remaining arguments */
2450                         if(++i < argc) opt_cmd = &argv[i];
2451                         goto run;
2452                 case 'g':
2453                         if(++i >= argc)
2454                                 break;
2455
2456                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2457                         if(bitm & XValue)
2458                                 xw.fx = xr;
2459                         if(bitm & YValue)
2460                                 xw.fy = yr;
2461                         if(bitm & WidthValue)
2462                                 xw.fw = (int)wr;
2463                         if(bitm & HeightValue)
2464                                 xw.fh = (int)hr;
2465                         if(bitm & XNegative && xw.fx == 0)
2466                                 xw.fx = -1;
2467                         if(bitm & XNegative && xw.fy == 0)
2468                                 xw.fy = -1;
2469
2470                         if(xw.fh != 0 && xw.fw != 0)
2471                                 xw.isfixed = True;
2472                         break;
2473                 case 'v':
2474                 default:
2475                         die(USAGE);
2476                 }
2477         }
2478
2479  run:
2480         setlocale(LC_CTYPE, "");
2481         tnew(80, 24);
2482         ttynew();
2483         xinit();
2484         selinit();
2485         run();
2486         return 0;
2487 }
2488