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