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