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