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