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