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