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