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